【问题标题】:How do I avoid TLE in codes like this?如何在这样的代码中避免 TLE?
【发布时间】:2017-08-24 09:08:59
【问题描述】:

我的大部分代码都面临类似的问题。我该如何解决?

这里的问题:http://usaco.org/index.php?page=viewproblem2&cpid=692

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
string rotate_s(string s){
  int m= s.size();
  string s2;
  for(int i=0; i<m; i++){
    s2[i] = s[(i+m-1)%m];
  }
  return s+s2;

 }
int main()
{
string s;
int n;
cin>>s>>n;
int k = s.size();
while(k<n){
    s = rotate_s(s);
    k = s.size();
}
cout<<s[n-1]<<endl;
return 0;

}

【问题讨论】:

  • 您显示的代码有undefined behavior。当你定义一个std::string 对象(例如s2 在你的rotate_s 函数中)时,它以empty 开始。这意味着对该字符串对象的任何索引都将超出范围。如果您有 UB(未定义行为),那么您的整个程序是格式错误且无效的,任何关于其行为或问题的猜测都将变得毫无意义。
  • 除了修复上面提到的UB,我建议重新考虑你的算法。 rotate_s 函数非常昂贵(时间和内存),所以我建议考虑如何减少它的调用次数。
  • “N 可能太大,无法放入标准的 32 位整数”。这让您真的认为您不必构建结果字符串,而只需从原始字符串中“计算”要使用的索引。
  • 什么是“TLE”?
  • @Ian: Too Long E执行。

标签: c++ debugging c++14 time-limiting


【解决方案1】:

您不必构建字符串,只需逐步修复索引即可:

char foo(const std::string& s, std::size_t index)
{
    auto size = s.size();

    // What would be the size of the (smaller) string containing index
    while (size <= index) {
        size *= 2;
    }
    while (size != s.size()) {
        size /= 2;
        if (index >= size) { // index is on the second part
            index = (index - 1) % size; // negate the rotate
        }
    }
    return s[index];
}

Demo

所以

0 1 2   3 4 5 | 6 7 8 9 10 11
0 1 2   3 4 5 | 5 0 1 2  3  4
0 1 2 | 3 4 5
0 1 2 | 2 0 1
0 1 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多