找亲戚

找亲戚

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;
}

转载于:https://www.cnblogs.com/debugger87/archive/2012/03/16/2400637.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值