Cod sursa(job #1950847)

Utilizator oanaroscaOana Rosca oanarosca Data 3 aprilie 2017 12:20:39
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <fstream>
#include <queue>

using namespace std;

struct muchie {
  int x, y, c;
}m, arb[200001];

struct cmp {
  bool operator () (const muchie &a, const muchie &b) const {
    return (a.c > b.c);
  }
};

int noduri, muchii, nms, comp[200001], rang[200001], cost_total;
priority_queue<muchie, vector<muchie>, cmp> pq;

void init () {
  for (int i = 1; i <= noduri; i++)
    comp[i] = i;
}

int findset (int r) {
  while (r != comp[r])
    r = comp[r];
  return comp[r];
}

void uniune (int r1, int r2) {
  if (rang[r1] > rang[r2])
    comp[r2] = r1;
  else {
    comp[r1] = r2;
    if (rang[r1] == rang[r2])
      rang[r2]++;
  }
}

int main () {
  ifstream fi("apm.in");
  ofstream fo("apm.out");
  fi >> noduri >> muchii; init();
  for (int i = 1; i <= muchii; i++)
    fi >> m.x >> m.y >> m.c, pq.push(m);
  for (; nms < noduri-1;) {
    m = pq.top(); pq.pop();
    if (findset(m.x) != findset(m.y)) {
      arb[++nms] = m;
      cost_total += m.c;
      uniune(findset(m.x), findset(m.y));
    }
  }
  fo << cost_total << '\n';
  for (int i = 1; i <= noduri-1; i++)
    fo << arb[i].x << ' ' << arb[i].y << '\n';
  return 0;
}