如何改进Codeforces解决方案?它显示超过了时间限制
How can I improve my Codeforces solution? It shows time limit exceeded
我在Codeforces Question(测试用例#28)上得到了一个超过时间限制的错误。
链接是http://codeforces.com/problemset/problem/525/B这个解决方案在谷歌上找不到。有人知道如何让这个解决方案更快一点吗。
我的代码是:
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <cstring>
using namespace std;
int main() {
char str[2000005];
scanf("%s", &str);
long long l = strlen(str);
long long k, i, j, days, pos, counter = 0;
scanf("%I64d", &days);
for (k = 1; k <= days; k++) {
f:
cin >> pos;
counter++;
i = pos - 1;
j = l - pos;
// swap(str[pos - 1], str[l - pos])
start:
swap(str[i], str[j]);
i++;
j--;
if (i <= j)
goto start;
else if (i > j && counter < days)
goto f;
else if(counter==days)
break;
}
printf("%s", str);
return 0;
}
我的解决方案:
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
int m, i, a[200002];
cin >> s >> m;
while (m--) {
cin >> i;
a[i]++;
}
int net = 0, n = s.length();
for (int i = 1; 2 * i <= n; i++) {
net += a[i];
if (net % 2) swap(s[i - 1], s[n - i]);
}
cout << s;
return 0;
}
建议:
- 如果指定了时间限制,请不要使用
goto
,使用for
或while
- 在代码中查找警告
long long
在这种情况下是不必要的- 正确格式化代码对调试有很大帮助
- 不要混合使用C I/O和C++I/O,请阅读此博客
编辑:不需要每次都反转字符串。我们需要计算字符串的每个位置将开始多少反转。阅读此博客条目了解更多信息。
相关文章:
- 使用 std::istream_iterator 时,它似乎跳过了空文件行 - 如果可能的话,如何避免这种情况?
- C++ For Loop在过程中被跳过了.如何解决?
- C++跳过了辛线
- 如何在我的代码中修复无穷循环?我认为它跳过了第二个CIN,因此它一直在循环
- QT Qtimeline跳过了第一个框架
- 输入后,我的程序似乎跳过了第一个IF语句,直接转到ELSE
- C RLE BMP压缩跳过了最后一个字节
- 提升单元测试似乎跳过了应执行的代码
- C 将数据读取到一个结构,但它跳过了我的一个获取线,使该元素空白
- 为什么我的程序跳过了一个步骤
- 当我采用测试用例数 = 1 时,我的程序终止.其他明智的是,它给出了正确的答案,但跳过了最后一个测试用例
- 为什么我的代码跳过了这个循环
- 请解释:在 for 循环之后跳过了行
- C++编译器似乎跳过了代码行
- 跳过了 int* 的琐碎分配
- 程序超过了时间限制,这似乎是不可能的——错误代码
- GLSL交错似乎在3DTV上甚至跳过了行
- std::basic_regex<char32_t>,有人已经尝试过了吗?
- Codeforces解决方案中超过了时间限制.如何改进我的解决方案
- 我用Turbo c++编写的c++程序过了一段时间就挂了