Pagini recente » Cod sursa (job #1916968) | Cod sursa (job #2908091) | Cod sursa (job #341851) | Cod sursa (job #323742) | Cod sursa (job #633364)
Cod sursa(job #633364)
#include <fstream>
using namespace std;
const int nmax = 100005;
int tata[nmax], niv[nmax];
int root(int x)
{
int aux=x, nv=0, radacina;
aux=x;
while (tata[x]!=x)
{
x=tata[x];
++nv;
}
radacina=x;
x=aux;
while (tata[x]!=x)
{
tata[x]=radacina;
niv[x]=nv;
x=tata[x];
}
return radacina;
}
void merge(int x, int y)
{
if (niv[x] >= niv[y])
tata[y]=x;
else
tata[x]=y;
}
int main()
{
int N, M, radacina_x, radacina_y, op, x, y;
ifstream f("disjoint.in");
ofstream g("disjoint.out");
f>>N>>M;
for (int i=1; i<=N; ++i)
tata[i]=i;
for (; M; --M)
{
f>>op>>x>>y;
radacina_x=root(x);
radacina_y=root(y);
if (op == 1)
merge(x,y);
else
if (radacina_x == radacina_y)
g<<"DA\n";
else
g<<"NU\n";
}
}