Cod sursa(job #1462514)

Utilizator DrumeaVDrumea Vasile DrumeaV Data 18 iulie 2015 13:42:03
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.07 kb
#include <stdio.h>
#include <utility>

#define mp make_pair
#define st first
#define nd second

using namespace std;

const int Dim = 100005;

int N,M;
pair< int,int > S[Dim];

int Find(int Node)
{
    if (Node != S[Node].st)
             S[Node].st = Find(S[Node].st);

    return S[Node].st;
}

void Union(int X,int Y)
{
    if (S[X].nd > S[Y].nd)
        S[Y].st = X;
    else
        S[X].st = Y;

    if (S[X].nd == S[Y].nd)
        S[Y].nd++;
}

int main()
{
    freopen("disjoint.in","r",stdin);
    freopen("disjoint.out","w",stdout);

     scanf("%d%d",&N,&M);

     for (int i = 1;i <= N;i++)
        S[i] = mp(i,1);

     while(M--)
     {
         int Op,X,Y;

         scanf("%d %d %d",&Op,&X,&Y);

         int A = Find(X) , B = Find(Y);

         switch (Op)
         {
             case 1:
                      if (A != B)
                             Union(A,B);
                      break;
             case 2:
                      printf("%s",(A == B ? "DA\n" : "NU\n"));
         }
     }

    return 0;
}