Pagini recente » Cod sursa (job #1706565) | Cod sursa (job #1712295) | Cod sursa (job #69666) | Cod sursa (job #195224) | Cod sursa (job #1325837)
///DISJOINT FOREST
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int mFind(int x, vector<int>& s) {
int c = x;
while(c != s[c])
c = s[c];
s[x] = c;
return c;
}
void mUnion(int x, int y, vector<int>& s, vector<int>& r) {
int s1, s2;
s1 = mFind(x, s);
s2 = mFind(y, s);
if(s1 == s2)
return;
if(r[s1] == r[s2]) {
s[s2] = s1;
++r[s1];
} else
if(r[s1] > r[s2])
s[s2] = s1;
else
s[s1] = s2;
}
int main() {
ifstream inStr("disjoint.in");
ofstream outStr("disjoint.out");
int N, M;
inStr >> N >> M;
vector<int> r(N, 0);
vector<int> s(N);
for(int i = 0; i<N; ++i)
s[i] = i;
int task, x, y;
for(int i=0; i<M; ++i) {
inStr >> task >> x >> y; --x; --y;
if(task == 1)
mUnion(x, y, s, r);
else {
if(mFind(x, s) == mFind(y, s))
outStr << "DA\n";
else
outStr << "NU\n";
}
}
return 0;
}