Result | TIME Limit | MEMORY Limit | Run Times | AC Times | JUDGE |
---|---|---|---|---|---|
![]() | 3s | 16384K | 390 | 105 | Standard |
将N个人分成M组,测试数据包含多组输入,每组输入第一行为两个整数N,T(1<=N<=10000),(1<=T<=10000),后面有T行输入,每行两个整数a,b(1<=a,b<=N),表示编号为a的人和编号为b的人在同一组中,根据已知条件求组数M至多为多少。
Sample Input
5 3 1 2 2 3 4 5 6 4 1 2 2 1 3 4 4 3
Sample Output
2 4
Problem Source: xwbsw
This problem is used for contest: 120
#include<iostream>
int n,m;
int p[10001],rank[10001];
void init()
{
int i;
for(i=1;i<=n;i++)
{
p[i]=i;
rank[i]=0;
}
}
int getfather(int a)
{
if(a!=p[a]) p[a]=getfather(p[a]);
return p[a];
}
void Union( int a,int b)
{
int ta=getfather(a),tb=getfather(b);
if(ta==tb) return;
if(ta<=tb)
{
p[tb]=p[ta];
rank[ta]+=rank[tb];
}
else
{
p[ta]=p[tb];
rank[tb]+=rank[ta];
}
return;
}
int main()
{
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
int a,b;
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(p,0,sizeof(p));
memset(rank,0,sizeof(rank));
init();//初始化
for(int i=0;i<m;i++)
{
scanf("%d%d",&a,&b);
Union(a,b);
}
int count=0;
for(int i=1;i<=n;++i)
{
if(p[i]==i) //有几个开头就有几个组
{
count++;
}
}
printf("%d/n",count);
}
return 0;
}