最长公共子序列及其序列打印【HDU 1159】

Common Subsequence

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

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


当这个点的字母相等是 即s1[i] == s2[j] 时 dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) 选取左边,或者上边的点做的“贡献”,然后再判断他的上段字符串 即1-(i - 1) 和1 - (j - 1)的字符串的最大值加上这个点, 即是加一,左边或者右边做的“贡献的最大值”还大,从中选取最大值,如果不相等,就直接选取“贡献”

dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
if(x[i - 1] == y[ j - 1]) 
dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + 1); 

路径打印是从后往前查找增加的量是从哪里来的,如果某个点大于“贡献”,那么这个点就是子序列的一个字符,那么久前插,
如果不大于,那么就按照大的那个边进行往前推

int n = len1;
		int m = len2;
		string s; 
		while(m > 0 && n > 0){
			if(dp[n][m] > max(dp[n][m - 1], dp[n - 1][m])){
			 s.insert(0, 1, x[n - 1]);
			
			 m--;
			 n--;
			}else if(dp[n - 1][m] > dp[n][m - 1]) n--;//上移
			else  m--;//左移
		
		}

完整代码:
注意:HDU不需要打印子序列

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int dp[1010][1010];

int main(){
	string x, y;
	while(cin >> x >> y){
		memset(dp, 0, sizeof(dp));
		int len1 = x.size();
		int len2 = y.size();
		for(int i = 1; i <= len1; i++){
			for(int j = 1; j <= len2; j++){
				dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
				if(x[i - 1] == y[ j - 1]) dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + 1); 
			}
		}
		int n = len1;
		int m = len2;
		string s; 
		while(m > 0 && n > 0){
			if(dp[n][m] > max(dp[n][m - 1], dp[n - 1][m])){
			 s.insert(0, 1, x[n - 1]);
			
			 m--;
			 n--;
			}else if(dp[n - 1][m] > dp[n][m - 1]) n--;
			else  m--;
		
		}
		cout << s << endl;
		cout << dp[len1][len2] << endl;
	}
	return 0;
} 
发布了28 篇原创文章 · 获赞 22 · 访问量 1026

猜你喜欢

转载自blog.csdn.net/qq_45432665/article/details/103331050