Cod sursa(job #2006609)

Utilizator LucaSeriSeritan Luca LucaSeri Data 30 iulie 2017 22:33:11
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.91 kb
#include <fstream>
using namespace std;

const int MaxN = 100010;

int tata[MaxN];
int rang[MaxN];

ifstream cin("disjoint.in");
ofstream cout("disjoint.out");
void combine(int x, int y){
   if(rang[x] >= rang[y]) tata[y] = x;
   else tata[x] = y;
   
   if(rang[x] == rang[y]) rang[x]++;    


}

int root(int x){
   int r = x;
   int y = x;;
   for(; tata[r] != r; r = tata[r]);
      
   int aux = tata[y];
   for(; aux != y; y = aux){  
      aux = tata[y];
      tata[y] = r;
   }
   
   
   return r;    
}


int main() {
    int n;
    cin >> n;
    int m;
    cin >> m;
    
    for(int i = 1; i <= n; ++i){
        tata[i] = i;
        rang[i] = 1;
    }    
    
   
    for(int cd, x, y; m; --m){
        cin >> cd >> x >> y;
        if(cd == 1){
            combine(root(x), root(y));
        }
        else{
            if(root(x) == root(y)) cout << "DA\n";
            else cout << "NU\n";
        }
    }
    return 0;
}