【问题标题】:Terminated due to timeout in Hackerrank (using malloc in cpp)由于 Hackerrank 中的超时而终止(在 cpp 中使用 malloc)
【发布时间】:2020-04-27 21:38:32
【问题描述】:

所以我是一个相当新的程序员,我刚刚开始在 Hackerrank 上做问题。我尝试了一个问题,它可以在离线 ide 上编译和工作。但是在hackerrank上显示错误。及时的回答对我很有帮助。

这是素数螺旋的虚拟表示(用于理解目的)

现在的问题 质数以螺旋形式书写,从原点 (0, 0) 开始,如上图所示移动。右列和底行显示的数字分别是列号和行号(即y和x坐标)

目标是找到给定素数的位置(x 和 y 坐标)。

错误 当我在hackerrank中运行代码时,3个测试用例中有2个有效。但是对于一个测试用例,它显示错误因超时而终止。 我写的代码如下:

    #include<iostream>
using namespace std;
int prime(int a)
{
    int count, h=0;
    for (int i = 2; i <= 12000000; i++)
    {
        count = 0;
        for (int j = 2; j <= i; j++)
        {
            if(i%j==0)
            {
                count++;
            }
        }
        if (count == 1)
        {
            h = h + 1;
        }
        if (a == i)
        {
            break;
        }
    }
    return h;

}
void spiral(int h)
{
    int stepnum=1, totalsteps = 2;
    int x_coordinate = 0, y_coordinate = 0;
    int operatn = 1;
    for(int i=2;i<=h;i++)
    {
        if (stepnum <= (totalsteps/2))
        {
            x_coordinate = x_coordinate + operatn;
        }
        else
        {
            if (stepnum <= totalsteps)
            {
                y_coordinate = y_coordinate + operatn;
            }
        }
        if (stepnum == totalsteps)
        {
            stepnum = 0;

            operatn = -1 * operatn;

            totalsteps = totalsteps + 2;


        }
        stepnum++;

        }

    cout << "x coordinate = "<<x_coordinate<< " y coordinate = "<<y_coordinate<<endl;

}

int main()
{
    int t;
    int* p;
    cout<<"Enter the number of cases :"<< endl;
    cin >> t;
    int test;
    p=(int*)malloc(t*4);
    for (int i = 0; i < t; i++)
    {
        cin >> *(p+i);
    }
    for (int i = 0; i < t; i++)
    {
        test = prime(*(p + i));
        spiral(test);

    }
}

【问题讨论】:

  • p=(int*)malloc(t*4); 使用 sizeof(int) 因为不能保证 int 总是 4 个字节。不过,真的,请使用newvector。使用测试用例的限制作为指导来测试和分析您的代码。寻找最坏的情况,并确保您在时间限制之内。对于这样的问题,您通常希望找到一种方法来缓存尽可能多的数据,这样您就不会每次都计算它。
  • 素数测试可以加快速度。无需将测试用例保存在数组中(我初学者时也习惯);获取输入,进行计算并将其输出到新行。测试人员将检查您的整个输出文件是否与他们的匹配。我看到函数prime 正在计算素数a 的“等级”,它也可以通过计算所有素数的等级来加速(直到问题陈述中必须给出的最大值),然后再计算输入然后查找排名将只查找预先计算的数组。函数spiral也可以做类似的事情。

标签: c++ performance memory-efficient


【解决方案1】:

你的问题是这个循环:

for (int i = 2; i <= 12000000; i++)
...
    for (int j = 2; j <= i; j++)
    ...

您最终将执行 n^2 次内部循环的迭代,其中 n=12000000,因此您的内部循环有 144*10^12 次迭代。

让我们假设每次迭代需要 1 纳秒(实际上会更长),因此完成对 prime 的调用需要 144*10^12 / 10^9 = 144000 秒,或约 1.7 天,除非你在if (a == i) 上休息。

因此,如果您的测试用例碰巧以较大的a 调用prime,则可能会超出分配的时间预算。

【讨论】:

    猜你喜欢
    • 2018-10-22
    • 2018-03-26
    • 1970-01-01
    • 2015-06-17
    • 1970-01-01
    • 1970-01-01
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多