ZOJ-2833*交友問題
2022 ワード
一群の人が互いに交友する.M 1 2代表1と2が友人Q 1代表クエリ1の友人数となる.
Sample Input
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
考え方:問題をまとめます.
Sample Input
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
考え方:問題をまとめます.
#include<iostream>
using namespace std;
#include<memory.h>
#include<stdio.h>
int disjoinset[100001];
int find(int * s,int x)
{
if(s[x] <= 0)
return x;
else
return s[x] = find(s,s[x]); //path compress
}
void unionbysize(int *s,int root1,int root2)
{
if(s[root1] <= s[root2]) //root1 is bigger
{
s[root1] = s[root1] + s[root2];
s[root2] = root1;
}
else
{
s[root2] = s[root1] + s[root2];
s[root1] = root2;
}
}
// ,
int main()
{
int N;
int M;
char type;
int mem1;
int mem2;
int root1;
int root2;
int i = 0;
bool isfirst = true;
while(scanf("%d%d",&N,&M) != EOF)
{
memset(disjoinset,-1,100001*sizeof(int));
if(!isfirst)
printf("
");
isfirst = false;
printf("Case %d:
",++i);
while(M--)
{
getchar();
scanf("%c",&type);
if(type == 'M')
{
scanf("%d%d",&mem1,&mem2);
root1 = find(disjoinset,mem1);
root2 = find(disjoinset,mem2);
if(root1 != root2)
unionbysize(disjoinset,root1,root2);
}
else if(type == 'Q')
{
scanf("%d",&mem1);
root1 = find(disjoinset,mem1);
printf("%d
",-disjoinset[root1]);
}
}
}
}