lightoj-1044 - Palindrome Partitioning(区间dp)

1044 - Palindrome Partitioning
PDF (English) Statistics Forum
Time Limit: 1 second(s) Memory Limit: 32 MB
A palindrome partition is the partitioning of a string such that each separate substring is a palindrome.

For example, the string "ABACABA" could be partitioned in several different ways, such as {"A","B","A","C","A","B","A"}, {"A","BACAB","A"}, {"ABA","C","ABA"}, or {"ABACABA"}, among others.

You are given a string s. Return the minimum possible number of substrings in a palindrome partition of s.

Input
Input starts with an integer T (≤ 40), denoting the number of test cases.

Each case begins with a non-empty string s of uppercase letters with length no more than 1000.

Output
For each case of input you have to print the case number and the desired result.

Sample Input
Output for Sample Input
3
AAAA
ABCDEFGH
QWERTYTREWQWERT
Case 1: 1
Case 2: 8
Case 3: 5

 

解题:预处理好回文字符串,然后dfs。

但dp[l][r] = min(dp[l][r],dfs(l,i)+dfs(i+1,r)); 这种的dfs会爆

仔细分析下会发现 (回文字符串+一串字母) + 一串字母 跟 回文字符串+(一串字母+一串字母) 的情况是一样, 所以可能省略掉前面dfs(l,i)的情况

直接  if(judge[l][i])  dp[l][r] = min(dp[l][r],1+dfs(i+1,r));

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;

const int inf = 1e9;
int T,len;
char str[1100];
int dp[1100][1100];
bool judge[1100][1100];

void init(){
    memset(judge,false,sizeof(judge));
    memset(dp,-1,sizeof(dp));    
    
    for(int i=0;i<len;i++){
        for(int j=i;j<len;j++){
            int flag = 0;
            for(int z=i;z<=(i+j)/2;z++){
                if(str[z]!=str[j-(z-i)]){
                    flag = 1;break;
                }
            }
            if(flag == 0) judge[i][j] = true;
        }
    }    
}

int dfs(int l,int r){
    
    if(judge[l][r]){
        dp[l][r] = 1;
        return 1;
    }
    if(dp[l][r]!=-1) return dp[l][r];
    
    dp[l][r] = inf;
    for(int i=l;i<r;i++){    
    
        if(judge[l][i])    
            dp[l][r] = min(dp[l][r],1+dfs(i+1,r));            
        //dp[l][r] = min(dp[l][r],dfs(l,i)+dfs(i+1,r));        
    }
    return dp[l][r];
}

int main(){
    
    scanf("%d",&T);
    for(int t=1;t<=T;t++){
        
        scanf("%s",str);
        len = strlen(str);
        init();
        printf("Case %d: %d\n",t,dfs(0,len-1));
    }
    
    return 0;
}
View Code

 

转载于:https://www.cnblogs.com/yuanshixingdan/p/5540692.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值