Pagini recente » Cod sursa (job #896797) | Cod sursa (job #883662) | Cod sursa (job #237301) | Cod sursa (job #2606486) | Cod sursa (job #2942888)
#include <bits/stdc++.h>
using namespace std;
class UnionFind{
int NrNodes;
vector<int> Heights, Fathers;
public:
// Exclusiv pentru problema
void Read();
void Solve();
// Functii union find
void Init();
int Find(int);
void Union(int,int);
};
void UnionFind::Read(){
ifstream fin("disjoint.in");
fin >> NrNodes;
for(int i = 0; i <= NrNodes; i++){
Init();
}
fin.close();
}
void UnionFind::Init() {
Fathers.push_back(0);
Heights.push_back(0);
}
int UnionFind::Find(int Node) {
if(Fathers[Node] == 0)
return Node;
Fathers[Node] = Find(Fathers[Node]);
return Fathers[Node];
}
void UnionFind::Union(int NodeX, int NodeY) {
if(Heights[NodeX] < Heights[NodeY]) {
Fathers[NodeX] = NodeY;
} else{
Fathers[NodeY] = NodeX;
if(Heights[NodeX] == Heights[NodeY])
Heights[NodeX]++;
}
}
void UnionFind::Solve() {
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
int M;
fin >> M >> M;
for(int i = 0; i < M; i++){
int cod, X, Y;
fin >> cod >> X >> Y;
int fatherX = Find(X), fatherY = Find(Y);
if(cod == 1){
Union(fatherX,fatherY);
} else{
if( fatherX== fatherY)
fout << "DA" << endl;
else
fout << "NU" << endl;
}
}
fin.close();
fout.close();
}
int main() {
UnionFind multime;
multime.Read();
multime.Solve();
return 0;
}