Pagini recente » Cod sursa (job #2816985) | Cod sursa (job #3229570) | Cod sursa (job #1515093) | Cod sursa (job #2876987) | Cod sursa (job #2009654)
#include <fstream>
#include <vector>
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 x, int y) {
_root[y] = _root[x];
for (int el : _node[y]) {
if (_root[el] == _root[x])
continue;
ch_root(x, el);
}
}
void _link(int x, int y) {
if (_size[x] >= _size[y]) {
ch_root(x, y);
_size[x] += _size[y];
_node[x].push_back(y);
}
else {
ch_root(y, x);
_size[y] += _size[x];
_node[y].push_back(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);
}
}
}