首页 > 代码库 > 任意两点间最短距离floyd-warshall ---- POJ 2139 Six Degrees of Cowvin Bacon
任意两点间最短距离floyd-warshall ---- POJ 2139 Six Degrees of Cowvin Bacon
floyd-warshall算法 通过dp思想 求任意两点之间最短距离
重复利用数组实现方式dist[i][j] i - j的最短距离
for(int k = 1; k <= N; k++)
for (int i = 1; i <= N; i++)
for (int j = 1; j <= N; j++)
dist[i][j] = min(dist[i][j], dist[i][k]+dist[k][j]);
非常好实现 O(V^3)
这里贴一道刚好用到的题
http://poj.org/problem?id=2139
1 #include <iostream> 2 #include <stdio.h> 3 #include <string.h> 4 #include <algorithm> 5 #define INF 0x3f3f3f3f 6 #define MAXV 307 7 using namespace std; 8 9 //floyd-warshall 10 11 int dist[MAXV][MAXV]; 12 int main() 13 { 14 int N, M; 15 int cow[MAXV]; 16 double sum[MAXV]; 17 freopen("in.txt", "r", stdin); 18 scanf("%d%d", &N, &M); 19 for (int i = 1; i <= N; i++) 20 for (int j = 1; j <= N; j++) 21 if (i != j) dist[i][j] = INF; 22 else dist[i][j] = 0; 23 for (int i = 0; i < M; i++) 24 { 25 int mi = 0; 26 scanf("%d", &mi); 27 for (int j = 0; j < mi; j++) 28 { 29 scanf("%d", &cow[j]); 30 } 31 for (int j = 0; j < mi; j++) 32 { 33 for (int k = 0; k < mi; k++) 34 { 35 if (cow[j] == cow[k]) continue; 36 else dist[cow[j]][cow[k]] = dist[cow[k]][cow[j]] = 1; 37 } 38 } 39 } 40 for (int k = 1; k <= N; k++) 41 for (int i = 1; i <= N; i++) 42 for (int j = 1; j <= N; j++) dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]); 43 for (int i = 1; i <= N; i++) 44 { 45 sum[i] = 0; 46 for (int j = 1; j <= N; j++) 47 { 48 sum[i] += dist[i][j]; 49 } 50 } 51 sort(sum+1, sum+N+1); 52 //注意题目最后的要求 A single integer that is 100 times the shortest mean degree of separation of any of the cows. 53 //所以要变为int 54 cout << int(sum[1] / (N-1)*100) << endl; 55 }
任意两点间最短距离floyd-warshall ---- POJ 2139 Six Degrees of Cowvin Bacon
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。