Pagini recente » Rating Miulescu Stefan-Adrian (miulescu94) | Arhiva de probleme | Cod sursa (job #2596444) | Cod sursa (job #1549216) | Cod sursa (job #2224048)
#include <fstream>
#include <vector>
#include <string>
using namespace std;
const string IN_FILE = "disjoint.in";
const string OUT_FILE = "disjoint.out";
const int NIL = -1;
class DisjointSets {
public:
DisjointSets(const int _size) :
size(_size),
parent(vector<int>(_size, NIL)) {}
int find(const int x) {
return parent[x] == NIL ? x : parent[x] = find(parent[x]);
}
bool merge(const int x, const int y) {
const int rx = find(x);
const int ry = find(y);
if (rx == ry) return false;
parent[ry] = rx;
return true;
}
private:
int size;
vector<int> parent;
};
int main() {
ifstream in(IN_FILE);
ofstream out(OUT_FILE);
int n, m;
in >> n >> m;
auto sets = DisjointSets(n);
for (int i = 0; i < m; i++) {
int type, x, y;
in >> type >> x >> y;
if (type == 1) {
sets.merge(x - 1, y - 1);
} else {
out << (sets.find(x - 1) == sets.find(y - 1) ? "DA" : "NU") << "\n";
}
}
return 0;
}