Pagini recente » Cod sursa (job #1230453) | Cod sursa (job #2859130)
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
struct arch {
int start, end, cost;
};
const int MAX_PEAKS = 200005;
const int MAX_ARCHES = 400005;
int noPeaks, noArches, representants[MAX_PEAKS];
arch arches[MAX_ARCHES];
void sortByCost() {
for (int i = 1; i < noArches; ++i) {
for (int j = i + 1; j <= noArches; ++j) {
if (arches[i].cost > arches[j].cost) {
swap(arches[i], arches[j]);
}
}
}
}
int main() {
fin >> noPeaks >> noArches;
for (int i = 1 ; i <= noArches ; ++i) {
fin >> arches[i].start >> arches[i].end >> arches[i].cost;
}
sortByCost();
for (int i = 1; i <= noPeaks; ++i) { // there are "noPeaks" trees in the first place
representants[i] = i;
}
int minSum = 0, noUnitedTreeArches = 0;
arch unitedTree[MAX_ARCHES];
for (int i = 1; i <= noArches; ++i) { // iterates through all the "sorted by cost" arches
if (representants[arches[i].start] != representants[arches[i].end]) { // if it unites 2 different trees
unitedTree[++noUnitedTreeArches].start = arches[i].start;
unitedTree[noUnitedTreeArches].end = arches[i].end;
minSum += arches[i].cost;
int firstRepresentant = representants[arches[i].start], secondRepresentant = representants[arches[i].end]; // we unite the 2 separate trees
for (int j = 1; j <= noPeaks; ++j) { // we mark the elements from the other tree with the first representant
if (representants[j] == secondRepresentant) {
representants[j] = firstRepresentant;
}
}
}
}
fout << minSum << "\n" << noUnitedTreeArches << "\n";
for (int i = 1; i <= noUnitedTreeArches; ++i) {
fout << unitedTree[i].start << " " << unitedTree[i].end << "\n";
}
return 0;
}