恰好经过 k 条边的最短路
P2886 [USACO07NOV] Cow Relays G
O(kn^3)
这道题可以用类似于 Floyd 的写法解决。考虑 dp,记
这样每次转移枚举
如此转移,求恰好经过
O(n^3\log k)
举例路径
关于优化和坑点
- 本题不需要单独定义第一维度,在计算时顺便维护即可(就像快速幂中不需要单独记录当前的幂次)。
- 快速幂的答案数组,代表了最初始的状态,即经过
0 条边最短路。此时,异点距离应为正无穷,同点由于不需要经过任意边就可以到,因此距离是0 。 - 描述初始图的数组,表示的是经过
1 条边的最短路。此时,异点距离取决于有没有边相连,同点不能初始化为0 ,因为0 没有经过任何边,这里需要恰好经过1 条边。
CODE for O(n^3\log k)
#include <iostream>
#include <algorithm>
#include <cstring>
#include <map>
using namespace std;
const int N = 110;
int res[N][N], g[N][N], temp[N][N];
// 需要离散化点坐标,不保序
map<int, int> id; int cnt;
int n, t, s, e;
void mul(int a[][N], int b[][N], int c[][N])
{
memset(temp, 0x3f, sizeof temp);
for (int k = 1; k <= cnt; k ++ )
for (int i = 1; i <= cnt; i ++ )
for (int j = 1; j <= cnt; j ++ )
temp[i][j] = min(temp[i][j], b[i][k] + c[k][j]);
memcpy(a, temp, sizeof temp);
}
void qmi()
{
memset(res, 0x3f, sizeof res);
for (int i = 1; i <= cnt; i ++ )
res[i][i] = 0;
while (n)
{
if (n & 1)
mul(res, res, g);
mul(g, g, g);
n >>= 1;
}
}
int main()
{
memset(g, 0x3f, sizeof g);
cin >> n >> t >> s >> e;
while (t -- )
{
int a, b, c;
cin >> a >> b >> c;
if (!id.count(b))
id[b] = ++ cnt;
if (!id.count(c))
id[c] = ++ cnt;
b = id[b], c = id[c];
g[b][c] = g[c][b] = min(g[b][c], a);
}
qmi();
s = id[s], e = id[e];
cout << res[s][e];
}