Pagini recente » Cod sursa (job #743957) | Cod sursa (job #2241873) | Cod sursa (job #1063714) | Cod sursa (job #1911290) | Cod sursa (job #1875288)
#include <fstream>
#include <string>
#include <vector>
using namespace std ;
ifstream cin ("disjoint.in") ;
ofstream cout ("disjoint.out") ;
class DisjointDataSet {
public :
DisjointDataSet (int nn)
{
n = nn ;
tata.resize(n+1) ;
rang.resize(n+1) ;
for ( int i = 1 ; i <= n ; ++ i ) {
tata [i] = i ;
rang [i] = 1 ;
}
}
void Unite (int x, int y) {
unite(x,y);
}
string Solution (int x, int y)
{
if (FindFather(x) == FindFather(y)) {
return "DA\n";
}
return "NU\n" ;
}
private :
int n ;
vector < int > tata ;
vector < int > rang ;
int FindFather (int x)
{
int R = x ;
while (x != tata[x]) {
x = tata [x] ;
}
while (R != tata[R]) {
int aux = tata [R] ;
tata[R] = x ;
R = aux ;
}
return R ;
}
void unite (int x, int y)
{
x = FindFather (x) ;
y = FindFather (y) ;
if (x == y) {
return ;
}
if (rang[x] < rang[y]) {
swap (x,y) ;
}
rang [x] += rang[y] ;
tata [y] = tata [x] ;
}
};
int main()
{
int n, m ;
cin >> n >> m ;
DisjointDataSet *D = new DisjointDataSet(n) ;
while (m --) {
int tip ;
cin >> tip ;
if (tip == 1) {
int x, y ;
cin >> x >> y ;
D -> Unite(x,y);
}
else {
int x, y ;
cin >> x >> y ;
cout << D -> Solution(x,y) ;
}
}
return 0 ;
}