1. 程式人生 > >HDU——1159 Common Subsequence(DP 最長公共子序列)

HDU——1159 Common Subsequence(DP 最長公共子序列)

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

解題思路:

最長公共子序列問題,但是這題必須要進行空間優化,不然會超記憶體。

優化方法:因為本題不需要給出具體的公共子序列,只需要給出長度即可,所以不必記錄每一步,又因為下一個字元比較的結果,只與上一個字元比較的結果有關,所以可以將map[2][10005]陣列直接記錄最近的兩次比較結果即可。

程式碼:

//最長公共子序列
//只要前後順序相同即可 , 不需要連續

//要進行空間優化 , 不然會報Memory Limit Exceeded
//因為本題中沒有要求要給出具體的子序列,所有可以直接將 map[10005][10005] 改成 map[2][10005]; #include <cstdio> #include <string> #include <string.h> #include <iostream> using namespace std; int map[2][10005]; string str1 , str2; int max(int x , int y){ if(x > y) return x; return y; } int main(){ //freopen("D://testData//1159.txt" , "r" , stdin);
int len1 ,len2 , i , j ; while(cin >> str1 >>str2){ memset(map , 0 , sizeof(map)); len1 = str1.length(); len2 = str2.length(); for(i = 0 ; i <= len2 ; i ++){ for(j = 0 ; j <= len1 + 1 ; j ++){ if(i == 0 || j == 0){ map[i % 2][j] = 0; continue; } if(str2[i-1] == str1[j-1]) map[i % 2][j] = map[(i-1) % 2][j-1] + 1; else map[i % 2][j] = max(map[(i-1) % 2][j], map[i % 2][j-1]); } } printf("%d\n",map[len2 % 2][len1]); } return 0; }