您的位置:首页 > 其它

2016最小生成树Kruskal算法1001

2017-07-21 22:17 260 查看


Constructing Roads


Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)


Total Submission(s) : 84   Accepted Submission(s) : 34


Font: Times New Roman | Verdana | Georgia


Font Size: ← →


Problem 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

思路:把那张图的每个点当做从i到j存到结构体中,然后排序一下,在找出不在集合中的最短边加起来就可以了。

代码:#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
int map[105][105];
int p[105];
struct node
{
int a,b,p;
}a[100005];
bool cmp(node a,node b)
{
return a.p<b.p;
}
int find(int x)
{
if(p[x]==x)return p[x];
else return (p[x]=find(p[x]));
}
int kruskal(int n)
{
int sum=0;
for(int i=0;i<n;i++)
{
int fx=find(a[i].a);
int fy=find(a[i].b);
if(fx!=fy)
{
p[fy]=fx;
sum+=a[i].p;
}
}
return sum;
}
int main()
{
int m;
while(scanf("%d",&m)!=EOF&&m)
{
int i,j;
for(i=0;i<=m;i++)
{
p[i]=i;
}
int k;
int z=0;
for(i=1;i<=m;i++)
{
for(j=1;j<=m;j++)
{
cin>>k;
if(i>=j)continue;
a[z].a=i;
a[z].b=j;
a[z].p=k;
z++;
}
}
int t;
cin>>t;
for(i=0;i<t;i++)
{
int x,y;
scanf("%d %d",&x,&y);
int fx=find(x);
int fy=find(y);
if(fy!=fx)
p[fy]=fx;
}
sort(a,a+z,cmp);
int e=kruskal(z);
cout<<e<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: