1. #include <cstdio> #include <iostream> #include <algorithm> #include <queue> #include < stack> #include <climits> #include <cstring> #include <cmath> #include <map> #include <set > #define INF 100000000using namespace Std;int n,v,m;int d[1000];int vis[1000];int g[1000][1000]; int Dijkstra (int s) {fill (D,d+n,inf), memset (vis,0,sizeof (VIS));d [s] = 0;for (int i = 0;i < n-1;i++) {int TM = Inf;int Q Find the smallest for (int j = 0;j < n;j++) {if (!vis[j] && D[j] < TM) {TM = D[j];q = j;}} in the point where the shortest path has been found Representing this point has found the shortest path vis[q] = 1; for (int j = 0;j < n;j++) {if (G[q][j]) {d[j] = min (D[j],d[q] + g[q][j]);}}} for (int i = 0;i < n;i++) {printf ("%d\n", D[i]);}} int main () {while (CIN >> n >> m) {for (int i = 0;i < m;i++) {int x,y,w;cin >> x >> y >> w; G[x][y] = W; G[y][x] = w;} int s;cin >> S;dijkstra (s);} return 0;}
2.
#include <cstdio> #include <iostream> #include <algorithm> #include <queue> #include <stack > #include <climits> #include <cstring> #include <cmath> #include <map> #include <set># Define INF 100000000using namespace Std;int n,v,m;int d[1000];int vis[1000];int g[1000][1000];typedef pair<int,int > Pa;int Dijkstra (int s) {fill (d,d+n,inf); memset (vis,0,sizeof (VIS));p riority_queue< Pa,vector<pa> greater<pa> > Que;que.push (PA (0,s));d [s] = 0;for (int i = 0;i < n-1;i++) {int q = que.top (). Second;que.pop (); f or (int j = 0;j < n;j++) {if (G[q][j]) {d[j] = min (D[j],d[q] + g[q][j]); Que.push (PA (d[j],j));}}} for (int i = 0;i < n;i++) {printf ("%d\n", D[i]);}} int main () {while (CIN >> n >> m) {for (int i = 0;i < m;i++) {int x,y,w;cin >> x >> y >> w; G[x][y] = W; G[y][x] = w;} int s;cin >> S;dijkstra (s);} return 0;}
Dijkstra Single Source Shortest path