loj 1044(dp+记忆化搜索)

来源:互联网 发布:java编写小程序 编辑:程序博客网 时间:2024/05/16 12:21

题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=26764

思路:dp[pos]表示0-pos这段字符串最少分割的回文子串,然后记忆化搜索(判断是否是回文子串的时候也用一个数组来记录是否是回文子串,记忆化搜索)。

 1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 using namespace std; 6 #define MAXN 1111 7 #define inf 1<<30 8 #define FILL(a,b) memset(a,b,sizeof(a)) 9 10 int len,dp[MAXN];11 int is_ok[MAXN][MAXN];12 char str[MAXN];13 14 int Judge(int l,int r)15 {16     if(l>r)return 1;17     if(is_ok[l][r]!=-1)return is_ok[l][r];18     if(str[l]!=str[r])return is_ok[l][r]=0;19     return is_ok[l][r]=Judge(l+1,r-1);20 }21 22 int dfs(int pos)23 {24     if(pos>=len)return 0;25     if(dp[pos]!=inf)return dp[pos];26     for(int i=pos;i<len;i++){27         if(Judge(pos,i))dp[pos]=min(dp[pos],dfs(i+1)+1);28     }29     return dp[pos];30 }31 32 int main()33 {34     int _case,t=1;35     scanf("%d",&_case);36     while(_case--){37         scanf("%s",str);38         len=strlen(str);39         FILL(is_ok,-1);40         fill(dp,dp+len,inf);41         printf("Case %d: %d\n",t++,dfs(0));42     }43     return 0;44 }
View Code

 

0 0