Cod sursa(job #1649749)

Utilizator lacraruraduRadu Matei Lacraru lacraruradu Data 11 martie 2016 14:55:44
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.92 kb
#include <fstream>

using namespace std;

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

#define N 200001
#define M 400001
#define INF 2147483647

int n, m;
int lst[N], vf[M], urm[M], cost[M], nvf = 0;
int h[N], poz[N], nh = 0;
int d[N], t[N];
bool ok[N];

void schimba(int i1, int i2)
{
    swap(h[i1], h[i2]);
    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 >>= 1;
    }
}

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

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

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

int main()
{
    in >> n >> m;
    while(m--)
    {
        int x, y, c;
        in >> x >> y >> c;
        vf[++nvf] = y;
        urm[nvf] = lst[x];
        cost[nvf] = c;
        lst[x] = nvf;
        vf[++nvf] = x;
        urm[nvf] = lst[y];
        cost[nvf] = c;
        lst[y] = nvf;
    }

    for(int i = 2; i <= n; i++)
        d[i] = INF;
    adauga(1);
    while(nh)
    {
        int x = h[1];
        ok[x] = 1;
        sterge(1);

        for(int i = lst[x]; i; i = urm[i])
            if(!ok[vf[i]] && cost[i] < d[vf[i]])
            {
                d[vf[i]] = cost[i];
                t[vf[i]] = x;
                if(poz[vf[i]])
                    urca(poz[vf[i]]);
                else
                    adauga(vf[i]);
            }
    }

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

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