http://poj.org/problem?id=2449
题意:输入 n, m 表示给一个 n 个顶点 m 条边的有向图,然后输入 m 条边,最后一行输入 s, t, k,要求这个图中 s 点到 t 点的第 k 短路径。
思路:用 A* 求,估价函数f(i)=g(i) + h(i)。g(i) 就是 s 点到 i 点的某条路径的长度, h(i)就是i点到t的最短距离, h(i) 通过从终点开始 spfa 求出。A* 的过程中如果 t 点出队次数达到 k 次就表示求出来了。
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int maxn = 1010;
const int maxm = 200200;
struct Side{
int to, val, next;
};
int n, m;
Side side[maxm];
int vis[maxn], dis[maxn];
int head[maxn], tail[maxn];
void add(int u, int v, int val, int e){
side[e<<1].to = v;
side[e<<1].val = val;
side[e<<1].next = head[u]; //正向边用于A*
head[u] = e<<1;
side[e<<1|1].to = u;
side[e<<1|1].val = val;
side[e<<1|1].next = tail[v];//反向边用于spfa
tail[v] = e<<1|1;
}
int spfa(int rt) //求出 h(i)
{
queue<int> que;
memset(vis, 0, sizeof(vis));
memset(dis, 63, sizeof(dis));
dis[rt] = 0;
vis[rt] = 1;
que.push(rt);
while(!que.empty()){
int rw = que.front();
que.pop();
vis[rw] = 0;
for(int i = tail[rw]; ~i; i = side[i].next){
int now = side[i].to;
if(dis[now] <= dis[rw] + side[i].val)
continue;
dis[now] = dis[rw] + side[i].val;
if(!vis[now]){
vis[now] = 1;
que.push(now);
}
}
}
return 0;
}
struct node{
int pos, val;
node(int a = 0, int b = 0){
pos = a, val = b;
}
friend bool operator < (node a, node b){ //优先队列
return dis[a.pos] + a.val > dis[b.pos] + b.val;
}
};
int Astar(int s, int t, int k) //A*
{
priority_queue<node> que;
memset(vis, 0, sizeof(vis));
que.push(node(s, 0));
while(!que.empty()){
node rw = que.top();
que.pop();
if(++vis[rw.pos] > k)
continue;
if(vis[t] == k)
return rw.val;
for(int i = head[rw.pos]; i != -1; i = side[i].next){
int now = side[i].to;
que.push(node(now, rw.val + side[i].val));
}
}
return -1;
}
int main()
{
while(~scanf("%d%d", &n, &m)){
int x, y, val;
memset(tail, -1, sizeof(tail));
memset(head, -1, sizeof(head));
for(int i = 0; i < m; i++){
scanf("%d%d%d", &x, &y, &val);
add(x, y, val, i);
}
int s, t, k;
scanf("%d%d%d", &s, &t, &k);
spfa(t);
if(s == t) k++;
printf("%d\n", Astar(s, t, k));
}
}