信息学奥赛一本通 / 例4.9 - 亲戚(relation) [并查集]
【问题描述】
或许你并不知道,你的某个朋友是你的亲戚。他可能是你的曾祖父的外公的女婿的外甥女的表姐的孙子。如果能得到完整的家谱,判断两个人是否亲戚应该是可行的,但如果两个人的最近公共祖先与他们相隔好几代,使得家谱十分庞大,那么检验亲戚关系实非人力所能及。在这种情况下,最好的帮手就是计算机。为了将问题简化,你将得到一些亲戚关系的信息,如Marry和Tom是亲戚,Tom和Ben是亲戚,等等。从这些信息中,你可以推出Marry和Ben是亲戚。请写一个程序,对于我们的关于亲戚关系的提问,以最快的速度给出答案。
【输入格式】
输入由两部分组成。
第一部分以N,M开始。N为问题涉及的人的个数(1<=N<=20000)。这些人的编号为1,2,3,…,N。 下面有M行(1<=M<=1000000), 每行有两个数ai,bi, 表示已知ai和bi是亲戚。
第二部分以Q开始。以下Q行有Q个询问(1<=Q<=1000000), 每行为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
OI C++ Code:
#include <iostream> using namespace std;
int father[20000];
int get_root(int child) { while (father[child] != child) { child = father[child]; } return child; }int main() { int N, M; cin >> N >> M;for (int i = 0; i < N; ++i)
{ father[i] = i;
} for (int i = 0; i < M; ++i) { int a, b; cin >> a >> b; --a; --b; father[a] = get_root(a); father[b] = get_root(b); if (father[a] != father[b]) {
father[father[a]] = father[b]; } } int Q; cin >> Q; for (int i = 0; i < Q; ++i) { int c, d; cin >> c >> d; --c; --d; if (get_root(father, c) == get_root(father, d)) { cout << "Yes" << endl; } else { cout << "No" << endl; } } return 0; }
C++ Code:
#include <iostream> #include <vector> using namespace std; int get_root(const vector<int> &father, int child) { while (father[child] != child) { child = father[child]; } return child; } int main() { int N, M; cin >> N >> M; vector<int> father(N); for (int i = 0; i < N; ++i) { father[i] = i; } for (int i = 0; i < M; ++i) { int a, b; cin >> a >> b; --a; --b; father[a] = get_root(father, a); father[b] = get_root(father, b); if (father[a] != father[b]) { father[father[a]] = father[b]; } } int Q; cin >> Q; for (int i = 0; i < Q; ++i) { int c, d; cin >> c >> d; --c; --d; if (get_root(father, c) == get_root(father, d)) { cout << "Yes" << endl; } else { cout << "No" << endl; } } return 0; }
C Code:
#include <stdio.h> #include <stdlib.h> int get_root(int *father, int child) { while (father[child] != child) { child = father[child]; } return child; } int main(void) { int N, M, Q, *father, i, a, b, c, d; scanf("%d %d", &N, &M); father = malloc(N * sizeof(int)); for (i = 0; i < N; ++i) { father[i] = i; } for (i = 0; i < M; ++i) { scanf("%d %d", &a, &b); --a; --b; father[a] = get_root(father, a); father[b] = get_root(father, b); if (father[a] != father[b]) { father[father[a]] = father[b]; } } scanf("%d", &Q); for (i = 0; i < Q; ++i) { scanf("%d %d", &c, &d); --c; --d; if (get_root(father, c) == get_root(father, d)) { puts("Yes"); } else { puts("No"); } } return 0; }