zoukankan      html  css  js  c++  java
  • HDU 1159 Common Subsequence 公共子序列 DP 水题重温

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1159

    Common Subsequence

    Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
    Total Submission(s): 18201    Accepted Submission(s): 7697


    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
     

    解题思路:

    开一个二维数组f[N][M]记录第一个数组取前N个数和第二个数组取前M个数的时候公共子序列的最大长度,最后输出f[l1][l2]即为最后结果。
     
     1 #include<cstdio>
     2 #include<cstring>
     3 #include<iostream>
     4 #include<algorithm>
     5 using namespace std;
     6 char keng1[2000],keng2[2000];
     7 int con[2000][2000];
     8 int getmax(int a,int b)
     9 {if(a>b)return a;else return b;}
    10 int main()
    11 {
    12     int i,j,l1,l2,Max;
    13     keng1[0]=keng2[0]='#';
    14     while(scanf("%s%s",keng1+1,keng2+1)!=EOF)
    15     {
    16         Max=0;
    17         l1=strlen(keng1);
    18         l2=strlen(keng2);
    19         memset(con,0,sizeof(con));
    20         for(i=1;i<l1;i++)
    21         {
    22             for(j=1;j<l2;j++)
    23             {
    24                 if(keng1[i]==keng2[j])
    25                     con[i][j]=getmax(con[i][j],con[i-1][j-1]+1);
    26                 else
    27                 con[i][j]=getmax(con[i-1][j],con[i][j-1]);
    28             }
    29         }
    30         printf("%d
    ",con[l1-1][l2-1]);
    31     }
    32     return 0;
    33 }
    View Code
     
     
  • 相关阅读:
    HDU-3790 最短路径问题(双重权值)
    Graph (floyd)
    POJ-3259 Wormholes(判断负环、模板)
    HDU-1317 XYZZY
    HDU-1548 A strange lift(单源最短路 或 BFS)
    最小生成树(模板 prim)
    【面试】386- JavaScript 面试 20 个核心考点
    【Koa】385- koa框架的快速入门与使用
    【小程序】384- 如何一人五天开发完复杂小程序(前端必看)
    【React】383- React Fiber:深入理解 React reconciliation 算法
  • 原文地址:https://www.cnblogs.com/wuwing/p/3307690.html
Copyright © 2011-2022 走看看