样例输入
6
0 3 1 6 2 1 3 5
1 3 0 6 2 5 4 3
2 5 0 1 1 5 3 5 4 6 5 4
3 3 0 5 2 5 5 4
4 3 1 3 2 6 5 6
5 3 4 6 2 4 3 2
样例输出
15
代码
# include <iostream>
# include <algorithm>
# include <queue>
using namespace std;
static const int MAX = 10000 ;
static const int INFTY = ( 1 << 20 ) ;
static const int WHITE = 0 ;
static const int GRAY = 1 ;
static const int BLACK = 2 ;
int n;
vector< pair< int , int >> adj[ MAX] ;
int prim ( ) {
priority_queue< pair< int , int >> PQ;
int color[ MAX] ;
int d[ MAX] ;
int p[ MAX] ;
for ( int i = 0 ; i < n; i++ )
{
d[ i] = INFTY;
p[ i] = - 1 ;
color[ i] = WHITE;
}
d[ 0 ] = 0 ;
PQ. push ( make_pair ( 0 , 0 ) ) ;
while ( ! PQ. empty ( ) )
{
pair< int , int > f = PQ. top ( ) ;
PQ. pop ( ) ;
int u = f. second;
color[ u] = BLACK;
if ( d[ u] < f. first * ( - 1 ) )
continue ;
for ( int j = 0 ; j < adj[ u] . size ( ) ; j++ )
{
int v = adj[ u] [ j] . first;
if ( color[ v] == BLACK)
continue ;
if ( d[ v] > adj[ u] [ j] . second)
{
d[ v] = adj[ u] [ j] . second;
p[ v] = adj[ u] [ j] . second;
PQ. push ( make_pair ( d[ v] * ( - 1 ) , v) ) ;
color[ v] = GRAY;
}
}
}
int sum = 0 ;
for ( int i = 0 ; i < n; i++ )
{
if ( p[ i] != - 1 )
sum += p[ i] ;
}
return sum;
}
int main ( )
{
int k, u, v, c;
cin >> n;
for ( int i = 0 ; i < n; i++ )
{
cin >> u >> k;
for ( int j = 0 ; j < k; j++ )
{
cin >> v >> c;
adj[ u] . push_back ( make_pair ( v, c) ) ;
}
}
cout << prim ( ) ;
return 0 ;
}