【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;
}
相关推荐
NAGNIP5 小时前
万字长文!回归模型最全讲解!
算法·面试
知乎的哥廷根数学学派5 小时前
面向可信机械故障诊断的自适应置信度惩罚深度校准算法(Pytorch)
人工智能·pytorch·python·深度学习·算法·机器学习·矩阵
666HZ6666 小时前
数据结构2.0 线性表
c语言·数据结构·算法
实心儿儿7 小时前
Linux —— 基础开发工具5
linux·运维·算法
charlie1145141918 小时前
嵌入式的现代C++教程——constexpr与设计技巧
开发语言·c++·笔记·单片机·学习·算法·嵌入式
清木铎9 小时前
leetcode_day4_筑基期_《绝境求生》
算法
清木铎9 小时前
leetcode_day10_筑基期_《绝境求生》
算法
j_jiajia9 小时前
(一)人工智能算法之监督学习——KNN
人工智能·学习·算法
源代码•宸10 小时前
Golang语法进阶(协程池、反射)
开发语言·经验分享·后端·算法·golang·反射·协程池
Jasmine_llq11 小时前
《CF280C Game on Tree》
数据结构·算法·邻接表·深度优先搜索(dfs)·树的遍历 + 线性累加统计