UVa 10066 The Twin Towers

一看就知道是lcs,10分钟敲好了代码,通过示例,一提交MLE,明白了没有保存中间结果;

再次提交,打开邮箱,一直F5,等了很长时间没反应,难道又MLE了?结果回到题目页面,发现了下面这句话:

You have to select a programming language.

。。。

再次提交WA:没有把ans[]初始化为-1;

最终花了25分钟才AC了,教训啊!

 1 # include <stdio.h>
2 # include <memory.h>
3
4 int N1, N2;
5 int x[2];
6 int s1[101];
7 int s2[101];
8 int ans[101*101];
9
10 int lcs(int *x);
11
12 int main()
13 {
14 int cnt, i;
15
16 cnt = 0;
17 while (1)
18 {
19 scanf("%d", &N1); scanf("%d", &N2);
20 if (!N1 && !N2) break;
21 for (i = 0; i < N1; ++i) scanf("%d", &s1[i]);
22 for (i = 0; i < N2; ++i) scanf("%d", &s2[i]);
23
24 x[0] = N1; x[1] = N2;
25 memset(ans, 0xff, sizeof(ans));
26
27 printf("Twin Towers #%d\n", ++cnt);
28 printf("Number of Tiles : %d\n\n", lcs(x));
29 }
30
31 return 0;
32 }
33
34 int lcs(int *x)
35 {
36 int index, ret, rem;
37
38 if (!x[0] || !x[1]) return 0;
39 index = x[0]-1 + (x[1]-1)*N1;
40 if (ans[index] >= 0) return ans[index];
41 if (s1[x[0]-1] == s2[x[1]-1])
42 {
43 --x[0]; --x[1];
44 ret = lcs(x) + 1;
45 ++x[0]; ++x[1];
46 }
47 else
48 {
49 ret = 0;
50 --x[0]; if ((rem = lcs(x)) > ret) ret = rem; ++x[0];
51 --x[1]; if ((rem = lcs(x)) > ret) ret = rem; ++x[1];
52 }
53 ans[index] = ret;
54
55 return ret;
56 }



原文地址:https://www.cnblogs.com/JMDWQ/p/2429673.html