Cod sursa(job #2945089)

Utilizator handicapatucavasi eduard handicapatu Data 23 noiembrie 2022 14:14:39
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <iostream>
#include <fstream>

using namespace std;

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

int n , m , type , x , y;
int t[100001];
int weight[100001];

int root(int x){
    if(t[x] == x)
        return x;
    else
        t[x] = root(t[x]);
        return t[x];
}

void unite(int x , int y){
    int root_x = root(x);
    int root_y = root(y);
    if(root_x != root_y){
        if(weight[root_x] > weight[root_y]){
            t[root_y] = root_x;
            weight[root_x] += weight[root_y];
        }
        else{
            t[root_x] = root_y;
            weight[root_y] += weight[root_x];
        }
    }
}

void query(int x , int y){
    int root_x = root(x);
    int root_y = root(y);
    if(root_x == root_y)
        g << "DA" << "\n";
    else g << "NU" << "\n";
}

int main()
{
    f >> n >> m;
    for(int i = 1 ; i <= n ; ++i)
        t[i] = i;
    for(int i = 1 ; i <= m ; ++i){
        f >> type >> x >> y;
        if(type == 1)
            unite(x , y);
        else if(type == 2)
            query(x , y);
    }
    return 0;
}