Cod sursa(job #3156729)

Utilizator Luca_Miscocilucainfoarena Luca_Miscoci Data 12 octombrie 2023 19:08:06
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <bits/stdc++.h>

using namespace std;
const int mmax = 4 * 1e5;
const int nmax = 2 * 1e5;



int parent[nmax + 1];

vector <pair<int, int>> ans;
int n, m;

struct edge {
   int x, y, c;
};

struct edge edges[mmax];

inline bool operator < (struct edge a, struct edge b) {
  return a.c < b.c;
}

void build (int n) {
  for ( int i = 1; i <= n; i ++ )
    parent[i] = i;
}

int get_root (int node) {
  if ( parent[node] == node )
    return node;
  return parent[node] = get_root(parent[node]);
}

void join(int x, int y) {
  int rx, ry;

  rx = get_root(x);
  ry = get_root(y);

  parent[ry] = rx;
}

int main(){


  ifstream fin ("apm.in");
  ofstream fout ("apm.out");

  fin >> n >> m;
  for ( int i = 0; i < m; i ++ )
    fin >> edges[i].x >> edges[i].y >> edges[i].c;

  build (n);

  sort(edges, edges + m);

  int sum = 0;
  for ( int i = 0; i < m; i++ ) {
    if ( get_root(edges[i].x) != get_root(edges[i].y) ) {
      join(get_root(edges[i].x), get_root(edges[i].y));
      sum += edges[i].c;
      ans.push_back(make_pair(edges[i].x, edges[i].y));
    }
  }

  fout << sum << " " << ans.size() << "\n";
  for ( auto i : ans )
    fout << i.second << " " << i.first << "\n";

  return 0;
}