题目描述
或许你并不知道,你的某个朋友是你的亲戚。他可能是你的曾祖父的外公的女婿的外甥女的表姐的孙子。如果能得到完整的家谱,判断两个人是否亲戚应该是可行的,但如果两个人的最近公共祖先与他们相隔好几代,使得家谱十分庞大,那么检验亲戚关系实非人力所能及。在这种情况下,最好的帮手就是计算机。为了将问题简化,你将得到一些亲戚关系的信息,如Marry和Tom是亲戚,Tom和Ben是亲戚,等等。从这些信息中,你可以推出Marry和Ben是亲戚。请写一个程序,对于我们的关于亲戚关系的提问,以最快的速度给出答案。
输入
输入由两部分组成。
第一部分以N,M开始。N为问题涉及的人的个数(1≤N≤20000)。这些人的编号为1,2,3,…, N。下面有M行(1≤M≤1 000 000),每行有两个数ai, bi,表示已知ai和bi是亲戚。
第二部分以Q开始。以下Q行有Q个询问(1≤Q≤1 000 000),每行为ci, di,表示询问ci和di是否为亲戚。
输出
对于每个询问ci, di,输出一行:若ci和di为亲戚,则输出“Yes”,否则输出“No”。
样例输入
10 7
2 4
5 7
1 3
8 9
1 2
5 6
2 3
3
3 4
7 10
8 9
样例输出
Yes
No
Yes
来源
图论-并查集
AC_CODE
Python
parent = [-1 for _ in range(20010)]
def find_root(x):
x_root = x
while parent[x_root] != -1:
x_root = parent[x_root]
return x_root
def union(x, y):
x_root = find_root(x)
y_root = find_root(y)
if x_root != y_root:
parent[x_root] = y_root
n, m = map(int, input().split())
for i in range(m):
a, b = map(int, input().split())
union(a, b)
q = int(input())
for i in range(q):
c, d = map(int, input().split())
c_root = find_root(c)
d_root = find_root(d)
if c_root == d_root and c_root != -1 and d_root != -1:
print('Yes')
else:
print('No')
C++
#include <iostream>
using namespace std;
const int VERTICES = 20010;
int parent[VERTICES];
int find(int x) {
int x_root = x;
while (parent[x_root] != -1) {
x_root = parent[x_root];
}
return x_root;
}
void union_vertices(int x, int y) {
int x_root = find(x);
int y_root = find(y);
if (x_root != y_root)
parent[x_root] = y_root;
}
int main() {
int n, m, a, b;
cin >> n >> m;
for (int i = 0; i <= n; i++)
parent[i] = -1;
while (m--) {
cin >> a >> b;
union_vertices(a, b);
}
int q, c, d;
cin >> q;
while (q--) {
cin >> c >> d;
int c_root = find(c);
int d_root = find(d);
if (c_root == d_root && c_root != -1 && d_root != -1)
cout << "Yes" << endl;
else
cout << "No" << endl;
}
return 0;
}