搜尋

首頁  >  問答  >  主體

c++ - 做USACO的sprime出現segmentation violation

/*
ID: hywhuan1
LANG: C++
TASK: sprime
*/
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <sstream>
using namespace std;
const int maxn = 100000000;
int p[100000008], in, out;
int check(int n)
{
    string ss, st;
    stringstream stream;
    stream << n;
    stream >> ss;
    int len = ss.length();
    for (int i = len; len >= 1; len--)
    {
        st = ss.substr(0, len);
        stringstream stream(st);
        int stnum;
        stream >> stnum;
        if (p[stnum] == 0)
            return 0;
    }
    return 1;
}
ofstream fout("sprime.out");
ifstream fin("sprime.in");
int main()
{
    memset(p, 0, sizeof(p));
    p[2] = 1;
    for (int i = 3; i <= maxn; i += 2)
    {
        p[i] = 1;
    }

    for (int i = 3; i <= maxn; i++)
        if (p[i] == 1)
            for (int j = i + i; j <= maxn; j += i)
            {
                p[j] = 0;
            }

    fin >> in;
    for (int i = pow(10, in - 1); i < pow(10, in); i++)
    {
        if (check(i) == 1)
            fout << i << endl;
    }
    return 0;
}

我感覺就是很簡單的先打表再判斷的想法 在Win 10運行沒問題 在USACO上卻

  > Run 1: Execution error: Your program (`sprime') exited with signal
        #11 (segmentation violation [maybe caused by accessing memory out
        of bounds, array indexing out of bounds, using a bad pointer
        (failed open(), failed malloc), or going over the maximum
        specified memory limit]). The program ran for 0.000 CPU seconds
        before the signal. It used 4180 KB of memory. 

實在搞不懂是什麼原因了

另附這題的中文翻譯:http://www.nocow.cn/index.php...

歡迎各路大神幫我這個弱雞解答

PHP中文网PHP中文网2689 天前3979

全部回覆(1)我來回復

  • 扔个三星炸死你

    扔个三星炸死你2017-07-06 10:37:02

    記憶體溢出了,你開的陣列太大了。

    估計 USACO 限制了記憶體大小

    回覆
    0
  • 取消回覆