簡體   English   中英

如何改進我的 Codeforces 解決方案? 顯示超出時間限制

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

建議:

  1. 如果指定了時間限制,請不要使用goto ,使用forwhile
  2. 在代碼中查找警告
  3. 在這種情況下long long是不必要的
  4. 正確格式化代碼對調試有很大幫助
  5. 不要混合 CI/O 和 C++ I/O,閱讀此博客

編輯:不需要每次都反轉字符串。 我們需要計算在字符串的每個位置將開始多少次反轉。 閱讀此博客條目了解更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM