并查集,最好写一个类,见 struct Uf ,可以看看 并查集的使用和优化 - jyhzf - 博客园
并查集主要三操作 Uf(构造函数初始化),find(找root节点,包含路径压缩), join(合并)
路径压缩可以理解成减小树的深度,把当前结点的root结点设为更上层的root的结点还不是直接root结点,白话就是把我的老大 设为 我的老大的老大...
本题注意去重,就是当某两个点的root一样时,就没必要在加数量了
#include <bits/stdc++.h>
using namespace std;
#define PERSON_NUM 100001
struct Uf {
vector<int> pa = vector<int>(PERSON_NUM);
vector<int> cnt = vector<int>(PERSON_NUM, 1);
Uf() {
for(int i = 1; i < PERSON_NUM; ++i) {
pa[i] = i;
}
}
int find(int x) {
if(pa[x] != x) return pa[x] = find(pa[x]);
return x;
}
int join(int x, int y) {
int px = find(x), py = find(y);
if(px != py) { // 去重
pa[px] = py;
cnt[py] += cnt[px];
}
return py;
}
};
int main() {
int T, n, x, y, ans;
scanf("%d", &T);
while(T--) {
struct Uf uf_;
ans = 1;
scanf("%d", &n);
for(int i = 0; i < n; ++i) {
scanf("%d%d", &x, &y);
int py = uf_.join(x, y);
ans = max(ans, uf_.cnt[py]);
}
printf("%d\n", ans);
}
}
知识点:
vector类型的数据成员初始化方式
class Foo(){
private:
vector<string> name = vector<string>(5);
}