单源最短路-dijkstra

find the safest road

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5628    Accepted Submission(s): 2005


Problem Description
XX星球有很多城市,每个城市之间有一条或多条飞行通道,但是并不是所有的路都是很安全的,每一条路有一个安全系数s,s是在 0 和 1 间的实数(包括0,1),一条从u 到 v 的通道P 的安全度为Safe(P) = s(e1)*s(e2)…*s(ek) e1,e2,ek是P 上的边 ,现在8600 想出去旅游,面对这这么多的路,他想找一条最安全的路。但是8600 的数学不好,想请你帮忙 ^_^
 

Input
输入包括多个测试实例,每个实例包括:
第一行:n。n表示城市的个数n<=1000;
接着是一个n*n的矩阵表示两个城市之间的安全系数,(0可以理解为那两个城市之间没有直接的通道)
接着是Q个8600要旅游的路线,每行有两个数字,表示8600所在的城市和要去的城市
 

Output
如果86无法达到他的目的地,输出"What a pity!",
其他的输出这两个城市之间的最安全道路的安全系数,保留三位小数。
 

Sample Input
3
1 0.5 0.5
0.5 1 0.4
0.5 0.4 1
3
1 2
2 3
1 3
 

Sample Output
0.500
0.400
0.500

  忘记了used没有初始化,结果老是wa,真是血的教训啊!

#include<iostream>
#include<algorithm>
#define MAX 1002
using namespace std;
int n, m;
double cost[MAX][MAX];
double d[MAX];
bool used[MAX];
void dijkstra(int s){
    fill(d, d + MAX, 0);
    fill(used, used + MAX, false);
    d[s] = 1;
    while (true){
        int v = -1;
        for (int i = 0; i < n; i++){
            if (!used[i] && (v == -1 || d[i]>d[v]))v = i;
        }
        if (v == -1)break;
        used[v] = true;
        for (int i = 0; i < n; i++){
            d[i] = max(d[i], d[v]*cost[v][i]);
        }
    }
}
int main()
{
    int s, t;
    while (cin >> n){
        for (int i = 0; i < n; i++){
            for (int j = 0; j < n; j++){
                cin >> cost[i][j];
            }
        }
        cin >> m;
        for (int i = 0; i < m; i++){
            cin >> s >> t;
            dijkstra(s-1);
            if (d[t-1] != 0){
                printf("%.3lf
", d[t-1]);
            }
            else{
                printf("What a pity!
");
            }
        }
    }

    return 0;
}

 Floyd算法也能过,不过有个地方要改一下,也是觉得坑爹的地方

#include<iostream>
#include<algorithm>
#define MAX 1002
using namespace std;
int n, m;
double cost[MAX][MAX];
int main()
{
    int s, t;
    while (cin >> n){
        for (int i = 0; i < n; i++){
            for (int j = 0; j < n; j++){
                cin >> cost[i][j];
            }
        }
        //Floyd算法
        for (int k = 0; k < n; k++){
            for (int i = 0; i < n; i++){
                for (int j = 0; j < n; j++){
                    if (cost[i][j] < cost[i][k] * cost[k][j]){//这里如果用max判断,就会超时!!!
                        cost[i][j] = cost[i][k] * cost[k][j];
                    }
                }
            }
        }
        cin >> m;
        for (int i = 0; i < m; i++){
            cin >> s >> t;
            if (cost[s-1][t-1] != 0){
                printf("%.3lf
", cost[s - 1][t - 1]);
            }
            else{
                printf("What a pity!
");
            }
        }
    }

    return 0;
}
世上无难事,只要肯登攀。
原文地址:https://www.cnblogs.com/littlehoom/p/3553621.html