poj1611 并查集
2014-11-09 00:24
155 查看
如题:http://poj.org/problem?id=1611
基础的并查集
#include<iostream>
using namespace std;
#define N 30005
#define M 505
struct Set
{
int data;
int rank;
int father;
}set
;
int findSet(int x)
{
if(set[x].father==x)
return x;
else
return findSet(set[x].father);
}
void Union(int a,int b) //a所在的集合和b所在的集合合并
{
int fa,fb;
fa=findSet(a);
fb=findSet(b);
if(fa==fb)
return;
if(set[fa].rank>set[fb].rank) //将深度小的集合放在深度大的下面
{
set[fb].father=fa;
if(set[fb].rank+1>set[fa].rank)
set[fa].rank=set[fb].rank+1;
}
else
{
set[fa].father=fb;
if(set[fa].rank+1>set[fb].rank)
set[fb].rank=set[fa].rank+1;
}
}
int main()
{
int N1,M1;
int i,j;
while(cin>>N1>>M1)
{
if(N1==0) break;
for(i=0;i<N;i++)
{
set[i].data=0;
set[i].father=i;
set[i].rank=0;
}
int n;int t1;
for(j=1;j<=M1;j++)
{
//scanf("%d",&n);
//getchar();
cin>>n;
if(n>=1)
{
// scanf("%d",&t1);
// getchar();
cin>>t1;
}
for(i=1;i<n;i++)
{
int t2;
scanf("%d",&t2);
getchar();
Union(t1,t2);
}
}
int sum=1;
for(i=1;i<N;i++)
{
if(findSet(i)==findSet(0))
sum++;
}
cout<<sum<<endl;
}
return 0;
}
基础的并查集
#include<iostream>
using namespace std;
#define N 30005
#define M 505
struct Set
{
int data;
int rank;
int father;
}set
;
int findSet(int x)
{
if(set[x].father==x)
return x;
else
return findSet(set[x].father);
}
void Union(int a,int b) //a所在的集合和b所在的集合合并
{
int fa,fb;
fa=findSet(a);
fb=findSet(b);
if(fa==fb)
return;
if(set[fa].rank>set[fb].rank) //将深度小的集合放在深度大的下面
{
set[fb].father=fa;
if(set[fb].rank+1>set[fa].rank)
set[fa].rank=set[fb].rank+1;
}
else
{
set[fa].father=fb;
if(set[fa].rank+1>set[fb].rank)
set[fb].rank=set[fa].rank+1;
}
}
int main()
{
int N1,M1;
int i,j;
while(cin>>N1>>M1)
{
if(N1==0) break;
for(i=0;i<N;i++)
{
set[i].data=0;
set[i].father=i;
set[i].rank=0;
}
int n;int t1;
for(j=1;j<=M1;j++)
{
//scanf("%d",&n);
//getchar();
cin>>n;
if(n>=1)
{
// scanf("%d",&t1);
// getchar();
cin>>t1;
}
for(i=1;i<n;i++)
{
int t2;
scanf("%d",&t2);
getchar();
Union(t1,t2);
}
}
int sum=1;
for(i=1;i<N;i++)
{
if(findSet(i)==findSet(0))
sum++;
}
cout<<sum<<endl;
}
return 0;
}
相关文章推荐
- POJ 1611 The Suspects (并查集)
- 【并查集】POJ 1611 The Suspects
- poj1611 The Suspects(并查集应用)
- POJ 1611 The Suspects( 并查集)
- poj 1611(并查集)(B)
- POJ 1611非典传染[并查集]
- poj-1611 并查集
- POJ1611 The Suspects (并查集)
- POJ 1611 The Suspects (并查集)
- POJ 1611 The Suspects 并查集
- 文章标题 POJ 1611 : The Suspects (并查集)
- POJ 1611 The Suspects:并查集
- POJ-1611-The Suspects(并查集)
- poj 1611(并查集_裸题)
- 【原】 POJ 1611 The Suspects 并查集 解题报告
- POJ 1611 The Suspects(并查集)
- poj-1611 传染病 并查集
- POJ 1611 The Suspects(并查集)
- POJ-1611 纯并查集
- poj 1611 并查集 按数目合并