Cod sursa(job #1376205)

Utilizator lacraruraduRadu Matei Lacraru lacraruradu Data 5 martie 2015 16:33:26
Problema Arbore partial de cost minim Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.12 kb
#include <fstream>

#define N 200001
#define M 400001
#define INF 2147483647
using namespace std;

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

int n, m;
int d[N];
int t[N];

int lst[N], vf[M], urm[M], cost[M], nvf = 0;

int h[N], poz[N], nh = 0;
bool ok[N];

void schimba(int i1, int i2)
{
    int aux = h[i1];
    h[i1] = h[i2];
    h[i2] = aux;
    poz[h[i1]] = i1;
    poz[h[i2]] = i2;
}

void urca(int i)
{
    while(i >= 2 && d[h[i]] < d[h[i >> 1]])
    {
        schimba(i, i >> 1);
        i = i >> 1;
    }
}

void coboara(int i)
{
    int bun = i, fs = i << 1, fd = (i << 1) + 1;
    if(fs <= nh && d[h[fs]] < d[h[bun]])
        bun = fs;
    if(fd <= nh && d[h[fd]] < d[h[bun]])
        bun = fd;
    if(i != bun)
    {
        schimba(i, bun);
        coboara(bun);
    }
}

void adauga(int x)
{
    h[++nh] = x;
    poz[x] = nh;
    urca(nh);
}

void sterge(int i)
{
    poz[h[i]] = 0;
    schimba(i, nh);
    nh--;
    urca(i);
    coboara(i);
}

void prim(int x)
{
    for(int i = 1; i <= n; i++)
        d[i] = INF;
    d[x] = 0;
    adauga(x);

    while(nh)
    {
        x = h[1];
        ok[x] = 1;
        sterge(1);

        for(int i = lst[x]; i; i = urm[i])
        {
            int y = vf[i];
            int c = cost[i];

            if(!ok[y] && c < d[y])
            {
                t[y] = x;
                d[y] = c;
                if(poz[y] == 0)
                    adauga(y);
                else
                    urca(y);
            }
        }
    }
}

int main()
{
    in >> n >> m;

    for(int i = 1; i <= m; i++)
    {
        int x, y, c;
        in >> x >> y >> c;

        vf[++nvf] = y;
        cost[nvf] = c;
        urm[nvf] = lst[x];
        lst[x] = nvf;
        vf[++nvf] = x;
        cost[nvf] = c;
        urm[nvf] = lst[y];
        lst[y] = nvf;
    }

    prim(1);

    int sum = 0;
    for(int i = 1; i <= n; i++)
        sum += d[i];
    out << sum << '\n';
    out << n - 1 << '\n';

    for(int i = 2; i <= n; i++)
        out << t[i] << ' ' << i << '\n';
    return 0;
}