您的位置:首页 > 大数据 > 人工智能

Again Palindromes - UVa 10617 dp

2014-07-31 15:11 561 查看

ProblemI

AgainPalindromes

Input:StandardInput

Output:StandardOutput
TimeLimit:2Seconds

Apalindormeisasequenceofoneormorecharactersthatreadsthesamefromtheleftasitdoesfromtheright.Forexample,Z,TOTandMADAMarepalindromes,butADAMisnot.



GivenasequenceSofNcapitallatinletters.Howmanywayscanonescoreoutafewsymbols(maybe0)thattherestofsequencebecomeapalidrome.Varintsthatareonlydifferentbyanorderofscoringoutshouldbeconsidered
thesame.



Input

Theinputfilecontainsseveraltestcases(lessthan15).ThefirstlinecontainsanintegerTthatindicateshowmanytestcasesaretofollow.



EachoftheTlinescontainsasequenceS(1≤N≤60).Soactuallyeachoftheselinesisatestcase.



Output

Foreachtestcaseoutputinasinglelineaninteger–thenumberofways.


SampleInputOutputforSampleInput

3

BAOBAB

AAAA

ABA

22

15

5

题意:删除字符串中任意数量的字符,使得其成为一个回文串,问这种删法一共有多少种,不删也算一种。

思路:还是从边上往中间递推if(s[l]==s[r])  dp[l][r]=dp[l+1][r]+dp[l][r-1]+1;  elsedp[l][r]=dp[l+1][r]+dp[l][r-1]-dp[l+1][r-1];

AC代码如下:

#include<cstdio>
#include<cstring>
usingnamespacestd;
longlongdp[100][100],;
chars[110];
voiddfs(intl,intr)
{if(dp[l][r]>=0)
return;
if(l>r)
{dp[l][r]=0;
return;
}
dfs(l+1,r);
dfs(l,r-1);
dfs(l+1,r-1);
if(s[l]==s[r])
dp[l][r]=dp[l+1][r]+dp[l][r-1]+1;
else
dp[l][r]=dp[l+1][r]+dp[l][r-1]-dp[l+1][r-1];
}
intmain()
{intt,n,m,i,j,k,len;
scanf("%d",&t);
while(t--)
{scanf("%s",s+1);
len=strlen(s+1);
memset(dp,-1,sizeof(dp));
for(i=1;i<=len;i++)
dp[i][i]=1;
dfs(1,len);
printf("%lld\n",dp[1][len]);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: