#include <stdio.h>
#include <string.h>
#include <queue>

using namespace std;

const int INF = 0x7fffffff;
const int NIL = -1;
const int MAXN = 1005;
const int MAXM = 100005;

typedef pair<int,int> tuple;

int N,M;
int S,T,K;

int u[MAXM];
int v[MAXM];
int w[MAXM];

int first0[MAXN];
int next0[MAXM];

int first1[MAXN];
int next1[MAXM];

int d[MAXN];
bool vis[MAXN];

int cnt[MAXN];

typedef struct NODE {
    int No;
    int f;
    int g;
    bool operator < (const NODE& x) const
    {
        return x.f < f;
    }
}NODE;

void read_graph()
{
    memset(first0, NIL, sizeof(first0));
    memset(next0, NIL, sizeof(next0));
    memset(first1, NIL, sizeof(first1));
    memset(next1, NIL, sizeof(next1));

    scanf("%d%d",&N,&M);
    for (int i = 0; i < M; i++)
    {
        scanf("%d%d%d",&u[i],&v[i],&w[i]);

        next0[i] = first0[u[i]];
        first0[u[i]] = i;

        next1[i] = first1[v[i]];
        first1[v[i]] = i;
    }

    scanf("%d%d%d",&S,&T,&K);
}

void dij(int s)
{
    priority_queue<tuple,vector<tuple>,greater<tuple> > q;
    memset(vis, 0, sizeof(vis));
    
    for (int i = 1; i <= N; i++)
        d[i] = INF;
    d[s] = 0;

    q.push(make_pair(d[s],s));

    while ( !q.empty() )
    {
        int curr = q.top().second;
        q.pop();

        if ( vis[curr] )
            continue;
        vis[curr] = true;
        for (int e = first1[curr]; e != NIL; e = next1[e])
        {
            if ( !vis[u[e]] && d[curr] < INF && d[curr] + w[e] < d[u[e]] )
            {
                d[u[e]] = d[curr] + w[e];
                q.push(make_pair(d[u[e]],u[e]));
            }
        }
    }
}

int Astar(int src,int dst,int k)
{
    priority_queue<NODE> q;
    memset(cnt, 0, sizeof(cnt));
    
    if ( d[src] == INF )
        return -1;

    NODE s;
    s.No = src;
    s.g = 0;
    s.f = s.g + d[src];
    q.push(s);

    while ( !q.empty() )
    {
        NODE curr = q.top();
        q.pop();
        
        cnt[curr.No]++;
        if ( cnt[curr.No] > k )
            continue;
        if ( curr.No == dst && cnt[dst] == k )
            return curr.f;

        NODE nxt;
        for (int e = first0[curr.No]; e != NIL; e = next0[e])
        {
            nxt.No = v[e];
            nxt.g = curr.g + w[e];
            nxt.f = nxt.g + d[v[e]];
            q.push(nxt);
        }
    }

    return -1;
}


int main()
{
//    freopen("1.txt","r",stdin);

    read_graph();
    if ( S == T )
        K++;
    
    dij(T);
    
    int ans = Astar(S,T,K);
    
    printf("%d\n",ans);
    
    return 0;
}

 

posted on 2013-05-04 23:46  Sinker  阅读(173)  评论(0编辑  收藏  举报