B27 A*算法 第K短路
视频链接:128 A*算法 第K短路_哔哩哔哩_bilibili
#include <cstdio> #include <iostream> #include <cstring> #include <vector> #include <queue> using namespace std; const int N=1010,M=200010; int h[N],rh[N],to[M],w[M],ne[M],tot; void add(int h[],int a,int b,int c){ to[++tot]=b;w[tot]=c; ne[tot]=h[a],h[a]=tot; } int n,m,S,T,K; int f[N],vis[N],cnt[N]; struct node{ int s,v,d; //s排序,v点,d距离 bool operator<(const node &x)const {return s>x.s;} }; void dijkstra(){ memset(f,0x3f,sizeof f); f[T]=0; priority_queue<pair<int,int>> q; q.push(make_pair(0,T)); while(q.size()){ pair<int,int> t=q.top(); q.pop(); int u=t.second; if(vis[u])continue; vis[u]=true; //第一次出队时最小 for(int i=rh[u]; i; i=ne[i]){ int v=to[i]; if(f[v]>f[u]+w[i]){ f[v]=f[u]+w[i]; //估价函数 q.push(make_pair(-f[v],v)); } } } } int aStar(){ priority_queue<node> q; //优先队列 node a={f[S],S,0}; q.push(a); while(q.size()){ node t=q.top(); q.pop(); int u=t.v; cnt[u]++; //记录出队次数 if(cnt[T]==K) return t.d; //边界 for(int i=h[u]; i; i=ne[i]){ int v=to[i], d=t.d+w[i]; if(cnt[v]<K){ node a={d+f[v],v,d}; q.push(a); } } } return -1; } int main(){ scanf("%d%d",&n,&m); for(int i=1; i<=m; i++){ int a,b,c; scanf("%d%d%d",&a,&b,&c); add(h,a,b,c); add(rh,b,a,c); //反图 } scanf("%d%d%d",&S,&T,&K); if(S==T) K++; //重合点,0是第一条 dijkstra(); printf("%d\n",aStar()); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!