find the safest road 【最长路】

来源:互联网 发布:男士保湿爽肤水 知乎 编辑:程序博客网 时间:2024/05/22 05:20

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

最长路

代码

#include<bits/stdc++.h>#define LL long longusing namespace std;const int MAXN = 1e3+100;const int MAXM =1e6;const int inf = 0x3f3f3f3f;inline int read(){    int f=1,x=0;char ch=getchar();    while(ch<'0'||ch>'9') {if(ch=='-') f=-1;ch=getchar();}    while(ch>='0'&&ch<='9') {x=x*10+ch-'0';ch=getchar();}    return x*f;}/*------------------------------*/struct Edge {    int from,to,nexts;    double val;}edge[MAXM]; int head[MAXN],top; int n,m; void init(){    memset(head,-1,sizeof(head));    top=0; } void addedge(int a,int b,double c){    Edge e ={a,b,head[a],c};    edge[top]=e;head[a]=top++; } void getmap(){     double c;    for(int i=1;i<=n;i++){        for(int j=1;j<=n;j++){            scanf("%lf",&c);            if(i>j) continue;            addedge(i,j,c*1.0);            addedge(j,i,c*1.0);        }    } } int vis[MAXN]; double dis[MAXN]; void spfa(int st,int ed){    for(int i=0;i<=n;i++) {        vis[i]=0;        dis[i]=0.0;    }    queue<int>que;    que.push(st);vis[st]=1;    dis[st]=1.0;    while(!que.empty()){        int now=que.front();que.pop();vis[now]=0;        for(int i=head[now];i!=-1;i=edge[i].nexts){            int nexts=edge[i].to;            if(dis[nexts]<dis[now]*edge[i].val){                dis[nexts]=dis[now]*edge[i].val;                if(!vis[nexts]){                    que.push(nexts);                    vis[nexts]=1;                }            }        }    }    if(fabs(dis[ed]-0.0)<1e-8 ) puts("What a pity!");    else printf("%.3lf\n",dis[ed]); }int main(){    while(~scanf("%d",&n)){        init();        getmap();        int q;cin>>q;        while(q--){            int a,b;            scanf("%d%d",&a,&b);            spfa(a,b);        }    }    return 0;}