【发布时间】:2012-01-27 06:50:55
【问题描述】:
我在 Codechef 遇到了问题here。我正在尝试使用向量进行记忆。由于我还是编程新手,而且对 STL 容器非常陌生,因此我使用了vector 作为查找表。 (尽管有人建议我使用map 有助于解决问题)。
所以,我的问题是下面给出的解决方案是如何遇到运行时错误的。为了得到错误,我使用问题的边界值 (100000000) 作为输入。我的 Netbeans IDE 显示的错误消息是 RUN FAILED (exit value 1, total time: 4s),输入为 1000000000。代码如下:
#include <iostream>
#include <cstdlib>
#include <vector>
#include <string>
#define LCM 12
#define MAXSIZE 100000000
using namespace std;
/*
*
*/
vector<unsigned long> lookup(MAXSIZE,0);
int solve(int n)
{
if ( n < 12) {
return n;
}
else {
if (n < MAXSIZE) {
if (lookup[n] != 0) {
return lookup[n];
}
}
int temp = solve(n/2)+solve(n/3)+solve(n/4);
if (temp >= lookup[n] ) {
lookup[n] = temp;
}
return lookup[n];
}
}
int main(int argc, char** argv) {
int t;
cin>>t;
int n;
n = solve(t);
if ( t >= n) {
cout<<t<<endl;
}
else {
cout<<n<<endl;
}
return 0;
}
【问题讨论】:
-
这可能是你递归太多并得到堆栈溢出。使用调试器看看会发生什么。
标签: c++ recursion vector runtime-error memoization