算法训练营|图论第5天
题目:107.寻找存在的路径
题目链接:
107. 寻找存在的路径 (kamacoder.com)
代码:
#include<bits/stdc++.h>
#include<unordered_map>
#include<unordered_set>
using namespace std;
vector<int>father;
int find(int u) {
if (u == father[u]) return u;
else return father[u] = find(father[u]);
}
void join(int u, int v) {
u = find(u);
v = find(v);
if (u == v) return;
father[v] = u;
}
bool isSame(int u, int v) {
u = find(u);
v = find(v);
return u == v;
}
int main() {
int n, m;
cin >> n >> m;
father = vector<int>(n + 1);
for (int i = 0; i <= n; i++) {
father[i] = i;
}
for (int i = 0; i < m; i++) {
int s, t;
cin >> s >> t;
join(s, t);
}
int source, destination;
cin >> source >> destination;
if (isSame(source, destination)) {
cout << 1 << endl;
}
else {
cout << 0 << endl;
}
}