1004: Xi and Bo
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 479 Solved: 177
[ 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
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
#include <stdio.h>
#define N 105
int fa[N];
int a[N];
void InitSet(int n){
for(int i=1; i<=n; i++) fa[i] = i ;
}
int Find(int x) {
return fa[x] == x ? x : fa[x] = Find(fa[x]) ;
}
bool Merge(int u ,int v) {
int fu = Find(u) , fv = Find(v) ;
if(fu != fv) fa[fv] = fu ;
return fu != fv ;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
InitSet(100);
int kstart,kend;
scanf("%d%d",&kstart,&kend);
int n;
scanf("%d",&n);
while(n--)
{
int m;
scanf("%d",&m);
for(int i=0;i<m;i++)
scanf("%d",&a[i]);
for(int i=1;i<m;i++)
Merge(a[i-1],a[i]);
}
printf("%s\n",Find(kstart)==Find(kend)?"Yes":"No");
}
return 0;
}