Advanced Fruits

来源:互联网 发布:家庭记账软件免费版 编辑:程序博客网 时间:2024/05/21 06:53

Description

The company "21st Century Fruits" has specialized in creating new sorts of fruits by transferring genes from one fruit into the genome of another one. Most times this method doesn't work, but sometimes, in very rare cases, a new fruit emerges that tastes like a mixture between both of them. 

A big topic of discussion inside the company is "How should the new creations be called?" A mixture between an apple and a pear could be called an apple-pear, of course, but this doesn't sound very interesting. The boss finally decides to use the shortest string that contains both names of the original fruits as sub-strings as the new name. For instance, "applear" contains "apple" and "pear" (APPLEar and apPlEAR), and there is no shorter string that has the same property. 
A combination of a cranberry and a boysenberry would therefore be called a "boysecranberry" or a "craboysenberry", for example. 

Your job is to write a program that computes such a shortest name for a combination of two given fruits. Your algorithm should be efficient, otherwise it is unlikely that it will execute in the alloted time for long fruit names. 

Input

Each line of the input contains two strings that represent the names of the fruits that should be combined. All names have a maximum length of 100 and only consist of alphabetic characters. 
Input is terminated by end of file.

Output

For each test case, output the shortest name of the resulting fruit on one line. If more than one shortest name is possible, any one is acceptable.

Sample Input

apple peachananas bananapear peach

Sample Output

appleachbananas

pearch

dp[i][j]表示包含了A串的前 i-1个字符和B串的前j-1个位置的C串的最短长度。

if(A[i]==B[j])

dp[i][j]=dp[i-1][j-1]+1;

else

dp[i][j]=min(dp[i][j-1],dp[i-1][j])+1;

#include<iostream>#include<string.h>#include<stdio.h>using namespace std;const int INF=0x3f3f3f3f;const int maxn=100010;int dp[150][150],path[150][150];char sa[150],sb[150];void print(int i,int j){  if(i==0&&j==0)    return;  if(path[i][j]==1)  {    print(i-1,j);    printf("%c",sa[i]);  }  else if(path[i][j]==-1)  {    print(i,j-1);    printf("%c",sb[j]);  }  else  {    print(i-1,j-1);    printf("%c",sa[i]);  }}int main(){  int i,j,la,lb;  while(~scanf("%s%s",sa+1,sb+1))  {    la=strlen(sa+1);    lb=strlen(sb+1);    for(i=1;i<=la;i++)      dp[i][0]=i,path[i][0]=1;    for(i=1;i<=lb;i++)      dp[0][i]=i,path[0][i]=-1;    for(i=1;i<=la;i++)      for(j=1;j<=lb;j++)      {        dp[i][j]=INF;        if(sa[i]==sb[j])//相等只用加入一个字符          dp[i][j]=dp[i-1][j-1]+1,path[i][j]=0;        else        {          if(dp[i][j-1]<dp[i-1][j])//增加sb[j]            dp[i][j]=dp[i][j-1]+1,path[i][j]=-1;          else//增加sa[i]            dp[i][j]=dp[i-1][j]+1,path[i][j]=1;        }      }    print(la,lb);    printf("\n");  }  return 0;}


0 0
原创粉丝点击