Cod sursa(job #2491561)

Utilizator Marius05Voina Marius Marius05 Data 12 noiembrie 2019 19:18:48
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.93 kb
#include <fstream>
#include <vector>

using namespace std;

struct PADURE
{
    int t,h;
};

vector <PADURE> v;

int varf(int x)
{
    while (x!=v[x].t)
        x=v[x].t;
    return x;
}

void unire(int x,int y)
{
    if (v[x].h==v[y].h)
    {
        v[x].h++;
        v[y].t=x;
    }
    else
    {
        if (v[x].h>v[y].h)
            v[y].t=x;
        else
            v[x].t=y;
    }
}

int main()
{
    ifstream fin ("disjoint.in");
    ofstream fout ("disjoint.out");
    PADURE temp;
    temp.h=1;
    int n,m,c,x,y;
    fin>>n>>m;
    for (int i=0; i<=n; i++)
    {
        temp.t=i;
        v.push_back(temp);
    }
    for (int i=1; i<=m; i++)
    {
        fin>>c>>x>>y;
        if (c==1)
            if (varf(x)!=varf(y))
                unire(x,y);
        if (c==2)
            fout<<(varf(x)==varf(y)?"DA\n":"NU\n");
    }
    fin.close();
    fout.close();
    return 0;
}