Codeforces 1132 problem F Clear the String —— 区间DP

202 篇文章 6 订阅

You are given a string s of length n consisting of lowercase Latin letters. You may apply some operations to this string: in one operation you can delete some contiguous substring of this string, if all letters in the substring you delete are equal. For example, after deleting substring bbbb from string abbbbaccdd we get the string aaccdd.

Calculate the minimum number of operations to delete the whole string s.

Input
The first line contains one integer n (1≤n≤500) — the length of string s.

The second line contains the string s (|s|=n) consisting of lowercase Latin letters.

Output
Output a single integer — the minimal number of operation to delete string s.

Examples
inputCopy
5
abaca
outputCopy
3
inputCopy
8
abcddcba
outputCopy
4

题意:

给你一个字符串,你只能每次删除所有字符相同的子串,问你最少需要删几次。

题解:

不知道为什么向外扩一个的那种区间DP用不了,第五个样例太长了也找不出来原因,但是好像标准的区间DP就是在一个区间内枚举分成左右区间的情况来着?若果左端点与右区间的左端点相同的话就可以并起来。

#include<bits/stdc++.h>
using namespace std;
char s[505];
int dp[505][505];
int main()
{
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
            dp[i][j]=1e9;
        dp[i][i]=0;
    }
    scanf("%s",s+1);
    for(int len=1;len<n;len++)
    {
        for(int i=1;i+len<=n;i++)
        {
            dp[i][i+len]=min(dp[i][i+len],min(dp[i][i+len-1]+1,dp[i+1][i+len]+1));
            for(int j=i;j<i+len;j++)
                if(s[j+1]==s[i])
                    dp[i][i+len]=min(dp[i][i+len],dp[i][j]+dp[j+1][i+len]);
        }
    }
    printf("%d\n",dp[1][n]+1);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值