Cod sursa(job #1394379)

Utilizator tweetyMarinescu Ion tweety Data 20 martie 2015 11:49:14
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.12 kb
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;

ifstream in("disjoint.in");
ofstream out("disjoint.out");

int N;
int M;
int* sef;

int find(int x)
{
    if (x != sef[x])
       return (sef[x] = find(sef[x]));
       
    return x;   
}

void Unite(int x, int y)
{
     int tx = find(x);
     int ty = find(y);
     
     sef[tx] = ty;
}

bool sameTree(int x, int y)
{
     return find(x) == find(y);
}

void readData()
{
     in >> N >> M;
     sef = new int[N + 1];
     
     for (int i = 1; i <= N; ++i)
         sef[i] = i;
     
     for (int cod, x, y, i = 1; i <= M; ++i)
     {   
         in >> cod >> x >> y;
         
         switch (cod)
         {
             case 1:
             {
                 Unite(x, y);
                 break;
             }
             
             case 2:
             {
                 sameTree(x, y) ? out << "DA\n" : out << "NU\n";
                 break;
             }
         }
     }
}

int main(int argc, char *argv[])
{
    readData();
    
    system("PAUSE");
    return EXIT_SUCCESS;
}