【问题标题】:How to avoid SEGMENTATION ERROR for the code below?如何避免以下代码的分段错误?
【发布时间】:2015-06-02 17:55:19
【问题描述】:

我收到以下代码的分段错误。这是the SPOJ problem "Coins"的解决方案。

我检查了How to avoid SIGSEGV?,并确保不要使用未初始化的指针,不要访问内存不足等(给定 n ≤ 109)。

我知道数组a[1000000000] 会导致堆栈溢出,所以我使用了std::mapstd::map 会导致堆栈溢出吗?我的代码有什么问题?

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <map>

using namespace std;

map<unsigned long long int, unsigned long long int> a;

unsigned long long int dp(unsigned long long int n)
{   
   if (a.find(n) == a.end())
      a[n] = dp(n/2) + dp(n/3) + dp(n/4);

   return a[n];
}

int main()
{
    for (unsigned long long int i = 1; i <= 24; i++) {
        a[i] = i;
        if (i == 12 || i == 24)
           a[i] = i + 1;
    }

    unsigned long long int n = 0;
    cin >> n;

    while (!feof(stdin)) {
        printf("%llu\n", dp(n));
        cin >> n;
    }
}

【问题讨论】:

  • @Michelle 确定是的。看main()开头的for循环
  • @Michelle : 我让它全球化了
  • 如果你有 10^9 long long's 那么这将占用超过 7GB 的内存。你有多少内存?
  • 你的缩进很奇怪

标签: c++ segmentation-fault maps dynamic-programming


【解决方案1】:

您在dp(0) 通话中获得 SIGSEGV。它会导致无限递归。

顺便说一句,你的解决方案是错误的,例如24的答案不是25。尽量避免使用魔法常数,设置a[0] = 0并制作更准确的dp函数就足够了:

uint32_t dp(uint32_t n) {
    if (a.find(n) == a.end())
        a[n] = max(n, dp(n / 2) + dp(n / 3) + dp(n / 4));

    return a[n];
}

从上面可以看出,32位类型足以存储任何可能的答案。

【讨论】:

  • 非常感谢.....AC.....想要投票给你的答案....但是stackoverflow的新手...没有足够的声誉:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-16
  • 1970-01-01
  • 2021-03-31
  • 2018-11-19
  • 2011-12-01
  • 1970-01-01
  • 2015-06-24
相关资源
最近更新 更多