【杭电】[1856]More is better

文章字数:189

问题描述

问题分析

要求集合中的元素的最大值
这里可以借助ran数组储存树的高度
(详见并查集防树形退化讲解)
在合并的时候可以对最大高度进行记录

 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
#include<stdio.h>
int par[10000020],ran[10000020];
int res;
int find(int m) {
    if(m==par[m])
        return m;
    else
        return par[m]=find(par[m]);
}
void unite(int x,int y) {
    x=find(x);
    y=find(y);
    if(x==y)
        return ;
    else {
        if(ran[x]<ran[y]) {
            par[x]=y;
            ran[y]+=ran[x];
            if(ran[y]>res)
                res=ran[y];
        } else {
            par[y]=x;
            ran[x]+=ran[y];
            if(ran[x]>res)
                res=ran[x];
        }
    }
}
int main() {
    int n;
    while(scanf("%d",&n)!=EOF) {
        for(int i=1; i<=10000000; i++) {
            ran[i]=1;
            par[i]=i;
        }
        res=1;
        for(int i=0; i<n; i++) {
            int a,b;
            scanf("%d %d",&a,&b);
            unite(a,b);
        }
        printf("%d\n",res);
    }
    return 0;
}

该内容采用 CC BY-NC-SA 4.0 许可协议。

如果对您有帮助或存在意见建议,欢迎在下方评论交流。

加载中...