《算法笔记》11.8小节——动态规划专题->总结 问题 D: Coincidence

发布于:2025-05-23 ⋅ 阅读:(14) ⋅ 点赞:(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.

样例输入
google
goodbye
样例输出
4

分析:求两个字符串的最长公共子序列。注意是多组输入。

#include<algorithm>
#include <iostream>
#include  <cstdlib>
#include  <cstring>
#include   <string>
#include   <vector>
#include   <cstdio>
#include    <queue>
#include    <stack>
#include    <ctime>
#include    <cmath>
#include      <map>
#include      <set>
#define INF 0x3fffffff
#define db1(x) cout<<#x<<"="<<(x)<<endl
#define db2(x,y) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<endl
#define db3(x,y,z) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<", "<<#z<<"="<<(z)<<endl
#define db4(x,y,z,r) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<", "<<#z<<"="<<(z)<<", "<<#r<<"="<<(r)<<endl
#define db5(x,y,z,r,w) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<", "<<#z<<"="<<(z)<<", "<<#r<<"="<<(r)<<", "<<#w<<"="<<(w)<<endl
using namespace std;

int main(void)
{
    #ifdef test
    freopen("in.txt","r",stdin);
//    freopen("out.txt","w",stdout);
    clock_t start=clock();
    #endif //test

    char s1[110],s2[110];
    while(~scanf("%s%s",s1,s2))
    {
        int dp[110][110];
        for(int i=0;i<=100;++i)
            for(int j=0;j<=100;++j)
                dp[i][j]=0;
        int l1=strlen(s1),l2=strlen(s2);
        for(int i=0;i<l1;++i)
        {
            for(int j=0;j<l2;++j)
            {
                if(s1[i]==s2[j])dp[i+1][j+1]=dp[i][j]+1;
                else dp[i+1][j+1]=max(dp[i][j+1],dp[i+1][j]);
            }
        }
        printf("%d\n",dp[l1][l2]);
    }

    #ifdef test
    clockid_t end=clock();
    double endtime=(double)(end-start)/CLOCKS_PER_SEC;
    printf("\n\n\n\n\n");
    cout<<"Total time:"<<endtime<<"s"<<endl;        //s为单位
    cout<<"Total time:"<<endtime*1000<<"ms"<<endl;    //ms为单位
    #endif //test
    return 0;
}


网站公告

今日签到

点亮在社区的每一天
去签到