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;
}

猜你喜欢

转载自blog.csdn.net/sinat_38052999/article/details/80215391