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;}
0 0
原创粉丝点击