【问题标题】:Terminated due timeout in hackerrank [closed]在hackerrank中因超时而终止[关闭]
【发布时间】:2018-03-26 21:19:04
【问题描述】:

我的代码是 C++ 并且目前正在努力完成任务。下面给出的链接

难度:中等

我的算法适用于 20 个测试用例中的 18 个。 其他 2 个因超时而终止。

我知道这意味着什么,但现在我不知道如何提高算法的效率。

我在下面给出了我的代码,任何人都可以帮我解决这个问题 https://www.hackerrank.com/challenges/and-product

    #include <cmath>
    #include <cstdio>
    #include <vector>
    #include <iostream>
    #include <algorithm>
    using namespace std;

    int main() 
    {
      int t;
      unsigned long int x,y,a;
      cin>>t;
      while(t)
       {       
           cin>>x>>y;
           a=x;
              for(;x<=y;x++)
                a=a&(x);

           cout<<a<<"\n";
           t--;
       }

     return 0;
    }

【问题讨论】:

标签: c++ algorithm timeout terminate


【解决方案1】:

“……每个人类问题都有一个众所周知的解决方案——简洁、合理和错误。” - H.L. 门肯

在计算机科学中,我们可以改写:

“对于每个计算问题,都有一个简单、优雅且错误的解决方案。”

诸如hackerrank、求职面试、游戏中的演员寻路、在3d 中绘制一队宇宙飞船以及任何涉及筛选数据的生产系统中的问题,从来都不是关于是否有解决方案的问题。

真正的问题总是这样:

“找到一种方法来降低这个看似微不足道的任务的复杂性。”

a 计数到b 同时将这些值组合在一起是线性时间算法 - O(b-a)。当 a 和 b 接近时,这很好。但是这个问题告诉你,他们最多可以有 2^32-1 的区间,也就是 40 亿次测试。

事实上,这个问题可以简化为 O(log2(b-a)),因为我们知道 b 大于 a。

查看以下二进制表示的最高位:

a 01001 (9)
b 11001 (25)

有一些常见的位,我们直观地认为这些位是答案中剩余 1 的候选者。

但是,b 有一个位是 1,其值比 a 的最高位大一个数量级。

为了从 a 计数到 b,低于最高位的每个位都必须存在于 1 和 0 的每个排列中 - 因为这就是二进制表示的工作方式。

如果我们通过每个排列对二进制位域进行置换,那么最终该域中的每个位都会在某个点包含一个 0。这意味着将位域的每个排列组合在一起的结果为零。

因此,当我们在 b 中找到不在 a 中的 1 位时,我们可以简单地从 a 中屏蔽掉所有较低幅度的位。

现在问题变成了:

找到b中不存在于a中的最高位,并屏蔽掉a中的所有低位。返回结果。

我们刚刚将搜索空间从 0

这是一个简单的解决方案——它甚至不需要优化位掩码的计算——它通过了所有关于hackerrank的测试。

#define TESTING 0

#include <iostream>
#include <string>
#if TESTING
  #include <sstream>
#endif
#include <cstdint>

using namespace std::literals;

#if TESTING

const char test_data[] =
R"__(
3
12 15
2 3
8 13
)__";
#endif

bool has_bit(const std::uint32_t x, int bitnum)
{
    return (x & (1 << bitnum)) != 0;
}

constexpr std::uint32_t mask_here_down(int bitnum)
{
    std::uint32_t result = 0;
    while (bitnum--)
    {
        result |= std::uint32_t(1) << bitnum;
    }
    return result;
}

void algo(std::istream& in, std::ostream& out)
{
    std::uint32_t a,b;
    in >> a >> b;

    for (int bit = 32 ; bit-- ; )
    {
        if (has_bit(b, bit) and not has_bit(a, bit))
        {
            std::cout << (a & ~mask_here_down(bit)) << std::endl;
            break;
        }
    }
}

void run_tests(std::istream& in, std::ostream& out)
{
    int n;
    in >> n;

    while (n--)
    {
        algo(in, out);
    }
}

int main()
{
    #if TESTING
    auto in = std::istringstream(test_data);
    #else
    auto& in = std::cin;
    #endif

    run_tests(in, std::cout);
}

【讨论】:

    猜你喜欢
    • 2018-03-03
    • 2018-10-22
    • 2016-09-10
    • 1970-01-01
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    相关资源
    最近更新 更多