Cod sursa(job #438019)

Utilizator alexandru92alexandru alexandru92 Data 10 aprilie 2010 13:46:30
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.99 kb
/* 
 * File:   main.cpp
 * Author: VirtualDemon
 *
 * Created on April 10, 2010, 9:57 AM
 */
#include <vector>
#include <cstdlib>
#include <fstream>
#include <algorithm>
#define Nmax 200001

/*
 * 
 */
using namespace std;
typedef pair< int, int > pr;
int N=1;
int H[Nmax], P[Nmax], D[Nmax], apm[Nmax];
vector< vector< pr > > G;
vector< pr >::const_iterator it, iend;
inline void DownHeap( int k )
{
    for( int son=2*k; son <= N; k=son, son=2*k )
    {
        if( son < N && D[H[son+1]] < D[H[son]] )
            ++son;
        if( D[H[k]] <= D[H[son]] )
            return;
        swap( H[k], H[son] );
        P[H[k]]=k;
        P[H[son]]=son;
    }
}
inline void UpHeap( int k )
{
    for( int key=D[H[k]], f=k/2; k > 1 && key < D[H[f]]; k=f, f/=2 )
    {
        swap( H[k], H[f] );
        P[H[k]]=k;
        P[H[f]]=f;
    }
}
inline int pop( void )
{
    int r=H[1];
    P[H[1]]=P[H[N]];
    H[1]=H[N];
    --N;
    DownHeap( 1 );
    return r;
}
inline void push( int k )
{
    H[++N]=k;
    P[k]=N;
    UpHeap(N);
}
int main( void )
{
    int n, M, x, y, c, s=0;
    ifstream in( "apm.in" );
    in>>n;
    G.resize(n);
    for( in>>M; M; --M )
    {
        in>>x>>y>>c;
        --x, --y;
        G[x].push_back( pr( y, c ) );
        G[y].push_back( pr( x, c ) );
    }
    while( N )
    {
        x=pop();
        s+=D[x];
        P[x]=-1;
        for( it=G[x].begin(), iend=G[x].end(); it < iend; ++it )
            if( -1 != P[it->first] )
            {
                y=it->first, c=it->second;
                if( !P[y] )
                {
                    D[y]=c;
                    apm[y]=x+1;
                    push(y);
                    continue;
                }
                if( D[y] > c )
                {
                    D[y]=c;
                    apm[y]=x+1;
                    UpHeap( P[y] );
                }
            }
    }
    ofstream out( "apm.out" );
    out<<s<<'\n'<<(n-1)<<'\n';
    for( x=1; x < n; ++x )
        out<<(x+1)<<' '<<apm[x]<<'\n';
    return EXIT_SUCCESS;
}