ACM 最大公共子序列
2015-08-14 19:12
239 查看
DescriptionA 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, x ij = 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.InputThe 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.OutputFor 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 mnpSample Output
4 2 0 [b]解题思路:[/b] [b]题目的大意是输入两个字符串以空格作为输入结束符,注意这个题目是以文件结束符作为结束,我们就可以很明确的看出这是一个求最大公共子序列的题目。所以我们可以利用求公共最大子序列的模版解出这一道题目。[/b] [b]程序代码: [/b]
#include <iostream> #include <cstdio> #include <cstring> using namespace std; int const N=1000; int save ; char str1 ,str2 ; int max(int x,int y) { return x>y?x:y; } int maxlen(char *str1,char *str2) { int n1=strlen(str1),n2=strlen(str2),i,j; for(i=0;i<=max(n1,n2);i++) save[i][0]=save[0][i]=0; for(i=1;i<=n1;i++) for(j=1;j<=n2;j++) //以下从str1[0]和str2[0]开始比较 save[i][j]=(str1[i-1]==str2[j-1] ? save[i-1][j-1]+1 : max(save[i-1][j],save[i][j-1])); return save[n1][n2]; } int main() { while(scanf("%s%s",str1,str2)!=EOF) { memset(save,0,sizeof(save)); cout<<maxlen(str1,str2)<<endl; } return 0; }
相关文章推荐
- 关于arguments.callee.caller.arguments[0]获得event的一些问题
- spark streaming updateStateByKey 用法
- 编写高质量代码改善C#程序的157个建议——建议24:迭代器应该是只读的
- hdoj 4746 莫比乌斯反演 + 优化
- uboot 入口解析
- Knockout.js on the way
- 常量折叠
- [VIM]可视模式下的几个命令
- UVa 1600-Patrol Robot题解
- Hibernate将sql查询结果中字符转为char类型的原因
- OC - Method(High)
- SDNU 1125 HDU 1004 Let the Balloon Rise【用map做水题】【map应用】 【8月14】
- Android自定义控件之乱涂
- C# odbc
- 大头小头 字节序
- 华为OJ(矩阵乘法)
- Quartz源码分析(二)
- Python学习笔记23:Django构建一个简单的博客网站(一个)
- 九度oj 1030
- hdu 1171 Big Event in HDU 多重背包问题