Cod sursa(job #2695848)

Utilizator stanbianca611Stan Bianca stanbianca611 Data 14 ianuarie 2021 18:24:07
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <fstream>
#include <bits/stdc++.h>
using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");

const int NMAX = 100001;
int n,m;
int reprez[NMAX];
int componenta[NMAX];

int find_reprez(int node)
{
    if (node == reprez[node])
    {
        return node;
    }
    int nreprez = find_reprez(reprez[node]);
    reprez[node] = nreprez;
    return nreprez;
}

int main()
{
    f >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        reprez[i] = i;
        componenta[i] = 1;
    }
    for (int i = 1; i <= m; i++)
    {
        int opt, x, y;
        f >> opt >> x >> y;
        int reprez_x = find_reprez(x);
        int reprez_y = find_reprez(y);
        if (opt == 1)
        {
            if (reprez_x == reprez_y)
                continue;
            if (componenta[reprez_x] > componenta[reprez_y])
            {
                reprez[reprez_y] = reprez_x;
                componenta[reprez_x] += componenta[y];
            }
            else
            {
                reprez[reprez_x] = reprez_y;
                componenta[reprez_y] += componenta[reprez_y];
            }
        }
        else
        {
            if (reprez_x == reprez_y)
            {
                g << "DA\n";
            }
            else
            {
                g << "NU\n";
            }
        }
    }
    return 0;
}