码迷,mamicode.com
首页 > 其他好文 > 详细

Palindrome subsequence (区间DP)

时间:2019-02-21 00:27:52      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:scan   exti   rem   i+1   sys   lower   mil   hang   部分   

Palindrome subsequence

 HDU - 4632 

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 = <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
题意:
  求字符串有多少回文子序列。(可以不连续)
题解:
  用dp[i][j]表示这一段里有多少个回文串,那首先dp[i][j]=dp[i+1][j]+dp[i][j-1],但是dp[i+1][j]和dp[i][j-1]可能有公共部分,即dp[i+1][j-1]是重复的,需要减去。如果s[l]==s[r],那么dp[l][r] = dp[l+1][r-1] + 1 。
 1 import java.util.Scanner;
 2 
 3 public class Main { 
 4     static int casen,mod = 10007;
 5     static int [][] dp ;
 6     static String s;
 7     public static void main(String[] args) {
 8         Scanner cin = new Scanner(System.in);
 9         casen = cin.nextInt();
10         int ca = 1;
11         while(casen-->0) {
12             s = cin.next();
13             dp = new int [s.length()+1][s.length()+1];
14             for(int i=0;i<s.length();i++) {
15                 dp[i][i] = 1;
16             }
17             for(int len=1;len<s.length();len++) {
18                 for(int l=0;l+len<s.length();l++) {
19                     int r = l+len;
20                     if(s.charAt(l)==s.charAt(r)) {
21                         dp[l][r] = (dp[l+1][r-1] + 1 + mod) % mod;
22                     }
23                     dp[l][r] = (dp[l][r] + dp[l][r-1] + dp[l+1][r] - dp[l+1][r-1] + mod) % mod;
24                 }
25             }
26             System.out.println("Case "+ ca++ + ": "+dp[0][s.length()-1]);
27         }
28     }
29 }
30  

 

Palindrome subsequence (区间DP)

标签:scan   exti   rem   i+1   sys   lower   mil   hang   部分   

原文地址:https://www.cnblogs.com/1013star/p/10409839.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!