Cod sursa(job #2418753)

Utilizator zsraduZamfir Radu zsradu Data 6 mai 2019 09:51:24
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");
int n,m,i;
int v[100003];
void unite(int x,int y)
{
    int cx=x,cy=y,hx=0,hy=0,tatax,tatay;
    while(v[cx]!=cx)
    {
        hx++;
        cx=v[cx];
    }
    tatax=cx;
    while(v[cy]!=cy)
    {
        hy++;
        cy=v[cy];
    }
    tatay=cy;
    if(hx<hy)///lipim y la x
        v[tatay]=tatax;
    else v[tatax]=tatay;
}
void afis(int x,int y)
{
    int cx=x,cy=y,tatax,tatay;
    while(v[cx]!=cx)
    {
        cx=v[cx];
    }
    tatax=cx;
    while(v[cy]!=cy)
    {
        cy=v[cy];
    }
    tatay=cy;
    if(tatax==tatay)g<<"DA"<<'\n';
    else g<<"NU"<<'\n';
    cx=x;cy=y;
    while(v[cx]!=cx)
    {
        int prevcx=cx;
        cx=v[cx];
        v[prevcx]=tatax;
    }
    while(v[cy]!=cy)
    {
        int prevcy=cy;
        cy=v[cy];
        v[prevcy]=tatay;
    }
    return;
}
int main()
{
    f>>n>>m;
    for(i=1;i<=n;i++)
        v[i]=i;
    for(i=1;i<=m;i++)
    {
        int op,x,y;
        f>>op>>x>>y;
        if(op==1)
            unite(x,y);
        else afis(x,y);
    }
}