Pagini recente » Monitorul de evaluare | Cod sursa (job #3320201) | Cod sursa (job #3134880) | Cod sursa (job #342291) | Cod sursa (job #3320186)
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <utility>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
struct muchie{
int x, y, c;
};
int p[200001], h[200001];
muchie v[400001];
vector<pair<int,int>> a;
bool cmp(muchie a, muchie b){
return a.c < b.c;
}
int Find(int x){
while(x != p[x]){
x = p[x];
}
return x;
}
void Union(int x,int y){
x = Find(x);
y = Find(y);
if (h[x] < h[y]){
p[x] = y;
}
else{
if (h[x] > h[y]){
p[y] = x;
}
else {
p[x] = y;
h[y]++;
}
}
}
int main(){
int n, m;
fin >> n >> m;
for (int i=1; i<=m; i++){
int x,y,c;
fin >> x >> y >> c;
v[i] = {x,y,c};
}
for (int i=0; i<=n; i++){
p[i] = i;
h[i] = 1;
}
sort(v+1, v+m+1, cmp);
int sol = 0;
for (int i=1; i<=m; i++){
if (Find(v[i].x) != Find(v[i].y)){
sol+=v[i].c;
a.push_back({v[i].x,v[i].y});
Union(v[i].x,v[i].y);
}
}
fout << sol << "\n";
fout << a.size() << "\n";
for (auto& i : a){
fout << i.second << " " << i.first << "\n";
}
}