21: Mincost
题目描述
The cost of taking a taxi in Hangzhou is not a constant for each kilometer you travel: the first 4 kilometers costs 10 yuan (yuan is the monetary unit in China), even if you don't finish it; the next 4 kilometers costs 2 yuan each and the price for the rest of the trip is 2.4 yuan per kilometer; the last part of the trip is regarded as 1 kilometer even if it's shorter. A traveller may reduce the cost by reseting the meter at the middle of the trip if used wisely. For example, if the trip is 16 kilometers, he should cut it into two parts with the same length, each half will cost 18 yuan, with an overall cost of 36, less than the original price of 37.2. Now, given the length of the trip, find the minimum cost.
输入
The input contains several cases, each has one positive integer in a seperate line, representing the length of the trip. All input data are less than 10000000. Proceed until a case with zero, which should be ignored.
输出
For each case, output the minimum cost, leave one digit after decimal point if NECESSARY.
输入样例
3
9
16
0
输出样例
10
20.4
36
分析和代码
题目大意:根据给出的公里数(小于10000000),计算打车的最小花费是多少。有多组输入,输入0时表示输入结束。 打车费用计算规则为前4公里(不管是否满4公里)均为10元;接下来4公里,2元/公里;剩下的公里为2.4元/公里。 分析:设给出的公里数为len。如果len <= 8,则打一次车即可;如果 len > 8,则需要考虑在什么时候需要重新打车。 只有在最后一段路程的费用超过重新打车的费用时,才需要重新打车,所以只需找到最后一段路程长为多少时的花费会超过 重新打车的费用。当最后一段长为 5 时,这一段花费为 5 * 2.4 = 12元,重新打车费用为 10 + 2 = 12元,当最后一段长为 6 时, 这一段花费为 14.4 元,重新打车费用为 14 元,所以只有当总长大于 13 时,我们才需要重新打车,根据分析可直接给出代码。#include<bits/stdc++.h>
using namespace std;
double cal(int len)
{
if(len <= 4) return 10;
else
{
if(len <= 8) return (10 + (len - 4) * 2);
else
{
if(len <= 13) return ((len - 8) * 2.4 + 18);
else
{
return 18 + cal(len - 8);
}
}
}
}
int main()
{
int len;
double pay;
while(scanf("%d", &len) != EOF)
{
if(len == 0) break;
pay = cal(len);
printf("%g\n", pay);
}
return 0;
}

浙公网安备 33010602011771号