Pagini recente » Cod sursa (job #171411) | Cod sursa (job #1350034) | Diferente pentru problema/maxcost intre reviziile 1 si 2 | Cod sursa (job #2881456) | Cod sursa (job #1470775)
//https://www.youtube.com/watch?v=ID00PMy0-vE
#include <iostream>
#include <fstream>
#include <algorithm>
#define N 100005
using namespace std;
fstream f,g;
int a[N],n,m,rang[N];
void make_sets()
{
int i;
f>>n>>m;
for (i = 1 ; i<=n ; i++)
{
a[i]=i; // radacina
rang[i] = 1; // sau 0 :-??
}
}
inline int root(int x)
{
int R = x, temp;
while ( R != a[R])
R = a[R];
while( x != R)
{
temp = a[x];
a[x] = R;
x = temp;
}
return R;
}
int same_set (int x, int y)
{
int R1, R2;
R1 = root(x);
R2 = root(y);
return R1 == R2 ? 1 : 0;
}
void unire (int x, int y)
{
int R1, R2;
R1 = root(x);
R2 = root(y);
// unire dupa rang ( inaltime aproximativa a arborelui )
if (rang[R1] > rang[R2])
a[R2] = R1;
else
a[R1] = R2;
if (rang[R1] == rang[R2])
rang[R2]++;
}
void solve()
{
int i,x,y,op;
while (m--)
{
f>>op>>x>>y;
if (op == 1)
unire(x,y);
else // op == 2
if (same_set(x,y))
g<<"DA\n";
else
g<<"NU\n";
}
}
int main()
{
f.open("disjoint.in",ios::in);
g.open("disjoint.out",ios::out);
make_sets();
solve();
}