Pagini recente » Cod sursa (job #1070592) | Cod sursa (job #267483) | Cod sursa (job #2610632) | Cod sursa (job #2207900) | Cod sursa (job #959817)
Cod sursa(job #959817)
#include<fstream>
#include<set>
#include<list>
#include<vector>
using namespace std;
struct node{
node *parent;
set<node*> children;
int height;
};
void join(node* a, node* b){
node *x, *y;
x=a, y=b;
if(a->height < b->height)
x=b, y=a;
if(y->parent != NULL)
y->parent->children.erase(y);
y->parent = x;
x->children.insert(y);
if(x->height==y->height)
x->height++;
}
bool check(node *a, node *b){
node *pa, *pb;
list<node*> la, lb;
for(pa=a; pa->parent; pa=pa->parent)
la.push_back(pa);
for(auto it=la.begin(); it!=la.end() && *it!=pa; ++it)
(*it)->parent->children.erase(*it), (*it)->parent=pa, pa->children.insert(*it);
for(pb=b; pb->parent; pb=pb->parent)
lb.push_back(pb);
for(auto it=lb.begin(); it!=lb.end() && *it!=pb; ++it)
(*it)->parent->children.erase(*it), (*it)->parent=pb, pb->children.insert(*it);
return pa==pb?true:false;
}
int main(){
int i, n, m, op, x, y;
freopen("disjoint.in", "rt", stdin);
freopen("disjoint.out", "wt", stdout);
scanf("%d %d",&n ,&m);
vector<node> v(n+1);
for(i=0; i<m; i++){
scanf("%d %d %d", &op, &x, &y);
if(op==1)
join(&v[x], &v[y]);
else
printf("%s\n", check(&v[x], &v[y])?"DA":"NU");
}
fclose(stdin);
fclose(stdout);
return 0;
}