Palindrome subsequence(区间dp+容斥)
(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 = <S x1, S x2, ..., S xk> and Y = <Sy1, S y2, ..., S yk> , if there exist an integer i (1<=i<=k) such that xi != yi, the subsequence X and Y should be consider different even if S xi = S yi. Also two subsequences with different length should be considered different.
InputThe 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.OutputFor 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
大致题意是给定一个字符串,求回文子序列个数,最后的答案要%10007
首先定义f数组f[l][r]表示l~r区间的回文子序列个数,f[i][i]=1;
显然 根据容斥原理 :f[l][r]=f[l][r-1]+f[l+1][r]-f[l+1][r-1] (因为中间的个数会算两遍);
然后,我们考虑s[l]==s[r]的情况,如果这两个位置相等,那么l+1 ~ r-1这个区间的所有子序列,都可以加入l和r这两个元素,构成一个新的回文子序列,除此之外 l和r这两个元素也可以构成一个回文子序列
注意减的时候取模+要加模
代码:
#include<cstdio> #include<iostream> #include<cstring> #include<algorithm> #include<queue> #include<stack> #include<set> #include<vector> #include<map> #include<cmath> const int maxn=1e5+5; const int mod=10007; typedef long long ll; using namespace std; char str[1005]; ll dp[1005][1005]; int main() { int T; int cnt=1; cin>>T; for(int t=1;t<=T;t++) { scanf("%s",str+1); int len=strlen(str+1); memset(dp,0,sizeof(dp)); for(int t=1;t<=len;t++) { dp[t][t]=1; if(t<len&&str[t]==str[t+1]) { dp[t][t+1]=3; } else { dp[t][t+1]=2; } } for(int l=2;l<=len;l++) { for(int j=1;j+l<=len;j++) { int r=j+l; if(str[j]==str[r]) { dp[j][r]=(dp[j+1][r]+dp[j][r-1]+1)%mod; } else dp[j][r]=(dp[j][r-1]+dp[j+1][r]-dp[j+1][r-1]+mod)%mod; } } printf("Case %d: %lld\n",cnt++,dp[1][len]); } return 0; }
-------------------------------------------
个性签名:独学而无友,则孤陋而寡闻。做一个灵魂有趣的人!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!
万水千山总是情,打赏一分行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主,哈哈哈(っ•̀ω•́)っ✎⁾⁾!

浙公网安备 33010602011771号