分层图最短路

lc2714

带状态的Dijkstra算法求解允许最多跳过k条边权重的最短路径

状态为(节点, 剩余跳过次数),每次转移可选择走边或跳过

typedef pair<int, int> PII;

typedef tuple<int, int, int> TIII;

class Solution {

public:

int shortestPathWithHops(int n, vector<vector<int>>& edges, int s, int d, int k) {

vector<vector<PII>> g(n);

for (auto& edge : edges) {

int a = edge[0], b = edge[1], c = edge[2];

g[a].emplace_back(b, c);

g[b].emplace_back(a, c);

}

vector<vector<int>> dist(n, vector<int>(k + 1, INT_MAX));

dist[s][0] = 0;

vector<vector<bool>> seen(n, vector<bool>(k + 1, false));

priority_queue<TIII, vector<TIII>, greater<TIII>> pq;

pq.emplace(0, s, 0);

while (!pq.empty()) {

auto [td, u, tk] = pq.top();

pq.pop();

if (seen[u][tk]) continue;

seen[u][tk] = true;

for (auto& [v, nd] : g[u]) {

if (dist[v][tk] > td + nd) {

dist[v][tk] = td + nd;

pq.emplace(td + nd, v, tk);

}

if (tk < k and dist[v][tk + 1] > td) {

dist[v][tk + 1] = td;

pq.emplace(td, v, tk + 1);

}

}

}

return *min_element(dist[d].begin(), dist[d].end());

}

};

相关推荐
Je1lyfish10 分钟前
CMU15-445 (2025 Fall/2026 Spring) Project#3 - QueryExecution
linux·c语言·开发语言·数据结构·数据库·c++·算法
许彰午12 分钟前
03-二叉树——从递归遍历到非递归实现
java·算法
Brilliantwxx25 分钟前
【C++】 vector(代码实现+坑点讲解)
开发语言·c++·笔记·算法
NorburyL2 小时前
DPO笔记
深度学习·算法
老纪的技术唠嗑局2 小时前
深度解析 LLM Wiki / Obsidian-Wiki / GBrain:Agent 时代知识的“自组织”与“自进化”
大数据·数据库·人工智能·算法
YXXY3135 小时前
模拟算法的介绍
算法
happymaker06266 小时前
简单LRU的实现(基于LinkedHashMap)
算法·leetcode·lru
会编程的土豆6 小时前
【数据结构与算法】空间复杂度从入门到面试:不仅会算,还要会解释
数据结构·c++·算法·面试·职场和发展
普通网友6 小时前
《算法面试必刷:15 个高频 LeetCode 题(附代码)》
算法·leetcode·面试
_深海凉_6 小时前
LeetCode热题100-搜索二维矩阵
算法·leetcode·矩阵