Cod sursa(job #2576159)

Utilizator betybety bety bety Data 6 martie 2020 17:39:46
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <fstream>
#define da "DA"
#define nu "NU"
using namespace std;
ifstream cin("disjoint.in");
ofstream cout("disjoint.out");
const int lim=1e5+3;
int link[lim],s[lim];
int supreme(int x)
{
    int r = x;
    while (x != link[x]) x = link[x];
    while(r != link[r]) r = link[r], link[r] = x;
    return x;
}
bool same(int a, int b)
{
    return supreme(a) == supreme(b);
}
void unite(int a, int b)
{
    a = supreme(a);
    b = supreme(b);
    if (s[a] < s[b]) swap(a,b);
    s[a] += s[b];
    link[b] = a;
}
int main()
{
    int n,m,op,x,y;
    bool okk;
    cin>>n>>m;
    for(int i=1; i<=n; ++i)
    {
        link[i]=i;
        s[i]=1;
    }
    for(int w=1; w<=m; ++w)
    {
        cin>>op>>x>>y;
        if(op==1)
            unite(x,y);
        else{
            okk=same(x,y);
            if(okk==1)
                cout<<da<<'\n';
            else cout<<nu<<'\n';
        }
    }
    return 0;
}