首页 > 代码库 > uva10048

uva10048

题目链接请戳 这里

 

解题思路

用类似于floyd算法解决。

状态转移方程:dp[i][j] = min(dp[i][j], max(dp[i][k], dp[k][j]))

 

代码

#include<iostream>
#include<algorithm>
using namespace std;

const int N = 110;
const int INF = 1e9 + 1;

int dp[N][N];
int n, m, q;

void floyd()
{
    for (int k = 1; k <= n; k++) {
        for (int i = 1; i <= n; i++) {
            //注意要判断i和k之间k和j之间是否有通路,否则求max的时候会把INF也算进去
            for (int j = 1; j <= n; j++) if(dp[i][k] < INF && dp[k][j] < INF){
                int min_num = max(dp[i][k], dp[k][j]);
                dp[i][j] = min(dp[i][j], min_num);
            }
        }
    }
}
int main()
{
    cin >> n >> m >> q;
    int t = 0;
    while (!(n == 0 && m == 0 && q == 0)) {
        t++;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                if (i != j)
                    dp[i][j] = INF;
                else
                    dp[i][j] = 0;
            }
        }
        for (int i = 0; i < m; i++) {
            int c1, c2, d;
            cin >> c1 >> c2 >> d;
            //注意是无向的,来回都要赋值
            dp[c1][c2] = d;
            dp[c2][c1] = d;
        }
        floyd();
        cout << "Case #" << t << endl;
        for (int i = 0; i < q; i++) {
            int a, b;
            cin >> a >> b;
            if(dp[a][b] < INF)
                cout << dp[a][b] << endl;
            else 
                //a和b之间没有通路
                cout << "no path" << endl;
        }
        cin >> n >> m >> q;
        //最后一个测试组不用输出换行
        if (!(n == 0 && m == 0 && q == 0)) cout << endl;
    }
}

 

uva10048