HDU 4396More lumber is required 过至少K条边的最短路

 

/*
** 题目要求过最少k条边的最短路
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn = 5010;
const int maxm = 200010;
const int INF = 1<<31-1;
struct node{
    int v,len,next;
}edge[maxm];
int vis[maxn][510],head[maxn],dp[maxn][510];
int n,m,s,t,k,id;
void add_edge(int u,int v,int len){
    edge[id].v = v;edge[id].len = len;edge[id].next = head[u];head[u]= id++;
    edge[id].v = u;edge[id].len = len;edge[id].next = head[v];head[v]= id++;
}

void init(){
    int u,v,cost;
    memset(head,-1,sizeof(head));
    id = 0;
    while( m-- ){
        scanf("%d%d%d",&u,&v,&cost);
        add_edge(u,v,cost);
    }
    scanf("%d%d%d",&s,&t,&k);
}
struct NODE{
    int v,num;
};
int spfa(int s){
    int mincost = INF;
    //cout << mincost << endl;
    memset(dp,-1,sizeof(dp));
    memset(vis,0,sizeof(vis));
    NODE tmp,now;
    queue<NODE>que;
    tmp.v = s,tmp.num = 0;
    dp[tmp.v][tmp.num] = 0;
    vis[tmp.v][tmp.num] = 1;
    que.push(tmp);
    while( !que.empty()){
        now = que.front();
       // cout << now.v << " " << now.num << " " << dp[now.v][now.num] << endl;
        if(now.v == t && now.num == k && dp[now.v][now.num] < mincost)
            mincost = dp[now.v][now.num];
        vis[now.v][now.num] = 0;
        que.pop();
        for(int id = head[now.v]; id != -1; id = edge[id].next){
            int v = edge[id].v;
            tmp.v = edge[id].v;tmp.num = now.num+10;
            if( tmp.num > k)tmp.num = k;
            if(dp[tmp.v][tmp.num] == -1 || dp[tmp.v][tmp.num] > dp[now.v][now.num] + edge[id].len){
                dp[tmp.v][tmp.num] = dp[now.v][now.num] + edge[id].len;
                if( !vis[tmp.v][tmp.num]){
                    vis[tmp.v][tmp.num] = 1;
                    que.push(tmp);
                }
            }
        }
    }

    if( mincost == INF)return -1;
    return mincost;
}
int main(){
    //freopen("in.txt","r",stdin);
    while( ~scanf("%d%d",&n,&m)){
        init();
        printf("%d\n",spfa(s));
    }
    return 0;
}

  

posted @ 2013-07-30 10:32  一生挚爱  阅读(284)  评论(0编辑  收藏  举报