1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| struct Dijkstra { using pii=pair<int,int>; vector<vector<pii>> g; vector<int> dis; vector<bool> vis; int n;
Dijkstra(int n) : n(n),g(n + 2),dis(n + 2, INF),vis(n + 2, false) {} void addEdge(int u, int v, int w) { g[u].push_back({v, w}); } void run(int s) { priority_queue<pii,vector<pii>,greater<pii>> pq; dis[s] = 0; pq.push({0,s}); while(!pq.empty()){ int d=pq.top().first,u=pq.top().second; pq.pop(); if(vis[u]) continue; vis[u]=true; for(auto &node:g[u]){ int v=node.first,w=node.second; if(dis[u]+w<dis[v]){ dis[v]=dis[u]+w; pq.push({dis[v],v}); } } } } void printDistances() { for (int i = 1; i <= n; ++i) { cout << dis[i] << " "; } cout << endl; } };
|