HDOJ-1159 Common Subsequence(动态规划,最长公共子列)

链接:HDOJ-1159

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


题目大意:求两个字符串的最长公共子序列的长度


求最长公共子列属于动态规划基础题型,是在看了这位→→点击这里←←的讲解后明白的,写的十分详细。


dp[i][j],i 表示字符串a前 i 个字符,j 表示字符串b前 j 个字符,那么可以得出状态转移方程:
d p [ i ] [ j ] = { d p [ i − 1 ] [ j − 1 ] + 1 , a [ i ] = b [ j ] m a x ( d p [ i − 1 ] [ j ] , d p [ i ] [ j − 1 ] ) , a [ i ] ≠ b [ j ] dp[i][j]=\begin{cases} dp[i-1][j-1]+1, &amp;a[i]=b[j]\\ max(dp[i-1][j],dp[i][j-1]), &amp;a[i] \neq b[j] \end{cases} dp[i][j]={dp[i1][j1]+1,max(dp[i1][j],dp[i][j1]),a[i]=b[j]a[i]̸=b[j]

其实用到了一些逆推的思维,从序列末尾往前推导,
当a、b字符串的最后一个字符相等,即a[i] == b[j],那么dp[i][j] = dp[i-1][j-1] + 1;
a[i]!=b[j],可以选择抛弃a最后一个或者b最后一个,因为公共子序列要最大长度,所以要在这两个情况择优。

此外,要考虑 i-1 或 j-1 越界的情况,可以在dp越界的地方围一圈0,或者处理时加特判。


以下代码:

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
	string a,b;
	while(cin>>a>>b)
	{
		int La=a.length(),Lb=b.length();
		int i,j;
		vector<vector<int> > dp(La,vector<int>(Lb));
		for(i=0;i<La;i++)
		{
			for(j=0;j<Lb;j++)   
			{                          //用三目运算符给 i==0 或 j==0 加个特判
				if(a[i]==b[j])
					dp[i][j]=(i==0||j==0)?1:dp[i-1][j-1]+1;
				else
					dp[i][j]=max(i==0?0:dp[i-1][j],j==0?0:dp[i][j-1]);
			}
		}
		cout<<dp[La-1][Lb-1]<<endl;
	}
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值