0w1

UVA 1160 - X-Plosives ( Union Find )

UVa Online Judge
Formally put, it is that given many edges through input, only connect the ones that do not form cycle, and otherwise count it in the answer. Checking whether a new edge will cause a cycle be formed can be managed by union find, examining whether the two nodes attempting to connect is already connected.

#include <bits/stdc++.h>
using namespace std;

struct UnionFind{
    vector< int > fa;
    UnionFind( int sz ){
        fa.resize( sz );
        for( int i = 0; i < sz; ++i )
            fa[ i ] = i;
    }
    int find( int x ){
        return fa[ x ] == x ? x : fa[ x ] = find( fa[ x ] );
    }
    bool unite( int a, int b ){
        int x = find( a );
        int y = find( b );
        if( x == y ) return true;
        fa[ x ] = y; return false;
    }
};

int main(){
    ios::sync_with_stdio( false );

    for( int X, Y; cin >> X; ){
        int ans = 0;
        cin >> Y;
        UnionFind uf( 100000 + 1 );
        uf.unite( X, Y );
        while( cin >> X and X != -1 ){
            cin >> Y;
            if( uf.find( X ) == uf.find( Y ) ) ++ans;
            else uf.unite( X, Y );
        }
        cout << ans << "\n";
    }

    return 0;
}