Cod sursa(job #3318972)

Utilizator busoistefanBusoi Radulescu Stefan busoistefan Data 30 octombrie 2025 08:25:22
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.95 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <set>
#include <map>
using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");
int dads[200006];
int forest(int x) {
  if (dads[x]==0)
    return x;
  return dads[x]=forest(dads[x]);

}
struct edge{
  int x;
  int y;
  int cost;

  bool operator <(const edge& other) const {
    return cost>other.cost;
  }
};
priority_queue<edge> edges;
vector<edge> ans;
int main(){
  int n,m,s=0;

  f>>n>>m;
  for(int i=0;i<m;i++){
    int x,y,cost;
    f>>x>>y>>cost;
    edges.emplace(x,y,cost);
  }
  while (edges.size()) {
    auto x=edges.top();
    edges.pop();
    int forest1=forest(x.x);
    int forest2=forest(x.y);
    if (forest1!=forest2) {
      ans.push_back(x);
      s+=x.cost;
      dads[forest1]=forest2;
    }

  }
  g<<s<<"\n"<<size(ans)<<"\n";
  for (auto x:ans) {
    g<<x.x<<" "<<x.y<<"\n";
  }

  return 0;
}