Posted on 2008-03-28 10:26
王大头 阅读(262)
评论(0) 编辑 收藏 引用
acm.pku.edu.cn 1458
/******************************************************************************************/
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 6135 Accepted: 2290
Description
A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X = < x1, x2, ..., xm > another sequence Z = < z1, z2, ..., zk > is a subsequence of X if there exists a strictly increasing sequence < i1, i2, ..., ik > of indices of X such that for all j = 1,2,...,k, xij = zj. For example, Z = < a, b, f, c > is a subsequence of X = < a, b, c, f, b, c > with index sequence < 1, 2, 4, 6 >. Given two sequences X and Y the problem is to find the length of the maximum-length common subsequence of X and Y.
Input
The program input is from the std input. Each data set in the input contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct.
Output
For each set of data the program prints on the standard output the length of the maximum-length common subsequence from the beginning of a separate line.
Sample Input
abcfbc abfcab
programming contest
abcd mnp
Sample Output
4
2
0
如果只看Sample就会觉得超级简单,但事实是残酷的。
DP算法。
既然是DP,就得把最优结果存下来,避免重复计算,否则TLE。
此题串长度不大于256。考虑到最大子串长度不可能大于256,因此使用char
数组来存储最优结果。内存使用量降低大约了一半。
#include <stdio.h>
#include <string.h>

char X[256], Z[256], t[256][256];

int max_match(char *x, char *z)
{
int s = 0, m1 = 0, m2 = 0, c;
char *i;

if(*x == NULL || *z == NULL)
return 0;

if(t[x - X][z - Z])
return t[x - X][z - Z];

m1 = max_match(x + 1, z);

c = *x;

if((i = strchr(z, c)) != NULL) {
m2 = max_match(x + 1, i + 1) + 1;
}

if(m1 > m2)
s = m1;
else
s = m2;

t[x - X][z - Z] = s;

return s;
}

int main()
{
memset(X, 0, sizeof(X));
memset(Z, 0, sizeof(Z));
memset(t, 0, sizeof(t));

while(scanf("%s %s", &X, &Z) != EOF) {
X[strlen(X)] = '\0';
Z[strlen(Z)] = '\0';

printf("%d\n", max_match(X, Z));

memset(X, 0, sizeof(X));
memset(Z, 0, sizeof(Z));
memset(t, 0, sizeof(t));
}
}
