poj 1458 最长公共子序列

迭代版:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int M=310;
typedef char ELEM;
ELEM X[M];
ELEM Y[M];
int c[M][M];
int LCS_LENGTH(int XLen,int YLen)
{//cout<<XLen<<" "<<YLen<<endl;
    for(int i=1;i<=XLen;i++) c[i][0]=0;
    for(int j=0;j<=YLen;j++) c[0][j]=0;
    for(int i=1;i<=XLen;i++)
        for(int j=1;j<=YLen;j++){//cout<<i<<" "<<X[i]<<" "<<j<<" "<<Y[j]<<endl;
            if(X[i]==Y[j]){ c[i][j]=c[i-1][j-1]+1;}
            else if(c[i-1][j]>=c[i][j-1]){ c[i][j]=c[i-1][j]; }
            else{ c[i][j]=c[i][j-1]; }}
    return c[XLen][YLen];
}
int main()
{
    //freopen("memoized lcs.txt","r",stdin);
    while(cin>>X+1>>Y+1){
        cout<<LCS_LENGTH(strlen(X+1),strlen(Y+1))<<endl;
//        for(int i=0;i<=strlen(X+1);i++){
//            for(int j=0;j<=strlen(Y+1);j++) cout<<c[i][j]<<" ";
//            cout<<endl;}
    }

    return 0;
}


带备忘递归版:

//要用负数(此处是-1)来表示未被计算的LCS长度,不能用0。因为LCS长度有可能为0。故遇到c[i][j]=0时,以为未被计算(会再次递归),其实很多时候已算,故TLE了
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int M=310;
typedef char ELEM;
ELEM X[M];
ELEM Y[M];
int c[M][M];
int MEMOIZED_LCS_LENGTH(int i,int j)
{
    if(i==0||j==0) return c[i][j]=0;
    if(c[i][j]>=0) return c[i][j];
    if(X[i]==Y[j]) return c[i][j]=MEMOIZED_LCS_LENGTH(i-1,j-1)+1;
    else return c[i][j]=max(MEMOIZED_LCS_LENGTH(i-1,j),MEMOIZED_LCS_LENGTH(i,j-1));
}
int main()
{
    //freopen("lcs.txt","r",stdin);
    while(scanf("%s%s",X+1,Y+1)==2){
        int XLen=strlen(X+1),YLen=strlen(Y+1);
        memset(c,-1,sizeof(c));
//        c=new int*[XLen+5];
//        for(int i=0;i<=XLen;i++) c[i]=new int[YLen+5]();
        printf("%d\n",MEMOIZED_LCS_LENGTH(XLen,YLen));
//        for(int i=0;i<=strlen(X+1);i++){
//            for(int j=0;j<=strlen(Y+1);j++) cout<<c[i][j]<<" ";
//            cout<<endl;}
//        for(int i=0;i<=XLen;i++) delete[] c[i];
//        delete[] c;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值