Cod sursa(job #1762480)

Utilizator antracodRadu Teodor antracod Data 23 septembrie 2016 16:43:34
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.91 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream fin("disjoint.in");
ofstream fout("disjoint.out");

const int nmax = 100000;

int r[nmax+1];

void update( int x ) {
    int y = x;
    while ( y != r[y] ) {
        y = r[y];
    }
    int z = x;
    while ( z != r[z] ) {
        int aux = r[z];
        r[z] = y;
        z = aux;
    }
}

int main()
{
    int n, m;
    fin >> n >> m;
    for ( int i = 1; i <= n; ++ i ) {
        r[i] = i;
    }

    for ( int i = 1; i <= m; ++ i ) {
        int x, y, z;
        fin >> x >> y >> z;
        if ( x == 1 ) {
            update(y);
            update(z);
            r[r[y]] = z;
        } else {
            update(y);
            update(z);
            if ( r[y] == r[z] ) {
                fout << "DA\n";
            } else {
                fout << "NU\n";
            }
        }
    }

    return 0;
}