HD1599 find the mincost route(floyd + 最小环)
题意:求最小环
第一反应时floyd判断,但是涉及到最少3个点,然后就不会了,又想的是 双联通分量,这个不知道为什么不对。
Floyd 判断 最小环
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <cstring> 5 using namespace std; 6 const int INF = 0x3f3f3f3f; 7 const int Max = 100 + 10; 8 int g[Max][Max], dist[Max][Max]; 9 //dist【i】【j】保存i到j的最短路经,然后i -> j -> k 就可以枚举k, dist[i][j] + g[i][k] + g[j][k]就是一个环的权值 10 int mincost; 11 void Floyed(int n) 12 { 13 mincost = INF; 14 for (int k = 1; k <= n; k++) 15 { 16 for (int i = 1; i < k; i++) 17 { 18 for (int j = i + 1; j < k; j++) 19 { 20 if (dist[i][j] != INF && g[i][k] != INF && g[k][j] != INF) 21 { 22 int temp = dist[i][j] + g[i][k] + g[k][j]; // 原先这里直接相加,一直没找到错误,爆精度 23 if (temp < mincost) 24 mincost = temp; 25 } 26 } 27 } 28 for (int i = 1; i <= n; i++) 29 { 30 for (int j = 1; j <= n; j++) 31 { 32 if (dist[i][k] != INF && dist[k][j] != INF) 33 dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]); 34 } 35 } 36 } 37 } 38 int main() 39 { 40 int n, m; 41 while (scanf("%d%d", &n, &m) != EOF) 42 { 43 for (int i = 1; i < Max; i++) 44 for (int j = 1; j < Max; j++) 45 { 46 g[i][j] = INF; 47 dist[i][j] = INF; 48 } 49 int a, b, c; 50 for (int i = 1; i <= m; i++) 51 { 52 scanf("%d%d%d", &a, &b, &c); 53 if (g[a][b] > c) 54 g[a][b] = g[b][a] = dist[a][b] = dist[b][a] = c; 55 } 56 Floyed(n); 57 if (mincost >= INF) 58 printf("It's impossible.\n"); 59 else 60 printf("%d\n", mincost); 61 62 } 63 return 0; 64 }