Pagini recente » Cod sursa (job #293209) | Cod sursa (job #1236845) | Cod sursa (job #2305588) | Cod sursa (job #602034) | Cod sursa (job #1204346)
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream f ("apm.in");
ofstream g ("apm.out");
const int nmax = 200000;
int n, m;
int cost, nrmuchii;
struct Muchie {
int a, b, cost;
bool kept;
Muchie (int a, int b, int cost) {
this->a = a;
this->b = b;
this->cost = cost;
this-> kept = false;
};
};
int v[nmax + 1];
vector <Muchie> muchii;
void citeste () {
f >> n >> m;
int a, b, c;
for (int i = 1; i <= m; i++) {
f >> a >> b >> c;
muchii.push_back (Muchie (a, b, c));
}
}
struct conditie {
inline bool operator () (Muchie a, Muchie b) {
return a.cost < b.cost;
}
};
int father(int node) {
return v[node] = (v[node] == node ? node : father(v[node]));
}
void APM () {
for (int i = 0; i < m; i++) {
if (father(muchii[i].a) != father(muchii[i].b)) {
nrmuchii++;
cost += muchii[i].cost;
muchii[i].kept = true;
v[father(muchii[i].a)] = father(v[muchii[i].b]);
}
}
}
void scrie () {
g << cost << '\n' << nrmuchii << '\n';
for (int i = 0; i < m; i++)
if (muchii[i].kept) g << muchii[i].a << ' ' << muchii[i].b << '\n';
}
int main () {
citeste ();
for (int i = 1; i <= n; i++) v[i] = i;
sort (muchii.begin (), muchii.end (), conditie());
APM ();
scrie ();
return 0;
}