POJ 2449 Remmarguts' Date A* -

本文介绍了一种求解从起点s到终点t的第k短路径的算法。通过使用Spfa算法预处理逆邻接表得到各节点到终点t的最短路径,再结合A*算法的思想,实现寻找第k条最短路径的功能。

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

求第s~t 第k短的路

先求出所有点到t的最短路径,这可以通过保存逆邻接表来求

这是求出h(u)的精确值dist[u],g()就是离s(起点)点经过多少距离

从优先队列里取出f最小的点,该点扩展数加1,扩展他连接的点,放入优先队列

原理类似Dijkstra,扩展到的点就是s出发最短路径,第i次扩展到u点就是到u点的第i短路径

#include<iostream>
#include<cstdio>
#include<vector>
#include<queue>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long LL;
const int maxn=1000+5;
struct Point{
	int to,weight;
	Point(int t,int w):to(t),weight(w){}
};
vector<vector<Point> > G(maxn),GT(maxn);
int n,m;
int dist[maxn],inq[maxn];
struct Node{
	int to;
	int f,g,h;
	Node(int to,int g):to(to),g(g){h=dist[to];f=g+h;}
	bool operator < (const Node& n) const {
		if(f==n.f) return g>n.g;
		return f>n.f;
	}
};
void Spfa(int s)
{
	memset(dist,0x6f,sizeof(dist));
	
	queue<int> Q;
	dist[s]=0;
	inq[s]=true;    
	Q.push(s);
	while(!Q.empty())
	{
		int u=Q.front(); Q.pop();
		inq[u]=false;
		for(int i=0;i<GT[u].size();i++)
		{
			int v=GT[u][i].to, w=GT[u][i].weight;
			if(dist[v]>dist[u]+w)
			{
				dist[v]=dist[u]+w;
				if(!inq[v]) Q.push(v),inq[v]=true;
			}
		}
	}
}
int closed[maxn];
int A_Star(int s,int t,int k)
{
	if(dist[s]==dist[0]) return -1;
	if(s==t) k++;
	
	memset(closed,0,sizeof(closed));
	priority_queue<Node> open;
	open.push(Node(s,0));
	while(!open.empty())
	{
		int u=open.top().to,g=open.top().g; open.pop();
		closed[u]++;
		if(closed[t]==k) return g;
		for(int i=0;i<G[u].size();i++)
		{
			int v=G[u][i].to,w=G[u][i].weight;
			open.push(Node(v,g+w));
		}
	}
	return -1;
}
int main()
{
	int n,m,u,v,w,s,t,k;
	cin>>n>>m;
	while(m--)
	{
		cin>>u>>v>>w;
		G[u].push_back(Point(v,w));
		GT[v].push_back(Point(u,w));
	}
	cin>>s>>t>>k;
	Spfa(t);
	cout<<A_Star(s,t,k)<<endl;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值