zoukankan      html  css  js  c++  java
  • 【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
    ",d[x][y]);
    	}
    	return 0;
    }
    
    
  • 相关阅读:
    Django中的分页操作、form校验工具
    Django之form表单操作
    手写版本orm
    mysql注入问题
    MySQL基本操作
    初识数据库
    进程池、线程池
    信号量
    event事件
    死锁
  • 原文地址:https://www.cnblogs.com/bbqub/p/7453918.html
Copyright © 2011-2022 走看看