题意:
输入两个字符串A和B,合并成一个串C,属于A和B的字符在C中顺序保持不变。
我们定义字符串的价值为其最长回文子串的长度,
需要求出所有可能的C中价值最大的字符串,输出这个最大价值即可。
思路:
用
dp[i][j][k][l]
记录第一个串的a[i - 1]
到a[j - 1]
和第二个串的b[k - 1]
到b[l - 1]
能不能构成一个回文串,转移方程://取两个串的长度之和小于等于1 dp[i][j][k][l] = 1; //取第一个串的长度大于等于2 dp[i][j][k][l] |= (dp[i + 1][j - 1][k][l] && (a[i - 1] == a[j - 1])); //取第二个串的长度大于等于2 dp[i][j][k][l] |= (dp[i][j][k + 1][l - 1] && (b[k - 1] == b[l - 1])); //两个串的长度都要大于等于1 dp[i][j][k][l] |= (dp[i + 1][j][k][l - 1] && (a[i - 1] == b[l - 1])); dp[i][j][k][l] |= (dp[i][j - 1][k + 1][l] && (a[j - 1] == b[k - 1]));
AC代码:
#include<bits/stdc++.h>
using namespace std;
int dp[55][55][55][55];
inline void solve()
{
memset(dp, 0, sizeof dp);
string a, b; cin >> a >> b;
int lena = a.size(), lenb = b.size();
int ans = -1;
for (int x = 0; x <= lena; ++x)
for (int y = 0; y <= lenb; ++y)
for (int i = 1; i + x - 1 <= lena; ++i)
for (int k = 1; k + y - 1 <= lenb; ++k)
int j = i + x - 1, l = k + y -1;
if (x + y <= 1) dp[i][j][k][l] = 1;
else
{
if (x > 1)
dp[i][j][k][l] |= (dp[i + 1][j - 1][k][l] && (a[i - 1] == a[j - 1]));
if (x > 0 && y > 0){
dp[i][j][k][l] |= (dp[i + 1][j][k][l - 1] && (a[i - 1] == b[l - 1]));
dp[i][j][k][l] |= (dp[i][j - 1][k + 1][l] && (a[j - 1] == b[k - 1]));
}
if (y > 1)
dp[i][j][k][l] |= (dp[i][j][k + 1][l - 1] && (b[k - 1] == b[l - 1]));
}
if (dp[i][j][k][l]) ans = max(ans, x + y);
}
cout << ans << endl;
}
int main()
{
int T = 1; cin >> T;
for (int i = 1; i <= T; ++i) solve();
return 0;
}