Cod sursa(job #1256558)

Utilizator xoSauceSergiu Ferentz xoSauce Data 6 noiembrie 2014 15:35:34
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include <iostream>
#include <memory.h>
using namespace std;

class disjointSet{
     
private:
     const static int limit = 100001;
     int entries;
     int group[limit];
     int depth[limit];
     int find_root(int x){
          if(group[x] == x)
	return x;
          return find_root(group[x]);
     }
public:
     disjointSet(int n){
          entries = n;
          for(int i = 1 ;i <= n; i++){
	group[i] = i;
	depth[i] = 0;
	
          }
     }
     void unite(int x,int y){
          int xRoot = find_root(x);
          int yRoot = find_root(y);
          if(depth[xRoot] < depth[yRoot])
	group[xRoot] = yRoot;
          else if (depth[xRoot] > depth[yRoot]){
	group[yRoot] = xRoot;
          }else{
	group[xRoot] = yRoot;
	depth[xRoot] ++;
          }
     }
     bool connected(int x,int y){
          return find_root(x)==find_root(y);
     }
     void print_group(){
          for(int i =1;i <= entries; i++){
	cout << group[i] << " ";
          }
          cout << endl;
     }

     
};

int main(){
     
     freopen("disjoint.in","r",stdin);
     freopen("disjoint.out","w",stdout);
     int n,m;
     cin >> n >> m;
     disjointSet disjoint_set(n);
     for(int i = 0; i < m ; i++){
          int c,x,y;
          cin >> c >> x >> y;
          if(c == 2){
	if(disjoint_set.connected(x,y))
	     cout << "DA" << endl;
	else
	     cout << "NU" << endl;
          }
          else{
	disjoint_set.unite(x,y);
          }
         // disjoint_set.print_group();
     }
     return 0;
}