Cod sursa(job #2527032)

Utilizator CharacterMeCharacter Me CharacterMe Data 19 ianuarie 2020 15:25:29
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <bits/stdc++.h>
std::ifstream fin("disjoint.in");
std::ofstream fout("disjoint.out");
int n, m;
int head[100005], height[100005];
void solve1(int node1, int node2);
void solve2(int node1, int node2);
int find_root(int node);
void change_head(int node, int root);
int main()
{
    fin>>n>>m;
    for(int i=1; i<=n; ++i){
        head[i]=i;
        height[i]=1;
    }
    for(int i=1; i<=m; ++i){
        int task, x, y;
        fin>>task>>x>>y;
        if(task==1) solve1(x, y);
        else solve2(x, y);
    }
    return 0;
}
void solve1(int node1, int node2){
    int root1, root2;
    root1=find_root(node1);
    root2=find_root(node2);
    change_head(node1, root1);
    change_head(node2, root2);
    if(height[root1]>height[root2]) head[root2]=root1;
    else if(height[root1]<height[root2]) head[root1]=head[root2];
    else{
        head[root1]=head[root2];
        ++height[root2];
    }
}
void solve2(int node1, int node2){
    int root1, root2;
    root1=find_root(node1);
    root2=find_root(node2);
    change_head(node1, root1);
    change_head(node2, root2);
    if(root1==root2) fout<<"DA\n";
    else fout<<"NU\n";
}
int find_root(int node){
    while(head[node]!=node) node=head[node];
    return node;
}
void change_head(int node, int root){
    while(head[node]!=node) {
        int next=head[node];
        head[node]=root;
        node=next;
    }
}