欢迎访问我的个人网站==》 jiashubing.cn

ZOJ 2744 Palindromes(动态规划)

Palindromes

Time 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

 1 # include<stdio.h>
 2 # include<string.h>
 3 # define maxn 5001
 4 char s[maxn];
 5 bool dp[maxn][maxn];
 6 
 7 int main()
 8 {
 9     int len,ans,i,j,k;
10     while(scanf("%s",s)!=EOF)
11     {
12         len=strlen(s);
13         ans=len;
14         memset(dp,0,sizeof(dp));
15         for(k=1;k<len;k++)
16         {
17             for(i=0;i<len-k;i++)
18             {
19                 j=i+k;
20                 dp[i][j]=0;
21                 if(s[i]==s[j])
22                 {
23                     if(i+1 <j-1)
24                     {
25                         if(dp[i+1][j-1])
26                         {
27                             dp[i][j]=1;
28                             ans++;
29                         }
30                     }
31                     else
32                     {
33                         dp[i][j]=1;
34                         ans++;
35                     }
36                 }
37             }
38         }
39         printf("%d\n",ans);
40     }
41     return 0;
42 }

 

posted @ 2013-03-18 16:40  贾树丙  阅读(314)  评论(0编辑  收藏  举报