Pagini recente » Cod sursa (job #2409586) | Cod sursa (job #290022) | Diferente pentru problema/spirala2 intre reviziile 2 si 1 | Diferente pentru problema/zigzag2 intre reviziile 31 si 27 | Cod sursa (job #676310)
Cod sursa(job #676310)
// http://infoarena.ro/problema/disjoint
#include <fstream>
using namespace std;
const int MAXSIZE = 100001;
ifstream in("disjoint.in");
ofstream out("disjoint.out");
int father[MAXSIZE],treeRank[MAXSIZE];
int numbers,operations,type,first,second;
void unite(int first,int second);
int find(int node);
int main() {
in >> numbers >> operations;
for(int i=1;i<=operations;i++) {
in >> type >> first >> second;
switch(type) {
case 1: { unite(first,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) {
int firstRoot = find(first);
int secondRoot = find(second);
if(treeRank[firstRoot] < treeRank[secondRoot])
father[firstRoot] = secondRoot;
else
father[secondRoot] = firstRoot;
if(treeRank[firstRoot] == treeRank[secondRoot])
treeRank[firstRoot]++;
}
int find(int node) {
if(!father[node])
return node;
else
return (father[node] = find(father[node]));
}