日期:2026年5月13日
ZeroJudge 題目連結:d242. 00481 - What Goes Up
解題想法
這題要找最長遞增子序列 (longest increasing subsequence, LIS) 的內容,網路上有不少的教學。我是記錄目前 lis 對應的字元索引值,最後再將這些索引值對應的字元組成字串,反序後輸出。
Python 程式碼
使用時間約為 0.9 s,記憶體約為 64.9 MB,通過測試。
def get_lis(nums):
if not nums: return []
n = len(nums)
prev = [-1]*n
tails = []
for i, num in enumerate(nums):
low, high = 0, len(tails)-1
while low <= high:
mid = (high - low) // 2 + low
if num > nums[tails[mid]]: low = mid + 1
else: high = mid - 1
if low == len(tails): tails.append(i)
else: tails[low] = i
if low > 0: prev[i] = tails[low-1]
lis = []
curr = tails[-1]
while curr != -1:
lis.append(nums[curr])
curr = prev[curr]
return lis[::-1]
def solve():
import sys
result = []
arr = list(map(int, sys.stdin.read().split()))
lis = get_lis(arr)
result.append(f"{len(lis):d}\n-\n")
for v in lis: result.append(f"{v:d}\n")
sys.stdout.write("".join(result))
if __name__ == "__main__":
solve()