Pagini recente » Cod sursa (job #2017684) | Borderou de evaluare (job #1525387) | Monitorul de evaluare | Borderou de evaluare (job #2481461) | Cod sursa (job #548552)
Cod sursa(job #548552)
#include <vector>
#include <fstream>
#include <cstdlib>
#include <iterator>
#include <algorithm>
#define N_MAX 200011
#define oo 1<<20
#define pr pair< int, int >
#define mkpr make_pair< int, int >
using namespace std;
bool was[N_MAX];
int lHeap;
int apm[N_MAX], d[N_MAX], P[N_MAX], H[N_MAX];
vector< pr > G[N_MAX];
vector< pr >::const_iterator it, iend;
inline void _swap( int& x, int& y ) { int aux=x; x=y; y=aux; }
void DownHeap( int k )
{
for( int son=2*k; son <= lHeap; k=son, son=k*2 )
{
if( son+1 < lHeap && 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;
}
}
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 void push( int k, int cost )
{
d[k]=cost;
H[++lHeap]=k;
P[k]=lHeap;
UpHeap( lHeap );
}
inline int pop()
{
int r=H[1];
P[H[1]]=-1;
H[1]=H[lHeap];
P[H[1]]=1;
--lHeap;
DownHeap( 1 );
return r;
}
int main( void )
{
int N, M, i, x, y, c, s=0;
ifstream in( "apm.in" );
for( in>>N>>M; M; --M )
{
in>>x>>y>>c;
G[x].push_back( mkpr( y, c ) );
G[y].push_back( mkpr( x, c ) );
}
for( i=0; i <= N; ++i )
apm[i]=i, d[i]=oo;
d[1]=0;
for( push( 1, 0 ); lHeap; )
{
x=pop();
s+=d[x];
for( it=G[x].begin(), iend=G[x].end(); it < iend; ++it )
if( d[it->first] > it->second )
{
apm[it->first]=x;
if( 0 == P[it->first] )
push( it->first, it->second );
else if( P[it->first] > 0 )
{
d[it->first]=it->second;
UpHeap( P[it->first] );
}
}
}
ofstream out( "apm.out" );
out<<s<<'\n'<<(N-1)<<'\n';
for( y=2; y <= N; ++y )
out<<y<<' '<<apm[y]<<'\n';
return EXIT_SUCCESS;
}