并查集
板子
\(Code\)
点击查看代码
#include <cstdio>
#include <iostream>
const int N = 1e4 + 3;
int n, m, fa[N];
int fint (int k) {
return fa[k] == k ? k : fa[k] = fint(fa[k]);
}
int main() {
scanf("%d %d", &n, &m);
for (int i = 1; i <= n; ++i) fa[i] = i;
for (int i = 1, z, x, y; i <= m; ++i) {
scanf("%d %d %d", &z, &x, &y);
int fx = fint(x), fy = fint(y);
if (z == 1) fa[fy] = fx;
else if (fy == fx) printf("Y\n");
else printf("N\n");
}
return 0;
}
P2391 白雪皑皑
\(Code\)
点击查看代码
#include <cstdio>
#include <iostream>
using namespace std;
const int N = 1e6 + 3;
int n, m, p, q, fa[N], col[N];
int fint(int k) {
return fa[k] == k ? k : fa[k] = fint(fa[k]);
}
int main() {
scanf("%d %d %d %d", &n, &m, &p, &q);
for (int i = 1; i <= n + 2; ++i) fa[i] = i;
for (int i = m, l, r; i >= 1; --i) {
l = ((i * p + q) % n) + 1;
r = ((i * q + p) % n) + 1;
if (r < l) swap(l, r);
for (int j = l; j <= r; ) {
int f = fint(j);
if (f == j) {
col[j] = i;
fa[j] = j + 1;
}
j = f;
}
}
for (int i = 1; i <= n; ++i) {
printf("%d\n", col[i]);
}
return 0;
}