原题地址
http://codeup.hustoj.com/problem.php?cid=100000615&pid=3
解题思路
题意就是求集合的最大元素数量。使用并查集的操作即可~
注意事项
1.还是那个老问题,在合并集合的时候如果要更新集合规模,一定要注意书写的顺序~详情见代码。
2.注意特判,n = 0时输出1。
参考代码
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
typedef double db;
typedef long long LL;
typedef vector<int> VI;
const int inf = 2e9;
const LL INF = 8e18;
const int maxn = 1e7 + 10;
int father[maxn];
int findFather(int x) {
if (father[x] < 0) return x;
else {
return father[x] = findFather(father[x]);
}
}
void Union(int a, int b) {
int fa = findFather(a);
int fb = findFather(b);
if (fa != fb) {
//fa元素比fb多
if (father[fa] < father[fb]) {
father[fb] += father[fa]; //一定一定这两句顺序不要反了
father[fa] = fb; //小集合并入大集合
} else {
father[fa] += father[fb];
father[fb] = fa;
}
}
}
int main() {
int n, m, a, b;
//while (~scanf("%d%d", &n, &m)) {
while (~scanf("%d", &m)) {
if (!m) {
printf("1\n");
continue;
}
n = -1;
//初始化数组元素
fill(father, father + maxn, -1);
for (int i = 0; i < m; ++i) {
scanf("%d%d", &a, &b);
Union(a, b);
n = max(n, a); //动态更新最大值
n = max(n, b);
}
int sum = -1;
for (int i = 1; i <= n; ++i) {
//注意这里要取个绝对值~
if (father[i] < -1) sum = max(sum, abs(father[i]));
}
printf("%d\n", sum);
}
return 0;
}