[AcWing 854] Floyd求最短路
作者:互联网
复杂度 \(O(n^{3})\)
点击查看代码
#include<iostream>
using namespace std;
const int N = 210, INF = 1e9;
int n, m, k;
int d[N][N];
void floyd()
{
for (int k = 1; k <= n; k ++)
for (int i = 1; i <= n; i ++)
for (int j = 1; j <= n; j ++)
d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
}
int main()
{
cin >> n >> m >> k;
for (int i = 1; i <= n; i ++) {
for (int j = 1; j <= n; j ++) {
if (i == j) d[i][j] = 0;
else d[i][j] = INF;
}
}
while (m --) {
int a, b, w;
cin >> a >> b >> w;
d[a][b] = min(d[a][b], w);
}
floyd();
while (k --) {
int a, b;
cin >> a >> b;
if (d[a][b] > INF / 2) puts("impossible");
else cout << d[a][b] << endl;
}
return 0;
}
- 不能处理出现负权回路的情况;
- 对负环不需要进行处理(因为题干保证了没有负权回路),对重边只保留最小值;
- d[ i ][ k ] + d[ k ][ j ] 代表从 i 到 j 经过 1 - k 这些点的最短路;
标签:854,int,Floyd,短路,floyd,回路,INF,负权,AcWing 来源: https://www.cnblogs.com/wKingYu/p/16242115.html