杭电acm— 1159 Common Subsequence

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1159

题目如下:

Common Subsequence

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 48342    Accepted Submission(s): 22226

Problem Description

A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X = another sequence Z = is a subsequence of X if there exists a strictly increasing sequence of indices of X such that for all j = 1,2,...,k, xij = zj. For example, Z = is a subsequence of X = 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

Source

Southeastern Europe 2003

这是一道非常非常经典的动态规划问题,求不连续的最长公共子序列,堪比背包问题。

本人动态规划的水平也只能做做这样的题目了。有时候状态转移方程是真的难找。

朴素的dp,空间为二维,如果数据太大,会爆内存,但是这个题目要求不高

ac代码如下:

#include
#include
#include
using namespace std;

int dp[1005][1005];

int main(){
	string s1,s2;
	while(cin>>s1>>s2){
		int len1=s1.length();
		int len2=s2.length();
		int max_l=0;
		memset(dp,0,sizeof(dp));
		for(int i=1;i<=len1;i++){
			for(int j=1;j<=len2;j++){
				if(s1[i-1]==s2[j-1])  dp[i][j]=dp[i-1][j-1]+1;  //状态 +1 
				else  dp[i][j]=max(dp[i][j-1],dp[i-1][j]);     //状态转移 
			}
		}
		printf("%d\n",dp[len1][len2]);
	}
	return 0;
}

利用滚动数组的空间优化,参照了大佬们的思路,pre[]记录i-1的状态,dp[]现在状态。

#include
#include
#include
using namespace std;

int dp[1005],pre[1005];

int main(){
	string s1,s2;
	while(cin>>s1>>s2){
		int len1=s1.length();
		int len2=s2.length();
		memset(dp,0,sizeof(dp));
		memset(pre,0,sizeof(pre));
		for(int i=1;i<=len1;i++){
			for(int j=1;j<=len2;j++){
				if(s1[i-1]==s2[j-1])  dp[j]=pre[j-1]+1;
				else  dp[j]=max(dp[j-1],pre[j]);
				pre[j-1]=dp[j-1];  //pre记录i-1行,dp记录i行 
			}
			pre[len2]=dp[len2];
		}
		printf("%d\n",dp[len2]);
	}
	return 0;
}

 

你可能感兴趣的:(杭电acm)