Cod sursa(job #1793573)

Utilizator Firealex2Rotileanu Alexandru Firealex2 Data 31 octombrie 2016 10:44:38
Problema Paduri de multimi disjuncte Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include <fstream>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <string>
#include <map>

using namespace std;

ifstream fi("disjoint.in");
ofstream fo("disjoint.out");

const int maxn = 100000;

struct node{
    int data, rang;
    node* father;
};

node* v[maxn];

int M,N;

void init();
void UNION(node* a, node* b);
node* FIND(node* a);
void solve();


int main()
{
    init();
    solve();
    return 0;
}

void init()
{
    fi>>N>>M;
    for(int i=1;i<=N;i++)
    {
        node* a = new node;
        a->data = i;
        a->father = NULL;
        a->rang=0;
        v[i] = a;
    }
    return;
}

void solve()
{
    for(int i=1;i<=M;i++)
    {
        int q,x,y;
        fi>>q>>x>>y;
        if(q==1)
            UNION(v[x],v[y]);
        else
        {
            if(FIND(v[x]) == FIND(v[y]))
                fo<<"DA\n";
            else fo<<"NU\n";
        }
    }
    return;
}

void UNION(node* a, node* b)
{
    if(a->rang > b->rang)
    {
        while(b->father != NULL)
            b=b->father;
        v[b->data]->father = a;
    }
    else if(b->rang > a->rang)
    {
        while(a->father != NULL)
            a=a->father;
        v[a->data]->father = b;
    }
    else
    {
        while(b->father != NULL)
            b=b->father;
        v[b->data]->father = a;
        v[a->data]->rang++;
    }
}

node* FIND(node* a)
{
    node* n = v[a->data];
    if(n->father!=NULL)
        n->father = FIND(n->father);
    else if(n->father ==NULL)
        return n;
    return n->father;
}