博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Advanced Fruits (LSC算法例题)
阅读量:270 次
发布时间:2019-03-01

本文共 2471 字,大约阅读时间需要 8 分钟。

题目:

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.

输入:

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.

输出:

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.

样例输入:

apple peachananas bananapear peach

样例输出:

appleachbananaspearch

 

题意:结合两个字符串,他们的公共子序列只输出一次。

 
题解:利用LCS算法标记字符——
 
注意:样例数据的输出不一定要和样例输出一致,是满足题目要求的任意杂交串。

 

代码:

//LCS(longest common subsequence) 最长公共子序列算法//dacao//2018/10/21#include
#include
#include
using namespace std;void LCS_length(string x,string y,vector
>&dp,vector
> &flag){ int m=x.length(); int n=y.length(); dp.resize(m+1); flag.resize(m+1); int i,j; for(i=0;i
= dp[i][j-1]) { dp[i][j]=dp[i-1][j]; flag[i][j]='u';//来源于上面 } else { dp[i][j]=dp[i][j-1]; flag[i][j]='l';//来源于左边 } } }}void dp_print_lcs(vector
> &flag,string &x,string &y,int i,int j){ int m; for(m=1;m<=i;m++)//给数组边缘初始化 flag[m][0]='u'; for(m=1;m<=j;m++) flag[0][m]='l'; if(i==0&&j==0) return; if(flag[i][j]=='c') { dp_print_lcs(flag,x,y,i-1,j-1); cout<
>x>>y) { vector< vector
> dp; vector< vector
> flag; LCS_length(x,y,dp,flag); dp_print_lcs(flag,x,y,x.size(),y.size()); cout<

 

 

 

 

 

 

转载地址:http://ygta.baihongyu.com/

你可能感兴趣的文章