博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C - Common Subsequence
阅读量:4334 次
发布时间:2019-06-07

本文共 2317 字,大约阅读时间需要 7 分钟。

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. 

Input

abcfbc abfcabprogramming contest abcd mnp

Output

420

Sample Input

abcfbc abfcabprogramming contest abcd mnp

Sample Output

42 0 题意:给你两组或多组子序列,现在让你求出他们的最大公共子序列的长度 分析:做这个提前我事先看了书知道这是个最大公共子序列问题,然后就根据书上给出的转移方程很顺利的就将此题AC了,解决本题的关键就是你要得到那个转移方程。
知识点:最大公共子序列问题。 心得:开数组的时候不能大意啊,一定要按题目给定的范围来定义 AC代码: 解法一:
#include 
#include
#include
using namespace std; int d[1005][1005]; char a[1005],b[1005]; int max(int x,int y) { return x>y?x:y; } int main() { while(scanf("%s %s",a,b)!=EOF) { memset(d,0,sizeof(d)); int m=strlen(a);//数组长度 int n=strlen(b); for(int i=1;i<=m;i++) for(int j=1;j<=n;j++) { if(a[i-1]==b[j-1]) d[i][j]=d[i-1][j-1]+1; else d[i][j]=max(d[i-1][j],d[i][j-1]);//最长公共子序列转移方程 } printf("%d\n",d[m][n]); } return 0; }
解法二:
#include
/*编译有问题,运行错误,提交用C++一直时格式错误,用G++一下就过了,好坑啊*/#include
//#include
using namespace std; const int MAX=500;//数组开大会导致运行错误,没弄懂。就是主函数内的数组不能开太大,所以一般定义数组最好定义在主函数外面 int main() { string a,b; int d[MAX][MAX]; while(cin>>a>>b) { int m=a.length();//数组长度 int n=b.length(); //memset(d,0,sizeof(d)); for(int i=1; i<=m; i++) for(int j=1; j<=n; j++) { if(a[i-1]==b[j-1]) d[i][j]=d[i-1][j-1]+1; else if(d[i-1][j]>d[i][j-1]) d[i][j]=d[i-1][j]; else d[i][j]=d[i][j-1]; } cout<
<
 

转载于:https://www.cnblogs.com/lbyj/p/5758066.html

你可能感兴趣的文章
XXL-Job分布式任务调度
查看>>
ASP隐藏文件地址,并在下载时替换文件名
查看>>
Windows下MongoDB的安装与设置MongoDB服务
查看>>
Microsoft.Jet.OLEDB.4.0”提供程序不支持 ITransactionLocal 接口。本地事务不可用于当前提供程序...
查看>>
oc 代码块的使用
查看>>
转:Eclipse中打开文件所在文件夹的插件及设置
查看>>
Django 之Form
查看>>
cocos2dx中的用户数据的管理
查看>>
微信公众平台开发教程(九)微信公众平台通用开发框架
查看>>
wsdl 结构解析
查看>>
IIS 支持 ajax 跨域
查看>>
python的切片
查看>>
JavaScript Date 对象
查看>>
Java 反射机制分析指南
查看>>
自动化测试前序(https://blog.csdn.net/ling_mochen/article/details/79314118)
查看>>
Javascript面向对象编程(三):非构造函数的继承
查看>>
UVA10010 Where's Waldorf?
查看>>
前端开发的开始---基于OO的Ajax类
查看>>
[4.9福建四校联考]
查看>>
JavaScript设计模式学习——builder pattern(建造者模式)
查看>>