Cod sursa(job #2329771)

Utilizator victorv88Veltan Victor victorv88 Data 27 ianuarie 2019 13:59:08
Problema Paduri de multimi disjuncte Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb
#include <iostream>
#include <fstream>


using namespace std;

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

int n, m, father[100005], from, to, operatie, height[100005];

int find(int x)
{
    if (father[x]==x)
    {
        return x;
    }
    father[x]=find(father[x]);
    height[x]=height[father[x]];
    return father[x];
}

void unire(int from, int to)
{
    if (find(from)==find(to))
    {
        return;
    }
    if (height[from]<height[to])
    {
        swap(from,to);
    }
    father[to]=from;
    if (height[from]==height[to])
    {
        height[from]++;
    }
}

void cautare(int from, int to)
{
    if (find(from)==find(to))
    {
        g <<"DA\n";
        return;
    }
    g << "NU\n";
}

int main() {
    f >> n >> m;
    for (int i=1; i<=n; i++)
        father[i]=i;
    for (int i=1; i<=m; i++)
    {
        f >> operatie >> from >> to;
        if (operatie==1)
        {
            unire(from,to);
        } else
        {
            cautare(from,to);
        }
    }
    return 0;
}