于是 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>
UVa 10617 Again Palindrome(回文串区间DP)
原文地址:http://blog.csdn.net/u014028317/article/details/45339235