SPFA,好久没练,有点生疏了
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
long long dis[ 10010 ] , v[ 10010 ] , f[ 1000010 ] , ph[ 10010 ] ;
long long m, n, k, x, y, d, t;
int b[ 10010 ] [ 5 ] , tot, head[ 10010 ] ;
struct node
{
int d, w;
} a[ 10010 ] ;
void ljb ( int x, int y, int d)
{
tot++ ;
b[ tot] [ 2 ] = y;
b[ tot] [ 3 ] = d;
b[ tot] [ 4 ] = head[ x] ;
head[ x] = tot;
}
bool cmp ( node x, node y)
{
return x. d< y. d;
}
void spfa ( int x, int z)
{
memset ( dis, 1 , sizeof ( dis) ) ;
memset ( v, 0 , sizeof ( v) ) ;
memset ( ph, 0 , sizeof ( ph) ) ;
dis[ x] = 0 ;
f[ 1 ] = x;
v[ x] = 1 ;
int hd= 0 , tl= 1 ;
while ( hd<= tl)
{
hd++ ;
int x1= f[ hd] ;
for ( int i= head[ x1] ; i; i= b[ i] [ 4 ] )
{
int y= b[ i] [ 2 ] ;
if ( dis[ y] > dis[ x1] + b[ i] [ 3 ] )
{
dis[ y] = dis[ x1] + b[ i] [ 3 ] ;
if ( v[ y] == 0 )
{
v[ y] = 1 ;
tl++ ;
f[ tl] = y;
ph[ y] ++ ;
if ( ph[ y] > n)
{
cout<< - 1 << endl;
return ;
}
}
}
}
v[ x1] = 0 ;
}
if ( z== 1 )
cout<< dis[ a[ n] . w] ;
else
cout<< dis[ a[ 1 ] . w] ;
cout<< endl;
}
int main ( )
{
freopen ( "attack.in" , "r" , stdin ) ;
freopen ( "attack.out" , "w" , stdout ) ;
cin>> t;
for ( int i= 1 ; i<= t; i++ )
{
memset ( b, 0 , sizeof ( b) ) ;
memset ( head, 0 , sizeof ( head) ) ;
tot= 0 ;
cin>> n>> d;
for ( int i= 1 ; i<= n; i++ )
{
cin>> a[ i] . d;
a[ i] . w= i;
ljb ( i, i- 1 , - 1 ) ;
}
sort ( a+ 1 , a+ 1 + n, cmp) ;
for ( int i= 1 ; i<= n- 1 ; i++ )
{
if ( a[ i] . w> a[ i+ 1 ] . w)
ljb ( a[ i+ 1 ] . w, a[ i] . w, d) ;
else
ljb ( a[ i] . w, a[ i+ 1 ] . w, d) ;
}
if ( a[ 1 ] . w< a[ n] . w)
spfa ( a[ 1 ] . w, 1 ) ;
else
spfa ( a[ n] . w, n) ;
}
return 0 ;
}