zoukankan      html  css  js  c++  java
  • HDU 1159 Common Subsequence (dp)

    题目链接

    Problem Description

    A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X = <x1, x2, ..., xm> another sequence Z = <z1, z2, ..., zk> is a subsequence of X if there exists a strictly increasing sequence <i1, i2, ..., ik> of indices of X such that for all j = 1,2,...,k, xij = zj. For example, Z = <a, b, f, c> is a subsequence of X = <a, b, c, f, b, c> with index sequence <1, 2, 4, 6>. Given two sequences X and Y the problem is to find the length of the maximum-length common subsequence of X and Y.

    The program input is from a text file. Each data set in the file contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct. For each set of data the program prints on the standard output the length of the maximum-length common subsequence from the beginning of a separate line.

    Sample Input

    abcfbc abfcab
    programming contest 
    abcd mnp
    

    Sample Output

    4
    2
    0
    

    分析:

    给出两个序列S1和S2,求出的这两个序列的最大公共部分S3就是就是S1和S2的最长公共子序列了。公共部分

    必须是以相同的顺序出现,但是不必要是连续的。

    1、字符相同,则指向左上,并加1

    2、字符不同,则指向左边或者上边较大的那个

    代码:

    #include <stdio.h>
    #include <string.h>
    #include <algorithm>
    using namespace std;
    char ch1[1000],ch2[1000];
    int dp[1000][1000];
    int k1,k2;
    void zhixul()
    {
        int i,j;
        memset(dp,0,sizeof(dp));
        for(i = 1; i<=k1; i++)
        {
            for(j = 1; j<=k2; j++)
            {
                if(ch1[i-1] == ch2[j-1])///字符相同,则指向左上,并加1
                    dp[i][j] = dp[i-1][j-1]+1;
                else
                    dp[i][j] = max(dp[i-1][j],dp[i][j-1]);///字符不同,比较左边和上边那个大取最大
            }
        }
    }
    int main()
    {
        while(~scanf("%s%s",ch1,ch2))
        {
            k1 = strlen(ch1);
            k2 = strlen(ch2);
            zhixul();
            printf("%d
    ",dp[k1][k2]);
        }
        return 0;
    }
  • 相关阅读:
    centos下修改hosts文件以及生效命令
    CentOS 7 上安装(LAMP)服务 Linux,Apache,MySQL,PHP
    sqlserver下载地址及密匙
    npm/gulp/nodejs
    sp_addlinkedserver 跨服务器连接数据库查询
    sql使用临时表循环
    nodejs和npm
    扫描输入后自动定位到下一个输入框
    Unable to load the specified metadata resource
    mysql保存乱码(C#)
  • 原文地址:https://www.cnblogs.com/cmmdc/p/6764053.html
Copyright © 2011-2022 走看看