Pagini recente » Cod sursa (job #1282169) | Cod sursa (job #2333544) | Cod sursa (job #2910098) | Cod sursa (job #2401564) | Cod sursa (job #438034)
Cod sursa(job #438034)
/*
* File: main.cpp
* Author: VirtualDemon
*
* Created on April 10, 2010, 9:57 AM
*/
#include <vector>
#include <cstdlib>
#include <fstream>
#include <algorithm>
#define INF 0x3f3f3f3f
#define Nmax 200011
/*
*
*/
using namespace std;
class pr
{
public:
int y, c;
pr* next;
pr( void ) : y(0), c(INF) { }
pr( int _y, int _c ) : y(_y), c(_c) { }
} *G[Nmax];
int N=1;
int H[Nmax], P[Nmax], D[Nmax], apm[Nmax];
inline void add( const int& x, const int& y, const int& c )
{
pr* q=new pr, *p=new pr;
q->y=y; q->c=c;
p->y=x; p->c=c;
q->next=G[x];
G[x]=q;
p->next=G[y];
G[y]=p;
}
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 )
{
pr* it;
int n, M, x, y, c, s=0;
ifstream in( "apm.in" );
in>>n;
for( in>>M; M; --M )
{
in>>x>>y>>c;
add( x, y, c );
}
H[1]=1;
while( N )
{
x=pop();
s+=D[x];
P[x]=-1;
for( it=G[x]; it; it=it->next )
if( -1 != P[it->y] )
{
y=it->y, c=it->c;
if( !P[y] )
{
D[y]=c;
apm[y]=x;
push(y);
continue;
}
if( D[y] > c )
{
D[y]=c;
apm[y]=x;
UpHeap( P[y] );
}
}
}
ofstream out( "apm.out" );
out<<s<<'\n'<<(n-1)<<'\n';
for( x=2; x <= n; ++x )
out<<x<<' '<<apm[x]<<'\n';
return EXIT_SUCCESS;
}