There are a total of n numbers, numbered 1∼n, and each number is in a set at the beginning.
Now to perform m operations, there are two types of operations:
M ab, merge the sets of the two numbers numbered a and b. If the two numbers are already in the same set, ignore this operation;
Q ab, ask whether the two numbers numbered a and b are in the same set. In a set;
input format
Enter the integers n and m on the first line.
Next m lines, each line contains an operation instruction, the instruction is one of M ab or Q ab .
Output format
For each query command Q ab, output a result, if a and b are in the same set, output Yes, otherwise output No.
One line for each result.
Data range
1≤n,m≤105
Input example:
4 5
M 1 2
M 3 4
Q 1 2
Q 1 3
Q 3 4
Output example:
Yes
No
Yes
#include<bits/stdc++.h>
using namespace std;
const int N = 100010;
int p[N];
int find(int a) //返回x的祖宗结点 + 路径压缩
{
if(a != p[a]) p[a] = find(p[a]);
return p[a];
}
int main()
{
int n, m;
cin >> n >> m;
for(int i=1; i<=n; i++) p[i] = i;
char op;
int a, b;
while(m--) {
cin >> op;
cin >> a >> b;
if(op == 'M') {
p[find(a)] = find(b);
}
else {
if(find(a) == find(b)) puts("Yes");
else puts("No");
}
}
return 0;
}