按照floyd算法,每次用k去更新, 和模板不同的是, 这里的k并不是一直可以用,因此需要循环判断,用当前可以更新的点来更新最短距离
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
using namespace std;
const int N = 210, INF = 0x3f3f3f3f;
int d[N][N];
int t[N];
int n, m;
void floyd(int 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;
for (int i = 1; i <= n; i ++ ) scanf("%d", &t[i]);
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, c;
scanf("%d%d%d", &a, &b, &c);
a ++, b ++;
d[a][b] = d[b][a] = c;
}
int q;
cin >> q;
while (q -- )
{
int x, y, time;
scanf("%d%d%d", &x, &y, &time);
x++, y ++;
int current = 1;
while (t[current] <= time && current <= n)
{
floyd(current);
current ++;
}
if (t[x] > time || t[y] > time || d[x][y] >= INF / 2) cout << -1 << endl;
else cout << d[x][y] << endl;
}
return 0;
}