Cod sursa(job #2377368)

Utilizator gabriel.bjgGabriel b. gabriel.bjg Data 10 martie 2019 01:37:01
Problema Paduri de multimi disjuncte Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
// 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";
			}
		}
	}

    return 0;
}