hdu 6705 path

题意:找第k短的路径

思路:优先队列bfs(启发式搜索)

#include 
#define fi first
#define se second
using namespace std;
typedef long long LL;
typedef int lint;
const int maxk = 50005;
const int maxn = 50005;
const int maxq = 50005;
struct type{
    LL v;
    int x,id;
    type( LL vv = 0,int xx = 0,int idid= 0 ){
        v = vv; x = xx;id = idid;
    }
    bool operator < ( const type& b )const{
        return v >b.v;
    }
};
typedef pair pii;
vector ve[maxn];
LL ans[maxk];
int query[maxq];
priority_queue que;

void init( int n ){
    while(que.size()) que.pop();
    for( int i =0 ;i <= n;i++ ) ve[i].clear();
}

int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        int n,m,q,x,y;
        LL w;
        scanf("%d%d%d",&n,&m,&q);
        init(n);
        for( int i = 1;i <= m;i++ ){
            scanf("%d%d%lld",&x,&y,&w);
            ve[x].push_back( pii( w,y ) );
        }
        int mx = 0;
        for( int i = 1;i <= q;i++ ){
            scanf("%d",&query[i]);
            mx = max( mx,query[i] );
        }
        for( int i = 1;i <= n;i++ ){
            sort( ve[i].begin(),ve[i].end() );
        }
        for( int i = 1;i <= n;i++ ){
            if( ve[i].size() )
            que.push( type( ve[i][0].fi,i,0 ) );
        }
        int cnt = 0;
        while( que.size() ){
            type cur = que.top();
            que.pop();
            int x = cur.x;
            int id = cur.id;
            LL v = cur.v;
            if(v)
                ans[++cnt] = cur.v;
            if( cnt == mx )
                break;
            if( id < (int)ve[x].size()-1 )
                que.push( type( v-ve[x][id].fi + ve[x][id+1].fi,x ,id+1  ) );
            int y = ve[x][id].se;
            if( ve[y].size() )
            que.push( type( v+ve[y][0].fi,y,0 ) );
        }
        for( int i = 1;i <= q;i++ ){
            printf("%lld\n",ans[ query[i] ]   );
        }
    }
    return 0;
}

 

你可能感兴趣的:(搜索,搜索)