Cod sursa(job #229341)

Utilizator alex23alexandru andronache alex23 Data 9 decembrie 2008 22:10:10
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.22 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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


vector<int> arbore, rang;
int n, m;

int find (int x)
 {
    int aux = x;
    while (arbore[aux] != aux)
        {aux = arbore[aux];
        }
    
    while (arbore[x] != x)
        {x = arbore[x];
         arbore[x] = aux;
        }
        
    return aux;
 } 

void uniune(int x, int y)
 {
     if (rang[x] < rang[y])
       {arbore[y] = x;
       }
     if (rang[x] > rang[y])
       {arbore[x] = y;
       }
     if (rang[x] == rang[y])
       {arbore[x] = y;
        rang[x]++;
       }
 }

int main()
 {
   
   in >> n >> m;
   for (int i = 0; i <= n; i++)
      {arbore.push_back(i);
       rang.push_back(1);
      }       
   
   for (int i = 1; i<= m; i++)
      {
            int x, y, z;
            
            in >> x >> y >> z;
            if (x == 1)
              {uniune(find(y), find(z));
              }
            else
              {if (find(y) == find(z))
                          out << "DA" << "\n";
               else 
                          out << "NU" << "\n";
              }
      } 
   
   return 0;
 }