[HDU] [2120] Ice_cream's world I

Problem Description

Loading...

Problem Analysis

Actually, this is just finding the number of cycles
Merging again when they are already in the same set
find(x)==find(y)
then a cycle is formed, res++

cpp
 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;
}
This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...