任意两点间最短距离floyd-warshall ---- POJ 2139 Six Degrees of Cowvin Bacon

Posted Lorazepam

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了任意两点间最短距离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的主要内容,如果未能解决你的问题,请参考以下文章

图论03—随意两点间最短距离及路径(改进)

求图中任意两点之间最短路径有啥算法?

蒜头君的树

只有五行的算法--floyd-warshall

Floyd-Warshall求图中任意两点的最短路径

多源最短路径 – Floyd-Warshall Algorithm