2015-06-29 24 views
-2

我在Codeforces问题(测试用例#28)上得到了超出时间限制的错误。我该如何改进我的Codeforces解决方案?它显示超出时间限制

链接是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; 
} 

回答

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,读this blog

编辑:每次都不需要反转字符串。我们需要计算在每个字符串位置会开始多少次反转。请阅读blog entry了解更多信息。

+0

谢谢Shreevardhan。但它仍然显示你的代码上的TLE :( – Subhankar

+1

非常感谢:)它被接受:);) – Subhankar

相关问题