Pagini recente » Cod sursa (job #664309) | Cod sursa (job #2580570) | Cod sursa (job #1129642) | Cod sursa (job #833685) | Cod sursa (job #3271297)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
void solve(const vector<vector<int>>& graph, int n)
{
vector<int> tata(n + 1, 0), h(n + 1, 0);
int cost_apcm = 0;
vector<vector<int>> new_edges;
auto Reprez = [&](int nod) {
while(tata[nod] != 0) {
nod = tata[nod];
}
return nod;
};
for(const vector<int>& i: graph) {
int u = i[0];
int v = i[1];
int cost = i[2];
int ru = Reprez(u);
int rv = Reprez(v);
if(ru != rv) {
new_edges.push_back({u, v});
cost_apcm += cost;
if(h[ru] > h[rv]) {
tata[rv] = ru;
}
else {
tata[ru] = rv;
if(h[ru] == h[rv]) {
h[rv] = h[rv] + 1;
}
}
}
}
fout << cost_apcm << endl;
fout << new_edges.size() << endl;
for(const vector<int>& edge: new_edges)
{
fout << edge[0] << ' ' << edge[1] << endl;
}
}
int main()
{
int n, m;
fin >> n >> m;
vector<vector<int>> graph;
for(int i = 0; i < m; i++)
{
int a, b, c;
fin >> a >> b >> c;
graph.push_back({a, b, c});
}
sort(graph.begin(), graph.end(), [](const vector<int>& a, const vector<int>& b) {
return a[2] < b[2];
});
solve(graph, n);
return 0;
}