Cod sursa(job #1377596)

Utilizator andreismara97Smarandoiu Andrei andreismara97 Data 5 martie 2015 22:53:09
Problema Arbore partial de cost minim Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 2.05 kb
#include<fstream>
#include<vector>
using namespace std;
ifstream in("apm.in");
ofstream out("apm.out");

#define N 200001
#define INF ((1<<31)-1)

struct muchie
{
    int y, cost;
};

vector <muchie> a[N];

int n, m;
int d[N];
int nh;
int h[N], poz[N];
int ok[N], pred[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>1 && d[h[i]] < d[h[i/2]])
    {
        schimba(i, i/2);
        i/=2;
    }
}

void coboara(int i)
{
    int bun = i, fs = i*2, fd = i*2+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)
{
    schimba(i, nh);
    nh--;
    coboara(i);
    urca(i);
}

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

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

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

            if(cost < d[y] && !ok[y])
            {
                d[y] = cost;
                pred[y] = x;

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

void citire()
{
    int x, y, cost;

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

        a[x].push_back((muchie) {y, cost});
        a[y].push_back((muchie) {x, cost});
    }
}

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

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

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