Friendship
http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2833
Time Limit:3000MS MemoryLimit:32768KB 64bit IO Format:%lld& %llu
Description
A friend is like a flower, |
Nowyou've grown up, it's time to make friends. The friends you make in universityare the friends you make for life. You will be proud if you have many friends.
Input
Thereare multiple test cases for this problem.
Eachtest case starts with a line containing two integers N, M (1 <= N <=100'000, 1 <= M <= 200'000), representing that there are totally Npersons (indexed from 1 to N) and M operations, then M lines with the form"M a b" (without quotation) or "Q a" (without quotation)follow. The operation "M a b" means that person a and b make friendswith each other, though they may be already friends, while "Q a"means a query operation.
Friendshipis transitivity, which means if a and b, b and c are friends then a and c arealso friends. In the initial, you have no friends except yourself, when you arefreshman, you know nobody, right? So in such case you have only one friend.
Output
For eachtest case, output "Case #:" first where "#" is the numberof the case which starts from 1, then for each query operation "Q a",output a single line with the number of person a's friends.
Separatetwo consecutive test cases with a blank line, but Do NOT outputan extra blank line after the last one.
SampleInput
3 5
M 1 2
Q 1
Q 3
M 2 3
Q 2
5 10
M 3 2
Q 4
M 1 2
Q 4
M 3 2
Q 1
M 3 1
Q 5
M 4 2
Q 4
Sample Output
Case 1:
2
1
3
Case 2:
1
1
3
1
4
Notes
Thisproblem has huge input and output data, please use 'scanf()' and 'printf()'instead of 'cin' and 'cout' to avoid time limit exceed.
#include<stdio.h>
#include<string.h>
int n,pre[100004],num[100004];
char s[4];
int find(int a)
{
while(pre[a]!=a)
a=pre[a];//追根寻祖
return a;
}
void uni(int a,int b)
{
int x=find(a),y=find(b);
if(x==y) return;
if(num[x]<num[y])
{//我是想把小树接在大树下,可是师父说没必要- -!
int r=x;
x=y;
y=r;
}
pre[y]=x;
num[x]+=num[y];
}
int main()
{
int m,i,t,cas=1,a,b;
while(scanf("%d%d",&n,&m)!=EOF)
{
if(cas!=1) printf("\n");
printf("Case %d:\n",cas++);
for(i=1; i<=n; i++)
{
pre[i]=i;
num[i]=1;
}
for(t=0; t<m; t++)
{
scanf("%s",s);
if(s[0]=='M')
{
scanf("%d%d",&a,&b);
uni(a,b);
}
if(s[0]=='Q')
{
scanf("%d",&a);
int x=find(a);
printf("%d\n",num[x]);
}
}
}
return 0;
}