代码改变世界

找亲戚

2012-03-16 17:15  debugger87  阅读(188)  评论(0编辑  收藏  举报

找亲戚

TimeLimit: 1 Second   MemoryLimit: 32 Megabyte

Totalsubmit: 85   Accepted: 9  

Description

有n(编号从1到n)个人,给你m个操作:
1 C x y。表示x和y是亲戚。
2 Q x y。问x和y是不是亲戚。
x和y是亲戚,y和z是亲戚,那么x和z也是亲戚。

Input

输入有多组。每一组第一行输入n和m(1<=n,m<=10000)。接下来是m个操作。

Output

对每组输入,先输出一行”Case T:”,T初始为1。对于每个Q x y,如果x和y是亲戚输出”yes”,否则输出”no”。

Sample Input

5 6
Q 1 2
C 1 2
Q 1 2
C 2 5
Q 1 5
Q 2 4

Sample Output

Case 1:
no
yes
yes
no

Source

[p][/p]
 
#include<iostream>
#define MAX 10001
int father[MAX];
int rank[MAX];
using namespace std;

void init(int n)
{
for(int i=1;i<=n;i++)
{
rank[i]=0;
father[i]=i;
}
}

int get_father(int v)
{
if(father[v]!=v)
father[v]=get_father(father[v]);
return father[v];
}

int is_same(int x, int y)
{
if(get_father(x)==get_father(y))
{
return 1;
}
return 0;
}

void set_union(int x, int y)
{
int fx,fy;
if((fx=get_father(x)) != (fy=get_father(y)))
{
if(rank[fx]>rank[fy])
father[fy]=fx;
else
{
father[fx]=fy;
if(rank[fx]==rank[fy])
rank[fy]++;
}
}
}

int main()
{
int n,m;
int T=1;
while(cin>>n>>m)
{
cout<<"Case "<<T<<":"<<endl;
init(n);
for(int i=0;i<m;i++)
{
char ch;
int a,b;
cin>>ch>>a>>b;
if(ch=='Q')
if(is_same(a,b))
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
else
set_union(a,b);
}
T++;
}
return 0;
}