Palindrome subsequence HDU - 4632 (区间dp)

Palindrome subsequence HDU - 4632 (区间dp)

题目链接
题目大意:求字符串有多少回文子序列。(这里的子序列可以不连续)
input:
4
a
aaaaa
goodafternooneveryone
welcometoooxxourproblems
output:
Case 1: 1
Case 2: 31
Case 3: 421
Case 4: 960

#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;

const int maxn = 1e3 + 100;
const int inf = 0x3f3f3f3f;
const int mod = 10007;
char str[maxn];
int dp[maxn][maxn];

int main()
{
   int t, cas = 1;
   scanf("%d", &t);
   while(t--)
   {
      scanf("%s", str);
      int len = strlen(str);

      memset(dp, 0, sizeof(dp));

      for(int i = 0; i < len; i++) {
         dp[i][i] = 1;
      }

      for(int i = 1; i < len; i++) {
         for(int j = i - 1; j >= 0; j--) {
            dp[j][i] = (dp[j + 1][i] + dp[j][i - 1] - dp[j + 1][i - 1] + mod) % mod; //小的容斥
            if(str[i] == str[j]) dp[j][i] = (dp[j][i] + dp[j + 1][i - 1] + 1) % mod;
         }
      }

      printf("Case %d: %d\n", cas++, dp[0][len - 1]);
   }

}

猜你喜欢

转载自blog.csdn.net/deerly_/article/details/80348219