#include<cstdio>
#include
<iostream>
#include
<vector>
#include
<queue>
#define MAX_N 1005
#define MAX_M 100005
using namespace std;
struct p{
    
int v,val;
    friend 
bool operator <(const p &a,const p &b){
        
return a.val>b.val;//从小到大
    }
};
//bool operator <(p a,p b){return a.val>b.val;}
//struct cmp1{
//    bool operator ()(p a,p b){return a.val>b.val;}
//};
//priority_queue<p>c;
//priority_queue<p,vector<p>,cmp1>d;     //优先队列运算符重载及构造方法
vector<struct p> map[MAX_N],rmap[MAX_N];   //邻接表表示,逆图
int n,m,a,b,t,s,k;
int h[MAX_N];
struct cmp2{
    
bool operator ()(p a,p b){return a.val+h[a.v]>b.val+h[b.v];}
};
void input()
{
    
struct p tmp;
    scanf(
"%d %d",&n,&m);
    
while(m--){
        scanf(
"%d %d %d",&a,&b,&t);
        tmp.v
=b;tmp.val=t;
        map[a].push_back(tmp);
        tmp.v
=a;
        rmap[b].push_back(tmp);
    }
    scanf(
"%d %d %d",&s,&t,&k);
    
if(s==t) k++;
}
void dijk()            //优先队列实现dijkstra
{
    
struct p tmp;
    
int tu,tv,tval,tcost,i;
    
for(i=0;i<=n+1;i++)
        h[i]
=10000000;     
//    fill(h,h+n+1,INT_MAX); 
    priority_queue<p> q;
    tmp.v
=t;tmp.val=0;h[t]=0;
    q.push(tmp);
    
while(!q.empty()){
        tmp
=q.top();tu=tmp.v;tval=tmp.val;q.pop();
        
if(h[tu]!=tval)    continue;          //顶点tu已访问过。估值函数h[]=dist[][t]
        for(i=0;i<rmap[tu].size();i++){
            tv
=rmap[tu][i].v;tcost=rmap[tu][i].val;
            
if(h[tv]>tcost+tval){
                tmp.v
=tv;tmp.val=tcost+tval;
                q.push(tmp);
                h[tv]
=tcost+tval;
            }
        }
    }
}
int A_STAR()
{
    
struct p tmp;
    
int tu,tval,i;
    priority_queue
<p,vector<p>,cmp2>q;
    
int cnt[MAX_N];
    memset(cnt,
0,sizeof(cnt));
    
if(h[s]==INT_MAX)    return -1;
    tmp.v
=s;tmp.val=0;
    q.push(tmp);
    
while(!q.empty()){
        tmp
=q.top();tu=tmp.v;tval=tmp.val;q.pop();
        cnt[tu]
++;
        
if(cnt[t]==k)    return tval;
        
if(cnt[tu]>k)    continue//如果x是s到t的第k短路径上的一个节点,那么由这条路径s到x是s到x的第m短路径,则不可能有m>k
        for(i=0;i<map[tu].size();i++){
            tmp.v
=map[tu][i].v;tmp.val=map[tu][i].val+tval;
            q.push(tmp);
        }
    }
    
return -1;
}
int main()
{
    input();
    dijk();
    printf(
"%d\n",A_STAR());
    
return 0;
}

 

题目链接:http://acm.pku.edu.cn/JudgeOnline/problem?id=2449

posted on 2009-05-07 13:44  pandy  阅读(605)  评论(0编辑  收藏  举报