题目内容:
两种水果杂交出一种新水果,现在给新水果取名,要求这个名字中包含以前两种水果的字母,且名字尽量短,即:以前的水果名字arr1、arr2是新水果名arr的子序列,使用动态规划的思想设计算法得到新水果名arr。
输入格式:
以空格分开两个水果的名字
输出格式:
新水果的名字
输入样例:
pear peach
输出样例:
pearch
输入样例:
peach pear
输出样例:
peachr
#include <string>
#include <iostream>
using namespace std;
struct node
{
int pi, pj;
char data;
};
int max(int a, int b)//返回a,b中的最大值
{
int max;
if (a >= b)
max = a;
else
max = b;
return max;
}
node* LCS(char* a, char* b,int x,int y,int &length)//a,b是两个字符串序列,此函数用来求最长公共子序列,x,y是a,b的长度
{
int* *db = new int*[x];//动态规划的表格
for (int i = 0; i < x; i++)
db[i] = new int[y];
for (int i = 0; i < x; i++)//二维数组0行0列不做记录,初始化为0
db[i][0] = 0;
for (int i = 0; i < y; i++)
db[0][i] = 0;
for (int i = 1; i < x; i++)//填表
{
for (int j = 1; j < y; j++)
{
if (a[i] == b[j])
db[i][j] = db[i - 1][j - 1] + 1;
else
db[i][j] = max(db[i - 1][j], db[i][j - 1]);
}
}
int max = db[x - 1][y - 1];
length = max;
node* ch= new node[max];
//倒推求轨迹
int i = x - 1, j = y - 1,k=0;
while (i > 0 && j > 0)
{
if (a[i] == b[j])
{
ch[k].data = a[i];
ch[k].pi = i;
ch[k].pj = j;
k++;
i--; j--;
}
else
{
if (db[i][j - 1] >= db[i - 1][j])
{
j--;
}
else
i--;
}
}
return ch;
}
int main()
{
int m, n;
string fruit1, fruit2;
cin >> fruit1 >> fruit2;
m = fruit1.length();
n = fruit2.length();
char* f1 = new char[m+2];
char* f2 = new char[n+2];
f1[0] = f2[0] = '0';
f1[m + 1] = f2[n + 1] = '\0';
for (int i = 1; i < m+1; i++)
f1[i] = fruit1[i-1];
for (int i = 1; i < n+1; i++)
f2[i] = fruit2[i-1];
int number;
node* ch = LCS(f1, f2, m + 1, n + 1,number);
for (int i = 1, j = 1;i<m+1,j<n+1;)
{
for (int k = number - 1; k >= 0; k--)
{
while (i != ch[k].pi)
{
cout << f1[i];
i++;
}
while (j != ch[k].pj)
{
cout << f2[j];
j++;
}
cout << ch[k].data;
i++;
j++;
}
if (i < m + 1)
{
while (i < m + 1)
cout << f1[i++];
}
if (j < n + 1)
{
while (j < n + 1)
cout << f2[j++];
}
}
return 0;
}