如何在这样的代码中避免 TLE?
How do I avoid TLE in codes like this?
我的大多数代码都面临类似的问题。我该如何解决它?
这里的问题: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;
}
您不必构建字符串,只需逐步修复索引:
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];
}
演示
所以
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
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 编译包含字符串的代码时遇到问题
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 在Linux for Windows上编译C++代码时出错
- 我的字符计数代码计算错误.为什么
- 孤立代码块在结构中引发异常
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 此代码是否违反一个定义规则
- 为什么我的代码在输出中增加了93天
- 简化代码以避免在顺时针旋转2D矩阵时出现TLE
- 如何在这样的代码中避免 TLE?
- DFS在kefa和park中给予TLE(代码560C)
- 我的代码在在线评判上获得了 TLE(超出时间限制),即使我已经根据社论进行了编码
- TLE用于大输入.如何在时间限制内运行我的代码