题目链接:acm.hdu.edu.cn/showproblem.php?pid=1159
Common Subsequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 17402 Accepted Submission(s): 7299
Problem 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.
The program input is from a text file. Each data set in the file contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct. 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.
The program input is from a text file. Each data set in the file contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct. 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
Source
这个其实就是求最长公共子序列的问题,相信大家都懂的。开始用基本的二维数组做了,AC是没有压力,后来看了讨论区一个大牛的思路,觉得可以借鉴一下。
重点是这个题目没有给定字符串的长度,如果题目限定空间较少的话,开二维数组就有可能超出空间限制。所以就可以用滚动数组来解决这个问题。
在依次搜索的时候,任一点得值只于它前一个位置,和上一个位置有关。即可以就把二维数组的行数开为2,就可以保证程序的运行了。在实现的时候分为偶数行和奇数行就行啦!!!
AC代码:
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
char q[1008],w[1008];
int dp[2][1008];
int main(){
int len1,len2,i,j;
while(~scanf("%s%s",&q,&w)){
len1=strlen(q);
len2=strlen(w);
memset(dp,0,sizeof(dp));
for(i=1;i<=len1;i++){
for(j=1;j<=len2;j++){
if(q[i-1]==w[j-1]) dp[i%2][j]=dp[(i-1)%2][j-1]+1;
else dp[i%2][j]=max(dp[i%2][j-1],dp[(i-1)%2][j]);
}
}
printf("%d\n",dp[len1%2][len2]);
}
return 0;
}
路途中。。。。。

被折叠的 条评论
为什么被折叠?



