zoukankan      html  css  js  c++  java
  • poj 1458最长公共子序列

    Common Subsequence
    Time Limit: 1000MS   Memory Limit: 10000K
    Total Submissions: 32971   Accepted: 12925

    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.

    Input

    The program input is from the std input. Each data set in the input contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct.

    Output

    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
     1 #include<stdio.h>
     2 #include<string.h>
     3 
     4 const int max=1010;
     5 char a[max],b[max];
     6 int d[max][max],s[max][max];
     7 
     8 void print(int i,int j)
     9 {
    10      if(i==0||j==0) return ;
    11      if(s[i][j]==0)
    12      {
    13                    print(i-1,j-1);
    14                    printf("%c ",a[i-1]);
    15      }
    16      else if(s[i][j]==1) print(i,j-1);
    17      else print(i-1,j);
    18 }
    19      
    20 int main()
    21 {
    22     int n,m,i,j;
    23     while(scanf("%s%s",a,b)!=EOF)
    24     {
    25         n=strlen(a);
    26         m=strlen(b);
    27         memset(d,0,sizeof(d));
    28         memset(s,0,sizeof(s));
    29         for(i=1;i<=n;i++)
    30             for(j=1;j<=m;j++)
    31             {
    32                 if(a[i-1]==b[j-1])
    33                 {
    34                     d[i][j]=d[i-1][j-1]+1;
    35                     s[i][j]=0;
    36                 }
    37                 else if(d[i][j-1]>d[i-1][j])
    38                 {
    39                     d[i][j]=d[i][j-1];
    40                     s[i][j]=1;
    41                 }
    42                 else 
    43                 {
    44                     d[i][j]=d[i-1][j];
    45                     s[i][j]=2;
    46                 }
    47             }
    48         printf("%d\n",d[n][m]);
    49         //print(n,m);
    50     }
    51     return 0;
    52 }
  • 相关阅读:
    C语言内存分析
    算法之快速排序
    单链表逆转
    C程序设计语言之一
    vim插件配置(一)
    makefile示例
    cocos2d基础入门
    Makefile
    Makefile
    GCC编译四阶段
  • 原文地址:https://www.cnblogs.com/xiaofanke/p/3119861.html
Copyright © 2011-2022 走看看