poj - 2250 题解

题意:魔改版的LCS问题。序列是单词序列

解法:原版LCS的序列元素是数字,想办法把数字替换成单词就解决了

  1 #include<iostream>
  2 #include<cstdio>
  3 #include<algorithm>
  4 #include<cstring>
  5 #include<string>
  6 using namespace std;
  7 string a[4000];
  8 string b[4000];
  9 int f[4000][4000];
 10 int la=0;
 11 int lb=0;
 12 string res[4000];
 13 bool get_res(int x,int y,int z)
 14 {
 15     if(z==f[la][lb]+1)
 16     {
 17         return true;
 18     }
 19     if(x*y==0)
 20     {
 21         return false;
 22     }
 23     if(a[x]==b[y])
 24     {
 25         res[z]=a[x];
 26         if(get_res(x-1,y-1,z+1))
 27         {
 28             return true;
 29         }
 30     }
 31     else
 32     {
 33         if(f[x][y]==f[x][y-1])
 34         {
 35             if(get_res(x,y-1,z))
 36             {
 37                 return true;
 38             }
 39         }
 40         if(f[x][y]==f[x-1][y])
 41         {
 42             if(get_res(x-1,y,z))
 43             {
 44                 return true;
 45             }
 46         }
 47     }
 48     return false;
 49 }
 50 int main()
 51 {
 52     string s;
 53     while(cin>>s)
 54     {
 55         bool flag=false;
 56         la=0;
 57         lb=0;
 58         a[++la]=s;
 59         while(true)
 60         {
 61             cin>>s;
 62             if(s=="#")
 63             {
 64                 if(flag)
 65                 {
 66                     break;
 67                 }
 68                 flag=true;
 69                 continue;
 70             }
 71             if(!flag)
 72             {
 73                 a[++la]=s;
 74             }
 75             else
 76             {
 77                 b[++lb]=s;
 78             }
 79         }
 80         memset(f,0,sizeof(f));
 81         for(int i=1;i<=la;i++)
 82         {
 83             for(int j=1;j<=lb;j++)
 84             {
 85                 if(a[i]==b[j])
 86                 {
 87                     f[i][j]=max(f[i][j],f[i-1][j-1]+1);
 88                 }
 89                 else
 90                 {
 91                     f[i][j]=max(f[i][j-1],f[i-1][j]);
 92                 }
 93             }
 94         }
 95         get_res(la,lb,1);
 96         for(int i=f[la][lb];i>=1;i--)
 97         {
 98             cout<<res[i]<<" ";
 99         }
100         cout<<endl;
101     }
102     
103     return 0;
104 }

 

转载于:https://www.cnblogs.com/shao0099876/p/7365096.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值