Cod sursa(job #2115636)

Utilizator TimoteiCopaciu Timotei Timotei Data 26 ianuarie 2018 22:55:53
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.93 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <cmath>

#define For(i, x, y) for(int i = x; i <= y; ++i)
#define Forr(i, x, y) for(int i = x; i <= y; --i)
#define sz() size()
#define nMax 100005

using namespace std;
int P[nMax], h[nMax];

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

void unite(int x, int y)
{
    int Rx = root(x);
    int Ry = root(y);
    if(h[Rx] >= h[Ry])
        P[Ry] = Rx;
    else
        P[Rx] = Ry;
    if(h[Rx] == h[Ry]) h[Rx]++;
}
int main()
{
    ifstream fin("disjoint.in");
    ofstream fout("disjoint.out");
    int n, m, type, x, y;
    fin >> n >> m;
    For(i, 1, n){
       P[i] = i;
       h[i] = 1;
    }
    For(i, 1, m){
       fin >> type >> x >> y;
       if(type == 1) unite(x, y);
         else if(root(x) == root(y)) fout << "DA\n";
                else fout << "NU\n";
    }
    return 0;
}