当前位置: 首页 > news >正文

洛谷 P12332 题解

本题为一道有约束的分层图最短路问题。

跟分层图最短路不一样的是,本题有一个连续 $k$ 短路不需要花费的一个约束条件,那么我们在传递状态的时候只需要特判一下,如果当前的已经使用了免费次数了,那么我们接下来我们松弛的时候就不需要花费。

这里我们使用一个二维数组 $dis_{i,k}$ 表示当前到达第 $i$ 个节点,使用了 $k$ 次免费次数的最短路径,那么我们可以得到状态转移方程:

不需要花费时:$dis_{v,{k-1}} = \min(dis_{v,{k-1}}, dis_{u,k})$。

需要花费时:$dis_{v,k} = \min(dis_{v,k}, dis_{u,k} + w)$。

C++ 代码如下:

#include <bits/stdc++.h>
using namespace std;const int maxn = 2000005;
const int inf = 1047483647;struct node {int to, next, data;
};node edge[maxn];
int head[maxn], cnt, k, n, m;void add_edge(int from, int to, int data) {edge[++cnt].to = to;edge[cnt].data = data;edge[cnt].next = head[from];head[from] = cnt;
}int dis[1005][15];
bool vis[1005][15];struct heap {int node, data, step;heap(int n, int d, int s) : node(n), data(d), step(s) {}bool operator>(const heap& h) const {return data > h.data;}
};void dijkstra() {memset(vis, 0, sizeof(vis));memset(dis, 0x3f, sizeof(dis));dis[0][k] = 0;priority_queue<heap, vector<heap>, greater<heap>> q;q.push(heap(0, 0, k));while (!q.empty()) {int now = q.top().node;int step = q.top().step;q.pop();if (vis[now][step])continue;vis[now][step] = true;for (int i = head[now]; i != 0; i = edge[i].next) {int to = edge[i].to, data = edge[i].data;if (step < k && step > 0 && dis[to][step - 1] > dis[now][step]) {dis[to][step - 1] = dis[now][step];q.push(heap(to, dis[to][step - 1], step - 1));}else if (step == k || step == 0) {if (dis[to][step] > dis[now][step] + data) {dis[to][step] = dis[now][step] + data;q.push(heap(to, dis[to][step], step));}if (step == k && dis[to][step - 1] > dis[now][step]) {dis[to][step - 1] = dis[now][step];q.push(heap(to, dis[to][step - 1], step - 1));}}}}
}int main() {cin >> n >> k >> m;while (m--) {int x, y, z;cin >> x >> y >> z;add_edge(x, y, z);add_edge(y, x, z);}dijkstra();cout << min(dis[n - 1][k], dis[n - 1][0]) << endl;return 0;
}

http://www.xdnf.cn/news/1369729.html

相关文章:

  • 如何利用ArcGIS探究环境与生态因子对水体、土壤、大气污染物等影响实践技术
  • pytorch_grad_cam 库学习笔记—— Ablation-CAM 算法的基类 AblationCAM 和 AblationLayer
  • 如何避免频繁切换npm源
  • pytorch-利用letnet5框架深度学习手写数字识别
  • Vue2(七):配置脚手架、render函数、ref属性、props配置项、mixin(混入)、插件、scoped样式
  • 深入解析交换机端口安全:Sticky MAC的工作原理与应用实践
  • 机器视觉学习-day03-灰度化实验-二值化和自适应二值化
  • 【C++】智能指针底层原理:引用计数与资源管理机制
  • 深度学习篇---LeNet-5网络结构
  • 病理软件Cellprofiler使用教程
  • vue2 和 vue3 生命周期的区别
  • 一篇文章拆解Java主流垃圾回收器及其调优方法。
  • LeetCode-22day:多维动态规划
  • 代码随想录Day62:图论(Floyd 算法精讲、A * 算法精讲、最短路算法总结、图论总结)
  • vue2和vue3的对比
  • TensorFlow 深度学习:使用 feature_column 训练心脏病分类模型
  • Day3--HOT100--42. 接雨水,3. 无重复字符的最长子串,438. 找到字符串中所有字母异位词
  • CentOS 7 服务器初始化:从 0 到 1 的安全高效配置指南
  • 肌肉力量训练
  • 木马免杀工具使用
  • 产品经理操作手册(3)——产品需求文档
  • 全链路营销增长引擎闭门会北京站开启倒计时,解码营销破局之道
  • 构建生产级 RAG 系统:从数据处理到智能体(Agent)的全流程深度解析
  • 书生大模型InternLM2:从2.6T数据到200K上下文的开源模型王者
  • word批量修改交叉引用颜色
  • 【SystemUI】新增实体键盘快捷键说明
  • 常用Nginx正则匹配规则
  • ruoyi-vue(十二)——定时任务,缓存监控,服务监控以及系统接口
  • 软件检测报告:XML外部实体(XXE)注入漏洞原因和影响
  • 服务器初始化流程***