北大2250题

来源:互联网 发布:拥有了域名,如何建站 编辑:程序博客网 时间:2024/05/16 12:16

 题目链接:http://acm.pku.edu.cn/JudgeOnline/problem?id=2250

此题脱胎于最长公共子序列,只是把原先的最小单位字符换成了单词,具体方法没有什么特殊

#include <iostream>
#include <string>
using namespace std;

#define MAX_N 101
#define MAX_L 31

#define UP 0
#define LU 1
#define LF 2


bool first;
void What(int i,int j,char t[MAX_N][MAX_L],int tag[MAX_N][MAX_N])
{
 if(i != 0 && j != 0)
 {
  if(tag[i][j] == LU)
  {
   What(i-1,j-1,t,tag);
   if(first)
   {
    cout << t[i];
    first = false;
   }
   else
    cout << ' ' << t[i];
  }
  else if(tag[i][j] == UP)
   What(i-1,j,t,tag);
  else
   What(i,j-1,t,tag);
 }
}

int main()
{
 freopen("in.txt","r",stdin);

 char t1[MAX_N][MAX_L],t2[MAX_N][MAX_L],*tmp;
 int i,j,len1,len2,res[MAX_N][MAX_N],tag[MAX_N][MAX_N];
 tmp = new char[31];
 while(true)
 {
  len1 = 1;
  while(cin >> tmp && strcmp(tmp,"#") != 0)
  {
   strcpy(t1[len1],tmp);
   ++len1;
  }

  if(cin.fail())
   break;

  len2 = 1;
  while(cin >> tmp && strcmp(tmp,"#") != 0)
  {
   strcpy(t2[len2],tmp);
   ++len2;
  }

  for(i = 0;i < len1;++i)
   res[i][0] = 0;
  for(i = 1;i < len2;++i)
   res[0][i] = 0;

  for(i = 1;i < len1;++i)
  {
   for(j = 1;j < len2;++j)
   {
    if(strcmp(t1[i],t2[j]) == 0)
    {
     res[i][j] = res[i-1][j-1] + 1;
     tag[i][j] = LU;
    }
    else if(res[i][j-1] > res[i-1][j])
    {
     res[i][j] = res[i][j-1];
     tag[i][j] = LF;
    }
    else
    {
     res[i][j] = res[i-1][j];
     tag[i][j] = UP;
    }
   }
  }
  
  first = true;
  What(len1-1,len2-1,t1,tag);
  cout << endl;
 }
 return 0;
}

原创粉丝点击