Cod sursa(job #1124953)

Utilizator petiVass Peter peti Data 26 februarie 2014 14:45:17
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 0.89 kb
/*VASS PETER LTC 2014-02-26*/
#include <fstream>
#include <vector>
using namespace std;

struct element{int r,p;};

vector<element> v;

void m(int i){
    v[i].r=0;
    v[i].p=i;
}

int f(int i){
    if(v[i].p!=i)
        v[i].p=f(v[i].p);
    return v[i].p;
}

void u(int i,int j){
    int ir=f(i);
    int jr=f(j);

    if(ir<jr)
        v[i].p=jr;
    else if(ir>jr)
        v[j].p=ir;
    else{
        v[j].p=ir;
        v[j].r+=1;
    }
}

int main(){
    ifstream ifs("disjoint.in");
    ofstream ofs("disjoint.out");
    int N,M;
    ifs>>N>>M;
    v.resize(N);
    for(int i=0;i<N;i++)
        m(i);

    for(int i=0;i<M;i++){
        int x,y,o;
        ifs>>o>>x>>y; x--; y--;
        if(1==o)
            u(x,y);
        else if(2==o){
            if(v[x].p==v[y].p)
                ofs<<"DA\n";
            else ofs<<"NU\n";
        }
    }
}