Pagini recente » Cod sursa (job #1589860) | Cod sursa (job #2149828) | Cod sursa (job #1198766) | Cod sursa (job #2004317) | Cod sursa (job #1832131)
/*
* =====================================================================================
*
* Filename: IA_paduri_de_multimi_disjuncte_disjoint_data_set.cpp
*
* Description: http://www.infoarena.ro/problema/disjoint
*
* Version: 1.0
* Created: 04/04/2016 12:44:12 PM
* Revision: none
* Compiler: gcc/g++
*
* Author: Marius-Constantin Melemciuc
* email:
* Organization:
*
* =====================================================================================
*/
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
class DisjointDataSet {
vector<int> rang;
vector<int> parent;
public:
DisjointDataSet(int);
~DisjointDataSet();
int findRoot(int);
void link(int, int);
void unionSets(int, int);
};
DisjointDataSet::DisjointDataSet(int n) {
rang.resize(n + 1, 0);
parent.resize(n + 1);
for (int i = 0; i < n + 1; i++) {
parent[i] = i;
}
}
DisjointDataSet::~DisjointDataSet() {
}
int DisjointDataSet::findRoot(int x) {
int i;
for (i = x; parent[i] != i; i = parent[i]) {
}
// i is the root
int aux;
while (parent[x] != x) { // path compression
aux = parent[x];
parent[x] = i;
x = aux;
rang[i]--;
}
return i;
}
void DisjointDataSet::link(int x, int y) {
if (rang[x] < rang[y]) { // reuniunea dupa rang
parent[x] = y;
} else {
if (rang[x] > rang[y]) {
parent[y] = x;
} else {
parent[x] = y;
rang[y]++;
}
}
}
void DisjointDataSet::unionSets(int x, int y) {
link(findRoot(x), findRoot(y));
}
int main() {
ifstream in("disjoint.in");
ofstream out("disjoint.out");
int n;
int numOperations;
in >> n >> numOperations;
DisjointDataSet d(n);
int operation, x, y;
for (int i = 0; i < numOperations; i++) {
in >> operation >> x >> y;
if (operation == 1) {
d.unionSets(x, y);
}
if (operation == 2) {
if (d.findRoot(x) == d.findRoot(y)) {
out << "DA";
} else {
out << "NU";
}
out << "\n";
}
}
in.close();
out.close();
return 0;
}