Cod sursa(job #959819)

Utilizator cousin.batmanVaru Batman cousin.batman Data 8 iunie 2013 22:12:56
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 kb
#include<fstream>
#include<set>
#include<list>
#include<vector>

using namespace std;
struct node{
    node *parent;
    set<node*> children;
    int height;

    node():parent(NULL), height(1){}
};

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;
}