Floyd算法
作者:
Oct_9
,
2024-04-24 14:20:53
,
所有人可见
,
阅读 12
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 210, INF = 0x3f3f3f3f;
int n, m, Q;
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()
{
scanf("%d%d%d", &n, &m, &Q);
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;
scanf("%d%d%d", &a, &b, &w);
d[a][b] = min(d[a][b], w);
}
floyd();
while (Q --)
{
int a, b;
scanf("%d%d", &a, &b);
if (d[a][b] >= INF / 2) puts("impossible");
else printf("%d\n", d[a][b]);
}
return 0;
}