Pagini recente » Cod sursa (job #396071) | Cod sursa (job #922149) | Cod sursa (job #889943) | Cod sursa (job #26737) | Cod sursa (job #2803838)
#include <iostream>
#include <fstream>
#include <vector>
#define Nmax 100001
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
vector< pair<int, pair<int,int>> > cod_muchie; // m.first == codul, m.second.first = x, m.second.second = y;
int n, m, cod, tata[Nmax], rang[Nmax];
int find (int x)
{
while (x!=tata[x])
return find(tata[x]);
}
void uneste(int x, int y) // reuniune dupa rang <=> atasez arborelui mai mare pe cel mai mic
{
x = find(x);
y = find(y);
if (rang[x] >= rang[y]) {
tata[y] = x;
rang[x] += rang[y];
}
else {
tata[x] = y;
rang[y] += rang[x];
}
}
void init() {
for (int i=0; i<n; i++) {
tata[i] = i; // parintele
rang[i] = 1; // dimensiunea arborelui => initial fiecare nod reprez un arbore form doar din rad
}
}
int main()
{
int x, y;
fin >> n >> m;
for (int i=1; i<=m; i++) {
fin >> cod >> x >> y;
cod_muchie.push_back(make_pair(cod, make_pair(x,y)));
}
init();
for (auto muchie : cod_muchie) {
x = muchie.second.first;
y = muchie.second.second;
if (muchie.first == 1)
uneste(x,y);
else {
if (find(x) == find(y)) fout << "DA\n";
else fout << "NU\n";
}
}
return 0;
}