Educational Codeforces Round 61 (Rated for Div. 2) F. Clear the String (DP)

给定一个长度为n的只包含小写字母的字符串s,每步可以删除所有相同字符的连续子串。求删除整个字符串s所需的最小操作数。输入包含字符串长度n和字符串s本身,输出需要的最小操作次数。示例展示了不同输入下的输出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目连接:http://codeforces.com/contest/1132/problem/F

You are given a string ss of length nn 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 ss.

Input

The first line contains one integer nn (1≤n≤5001≤n≤500) — the length of string ss.

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

Output

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

Examples

input

Copy

5
abaca

output

Copy

3

input

Copy

8
abcddcba

output

Copy

4

题意: 给你一个只包含小写字符的字符串,你可以删除连续相同的一段字符,问最少需要几次操作完全删除这个字符串

#include<cstdio>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<cmath>
#include<vector>
#include<cstring>
#include<string>
#include<iostream>
#include<iomanip>
#define mset(a,b)   memset(a,b,sizeof(a))
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
//const ll mod=1e9+7;
const int N=1000000;
const int inf=0x3f3f3f3f;
//priority_queue<int,vector<int>,greater<int> >q;
char s[505];
int dp[505][505];
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        scanf("%s",s);
        for(int i=0;i<n;i++)
            dp[i][i]=1;
        for(int len=1;len<=n;len++)
        {
            for(int i=0,j=len;i<=n,j<=n;i++,j++)
            {
                if(s[i]==s[j])//如果i和j的字母相同
                    dp[i][j]=dp[i+1][j-1]+1;
                else//不相同
                    dp[i][j]=min(dp[i][j-1],dp[i+1][j])+1;
                for(int k=i;k<=j;k++)
                {
                    dp[i][j]=min(dp[i][j],dp[i][k]+dp[k][j]-1);
                }
            }
        }
        printf("%d\n",dp[0][n-1]);
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值