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

    题目:

    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.

    Input

    abcfbc abfcab
    programming contest 
    abcd mnp

    Output

    4
    2
    0

    Sample Input

    abcfbc abfcab
    programming contest 
    abcd mnp

    Sample Output

    4
    2
    0
    题意描述:
    输入两串英文字符
    计算并输出两串字符的最长公共子序列的长度
    解题思路:
    属于DP问题。双重循环遍历,若对应字符一样,则最长子序列数加一;
    若不一样,选择第一串字符当前长度-1和第二串字符当前长度的最长公共子序列的长度和第一串字符当前长度和第二串字符当前长度-1的最长公共子序列的长度中较大的长度。
    代码实现:
     1 #include<stdio.h>
     2 #include<string.h>
     3 char str1[1010],str2[1010];
     4 int maxlen[1010][1010];
     5 int main()
     6 {
     7     int l1,l2,i,j;
     8     while(scanf("%s%s",str1+1,str2+1) != EOF)
     9     {
    10         l1=strlen(str1+1);
    11         l2=strlen(str2+1);
    12         for(i=0;i<=l1;i++)
    13             maxlen[i][0]=0;
    14         for(i=0;i<=l2;i++)
    15             maxlen[0][i]=0;
    16         for(i=1;i<=l1;i++)
    17         {
    18             for(j=1;j<=l2;j++)
    19             {
    20                 if(str1[i]==str2[j])
    21                 maxlen[i][j]=maxlen[i-1][j-1]+1;
    22                 else
    23                 maxlen[i][j]=maxlen[i-1][j]>maxlen[i][j-1]?maxlen[i-1][j]:maxlen[i][j-1];
    24             }
    25         }
    26         printf("%d
    ",maxlen[l1][l2]);
    27     }
    28     return 0;
    29 }

    易错分析:

    注意dp数组的初始化问题



  • 相关阅读:
    datalist和repeater中radiobutton单选的问题
    SQL循环在表中增加新列
    [jQuery]使用jQuery.Validate进行客户端验证(高级篇上)——不使用微软验证控件的理由
    C# Excel 行高,列宽,合并单元格,单元格边框线,冻结 关于C#操作EXCLE常见操作比较全的
    JS弹出窗口的运用与技巧(转)
    设计模式完整备忘录
    jquery + ashx + Json 操作数据
    SQL STUFF函数 拼接字符串
    获取SQL 各字段说明,表名等有效信息
    谈谈对于企业级系统架构的理解
  • 原文地址:https://www.cnblogs.com/wenzhixin/p/7267948.html
Copyright © 2011-2022 走看看