Cod sursa(job #2628755)

Utilizator marius004scarlat marius marius004 Data 17 iunie 2020 12:44:22
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

ifstream f("disjoint.in");
ofstream g("disjoint.out");

class DisjointSet {
    
private:
    
    vector<int>parent;
    
public:
    
    DisjointSet(const int& size) {
        parent.resize(size + 1,-1);
    }
    
    void collapse(int node, int root) {
       while(node != root) {
           int aux = parent[node];
           parent[node] = root;
           node = aux;
       }
    }
    
    int _find(int node) {
        
        int root = node;
        
        while(parent[root] > 0)
            root = parent[root];
        
        collapse(node,root);
        
        return root;
    }
    
    void _union(int x,int y) {
        parent[y] = x;
    }
};

int n, m, type, x, y;

int main() {
    
    f >> n >> m;
    
    DisjointSet disjoint(n);
    
    while(m--) {
        
        f >> type >> x >> y;
        
        if(type == 1) {
            disjoint._union(x,y);
        } else {
            int rootX = disjoint._find(x);
            int rootY = disjoint._find(y);
            g << (rootX == rootY ? "DA" : "NU") << '\n';
        }
        
    }
    
    return 0;
}