Cod sursa(job #2977594)

Utilizator andreipirjol5Andrei Pirjol andreipirjol5 Data 11 februarie 2023 21:49:34
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <iostream>

using namespace std;
FILE *fin, *fout;

const int NMAX = 1e5;
int father[NMAX + 5], depth[NMAX + 5];

int findrt(int node)
{
    if(node == father[node])
        return node;

    return father[node] = findrt(father[node]);
}

void update(int x, int y)
{
    int root1 = findrt(x), root2 = findrt(y);

    if(root1 == root2)
        return;

    if(depth[root1] < depth[root2])
    {
        father[root1] = root2;
    }
    else if(depth[root1] > depth[root2])
    {
        father[root2] = root1;
    }
    else if(depth[root1] == depth[root2])
    {
        depth[root1]++;
        father[root2] = root1;
    }
}

void query(int x, int y)
{
    int root1 = findrt(x), root2 = findrt(y);

    if(root1 == root2)
        fprintf(fout, "DA\n");
    else fprintf(fout, "NU\n");
}

int main()
{
    fin = fopen("disjoint.in", "r");
    fout = fopen("disjoint.out", "w");

    int n, m;
    fscanf(fin, "%d%d", &n, &m);

    for(int i = 1; i <= n; i++)
        father[i] = i;

    for(int test = 1; test <= m; test++)
    {
        int op, x, y;
        fscanf(fin, "%d%d%d", &op, &x, &y);

        if(op == 1)
            update(x, y);
        else if(op == 2)
            query(x, y);
    }

    fclose(fin);
    fclose(fout);
    return 0;
}