Floyd

时间:2024-10-13 07:11:14

思想

  • 遍历所有V,考虑让每个顶点介入每个路径,以更新路径

题目

代码

#include <bits/stdc++.h>
using namespace std;
const int N = 210;
const int inf = 0x3f3f3f3f;
int g[N][N];
int n, m, k;
void floyd()
{
    for(int t = 1; t <= n; t++)
    {
        for(int i = 1; i <= n; i++)
        {
            for(int j = 1; j <= n; j++)
            {
                g[i][j] = min(g[i][j], g[i][t] + g[t][j]);
            }
        }
    }
}
int main()
{
    cin >> n >> m >> k;
    
    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= n; j++)
        {
            if(i == j) g[i][j] = 0;
            else g[i][j] = inf;
        }
    }
    for(int i = 1; i <= m; i++)
    {
        int a, b, c;
        cin >> a >> b >> c;
        g[a][b] = min(g[a][b], c);
    }
    
    floyd();
    
    while(k--)
    {
        int a, b;
        cin >> a >> b;
        if(g[a][b] > inf / 2) cout << "impossible\n" ;
        else cout << g[a][b] << '\n';
    }

}