Uva--10617(动规)

2014-08-04 23:25:42

Again Palindromes

Output: Standard Output

Time Limit: 2 Seconds 

A palindorme is a sequence of one or more characters that reads the same from the left as it does from the right. For example, ZTOTand MADAM are palindromes, but ADAM is not.

Given a sequence S of N capital latin letters. How many ways can one score out a few symbols (maybe 0) that the rest of sequence become a palidrome. Varints that are only  different by an order of scoring out should be considered the same.

Input

The input file contains several test cases (less than 15). The first line contains an integer T that indicates how many test cases are to follow.

Each of the T lines contains a sequence S (1≤N≤60). So actually each of these lines is a test case.

Output

For each test case output in a single line an integer – the number of ways.

Sample Input                             Output for Sample Input

3

BAOBAB

AAAA

ABA

22

15

5

 

 

思路:求回文子串数,经典回文串dp处理,注意好递推方向,区间延展型dp。dp[i][j]表示区间字符串区间[i , j]的回文子串数,最后注意下long long。

    DP方程: dp[i][j] 要考虑 (1) d[i+1][j-1] 和 s[i] 配对、(2) dp[i+1][j-1] 和 s[j] 配对、以及(3) dp[i+1][j-1] 和 s[i],s[j] 同时配对的情况。

    s[i] == s[j] :

      dp[i][j] = max(dp[i][j] , dp[i][j-1](必删j) + dp[i+1][j](必删i) - dp[i+1][j-1](i,j都删)(因为前两者有重复部分)+ (dp[i+1][j-1](i,j都不删) + 1)(因为dp[i+1][j-1]和s[i],s[j]配对依然回文))

     --> dp[i][j] = max(dp[i][j] , dp[i][j-1] + dp[i+1][j] + 1);

      s[i] != s[j]  :    

       dp[i][j] = max(dp[i][j] , dp[i][j-1](必删j) + dp[i+1][j](必删i) - dp[i+1][j-1](i,j都删)(因为前面两者有重复部分));

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <iostream>
 4 using namespace std;
 5 #define ll long long
 6 
 7 int main(){
 8     int t;
 9     int len;
10     ll dp[100][100];
11     char s[100];
12     scanf("%d",&t);
13     while(t--){
14         memset(dp,0,sizeof(dp));
15         scanf("%s",s + 1);
16         len = strlen(s + 1);
17         for(int i = len ; i >= 0; --i){
18             for(int j = i; j <= len; ++j){
19                 if(s[i] == s[j])
20                     dp[i][j] = max(dp[i][j],dp[i + 1][j] + dp[i][j - 1] + 1);
21                 else
22                     dp[i][j] = max(dp[i][j],dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]);
23             }
24         }
25         printf("%lld\n",dp[1][len]);
26     }
27     return 0;
28 }
posted @ 2014-08-04 23:47  Naturain  阅读(182)  评论(0编辑  收藏  举报