如何进一步优化代码以克服TLE错误



我正在解决Codechef的一些问题,但我遇到问题https://www.codechef.com/may19b/problems/matchss.i遇到了这个问题,就是动态程序化问题。因此,我已经使用了functool.lru_cache来保存功能结果。但是,在某些测试用例中我会遇到tle错误。如何进一步优化代码?以下是问题:

Ari和Rich正在玩令人困惑的游戏。这是游戏的规则:

1. The game is played with two piles of matches. Initially, the first pile 
  contains N matches and the second one contains M matches.
2. The players alternate turns; Ari plays first.
3. On each turn, the current player must choose one pile and remove a 
  positive number of matches (not exceeding the current number of matches 
  on that pile) from it.
4. It is only allowed to remove X matches from a pile if the number of 
  matches in the other pile divides X.
5. The player that takes the last match from any pile wins.

solve(n,m(
1.如果它的Ari转弯和n%M == 0,那么Ari将获胜。
2.如果n%m!= 0,则玩家尝试所有可能的动作,并检查他是否赢了其中任何一个 最后。

from functools import lru_cache 
@lru_cache(maxsize=None)
def Solve(X,Y,Player=True):
    if X%Y==0:
        return Player
    else:
        temp=X
        X=X%Y
        if Player==Solve(max(X,Y),min(X,Y),not Player):
            return Player
        while temp!=X+Y:
            X=X+Y
            if Player==Solve(max(X,Y),min(X,Y),not Player):
                return Player
        return not Player

游戏玩了两堆比赛。最初,第一个堆 包含n匹配,第二个匹配包括M匹配。2.球员交替转弯;阿里首先扮演。3.在每个回合中,当前的玩家必须选择一个堆并删除 匹配数(不超过当前匹配数量 在那堆中(。4.如果数量的数量 在另一个桩中的匹配分配X。5.从任何桩中拿到最后一场比赛的球员

如何存储x和y值的计算,假设您的求解函数遇到了某些元素(14,5(,那么它将计算谁使用while循环并返回您获胜一些价值。现在假设您的功能遇到(19,5(,然后将计算(4,5(,(9,5(,(14,5(的值。如您所见,(14,5(被计算出两次。现在,想象一下数字为10^6和10^9大的情况,在这种情况下,您的程序将浪费大量时间来计算已经计算价值的情况的值。所以最后

>尝试将预计算值存储到列表

最新更新