BZOJ-2763: [JLOI2011]飞行路线(Dijkstra)

题目:http://www.lydsy.com/JudgeOnline/problem.php?id=2763

赤裸裸的Dijkstra算法求最短路,也没什么好说的了吧。。。

代码:

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#include <queue>
 
using namespace std ;
 
#define travel( x ) for ( vector < edge > :: iterator p = E[ x ].begin(  ) ; p != E[ x ].end(  ) ; ++ p )
#define Add( s , t , c ) E[ s ].push_back( edge( t , c ) )
#define AddEdge( s , t , c ) Add( s , t , c ) , Add( t , s , c )
#define rep( i , x ) for ( int i = 0 ; i < x ; ++ i )
 
const int inf = 0x7fffffff ;
const int maxn = 10010 , maxk = 15 ;
 
struct edge {
    int t , d ;
    edge( int _t , int _d ) : t( _t ) , d( _d ) {
    }
};
 
vector < edge > E[ maxn ] ;
 
int dist[ maxn ][ maxk ] ;
bool f[ maxn ][ maxk ] ;
 
struct node {
    int t , x ;
    bool operator < ( const node &a ) const {
        return dist[ t ][ x ] > dist[ a.t ][ a.x ] ;
    }
    node( int _t , int _x ) : t( _t ) , x( _x ) {
    }
};
 
priority_queue < node > q ;
 
int n , m , k , S , T ;
 
void update( node u , int d ) {
    dist[ u.t ][ u.x ] = d ; 
    q.push( u ) , f[ u.t ][ u.x ] = true ;
}
 
int main(  ) {
    scanf( "%d%d%d%d%d" , &n , &m , &k , &S , &T ) ;
    while ( m -- ) {
        int s , t , d ; scanf( "%d%d%d" , &s , &t , &d ) ;
        AddEdge( s , t , d ) ;
    }
    rep( i , n ) rep( j , k + 1 ) dist[ i ][ j ] = inf ;
    memset( f , true , sizeof( f ) ) ;
    dist[ S ][ 0 ] = 0 , q.push( node( S , 0 ) ) ;
    while ( ! q.empty(  ) ) {
        node v = q.top(  ) ; q.pop(  ) ;
        if ( ! f[ v.t ][ v.x ] ) continue ;
        f[ v.t ][ v.x ] = false ;
        int cost ;
        travel( v.t ) {
            if ( ( cost = dist[ v.t ][ v.x ] + p -> d ) < dist[ p -> t ][ v.x ] ) {
                update( node( p -> t , v.x ) , cost ) ;
            }
            if ( v.x < k ) if ( ( cost = dist[ v.t ][ v.x ] ) < dist[ p -> t ][ v.x + 1 ] ) {
                update( node( p -> t , v.x + 1 ) , cost ) ;
            }
        }
    }
    int ans = inf ;
    rep( i , k + 1 ) ans = min( ans , dist[ T ][ i ] ) ;
    printf( "%d\n" , ans ) ;
    return 0 ; 
}
    原文作者:AmadeusChan
    原文地址: https://www.jianshu.com/p/8c480ad52954
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞