hdu 1232 畅通工程 最小生成树 并查集
1232的连接:http://acm.hdu.edu.cn/showproblem.php?pid=1232
#include <iostream>
#include <cstdio>
#define MAX 1005
using namespace std;
int father[MAX],rank[MAX];
int N,M;
void make_set(){
for(int i=1;i<=N;i++){
father[i]=i;
}
}
int find_set(int x){
if(x!=father[x]){
father[x]=find_set(father[x]);
}
return father[x];
}
void Union(int x,int y){
x=find_set(x);
y=find_set(y);
if(x==y) return;
father[y]=x;
}
int main()
{
int st,end;
int count;
freopen("acm.txt","r",stdin);
cin>>N>>M;
while(N){
count=0;
make_set();
for(int i=1;i<=M;i++){
cin>>st>>end;
Union(st,end);
}
for(int j=1;j<=N;j++){
if(father[j]!=j)
count++;
}
cout<<N-1-count<<endl; //每合并一次,就可以减少建一条路
cin>>N>>M;
}
return 0;
}
做了几题同类型的并查集的题目。感觉还不错哦~凡事要多练!
我是一名在校大学生,热爱编程,虽然起步晚了些,但我会努力的。呵呵!
数据结构 算法