简体   繁体   English

如何修复超过时间限制

[英]How to fix Time Limit Exceeded

Hi the given code is here嗨,给定的代码在这里

int a, b, c, d, e, f;
int fn( int n ) {
    if( n == 0 ) return a;
    if( n == 1 ) return b;
    if( n == 2 ) return c;
    if( n == 3 ) return d;
    if( n == 4 ) return e;
    if( n == 5 ) return f;
    return( fn(n-1) + fn(n-2) + fn(n-3) + fn(n-4) + fn(n-5) + fn(n-6) );
}
int main() {
    int n, caseno = 0, cases;
    scanf("%d", &cases);
    while( cases-- ) {
        scanf("%d %d %d %d %d %d %d", &a, &b, &c, &d, &e, &f, &n);
        printf("Case %d: %d\n", ++caseno, fn(n) % 10000007);
    }
    return 0;
}

It has two problems.它有两个问题。 One is integer overflow .一种是integer 溢出 And another is Time Limit Exceeded .另一个是Time Limit Exceeded I fixed the integer overflow using long int.我使用long int 修复了 integer 溢出。 But problem is with time.但问题在于时间。 When I submit the code, the online judge shows Time Limit Exceeded .当我提交代码时,在线法官显示Time Limit Exceeded Please help me to fix this problem.请帮我解决这个问题。

This looks like a pretty standard dynamic programming problem, and the key is memoizing your function.这看起来像是一个非常标准的动态规划问题,关键是记住你的 function。 Since this is a problem, I won't provide any code, but I will explain what you have to do.由于这是一个问题,我不会提供任何代码,但我会解释你必须做什么。 You should maintain an array of values, and before returning from your function you update the value in the array with the return value.您应该维护一个值数组,并在从 function 返回之前使用返回值更新数组中的值。 At the start of the function, you check if that array has the return value already, and if it does, then you can just return that value.在 function 的开头,您检查该数组是否已经有返回值,如果有,那么您可以返回该值。

Read more about memoization here .在此处阅读有关记忆的更多信息

Your approach has an exponential time complexity and is far from ideal.您的方法具有指数时间复杂度,远非理想。 The good news is that there is a simple and easy fix.好消息是有一个简单易行的修复方法。

What you can do is simply create an array whose size is the max possible value of n .您可以做的只是创建一个数组,其大小是n的最大可能值。 I presume it is probably something like 10^5 , as is the standard for such problems.我认为它可能类似于10^5 ,这是此类问题的标准。

Let us call this array ans[] .让我们将此数组称为ans[] Set the first 6 values of ans[] manually and for the rest, run a loop which does something like this:手动设置ans[]的前 6 个值,对于 rest,运行如下循环:

ans[i] = (ans[i-1] + ans[i-2] + ans[i-3] + ans[i-4] + ans[i-5] + ans[i-6]) % 1000000007

Now, for each case, you simply need to print ans[n] as your answer.现在,对于每种情况,您只需打印ans[n]作为您的答案。 (or ans[n-1] depending upon how you've stored the elements. (或ans[n-1]取决于您存储元素的方式。

On a separate note, you may want to check the number with which you're taking the modulo.在单独的说明中,您可能需要检查用于取模的数字。 It is supposed to be 10^9 + 7 , yours is missing two 0s.它应该是10^9 + 7 ,你的缺少两个 0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM