107. 寻找存在的路径 (kamacoder.com)
#include<vector>
#include<iostream>
using namespace std;
int n = 0;
vector<int> father = vector<int>(101);
void init(){
for(int i = 1; i < n + 1; i++){
father[i] = i;
}
}
int find(int i){ // 找根节点
if(i == father[i]){
return i;
}
return father[i] = find(father[i]); // 压缩作用,直接将i链接到根部
}
void join(int i, int j){
i = find(i);
j = find(j);
if(i == j){
return;
}
father[j] = i;
}
bool ifsame(int i, int j){
i = find(i);
j = find(j);
return i == j;
}
int main(){
int m = 0;
cin >> n >> m;
init();
for(int i = 0; i < m; i++){
int u = 0, v = 0;
cin >> u >> v;
join(u, v);
}
int s = 0, t = 0;
cin >> s >> t;
if(ifsame(s, t)){
cout << 1 << endl;
}else{
cout << 0 << endl;
}
return 0;
}