天天看點

UVALive 3644 X-Plosives (并查集)

思路:

當出現環路時,化合物會爆炸,是以我們通過并查集來建構一棵樹,在這棵樹上,增加任意一條邊都會構成環路。問你有多少邊是能使這顆樹成環。

#include <iostream>
#include <cstdio>
#include <string.h>
#include <queue>
#include <cmath>
typedef long long int lli;
using namespace std;

int a[];

int find(int x){
    int xx = x;
    while(xx != a[xx]){
        xx = a[xx];
    }
    int temp = a[x];
    while(x != xx){
        a[x] = xx;
        x = temp;
        temp = a[temp];
    }
    return xx;
}
bool merge(int i,int j){
    int aa = find(i);
    int bb = find(j);
    if( aa != bb){
        a[aa] = bb;
        return false;
    }
    return true;
}

int main(){
    int m,n;
    int ans = ;
    while(~scanf("%d%d",&m,&n)){
        ans = ;
        for(int i = ;i <= ;i++){
            a[i] = i;
        }
        merge(m,n);
        while(scanf("%d",&m),m != -){
            scanf("%d",&n);
            if(merge(m,n)){
                ans++;
            }
        }
        printf("%d\n",ans);
    }
}