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
Source
中南大学第五届大学生程序设计竞赛-热身赛
Solution
#include <iostream>
#include <cmath>
#include <set>
using namespace std;
//判断图上的两个节点是否连通
bool can_reach(bool stations[][101],int sta1,int sta2,set<int>& sets){
if(stations[sta1][sta2]) return true;
sets.insert(sta1);
for(int i=0; i<101; i++){
if(stations[sta1][i] && (sets.find(i) == sets.end())){
if(can_reach(stations,i,sta2,sets)) return true;
}
}
return false;
}
int main(int argc, char** argv) {
int T;
cin>>T;
for(int i=0; i<T; i++){
int sta1,sta2;
cin>>sta1>>sta2;
int n;
cin>>n;
bool stations[101][101] = {false}; //图创建
for(int j=0; j<n; j++){
int m;
cin>>m;
int temp1,temp2;
cin>>temp1;
for(int k=0; k<m-1; k++){
cin>>temp2;
stations[temp1][temp2] = true;
stations[temp2][temp1] = true;
}
}
set<int> sets; //set容器用来记录是否搜索过该节点
if(can_reach(stations,sta1,sta2,sets)){
cout<<"Yes"<<endl;
}else{
cout<<"No"<<endl;
}
}
return 0;
}