使用swap和substr函数的奇怪结果

时间:2014-07-30 00:31:47

标签: c++ swap substr

我试图在TopCoder解决问题。我在TopCoder的测试部分得到了奇怪的结果;但是,当我提交我的代码时,我得到了AC(代表接受)。 TCHS SRM 47一级的情况相同--250 pt - Cards Shuffle。我使用了swap函数,我的code

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
using namespace std;

int main() {
    int f, l, t;
    string c;
    cin>>c;
    scanf("%d%d%d", &f, &l, &t);
    //while(t--) c=c.substr(f-1, l-f+1)+c.substr(0, f-1)+c.substr(l);
    while(t--) for(int i=0, j=f-1; j<=l-1; i++, j++) swap(c[i], c[j]);
    cout<<c;
    return 0;
}

在TC(代表TopCoder)的测试部分返回WA(代表错误答案),在TC上提交AC。然后我分别使用ideone和交换函数检查substr上的代码。首先尝试substr函数给出预期结果,而swap函数意外结果。然而,在第二次尝试时反之亦然。我不知道发生了什么,我的代码是否有bug,或者是ideone,还是TopCoder测试系统。

1 个答案:

答案 0 :(得分:1)

您的算法

使用swap的算法有问题。让我们逐步完成while循环的一次迭代。你有:

for ( int i = 0; j = f-1; j <= l-1; ++i, ++i )
   swap(c[i], c[j]);

我不知道您使用flt的原因。如果您使用firstlasttimes,这将更容易阅读。

for ( int i = 0; j = first-1; j <= last-1; ++i, ++i )
   swap(c[i], c[j]);

让我们使用以下输入:

ABCDEFGHIJ
5 6 1

for循环的第一次迭代中,

i = 0;
j = 4;
交换后

c的新值为

EBCDAFGHIJ (A and E are swapped)

for循环的第二次迭代中,

i = 1;
j = 5;
交换后

c的新值为

EFCDABGHIJ (B and F are swapped)

迭代在此处停止,因为j的值变为6

您最终需要的是:

EFABCDGHIJ

不同的算法

如果要最小化创建的字符串数量,可以使用以下策略。

对于给定的输入,创建子串&#34; EF&#34;并存储它。然后移动&#34; ABCDE&#34;两个人右边。然后移动&#34; EF&#34;到字符串的开头。以下功能可以做到这一点。它会更改c

void fun(string& c, int first, int last)
{
   // Convert first to a 0-based index for easier manipulation.
   --first;

   int delta = last-first;
   string c1 = c.substr(first, delta);
   for ( int i = first-1; i >= 0; --i )
   {
      c[i+delta] = c[i];
   }

   for ( int i = 0; i < delta; ++i )
   {
      c[i] = c1[i];
   }
}