回文串数dp(uvaAgain Palindromes )
2015-03-14 16:09
435 查看
Problem I
Again Palindromes
Input: Standard Input
Output: Standard OutputTime Limit: 2 Seconds
A palindorme is a sequence of one or more characters that reads the same from the left as it does from the right. For example,
Z, TOT and MADAM are palindromes, but
ADAM is not.
Given a sequence S of N capital latin letters. How many ways can one score out a few symbols (maybe 0) that the rest of sequence become a palidrome. Varints that are only different by an order of scoring out should be considered
the same.
Input
The input file contains several test cases (less than 15). The first line contains an integerT that indicates how many test cases are to follow.
Each of the T lines contains a sequence S (1≤N≤60). So actually each of these lines is a test case.
Output
For each test case output in a single line an integer – the number of ways.Sample Input Output for Sample Input
3 BAOBAB
AAAA
ABA
22
15
5
题意:给定一个字符串,然后可以删除一些字符形成回文串,问有多少种删除方法
思路:dp[i][j]表示区间(i,j)有多少个回文串。如果s[i]==s[j],那么要加上(i+1,j),(i,j-1)之间的回文串,因为两个都计算了(i+1,j-1)的串,所以要减掉,s[i],s[j]跟(i+1,j-1)之间的回文串也可以组成回文串,所以要加上
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
typedef long long LL;
const int maxn=70;
int N;
char s[maxn];
LL dp[maxn][maxn];
LL DP(int l,int r)
{
if(dp[l][r]!=-1)return dp[l][r];
if(l>r)return dp[l][r]=0;
if(l==r)return dp[l][r]=1;
LL &ans=dp[l][r];
ans=0;
if(s[l]==s[r])ans=DP(l+1,r)+DP(l,r-1)+1;
else ans=DP(l+1,r)+DP(l,r-1)-DP(l+1,r-1);
return ans;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%s",s);
memset(dp,-1,sizeof(dp));
int len=strlen(s);
printf("%lld\n",DP(0,len-1));
}
return 0;
}
相关文章推荐
- UVa 10617 Again Palindromes / 记忆化搜索
- UVa 10617 Again Palindromes / 记忆化搜索
- uva 507 Jill Rides Again
- UVa_401 - Palindromes
- UVa 19780 Again Prime?No time. (质因数分解)
- UVa10976 - Fractions Again?!
- uva507 - Jill Rides Again(JIll又骑车了)
- UVA10780:Again Prime? No Time(数论)
- 章三例题3——UVA 401 Palindromes
- Fractions Again?! UVA - 10976
- UVA 11584 - Partitioning by Palindromes DP
- UVA 题目401 - Palindromes
- 字符串训练 ------- UVA 题目401 - Palindromes
- UVA-10780-Again Prime? No Time(素数分解)
- Partitioning by Palindromes UVA - 11584
- UVA 10494 - If We Were a Child Again
- UVA - 10976 Fractions Again?!(水题)
- UVA 11584-Partitioning by Palindromes(DP)
- UVA 10494 - If We Were a Child Again
- UVA 10976 - Fractions Again?!