HDU 1102-Constructing Roads

D - Constructing Roads
Time Limit:2000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u
Submit Status

Description

There are N villages, which are numbered from 1 to N, and you should build some roads such that every two villages can connect to each other. We say two village A and B are connected, if and only if there is a road between A and B, or there exists a village C such that there is a road between A and C, and C and B are connected.

We know that there are already some roads between some villages and your job is the build some roads such that all the villages are connect and the length of all the roads built is minimum.

Input

The first line is an integer N (3 <= N <= 100), which is the number of villages. Then come N lines, the i-th of which contains N integers, and the j-th of these N integers is the distance (the distance should be an integer within [1, 1000]) between village i and village j.

Then there is an integer Q (0 <= Q <= N * (N + 1) / 2). Then come Q lines, each line contains two integers a and b (1 <= a < b <= N), which means the road between village a and village b has been built.

Output

You should output a line contains an integer, which is the length of all the roads to be built such that all the villages are connected, and this value is minimum.

Sample Input

3
0 990 692
990 0 179
692 179 0
1
1 2

Sample Output

179
当路已经修建了的时候,把他们之间的权值置为最小值0,就不会影响结果了;
 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <algorithm>
 4 using namespace std;
 5 const int N=110;
 6 const int inf=1<<29;
 7 int w[N][N],n,flag[N],dis[N];
 8 int  prim()
 9 {
10     int sum=0;
11     memset(flag,0,sizeof(flag));
12     for(int i=1; i<=n; i++)
13     {
14         dis[i]=w[1][i];
15     }
16     flag[1]=1;
17     for(int i=1; i<n; i++)
18     {
19         int to=-1,min1=inf;
20         for(int j=1; j<=n; j++)
21         {
22             if(!flag[j]&&dis[j]<min1)
23             {
24                 to=j;
25                 min1=dis[j];
26             }
27         }
28         if(to==-1) return -1;
29         sum+=min1;
30         flag[to]=1;
31         for(int i=1; i<=n; i++)
32         {
33             dis[i]=min(dis[i],w[to][i]);
34         }
35     }
36     return sum;
37 }
38 int main()
39 {
40 
41     while(scanf("%d",&n)!=EOF&&n)
42     {
43         for(int i=1; i<=n; i++)
44         {
45             for(int j=1; j<=n; j++)
46             {
47                 scanf("%d",&w[i][j]);
48             }
49         }
50         int m,u,v;
51         scanf("%d",&m);
52         for(int i=1; i<=m; i++)
53         {
54             scanf("%d%d",&u,&v);
55             w[u][v]=0;
56             w[v][u]=0;
57         }
58         printf("%d\n",prim());
59     }
60     return 0;
61 }

 

posted on 2015-08-29 15:47  甜蜜蜜吖甜蜜蜜  阅读(119)  评论(0编辑  收藏  举报

导航