Pagini recente » Cod sursa (job #1315060) | Cod sursa (job #738369) | Cod sursa (job #571789) | Cod sursa (job #1590359) | Cod sursa (job #1312242)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
#define nmax 100020
ifstream fin ("disjoint.in");
ofstream gout ("disjoint.out");
int n, m, i, x, y, a, b, op;
vector <int> v; // the array that we use for our optimization
// if the dimension of it it's negative, it will record the size of it.
// if it's positive, it will record the tree of that current node.
void union_nodes(int a, int b){ // when we union two trees, we always "move" the smaller tree so we win some time.
if(v[a] > v[b]){ // if v[a] > v[b] assuming that these two values are negative values, we have to inverse the sign.
// for example for v[a]=-3 && v[b]==-5 v[a] is going to be > then v[b] since the values are negative.
v[b] += v[a]; // we now grow the size of the tree by the size of it's current plus the size of the tree we attach
v[a] = b; // we now make the tree we attach be the child of the root node of the other tree.
}
else{ // otherwise we do the same things
v[a] += v[b];
v[b] = a;
}
}
int find_parent(int x){ // searching for the root node of a node
if(v[x]<0) return x; // if v[x] is negative that means the current node x has no parent so that makes him the root node of it's tree
else{ // else
v[x] = find_parent(v[x]); // we look up for it's parent and so on till we find the root node
return v[x]; // we return the root node after we found it
}
}
int main(){
fin >> n >> m; // n would be the number of trees and m the number of operations we do
for(i=0; i<=n; i++){
v.push_back(-1); // we initialize the array with -1, because at the beginning all the trees are composed by one single node.
}
for(i=1; i<=m; i++){
fin >> op >> x >> y; // x and y are two nodes given and asked to tell if they belong to the same tree, or if they don't to union them
a = find_parent(x); // a is now the root node of x;
b = find_parent(y); // b is now the root node of y;
if(op==1)
union_nodes(a, b); // we union the trees
else{
if(a==b) cout << "DA\n";
else cout << "NU\n";
}
}
return 0;
}