Pagini recente » Cod sursa (job #601970) | Cod sursa (job #2108144) | Cod sursa (job #1473300) | Cod sursa (job #3173325) | Cod sursa (job #1194619)
#include <iostream>
#include <fstream>
using namespace std;
#define dim 100001
int adancime[dim], tata[dim];
struct bananier
{
int x, y;
};
//cu comprimare drum
int gaseste(int x)
{
if(tata[x] != tata[tata[x]])
tata[x] = gaseste(tata[x]);
return tata[x];
/*
SAU asa, de vazut care e mai rapida :
while(x != tata[x])
{
tata[x] = tata[tata[x]];
x = tata[x];
}
*/
}
bool uneste(int x, int y)
{
int x_aux = gaseste(x), y_aux = gaseste(y), aux;
if(x_aux == y_aux)
return false;
//fac ca x sa aiba adancimea mai mica
if(adancime[x_aux] > adancime[y_aux])
{
aux = x_aux;
x_aux = y_aux;
y_aux = aux;
}
//daca au adancimi egale, atunci adancimea arborelui ce se formeaza creste cu 1
if(adancime[x_aux] == adancime[y_aux])
++adancime[y_aux];
tata[x_aux] = y_aux;
return true;
}
//de testat cu datele din paduri disjuncte de pe infoarena
int main()
{
//bananier b[dim];
ifstream f("disjoint.in");
ofstream g("disjoint.out");
//din cate mai imi amintesc, se citeau n nr si m perechi ce deveneau vecini
int n, nr_perechi, optiune, x, y, i;
f >> n >> nr_perechi;
for(i = 0; i < n; ++i)
{
tata[i] = i;
adancime[i] = 1;
}
for(i = 0; i < nr_perechi; ++i)
{
f >> optiune >> x >> y;
if(optiune == 2)
{
if(gaseste(x) == gaseste(y))
g << "DA\n";
else
g << "NU\n";
}
else
{
uneste(gaseste(x), gaseste(y));
}
}
return 0;
}