图论 —— dijkstra
https://www.acwing.com/problem/content/852/
https://www.luogu.com.cn/problem/P3371
https://www.luogu.com.cn/problem/P4779
#include <cstring> #include <iostream> #include <algorithm> #include <queue> #include <cmath> using namespace std; typedef pair<int, int> PII; const int N = 1e7 + 10; int n, m; int h[N], w[N], e[N], ne[N], idx; int dist[N]; bool st[N]; void add(int a, int b, int c) { w[idx] = c, e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ; } void dijkstra(int u) { memset(dist, 0x3f, sizeof dist); dist[u] = 0; priority_queue<PII, vector<PII>, greater<PII>> heap; heap.push({0, u}); while (heap.size()) { auto t = heap.top(); heap.pop(); int ver = t.second, distance = t.first; if (st[ver]) continue; st[ver] = true; for (int i = h[ver]; i != -1; i = ne[i]) { int j = e[i]; if (dist[j] > dist[ver] + w[i]) { dist[j] = dist[ver] + w[i]; heap.push({dist[j], j}); } } } for(int i = 1; i <= n; i ++ ) { if (dist[i] == 0x3f3f3f3f) dist[i] = pow(2, 31) - 1; } } int main() { int u; scanf("%d%d%d", &n, &m, &u); memset(h, -1, sizeof h); while (m -- ) { int a, b, c; scanf("%d%d%d", &a, &b, &c); add(a, b, c); } dijkstra(u); for(int i = 1; i <= n; i ++ ) cout << dist[i] << ' '; return 0; }
知道图中任意两点间距离
要求所有点到一个确定的点的最短距离(可能到不了)
输出

浙公网安备 33010602011771号