Pagini recente » Cod sursa (job #2243074) | Cod sursa (job #2147104) | Cod sursa (job #2959648) | Cod sursa (job #2862809) | Cod sursa (job #1374741)
///KRUSKAL
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int find(vector<int>& st, vector<int>& rnk, int a) {
int b = st[a];
while(st[b] != b)
b = st[b];
st[a] = b;
return st[a];
}
void unite(vector<int>& st, vector<int>& rnk, int a, int b) {
int pA = find(st, rnk, a);
int pB = find(st, rnk, b);
if(pA == pB) return;
if(rnk[pA] < rnk[pB])
st[pA] = pB;
if(rnk[pA] > rnk[pB])
st[pB] = pA;
if(rnk[pA] == rnk[pB]) {
st[pB] = pA;
++rnk[pA];
}
}
int main() {
ifstream inStr("disjoint.in");
ofstream outStr("disjoint.out");
int N, M;
inStr >> N >> M;
vector<int> rnk(N, 0);
vector<int> st(N);
for(int i=0; i<N; ++i)
st[i] = i;
int tp, a, b;
for(int i=0; i<M; ++i) {
inStr >> tp >> a >> b;
switch(tp) {
case 1:
unite(st, rnk, a, b);
break;
case 2:
if(find(st, rnk, a) == find(st, rnk, b))
outStr << "DA\n";
else outStr << "NU\n";
}
}
return 0;
}