取出回文

【题目描述】:
给定长为n的字符串(n<=500),每次可以将连续一段回文序列消去,消去后左右两边会接到一起,求最少消去几次能消完整个序列。
【输入描述】:
一行一个由小写字母组成的字符串。
【输出描述】:
一个正整数,表示消去次数。
【样例输入】:
asbasda
【样例输出】:
3
【样例说明】:
“asbasda” -> “asasda” -> “asasa” -> “”
【时间限制、数据范围及描述】:
时间:1s 空间:64M
对于 30%的数据:n<=10;
对于 60%的数据:n<=500;
对于100%的数据:n<=1000;

【解题思路】
区间DP,一般都是枚举断开点,然后进行一些鬼畜 的计算

【code】

 1 #include<iostream>
 2 #include<cmath>
 3 #include<cstdio>
 4 #include<algorithm>
 5 #include<cstring>
 6 using namespace std;
 7 const int N=1005;
 8 char c[N],s;
 9 int f[N][N],len;
10 int main()
11 {
12     int l,i,j;
13     s=getchar();
14     while(s>='a'&&s<='z'){
15         c[++len]=s;
16         s=getchar();
17     }
18     memset(f,0x3f,sizeof(f));
19     for(i=1;i<=len;i++)
20         f[i][i]=1;
21     for(l=1;l<len;l++){
22         for(i=1;i+l<=len;i++){
23             j=i+l;
24             if(c[i]==c[j])
25             {
26                 f[i][j]=f[i+1][j-1];
27                 if(j==i+1)
28                     f[i][j]=1;
29             }
30             for(int k=i;k<j;k++)
31                 f[i][j]=min(f[i][k]+f[k+1][j],f[i][j]);
32         }
33     }
34     printf("%d\n",f[1][len]);
35     return 0;
36 }

 

posted @ 2019-07-15 12:08  GTR_PaulFrank  阅读(188)  评论(0编辑  收藏  举报