登录

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...

欢迎各路大神帮我这个弱鸡解答

# C++
PHP中文网 PHP中文网 2458 天前 1715 次浏览

全部回复(1) 我要回复

  • 扔个三星炸死你

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

    内存溢出了,你开的数组太大了。

    估计 USACO 限制了内存大小

    回复
    0
  • 取消 回复 发送