Cod sursa(job #1374191)

Utilizator FapFapAdriana FapFap Data 4 martie 2015 23:47:07
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.85 kb
#include <iostream>
#include <fstream>
#define nmax 100005
using namespace std;

ifstream fin ("disjoint.in");
ofstream fout ("disjoint.out");

int n, m;
int v[nmax];

void merge_elements(int x, int y){
    if(v[x] > v[y]){
        v[y]+= v[x];
        v[x]= y;
    }
    else{
        v[x]+= v[y];
        v[y]= x;
    }
}

int find_repr(int x){
    if(v[x]<0)  return x;
    v[x]= find_repr(v[x]);
    return v[x];
}

int main(){
    int x, y, op;
    fin.sync_with_stdio(false);
    fin >> n >> m;
    for(int i=1; i<=n; i++) v[i]= -1;

    for(int i=1; i<=m; i++){
        fin >> op >> x >> y;
        int node1= find_repr(x);
        int node2= find_repr(y);
        if(op==1)   merge_elements(node1, node2);
        else if(node1==node2 && op==2)  fout << "DA\n";
        else    fout << "NU\n";
    }

    return 0;
}