poj 2250

     题目实际意思,就是找两篇文章中的“最多公共单词”——其实可以把它转换成最长公共子序列问题,只是这里的序列的元素不是字母而是单词罢了。

     另外,此题主要是考察LCS的形成路径,因此需要一个数组记录这个路径,这里用的是二维的字符数组dir[][],其中'1''2''3'分别表示斜向上,向左和向上。具体原理可以看算法导论的动态规划的最长公共子序列那一篇的内容,写得非常好。

      以下是详细代码:

 

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
const int M=32,N=105;

char s1[N][M],s2[N][M];
char s[M];
int len1,len2;
int c[N][N];
char dir[N][N],stack[N][M]; 
char ch;

void LCS()
{
 int i,j;
 for(i=1;i<=len1;i++)
 {
  for(j=1;j<=len2;j++)
  {
   if(strcmp(s1[i],s2[j])==0)
   {
    c[i][j]=c[i-1][j-1]+1;
    dir[i][j]='1';
   }
   else
   {
    if(c[i-1][j]>=c[i][j-1])
    {
     c[i][j]=c[i-1][j];
     dir[i][j]='2';
    }
    else
    {
     c[i][j]=c[i][j-1];
     dir[i][j]='3';
    }
   }
  }
 }
}

int main()
{
 while(scanf("%s",s)==1)
 {
  int i=1,j=1;
  int top=0;
  strcpy(s1[i++],s);
  while(1)
  {
   scanf("%s",s1[i]);
   if(s1[i][0]=='#') break;
   i++;
  }
  len1=i-1;
  while(1)
  {
   scanf("%s",s2[j]);
   if(s2[j][0]=='#') break;
   j++;
  }
  len2=j-1;
  LCS();
  
i=len1;j=len2;
  while(dir[i][j]!='/0')
  {
   int p,q;
   p=i;q=j;
   if(dir[i][j]=='1') p-=1,q-=1;
   else if(dir[i][j]=='2') p-=1;
   else if(dir[i][j]=='3') q-=1;
   if(c[i][j]!=c[p][q]) strcpy(stack[top++],s1[i]);
   i=p;
   j=q;
  }
  
for(i=top-1;i>=0;i--)
   printf("%s ",stack[i]);
  printf("/n");
 }
 return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值