1. 程式人生 > >HDU 4632 Palindrome subsequence(區間DP求回文子序列數)

HDU 4632 Palindrome subsequence(區間DP求回文子序列數)

pan get color math stdout 一個 inf 序列 star

題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=4632

題目大意:給你若幹個字符串,回答每個字符串有多少個回文子序列(可以不連續的子串)。
解題思路:

設dp[i][j]為[i,j]的回文子序列數,那麽得到狀態轉移方程:
dp[i][j]=(dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1]+MOD)%MOD
if(str[i]==str[j])
  dp[i][j]+=dp[i-1][j+1]+1

代碼:

 1 #include<cstdio>
 2
#include<cmath> 3 #include<cctype> 4 #include<cstring> 5 #include<iostream> 6 #include<algorithm> 7 #include<vector> 8 #include<queue> 9 #include<set> 10 #include<map> 11 #include<stack> 12 #include<string> 13 #define
lc(a) (a<<1) 14 #define rc(a) (a<<1|1) 15 #define MID(a,b) ((a+b)>>1) 16 #define fin(name) freopen(name,"r",stdin) 17 #define fout(name) freopen(name,"w",stdout) 18 #define clr(arr,val) memset(arr,val,sizeof(arr)) 19 #define _for(i,start,end) for(int i=start;i<=end;i++) 20
#define FAST_IO ios::sync_with_stdio(false);cin.tie(0); 21 using namespace std; 22 typedef long long LL; 23 const int N=1e3+5; 24 const int MOD=10007; 25 const int INF=0x3f3f3f3f; 26 const double eps=1e-10; 27 28 int dp[N][N]; 29 char str[N]; 30 31 int main(){ 32 int t,cas=0; 33 cin>>t; 34 while(t--){ 35 cin>>str; 36 int n=strlen(str); 37 memset(dp,0,sizeof(dp)); 38 for(int i=0;i<n;i++){ 39 dp[i][i]=1; 40 } 41 for(int len=1;len<n;len++){ 42 for(int i=0;i+len<n;i++){ 43 int j=i+len; 44 dp[i][j]=(dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1]+MOD)%MOD; 45 //如果str[i]==str[j],單獨兩個字符str[i],str[j]能組成一個回文串,同樣也能跟[i-1,j+1]的所有回文串組成新的回文串 46 if(str[i]==str[j]) 47 dp[i][j]+=dp[i+1][j-1]+1; 48 } 49 } 50 cout<<"Case "<<++cas<<": "<<dp[0][n-1]%MOD<<endl; 51 } 52 return 0; 53 }

HDU 4632 Palindrome subsequence(區間DP求回文子序列數)