Cod sursa(job #2329166)

Utilizator victorv88Veltan Victor victorv88 Data 26 ianuarie 2019 13:52:22
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.89 kb
#include <iostream>
#include <fstream>


using namespace std;

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

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

void reunire(int m1, int m2)
{
    if (father[m2]==m2)
    {
        father[m2]=m1;
        return;
    }
    reunire(m1,father[m2]);
    father[m2]=father[father[m2]];
}

int cautare(int m)
{
    if (father[m]==m)
    {
        return m;
    }
    int val=cautare(father[m]);
    father[m]=val;
    return father[m];
}

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)
        {
            reunire(from,to);
        }
        else
        {
            if (cautare(from)==cautare(to))
            {
                g << "DA\n";
            }
            else
                g << "NU\n";
        }
    }
    return 0;
}