题目是这样的:求通过添加字将一个字符串变为回文字符串所需最少的添加次数。
解法:求出该字符串与反串的最大公共子序列的长度k,那么字符串的长度n减去k就是所求值。
为了不超出内存限制,使用了类似滚动数组的方法。
问题在这里,C程序和改写后的C++程序(只改写了头文件,添加了一句using namespace std;),而被判运行时差足有3s,有图为证:
可能与测试数据和OJ的评判系统有关,但我想肯定也和这两种语言某种方面的差异有关,在此请教路过的同学,谢谢!
附:
原题链接:1097 Palindrome
C代码
1 # include <stdio.h>
2 # include <string.h>
3
4 int N;
5 int c1[5006];
6 int c2[5006];
7
8 int main()
9 {
10 char s1[5005], s2[5005];
11 int i, j;
12
13 while (~scanf("%d%s", &N, s1))
14 {
15 for (i = 0; i < N; ++i)
16 s2[i] = s1[N-1-i];
17
18 for (j = 0; j < N; ++j)
19 {
20 for (i = 0; i < N; ++i)
21 if (s1[i] == s2[j]) c2[i+1] = c1[i] + 1;
22 else c2[i+1] = c1[i+1]>c2[i] ? c1[i+1]:c2[i];
23 memcpy(c1, c2, (N+1)*sizeof(int));
24 }
25 printf("%d\n", N-c1[N]);
26 memset(c1, 0, sizeof(c1));
27 }
28
29 return 0;
30 }
C++代码
1 # include <cstdio>
2 # include <cstring>
3
4 using namespace std;
5
6 int N;
7 int c1[5006];
8 int c2[5006];
9
10 int main()
11 {
12 char s1[5005], s2[5005];
13 int i, j;
14
15 while (~scanf("%d%s", &N, s1))
16 {
17 for (i = 0; i < N; ++i)
18 s2[i] = s1[N-1-i];
19
20 for (j = 0; j < N; ++j)
21 {
22 for (i = 0; i < N; ++i)
23 if (s1[i] == s2[j]) c2[i+1] = c1[i] + 1;
24 else c2[i+1] = c1[i+1]>c2[i] ? c1[i+1]:c2[i];
25 memcpy(c1, c2, (N+1)*sizeof(int));
26 }
27 printf("%d\n", N-c1[N]);
28 memset(c1, 0, sizeof(c1));
29 }
30
31 return 0;
32 }