CSU 1004
1004: Xi and Bo
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 273 Solved: 93
[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
一开始想到了并查集
后来发现不是两个两个的输入
又想到DFS
其实可以把他变成两个两个的就好
1 #include <iostream> 2 3 using namespace std; 4 int fa[101]; 5 void init() 6 { 7 for(int i =0;i<101;i++) 8 { 9 fa[i]=i; 10 } 11 } 12 13 int find(int x) 14 { 15 while(x!=fa[x]) 16 x = fa[x]; 17 return x; 18 } 19 20 void merge(int x,int y) 21 { 22 int a = find(x); 23 int b = find(y); 24 if(a!=b) 25 { 26 fa[a]=b; 27 } 28 } 29 int main() 30 { 31 int T,start,end,n,m; 32 cin.sync_with_stdio(false); 33 cin>>T; 34 while(T--) 35 { 36 init(); 37 cin>>start>>end>>n; 38 for(int i=0;i<n;i++) 39 { 40 cin>>m; 41 int x,y; 42 cin>>x; 43 for(int i=1;i<m;i++) 44 { 45 cin>>y; 46 merge(x,y); 47 } 48 } 49 if(find(start)!=find(end)) 50 cout<<"No"<<endl; 51 else 52 cout<<"Yes"<<endl; 53 54 } 55 return 0; 56 }
实现代码