SDAU dp专题 1002
来源:互联网 发布:新浪微博登陆网络异常 编辑:程序博客网 时间:2024/05/27 21:46
1:问题描述
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.
Sample Input
abcfbc abfcab
programming contest
abcd mnp
Sample Output
4
2
0
2:大致题意
求出字符串最长公共子序列。
3:思路
这里注意子序列与子串的区别。
通俗的来说,子序列是可以不连续的,而子串必须是连续的。
这个题直接套lcs模板即可。
dp数组是从1开始的,要注意下标的改变。
lcs:
先用s1的第一个字符去匹配s2这个字符串,如果相同的话就+1,然后再用s1的前2个字符去匹配,以此类推,可以写出一个行列式。
1、字符相同,则指向左上,并加1
2、字符不同,则指向左边或者上边较大的那个
最终dp【l1】【l2】就是最长的子序列~
4:感想
dp【i】【j】的意义是s1的前 i 个字符与 s2 的前 j 个字符的最长公共子序列。
豆豆这道题写的好详细~~
5:ac代码
#include<iostream>#include<string.h>#include<set>#include<stdio.h>#include<vector>#include<algorithm>#include<numeric>#include<math.h>#include<string.h>#include<sstream>#include<stdio.h>#include<string>#include<cstdlib>#include<algorithm>#include<iostream>#include<map>#include<queue>#include<iomanip>#include<cstdio>using namespace std;int dp[1005][1005];int main(){ //freopen("r.txt","r",stdin); string s1,s2; int n,m,i,j,k,l1,l2; while(cin>>s1>>s2) { memset(dp,0,sizeof(dp)); l1=s1.size(); l2=s2.size(); for(i=1;i<=l1;i++) { for(j=1;j<=l2;j++) { if(s1[i-1]==s2[j-1]) dp[i][j]=dp[i-1][j-1]+1; else dp[i][j]=max(dp[i-1][j],dp[i][j-1]); //cout<<dp[i][j]<<endl; } } cout<<dp[l1][l2]<<endl; } return 0;}
- SDAU dp专题 1002
- SDAU dp专题 1001
- SDAU dp专题 1003
- SDAU dp专题 1004
- SDAU dp专题 1005
- SDAU dp专题 1006
- SDAU dp专题 1007
- SDAU dp专题 1008
- SDAU dp专题 1009
- SDAU dp专题 1010
- SDAU dp专题 1011
- SDAU dp专题 1012
- SDAU dp专题 1013
- SDAU dp专题 1014
- 2016sdau课程练习专题二 1002
- 2016sdau课程练习专题三 1002
- 2016sdau课程练习专题四 1002
- SDAU 贪心专题 总结
- JavaScript学习之DOM编程
- Nginx和Tengine
- matlab2014a中help与参考页翻译 all
- POJ1523 SPF
- java项目转为web项目
- SDAU dp专题 1002
- 疯狂安卓书籍的学习--未完待续~
- [python]迭代器与生成器
- 如何用jsp+servlet+fliter实现非法字符过滤
- matlab2014a中help与参考页翻译 not
- Unsupported major.minor version 52.0
- Java学习笔记之反射
- Java泛型
- android 多点触摸绘画demo