107. 寻找存在的路径
只需要判断是否联通,不需要知道具体路径或者路径数量,可以使用并查集。
cpp
// project1.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <vector>
using namespace std;
void init(vector<int> &father) {
for (int i = 0; i < father.size(); ++i) {
father[i] = i;
}
}
int find(vector<int>& father, int u) {
if (father[u] == u) return u;
return father[u] = find(father, father[u]);
}
int isSame(vector<int>& father, int u, int v) {
u = find(father, u);
v = find(father, v);
return u == v;
}
void join(vector<int>& father, int u, int v) {
u = find(father, u);
v = find(father, v);
if (u == v) return;
father[v] = u;
}
int main()
{
int n, m, u, v, source, destination;
cin >> n >> m;
vector<int> father(n + 1, 0);
init(father);
while (m--) {
cin >> u >> v;
join(father, u, v);
}
cin >> source >> destination;
if (isSame(father, source, destination))
cout << 1 << endl;
else
{
cout << 0 << endl;
}
return 0;
}