Pagini recente » Statistici Posa Dorel Gabriel (dodoposa) | remediere | Cod sursa (job #12743) | Cod sursa (job #162355) | Cod sursa (job #2003528)
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <time.h>
#include <algorithm>
using namespace std;
ifstream in("disjoint.in");
ofstream out("disjoint.out");
#define ll long long
#define ui unsigned int
#define pb push_back
const int inf = 1e9 + 5;
const int NMax = 1e6 + 5;
int N,M;
int nrArb[NMax],dad[NMax];
int findRoot(int);
void unite(int,int);
int main() {
in>>N>>M;
for (int i=1;i <= N;++i) {
dad[i] = i;
nrArb[i] = 1;
}
while (M--) {
int tip,x,y;
in>>tip>>x>>y;
switch(tip) {
case 1: {
unite(x,y);
break;
}
case 2: {
int root1 = findRoot(x), root2 = findRoot(y);
if (root1 == root2) {
out<<"DA\n";
}
else {
out<<"NU\n";
}
break;
}
}
}
in.close();
out.close();
return 0;
}
int findRoot(int node) {
if (dad[node] == node) {
return node;
}
int root = findRoot(dad[node]);
dad[node] = root;
return root;
}
void unite(int x,int y) {
int root1 = findRoot(x), root2 = findRoot(y);
if (nrArb[root1] > nrArb[root2]) {
dad[root2] = root1;
nrArb[root1] += nrArb[root2];
}
else {
dad[root1] = root2;
nrArb[root2] += nrArb[root1];
}
}