Pagini recente » Cod sursa (job #2929972) | Cod sursa (job #1186486) | Cod sursa (job #1208775) | Cod sursa (job #1503667) | Cod sursa (job #2936165)
#include <vector>
#include <fstream>
using namespace std;
ifstream fileIn("disjoint.in");
ofstream fileOut("disjoint.out");
class Graph {
int N;
int M;
vector <int> r;
vector <int> parent;
public:
int reprez(int x);
void reuneste(int a, int b) ;
void rezolva();
};
int Graph::reprez(int x) {
int reprezentant = x;
while (parent[reprezentant] != 0) {
reprezentant = parent[reprezentant];
}
int y;
while(parent[x]!=0) {
y = parent[x];
parent[x] = reprezentant;
x = y;
}
return reprezentant;
}
void Graph::reuneste(int a, int b) {
int r1 = reprez(a);
int r2 = reprez(b);
if(r[r1] > r[r2]) {
parent[r2] = r1;
} else {
parent[r1] = r2;
if (r[r1] == r[r2] ) {
r[r1]++;
}
}
}
void Graph:: rezolva() {
fileIn >> N >> M;
parent.resize(N + 1, 0);
r.resize(N + 1, 1);
int op, a, b;
while(M) {
M--;
fileIn >> op >> a >> b;
if (op == 1) {
reuneste(a,b);
} else {
if (reprez(a) == reprez(b)) {
fileOut << "DA\n";
} else {
fileOut << "NU\n";
}
}
}
}
int main() {
Graph my_graph;
my_graph.rezolva();
return 0;
}