COJ 1004: Xi and Bo(并查集)

来源:互联网 发布:java看书能学会吗 编辑:程序博客网 时间:2024/06/05 06:58

Xi and Bo

Time Limit: 1 Sec Memory Limit: 128 Mb Submitted: 1072 Solved: 423


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 number m (2<=m<= 100) which stands for the number of bus station in the bus’ route. The remaining m 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

30 333 1 2 33 4 5 63 1 5 60 423 0 2 32 2 43 214 2 1 0 3
### **Sample Output**
NoYesYes

Hint


Source

中南大学第五届大学生程序设计竞赛-热身赛
原题链接:COJ 1004

题目分析:给定一些公交路线,路线里包括任意个公交站,现在告诉你起点站和终点站,问两站能不能相连。
很明显可以用并查集做,检查起始站是否在同一集合中,即可判断能否到达。

AC 代码

#include<cstdio>#include<iostream>using namespace std;#define maxn 105int root[maxn];int main(){    int t;    cin >> t;    while(t--)    {        int start, ends, route;        for(int i=0; i<maxn; i++)            root[i]=i;        cin >> start >> ends >> route;        while(route--)        {            int m, x, y;            cin >> m >> x;            while(x != root[x]) x=root[x];            for(int i=1; i<m; i++)            {                cin >> y;                while(y != root[y]) y=root[y];                if(y != x) root[y]=x;            }        }        while(start != root[start]) start=root[start];        while(ends != root[ends]) ends=root[ends];        printf(start==ends?"Yes\n":"No\n");    }    return 0;}
原创粉丝点击