Cod sursa(job #3341429)

Utilizator bagae123Burlacu Andrei bagae123 Data 19 februarie 2026 16:10:52
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <fstream>

using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");

const int NMAX=1e5;

int rang[NMAX+5];

int root[NMAX+5];

void make_set(int nod)
{
    root[nod]=nod;
    rang[nod]=0;
}
int find_set(int nod)
{
    if(nod==root[nod])return nod;
    return root[nod]=find_set(root[nod]);
}
void unite(int x,int y)
{
    int rootx=find_set(x);
    int rooty=find_set(y);
    if(rootx!=rooty)
    {
        if(rang[rootx]<rang[rooty])
            swap(rootx,rooty);
        root[rooty]=rootx;
        if(rang[rootx]==rang[rooty])
        {
            rang[rootx]++;
        }
    }
}
int main()
{
  int n,m;
  fin>>n>>m;
  for(int i=1;i<=n;i++)
  {
      make_set(i);
  }
  while(m--)
  {
      int task,x,y;
      fin>>task>>x>>y;
      if(task==1)
      {
          unite(x,y);
      }
      else
      {
         int rootx=find_set(x);
         int rooty=find_set(y);
         if(rootx!=rooty)
         {
             fout<<"NU\n";
         }
         else
         {
             fout<<"DA\n";

         }
      }
  }
  for(int i=1;i<=n;i++)
  {
      fout<<root[i]<<" ";
  }
    return 0;
}