Pagini recente » Cod sursa (job #2291419) | Cod sursa (job #1700203) | Cod sursa (job #1426719) | Cod sursa (job #382226) | Cod sursa (job #3183848)
#include <iostream>
#include <fstream>
#define FIN "disjoint.in"
#define FOUT "disjoint.out"
typedef unsigned int uint;
typedef unsigned long ulong;
using namespace std;
class UnionFind {
public:
//constructor of the class
UnionFind(uint n):nElements(n), parent( new ulong[n+1] ), rank( new ulong[n+1] ) {
for(int i = 1; i <= nElements; ++i) {
parent[ i ] = i;
rank[ i ] = 1;
}
};
void unionSets(ulong x, ulong y) {
ulong rootX = getRoot( x ),
rootY = getRoot( y );
if(rank[ rootX ] > rank[ rootY ]) {
parent[ rootY ] = rootX;
} else if(rank[ rootX ] < rank[ rootY ]) {
parent[ rootX ] = rootY;
} else {
parent[ rootY ] = rootX;
rank[ rootX ]++;
}
}
ulong sameSets(ulong x, ulong y) {
ulong rootX = getRoot( x ),
rootY = getRoot( y );
return rootX == rootY;
}
//destructor of the class
~UnionFind() {
delete [] parent;
delete [] rank;
}
private:
uint nElements;
ulong *parent,
*rank;
ulong getRoot( ulong node ) {
ulong root = parent[ node ];
while(root != parent[root]) {
root = parent[root];
}
return root;
}
};
int main(int argc, char const *argv[]) {
ulong numElements, numOps, type, x, y;
ifstream fin( FIN );
ofstream fout( FOUT );
if(!fin) {
cout<<"Error opening the file";
return -1;
}
if(!fout) {
cout<<"Error opening the file";
return -1;
}
fin>>numElements>>numOps;
UnionFind forest( numElements );
while( numOps-- ) {
fin>>type>>x>>y;
if(type == 1) {
forest.unionSets(x, y);
} else if(type == 2) {
if(forest.sameSets(x, y)==1) cout<<"DA\n";
else cout<<"NU\n";
}
}
return 0;
}