Pagini recente » Cod sursa (job #2427356) | Cod sursa (job #2566877) | Clasament o__o | Cod sursa (job #1579420) | Cod sursa (job #2551147)
#include <bits/stdc++.h>
using namespace std;
ifstream in ("apm.in");
ofstream out ("apm.out");
const int MAX = 200001;
const int INF = 2e9;
int h[MAX], poz[MAX], d[MAX], x, y, n, nh, cst[2*MAX], cost, urm[2*MAX], vf[2*MAX], lst[2*MAX], c, nr, pred[MAX], m;
void adauga(int x, int y, int c)
{
vf[++nr] = y;
urm[nr] = lst[x];
lst[x] = nr;
cst[nr] = c;
}
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 ad_in_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--);
coboara(p);
}
void prim()
{
for(int i = 2; i <= n; i++)
{
d[i] = INF;
}
for(int i = 1; i <= n; i++)
{
ad_in_heap(i);
}
d[1] = 0;
while(nh > 0)
{
x = h[1];
sterge(1);
poz[x] = -1;
cost += d[x];
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;
while(m--)
{
in >> x >> y >> c;
adauga(x,y,c);
adauga(y,x,c);
}
prim();
out << cost << "\n" << n - 1 << "\n";
for(int i = 2; i <= n; i++)
{
out << pred[i] << " " << i;
out << "\n";
}
return 0;
}