Pagini recente » Cod sursa (job #291240) | Cod sursa (job #2241330) | Profil miholcaandreea | Monitorul de evaluare | Cod sursa (job #1159096)
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;
FILE *f=fopen("disjoint.in","r");
ofstream out("disjoint.out");
struct node
{
int r;
node* parent;
};
void make_set(node& x)
{
x.parent=&x;
x.r=0;
}
node find_parent(node& x)
{
if(x.parent!=&x)
{
*x.parent=find_parent(*x.parent);
return *x.parent;
}
else
return x;
}
void link(node& x, node& y)
{
if(x.parent!=y.parent)
{
if(x.r==y.r)
{
*x.parent=y;
y.r++;
return;
}
if(x.r>y.r)
{
*y.parent=x;
return;
}
if(y.r>x.r)
{
*x.parent=y;
return;
}
}
}
void unite(node& x,node& y)
{
node tmp1=find_parent(x);
node tmp2=find_parent(y);
link(tmp1,tmp2);
}
int main()
{
int n,m;
fscanf(f,"%d %d",&n,&m);
node arr[n+6];
for(int i=1;i<=n;i++)
{
make_set(arr[i]);
}
for(int i=1;i<=n;i++)
{
cout<<&arr[i]<<" "<<arr[i].parent<<" "<<arr[i].r<<endl;
}
int operation,node1,node2;
for(int i=1;i<=m;i++)
{
fscanf(f,"%d %d %d",&operation,&node1,&node2);
if(operation==1)
{
unite(arr[node1],arr[node2]);
}
if(operation==2)
{
if(find_parent(arr[node1]).parent==arr[node2].parent)
out<<"DA"<<endl;
else
out<<"NU"<<endl;
}
}
return 0;
}