DP之最长公共子序列 LCS
2016-02-07 16:41
423 查看
/*
DP之最长公共子序列 LCS
dp[0][j] (0<=j<=m)=0;
dp[i][0] (0<=i<=n)=0;
dp[i][j] = dp[i-1][j-1]+1;(s1[i] == s2[j])
dp[i][j] = max{dp[i-1][j],dp[i][j-1]} (s1[i] != s2[j])
题目1042:Coincidence
题目描述:
Find a longest common subsequence of two strings.
输入:
First and second line of each input case contain two strings of lowercase character a…z. There are no spaces before, inside or after the strings. Lengths of strings do not exceed 100.
输出:
For each case, output k – the length of a longest common subsequence in one line.
样例输入:
abcd
cxbydz
样例输出:
2
*/
#include <stdio.h>
#include <string.h>
int dp[101][101];
int max(int a, int b){return a>b ? a : b;}//取最大值函数
int main(){
int i,j;
char s1[101],s2[101];
while(scanf("%s%s",s1,s2) != EOF){//输入
int l1 = strlen(s1);
int l2 = strlen(s2);//依次求得两个字符串的长度
for(i=0;i<=l1;i++) dp[i][0] = 0;
for(j=0;j<=l2;j++) dp[0][j] = 0;//初始值
for(i=1;i<=l1;i++){
for(j=1;j<=l2;j++){//二重循环依次求得每个dp[i][j]值
if(s1[i-1] != s2[j-1])//因为字符串数组下标从0开始,所以第
//i个字符位置为s1[i-1],若当前两个字符不相等
dp[i][j] = max(dp[i][j-1],dp[i-1][j]);
//dp[i][j]为dp[i][j-1]和dp[i-1][j]中较大的一个
else dp[i][j] = dp[i-1][j-1]+1;
//若它们相等,则dp[i][j]比dp[i-1][j-1]再加1
}
}
printf("%d\n",dp[l1][l2]);
}
return 0;
}
DP之最长公共子序列 LCS
dp[0][j] (0<=j<=m)=0;
dp[i][0] (0<=i<=n)=0;
dp[i][j] = dp[i-1][j-1]+1;(s1[i] == s2[j])
dp[i][j] = max{dp[i-1][j],dp[i][j-1]} (s1[i] != s2[j])
题目1042:Coincidence
题目描述:
Find a longest common subsequence of two strings.
输入:
First and second line of each input case contain two strings of lowercase character a…z. There are no spaces before, inside or after the strings. Lengths of strings do not exceed 100.
输出:
For each case, output k – the length of a longest common subsequence in one line.
样例输入:
abcd
cxbydz
样例输出:
2
*/
#include <stdio.h>
#include <string.h>
int dp[101][101];
int max(int a, int b){return a>b ? a : b;}//取最大值函数
int main(){
int i,j;
char s1[101],s2[101];
while(scanf("%s%s",s1,s2) != EOF){//输入
int l1 = strlen(s1);
int l2 = strlen(s2);//依次求得两个字符串的长度
for(i=0;i<=l1;i++) dp[i][0] = 0;
for(j=0;j<=l2;j++) dp[0][j] = 0;//初始值
for(i=1;i<=l1;i++){
for(j=1;j<=l2;j++){//二重循环依次求得每个dp[i][j]值
if(s1[i-1] != s2[j-1])//因为字符串数组下标从0开始,所以第
//i个字符位置为s1[i-1],若当前两个字符不相等
dp[i][j] = max(dp[i][j-1],dp[i-1][j]);
//dp[i][j]为dp[i][j-1]和dp[i-1][j]中较大的一个
else dp[i][j] = dp[i-1][j-1]+1;
//若它们相等,则dp[i][j]比dp[i-1][j-1]再加1
}
}
printf("%d\n",dp[l1][l2]);
}
return 0;
}
相关文章推荐
- 流式计算-Jstorm提交Topology过程(上)
- Spark Core 问题详解
- 信号量
- Linux命令行学习之路(八)——压缩和解压缩
- 丙申年把真假美猴王囚禁在容器中跑 ASP.NET Core 1.0
- Java Fibonacci数列
- 浅谈C语言编程中程序的一些基本的编写优化技巧
- 【Cloud Foundry】Could Foundry学习(二)——核心组件分析
- 深入了解spark运行计划及调优
- fuse_operations与fuse_lowlevel_ops结构学习
- POJ 1789-Truck History
- 用户空间文件系统-fuse
- 文件的下载和断电续传
- HDU5621 KK's Point
- IoSetNextIrpStackLocation routine
- innodb_fast_shutdown的内幕
- 观察者模式——解耦的钥匙
- Failed to load native-hadoop本地库不一致的解决办法
- hrbust 1286/哈理工oj 1286 迷宫与宝藏【较难bfs】
- C++自制Redis数据库(三)设计开始敲定各模块架构-简单集群设计