Palindrome subsequence HDU-4632区间dp 回文问题 寒假集训

In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence <A, B, D> is a subsequence of <A, B, C, D, E, F>.
(http://en.wikipedia.org/wiki/Subsequence)

Given a string S, your task is to find out how many different subsequence of S is palindrome. Note that for any two subsequence X = <Sx1, Sx2, …, Sxk> and Y = <Sy1, Sy2, …, Syk> , if there exist an integer i (1<=i<=k) such that xi != yi, the subsequence X and Y should be consider different even if Sxi = Syi. Also two subsequences with different length should be considered different.
Input
The first line contains only one integer T (T<=50), which is the number of test cases. Each test case contains a string S, the length of S is not greater than 1000 and only contains lowercase letters.
Output
For each test case, output the case number first, then output the number of different subsequence of the given string, the answer should be module 10007.
Sample Input
4
a
aaaaa
goodafternooneveryone
welcometoooxxourproblems
Sample Output
Case 1: 1
Case 2: 31
Case 3: 421
Case 4: 960
在用dp记录1到len中有多少个回文子序列,我们从小区间去推到大区间,所以在有着前后相同的字符出现时,有dp[j][k]=max(dp[j][k],dp[j][k-1]+dp[j+1][k]+1)%10007,因为中间可以与第一个相组合也可以与最后一个相组合,
当遇到前后不同的情况下,有dp[j][k]=(dp[j][k-1]+dp[j+1][k]-dp[j+1][k-1]+10007)%10007,可以把前面与第一个结合+与后一个结合的长度-中间重复出现的长度,这里注意过程中取模要在最后加+mod,这样确保了不会出现负数取模和一些特殊情况

#include<map>
#include<stack>
#include<queue>
#include<string>
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#define ls (k<<1)
#define rs (k<<1|1)
#define pb push_back
#define mid ((l+r)>>1)
using namespace std;
const int p=1e4+7;
const int mod=10007;
const int maxn=1500;
typedef long long ll;
const int inf=0x3f3f3f3f;   
int dp[maxn][maxn];
char s[maxn];
ll mode(ll a,ll b){
    
    
    ll sum=1;
    a=a;
    while(b>0){
    
    
        if(b%2==1)
            sum=(sum*a);
            b/=2;
            a=(a*a);
    }
    return sum;
}
void solve(){
    
    
    int t;
    cin>>t;
    int cnt=0;
    while(t--){
    
    
        scanf("%s",s+1);
        memset(dp,0,sizeof(dp));
        int len=strlen(s+1);
        for(int i=1;i<=len;i++)
            dp[i][i]=1;
        for(int i=1;i<=len;i++){
    
    //枚举字符串长度
            for(int j=1;j+i<=len+1;j++){
    
    //枚举端点
                int k=i+j-1;//
                if(s[j]==s[k])
                    dp[j][k]=max(dp[j][k],dp[j][k-1]+dp[j+1][k]+1)%10007;
                else
                    dp[j][k]=(dp[j][k-1]+dp[j+1][k]-dp[j+1][k-1]+10007)%10007;
            }   
        }
        printf("Case %d: %d\n",++cnt,dp[1][len]);
    }
}
int main(){
    
    
    ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
    solve();
    system("pause");    
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_45891413/article/details/112741291
今日推荐