Cod sursa(job #2054725)

Utilizator Andreiii500Andrei Puiu Andreiii500 Data 2 noiembrie 2017 14:22:16
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.22 kb
#include<iostream>
#include<fstream>
using namespace std;

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

const int N = 100001;

int boss[N],n,m;

void update(int a, int b) /// Joins A and B's families
{
    while(a != boss[a]) a = boss[a];
    while(b != boss[b]) b = boss[b];

    boss[a] = boss[b];
}

int getBoss(int x)
{
    int stack[N], stackLength = 0;
    while(x = boss[x]) /// Haven't found the boss yet
    {
        stack[stackLength++] = x;
        x = boss[x];
    }
    for(int index=0; index<stackLength; ++i)
        boss[stack[index]] = boss[x]; /// Every visited node has its 'boss' updated to the X's boss = the biggest boss

    return x; /// Return the boss
}

void query(int a, int b)
{
    if(getBoss(a) == getBoss(b)) out<<"DA\n";
    else out<<"NU\n";
}

void afis()
{
    int i;
    for(i=1; i<=n; ++i) cout<<i<<" "; cout<<"\n";
    for(i=1; i<=n; ++i) cout<<boss[i]<<" "; cout<<"\n";
    cout<<"\n";
}

int main()
{
    in>>n>>m;
    for(int i=1; i<=n; ++i) boss[i] = i;
    for(int i=0; i<m; ++i)
    {
        int tip,x,y;
        in>>tip>>x>>y;
        if(tip == 1) update(x, y);
        else if(tip == 2) query(x, y);
    }

    return 0;
}