首页 > 试题广场 >

最小花费

[编程题]最小花费
  • 热度指数:9287 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
在某条线路上有N个火车站,有三种距离的路程,L1,L2,L3,对应的价格为C1,C2,C3.其对应关系如下: 距离s           票价 0<S<=L1         C1 L1<S<=L2        C2 L2<S<=L3        C3 输入保证0<L1<L2<L3<10^9,0<C1<C2<C3<10^9。 每两个站之间的距离不超过L3。 当乘客要移动的两个站的距离大于L3的时候,可以选择从中间一个站下车,然后买票再上车,所以乘客整个过程中至少会买两张票。 现在给你一个 L1,L2,L3,C1,C2,C3。然后是A B的值,其分别为乘客旅程的起始站和终点站。 然后输入N,N为该线路上的总的火车站数目,然后输入N-1个整数,分别代表从该线路上的第一个站,到第2个站,第3个站,……,第N个站的距离。 根据输入,输出乘客从A到B站的最小花费。

输入描述:
以如下格式输入数据:
L1  L2  L3  C1  C2  C3
A  B
N
a[2]
a[3]
……
a[N]


输出描述:
可能有多组测试数据,对于每一组数据,
根据输入,输出乘客从A到B站的最小花费。
示例1

输入

1 2 3 1 2 3
1 2
2
2

输出

2
def fareNum(distance):
    if distance <= length[0]:
        return costs[0]
    elif distance <= length[1]:
        return costs[1]
    else:
        return costs[2]
try:
    while True:
        tempInput = list(map(int,input().split()))
        length = tempInput[:3]
        costs = tempInput[3:]
        a,b = list(map(int,input().split()))
        if a > b:
            a,b = b,a
        n = int(input())
        distances = [0,0]                    #distances[i]表示第一个车站到第i个车站的路程
        for i in range(n-1):
            distances.append(int(input()))
        spend = [float('inf')] * (n+1)       #spend[i]表示车站a到车站i的最小花费
        spend[a] = 0
        for i in range(a+1,b+1):
            temp = i - 1                     #从前一个开始查找最少花费
            while temp >= a and (distances[i]-distances[temp]) <= length[2]:
                spend[i] = min(spend[i],spend[temp]+fareNum(distances[i]-distances[temp]))
                temp -= 1
        print(spend[b])
except Exception:
    pass
编辑于 2018-10-09 23:07:49 回复(0)