POJ 2387 Til the Cows Come Home
思路:Dijkstra, bellman-ford和spfa,但是用dijkstra要考虑重边
1 #include <iostream> 2 #include <cstring> 3 #include <algorithm> 4 #include <stack> 5 #include <cstdio> 6 #include <queue> 7 #define MAXVERTEXNUM 1010 8 #define INF 99999999 9 #define ERROR -1 10 using namespace std; 11 12 int MGraph[MAXVERTEXNUM][MAXVERTEXNUM]; 13 int dist[MAXVERTEXNUM]; 14 int Nv, Ne; 15 int collected[MAXVERTEXNUM]; 16 17 int FindMinDist() 18 { 19 int MinDist = INF; 20 int MinV; 21 for (int i = 1; i < Nv; ++i) 22 { 23 if (!collected[i] && dist[i] < MinDist) 24 { 25 MinDist = dist[i]; 26 MinV = i; 27 } 28 } 29 if (MinDist != INF) 30 return MinV; 31 return ERROR; 32 } 33 34 void Dijkstra() 35 { 36 memset(collected, 0, sizeof(collected)); 37 38 int start = Nv; 39 //init start 40 dist[start] = 0; 41 collected[start] = 1; 42 for (int i = 1; i < Nv; ++i)//start did not need to involve 43 { 44 dist[i] = MGraph[i][start]; 45 } 46 47 while (true) 48 { 49 int V = FindMinDist(); 50 if (V == ERROR) 51 break; 52 collected[V] = 1; 53 for (int i = 1; i < Nv; ++i) 54 { 55 if (!collected[i] && dist[V] + MGraph[V][i] < dist[i])//&& MGraph[V][i] != INF 56 dist[i] = dist[V] + MGraph[V][i]; 57 } 58 } 59 } 60 61 int main() 62 { 63 ios::sync_with_stdio(false); 64 cin >> Ne >> Nv; 65 66 //init 67 for (int i = 1; i <= Nv; ++i) 68 { 69 for (int j = 1; j <= Nv; ++j) 70 { 71 MGraph[i][j] = INF; 72 } 73 } 74 75 76 for (int i = 0; i < Ne; ++i) 77 { 78 int V1, V2, E; 79 cin >> V1 >> V2 >> E; 80 if (MGraph[V1][V2] > E) 81 { 82 MGraph[V1][V2] = E; 83 MGraph[V2][V1] = E; 84 } 85 } 86 87 Dijkstra(); 88 cout << dist[1] << endl; 89 90 return 0; 91 }
不忘初心,方得始终