Pagini recente » Cod sursa (job #171882) | Cod sursa (job #3206225) | Cod sursa (job #885008) | Cod sursa (job #1651490) | Cod sursa (job #2559614)
#include <iostream>
#include <fstream>
using namespace std;
ifstream in("apm.in");
ofstream out("apm.out");
const int N = 200000, M = 400000, INF = 1 << 30;
int n, m, d[N], lst[N], vf[2*M], urm[2*M], pred[N], h[N], poz[N], nh, nr, cost, cst[2*M];
void schimb(int p, int q)
{
swap(h[p], h[q]);
poz[h[p]] = p;
poz[h[q]] = q;
}
void urca(int p)
{
while(p > 1 && d[h[p]] < d[h[p / 2]]){
schimb(p, p / 2);
p /= 2;
}
}
void adauga_lista(int a, int b, int c)
{
vf[++nr] = b;
cst[nr] = c;
urm[nr] = lst[a];
lst[a] = nr;
vf[++nr] = a;
cst[nr] = c;
urm[nr] = lst[b];
lst[b] = nr;
}
void adauga_heap(int p)
{
h[++nh] = p;
poz[p] = nh;
urca(nh);
}
void coboara(int p)
{
int fs = 2 * p, fd = 2 * p + 1, bun = p;
if(fs <= nh && d[h[fs]] < d[h[bun]]){
bun = fs;
}
if(fd <= nh && d[h[fd]] < d[h[bun]]){
bun = fd;
}
if(bun != p){
schimb(bun, p);
coboara(bun);
}
}
void sterge(int p)
{
schimb(p, nh--);
urca(p);
coboara(p);
}
void prim()
{
int x, y, c;
for(int i = 2; i <= n; i++){
d[i] = INF;
adauga_heap(i);
}
d[1] = 0;
adauga_heap(1);
//cout << "\n\n";
while(nh > 0){
x = h[1];
//cout << pred[x] << "\t" << x << "\t" << d[x] << "\n";
sterge(1);
poz[x] = -1;
cost += d[x];
//cnt++;
for(int p = lst[x]; p != 0; p = urm[p]){
y = vf[p];
c = cst[p];
if(poz[y] != -1 && c < d[y]){
d[y] = c;
urca(poz[y]);
pred[y] = x;
}
}
}
}
int main()
{
in >> n >> m;
int x, y, z;
for(int i = 1; i <= m; i++){
in >> x >> y >> z;
adauga_lista(x, y, z);
}
prim();
out << cost << "\n" << n - 1 << "\n";
for(int i = 2; i <= n; i++){
out << pred[i] << " " << i << "\n";
}
return 0;
}