Skip to content

02945: 拦截导弹

dp, greedy http://cs101.openjudge.cn/practice/02945/

某国为了防御敌国的导弹袭击,开发出一种导弹拦截系统。但是这种导弹拦截系统有一个缺陷:虽然它的第一发炮弹能够到达任意的高度,但是以后每一发炮弹都不能高于前一发的高度。某天,雷达捕捉到敌国的导弹来袭,并观测到导弹依次飞来的高度,请计算这套系统最多能拦截多少导弹。拦截来袭导弹时,必须按来袭导弹袭击的时间顺序,不允许先拦截后面的导弹,再拦截前面的导弹。

输入

输入有两行, 第一行,输入雷达捕捉到的敌国导弹的数量k(k<=25), 第二行,输入k个正整数,表示k枚导弹的高度,按来袭导弹的袭击时间顺序给出,以空格分隔。

输出

输出只有一行,包含一个整数,表示最多能拦截多少枚导弹。

样例输入

8
300 207 155 300 299 170 158 65

样例输出

6

来源

医学部计算概论2006期末考试题

使用动态规划(Dynamic Programming)来计算最长非递增子序列的长度。核心思路:

  • 状态定义dp[i] 表示以第 i 个导弹为结尾的最长非递增子序列长度。
  • 状态转移:对于每个 i,遍历 j < i,如果 heights[i] <= heights[j],则 dp[i] = max(dp[i], dp[j] + 1)
  • 初始状态:每个导弹自身构成一个长度为 1 的子序列,故 dp = [1] * n
  • 结果max(dp) 即为全局最长非递增子序列的长度。
python
def max_intercepted_missiles(k, heights):
    # Initialize the dp array
    dp = [1] * k

    # Fill the dp array
    for i in range(1, k):
        for j in range(i):
            if heights[i] <= heights[j]:
                dp[i] = max(dp[i], dp[j] + 1)

    # The result is the maximum value in dp array
    return max(dp)


if __name__ == "__main__":

    k = int(input())
    heights = list(map(int, input().split()))

    result = max_intercepted_missiles(k, heights)
    print(result)
python
"""
与这个题目思路相同:
28389: 跳高,http://cs101.openjudge.cn/practice/28389

拦截导弹 求最长不升LNIS,可以相等所以用 bisect right。如果求最长上升LIS,用 bisect_left
"""

from bisect import bisect_right

def min_testers_needed(scores):
    scores.reverse()  # 反转序列以找到最长下降子序列的长度
    lis = []  # 用于存储最长上升子序列

    for score in scores:
        pos = bisect_right(lis, score)
        if pos < len(lis):
            lis[pos] = score
        else:
            lis.append(score)

    return len(lis)


N = int(input())
scores = list(map(int, input().split()))

result = min_testers_needed(scores)
print(result)