【Codeforces 607 B. Zuma】

CF607B
容易看出是区间dp dp[l][r]代表 l 到 r 长度的最小代价
就是需要特判长度为 2
不然如果arr[l] == arr[r] dp[l][r] 可以直接由dp[l+1][r-1]转移过来
然后再枚举左右两部分枚举最小就行

/*
    if you can't see the repay
    Why not just work step by step
    rubbish is relaxed
    to ljq
*/
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

#define dbg(x) cout<<#x<<" = "<< (x)<< endl
#define dbg2(x1,x2) cout<<#x1<<" = "<#define dbg3(x1,x2,x3) cout<<#x1<<" = "<#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))

typedef pair<int,int> pll;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int _inf = 0xc0c0c0c0;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const ll _INF = 0xc0c0c0c0c0c0c0c0;
const ll mod =  (int)1e9+7;

ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
ll ksm(ll a,ll b,ll mod){int ans=1;while(b){if(b&1) ans=(ans*a)%mod;a=(a*a)%mod;b>>=1;}return ans;}
ll inv2(ll a,ll mod){return ksm(a,mod-2,mod);}
void exgcd(ll a,ll b,ll &x,ll &y,ll &d){if(!b) {d = a;x = 1;y=0;}else{exgcd(b,a%b,y,x,d);y-=x*(a/b);}}//printf("%lld*a + %lld*b = %lld\n", x, y, d);

/*namespace sgt
{
    #define mid ((l+r)>>1)

    #undef mid
}*/
const int MAX_N = 505;
int arr[MAX_N],dp[MAX_N][MAX_N];
int main()
{
    //ios::sync_with_stdio(false);
    //freopen("a.txt","r",stdin);
    //freopen("b.txt","w",stdout);
    int n;
    scanf("%d",&n);
    for(int i = 1;i<=n;++i) scanf("%d",&arr[i]);
    memset(dp,0x3f,sizeof(dp));
    for(int i = 1;i<=n;++i)
        dp[i][i] = 1;
    for(int len = 2;len<=n;++len)
    {
        for(int l = 1;l+len-1<=n;++l)
        {
            int r = l + len - 1;
            if(len==2)
            {
                if(arr[l]==arr[r])
                {
                    dp[l][r] = 1;
                }
                else dp[l][r] = 2;
                continue;
            }
            if(arr[l]==arr[r])
            {
                dp[l][r] = min(dp[l+1][r-1],dp[l][r]);
            }
            for(int k = l ;k<r;++k)
            {
                dp[l][r] = min(dp[l][k]+dp[k+1][r],dp[l][r]);
            }
        }
    }
    printf("%d\n",dp[1][n]);
    //fclose(stdin);
    //fclose(stdout);
    //cout << "time: " << (long long)clock() * 1000 / CLOCKS_PER_SEC << " ms" << endl;
    return 0;
}

你可能感兴趣的:(ACM,DP,区间dp)