您的位置:首页 > 其它

ZOJ 2744 Palindromes(动态规划)

2013-03-18 16:40 267 查看
PalindromesTime Limit: 2 Seconds Memory Limit: 65536 KB
A regular palindrome is a string of numbers or letters that is the same forward as backward. For example, the string "ABCDEDCBA" is a palindrome because it is the same when the string is read from left to right as when the string is read from right to left.

Now give you a string S, you should count how many palindromes in any consecutive substring of S.

Input

There are several test cases in the input. Each case contains a non-empty string which has no more than 5000 characters.

Proceed to the end of file.

Output

A single line with the number of palindrome substrings for each case.

Sample Input

aba
aa

Sample Output

4
3

做了一下午的动态规划,才发现懂得只有那么一点点,大部分还是百度出来才能理解状态转移方程,这一道,算是自己思考的最多的一道吧

令d[i][j]表示这一串字符从第i个到第j个字符组成的串是否是回文。

如果 i 到 j 组成的串字符超过了3个,则必须满足 i-1 到j-1 个字符组成的串是回文,它才有可能是回文

初始条件是:数组所有数据为0

# include<stdio.h>
# include<string.h>
# define maxn 5001
char s[maxn];
bool dp[maxn][maxn];

int main()
{
int len,ans,i,j,k;
while(scanf("%s",s)!=EOF)
{
len=strlen(s);
ans=len;
memset(dp,0,sizeof(dp));
for(k=1;k<len;k++)
{
for(i=0;i<len-k;i++)
{
j=i+k;
dp[i][j]=0;
if(s[i]==s[j])
{
if(i+1 <j-1)
{
if(dp[i+1][j-1])
{
dp[i][j]=1;
ans++;
}
}
else
{
dp[i][j]=1;
ans++;
}
}
}
}
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: