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 }

转载于:https://www.cnblogs.com/naturepengchen/articles/3891299.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值