POJ1458 HDU1159 ZOJ1733 UVALive2759 Common Subsequence【最长公共子序列+DP】

Common Subsequence
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 63742 Accepted: 26604
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.
Input
The program input is from the std input. Each data set in the input contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct.
Output
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

问题链接POJ1458 HDU1159 ZOJ1733 UVALive2759 Common Subsequence
问题描述:(略)
问题分析
    动态规划问题,是一个标准模板题,套模板就可以了。
    需要注意字符串长度!
程序说明:(略)
参考链接:(略)
题记:(略)

AC的C语言程序如下:

/* POJ1458 HDU1159 ZOJ1733 UVALive2759 Common Subsequence */

#include <stdio.h>
#include <string.h>

#define MAX(x,y) (((x) > (y)) ? (x) : (y))

#define N 1000
char a[N + 2], b[N + 2];
int dp[N + 1][N + 1];

int main(void)
{
    int i, j;

    while(~scanf("%s%s", a + 1, b + 1)) {
        memset(dp, 0, sizeof(dp));

        int len1 = strlen(a + 1);
        int len2 = strlen(b + 1);
        for(i = 1; i <= len1; i++)
            for(j = 1; j <= len2; j++) {
                if(a[i] == b[j])
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                else
                    dp[i][j] = MAX(dp[i - 1][j], dp[i][j - 1]);
            }

        printf("%d\n", dp[len1][len2]);
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/tigerisland45/article/details/84643018