【floyd】8.29题解-path

path


题目描述

这次的任务很简单,给出了一张有N个点M条边的加权有向无环图,接下来有Q个询问,每个询问包括2个节点X和Y,要求算出从X到Y的一条路径,使得密度最小(密度的定义为,路径上边的权值和除以边的数量)。

输入输出

输入
第一行包括2个整数N和M。
以下M行,每行三个数字A、B、W,表示从A到B有一条权值为W的有向边。
再下一行有一个整数Q。
以下Q行,每行一个询问X和Y,如题意所诉。
输出
对于每个询问输出一行,表示该询问的最小密度路径的密度(保留3位小数),如果不存在这么一条路径输出“OMG!”(不含引号)。

样例

输入

3 3
1 3 5
2 1 6
2 3 6
2
1 3
2 3

输出

5.000
5.500

说明

数据范围
对于60%的数据,有1 ≤ N ≤ 10,1 ≤ M ≤ 100,1 ≤ W ≤ 1000,1 ≤ Q ≤ 1000;
对于100%的数据,有1 ≤ N ≤ 50,1 ≤ M ≤ 1000,1 ≤ W ≤ 100000,1 ≤ Q ≤ 100000。

思路

100%的数据只有不到50个点,所以floyd可以稳过
具体做法
在朴素的floyd上多加一维,f[x][y][t];
t代表x,y间的边数。
即:
f[x][y][1]=从x到y经过一条边时,最短的距离
f[x][y][2]=从x到y经过两条边时,最短的距离
······
所以有map[i][j][t]=min(map[i][j][t],map[i][k][t-1]+map[k][j][1]);

代码

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
const int maxx=17258205;
const int maxn=55;
int n,m,q;
double map[maxn][maxn][maxn];
double d[maxn][maxn];

inline int read() {
    int x=0,w=1;
    char ch=0;
    while(ch!='-'&&(ch<'0'||ch>'9')) ch=getchar();
    if(ch=='-') w=-1,ch=getchar();
    while(ch>='0'&&ch<='9')x=x*10+ch-48,ch=getchar();
    return x*w;
}

inline void add(int from,int to,double dist) {
    map[from][to][1]=min(map[from][to][1],dist);
}

inline void density() {
    for(int i=1; i<=n; i++)
        for(int j=1; j<=n; j++)
            for(int k=1; k<=n; k++)
                if(map[i][j][k]!=maxx)d[i][j]=min(d[i][j],map[i][j][k]/k);
}

void floyd() {
    for(int t=2; t<=n; t++)
        for(int k=1; k<=n; k++)
            for(int i=1; i<=n; i++)
                for(int j=1; j<=n; j++)
                    map[i][j][t]=min(map[i][j][t],map[i][k][t-1]+map[k][j][1]);
    density();
}

int main() {
    //freopen("path.in","r",stdin);
    //freopen("path.out","w",stdout);
    n=read();
    m=read();
    for(int i=1; i<=n; i++)
        for(int j=1; j<=n; j++) {
            for(int k=1; k<=n; k++)
                map[i][j][k]=maxx;
            d[i][j]=maxx;
        }
    for(int i=1; i<=m; i++) {
        int x,y,v;
        x=read(),y=read(),v=read();
        add(x,y,v);
    }
    floyd();
    q=read();
    for(int i=1; i<=q; i++) {
        int x,y;
        x=read(),y=read();
        if(d[x][y]==maxx) cout<<"OMG!"<<endl;
        else printf("%0.3lf\n",d[x][y]);
    }
    return 0;
}

转载于:https://www.cnblogs.com/bbqub/p/7453918.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值