九度OJ 1042 Coincidence -- 动态规划(最长公共子序列)

题目地址:http://ac.jobdu.com/problem.php?pid=1042

 

题目描述:

Find a longest common subsequence of two strings.

输入:

First and second line of each input case contain two strings of lowercase character a…z. There are no spaces before, inside or after the strings. Lengths of strings do not exceed 100.

输出:

For each case, output k – the length of a longest common subsequence in one line.

样例输入:
abcd

cxbydz
样例输出:
2
#include <stdio.h>

#include <string.h>

 

#define MAX 101

 

int main(void){

    char first[MAX], second[MAX];

    int len1, len2;

    int i, j;

    int subseq[2][MAX];

 

    while (scanf ("%s%s", first, second) != EOF){

        len1 = strlen (first);

        len2 = strlen (second);

        for (i=0; i<=len2; ++i)

            subseq[0][i] = 0;

        subseq[1][0] = 0;

        for (i=1; i<=len1; ++i){

            for (j=1; j<=len2; ++j){

                if (first[i-1] == second[j-1])

                    subseq[i%2][j] = subseq[(i-1)%2][j-1] + 1;

                else{

                    subseq[i%2][j] = (subseq[(i-1)%2][j] > subseq[i%2][j-1]) ? subseq[(i-1)%2][j] : subseq[i%2][j-1];

                }

            }

        }

        printf ("%d\n", subseq[len1%2][len2]);

    }

     

    return 0;

}

 

 

HDOJ上相似的题目:http://acm.hdu.edu.cn/showproblem.php?pid=1243


参考资料:http://www.cnblogs.com/liyukuneed/archive/2013/05/22/3090597.html


 

你可能感兴趣的:(动态规划)