您的位置:首页 > 其它

hdu 1102 Constructing Roads(Kruskal算法)

2015-08-11 16:38 375 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1102

Constructing Roads

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 17132 Accepted Submission(s): 6500



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


注意并查集的初始化 MakeSet, 注意Kruskal 算法与边有关,储存边的数组要开到 N^2;

【代码】

#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 110;
const int maxe =10010;
struct node{
	int V1,V2, len ;
}edge[maxe];
int father[maxn];
bool cmp(const node &a, const node& b){
	return a.len<b.len;
}
void MakeSet(){
	for(int i=0;i<maxn;i++)
		father[i]=i;
}
int Find(int x){
	
	int root = x;
	while(root!=father[root])
		root = father[root];
	while(x!=root){
		int tmp = father[x];
		father[x] = root;
		x = tmp;
	}
	return root;
}
void Union(int x,int y){
	int xr = Find(x);
	int yr = Find(y);
	if(xr==yr) return ;
	father[xr]=yr;
}
int cnt;	int n;
void Kruskal(){
	int edgenum=0;
	int ans=0;
	for(int i=0;i<cnt &&edgenum!=n-1;i++){
		if(Find(edge[i].V1)!=Find(edge[i].V2)){
			ans+=edge[i].len;
			Union(edge[i].V1,edge[i].V2);
		}
	}
	cout<<ans<<endl;
}
int main(){

	while(cin>>n){
		int dis;
		cnt=0;
		MakeSet();
		for(int i=0;i<n;i++){
			for(int j=0;j<n;j++){
				cin>>dis;
				if(j==i) continue;
				edge[cnt].V1 = i;
				edge[cnt].V2 = j;
				edge[cnt].len = dis;
				cnt++;
			}
		}
		sort(edge,edge+cnt,cmp);
		int t,v1,v2;
		cin>>t; 
		for(int i=0;i<t;i++){
			cin>>v1>>v2;
			Union(v1-1,v2-1);
		}
		Kruskal();
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: