并查集
定义一个数组保存各个结点的祖先
数组一般初始化时会将祖先定义为本结点
int father[N]
for(int i = 1; i <= n; i++){
father[i] = i;
}
查找根节点
int findRoot(int x){
return x == father[x] ? x : findRoot(father[x]);
}
//或者
int findRoot(int x){
if(father[x] == x)
return x;
return findRoot(father[x]);
}
路径压缩
int findRoot(int x){
if(father[x] == x)
return x;
father[x] = findRoot(farther[x]);
return findRoot(father[x]);
//return father[x] = findRoot(farther[x]);
}
//普通合并
void join(int x, int y){
int u = findRoot(x), v = findRoot(y);
if(u != v)
father[u] = v;
}
按秩合并
//按大小合并
int size[N];
void join(int x, int y){
int u = findRoot(x), v = findRoot(y);
if(u != v){
if(size[u] > size[v]){
father[v] = u;
size[u] += size[v];
}
else{
father[u] = v;
size[v] += size[u];
}
}
}
//按树高合并
int high[N];
void join(int x, int y){
int u = findRoot(x), v = findRoot(y);
if(u != v){
if(high[u] > high[v]){
father[v] = u;
}
else{
father[u] = v;
if(high[u] == high[v])
high[v]++;
}
}
}
HDU 1856
Problem Description
Mr Wang wants some boys to help him with a project. Because the project is rather complex, the more boys come, the better it will be. Of course there are certain requirements.
Mr Wang selected a room big enough to hold the boys. The boy who are not been chosen has to leave the room immediately. There are 10000000 boys in the room numbered from 1 to 10000000 at the very beginning. After Mr Wang’s selection any two of them who are still in this room should be friends (direct or indirect), or there is only one boy left. Given all the direct friend-pairs, you should decide the best way.
Input
The first line of the input contains an integer n (0 ≤ n ≤ 100 000) - the number of direct friend-pairs. The following n lines each contains a pair of numbers A and B separated by a single space that suggests A and B are direct friends. (A ≠ B, 1 ≤ A, B ≤ 10000000)
Output
The output in one line contains exactly one integer equals to the maximum number of boys Mr Wang may keep.
Sample Input
4
1 2
3 4
5 6
1 6
4
1 2
3 4
5 6
7 8
Sample Output
4
2
Hint
A and B are friends(direct or indirect), B and C are friends(direct or indirect),
then A and C are also friends(indirect).
In the first sample {1,2,5,6} is the result.
In the second sample {1,2},{3,4},{5,6},{7,8} are four kinds of answers.
代码
#include <iostream>
#include <cstdio>
#define N 10000005
using namespace std;
int father[N];
int sum[N];
int findRoot(int x){
if(father[x] == x)
return x;
return father[x] = findRoot(father[x]);
}
void join(int x, int y){
int u = findRoot(x), v = findRoot(y);
if(u != v){
father[u] = v;
sum[v] += sum[u];
}
}
int main()
{
int n, a, b;
while(scanf("%d", &n) != EOF)
{
for(int i = 1; i < N; i++){
father[i] = i;
sum[i] = 1;
}
for(int j = 0; j < n; j++){
scanf("%d%d", &a, &b);
join(a, b);
}
int ans = 1;
for(int i = 1; i < N; i++){
if(father[i] == i && sum[i] > ans)
ans = sum[i];
}
cout << ans << endl;
}
return 0;
}
博客介绍了并查集相关知识,包括定义数组保存结点祖先、初始化、查找根节点、路径压缩和按秩合并。还给出HDU 1856问题,描述了问题背景、输入输出要求及示例,最后给出了相关代码。
11万+

被折叠的 条评论
为什么被折叠?



