P1551 Relatives (and check template questions)

Background of the topic
If a family member is too large, it is really not easy to judge whether two people are relatives. Now give a diagram of a relative relationship and ask whether any two people given are related.

Title description
Regulations: x and y are relatives, y and z are relatives, then x and z are also relatives. If x and y are relatives, then x's relatives are all y's relatives, and y's relatives are also x's relatives.

Input format The
first line: three integers n, m, p, (n<=5000, m<=5000, p<=5000), which respectively indicate that there are n individuals and m relatives. Ask p for relatives.

The following m lines: each line has two numbers Mi, Mj, 1<=Mi, Mj<=N, indicating that Mi and Mj are related.

Next line p: each line has two numbers Pi, Pj, asking whether Pi and Pj are related.

The output format is
P lines, with one'Yes' or'No' per line. Indicates that the answer to the i-th question is "has" or "does not have" relatives.

Input and output sample
Input #1
6 5 3
1 2
1 5
3 4
5 2
1 3
1 4
2 3
5 6
Output #1
Yes
Yes
No
Question analysis: This is a template question of naked union search. Set the ancestor of each person as himself, and then search for the ancestors according to each pair of relatives. If the ancestors are different, set the ancestor of one person to the other person. Finally, the ancestors of the relatives will be the same "ancestor" ", by judging whether the ancestors are the same or not, you can know whether they are related.

#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;

int n, m, p, f[5010], x, y;

int query(int x){
    
    
	if(f[x] == x) return x;
	else return query(f[x]);
}

void merge(int x, int y){
    
    
	int f1 = query(x);
	int f2 = query(y);
	if(f1 != f2) f[f1] = f2;
} 

int main(){
    
    
	scanf("%d%d%d", &n, &m, &p);
	for(int i = 1; i <= n; i++){
    
    
		f[i] = i;
	}
	for(int i = 1; i <= m; i++){
    
    
		scanf("%d%d", &x, &y);
		merge(x ,y);
	}
	for(int i = 1; i <= p; i++){
    
    
		scanf("%d%d", &x, &y);
		if(query(x) == query(y)) printf("Yes\n");
		else printf("No\n");
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_42920035/article/details/109248317