Cod sursa(job #2643008)

Utilizator AndreiDeltaBalanici Andrei Daniel AndreiDelta Data 18 august 2020 11:18:58
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.81 kb
#include <bits/stdc++.h>
#define pb push_back
using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");
typedef long long ll;
const int dim=1e5+3;
int t,T;
int n,m,tata[dim],niv[dim],cod,xx,yy;

void Union(int x,int y) //regula de ponderare
{
    if(niv[x]>niv[y]) tata[y]=x;
    else
    {
        tata[x]=y;
        if(niv[x]==niv[y]) niv[y]++;
    }
}

int Find(int val) //regula de compresie
{
    int r=val;
    while(tata[r]) r=tata[r];
    int y=val;
    while(y!=r)
    {
        int t=tata[y];
        tata[y]=r;
        y=t;
    }
    return r;
}

int main()
{
    f>>n>>m;
    for(int i=1;i<=m;i++)
    {
        f>>cod>>xx>>yy;
        if(cod==1) Union(Find(xx),Find(yy));
        else g<<( ( Find(xx)==Find(yy) )?"DA":"NU" )<<'\n';;
    }

    return 0;
}