如何改进Codeforces解决方案?它显示超过了时间限制

How can I improve my Codeforces solution? It shows time limit exceeded

本文关键字:过了 时间 显示 何改进 Codeforces 解决方案      更新时间:2023-10-16

我在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;
}

建议:

  1. 如果指定了时间限制,请不要使用goto,使用forwhile
  2. 在代码中查找警告
  3. long long在这种情况下是不必要的
  4. 正确格式化代码对调试有很大帮助
  5. 不要混合使用C I/O和C++I/O,请阅读此博客

编辑:不需要每次都反转字符串。我们需要计算字符串的每个位置将开始多少反转。阅读此博客条目了解更多信息。