nyoj749Splits the string(区间dp)

来源:互联网 发布:大数据修炼系统123 编辑:程序博客网 时间:2024/06/05 19:18

题目链接:click here~

题目解析:区间dp:从最初的状态开始,长度为1,为2,为3,.......一直到区间长度,然后还要保存之前的结果,因为后面的结果需要用到前面已经推出来的结果,同时这也是动态规划的思想,更多细节在代码中。

代码如下:

01.#include<stdio.h>
02.#include<string.h>
03.#include<iostream>
04.#include<algorithm>
05.using namespace std;
06.char str[1010];
07.int dp[1010];
08.bool check(int x,int y)
09.{
10.while(x<y)
11.{
12.if(str[x]!=str[y])
13.return false;
14.else
15.{
16.x++;
17.y--;
18.}
19.}
20.return true;
21.}
22.int main()
23.{
24.while(scanf("%s",str+1)!=EOF)
25.{
26.int len=strlen(str+1);
27.dp[0]=0;
28.for(int i=1;i<=len;i++)
29.{
30.dp[i]=i;
31.for(int j=1;j<=i;j++)
32.if(check(j,i))
33.dp[i]=min(dp[i],dp[j-1]+1);    //区间dp,如果j到i是回文的,则比较dp[j-1]再加上这个回文串和dp[i]
34.//的大小关系,取最小的,更新dp数组
35.}
36.printf("%d\n",dp[len]);
37.}
38.return 0;
39.}



0 0
原创粉丝点击