如何在这样的代码中避免使用TLE?

时间:2017-08-24 09:08:59

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

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

问题在这里: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;

}

1 个答案:

答案 0 :(得分:1)

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

+

Demo

所以

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];
}