Pagini recente » Cod sursa (job #158144) | Cod sursa (job #2538946) | Cod sursa (job #2574195) | Cod sursa (job #2074577) | Cod sursa (job #1950847)
#include <fstream>
#include <queue>
using namespace std;
struct muchie {
int x, y, c;
}m, arb[200001];
struct cmp {
bool operator () (const muchie &a, const muchie &b) const {
return (a.c > b.c);
}
};
int noduri, muchii, nms, comp[200001], rang[200001], cost_total;
priority_queue<muchie, vector<muchie>, cmp> pq;
void init () {
for (int i = 1; i <= noduri; i++)
comp[i] = i;
}
int findset (int r) {
while (r != comp[r])
r = comp[r];
return comp[r];
}
void uniune (int r1, int r2) {
if (rang[r1] > rang[r2])
comp[r2] = r1;
else {
comp[r1] = r2;
if (rang[r1] == rang[r2])
rang[r2]++;
}
}
int main () {
ifstream fi("apm.in");
ofstream fo("apm.out");
fi >> noduri >> muchii; init();
for (int i = 1; i <= muchii; i++)
fi >> m.x >> m.y >> m.c, pq.push(m);
for (; nms < noduri-1;) {
m = pq.top(); pq.pop();
if (findset(m.x) != findset(m.y)) {
arb[++nms] = m;
cost_total += m.c;
uniune(findset(m.x), findset(m.y));
}
}
fo << cost_total << '\n';
for (int i = 1; i <= noduri-1; i++)
fo << arb[i].x << ' ' << arb[i].y << '\n';
return 0;
}