Pagini recente » Cod sursa (job #2357742) | Cod sursa (job #1330841) | Cod sursa (job #269099) | Cod sursa (job #284432) | Cod sursa (job #2377367)
// disjoints_sets.cpp : Defines the entry point for the console application.
//
//#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
class Node
{
public:
Node(int data, int rank) : data(data), rank(rank), parent(this) {};
void make_union(Node* other)
{
auto this_parent = this->getParent();
auto other_parent = other->getParent();
if (this_parent == other_parent)
return;
if (this_parent->rank >= other_parent->rank)
{
if (this_parent->rank == other_parent->rank)
{
this_parent->rank += 1;
}
other_parent->parent = this_parent;
}
else
{
this_parent->parent = other_parent;
}
}
Node* getParent()
{
queue<Node*> Q;
Node* current = this;
while (current != current->parent)
{
Q.push(current);
current = current->parent;
}
Node* root = current;
while (!Q.empty())
{
auto node = Q.front();
node->parent = root;
Q.pop();
}
return root;
}
int data;
int rank;
Node* parent;
};
int main()
{
vector<Node*> nodes;
int n, m, code, x, y;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
fin >> n >> m;
for (auto i = 0; i <= n; ++i)
{
nodes.push_back(new Node(i, 0));
}
for (auto i = 0; i < m; ++i)
{
fin >> code >> x >> y;
if (code == 1)
{
nodes[x]->make_union(nodes[y]);
}
else if (code == 2)
{
if (nodes[x]->getParent() == nodes[y]->getParent())
{
fout << "DA\n";
}
else
{
fout << "NU\n";
}
}
}
for (auto i = 0; i < n; ++i)
{
delete nodes[i];
}
return 0;
}