Pagini recente » Cod sursa (job #2724317) | Cod sursa (job #1480180) | Cod sursa (job #2193119) | Cod sursa (job #3273189) | Cod sursa (job #1206620)
#include <fstream>
using namespace std;
void join(int x, int y, int dad[],int harb[] ) {
int xup,yup,sw; // xup,yup <- roots of their respective trees
xup=x;
yup=y;
while(dad[xup]!=xup) //Find X root
xup=dad[xup];
/*while (dad[x]!=xup) { //Join X and ancestors to root
sw=x;
x=dad[x];
dad[sw]=xup;
}*/
while(dad[yup]!=yup) //Find Y root
yup=dad[yup];
/*while (dad[y]!=yup) { //Join Y and ancestors to root
sw=y;
y=dad[y];
dad[sw]=yup;
}*/
if (harb[xup]<harb[yup]) //Join smaller tree (sorted by height upper bound) to the larger
dad[xup]=yup;
else
dad[yup]=xup;
if (harb[xup]==harb[yup]) //If they are equal, after they are joined the height upper bound increases by 1
harb[yup]++;
}
int query(int x, int y, int dad[], int harb[]) {
int xup,yup,sw;
xup=x;
yup=y;
while(dad[xup]!=xup) //Find X root
xup=dad[xup];
while (dad[x]!=xup) { //Join X and ancestors to root
sw=x;
x=dad[x];
dad[sw]=xup;
}
while(dad[yup]!=yup) //Find Y root
yup=dad[yup];
while (dad[y]!=yup) { //Join Y and ancestors to root
sw=y;
y=dad[y];
dad[sw]=yup;
}
if (xup==yup)
return 1;
else
return 0;
}
int main() {
int dad[100001],harb[100001],i,x,y,opt,ans,n,m; //harb is height of the tree
ifstream in("disjoint.in");
ofstream out("disjoint.out");
in>>n>>m;
for (i=1; i<=n; i++) {
dad[i]=i;
harb[i]=1;
}
for (i=1; i<=m; i++) {
in>>opt>>x>>y;
if (opt==1)
join(x,y,dad,harb);
else if (opt==2) {
ans=query(x,y,dad,harb);
if (ans)
out<<"DA"<<'\n';
else
out<<"NU"<<'\n';
}
}
in.close();
out.close();
return 0;
}