Pagini recente » Cod sursa (job #2780663) | Cod sursa (job #1282881) | Cod sursa (job #390453) | Cod sursa (job #67220) | Cod sursa (job #2469679)
#include <fstream>
using namespace std;
ifstream fin ("disjoint.in");
ofstream fout ("disjoint.out");
void unire ( int x, int y );
void verificare ( int x, int y );
int t[100001], lg[100001];
int main()
{
int n, m, i, c, a, b;
fin >> n >> m;
for ( i = 1 ; i <= n ; i++ ) lg[i] = 1;
for ( i = 1 ; i <= m ; i++ )
{
fin >> c >> a >> b;
if ( c == 1 ) unire ( a, b );
else verificare ( a, b );
}
return 0;
}
void unire ( int x, int y )
{
int rx = x, ry = y, cx = x, cy = y;
while ( t[rx] != 0 ) rx = t[rx];
while ( t[ry] != 0 ) ry = t[ry];
if ( lg[rx] >= lg[ry] )
{
while ( t[x] != 0 ) x = t[x], t[cx] = rx, cx = x;
while ( t[y] != 0 ) y = t[y], t[cy] = rx, cy = y;
t[cy] = cx;
if ( lg[rx] == lg[ry] ) lg[rx]++;
}
else
{
while ( t[x] != 0 ) x = t[x], t[cx] = ry, cx = x;
while ( t[y] != 0 ) y = t[y], t[cy] = ry, cy = y;
t[rx] = ry;
}
}
void verificare ( int x, int y )
{
while ( t[x] != 0 ) x = t[x];
while ( t[y] != 0 ) y = t[y];
if ( x == y ) fout << "DA" << '\n';
else fout << "NU" << '\n';
}