UVa 10617 Again Palindrome(经典回文串区间DP)
题意:
给定一个字符串s,对s进行删除操作,使得剩下的子串是回文字符串,问最多有多少种这种子串。
思路:
涉及到回文字符串,首先要想到的肯定是区间DP,如何写出状态转移方程?
直接从题意切入:dp[i, j]表示区间[i, j]最多有多少个这样的子串。
1. s[i] == s[j] 去掉s[i],则一个子问题就是dp[i+1, j]; 去掉s[j],另一个子问题就是dp[i, j-1];
显然这两个子问题是会有重叠的,重叠的部分就是dp[i+1, j-1],所以要减去这部分。
如果s[i], s[j]都不去掉呢?因为s[i] == s[j], s[i]和s[j]组成一个子回文字串,并且s[i],s[j]和dp[i+1, j-1]
里面包含的所有子回文字串都构成回文字串,则这个子问题的解显然是dp[i+1, j-1] + 1。
于是会有 dp[i][j] = dp[i+1][j] + dp[i][j-1] + dp[i+1, j-1] + 1 - dp[i+1, j-1];
化简为 dp[i][j] = dp[i+1][j] + dp[i][j-1] + 1;
2. s[i] != s[j] 此时的子问题就比上述要简单了,因为s[i] s[j]与dp[i+1, j-1]的回文子串构成不了回文串。
于是 dp[i][j] = dp[i+1][j] + dp[i][j-1] - dp[i+1][j-1];
<span style="font-size:18px;">#include <cstdio> #include <iostream> #include <cstring> #include <cmath> #include <string> #include <algorithm> #include <queue> #include <stack> using namespace std; #define ll long long const double PI = acos(-1.0); const double e = 2.718281828459; const double eps = 1e-8; const int MAXN = 65; ll dp[MAXN][MAXN]; char s[MAXN]; int main() { //freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); int Case; cin>>Case; while(Case--) { scanf("%s", s+1); int len = strlen(s+1); memset(dp, 0, sizeof(dp)); for(int i = 1; i <= len; i++) { dp[i][i] = 1; } for(int k = 2; k <= len; k++) { for(int i = 1, j = k; j <= len; i++, j++) { if(s[i] == s[j]) dp[i][j] = dp[i+1][j]+dp[i][j-1]+1; else dp[i][j] = dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1]; } } cout<<dp[1][len]<<endl; } return 0; }</span>
下面这种为递归写法,记忆化搜索。
<span style="font-size:18px;">#include <cstdio> #include <iostream> #include <cstring> #include <cmath> #include <string> #include <algorithm> #include <queue> #include <stack> using namespace std; #define ll long long #define max(a, b) (a)>(b)?(a):(b) const double PI = acos(-1.0); const double e = 2.718281828459; const double eps = 1e-8; const int MAXN = 65; ll dp[MAXN][MAXN]; char s[MAXN]; ll dfs(int l, int r) { if(dp[l][r] != -1) return dp[l][r]; if(l >= r) return dp[l][r] = (l==r)?1:0; if(s[l] == s[r]) dp[l][r] = max(dp[l][r], dfs(l+1, r)+dfs(l, r-1)+1); else dp[l][r] = max(dp[l][r], dfs(l+1, r)+dfs(l, r-1)-dfs(l+1, r-1)); return dp[l][r]; } int main() { //freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); int Case; cin>>Case; while(Case--) { scanf("%s", s+1); int len = strlen(s+1); memset(dp, -1, sizeof(dp)); dp[1][len] = dfs(1, len); cout<<dp[1][len]<<endl; } return 0; }</span>
时间: 2024-08-02 14:33:47