题解:P5810 [SCOI2004] 文本的输入

· · 题解

题意简述

你有两个数字 a、b,它们初始都为 0,你有如下 3 种操作:

给定一个正整数 n,问至少需要多少代价使得 a \ge n?

基本思路

考虑 BFS,每次搜索相同代价的 (a, b) 组合,直到搜到某一代价的某个 (a, b) 组合满足 a \ge n,则该代价即为最小代价。

优化

对于内存管理,注意到当前搜索位置仅需保留该代价及其之后的 5 个代价的情况,因此可以使用滚动数组,一个数组内仅需存储 6 个集合。

对于运行速度,考虑一个强力的剪枝:对于某代价集合的任意 (a, b),如果该代价集合中存在另一组 (a', b') 满足 a \le a' 且 b \le b',则 (a, b) 组合显然是较为不优的,可以直接舍去。

代码

def main():
    n=int(input())
    mem=[set() for _ in range(6)] # 滚动数组
    mem[0].add((0,0)) # 搜索起点
    index=0
    while True:
        for i,j in mem[0].copy():
            if any(i<=k and j<=l and (i,j)!=(k,l) for k,l in mem[0]):
                mem[0].remove((i,j)) # 剪枝优化
        max_count=0
        while mem[0]:
            count,length=mem[0].pop()
            if count>=n:
                return print(index) # 答案输出
            mem[1].add((count+1,length)) # 操作 1
            mem[2].add((count+length,length)) # 操作 2
            max_count=max(count,max_count)
        mem[5].add((max_count,max_count)) # 操作 3
        index+=1
        mem.append(mem.pop(0))
main()

运行效率

经实际测试,该代码的运行效率奇高无比,哪怕输入 10 ^ {1000} 也能立刻输出结果,内存占用也极低。