HDUOJ 1159
来源:互联网 发布:ubuntu mongodb安装 编辑:程序博客网 时间:2024/06/03 20:38
原题:
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…….Sample Input
abcfbc abfcab
programming contest
abcd mnpSample Output
4
2
0
解题思路:
- 可以把c[ i ][ j ]理解成:取X的前i个字符和取Y的前j个字符,能得到的LCS值
- 分为一下两类:
- 如果X的第i个字符X[ i ] 等于 Y的第j个字符Y[ j ]
- 如果X的第i个字符X[ i ] 不等于 Y的第j个字符Y[ j ]
引进一个二维数组c[ ][ ],用c[ i ][ j ]记录X[ i ]与Y[ j ] 的LCS 的长度。
我们是自底向上从小到大进行递推计算,所以就能在在计算c[ i ][ j ]之前,把c[ i-1 ][ j-1 ],c[ i-1 ][ j ]与c[ i ][ j-1 ]计算出来,此时我们根据X[ i ] = Y[ j ]还是X[ i ] != Y[ j ],就可以计算出c[ i ][ j ]。
代码:
#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;int dp[1000][1000];char a[1000], b[1000];int main(){ int a_length, b_length, maxLength, i, j; while (scanf("%s%s",a + 1,b + 1)!=EOF)//0位不存 { a[0] = b[0] = '*';//无用--只是方便下面数组循环无需减一加一操作 a_length = strlen(a); b_length = strlen(b); maxLength = max(a_length, b_length); for (i = 0; i <= maxLength; i++) dp[i][0] = dp[0][i] = 0;//初始化 for (i = 1; i < a_length; i++)//动态规划 for (j = 1; j < b_length; j++) if (a[i] == b[j])dp[i][j] = dp[i - 1][j - 1] + 1; else dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); printf("%d\n", dp[i - 1][j - 1]); }}
- HDUOJ 1159
- HDUOJ
- HDUoj
- HDUOJ 2050
- HDUOJ 2018
- HDUOJ 2069
- HDUOJ 1303
- HDUOJ 2031
- HDUOJ 2047
- HDUOJ 2089
- hduoj 1708
- hduoj 2031
- hduoj 2032
- hduoj 1062
- HDUOJ 1039
- HDUOJ lines
- HDUOJ入门
- HDUOJ 水果
- JSP内容之Tomcat
- Android 状态栏样式 全面解析
- 【Tensorflow slim】slim.data包
- Transacion事务
- 五天面试
- HDUOJ 1159
- CBK与龙凤集团开展深度合作洽谈
- Swarm+docker集群搭建
- Swift基础 枚举
- 目前可行的markdown转pdf方案
- 特征选择
- 初学者:Android Studio开发环境配置
- 公共ajax请求方法
- ubuntu压缩与解压缩、字符串比较常用指令