cf Educational Codeforces Round 61 F. Clear the String

原題:
F. Clear the String
time limit per test3 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
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
input
5
abaca
output
3
input
8
abcddcba
output
4

中文:

給你一個字符串,每次可以去掉字符串中的一個連續的子串,這個連續的子串必須所有的字符都相同,問你最少去掉多少次可以將整個字符串去掉。

代碼:

#include<bits/stdc++.h>
using namespace std;
 
typedef long long ll;
const int maxn=501;
int dp[maxn][maxn];
int n;
char s[maxn];
 
int main()
{
    ios::sync_with_stdio(false);
    while(cin>>n)
    {
        cin>>&s[1];
        memset(dp,0,sizeof(dp));
        for(int i=1;i<=n;i++)
            dp[i][i]=1;
 
        for(int len=1;len<n;len++)
        {
            for(int i=1;i<=n-len;i++)
            {
                int j=i+len;
                dp[i][j]=dp[i+1][j]+1;
                for(int k=i+1;k<=j;k++)
                {
                    if(s[i]==s[k])
                        dp[i][j]=min(dp[i][j],dp[i+1][k-1]+dp[k][j]);
                }
            }
        }
        cout<<dp[1][n]<<endl;
    }
    return 0;
}

思路:

區間dp

設置狀態爲dp[i][j]表示i到j的子串全部去掉需要的最少步數,設字符串爲s

狀態轉移方程爲

dp[i][j]=min(dp[i+1][j]+1,dp[i+1][k1]+dp[k][j]) dp[i][j]=min(dp[i+1][j]+1,dp[i+1][k-1]+dp[k][j])

dp[i+1][j]+1dp[i+1][j]+1表示去掉第i個字符,
dp[i+1][k1]+dp[k][j]dp[i+1][k-1]+dp[k][j]表示當第k個字符與第i個字符相同時,想要去掉所有在區間i到k-1中與s[i]相同的字符,此時在區間[i+1,k1][i+1,k-1]去掉使得字符s[i]與s[k]相鄰

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章