Pagini recente » Cod sursa (job #2865066) | Cod sursa (job #2562292) | Cod sursa (job #1009391) | Cod sursa (job #2537239) | Cod sursa (job #542624)
Cod sursa(job #542624)
// http://infoarena.ro/problema/disjoint
#include <fstream>
using namespace std;
#define maxSize 100001
ifstream in("disjoint.in");
ofstream out("disjoint.out");
int father[maxSize];
void unite(int first,int second);
int find(int node);
int main() {
int number,operations;
int type,first,second;
in >> number >> operations;
// initial fiecare nod este radacina
// (pointeaza spre el insusi)
for(int i=1;i<=number;i++)
father[i] = i;
for(int i=1;i<=operations;i++) {
in >> type >> first >> second;
switch(type) {
case 1:
unite(find(first),find(second));
break;
case 2:
if(find(first) == find(second))
out << "DA\n";
else
out << "NU\n";
break;
}
}
in.close();
out.close();
return (0);
}
void unite(int first,int second) {
father[first] = second;
}
int find(int node) {
int current = node;
int next;
// merg in sus pe arbore pana gasesc un nod
// care pointeaza spre el insusi (radacina)
while(father[node] != node)
node = father[node];
// aplic compresia drumurilor
// (toate nodurile prin care am trecut
// le leg acum direct de radacina)
while(father[current] != current) {
next = father[current];
father[current] = node;
current = next;
}
// returnez radacina
return node;
}