Cod sursa(job #2329156)

Utilizator victorv88Veltan Victor victorv88 Data 26 ianuarie 2019 13:40:16
Problema Paduri de multimi disjuncte Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 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]];
}

void cautare(int m1, int m2)
{
    while (father[m1]!=m1)
        m1=father[m1];
    while (father[m2]!=m2)
        m2=father[m2];
    if (m2==m1)
        g << "DA\n";
    else
        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)
        {
            reunire(from,to);
        }
        else
        {
            cautare(from,to);
        }
    }
    return 0;
}