原题链接:http://poj.org/problem?id=2449
一直RE,找不到解决,以后再看。
#define _CRT_SECURE_NO_DEPRECATE
#include<iostream>
#include<vector>
#include<cstring>
#include<queue>
#include<stack>
#include<algorithm>
#include<cmath>
#include<string>
#include<stdio.h>
#define INF 1000000000
#define eps 0.0001
using namespace std;
struct P
{
int v, w;
int next;
};
struct Node
{
int v;
int f, g;
bool operator<(const Node& node)const
{
if (node.f == f) return g > node.g;
return f > node.f;
}
};
int cnt;
int n, m;
int s, t, k;
bool vis[1005];
int Q[1005];//模拟队列
int dis[1005];
int head[1005];
int rhead[1005];
P p[500005];
P rp[500005];
void add(int u, int v, int w)
{
p[cnt].v = v;
p[cnt].next = head[u];
p[cnt].w = w;
head[u] = cnt;
rp[cnt].v = u;
rp[cnt].next = rhead[v];
rp[cnt].w = w;
rhead[v] = cnt++;
}
void spfa(int src)
{
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= n; i++)
dis[i] = INF;
int down = 0;
int up = 1;
Q[down] = src;//模拟队列
dis[src] = 0;
vis[src] = 1;
while (down<up)
{
int u = Q[down++];
vis[u] = 0;
for (int i = rhead[u]; i != -1; i = rp[i].next)
{
int v = rp[i].v;
if (dis[v] > dis[u] + rp[i].w)
{
dis[v] = dis[u] + rp[i].w;
if (vis[v]) continue;
Q[up++] = v;
vis[v] = 1;
}
}
}
}
int aStar(int src, int dst)
{
if (dis[src] == INF)//根本无法连通,直接就是-1
return -1;
priority_queue<Node> pq;
int kk = 0;
if (src == dst)
kk++;
Node node;
Node node1;
node.v = src;
node.g = 0;
node.f = node.g + dis[src];
pq.push(node);
while (!pq.empty())
{
node = pq.top();
pq.pop();
if (node.v == dst)
{
kk++;
if (kk == k)
return node.g;
}
for (int i = head[node.v]; i!=-1; i=p[i].next)
{
node1.v = p[i].v;
node1.g = node.g + p[i].w;
node1.f = node1.g + dis[node.v];
pq.push(node1);
}
}
return -1;
}
int main()
{
while (~scanf("%d%d", &n, &m))
{
cnt = 0;
memset(head, -1, sizeof(head));
memset(rhead, -1, sizeof(rhead));
int u, v, w;
for (int i = 1; i <= m; i++)
{
scanf("%d%d%d", &u, &v, &w);
add(u, v, w);
}
scanf("%d%d%d", &s, &t, &k);
spfa(t);
printf("%d\n", aStar(s, t));
}
return 0;
}