Cod sursa(job #2970246)

Utilizator sandry24Grosu Alexandru sandry24 Data 24 ianuarie 2023 18:48:53
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <bits/stdc++.h>
using namespace std;
 
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pi;
#define pb push_back
#define mp make_pair
#define f first
#define s second

int parent[100001];
int size[100001];

void make_set(int x){
    size[x] = 1;
    parent[x] = x;
}

int find_set(int x){
    if(parent[x] == x)
        return x;
    return parent[x] = find_set(parent[x]);
}

void union_sets(int a, int b){
    a = find_set(a);
    b = find_set(b);
    if(a != b){
        if(size[a] < size[b])
            swap(a, b);
        size[a] += size[b];
        parent[b] = a;
    }
}
 
void solve(){
    int n, m;
    cin >> n >> m;
    for(int i = 1; i <= n; i++)
        make_set(i);
    for(int i = 0; i < m; i++){
        int t, x, y;
        cin >> t >> x >> y;
        if(t == 1){
            union_sets(x, y);
        } else {
            if(find_set(x) == find_set(y))
                cout << "DA\n";
            else
                cout << "NU\n";
        }
    }
}  
 
int main(){
    freopen("disjoint.in", "r", stdin);
    freopen("disjoint.out", "w", stdout);
    ios::sync_with_stdio(0); cin.tie(0);
    int t = 1;
    //cin >> t;
    while(t--){
        solve();
    }
}