Pagini recente » Cod sursa (job #3040399) | Cod sursa (job #1242278) | Cod sursa (job #1312642) | Cod sursa (job #2398951) | Cod sursa (job #2749738)
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
struct edge {
int x, y, cost;
bool operator <(const edge& other) const{
return cost < other.cost;
}
};
vector <edge> v;
vector <int> h, t;
vector <pair <int, int> > apm;
int n, m, totalCost;
void init() {
h = vector <int> (n + 1);
t = vector <int> (n + 1);
for(int i = 1; i <= n; ++i)
t[i] = i;
}
void read() {
f >> n >> m;
init();
int x, y, cost;
for(int i = 1; i <= m; ++i) {
f >> x >> y >> cost;
v.push_back({x, y, cost});
}
sort(v.begin(), v.end());
}
int getRoot(int node) {
if(t[node] == node) {
return node;
}
return (t[node] = getRoot(t[node]));
}
bool sameConnectedComponents(int x, int y) {
return getRoot(x) == getRoot(y);
}
void unite(int x, int y) {
int rootX = getRoot(x);
int rootY = getRoot(y);
if(rootX == rootY) {
return;
}
if(h[rootX] < h[rootY]) {
t[rootX] = rootY;
}
else {
if(h[rootX] == h[rootY])
++h[rootX];
t[rootY] = rootX;
}
}
void kruskal() {
int x, y, cost;
for(const auto& p : v) {
x = p.x;
y = p.y;
cost = p.cost;
if(sameConnectedComponents(x, y))
continue;
unite(x, y);
totalCost += cost;
apm.push_back({x, y});
if(apm.size() == n - 1)
return;
}
}
void print() {
g << totalCost << '\n' << n - 1 << '\n';
for(const auto& p : apm)
g << p.first << " " << p.second << '\n';
}
int main()
{
read();
kruskal();
print();
}