题目:
输入两个字符串A和B,合并成一个串C。问C的最长回文子串长度。
合并规则:属于A和B的字符在C中顺序保持不变。如"abc"和"xyz"可以被合并成"axbycz"或"abxcyz"等。
|A|、|B| ≤ 50
做法:
代码
#include <bits/stdc++.h> #define IOS ios::sync_with_stdio(false), cin.tie(0) #define debug(a) cout << #a ": " << a << endl using namespace std; typedef long long ll; const int N = 55; char s[N], p[N]; int dp[N][N][N][N]; int main(void){ IOS; int T; cin >> T; while (T--){ cin >> (s+1) >> (p+1); int n = strlen(s+1), m = strlen(p+1); int ans = 0; for (int s_len = 0; s_len <= n; ++s_len){ for (int p_len = 0; p_len <= m; ++p_len){ for (int i = 1; i+s_len-1 <= n; ++i){ for (int k = 1; k+p_len-1 <= m; ++k){ int j = i+s_len-1, l = k+p_len-1; if (s_len+p_len <= 1) dp[i][j][k][l] = 1; else{ dp[i][j][k][l] = 0; if (s[i] == s[j] && s_len) dp[i][j][k][l] |= dp[i+1][j-1][k][l]; if (p[k] == p[l] && p_len) dp[i][j][k][l] |= dp[i][j][k+1][l-1]; if (s[i] == p[l] && s_len && p_len) dp[i][j][k][l] |= dp[i+1][j][k][l-1]; if (p[k] == s[j] && s_len && p_len) dp[i][j][k][l] |= dp[i][j-1][k+1][l]; } if (dp[i][j][k][l]) ans = max(ans, s_len+p_len); } } } } cout << ans << endl; } return 0; }