Fork me on GitHub

数据结构与算法-图论(一)-并查集


数据结构与算法-图论(一)-并查集

关于并查集的理解可以看一下这个csdn博客:https://blog.csdn.net/xr469786706/article/details/86494565

并查集的操作如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

int pre[1000];

int find(int x){
int r = x;
while(r != pre[r]){
r = pre[r];
}

int i = x,j;
// 路径压缩
while(i != r){
j = pre[i];
pre[i] = r;
i = j;
}

return r;
}

void join(int x,int y){
int fx = find(x);
int fy = find(y);
if(fx != fy){
pre[fx] = fy;
}
}

接下来我们来看一下并查集的运用

  1. More is better

    题目描述:

    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.

    输入:

    The first line of the input contains an integer n (0 <= n <= 100000) - 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)

    输出:

    The output in one line contains exactly one integer equals to the maximum number of boys Mr Wang may keep.

    样例输入:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    4
    1 2
    3 4
    5 6
    1 6
    4
    1 2
    3 4
    5 6
    7 8

    样例输出:

    1
    2
    4
    2

    代码如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    #include<iostream>

    using namespace std;

    #define N 10000000
    int pre[N];

    int find(int x){
    int r = x;
    while(r != pre[r]){
    r = pre[r];
    }
    int i = x,j;
    while(i != r){
    j = pre[i];
    pre[i] = r;
    i = j;
    }
    return r;
    }

    void join(int x,int y){
    int fx = find(x);
    int fy = find(y);
    if(fx != fy){
    pre[fx] = fy;
    }
    }

    int sum[N];
    int main()
    {
    int n;
    while(scanf("%d",&n)!=EOF){
    for(int i = 1 ; i <= N ; i++){
    pre[i] = i;
    sum[i] = i;
    }

    for(int i = 1 ; i <= n ; i++){
    int a,b;
    scanf("%d%d",&a,&b);
    join(a,b);
    sum[b] += sum[a];
    }
    int ans = 1;
    for(int i = 1 ; i <= N ; i++){
    if(i == pre[i] && sum[i] > ans) ans = sum[i];
    }
    printf("%d\n",ans);
    }

    return 0;
    }

    运行结果:

坚持原创技术分享,您的支持将鼓励我继续创作
-------------本文结束感谢您的阅读-------------
0%