COJ 1004 Xi and Bo

原题传送门:http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1004

1004: Xi and Bo

Time Limit: 1 Sec   Memory Limit: 128 MB
Submit: 275   Solved: 95
[ Submit][ Status][ Web Board]

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

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

HINT

 

Source

中南大学第五届大学生程序设计竞赛-热身赛

 

分析:用并查集。对于每条公交路线,因为都是双向的,每个测试组的第一条公交路线的root 肯定是第一个站,对于剩下的公交路线,看看路线中是否包含这条以上路线的公交站,如果有就把那条路线合并到当前这条来,(f_a= fater[那条路线],father[f_a] = father[当前路线]);这样就把所有路线的集合合并了,最后判断father[起点] == father[终点] ?如果是则说明可以行得通,不是就over;

 

#include<cstdio>
#define MAXM 110
int father[MAXM];
void init()
{
    for(int i=0;i<MAXM;i++)
        father[i] = i;
}
int find(int a)
{
    return father[a]==a?a:father[a] = find(father[a]);
}
void add(int a,int b)
{
    int f_a = find(a);
    int f_b = find(b);
    if(f_a!=f_b) father[f_b] = f_a;
}
int t,s,e,n,m,head,x,y;
int main()
{
    scanf("%d",&t);
    while(t--)
    {
        init();
        scanf("%d%d%d",&s,&e,&n);
        while(n--)
        {
            scanf("%d%d",&m,&x);
            head = find(x);
            for(int i=2;i<=m;i++)
            {
                scanf("%d",&y);
                y = find(y);
                add(head,y);
            }
        }
        printf("%s\n",find(s)==find(e)?"Yes":"No");
    }
}

 

你可能感兴趣的:(BO)