Cod sursa(job #2757751)

Utilizator lahayonTester lahayon Data 6 iunie 2021 12:53:07
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <vector>
#include <fstream>

using namespace std;
	
int find_compress(int x, vector<int>& forest){

    // tree compression
    int root = x;
    while(forest[root] != root)
        root = forest[root];

    while(forest[x] != root){
        forest[forest[x]] = root;
        x = forest[x];
    }

    return root;
}
 
int find_halve(int x, vector<int>& forest){

    while(forest[x] != x){
        forest[x] = forest[forest[x]];
        x = forest[x];
    }
    return x;
}
	
void reunion(int x, int y, vector<int>& forest, vector<int>& sizes){

    x = find_compress(x, forest);
    y = find_compress(y, forest);
    if(x == y)
        return;
    if(sizes[x] < sizes[y])
        x = x + y - (y = x);
    forest[y] = x;
    sizes[x] += sizes[y];
}

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

    int N, M;
    cin >> N >> M;
    vector<int> forest(N, 0);
    vector<int> sizes(N, 1);
    for(int i = 0; i < N; ++i)
        forest[i] = i;
  

    int op, x, y;

    for(; M > 0; M--){

        cin >> op >> x >> y;
        switch (op)
        {
        case 1:
            reunion(--x, --y, forest, sizes);
            break;
        case 2:
            if(find_compress(--x, forest) == find_compress(--y, forest))
                cout << "DA" << "\n";
            else cout << "NU" << "\n";
            break;
        default:
            break;
        }
    }
  
  return 0;
	
}