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

UVa 10617 - Again Palindrome 字符串dp

2013-05-02 20:19 357 查看

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

RussianOlympicCamp

----------------------
忽然发现我的字符串dp弱成渣啊。。。

f[i][j]表示从i到j的回文串个数。

当i!=j时,f[i][j]=f[i+1][j]+f[i][j-1]-f[i+1][j-1];从i到j的回文数=删除左边的字符后的回文数+删除右边字符后的回文数-重复部分

当i==j时,f[i][j]=f[i+1][j]+f[i][j-1]-f[i+1][j-1]+f[i+1][j-1]+1;从i到j的回文数=删除左边的字符后的回文数+删除右边字符后的回文数-重复部分+保留ij后的回文数+只留下ij的回文数即1

--------------------------

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
usingnamespacestd;

intT;
chars[111];
longlongf[111][111];
intn;

longlongdfs(intl,intr)
{
if(f[l][r]!=-1)returnf[l][r];
if(r-l<0)return0;
if(s[l]==s[r])
{
f[l][r]=dfs(l+1,r)+dfs(l,r-1)+1;
}
else
{
f[l][r]=dfs(l+1,r)+dfs(l,r-1)-dfs(l+1,r-1);
}
returnf[l][r];
}

intmain()
{
cin>>T;
while(T--)
{
memset(f,-1,sizeof(f));
cin>>(s+1);
n=strlen(s+1);
longlongans=dfs(1,n);
cout<<ans<<endl;
}
return0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: