Pagini recente » Cod sursa (job #481729) | Cod sursa (job #1524357) | Cod sursa (job #2613214) | Cod sursa (job #641148) | Cod sursa (job #1238918)
#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];
int t[nmax + 1], r[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));
}
}
bool conditie (Muchie a, Muchie b) {
return a.cost < b.cost;
}
int cauta (int x) {
int rd = x, y;
while (rd != t[rd]) rd = t[rd];
return rd;
}
void uneste (int x, int y) {
if (r[x] > r[y]) t[y] = x;
else t[x] = y;
if (r[x] == r[y]) r[y]++;
}
void APM () {
int ra, rb;
for (int i = 0; i < m; i++) t[i] = i, r[i] = 1;
for (int i = 0; i < m; i++) {
ra = cauta(muchii[i].a);
rb = cauta(muchii[i].b);
if (ra != rb) {
nrmuchii++;
cost += muchii[i].cost;
muchii[i].kept = true;
uneste(ra, rb);
//for (int i = 1; i <= n; i++) cout << v[i] << ' ';
//cout << endl;
}
}
}
void scrie () {
g << cost << '\n' << nrmuchii << '\n';
for (int i = 0; i < m; i++)
if (muchii[i].kept) g << muchii[i].b << ' ' << muchii[i].a << '\n';
}
int main () {
citeste ();
for (int i = 1; i <= n; i++) v[i] = i;
sort (muchii.begin (), muchii.end (), conditie);
APM ();
scrie ();
return 0;
}