• 动态规划最长公共子序列


    最长公共子序列

    时限:1000ms 内存限制:200000K  总时限:3000ms

    描述:

    一个给定序列的子序列是在该序列中删去若干元素后得到的序列。确切地说,若给定序列X=<x1, x2,…, xm>,则另一序列Z=<z1, z2,…, zk>是X的子序列是指存在一个严格递增的下标序列 <i1, i2,…, ik>,使得对于所有j=1,2,…,k有:
    Xij = Zj
    如果一个序列S即是A的子序列又是B的子序列,则称S是A、B的公共子序列。 求A、B所有公共子序列中最长的序列的长度。

    输入:

    输入共两行,每行一个由字母和数字组成的字符串,代表序列A、B。A、B的长度不超过200个字符。

    输出:

    一个整数,表示最长各个子序列的长度。 格式:printf("%d\n");

    输入样例:

    programming contest

    输出样例:

    2

    #include <iostream>
    #include <string>
    using namespace std;
    void LCSLength(int m,int n,char *x,char *y,int c[][200])
    {
        int i,j;
        for(i=1;i<=m;i++)
        c[i][0]=0;
        for(i=1;i<=n;i++)
        c[0][i]=0;
    
        /* for(int a=0;a<m;a++)
            {
                for(int b=0;b<n;b++)
                cout<<c[a][b]<<" ";
                cout<<endl;
            }*/
    
    
        //cout<<x[0]<<" "<<y[0]<<endl;
        for(i=1;i<=m;i++)
        for(j=1;j<=n;j++)
        {
            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];
        }
        /*for(int a=1;a<=m;a++)
            {
                for(int b=1;b<=n;b++)
                cout<<c[a][b]<<" ";
                cout<<endl;
            }*/
    
        cout<<c[m][n]<<endl;
    }
    int main()
    {
        string dataA;
        string dataB;
        int c[200][200];
        //dataA[0]=;
        //dataB[0]="0";
        char *x,*y;
        cin>>dataA;
        cin>>dataB;
        int m=dataA.length();
        int n=dataB.length();
        //cout<<m<<" "<<n<<endl;
        x=new char[m+2];
        y=new char[n+2];
        int i;
        for(i=0;i<m;i++)
        x[i+1]=dataA[i];
        x[i+1]='\0';
    
        for(i=0;i<n;i++)
        y[i+1]=dataB[i];
        y[i+1]='\0';
    
    
        //cout<<x<<endl;
        //cout<<y<<endl;
        //cout<<x[1]<<endl;
        //cout<<y[1]<<endl;
        LCSLength(m,n,x,y,c);
    
    }
    

      

  • 相关阅读:

    JVM基础
    rpm、yum、解压缩安装
    Vim使用及账号用户管理
    linux常用操作
    属主权限和属组权限
    解决Hystrix Dashboard 一直是Loading ...的情况
    扫描不到了@FeignClient注解的调用接口
    springcloud与springboot版本问题
    【力扣】6和9组成的最大数字 题解
  • 原文地址:https://www.cnblogs.com/lxk2010012997/p/3048293.html
Copyright © 2020-2023  润新知