Cod sursa(job #2713845)

Utilizator Botnaru_VictorBotnaru Victor Botnaru_Victor Data 28 februarie 2021 19:08:02
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.88 kb
#include <bits/stdc++.h>

#define nmax 100000

using namespace std;

int p[nmax];
int n,m;

void update(int x, int y, int t)
{
    vector<int> stiva;
    int sx=0,sy=0;
    while(p[x]!=0) {stiva.push_back(x); x=p[x];}
    sx=stiva.size();
    while(!stiva.empty()) {p[stiva.back()]=x;stiva.pop_back();}

    while(p[y]!=0) {stiva.push_back(y); y=p[y];}
    sy=stiva.size();
    while(!stiva.empty()) {p[stiva.back()]=y;stiva.pop_back();}

    if(t==1&&x!=y)
    {
        if(sx<sy) p[x]=y;
        else p[y]=x;
    }
    if(t==2)
    {
        if(x==y) printf("DA \n");
        else printf("NU \n");
    }
}

int main()
{
    freopen("disjoint.in","r",stdin);
    freopen("disjoint.out","w",stdout);

    scanf("%i %i",&n,&m);
    for(int i=0;i<m;i++)
    {
        int x,y,t;
        scanf("%i %i %i",&t,&x,&y);
        update(x,y,t);
    }
    return 0;
}