题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1874
练习,FLOYD和DIJKSTRA解法。有重边
1 #pragma warning(disable:4996) 2 3 4 #include <algorithm> 5 #include <iostream> 6 #include <iomanip> 7 #include <cstring> 8 #include <climits> 9 #include <complex> 10 #include <fstream> 11 #include <cassert> 12 #include <cstdio> 13 #include <bitset> 14 #include <vector> 15 #include <deque> 16 #include <queue> 17 #include <stack> 18 #include <ctime> 19 #include <set> 20 #include <map> 21 #include <cmath> 22 23 using namespace std; 24 25 const int maxn = 2010; 26 const int inf = 0xffffff; 27 int d[maxn]; 28 int G[maxn][maxn]; 29 int vis[maxn]; 30 int n, m; 31 32 void init() { 33 memset(vis, 0, sizeof(vis)); 34 for(int i = 0; i <= n; i++) { 35 d[i] = inf; 36 for(int j = 0; j <= n; j++) { 37 G[i][j] = G[j][i] = inf; 38 } 39 G[i][i] = 0; 40 } 41 } 42 43 void dijkstra(int start) { 44 d[start] = 0; 45 for(int i = 0; i < n; i++) { 46 int u = -1; 47 for(int j = 0; j < n; j++) { 48 if(!vis[j]) { 49 if(u == -1 || d[j] < d[u]) { 50 u = j; 51 } 52 } 53 } 54 vis[u] = 1; 55 for(int j = 0; j < n; j++) { 56 if(!vis[j]) { 57 d[j] = min(d[u]+G[u][j], d[j]); 58 } 59 } 60 } 61 } 62 63 void floyd() { 64 for(int k = 0; k < n; k++) { 65 for(int i = 0; i < n; i++) { 66 for(int j = 0; j < n; j++) { 67 G[i][j] = min(G[i][j], G[i][k]+G[k][j]); 68 } 69 } 70 } 71 } 72 73 int main() { 74 // freopen("in", "r", stdin); 75 int u, v, w; 76 while(~scanf("%d %d", &n, &m)) { 77 init(); 78 while(m--) { 79 scanf("%d %d %d", &u, &v, &w); 80 if(G[u][v] > w) { 81 G[u][v] = G[v][u] = w; 82 } 83 } 84 int S, E; 85 scanf("%d %d", &S, &E); 86 87 /* dijkstra 88 dijkstra(S); 89 printf("%d ", d[E] == inf ? -1 : d[E]); 90 //*/ 91 92 //* floyd 93 floyd(); 94 printf("%d ", G[S][E] == inf ? -1 : G[S][E]); 95 //*/ 96 } 97 }