Cod sursa(job #3193406)

Utilizator TheAndreiEnache Andrei Alexandru TheAndrei Data 14 ianuarie 2024 15:39:39
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <iostream>
#include <fstream>

#define MAX_N 1000

using namespace std;

ifstream fin("disjoint.in");
fstream fout("disjoint.out");


int n;
int father[MAX_N], height[MAX_N];

int find(int x);
void unite(int x, int y);

void init() {
  int i;

  for (i = 0; i < n; ++i)
    father[i] = i, height[i] = 1;
}

void unite(int x, int y) {
  int setX, setY;

  setX = find(x);
  setY = find(y);
  if (setX != setY) {
    if (height[setX] < height[setY])
      father[setX] = setY;
    else if (height[setX] > height[setY])
      father[setY] = setX;
    else {
      father[setX] = setY;
      ++height[setY];
    }
  }
}

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

int main()
{

    int m, c, x, y;
    fin>>n>>m;
    init();

    for(int i=0;i<m;i++){
        fin>>c>>x>>y;
        if(c==1)
            unite(x, y);
        else
            if(find(x)==find(y))
                fout<<"DA\n";
            else
                fout<<"NU\n";
    }

    return 0;
}