Cod sursa(job #2916608)

Utilizator MR0L3eXMaracine Constantin Razvan MR0L3eX Data 30 iulie 2022 20:27:09
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
/**
 *    author:  R0L3eX
 *    created: 30.07.2022 19:32:03
 *    quote: Claustrophobic? Who would ever be afraid of Santa Clause?
**/

#include "bits/stdc++.h"

using namespace std;

#if defined(ONPC)
#include "bits/debug.h"
#endif

#define uid(a, b) uniform_int_distribution<int>(a, b)(rng)
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

const int MOD = 1e9 + 7;
const int mxN = 2e5;
const int INF = INT_MAX;
const char nl = '\n';

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

vector<int> rep, sz;
vector<array<int, 3>> edg;

int find(int a) {
  if (a == rep[a]) return a;
  return rep[a] = find(rep[a]);
}

bool join(int a, int b) {
  a = find(a), b = find(b);
  if (a == b) return false;
  if (sz[a] < sz[b]) swap(a, b);
  sz[a] += sz[b];
  rep[b] = a;
  return true;
}

void init(int n, int m) {
  edg = vector<array<int, 3>>(m);
  rep = sz = vector<int>(n);

  for (int node = 0; node < n; ++node) {
    sz[node] = 1;
    rep[node] = node;
  }
}

int main() {
  cin.tie(0)->sync_with_stdio(0);

  int n, m;
  fin >> n >> m;

  init(n, m);

  for (int i = 0; i < m; ++i) {
    int a, b, c;
    fin >> a >> b >> c;
    --a, --b;
    edg[i] = {c, a, b};
  }

  sort(edg.begin(), edg.end());

  int cost = 0;
  vector<array<int, 2>> ans_edg;
  for (int e = 0; e < m; ++e) {
    if (join(edg[e][1], edg[e][2])) {
      cost += edg[e][0];
      ans_edg.push_back({edg[e][1], edg[e][2]});
    }
  } 

  fout << cost << nl;
  for (array<int, 2> e : ans_edg) {
    fout << e[0] + 1 << ' ' << e[1] + 1 << nl;
  }
}