Cod sursa(job #2747801)

Utilizator CronosClausCarare Claudiu CronosClaus Data 29 aprilie 2021 17:41:13
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.82 kb
#include <bits/stdc++.h>

using namespace std;

const int mxn = 100 * 1000 + 10;

int n, m;

int p[ mxn ];

int highest(int x){
    if(p[ x ] != x){
        p[ x ] = highest(p[ x ]);
    }
    return p[ x ];
}

int unite(int x, int y){
    int px = highest( x );
    p[ highest( y ) ] = px;
    highest( y );
}

bool sameForest(int x, int y){
    return highest( x ) == highest( y );
}

int main()
{
    ifstream cin("disjoint.in");
    ofstream cout("disjoint.out");
    cin>> n >> m;

    for(int i = 1; i <= n; i++){
        p[ i ] = i;
    }

    for(int i = 0, cer, x, y; i < m; i++){
        cin>> cer >> x >> y;
        if(cer == 1){
            unite(x, y);
        }
        else if(cer == 2){
            cout<< (sameForest(x, y) ? "DA\n" : "NU\n");
        }
    }

    return 0;
}