0
点赞
收藏
分享

微信扫一扫

无字母绕过webshell

Ad大成 2024-08-18 阅读 43
动态规划

跳格子3 (200)

  • 跳格子游戏,每个格子上有特定的分数,从起点score[0]开始,每次最大的步长为k, 计算跳到终点时能够得到的最大分数;
  • 格子总长度、步长在【1,100000】,每个格子的分数在【-10000,10000】

输入描述:
第一行输入总的格子数;
第二行输入格子的分数;
第三行输入最大步长k
输出描述:
最大分数值

示例1
输入:
6
1 -1 -6 7 -17 7
2
输出:
14

示例2
输入:
10
2 -3 2 5 -1 -3 -4 9 1 -3
5
输出:
16

思路:

  • 动态规划,i = 0时的分数为当前最大分数;

# 输入格子数
n = int(input().strip())
scores = list(map(int, input().strip().split()))
k = int(input().strip())

# n * 2
queue = [[0 for i in range(2)] for j in range(n)]
cache = [0 for i in range(n)]

# 起始位置
cache[0] = scores[0]
queue[0][0] = 0 #
queue[0][1] = cache[0]

index1 = 0 # 当前最大分数 的位置
index2 = 1 # 当前跳的位置

# 从第二个位置开始跳
i = 1
while i < n:
    # 步长控制
    while index1 < index2:
        # 步长超出
        if queue[index1][0] < i - k: # i 表示当前跳的位置
            index1 += 1
        else:
            break

    # 当前跳的位置分数 + 当前的最大分数
    cache[i] = scores[i] + queue[index1][1]

    while index1 < index2:
        # 向更大分数 走一步
        if queue[index1][1] <= cache[i]:
            index1 += 1

        else:
            break

    # 记录当前位置的分数
    queue[index2][0] = i  # 跳的位置
    queue[index2][1] = cache[i] # 对应分数
    index2 += 1
    i += 1

print(cache[n - 1])

举报

相关推荐

0 条评论