Cod sursa(job #2447597)

Utilizator mihneacazCazacu Mihnea mihneacaz Data 13 august 2019 21:24:22
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <fstream>

using namespace std;

const int NMAX=100005;

int father[NMAX],height[NMAX];

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

namespace actions
{
    int search (int element)
    {
        int aux = element;
        while(father[element] != element)
            element = father[element];
        while(father[aux] != aux)
        {
            int aux2 = father[aux];
            father[aux] = element;
            aux = aux2;
        }
        return element;
    }
    void unite (int first, int second)
    {
        first=search(first);
        second=search(second);
        if(first==second)
            return ;
        if(height[first] > height[second])
            father[second] = first;
        else
        {
            father[first] = second;
            if(height[first] == height[second])
                height[first]++;
        }

    }
    void print (int first, int second)
    {
        if(search(first)==search(second))
            cout<<"DA\n";
        else
            cout<<"NU\n";
    }
}
int main()
{
    int n,m;
    cin>>n>>m;
    for(int i=1; i<=n; ++i)
        father[i] = i;
    for(int i=1; i<=m; ++i)
    {
        int op,x,y;
        cin>>op>>x>>y;
        if(op == 1)
            actions :: unite(x,y);
        else
            actions :: print(x,y);
    }
    return 0;
}