Pagini recente » Cod sursa (job #2595668) | Monitorul de evaluare | Cod sursa (job #1158568) | Cod sursa (job #1672839) | Cod sursa (job #1243694)
#include <bits/stdc++.h>
using namespace std;
class DSU
{
public:
DSU( const int _N )
{
N = _N;
Father = vector<int>( N + 1, 0 );
Rank = vector<int> ( N + 1, 0 );
initialise();
}
void initialise()
{
for ( int i = 1; i <= N; ++i )
{
Father[i] = i;
Rank[i] = 1;
}
}
int Find( int node )
{
int root = node, auxNode;
while ( Father[ root ] != root )
root = Father[ root ];
while ( root != Father[ node ] )
{
auxNode = Father[ node ];
Father[ node ] = root;
node = auxNode;
}
return root;
}
int Check( int x, int y )
{
return ( Find( x ) == Find( y ) );
}
void Union( int x, int y )
{
int fx = Find( x );
int fy = Find( y );
if ( fx != fy )
{
x = fx; y = fy;
if ( Rank[x] < Rank[y] )
Father[x] = y;
else
Father[y] = x;
if ( Rank[x] == Rank[y] )
Rank[y]++;
}
}
private:
vector <int> Father, Rank;
int N;
};
int main()
{
ifstream in("disjoint.in");
ofstream out("disjoint.out");
int N, M, a, b, tip;
in >> N >> M;
DSU D( N );
while ( M-- )
{
in >> tip >> a >> b;
if ( tip == 1 )
{
D.Union( a, b );
}
else
{
if ( D.Check( a, b ) )
out << "DA\n";
else
out << "NU\n";
}
}
return 0;
}