Cod sursa(job #1506352)

Utilizator superstar1998Moldoveanu Vlad superstar1998 Data 20 octombrie 2015 15:25:06
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 0.81 kb
#include <fstream>

using namespace std;
int n,m,o,x,y,t[100001],h[100001],c;
ifstream f("disjoint.in");
ofstream g("disjoint.out");
int main()
{
    f>>n>>m;
    for(int i=1;i<=n;i++)
        h[i]=1,t[i]=i;
    for(int i=1;i<=m;i++)
    {
        f>>o>>x>>y;
        int r1=x;
        int r2=y;
        while(r1!=t[r1])r1=t[r1];
        while(r2!=t[r2])r2=t[r2];
        if(o==1)
        {
            if(h[r1]>h[r2]) t[r2]=r1,c=r1;
            else t[r1]=r2,c=r2;
            if(h[r1]==h[r2])h[c]++;
        }
        else
        {
            int x1,x2;
            if(r1==r2) g<<"DA"<<endl;
            else g<<"NU"<<endl;
            while(t[x]!=r1)x1=t[x],t[x]=t[x1],x=x1;
            while(t[y]!=r2)x2=t[y],t[y]=t[x2],y=x2;
        }
    }
    f.close();
    g.close();
    return 0;
}