Pagini recente » Autentificare | Cod sursa (job #851446) | Cod sursa (job #3314124) | Cod sursa (job #3136561) | Cod sursa (job #3318834)
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
ifstream in("disjoint.in");
ofstream out("disjoint.out");
const int NMAX = 1000;
int n, k;
int Heights[NMAX], Fathers[NMAX], UnionSize[NMAX];
void Init(int x)
{
Fathers[x] = 0;
Heights[x] = 0;
UnionSize[x] = 1;
}
int Find(int x)
{
if (Fathers[x]==0)
return x;
Fathers[x]=Find(Fathers[x]);
return Fathers[x];
}
/*
//reuniune ponderata dupa inaltime - by rank
void Union(int x, int y)
{
int RootX = Find(x), RootY = Find(y);
if(Heights[RootX] < Heights[RootY])
{
Fathers[RootX] = RootY;
return UnionSize[RootY];
}
else
{
if(Heights[RootX] > Heights[RootY])
Fathers[RootY] = RootX;
else
Fathers[RootY] = RootX, Heights[RootX]++;
}
} */
//reuniune ponderata dupa dimensiune(nr de varfuri) - by size
//putem renunta la height si sa facem reuniunea in functie de unionsize
void Union(int x, int y)
{
int RootX = Find(x), RootY = Find(y);
if(UnionSize[RootX] < UnionSize[RootY])
{
Fathers[RootX] = RootY;
UnionSize[RootY] += UnionSize[RootX];
}
else
{
if(UnionSize[RootX] > UnionSize[RootY])
Fathers[RootY] = RootX;
else
Fathers[RootY] = RootX;
UnionSize[RootX] += UnionSize[RootY];
}
}
int main()
{
int m, x, y,t;
in >> n >> m ;
cout<<n;
for(int i = 1; i <= n; i++)
Init(i);
for(int i = 1; i <= m; i++)
{
in >> t>>x>>y;
if (t==1)
Union(x,y);
else
if (Find(x)==Find(y))
out<<"DA"<<endl;
else
out<<"NU"<<endl;
}
return 0;
}