Codeforces 1132 F 区间dp

http://codeforces.com/problemset/problem/1132/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

5
abaca

Output

3

Input

8
abcddcba

Output

4

题目大意:给一个长度为n的字符串,你可以消去任意个连续的相同字符,求把这个序列消除的最少操作次数。

思路:真dp全靠猜看着就像区间dp的题目。dp[i][j]表示删除[i,j]区间的序列所需要的最少操作数。最外层枚举区间长度len从2到n,(len-1为区间长度)内层枚举区间左端点i,i+len-1<=n,那么区间右端点j=i+len-1;最内层枚举断点k,若s[i]!=s[j],那么我们只能只能朴素的删除,即删除[i, k]和[k+1,j],;操作次数为:若dp[i][k]+dp[k+1][j];若[i]=s[j],那么我们可以先删除里面的,让i、j凑到一起删除,这样可以少做一次删除操作,操作次数为:dp[i][k]+dp[k+1][j]-1。(没错 dp方程也是猜的)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define INF 0x3f3f3f3f
typedef long long ll;
using namespace std;

char s[505];
int dp[505][505];

int main()
{
    int n;
    scanf("%d",&n);
    scanf("%s",s+1);
    memset(dp,INF,sizeof(dp));
    for(int i=1;i<=n;i++)
        dp[i][i]=1;
    for(int len=2;len<=n;len++)//len-1为区间长度
    {
        for(int i=1;i+len-1<=n;i++)
        {
            int j=i+len-1; //[i,j]
            for(int k=i;k<j;k++)
            {
                if(s[i]!=s[j])
                    dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]);
                else
                    dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]-1);
              //  cout<<i<<' '<<j<<' '<<dp[i][j]<<endl;
            }
        }
    }
    printf("%d\n",dp[1][n]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/xiji333/article/details/88345328