Pagini recente » Cod sursa (job #2385768) | Cod sursa (job #2309166) | Cod sursa (job #2575941) | Cod sursa (job #1010787) | Cod sursa (job #2951587)
#include <iostream>
#include <fstream>
using namespace std;
ifstream in("disjoint.in");
ofstream out("disjoint.out");
int n;
const int M = 100005;
int tata[M];
int rang[M];
void create(){
for(int i=1; i<=n; i++)
tata[i]=i, rang[i]=1;
}
int Find(int x){
int root = x;
for (root = x; tata[root] != root; root = tata[root]);
/// compresia caii
int aux;
while(tata[x] != x) {
aux = tata[x];
tata[x] = root;
x = aux;
}
return root;
}
void Union(int x, int y){
int rootx = Find(x);
int rooty = Find(y);
/// in acelasi arbore
if( rootx == rooty )
return;
int rangx = rang[x];
int rangy = rang[y];
/// punem arborele cu rang mai mic in cel cu rang mai mare
if( rang[x]<rang[y] ){
tata[x] = y;
} else {
if( rang[y]<rang[x] ){
tata[y] = x;
} else {
tata[x] = y;
rang[y]++;
}
}
}
int main()
{
in>>n;
int op;
in>>op;
create();
for(int i=1; i<=op; i++){
int cod, x, y;
in>>cod>>x>>y;
if(cod==1){
int rootx = Find(x);
int rooty = Find(y);
Union(rootx, rooty);
} else {
if( Find(x)==Find(y) )
out<<"DA"<<'\n';
else
out<<"NU"<<'\n';
}
}
return 0;
}