一直对AStar(简称A*)有些抗拒,感觉是挺难的东西,特别是那个f=g+h的公式里面的参数到底要怎么算总搞不清楚。但是今天把这题给做了,感觉对A*的理解又上一层了。
对于本题,h就是i点到目的地的最短距离,g就是开始地方到i点的实际距离,我们要求f=g+h最小,并且当目的地第K次出队时,那么这时候g的值就是我们所要求解的答案,对于入队大于K次的点,我们不继续求解,因为此后求的就是K+1之后的最短距离了。
怎么求各点到目的点的最短距离呢?只要把所有边反向,然后以目的地为源点求一下最短路,得到的结果就是各点到目的地的最短路。
参考代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <queue>
using namespace std;
const int MAXN = 2000;
const int MAXM = 100100;
const int INF = 0x7f7f7f7f;
typedef struct Edge {
int to,dis,next;
}Edge;
typedef struct dNode {
int now;
int dis;
dNode(){};
dNode(int n,int d):now(n),dis(d){};
}dNode;
typedef struct aNode {
int v,g;
aNode(){};
aNode(int v,int g):v(v),g(g){};
}aNode;
void init();
void add_edge(int form,int to,int dis,Edge * edge,Edge * head,int &total);
void dijkstra(int src,Edge * edge,Edge * head);
int astar(int src,int des,int K,Edge * edge,Edge * head);
bool operator < (const dNode &a,const dNode &b);
bool operator < (const aNode &a,const aNode &b);
int vis[MAXN];
int dis[MAXN];
Edge head_1[MAXN]; //记录正向边的邻接表
Edge head_2[MAXN]; //记录反向边的邻接表
Edge edge_1[MAXM]; //记录正向边数据
Edge edge_2[MAXM]; //记录反向边数据
int N,M,total_1,total_2;
int main(int argc,char * argv[]) {
int i,j,k;
int from,to,dis;
int S,T,K;
int res;
while (scanf("%d%d",&N,&M)!=EOF) {
init();
for (i=0;i<M;++i) {
scanf("%d%d%d",&from,&to,&dis);
add_edge(from,to,dis,edge_1,head_1,total_1);
add_edge(to,from,dis,edge_2,head_2,total_2);
}
scanf("%d%d%d",&S,&T,&K);
if (S == T) ++K;
dijkstra(T,edge_2,head_2);
res = astar(S,T,K,edge_1,head_1);
printf("%d\n",res);
}
return 0;
}
void init() {
int i;
for (i=0;i<=N;++i) {
head_1[i].next = 0;
head_2[i].next = 0;
}
total_1 = 0;
total_2 = 0;
}
void add_edge(int from,int to,int dis,Edge * edge,Edge * head,int &total) {
++total;
edge[total].to = to;
edge[total].dis = dis;
edge[total].next = head[from].next;
head[from].next = total;
}
void dijkstra(int src,Edge * edge,Edge * head) {
int p;
dNode node;
priority_queue<dNode> pq;
memset(dis,0x7f,sizeof(dis));
dis[src] = 0;
while (!pq.empty()) pq.pop();
pq.push(dNode(src,0));
memset(vis,0,sizeof(vis));
while (!pq.empty()) {
node = pq.top();
pq.pop();
if (vis[node.now]) continue;
vis[node.now] = 1;
p = head[node.now].next;
while (p) {
if (dis[node.now] < dis[edge[p].to] - edge[p].dis) {
dis[edge[p].to] = dis[node.now] + edge[p].dis;
pq.push(dNode(edge[p].to,dis[edge[p].to]));
}
p = edge[p].next;
}
}
}
int astar(int src,int des,int K,Edge * edge,Edge * head) {
int p;
aNode now;
priority_queue<aNode> pq;
while (!pq.empty()) pq.pop();
memset(vis,0,sizeof(vis));
pq.push(aNode(src,0));
while (!pq.empty()) {
now = pq.top();
pq.pop();
++vis[now.v];
if (vis[now.v] > K) continue;
if (K == vis[des]) return now.g;
p = head[now.v].next;
while (p) {
pq.push(aNode(edge[p].to, now.g + edge[p].dis));
p = edge[p].next;
}
}
return -1;
}
bool operator < (const dNode &a,const dNode &b) {
return a.dis > b.dis;
}
bool operator < (const aNode &a,const aNode &b) {
return a.g + dis[a.v] > b.g + dis[b.v];
}