题目内容:
两种水果杂交出一种新水果,现在给新水果取名,要求这个名字中包含以前两种水果的字母,且名字尽量短,即:以前的水果名字arr1、arr2是新水果名arr的子序列,使用动态规划的思想设计算法得到新水果名arr。
输入格式:
以空格分开两个水果的名字
输出格式:
新水果的名字
输入样例:
pear peach
输出样例:
pearch
输入样例:
peach pear
输出样例:
peachr
#include<iostream>
#include<vector>
using namespace std;
void CommonOrder(int a,int b, vector<vector<int>>& dp, vector<vector<int>>& bs,string x, string y)
{
int i, j;
for (i = 0; i <= a; i++) //将dp[i][0]置为0,边界条件
{
dp[i][0] = 0;
}
for (j = 0; j <= b; j++) //将dp[0][j]置为0,边界条件
{
dp[0][j] = 0;
}
for (i = 1; i <= a; i++)
{
for (j = 1; j <= b; j++) //两重for循环处理a、b的所有字符
{
if (x[i - 1] == y[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
bs[i][j] = 1;
}
else {
dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]);
if (dp[i - 1][j] > dp[i][j - 1])
{
bs[i][j] = 3;
}else
{
bs[i][j] = 2;
}
}
}
}
}
void output(int i, int j, vector<vector<int>> bs,string x,string y)
{
if (i == 0 && j == 0)
{
return;
}
if (i == 0)
{
output(i, j - 1,bs,x,y);
cout << y[j - 1];
return;
}
else if (j == 0)
{
output(i - 1, j, bs, x, y);
cout << x[i - 1];
return;
}
if (bs[i][j] == 1)
{
output(i - 1, j - 1, bs, x, y);
cout << x[i - 1];
return;
}else if (bs[i][j] == 3)
{
output(i - 1, j, bs, x, y);
cout << x[i - 1];
return;
}else
{
output(i, j - 1, bs, x, y);
cout << y[j - 1];
return;
}
}
int main()
{
string x;
string y;
cin >> x;
cin >> y;
int a = x.length();
int b = y.length();
vector<vector<int>> dp(a+1, vector<int>(b+1));
vector<vector<int>> bs(a+1, vector<int>(b+1));
CommonOrder(a,b,dp,bs,x,y);
output(a, b,bs,x,y);
return 0;
}