【杭电】[2120]Ice_cream's world I

文章字数:134

问题描述

问题分析

其实也就是找出成环个数
已经在同一集合中的又进行合并
find(x)==find(y)
则形成一个环 res++

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

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

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

加载中...