Pagini recente » Cod sursa (job #1980803) | Cod sursa (job #1022121)
#include <fstream>
#define in "disjoint.in"
#define out "disjoint.out"
#define Max_Size 100009
std :: ifstream f(in);
std :: ofstream g(out);
int N, M;
//T este arborele meu si este reprezentat ca un vector a tatilor
//Pentru a reuni doua multimi vom respecta Regula Ponderilor - > daca numarul de nivele in arborele cu radacina x este mai mic
//ca numarul de nivele din arborele cu radacina y atunci x devine subarbore a lui y altfel invers
int T[Max_Size], R[Max_Size];
inline int Find(int x)
{
int Root;
for(Root = T[x]; Root != T[Root]; Root = T[Root]);
int y;
//Compresam drumurile adica pentru fiecare nod indicam direct cine e radacina lui
while(x != T[x])
{
y = T[x];
T[x] = Root;
x = y;
}
return Root;
}
inline void Union(int x, int y)
{
if(R[y] < R[x]) T[y] = x;
else
if(R[y] > R[x]) T[x] = y;
if(R[y] == R[x])
R[y] ++,
T[y] = x;
}
int main()
{
int _tip, x, y;
f >> N >> M;
for(int i = 1; i <= N; ++i) T[i] = i, R[i] = 1;
for(int i = 1; i <= M; ++i)
{
f >> _tip >> x >> y;
if(_tip == 1)
Union(x, y);
else
{
if(Find(x) == Find(y)) g << "DA\n";
else g << "NU\n";
}
}
g.close();
return 0;
}