Cod sursa(job #3342715)

Utilizator uncle_sam_007ioan bulik uncle_sam_007 Data 25 februarie 2026 13:53:40
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.14 kb
#include <fstream>

using namespace std;

ifstream fin("disjoint.in");
ofstream fout("disjoint.out");

const int NMAX = 100005;

int h[NMAX], p[NMAX];

int Find(int x){
    while(p[x] != x){
        x = p[x];
    }
    return x;
}

void Union(int x, int y){
    if(h[x] > h[y]){
        p[y] = x;
    }
    else{
        if(h[x] == h[y]){
            p[x] = y;
            h[y] ++;
        }
        else{
            p[x] = y;
        }
    }
}

void solve(){
    int n, m;
    fin >> n >> m;
    for(int i = 1; i <= n; ++i){
        h[i] = 1;
        p[i] = i;
    }
    for(int i = 1; i <= m; ++i){
        int type, x, y;
        int rootX, rootY;
        fin >> type >> x >> y;
        if(type == 1){
            rootX = Find(x);
            rootY = Find(y);
            Union(rootX, rootY);
        }
        else{
            rootX = Find(x);
            rootY = Find(y);
            if(rootX == rootY){
                fout << "DA";
            }
            else{
                fout << "NU";
            }
            fout << "\n";
        }
    }
}

int main()
{
    solve();
    return 0;
}