Pagini recente » Cod sursa (job #1645290) | Cod sursa (job #1876469) | Cod sursa (job #1723833) | Cod sursa (job #1130661) | Cod sursa (job #1217036)
#include <bits/stdc++.h>
using namespace std;
class DSU
{
public:
DSU() {}
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, auxNode;
for ( root = node; Father[ root ] != root; root = Father[ root ] );
while ( node != 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 )
{
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 N, M;
int main()
{
ifstream in("disjoint.in");
ofstream out("disjoint.out");
in >> N >> M;
DSU D( N );
for ( int i = 1, tip, x, y; i <= M; ++i )
{
in >> tip >> x >> y;
if ( tip == 1 )
D.Union( D.Find( x ), D.Find( y ) );
else
{
if ( D.Check( x, y ) )
out << "DA\n";
else
out << "NU\n";
}
}
return 0;
}