Pagini recente » Cod sursa (job #781241) | Cod sursa (job #131380) | Cod sursa (job #2849659) | Cod sursa (job #2828521) | Cod sursa (job #1753272)
#include <fstream>
using namespace std;
typedef struct elem
{
struct elem *parent;
int rank;
public:
elem() {parent = this; rank = 0;}
}Elem;
void Union(Elem* x, Elem* y);
Elem* Find(Elem* x);
Elem** CreateSets(int n);
int main()
{
ifstream fin;
ofstream fout;
fout.open("disjoint.out");
fin.open("disjoint.in");
int n, m;
fin >> n >> m;
Elem** elemList = CreateSets(n);
int option, x, y;
for(int i = 1; i <= m; i++)
{
fin >> option >> x >> y;
switch(option)
{
case 1:
Union(Find(elemList[x]),Find(elemList[y]));
break;
case 2:
if(Find(elemList[x]) == Find(elemList[y]))
fout << "DA" << "\n";
else
fout << "NU" << "\n";
break;
default:
exit(1);
}
}
fin.close();
fout.close();
return 0;
}
Elem** CreateSets(int n)
{
Elem** list = new Elem*[n + 1]();
for (int i = 1; i <= n; i++)
{
list[i] = new Elem();
}
return list;
}
Elem* Find(Elem* x)
{
if(x != x->parent)
x->parent = Find(x->parent);
return x->parent;
}
void Union(Elem* x, Elem* y)
{
Elem* xRoot = Find(x);
Elem* yRoot = Find(y);
if(xRoot == yRoot)
return;
if(xRoot->rank > yRoot->rank)
yRoot->parent = xRoot;
else if(yRoot->rank > xRoot->rank)
xRoot->parent = yRoot;
else
{
yRoot->parent = xRoot;
xRoot->rank += 1;
}
}