Pagini recente » Cod sursa (job #3357721) | Statistici Rotaru Stefan (BrutalArmy) | Cod sursa (job #3324144) | Cod sursa (job #670507) | Cod sursa (job #3357986)
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
const int NMAX = 200005;
struct muchie {
int x, y, cost;
};
int tata[NMAX], h[NMAX];
vector<muchie> muchii;
int n, m;
int find(int nod) {
if (tata[nod] == nod) return nod;
int t = find(tata[nod]);
h[nod] = h[nod] + h[tata[nod]];
tata[nod] = t;
return t;
}
void reunioneaza(int x, int y) {
x = find(x);
y = find(y);
if (x == y) return;
if (h[x] < h[y]) {
tata[x] = y;
h[y] += h[x];
} else {
tata[y] = x;
h[x] += h[y];
}
}
bool cmp(muchie a, muchie b) {
return a.cost < b.cost;
}
int main() {
ifstream cin("apm.in");
ofstream cout("apm.out");
cin >> n >> m;
for (int i = 1; i <= m; i++) {
muchie m;
cin >> m.x >> m.y >> m.cost;
muchii.push_back(m);
}
sort(muchii.begin(), muchii.end(), cmp);
for (int i = 1; i <= n; i++) {
tata[i] = i;
h[i] = 1;
}
int cost = 0;
int nr = 0;
for (auto m : muchii) {
if (find(m.x) != find(m.y)) {
reunioneaza(m.x, m.y);
cost += m.cost;
nr++;
cout << m.x << " " << m.y << "\n";
}
}
cout << cost << "\n" << nr << "\n";
return 0;
}