ZJU 1221 Risk (Floyd算法模板题)

题目链接http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=221

本来找这个题是要练习dijkstra的。。结果发现这个题权值都是1,可以用BFS很方便,这时又想到了Floyd 用来求每对顶点之间的距离,第一次实现了Floyd算法~!该算法代码结构简单,还没理解就先用了。下面是AC代码~  (p.s:这是我在zoj上提交的第一个代码~~)

 1 #include<stdio.h>
 2 #define INF 1000
 3 int map[110][110];
 4 int main()
 5 {
 6     int n,i,j,k,x,from,to,count=1;
 7     while(scanf("%d",&n)!=EOF)
 8     {
 9         for(i=1;i<=20;i++)   //初始化
10             for(j=1;j<=20;j++)
11                 map[i][j]=INF;
12         for(i=1;i<=n;i++)
13         {
14             scanf("%d",&x);
15             map[1][x]=1;
16             map[x][1]=1;
17         }
18         for(i=2;i<=19;i++)
19         {
20             scanf("%d",&n);
21             for(j=1;j<=n;j++)
22             {
23                 scanf("%d",&x);
24                 map[i][x]=1;
25                 map[x][i]=1;
26             }
27         }
28         for(k=1;k<=20;k++)    //floyd核心代码
29             for(i=1;i<=20;i++)
30                 for(j=1;j<=20;j++)
31                     if(map[i][j]>map[i][k]+map[k][j])
32                         map[i][j]=map[i][k]+map[k][j];
33         scanf("%d",&n);
34         printf("Test Set #%d\n",count++);
35         while(n--)
36         {
37             scanf("%d%d",&from,&to);
38             printf("%d to %d: %d\n",from,to,map[from][to]);
39         }
40         printf("\n");
41     }
42     return 0;
43 }

 

posted @ 2013-09-11 11:54  hjf007  阅读(435)  评论(0编辑  收藏  举报