Pagini recente » Cod sursa (job #1575048) | Cod sursa (job #1574644) | Cod sursa (job #880848) | kmp_aib | Cod sursa (job #2009779)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream cin("disjoint.in");
ofstream cout("disjoint.out");
class Graph {
public:
Graph(int n) {
this -> n = n;
_node.resize(n + 1);
_root.resize(n + 1);
_size.resize(n + 1);
for (int i = 1; i <= n; i ++) {
_size[i] = 1;
_root[i] = i;
}
}
void link(int x, int y) {
_link(x, y);
}
void query(int x, int y) {
_root[x] == _root[y] ? cout << "DA" << '\n' : cout << "NU" << '\n';
}
private:
int n;
vector < vector < int > > _node;
vector < int > _size;
vector < int > _root;
void ch_root(int r, int y) {
queue < int > q;
q.push(y);
_root[y] = r;
while (!q.empty()) {
int cur = q.front();
for (auto x : _node[cur]) {
if (_root[x] != r) {
_root[x] = r;
q.push(x);
}
}
q.pop();
}
}
void _link(int x, int y) {
if (_size[_root[x]] >= _size[_root[y]]) {
_node[x].push_back(_root[y]);
ch_root(_root[x], _root[y]);
_size[_root[x]] += _size[_root[y]];
}
else {
_node[_root[y]].push_back(_root[x]);
ch_root(_root[y], _root[x]);
_size[_root[y]] += _size[_root[x]];
}
}
};
int main() {
int n, m;
cin >> n >> m;
Graph *graph = new Graph(n);
for (int i = 1; i <= m; i ++) {
int type;
cin >> type;
if (type == 1) {
int x, y;
cin >> x >> y;
graph -> link(x, y);
}
else {
int x, y;
cin >> x >> y;
graph -> query(x, y);
}
}
}