-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathShortest path with K edges.cpp
52 lines (41 loc) · 1.12 KB
/
Shortest path with K edges.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*8<
@Title:
Shortest Path With K-edges
@Description:
Given an adjacency matrix of a graph, and a
number $K$ computes the shortest path between
all nodes that uses exactly $K$ edges, so for
$0 \leq i, j \leq N-1$ ans[i][j] = "the
shortest path between $i$ and $j$ that uses
exactly $K$ edges, remember to initialize the
adjacency matrix with $\infty$.
@Time:
$O(N^3 \cdot \log{K})$
>8*/
template <typename T>
vector<vector<T>> prod(vector<vector<T>> &a,
vector<vector<T>> &b) {
const T _oo = numeric_limits<T>::max();
int n = a.size();
vector<vector<T>> c(n, vector<T>(n, _oo));
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
for (int k = 0; k < n; k++)
if (a[i][k] != _oo and b[k][j] != _oo)
c[i][j] =
min(c[i][j], a[i][k] + b[k][j]);
return c;
}
template <typename T>
vector<vector<T>> shortest_with_k_moves(
vector<vector<T>> adj, long long k) {
if (k == 1) return adj;
auto ans = adj;
k--;
while (k) {
if (k & 1) ans = prod(ans, adj);
k >>= 1;
adj = prod(adj, adj);
}
return ans;
}