[英]Time Limit Exceeded in Codeforces solution. How can I improve my solution?
[英]How can I improve my Codeforces solution? It shows time limit exceeded
我在 Codeforces 問題(測試用例 #28)上遇到了超出時間限制的錯誤。
鏈接是http://codeforces.com/problemset/problem/525/B google上找不到解決方案。 有沒有人有任何關於使這個解決方案更快一點的想法。
我的代碼是:
#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
是不必要的編輯:不需要每次都反轉字符串。 我們需要計算在字符串的每個位置將開始多少次反轉。 閱讀此博客條目了解更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.