1042.coincidence(动态规划求最长公共子序列)

题目描述:

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<iostream>
#include<cstring>
#include<algorithm>
using namespace std;

int main(){
    char a[101],b[101];
    int d[101][101];
    while(gets(a)&&gets(b)){
        int len1=strlen(a);
        int len2=strlen(b);
        for(int i=0;i<=len1;i++) d[i][0]=0;
        for(int i=0;i<=len2;i++) d[0][i]=0;
        for(int i=1;i<=len1;i++){
            for(int j=1;j<=len2;j++)
            {
                if(a[i-1]==b[j-1]) d[i][j]=d[i-1][j-1]+1;
                else d[i][j]=max(d[i-1][j],d[i][j-1]);
            }
        }
        cout<<d[len1][len2]<<endl;
    }
    return 0;
}

原文地址:https://www.cnblogs.com/bernieloveslife/p/9736524.html