简体   繁体   English

为什么我的递归最长递增子序列函数不适用于大输入?

[英]Why doesn't my recursive longest increasing subsequence function work for large inputs?

I wrote it to work on a single test case at a time.我写它是为了一次处理一个测试用例。 It either takes too long on online judges or returns wrong answers在线评委花费的时间太长或返回错误的答案

Source: The problem I used to test it on来源: 问题我用来测试它

It works perfectly for small cases:它非常适合小案例:

#include <iostream>
  #include <algorithm>
  #include <vector>
  int LIS[100000];
  void LS (int *arr , int n)
  {
      if (n == 0)
      {
          LIS[0] = 1;
          return;
      }
      if (LIS[n])
      {
          return;
      }
      int i = 0;
      int max = 0;
      while (i < n)
      {
          if (arr[i] < arr[n])
          {
              LS(arr,i);
              if (LIS[i] + 1 > max)
              {
                  max = 1 + LIS[i];
              }
          }
          ++i;
      }
      LIS[n] = max;

  }
  int main()
  {
      int n;
      std::cin >> n;
      int arr[n];
      for(int i = 0 ; i < n ; ++i) std::cin >> arr[i];
      LS(arr,n-1);
      std::sort (LIS , LIS+n);
      std::cout << "\n" << LIS[n-1] << "\n";
  }

You said it works perfectly small cases.. than maybe it is stack overflow..你说它在很小的情况下工作得很好..比可能是堆栈溢出..

A function call consume stack memory..函数调用消耗堆栈内存..

If recursive call depth is too deep, stack memory runs out, and crash..如果递归调用深度太深,堆栈内存耗尽,并崩溃..

When you read int n value from std::cin , you have to dynamically allocate memory for your array arr , so you should first declare int *arr , then get the user input the same way as you're doing it now, and then allocate memory using arr = new int[n] .当您从std::cin读取int n值时,您必须为数组arr动态分配内存,因此您应该首先声明int *arr ,然后以与现在相同的方式获取用户输入,然后使用arr = new int[n]分配内存。

When it comes to the long time it takes to compute next values using recursive function, you should think about remaking the function to use tail recursion, which is much closer to iteration.当涉及到使用递归函数计算下一个值需要很长时间时,您应该考虑将函数改造成使用尾递归,这更接近迭代。 You can check the difference by writing two programs for counting Fibonacci numbers - one recursive and another one iterative, then check how long it takes to compute ~50th value using both methods.您可以通过编写两个计算斐波那契数的程序来检查差异 - 一个递归,另一个迭代,然后检查使用这两种方法计算第 50 个值需要多长时间。

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

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