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

题目连接: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

扫描二维码关注公众号,回复: 5680939 查看本文章
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;
}

猜你喜欢

转载自blog.csdn.net/Kuguotao/article/details/88317286