【Luogu】每日一题——Day20. P4366 [Code+#4] 最短路 (图论)

P4366 Code+#4 最短路 - 洛谷

题目:

思路:

其实是找性质

本题我们首先可以想到的就是建图然后跑最短路,但是数据给的很大,如果直接暴力建图显然不行,考虑一些特殊情况需要建图

考虑 1 -> 7 这个例子

我们一种走法是直接从 1->7,那么二进制下就是 001 -> 111,花费就是 6 * c

另一种走法就是考虑走中间节点,具体的从 001 -> 011 -> 111,花费一样也是 6 * c

可以看出,只要两个数有超过一位不同,那么就能通过中间节点走到终点

具体的,我们每个数都建一条和自己有一位不同的边,那么其连接的点就是 i ^ ,即只有一位不同,这个位可以是 32 位中的任意一位,所以价值就是 c * (i ^ (i ^ )) = c *

所以就从 n*n 变成了 n*logn 的建图了,顺利解决

代码:

cpp 复制代码
#include <iostream>
#include <algorithm>
#include<cstring>
#include <iomanip>
#include<cctype>
#include<string>
#include <set>
#include <vector>
#include <cmath>
#include <queue>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <stack>
#include <utility>
#include <array>
#include <tuple>
using namespace std;
#define int long long
#define yes cout << "YES" << endl
#define no cout << "NO" << endl

vector<vector<pair<int,int>>> g(100005);
int n, m, c;
int dis[100005];
int s, e;

void Init()
{
    for (int i = 0; i <= n; i++)
    {
        for (int j = 1; j <= n; j <<= 1)
        {
            if ((i ^ j) > n)
                continue;
            g[i].push_back({ i ^ j, j * c });
        }
    }
}

void fuc()
{
    dis[s] = 0;
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;
    pq.push({ 0,s });
    while (!pq.empty())
    {
        auto t = pq.top();
        pq.pop();
        if (t.second == e || dis[t.second] < t.first)
        {
            continue;
        }
        for (auto & son : g[t.second])
        {
            int v = son.first;
            int cost = son.second;
            if (dis[v] > t.first + cost)
            {
                dis[v] = t.first + cost;
                pq.push({ t.first + cost ,v });
            }
        }
    }
}

void solve()
{
    cin >> n >> m >> c;
    for (int i = 0; i < m; i++)
    {
        int u, v, c;
        cin >> u >> v >> c;
        g[u].push_back({ v, c });
    }
    cin >> s >> e;
    Init();
    memset(dis, 0x3f, sizeof dis);
    fuc();
    cout << dis[e] << endl;
}
signed main()
{
    //cin.tie(0)->sync_with_stdio(false);
    int t = 1;
    //cin >> t;
    while (t--)
    {
        solve();
    }
    return 0;
}
相关推荐
毕竟是shy哥2 小时前
计算YOLO数据集中每个类的目标数
算法·yolo·机器学习
M78佐菲2 小时前
Linux学习笔记:TCP协议
linux·笔记·学习·tcp/ip·算法
晊晌_h4 小时前
嵌入式从0到精通——数据结构总结[特殊字符]
数据结构·算法·排序算法
我找到地球的支点啦4 小时前
Matlab系列(009) 一CRC循环冗余校验详解
开发语言·数据结构·算法·matlab·信息与通信
罗西的思考4 小时前
【OpenClaw具身硬件】ZeroClaw 源码阅读笔记(3)--- RAG
人工智能·算法·机器学习
浪里镖客5 小时前
位姿转换矩阵写法-个人习惯(计算机理解其实是相反的)
线性代数·算法·矩阵
小白羊丨8 小时前
如何诊断 Prompt 模板导致的效果下降?
人工智能·算法·prompt
OPEN-F9 小时前
C++11/14新特性精讲:移动语义与智能指针实战
开发语言·c++·算法
lisin-lee-cooper10 小时前
【leetcode658】有序数组找出k个最接近x的数
java·数据结构·算法
sunburn-10 小时前
Java堆(Heap)详解与实战教学
java·开发语言·数据结构·ide·算法