zoukankan      html  css  js  c++  java
  • 动态规划———求两个字符串的最长公共子序列!

     1 #include<stdio.h>
     2 #include<string.h>
     3 
     4 const int max=120;//字符串大小
     5 char x[max],y[max];
     6 int b[max][max];
     7 int c[max][max];
     8 int m,n;
     9 
    10 void printstring(int i,int j)//打印最长字串
    11 {
    12     if(i==0||j==0) return;
    13     if(b[i][j]==1) 
    14     {
    15         printstring(i-1,j-1);
    16         printf("%c ",x[i-1]);
    17     }
    18     else if(b[i][j]==2)
    19         printstring(i-1,j);
    20     else
    21         printstring(i,j-1);
    22 }
    23 
    24 void maxstring()//动态规划求最长字串长度
    25 {
    26     int i,j;
    27     memset(c,0,sizeof(c));
    28     for(i=1;i<=m;i++)
    29         for(j=1;j<=n;j++)
    30             if(x[i-1]==y[j-1]) 
    31             {
    32                 c[i][j]=c[i-1][j-1]+1;
    33                 b[i][j]=1;
    34             }
    35             else if(c[i-1][j]>c[i][j-1])
    36             {
    37                 c[i][j]=c[i-1][j];
    38                 b[i][j]=2;
    39             }
    40             else
    41             {
    42                 c[i][j]=c[i][j-1];
    43                 b[i][j]=3;
    44             }
    45     printf("%d\n",c[m][n]);
    46 }
    47 
    48 
    49 int main()
    50 {
    51     while(scanf("%s%s",x,y))
    52     {
    53         m=strlen(x);
    54         n=strlen(y);
    55         maxstring();
    56         printstring(m,n);
    57         printf("\n\n");
    58     }
    59     return 0;
    60 }
  • 相关阅读:
    Windows 8.1 序列化与反序列化
    window store app 附件读取
    Window 8.1 计时器功能及图片切换
    c#多层嵌套Json
    isNotNull与isNotEmpty的区别
    商务用语
    国家气象局三天天气WebService接口
    WebServise
    EF架构基础代码
    接口定义
  • 原文地址:https://www.cnblogs.com/xiaofanke/p/2650149.html
Copyright © 2011-2022 走看看