Cod sursa(job #2565686)

Utilizator baltoi.teodorTeodor Baltoi baltoi.teodor Data 2 martie 2020 16:06:12
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <bits/stdc++.h>
#define ff first
#define ss second
#define NMAX 100020
#define pb push_back
using namespace std;
const string file = "disjoint";

ifstream fin (file+".in");
ofstream fout (file+".out");
typedef long long ll;
typedef long double ld;

const ll INF = 9223372036854775807ll;
const int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1}, inf = 2147483647;

int gr[NMAX], len[NMAX]; // din ce grupa e fiec nod, inaltimea arborelui
void reunion(int x, int y) ;
int findit(int x);
int N,M,t;
int main()
{
    int x,y;
    fin >> N >> M;
    for(int i=1;i<=N;++i) gr[i]=i, len[i]=1;
    for(int i=1;i<=M;++i)
    {
        fin >> t >> x >> y;
        if(t==1)
        {
            reunion(x,y);
        }
        else{
            if(findit(x) == findit(y)) fout<<"DA\n";
            else fout<<"NU\n";
        }
    }
    return 0;
}
void reunion(int x, int y)
{
    if(len[x] > len[y])
        gr[y]=gr[x];
    else gr[x]=gr[y];
    if(len[x]==len[y]) len[y]++;
}
int findit(int x)
{
    int R,y;
    R=x;
    while(R!=gr[R])
        R=gr[R];
    y=x;
    while(y!=R)
    {
        int aux=gr[y];
        gr[y]=R;
        y=aux;
    }
    return R;
}