Pagini recente » Cod sursa (job #3136733) | Cod sursa (job #90997) | Cod sursa (job #2096828) | Cod sursa (job #3260477) | Cod sursa (job #2635819)
#include <iostream>
#include <fstream>
#define DIM 100005
using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");
int t[DIM],rang[DIM],n,m;
int radacina(int nod){
if(t[nod] == 0)
return nod;
else{ //derecursivitate - leaga toti descendentii radacinii de radacina
int x = radacina(t[nod]);
t[nod] = x;
return x;
}
}
void op1(int x, int y){ // "uniune" - reuniunea multimilor cu repr. rx si ry, in functie de rang
int rx = radacina(x), ry=radacina(y);
if(rang[rx]>rang[ry])
t[ry]=rx;
else{
t[rx]=ry;
if(rang[rx]==rang[ry])
rang[ry]++;
}
}
void op2(int x, int y){//check if x and y belong to the same set
int rx=radacina(x), ry=radacina(y);
if(rx==ry)
g<<"DA\n";
else
g<<"NU\n";
}
int main()
{
f>>n>>m;
int op,x,y;
for(int k=1; k<=m; k++){
f>>op>>x>>y;
if(op==1)
op1(x,y);
else
op2(x,y);
}
}