码迷,mamicode.com
首页 > 其他好文 > 详细

Coincidence(LCS) 最长公共子序列问题

时间:2015-01-13 19:37:52      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:

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


------------------------------------------------------------------------------------------------------------------------------------------
思想:
dp[ i ][ j ] 代表s1s2...si和t1t2...tj对应的LCS的长度。

状态转移方程:
dp[ i+1 ][ j+1 ]=dp[ i ][ j ]+1 此时Si+1==Sj+1
dp[ i+1 ][ j+1 ]=max(dp[ i+1 ][ j ],dp[ i ][ j+1 ]) 此时Si+1!=Sj+1


Source Code:
#include <iostream>
#include <string>
 
using namespace std;
 
int maxVal(int a,int b){
    return a>b?a:b;
}
 
int main()
{
    string str_A,str_B;
    int dp[110][110];
    while(cin>>str_A>>str_B){
        unsigned int len_A=str_A.size();
        unsigned int len_B=str_B.size();
        for(unsigned int i=0;i<=len_A;++i)
            for(unsigned int j=0;j<=len_B;++j)
                dp[i][j]=0;
        for(unsigned int i=0;i<len_A;++i){
            for(unsigned int j=0;j<len_B;++j){
                if(str_A[i]==str_B[j])
                    dp[i+1][j+1]=dp[i][j]+1;
                else
                    dp[i+1][j+1]=maxVal(dp[i+1][j],dp[i][j+1]);
            }
        }
        cout<<dp[len_A][len_B]<<endl;
    }
    return 0;
}

 

 

Coincidence(LCS) 最长公共子序列问题

标签:

原文地址:http://www.cnblogs.com/Murcielago/p/4222237.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!