K-Shortest Walk
(graph/k_shortest_walk.hpp)
- View this file on GitHub
- Last update: 2026-08-13 01:41:40+09:00
- Include:
#include "graph/k_shortest_walk.hpp"
Overview
k_shortest_walk lists the lengths of the shortest walks from one vertex to
another in nondecreasing order. A walk may repeat vertices and edges, and two
different walks are counted separately even when their lengths are equal.
The implementation uses a shortest-path tree toward the target and persistently melded heaps of Eppstein sidetracks. It is intended for large sparse or dense directed graphs with non-negative edge costs.
Requirements and Behavior
-
Tmust support construction from integers, addition, subtraction, equality, and ordering. - Every alive edge cost must be non-negative.
- Costs of all relevant walks and intermediate sums must fit in
Tand remain belowinf. - Inactive edges are ignored.
- If
s == t, the empty walk of length zero is the first answer. - If fewer than
kwalks exist, the returned vector is shorter thank. No sentinel value is appended.
Function
| Function | Signature | Description | Complexity |
|---|---|---|---|
k_shortest_walk |
template <class T> std::vector<T> k_shortest_walk(const Graph<T>& g, int s, int t, int k, T inf = std::numeric_limits<T>::max() / T(4)) |
Returns up to k walk lengths from s to t in nondecreasing order. |
$O((N+M)\log N + M\log M + K\log K)$ time and $O(N+M+N\log M+K)$ memory. |
Here M counts alive adjacency entries, so an undirected edge stored by
Graph::add_edge contributes two entries. The graph itself is not modified.
Example
#include "graph/graph.hpp"
#include "graph/k_shortest_walk.hpp"
#include <iostream>
int main() {
m1une::graph::Graph<long long> g(3);
g.add_directed_edge(0, 1, 2);
g.add_directed_edge(1, 2, 3);
g.add_directed_edge(0, 2, 8);
g.add_directed_edge(1, 1, 1);
auto lengths = m1une::graph::k_shortest_walk(g, 0, 2, 4);
for (long long length : lengths) std::cout << length << "\n";
// 5, 6, 7, 8
}
Depends on
Required by
Graph All
(graph/all.hpp)
Directed Graph Algorithms
(graph/directed.hpp)
Shortest Path
(graph/shortest_path.hpp)
Undirected Graph Algorithms
(graph/undirected.hpp)
Verified with
verify/graph/cow_game.test.cpp
verify/graph/graph_algorithms.test.cpp
verify/graph/k_shortest_walk.test.cpp
verify/graph/range_edge_graph.test.cpp
Code
#ifndef M1UNE_GRAPH_K_SHORTEST_WALK_HPP
#define M1UNE_GRAPH_K_SHORTEST_WALK_HPP 1
#include <cassert>
#include <functional>
#include <limits>
#include <queue>
#include <utility>
#include <vector>
#include "graph.hpp"
namespace m1une {
namespace graph {
namespace internal {
template <class T>
class KShortestWalkHeap {
struct Node {
T key;
int to;
int left;
int right;
int rank;
};
std::vector<Node> _nodes;
int rank(int root) const {
return root == -1 ? 0 : _nodes[root].rank;
}
public:
int make_node(T key, int to) {
int result = int(_nodes.size());
_nodes.push_back(Node{key, to, -1, -1, 1});
return result;
}
int meld_mutable(int first, int second) {
if (first == -1) return second;
if (second == -1) return first;
if (_nodes[second].key < _nodes[first].key) std::swap(first, second);
_nodes[first].right = meld_mutable(_nodes[first].right, second);
if (rank(_nodes[first].left) < rank(_nodes[first].right)) {
std::swap(_nodes[first].left, _nodes[first].right);
}
_nodes[first].rank = rank(_nodes[first].right) + 1;
return first;
}
int meld_persistent(int first, int second) {
if (first == -1) return second;
if (second == -1) return first;
if (_nodes[second].key < _nodes[first].key) std::swap(first, second);
int result = int(_nodes.size());
_nodes.push_back(_nodes[first]);
_nodes[result].right = meld_persistent(_nodes[result].right, second);
if (rank(_nodes[result].left) < rank(_nodes[result].right)) {
std::swap(_nodes[result].left, _nodes[result].right);
}
_nodes[result].rank = rank(_nodes[result].right) + 1;
return result;
}
const Node& operator[](int index) const {
return _nodes[index];
}
};
} // namespace internal
template <class T>
std::vector<T> k_shortest_walk(
const Graph<T>& g,
int s,
int t,
int k,
T inf = std::numeric_limits<T>::max() / T(4)
) {
int n = g.size();
assert(0 <= s && s < n);
assert(0 <= t && t < n);
assert(0 <= k);
if (k == 0) return {};
struct ReverseEdge {
int from;
int index;
T cost;
};
std::vector<std::vector<ReverseEdge>> reverse_graph(n);
for (int from = 0; from < n; from++) {
for (int index = 0; index < int(g[from].size()); index++) {
const auto& edge = g[from][index];
if (!edge.alive) continue;
assert(T(0) <= edge.cost);
reverse_graph[edge.to].push_back(ReverseEdge{from, index, edge.cost});
}
}
std::vector<T> dist(n, inf);
std::vector<int> tree_edge(n, -1);
std::vector<int> order;
order.reserve(n);
using QueueEntry = std::pair<T, int>;
std::priority_queue<QueueEntry, std::vector<QueueEntry>, std::greater<QueueEntry>> queue;
dist[t] = T(0);
queue.emplace(T(0), t);
while (!queue.empty()) {
auto [current_dist, vertex] = queue.top();
queue.pop();
if (dist[vertex] != current_dist) continue;
order.push_back(vertex);
for (const auto& edge : reverse_graph[vertex]) {
T next_dist = current_dist + edge.cost;
if (dist[edge.from] <= next_dist) continue;
dist[edge.from] = next_dist;
tree_edge[edge.from] = edge.index;
queue.emplace(next_dist, edge.from);
}
}
if (dist[s] == inf) return {};
internal::KShortestWalkHeap<T> heap_pool;
std::vector<int> local_heap(n, -1);
for (int vertex : order) {
for (int index = 0; index < int(g[vertex].size()); index++) {
const auto& edge = g[vertex][index];
if (!edge.alive || dist[edge.to] == inf || index == tree_edge[vertex]) continue;
T extra = edge.cost + dist[edge.to] - dist[vertex];
assert(T(0) <= extra);
int node = heap_pool.make_node(extra, edge.to);
local_heap[vertex] = heap_pool.meld_mutable(local_heap[vertex], node);
}
}
std::vector<int> path_heap(n, -1);
for (int vertex : order) {
int inherited = -1;
if (tree_edge[vertex] != -1) inherited = path_heap[g[vertex][tree_edge[vertex]].to];
path_heap[vertex] = heap_pool.meld_persistent(inherited, local_heap[vertex]);
}
std::vector<T> result;
result.reserve(k);
result.push_back(dist[s]);
std::priority_queue<QueueEntry, std::vector<QueueEntry>, std::greater<QueueEntry>> candidates;
if (path_heap[s] != -1) {
candidates.emplace(dist[s] + heap_pool[path_heap[s]].key, path_heap[s]);
}
while (int(result.size()) < k && !candidates.empty()) {
auto [cost, node_index] = candidates.top();
candidates.pop();
result.push_back(cost);
const auto& node = heap_pool[node_index];
if (node.left != -1) {
candidates.emplace(cost - node.key + heap_pool[node.left].key, node.left);
}
if (node.right != -1) {
candidates.emplace(cost - node.key + heap_pool[node.right].key, node.right);
}
int next_heap = path_heap[node.to];
if (next_heap != -1) {
candidates.emplace(cost + heap_pool[next_heap].key, next_heap);
}
}
return result;
}
} // namespace graph
} // namespace m1une
#endif // M1UNE_GRAPH_K_SHORTEST_WALK_HPP#line 1 "graph/k_shortest_walk.hpp"
#include <cassert>
#include <functional>
#include <limits>
#include <queue>
#include <utility>
#include <vector>
#line 1 "graph/graph.hpp"
#include <array>
#line 8 "graph/graph.hpp"
namespace m1une {
namespace graph {
template <class T = int>
struct Edge {
using cost_type = T;
int from;
int to;
T cost;
int id;
bool alive;
Edge() : from(-1), to(-1), cost(T()), id(-1), alive(true) {}
Edge(int from_, int to_, T cost_ = T(1), int id_ = -1, bool alive_ = true)
: from(from_), to(to_), cost(cost_), id(id_), alive(alive_) {}
int other(int v) const {
assert(v == from || v == to);
return from ^ to ^ v;
}
};
template <class T = int>
struct Graph {
using edge_type = Edge<T>;
using cost_type = T;
private:
struct EdgePositions {
std::array<std::pair<int, int>, 2> value{};
int size = 0;
void push_back(std::pair<int, int> position) {
assert(size < 2);
value[size++] = position;
}
};
int _n;
int _edge_count;
std::vector<std::vector<edge_type>> _g;
std::vector<EdgePositions> _edge_positions;
public:
Graph() : _n(0), _edge_count(0) {}
explicit Graph(int n) : _n(n), _edge_count(0), _g(n) {
assert(0 <= n);
}
int size() const {
return _n;
}
bool empty() const {
return _n == 0;
}
int edge_count() const {
return _edge_count;
}
int add_vertex() {
_g.emplace_back();
return _n++;
}
int add_directed_edge(int from, int to, T cost = T(1)) {
assert(0 <= from && from < _n);
assert(0 <= to && to < _n);
int id = _edge_count++;
int idx = int(_g[from].size());
_g[from].push_back(edge_type(from, to, cost, id));
_edge_positions.emplace_back();
_edge_positions.back().push_back({from, idx});
return id;
}
int add_edge(int u, int v, T cost = T(1)) {
assert(0 <= u && u < _n);
assert(0 <= v && v < _n);
int id = _edge_count++;
int u_idx = int(_g[u].size());
_g[u].push_back(edge_type(u, v, cost, id));
int v_idx = int(_g[v].size());
_g[v].push_back(edge_type(v, u, cost, id));
_edge_positions.emplace_back();
_edge_positions.back().push_back({u, u_idx});
_edge_positions.back().push_back({v, v_idx});
return id;
}
void set_edge_alive(int id, bool alive) {
assert(0 <= id && id < _edge_count);
for (int i = 0; i < _edge_positions[id].size; ++i) {
auto [v, idx] = _edge_positions[id].value[i];
_g[v][idx].alive = alive;
}
}
void erase_edge(int id) {
set_edge_alive(id, false);
}
void revive_edge(int id) {
set_edge_alive(id, true);
}
bool is_edge_alive(int id) const {
assert(0 <= id && id < _edge_count);
assert(_edge_positions[id].size != 0);
auto [v, idx] = _edge_positions[id].value[0];
return _g[v][idx].alive;
}
const std::vector<edge_type>& operator[](int v) const {
assert(0 <= v && v < _n);
return _g[v];
}
std::vector<edge_type>& operator[](int v) {
assert(0 <= v && v < _n);
return _g[v];
}
const std::vector<std::vector<edge_type>>& adjacency() const {
return _g;
}
std::vector<std::vector<edge_type>>& adjacency() {
return _g;
}
std::vector<edge_type> edges(bool include_inactive = false) const {
std::vector<edge_type> result;
result.reserve(_edge_count);
std::vector<char> used(_edge_count, false);
for (int v = 0; v < _n; v++) {
for (const auto& e : _g[v]) {
if (!include_inactive && !e.alive) continue;
if (0 <= e.id && e.id < _edge_count) {
if (used[e.id]) continue;
used[e.id] = true;
}
result.push_back(e);
}
}
return result;
}
Graph reversed() const {
Graph result(_n);
result._edge_count = _edge_count;
result._edge_positions.assign(_edge_count, {});
for (int v = 0; v < _n; v++) {
for (const auto& e : _g[v]) {
int idx = int(result._g[e.to].size());
result._g[e.to].push_back(edge_type(e.to, e.from, e.cost, e.id, e.alive));
if (0 <= e.id && e.id < _edge_count) result._edge_positions[e.id].push_back({e.to, idx});
}
}
return result;
}
};
} // namespace graph
} // namespace m1une
#line 12 "graph/k_shortest_walk.hpp"
namespace m1une {
namespace graph {
namespace internal {
template <class T>
class KShortestWalkHeap {
struct Node {
T key;
int to;
int left;
int right;
int rank;
};
std::vector<Node> _nodes;
int rank(int root) const {
return root == -1 ? 0 : _nodes[root].rank;
}
public:
int make_node(T key, int to) {
int result = int(_nodes.size());
_nodes.push_back(Node{key, to, -1, -1, 1});
return result;
}
int meld_mutable(int first, int second) {
if (first == -1) return second;
if (second == -1) return first;
if (_nodes[second].key < _nodes[first].key) std::swap(first, second);
_nodes[first].right = meld_mutable(_nodes[first].right, second);
if (rank(_nodes[first].left) < rank(_nodes[first].right)) {
std::swap(_nodes[first].left, _nodes[first].right);
}
_nodes[first].rank = rank(_nodes[first].right) + 1;
return first;
}
int meld_persistent(int first, int second) {
if (first == -1) return second;
if (second == -1) return first;
if (_nodes[second].key < _nodes[first].key) std::swap(first, second);
int result = int(_nodes.size());
_nodes.push_back(_nodes[first]);
_nodes[result].right = meld_persistent(_nodes[result].right, second);
if (rank(_nodes[result].left) < rank(_nodes[result].right)) {
std::swap(_nodes[result].left, _nodes[result].right);
}
_nodes[result].rank = rank(_nodes[result].right) + 1;
return result;
}
const Node& operator[](int index) const {
return _nodes[index];
}
};
} // namespace internal
template <class T>
std::vector<T> k_shortest_walk(
const Graph<T>& g,
int s,
int t,
int k,
T inf = std::numeric_limits<T>::max() / T(4)
) {
int n = g.size();
assert(0 <= s && s < n);
assert(0 <= t && t < n);
assert(0 <= k);
if (k == 0) return {};
struct ReverseEdge {
int from;
int index;
T cost;
};
std::vector<std::vector<ReverseEdge>> reverse_graph(n);
for (int from = 0; from < n; from++) {
for (int index = 0; index < int(g[from].size()); index++) {
const auto& edge = g[from][index];
if (!edge.alive) continue;
assert(T(0) <= edge.cost);
reverse_graph[edge.to].push_back(ReverseEdge{from, index, edge.cost});
}
}
std::vector<T> dist(n, inf);
std::vector<int> tree_edge(n, -1);
std::vector<int> order;
order.reserve(n);
using QueueEntry = std::pair<T, int>;
std::priority_queue<QueueEntry, std::vector<QueueEntry>, std::greater<QueueEntry>> queue;
dist[t] = T(0);
queue.emplace(T(0), t);
while (!queue.empty()) {
auto [current_dist, vertex] = queue.top();
queue.pop();
if (dist[vertex] != current_dist) continue;
order.push_back(vertex);
for (const auto& edge : reverse_graph[vertex]) {
T next_dist = current_dist + edge.cost;
if (dist[edge.from] <= next_dist) continue;
dist[edge.from] = next_dist;
tree_edge[edge.from] = edge.index;
queue.emplace(next_dist, edge.from);
}
}
if (dist[s] == inf) return {};
internal::KShortestWalkHeap<T> heap_pool;
std::vector<int> local_heap(n, -1);
for (int vertex : order) {
for (int index = 0; index < int(g[vertex].size()); index++) {
const auto& edge = g[vertex][index];
if (!edge.alive || dist[edge.to] == inf || index == tree_edge[vertex]) continue;
T extra = edge.cost + dist[edge.to] - dist[vertex];
assert(T(0) <= extra);
int node = heap_pool.make_node(extra, edge.to);
local_heap[vertex] = heap_pool.meld_mutable(local_heap[vertex], node);
}
}
std::vector<int> path_heap(n, -1);
for (int vertex : order) {
int inherited = -1;
if (tree_edge[vertex] != -1) inherited = path_heap[g[vertex][tree_edge[vertex]].to];
path_heap[vertex] = heap_pool.meld_persistent(inherited, local_heap[vertex]);
}
std::vector<T> result;
result.reserve(k);
result.push_back(dist[s]);
std::priority_queue<QueueEntry, std::vector<QueueEntry>, std::greater<QueueEntry>> candidates;
if (path_heap[s] != -1) {
candidates.emplace(dist[s] + heap_pool[path_heap[s]].key, path_heap[s]);
}
while (int(result.size()) < k && !candidates.empty()) {
auto [cost, node_index] = candidates.top();
candidates.pop();
result.push_back(cost);
const auto& node = heap_pool[node_index];
if (node.left != -1) {
candidates.emplace(cost - node.key + heap_pool[node.left].key, node.left);
}
if (node.right != -1) {
candidates.emplace(cost - node.key + heap_pool[node.right].key, node.right);
}
int next_heap = path_heap[node.to];
if (next_heap != -1) {
candidates.emplace(cost + heap_pool[next_heap].key, next_heap);
}
}
return result;
}
} // namespace graph
} // namespace m1une