旅行家的预算

时间:2023-01-09 10:26:42

 

题目描述

一个旅行家想驾驶汽车以最少的费用从一个城市到另一个城市(假设出发时油箱是空的)。给定两个城市之间的距离D1、汽车油箱的容量C(以升为单位)、每升汽油能行驶的距离D2、出发点每升汽油价格P和沿途油站数N(N可以为零),油站i离出发点的距离Di、每升汽油价格Pi(i=1,2,…,N)。计算结果四舍五入至小数点后两位。如果无法到达目的地,则输出“No Solution”。

输入输出格式 Input/output

输入格式:
第一行,D1,C,D2,P,N。
接下来有N行。
第i+1行,两个数字,油站i离出发点的距离Di和每升汽油价格Pi。
输出格式:
所需最小费用,计算结果四舍五入至小数点后两位。如果无法到达目的地,则输出“No Solution”。

输入输出样例 Sample input/output

样例测试点#1
输入样例: 

275.6 11.9 27.4 2.8 2
102.0 2.9
220.0 2.2

输出样例:

26.95

 


1 #include<iostream> 2 #include<algorithm>
3 #include<iomanip>
4 using namespace std;
5 double d[10000], p[10000];
6 int main()
7 {
8 ios::sync_with_stdio(false);
9 double d1, c, d2;
10 int n;
11 cin >> d1 >> c >> d2 >> p[0] >> n;
12 d[n + 1] = d1;
13 for (int i = 1; i <= n; i++)
14 {
15 cin >> d[i] >> p[i];
16 }
17 int pos = 0;
18 double remain = 0, cost = 0;
19 do
20 {
21 bool found = false;
22 for (int i = pos + 1; i <= n + 1 && d[i] <= d[pos] + c*d2; i++)
23 {
24 if (p[i] < p[pos])
25 {
26 if (d[pos] + remain*d2 >= d[i])
27 {
28 remain -= (d[i] - d[pos]) / d2;
29 }
30 else
31 {
32 cost += ((d[i] - d[pos]) / d2 - remain)*p[pos];
33 remain = 0;
34 }
35 pos = i;
36 found = true;
37 break;
38 }
39 }
40 if (!found)
41 {
42 cost += (c - remain)*p[pos];
43 remain = c - (d[pos + 1] - d[pos]) / d2;
44 if (remain >= 0) pos++;
45 else
46 {
47 cout << "No Solution";
48 return 0;
49 }
50 }
51 } while (pos <= n);
52 cout.setf(ios::fixed);
53 cout << setprecision(2) << cost;
54 }