Cod sursa(job #3192237)

Utilizator Vlad_NistorNIstor Vlad Vlad_Nistor Data 11 ianuarie 2024 20:44:17
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.01 kb
#pragma GCC optimize("unroll-loops")
#include <fstream>
using namespace std;
#define NMAX 100001

int tatic[NMAX], len[NMAX];

int getRoot(int node){
    if(tatic[node] == node)return node;
    else return getRoot(tatic[node]);
}
void uniteTrees(int left, int right){
    int x = getRoot(left), y = getRoot(right);
    if(len[x] > len[y]){
        swap(x,y);
    }
    tatic[x] = y;
    len[y] += len[x];
}


int main(void){
    ofstream cout("disjoint.out");
    ifstream cin("disjoint.in");
    int n, Q;
    cin >> n >> Q;
    for(int i = 1;i<=n;i++){
        tatic[i] = i;
        len[i] = 1;
    }
    while(Q--){
        int x,y,z;
        cin >> x >> y >> z;
        if(x == 1){
            /// we need to unite y, z
            uniteTrees(y,z);
        }else{
            int root1 = getRoot(y), root2 = getRoot(z);
            if(root1 == root2)cout << "DA" << '\n'; /// apartine aceluiasi arbore avand acelasi tatic
            else cout << "NU" << '\n'; /// e negru
        }
    }
}