poj2449 Remmarguts' Date 第K短路(A*算法)

本文介绍了一种使用A*算法求解从起点s到终点e的第k条最短路径的方法。A*算法是一种启发式搜索算法,通过结合已知路径长度g(n)和预估剩余距离h(n)来确定搜索方向。文中详细阐述了如何通过维护优先队列和反向邻接表来实现这一算法,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

求从s点到e点的第k条最短路。这里是最短路的典型变形之一:A*算法。A*算法是一种启发式搜索,不是纯粹的盲目搜索。A*算法中有个估值算法g(n),对于每个点而言,都有一个g(n)和h(n)来确定的f(n),实际上就是以f(n)为参考权值来确定搜索的方向,在这里,h(n)表示的是从s点出发到这个点n现在走过的路径长度,而g(n)表示的是从n到e的最短长度的大小,那么就确定了搜索的优先性,这里的A*算法的估价函数g(n)是完美估价,搜索的方向一定是对的。

第k条最短路可以理解为第k次走到终点,那就相当于是终点被找到k次,即出队k次。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int INF=0x3f3f3f3f;
const int MAXN=1005;
const int MAXM=100000;
int head[MAXN],next[MAXM],n_head[MAXN],n_next[MAXM];//n_head和n_next存储反向邻接表 
int dis[MAXN],vis[MAXN],no,n,m,S,E,k;//dis为上文算法说明中的g数组
struct edge{
	int s,e,w;
	edge(){
	}
	edge(int s,int e,int w){
		this->s=s; this->e=e; this->w=w; 
	}
}p[MAXM];
struct node{
	int v,h; //h为上文算法说明中的h数组 
	node(){
	}
	node(int v,int h){
		this->v=v; this->h=h;
	}
	friend bool operator < (node a,node b){//在a_star算法中按h+g排升序 
		return a.h+dis[a.v]>b.h+dis[b.v];
	} 
};
void addedge(int s,int e,int w){
	p[no]=edge(s,e,w);
	next[no]=head[s]; head[s]=no;
	n_next[no]=n_head[e]; n_head[e]=no++;//加反向边 
}
void dijkstra(int src){ //求估值函数g即为dis数组
	memset(vis,0,sizeof(vis));
	memset(dis,INF,sizeof(dis));
	dis[src]=0;
	priority_queue<node>que;
	que.push(node(src,0));
	while(que.size()){
		node now=que.top(); que.pop();
		if(vis[now.v]) continue;
		vis[now.v]=1;
		for(int i=n_head[now.v];i+1;i=n_next[i]){
			if(dis[p[i].e]+p[i].w<dis[p[i].s]){//与存储的正向边的起点终点相反 
				dis[p[i].s]=dis[p[i].e]+p[i].w;
				que.push(node(p[i].s,0));
			}
		}
	}	
}
int a_star(int src){
	priority_queue<node>que;
	que.push(node(src,0)); k--;
	while(que.size()){
		node now=que.top(); que.pop();
		if(now.v==E){
			if(k) k--;
			else return now.h;
		}
		for(int i=head[now.v];i+1;i=next[i]){
			que.push(node(p[i].e,now.h+p[i].w));
		}
	}
	return -1;
}
int main(){
	while(scanf("%d %d",&n,&m)!=EOF){
		memset(head,-1,sizeof(head));
		memset(n_head,-1,sizeof(n_head));
		no=0;
		for(int i=0;i<m;i++){
			int s,e,w;
			scanf("%d %d %d",&s,&e,&w);
			addedge(s,e,w); 
		}
		scanf("%d %d %d",&S,&E,&k);
		dijkstra(E);
		if(dis[S]==INF){
			printf("-1\n");
			continue;
		}
		if(S==E) k++;//如果终点为起点则需要多找一次 
		printf("%d\n",a_star(S));
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值