Cod sursa(job #2421095)

Utilizator ToniBAntonia Biro ToniB Data 14 mai 2019 11:23:17
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.49 kb
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;

ofstream out("disjoint.out");

struct padure
{
    int n;
     vector<int> tat;
    vector<int> rang;

    padure(int a): n(a), tat(a+1), rang(a+1, 1)
    {
        for(int i = 1; i <= n; ++i)
            tat[i] = i;
    }

    int find_tat(int nod)
    {
        if(tat[nod] == nod)
            return nod;
        else
        {
            int tata = find_tat(tat[nod]);
            tat[nod] = tata;
            return tata;
        }
    }

    void find_r(int x, int y)
    {
        if(find_tat(x) == find_tat(y))
            out << "DA";
        else
            out << "NU";
        out << "\n";
    }

    void union_nod(int x, int y)
    {
        int tx = find_tat(x);
        int ty = find_tat(y);
        if(rang[tx] < rang[ty])
        {
            tat[tx] = ty;
            rang[ty] += rang[tx];
        }
        else
        {
            tat[ty] = tx;
            rang[tx] += rang[ty];
        }
    }

    void afis()
    {
        for(int i = 0; i < n; ++i)
            cout << tat[i] << ' ';
        cout << endl;
    }

};


int main()
{
    ifstream in("disjoint.in");

    int n, m, b, x, y;

    in >> n >> m;
    padure P(n);
    for(int i = 0; i < m; ++i)
    {
        in >> b >> x >> y;
        if(b == 1)
            P.union_nod(x, y);
        if(b == 2)
            P.find_r(x, y);
    }


    in.close();
    out.close();
}