题解:P11966 [GESP202503 八级] 上学

· · 题解

板子题。

20 pts

代码略。 ## 40 pts 跑 Floyd 即可。 $\mathcal O(n^3)$ 完全可过。 代码略。 ## 100 pts 显然,从 $q$ 个点各跑一次最短路不可行。 因为到达的终点是一致的,又因为输入的是无向图,可以直接以终点为源点跑最短路。 ~~暗示很明显,终点输入的变量名就是 $s$。~~ 用 Dijkstra,可过。 十年 OI 一场空,不开【】见祖宗。 Talk is cheap,show me the CODE. ```cpp #include <iostream> #include <algorithm> #include <cmath> #include <vector> #include <queue> using namespace std; struct edge { long long v,w; }; const long long inf = 9e18; long long n,m,s; vector<edge> e[200005]; long long d[200005]; bool vis[200005]; void dijkstra(int s) { for(int i = 0;i <= n;i++) { d[i] = inf; } d[s] = 0; priority_queue<pair<long long,int>, vector<pair<long long,int>>, greater<pair<long long,int>>> q; q.push({0,s}); while(!q.empty()) { int u = q.top().second; q.pop(); if(vis[u]) continue; vis[u] = 1; for(auto eg : e[u]) { int v = eg.v; int w = eg.w; if(d[v] > d[u] + w) { d[v] = d[u] + w; q.push({d[v],v}); } } } } int main() { int q; cin >> n >> m >> s >> q; while(m--) { long long u,v,l; cin >> u >> v >> l; e[u].push_back(edge{v,l}); e[v].push_back(edge{u,l}); } dijkstra(s); while(q--) { int h; cin >> h; cout << d[h] << endl; } return 0; } ```