为什么D题使用@cache + dfs 过不了

@cache + dfs的递归和递推在复杂度上是等效的吧?

from math import sqrt, log, gcd, inf
# from math import isqrt  #pypy 无
from operator import ixor, and_
from random import randint
from string import ascii_lowercase
from typing import List
from heapq import *
from collections import *
from bisect import *
from itertools import *
from functools import lru_cache
from copy import *
import sys

sys.setrecursionlimit(1500000)  #pypy卡这个...
input = lambda: sys.stdin.readline().rstrip()
il = lambda: list(map(int, input().split()))
ix = lambda: il()[0]
iis = lambda: input().split()
printt = print
print = lambda a: printt(" ".join(map(str, a))) if isinstance(a, list) else printt(a)
def pairwise(a):
    ans = []; n = len(a)
    for i in range(n - 1): ans += (a[i], a[i + 1]),
    return ans
py = lambda: print("YES")
pn = lambda:  print("NO")
mod = 998244353  #ac
# mod = 10**9 + 7
'''代码'''

# mod ↑

times = 1  # 0有t, 1无t
if not times:
    times = ix()
for _ in range(times):
    n,mn,mx = il()
    s= input()
    c0 , c1 = [0], [0]
    for x in s:
        c0 += c0[-1] + (x == "0"),
        c1 += c1[-1] + (x == "1"),
    # print([c0,c1])
    n = len(s)


    @lru_cache(maxsize=None)
    def dfs(l=0, r=n - 1):
        # if l == r: return 0
        ans = 0
        for i in range(l + 1, r + 1):
            if mn <= abs(c0[i] - c0[l] - (c1[r + 1] - c1[i])) <= mx:
                t = dfs(l, i - 1) + dfs(i, r) + 1
                if t > ans : ans = t
                # ans = max(ans, dfs(l, i - 1) + dfs(i, r) + 1)
        return ans

    ans = dfs()
#     dfs.cache_clear()
    print(ans)

    # code ↑

'''test
3
1 1
2 2
9982 44353
'''

全部评论

相关推荐

点赞 评论 收藏
分享
2 收藏 评论
分享
牛客网
牛客企业服务