1004: Xi and Bo
Time Limit: 1 Sec Memory Limit: 128 Mb
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
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
中南大学第五届大学生程序设计竞赛-热身赛
题目链接:http://acm.csu.edu.cn/csuoj/problemset/problem?pid=1004
题解:本题的意思是给定两个公交站点,判断是否这两个站点在给定的线路中可以到达(直达或者通过中间站点到达都可以)。这题就是典型的并查集问题。具体看如下代码:
AC代码:
#include<iostream>
using namespace std;
int s,e,n,m,tmp;
int fa[110];
void Init(){
for(int i=0;i<110;i++){
fa[i]=i;
}
}
//寻址树的根节点
int find(int x){
return x==fa[x]?x:fa[x]=find(fa[x]); //路径压缩
}
void merge(int x,int y){
int a=find(x);
int b=find(y);
if(a!=b){
fa[a]=b;
}
}
int main(){
int T;
scanf("%d",&T);
while(T--){
Init();
scanf("%d%d%d",&s,&e,&n); //起点,终点,线路数目
for(int i=1;i<=n;i++){
scanf("%d",&m); // 站点数目
for(int j=0;j<m;j++){
scanf("%d",&tmp); //站点
merge(n,tmp);
}
}
if(find(s)==find(e)){
printf("Yes\n");
}
else{
printf("No\n");
}
}
return 0;
}