Cod sursa(job #1125278)

Utilizator petiVass Peter peti Data 26 februarie 2014 16:41:54
Problema Paduri de multimi disjuncte Scor 100
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[ir].p=jr;
    else if(ir>jr)
        v[jr].p=ir;
    else{
        v[jr].p=ir;
        v[jr].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(f(x)==f(y))
                ofs<<"DA\n";
            else ofs<<"NU\n";
        }
    }
}