Cod sursa(job #1968260)

Utilizator DiClauDan Claudiu DiClau Data 17 aprilie 2017 16:23:34
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.94 kb
#include<stdio.h>
using namespace std;
const int N = 200005, M = 400000, INF = 10005;
int v[N], h[N], poz[N], lst[N], vf[2 * M], urm[2 * M], c[2 * M], nrm, nrh, pre[N];
void adauga (int x, int y, int cost)
{
    vf[++nrm] = y;
    c[nrm] = cost;
    urm[nrm] = lst[x];
    lst[x] = nrm;
}
void schimba (int p1, int p2)
{
    int aux = h[p1];
    h[p1] = h[p2];
    h[p2] = aux;
    poz[h[p1]] = p1;
    poz[h[p2]] = p2;
}
void urca (int p)
{
    while (p > 1 && v[h[p]] < v[h[p >> 1]])
    {
        schimba (p, p >> 1);
        p >>= 1;
    }
}
void coboara (int p)
{
    int bun = p, fs = 2 * p, fd = 2 * p + 1;
    if (fs <= nrh && v[h[fs]] < v[h[bun]])
        bun = fs;
    if (fd <= nrh && v[h[fd]] < v[h[bun]])
        bun = fd;
    if (bun != p)
    {
        schimba (bun, p);
        coboara (bun);
    }
}
void init (int n)
{
    int i;
    for (i = 2; i <= n; i++)
    {
        v[i] = INF;
        h[i] = i;
        poz[i] = i;
    }
    nrh = n;
}
int main ()
{
    FILE *in, *out;
    in = fopen ("apm.in", "r");
    out = fopen ("apm.out", "w");
    int n, m;
    fscanf (in, "%d%d", &n, &m);
    int i, x, y, cost;
    for (i = 1; i <= m; i++)
    {
        fscanf (in, "%d%d%d", &x, &y, &cost);
        adauga (x, y, cost);
        adauga (y, x, cost);
    }
    int p;
    h[++nrh] = 1;
    poz[1] = 1;
    init(n);
    int s = 0;
    while (nrh != 0)
    {
        x = h[1];
        s += v[h[1]];
        schimba (1, nrh--);
        poz[x] = -1;
        coboara (1);
        p = lst[x];
        while (p != 0)
        {
            y = vf[p];
            if (poz[y] != -1 && c[p] < v[y])
            {
                v[y] = c[p];
                urca (poz[y]);
                pre[y] = x;
            }
            p = urm[p];
        }
    }
    fprintf (out, "%d\n%d\n", s, n - 1);
    for (i = 2; i <= n; i++)
        fprintf (out, "%d %d\n", i, pre[i]);
    return 0;
}