标签:
Given a string, calculate the number of subsequences that are palindrome. A palindrome is a sequence of characters that reads the same backward or forward. For example, in the string “aba”, there are 7 subsequences "a", "b", "a", "ab", "aa", "ba", "aba". Only "a", "b", "a", "aa", "aba" are palindrome. Two subsequences that contain characters from different positions are considered different.
The first line of input contains a single integer T specifying the number of test cases. In each test case, there is only one line containing a string.
For each test case, output a line containing "Case #X: Y", where X is the test case number starting from 1, followed by one integer Y indicating the number of palindrome subsequences. Output the answer modulo 100007.
1 ≤ T ≤ 30
Small
Length of string ≤ 25
Large
Length of string ≤ 1000
Sample Input
5 aba abcbaddabcba 12111112351121 ccccccc fdadfa
Sample Output
Case #1: 5 Case #2: 277 Case #3: 1333 Case #4: 127 Case #5: 17
Solution:
典型的动态规划问题, TALK IS CHEAP......
1 #include <iostream> 2 #include <vector> 3 #include <cstdio> 4 #include <cstring> 5 using namespace std; 6 typedef long long LL; 7 const LL MOD = 100007; 8 9 10 LL palindromeSeq(char *s, int i, int j, vector<vector<LL> > &dp) { 11 if ( i > j) return 0; 12 if (i == j) return 1; 13 if (dp[i][j] >= 0) return dp[i][j]; 14 if (s[i] == s[j]) { 15 dp[i][j] = 1 + (palindromeSeq(s, i+1, j, dp)%MOD) + (palindromeSeq(s, i, j-1, dp)%MOD); 16 17 } 18 else { 19 dp[i][j] = ((- (palindromeSeq(s, i+1, j-1, dp)%MOD) + MOD)%MOD) + 20 (palindromeSeq(s, i+1, j, dp)%MOD) + 21 (palindromeSeq(s, i, j-1, dp)%MOD); 22 23 } 24 return dp[i][j] = dp[i][j] %MOD; 25 26 } 27 28 int main() { 29 int T; 30 cin >> T; 31 for (int k = 1; k <= T; ++k) { 32 char buf[1010]; 33 scanf("%s", buf); 34 int len = strlen(buf); 35 vector<vector<LL> > dp(len, vector<LL>(len, -1)); 36 cout << "Case #" << k << ": " << palindromeSeq(buf, 0, len-1, dp) << endl; 37 } 38 39 }
标签:
原文地址:http://www.cnblogs.com/liew/p/4741026.html