Pagini recente » Cod sursa (job #2667198) | Cod sursa (job #449010) | Cod sursa (job #259889) | Cod sursa (job #2637510) | Cod sursa (job #2817356)
#include <bits/stdc++.h>
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
int n, m;
int t[200001], r[200001];
struct edge{
int cost, x, y;
};
vector<edge> edges;
bool cmp(edge edge1, edge edge2)
{
return edge1.cost < edge2.cost;
}
void read()
{
f>>n>>m;
int x, y, z;
for(int i = 1;i <= m;++i)
f>>x>>y>>z, edges.push_back({z, x, y});
}
int found(int x)
{
if(t[x] == x)
return x;
return t[x] = found(t[x]);
}
void unite(int x, int y)
{
if(r[x] > r[y])
t[y] = x, r[x] += r[y];
else
t[x] = y, r[y] += r[x];
}
void solve()
{
for(int i = 1;i <= n;++i)
r[i] = 1, t[i] = i;
sort(edges.begin(), edges.end(), cmp);
int cost = 0;
vector<pair<int, int>> result;
for(edge it : edges)
if(found(it.x) != found(it.y))
{
cost += it.cost;
unite(found(it.x), found(it.y));
result.push_back(make_pair(it.x, it.y));
}
g<<cost<<'\n';
for(auto it : result)
g<<it.first<<" "<<it.second<<'\n';
}
int main()
{
read();
solve();
return 0;
}