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;
}