最小密度路径 洛谷 1730

来源:互联网 发布:java提取数组相同元素 编辑:程序博客网 时间:2024/05/02 23:14

题目描述

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

输入输出格式

输入格式:
第一行包括2个整数N和M。

以下M行,每行三个数字A、B、W,表示从A到B有一条权值为W的有向边。

再下一行有一个整数Q。

以下Q行,每行一个询问X和Y,如题意所诉。

输出格式:
对于每个询问输出一行,表示该询问的最小密度路径的密度(保留3位小数),如果不存在这么一条路径输出“OMG!”(不含引号)。

输入输出样例

输入样例#1:
3 3
1 3 5
2 1 6
2 3 6
2
1 3
2 3
输出样例#1:
5.000
5.500
说明

1 ≤ N ≤ 10,1 ≤ M ≤ 100,1 ≤ W ≤ 1000,1 ≤ Q ≤ 1000

分析:
直接暴力就好了,这题数据n只有10。

代码:

var  n,m,q:longint;  a:array [0..51,0..51,0..51] of longint;procedure init;var  i,j,l,k,x,y,z:longint;begin  fillchar(a,sizeof(a),255);  readln(n,m);  for i:=1 to m do    begin      readln(x,y,z);      if (a[x,y,1]=-1) or (z<a[x,y,1]) then        a[x,y,1]:=z;    end;  for i:=1 to n do    a[i,i,0]:=0;  for l:=2 to n do    for k:=1 to n do      for i:=1 to n do        for j:=1 to n do          if (a[i,k,l-1]>-1) and (a[k,j,1]>-1) and ((a[i,j,l]=-1) or (a[i][j][l]>a[i,k,l-1]+a[k,j,1])) then            a[i,j,l]:=a[i,k,l-1]+a[k,j,1];end;procedure main;var  i,j,x,y:longint;  max:real;begin  readln(q);  for i:=1 to q do    begin      readln(x,y);      max:=maxlongint div 3;      for j:=0 to n do        if (a[x,y,j]<>-1) and (a[x,y,j]<max*j) then          max:=a[x,y,j]/j;        if max<>maxlongint div 3 then writeln(max:0:3)                                 else writeln('OMG!');    endend;begin  init;  main;end.
0 0
原创粉丝点击