Cod sursa(job #1338068)

Utilizator lacraruraduRadu Matei Lacraru lacraruradu Data 9 februarie 2015 19:25:57
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.21 kb
#include <fstream>
#include <vector>

using namespace std;

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


struct nod
{
    int v, c;
};


const int N = 200001;
const int INF = 1001;

int n, m;
int l[N], poz[N], pred[N];
bool t[N];
vector<nod> a[N];

int nh, h[N];
void schimba(int i1, int i2);
void adauga(int x);
void sterge(int i);
void urca(int i);
void coboara(int i);


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 adauga(int x)
{
    h[++nh] = x;
    poz[h[nh]] = nh;
    urca(nh);
}

void sterge(int i)
{
    schimba(i, nh);
    nh--;
    coboara(i);
    urca(i);
}

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

void coboara(int i)
{
    int bun = i, fs = 2 * i, fd = 2 * i + 1;

    if(fs <= nh && l[h[fs]] < l[h[bun]])
        bun = fs;
    if(fd <= nh && l[h[fd]] < l[h[bun]])
        bun = fd;

    if(i != bun)
    {
        schimba(i, bun);
        coboara(bun);
    }
}


void apm(int x)
{
    for(int i = 1; i <= n; i++)
        l[i] = INF;

    l[x] = 0;
    adauga(x);

    while(nh != 0)
    {
        x = h[1];
        t[x] = true;
        sterge(1);

        for(size_t i = 0; i < a[x].size(); i++)
        {
            int y = a[x][i].v;
            int c = a[x][i].c;

            if(!t[y] && c < l[y])
            {
                l[y] = c;
                pred[y] = x;

                if(poz[y] == 0)
                    adauga(y);
                else
                    urca(poz[y]);
            }
        }
    }
}


void citire()
{
    nh = 0;
    in >> n >> m;

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

        a[x].push_back((nod){y, c});
        a[y].push_back((nod){x, c});
    }
}

void afisare()
{
    int s = 0;
    for(int i = 1; i <= n; i++)
        s += l[i];

    out << s << '\n' << n - 1 << '\n';

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

}

int main()
{
    citire();
    apm(1);
    afisare();
    return 0;
}