Pagini recente » Cod sursa (job #423016) | Cod sursa (job #2367954) | Borderou de evaluare (job #557029) | Cod sursa (job #1869901) | Cod sursa (job #2192088)
#include <iostream>
#include <fstream>
using namespace std;
class Multime{
private :
int n;
int *tata, *h;
public :
explicit Multime(int);
~Multime();
void initialiare(int);
int Reprez(int);
void reuniune(int, int);
};
Multime::Multime(const int n) {
this->n = n;
this->tata = new int[n + 1];
this->h = new int[n + 1];
}
Multime::~Multime() {
delete[] tata;
delete[] h;
}
void Multime::initialiare(const int u) {
tata[u] = h[u] = 0;
}
int Multime::Reprez(int u) {
//fara compresie de cale
while(tata[u])
u = tata[u];
return u;
}
void Multime::reuniune(int u, int v) {
int ru = Reprez(u);
int rv = Reprez(v);
if(h[ru] > h[rv])
tata[rv] = ru;
else {
tata[ru] = rv;
if(h[ru] == h[rv])
h[rv]++;
}
}
class Drive{
private :
int *N, *M;
int *choice, *x, *y;
public :
Drive();
~Drive();
void solve();
};
Drive::Drive() {
N = new int;
M = new int;
choice = new int;
x = new int;
y = new int;
}
Drive::~Drive() {
delete (N, M, choice, x, y);
}
void Drive::solve() {
ifstream fin("disjoint.in");
if(!fin.is_open()) {
cout << "The file can't be opened!\n";
exit(EXIT_FAILURE);
}
ofstream fout("disjoint.out");
if(!fout.is_open()) {
cout << "The file can't be opened!\n";
exit(EXIT_FAILURE);
}
fin >> *N >> *M;
Multime *disjoint = new Multime(*N);
for(int i = 0; i < *M; ++i) {
fin >> *choice >> *x >> *y;
switch(*choice) {
case 1 : {
disjoint->reuniune(*x, *y);
break;
}
case 2 : {
if(disjoint->Reprez(*x) == disjoint->Reprez(*y))
fout << "DA\n";
else
fout << "NU\n";
}
}
}
delete disjoint;
fin.close();
fout.close();
}
int main() {
Drive *test = new Drive;
test->solve();
delete test;
return 0;
}