topic link
Topic description
As the title, now there is a union query set, you need to complete the merge and query operations.
input format
The first line contains two integers N, M, representing a total of N elements and M operations.
Next M lines, each line contains three integers Z i , X i , Y i .
When Z i = 1, merge the sets where X i and Y i are.
When Z i = 2, output whether X i and Yi i are in the same set, yes, output Y; otherwise, output N.
output format
For each operation with Z i = 2, there is a line of output, each line containing an uppercase letter, either Y or N.
Input and output example
Enter #1
4 7
2 1 2
1 1 2
2 1 2
1 3 4
2 1 4
1 2 3
2 1 4
output #1
N
Y
N
Y
Instructions/Tips
For 30% of the data, N ≤ 10, M ≤ 20.
For 70% of the data, N ≤ 100, M ≤ 10 3 .
For 100% of the data, 1 ≤ N ≤ 10 4 , 1 ≤ M ≤ 2 × 10 5 .
AC code:
( Function details )
#include <cstdio>
const int maxn = 1e4+5;
int f[maxn], h[maxn];
int n, m, z, x, y;
void Init() {
for(int i=1; i<=n; i++) {
f[i] = i;
h[i] = 0;
}
}
int Find(int x) {
return f[x]==x ? f[x] : f[x] = Find(f[x]);
}
void merge(int a, int b) {
int fa = Find(a);
int fb = Find(b);
if(fa==fb) return;
if(h[fa] < h[fb])
f[fa] = fb;
} else {
f[fb] = fa;
if(h[fa] == h[fb]) h[fa]++;
}
}
int main() {
scanf("%d %d", &n, &m);
Init(); //记住一定要先初始化
// 本题只有一组数据,但若有多组数据,每次都需先进行初始化!!
while(m--) {
scanf("%d %d %d", &z, &x, &y);
if(z==1) {
//由题:当 z为 1时
merge(x,y); //合并两个元素
} else if(z==2) {
//当 z为2时
if(Find(x)==Find(y)) //如果两个元素的根相同
printf("Y\n"); //则输出Y
else //如果两个元素的根不同
printf("N\n"); //则输出N
}
}
return 0;
}