CSU1004: Xi and Bo (并查集)

1004: Xi and Bo

     Time Limit: 1 Sec     Memory Limit:128 Mb     Submitted:861     Solved:316    

Description

Bo has been in Changsha for four years. However he spends most of his time staying his small dormitory. One day he decides to get out of the dormitory and see the beautiful city. So he asks to Xi to know whether he can get to another bus station from a bus station. Xi is not a good man because he doesn't tell Bo directly. He tells to Bo about some buses' routes. Now Bo turns to you and he hopes you to tell him whether he can get to another bus station from a bus station directly according to the Xi's information.

Input

The first line of the input contains a single integer T (0<T<30) which is the number of test cases. For each test case, the first contains two different numbers representing the starting station and the ending station that Bo asks. The second line is the number n (0<n<=50) of buses' routes which Xi tells. For each of the following n lines, the first numberm (2<=m<= 100) which stands for the number of bus station in the bus' route. The remainingm numbers represents the m bus station. All of the bus stations are represented by a number, which is between 0 and 100.So you can think that there are only 100 bus stations in Changsha.

Output

For each test case, output the "Yes" if Bo can get to the ending station from the starting station by taking some of buses which Xi tells. Otherwise output "No". One line per each case. Quotes should not be included.

Sample Input

3
0 3
3
3 1 2 3
3 4 5 6
3 1 5 6
0 4
2
3 0 2 3
2 2 4
3 2
1
4 2 1 0 3

Sample Output

No
Yes
Yes


解题思路:题目大意就是Bo想去外面玩,要坐公交车,然后告诉你一些公交车路线,然后要你判断他能不能到达目的地。。。这就是一个并查集模板

代码如下:

#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
int f[101];
int find(int x)
{
    return f[x] == x ? x : f[x]=find(f[x]);
}
void merge(int x,int y)
{
    int a=find(x);
    int b=find(y);
    if(a!=b) f[a]=b;
}
int main()
{
    int T,x,y,t,n,m,a;
    scanf("%d",&T);
    while(T--)
    {
        for(int i=0; i<101; i++)///初始化
            f[i]=i;
        scanf("%d %d",&x,&y);
        scanf("%d",&t);
        while(t--)
        {
            scanf("%d",&n);
            for(int i=0;i<n;i++)
            {
                scanf("%d",&m);
                merge(n,m);
            }
        }
        if(find(x)==find(y)) printf("Yes\n");
        else printf("No\n");
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值