[luoguP2901] Cow Jogging G
题意
给出一个 个点 条边的正权有向图,求从点 到点 的前 短路的距离分别是多少。
sol
短路问题往往使用 A* 算法(时间复杂度 )或可持久化可并堆优化最短路树(时间复杂度 ),由于本题数据范围较小,可以使用更好写的 A* 算法。
A* 算法
A* 算法是启发式搜索的一种,其核心是估价函数 ,其中, 是当前到达状态 的最小代价, 是状态 到达目标状态的估计最小代价(该值必须不大于实际代价,且越大越好)。每次选择 最小的未选择的状态,直到到达目标状态
短路
对于本题,我们计 ,这样可以保证一定不大于第 短路中这一段的距离。然后执行 A* 算法,当点 被遍历 次后,返回即可。
代码
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#include <vector>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
typedef pair<int, PII> PIP;
const int N = 1005, M = 10005;
struct Graph{
int h[N], e[M], w[M], ne[M], idx;
Graph(){
memset(h, -1, sizeof h);
}
void add(int a, int b, int c){
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}
} G, Ginv;
int n, m, k;
int h[N];
bool st[N];
int cnt[N];
void dijkstra(){
memset(h, 0x3f, sizeof h);
h[1] = 0;
priority_queue<PII, vector<PII>, greater<PII>> heap;
heap.push({0, 1});
while (!heap.empty()){
PII t = heap.top();
heap.pop();
if (st[t.y]) continue;
st[t.y] = true;
for (int i = Ginv.h[t.y]; ~i; i = Ginv.ne[i]){
int j = Ginv.e[i];
if (h[j] > h[t.y] + Ginv.w[i]) {
h[j] = h[t.y] + Ginv.w[i];
heap.push({h[j], j});
}
}
}
}
void A_star(){
priority_queue<PIP, vector<PIP>, greater<PIP>> heap;
heap.push({h[n], {0, n}});
while (!heap.empty()){
PIP t = heap.top();
heap.pop();
cnt[t.y.y] ++ ;
if (t.y.y == 1) {
printf("%d\n", t.x);
if (cnt[t.y.y] == k) return ;
}
for (int i = G.h[t.y.y]; ~i; i = G.ne[i]) {
int j = G.e[i];
if (cnt[j] > k) continue;
heap.push({t.y.x + G.w[i] + h[j], {t.y.x + G.w[i], j}});
}
}
}
int main(){
scanf("%d%d%d", &n, &m, &k);
while (m -- ){
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
G.add(a, b, c), Ginv.add(b, a, c);
}
dijkstra();
A_star();
for (int i = cnt[1]; i < k; i ++ ) puts("-1");
return 0;
}
分类:
题解 / 2024训练
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现