Cod sursa(job #1367602)

Utilizator somuBanil Ardej somu Data 1 martie 2015 23:26:13
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include <iostream>
#include <fstream>
#define nmax 100005

using namespace std;

int n, m;
int tata[nmax], nr[nmax];

int root(int x) {
    if (tata[x] == x)
        return x;
    return root(tata[x]);
}

int main() {
    
    ifstream fin("disjoint.in");
    ofstream fout("disjoint.out");
    
    fin >> n >> m;
    
    for (int i = 1; i <= n; i++)
        tata[i] = i, nr[i] = 1;
    
    for (int i = 1; i <= m; i++) {
        int x, y, op;
        fin >> op >> x >> y;
        
        int r1 = root(x);
        int r2 = root(y);
        
        if (op == 2)
            r1 == r2 ? fout << "DA\n" : fout << "NU\n";
        
        if (r1 == r2) {
            continue;
        }
        
        if (nr[r1] >= nr[r2]) {
            nr[r1] += nr[r2];
            tata[r2] = r1;
        } else {
            nr[r2] += nr[r1];
            tata[r1] = r2;
        }
        
    }
    
    fin.close();
    fout.close();
    
    return 0;
}