A: Xi and Bo
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
就说通过一堆能转站换乘的公交线路能不能从起始到终点
这个题就是并查集的裸的模板题呀个人感觉,最后如果询问的点在同一个并查集里就YES,否则NO
#include <bits/stdc++.h>
#define N 10100
#define INF 0x3f3f3f3f
#define LL long long
#define mem(a,n) memset(a,n,sizeof(a))
#define fread freopen("in.txt","r",stdin)
#define fwrite freopen("out.txt","w",stdout)
using namespace std;
int par[N],rak[N];
void init(int n)
{
for(int i=0;i<=n;++i){
rak[i]=0;
par[i]=i;
}
}
int find(int x)
{
if(par[x]==x){
return x;
}
return par[x]=find(par[x]);//注意此处的赋值,可以在查找的时候把并查集的深度降低
}
void unite(int x,int y)
{
int fx=find(x);
int fy=find(y);
if(fx==fy){
return;
}else{
par[fy]=fx;
if(rak[fx]==rak[fy]){
++rak[fx];
}
}
}
bool same(int x,int y)
{
return find(x)==find(y);
}
int main()
{
ios::sync_with_stdio(false);
int t,n,d,s,num1,num3,num2;
cin>>t;
while(t--){
cin>>s>>d;
cin>>n;
init(200);
for(int i=0;i<n;++i){
cin>>num1>>num2;
for(int j=1;j<num1;++j){
cin>>num3;
unite(num3,num2);
}
}
if(same(s,d)){
cout<<"Yes"<<endl;
}else{
cout<<"No"<<endl;
}
}
return 0;
}
/**********************************************************************
Problem: 1004
User: CSUzick
Language: C++
Result: AC
Time:0 ms
Memory:1768 kb
**********************************************************************/