题目我上面有人儿
代码
#include <bits/stdtr1c++.h>
using namespace std;
const int N = 1005;
int f[N];
int n;
int siz[N];
// 初始化并查集
// void init()
// {
// for (int i = 1; i <= n; i++)
// {
// f[i] = i; // 初始化所有的节点都是自己的父节点
// }
// }
int find(int j)
{// if (f[j] == j)// {// return j;// }// else// {// f[j] = find(f[j]);// return f[j];// }if (f[j] != j){f[j] = find(f[j]);}return f[j];
}void unio(int i, int j)
{int i_fa = find(i);int j_fa = find(j);// i的父亲变为j的父亲if (i_fa != j_fa){f[i_fa] = j_fa;siz[j_fa] += siz[i_fa];}
}int main()
{ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);cin >> n;for (int i = 1; i <= n; i++){f[i] = i;siz[i] = 1;}for (int i = 1; i <= n; i++){int x;cin >> x;unio(i, x); // i的父亲是x// cout << f[i] << " ";}for (int i = 1; i <= n; i++){int root = find(i);cout << siz[root] << " ";}
}
并查集模板
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;#define N 100010
int n, m, x, y, z;
int fa[N];
void init()
{for (int i = 1; i <= n; i++)fa[i] = i;
}
int find(int x)
{if (fa[x] == x)return x;return fa[x] = find(fa[x]);
}
// 结合
void unionset(int x, int y)
{fa[find(x)] = find(y);
}
int main()
{cin >> n >> m;init();while (m--){cin >> z >> x >> y;if (z == 1)unionset(x, y);else{x = find(x), y = find(y);if (x == y)puts("Y");elseputs("N");}}return 0;
}