Cod sursa(job #2603751)

Utilizator MihclerioVladimir Chim Mihclerio Data 20 aprilie 2020 19:43:39
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.73 kb
#include <bits/stdc++.h>

const int nmax=1e5+3;
const int inf=2e9+3;

using namespace std;

int p[nmax];

void baga(int x)
{
  p[x]=x;
}

int cauta(int x)
{
  if(x==p[x]) return x;
  return p[x]=cauta(p[x]);
}

void leaga(int a,int b)
{
  a=cauta(a);
  b=cauta(b);
  if(a!=b) p[b]=a;
}

int main()
{
    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    freopen("disjoint.in","r",stdin);
    freopen("disjoint.out","w",stdout);

    int n,k;
    cin>>n>>k;
    for(int i=1;i<=n;i++) baga(i);
    while(k--)
    {
      int k,a,b;
      cin>>k>>a>>b;
      if(k==1)
      {
        leaga(a,b);
      } else
      {
        if(cauta(a)==cauta(b)) cout<<"DA\n"; else cout<<"NU\n";
      }
    }

}