Pagini recente » Cod sursa (job #1100824) | Cod sursa (job #1099025) | Cod sursa (job #2141637) | Cod sursa (job #2434485) | Cod sursa (job #3190047)
#include <iostream>
#include <fstream>
#define MAX 100002
using namespace std;
int n,m,tip,x,y,t[MAX];
/// t[x] = -k, nr de noduri al arborelui cu radacina x
/// j, unde j este tatal lui x
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
int get_root(int x){
int aux = x;
while(t[x] > 0){
x = t[x];
}
int root = x;
x = aux;
/// comprimam drumul
while(x != root){
aux = t[x];
t[x] = root;
x = aux;
}
return root;
}
void join(int x, int y){
int root_x = get_root(x);
int root_y = get_root(y);
if(root_x == root_y){
/// sunt deja in aceasi multime
return;
}
if(t[root_x] <= t[root_y]){
/// x are mai multe noduri decat y | => punem arborele y in x
/// pentru ca numerele sunt negative | (cel mic in cel mare)
t[root_x] += t[root_y]; /// schimbam nr de noduri
t[root_y] = root_x;
}else{
/// y are mai multe noduri decat x => punem x in y
t[root_y] += t[root_x];
t[root_x] = root_y;
}
}
int query(int x, int y){
return (get_root(x) == get_root(y));
}
int main()
{
fin >> n >> m;
for(int i = 1; i <= m; i++){
fin >> tip >> x >> y;
if(tip == 1){
join(x, y);
}else{
fout << ((query(x, y) == 1) ? "DA\n" : "NU\n");
}
}
return 0;
}