码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-02-15 00:37:58      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:open   else   single   pac   war   integer   hal   pen   span   

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

标签:open   else   single   pac   war   integer   hal   pen   span   

原文地址:http://www.cnblogs.com/oscar-cnblogs/p/6399624.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!