版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/AivenZhong/article/details/86360084
题目大意:
这题和第一题的区别在于,小明事先得知路况(路口通过时间和交通灯数据),走之前预测估算走多少时间,不再是第一题那样走多少记多少。
思路:
由于没有亲自去走,所以需要模拟人去走,得到走的总时间,遇到路口就加时间,遇到交通灯的时候,通过总时间和交通灯一开始的情况推算出,现在交通灯情况,用现在交通灯情况就可以像第一题那样加时间。
细节:
1.推算时注意题目交通灯的标号(1-红,2-黄,3-绿),然后红绿灯运行顺序是((0)红–>(1)绿–>(2)黄),到时候进行推算的时候要进行下标与标号的转换,把123一一对应成012。下标往前推进的时候,通过模运算保证下标一直是0,1,2。
2.不要一个个灯去推(要不然就超时了,呜呜呜~~这次考试的时候就是这样,最后才70分),因为红绿灯是周期运行的,总时间可以减去前面的周期时间,剩下最后一个周期时间,再在这个周期时间内推算交通灯的情况
python代码:
def comput(light, time, total, r, y, g):
# 红-->绿-->黄
lights = [r, g, y]
# 转换下标
# 123ryg-->012rgy
if light == 1:
light = 0
elif light == 3:
light = 1
# 先减去第一个灯的剩余时间
total -= time
# 灯变成下一个灯
light = (light + 1) % 3
if total < 0:
return (light - 1) % 3, -total
# 减去前面重复的周期
total -= total // (r + y + g) * (r + y + g)
while total >= 0:
total -= lights[light]
light = (light + 1) % 3
return (light - 1) % 3, -total
# 主逻辑
r, y, g = map(int, input().split())
n = int(input())
total = 0
for i in range(n):
k, t = map(int, input().split())
# 通过路口
if k == 0:
total += t
# 遇到交通灯
else:
# 推算出当前交通灯的情况
k, t = comput(k, t, total, r, y, g)
# 红灯
if k == 0:
total += t
# 黄灯
elif k == 2:
total += t + r
print(total)