[Codeforces 607B Zuma]区间DP

[Codeforces 607B Zuma]区间DP

分类:区间DP

1. 题目链接

[Codeforces 607B Zuma]

2. 题意描述

给出一个长度为n的序列c[i],每次操作可以删去一个回文子串,求将整个序列删除完需要的最少操作数。
(1n500,1cin)

3. 解题思路

比较直观的区间DP,dp[i][j]表示从i到j的最少操作次数。枚举区间 [i+1,j] 中与 ci 相同的元素 ck=ci,k[i+1,j] ,那么,有转移方程:

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

这样时间复杂度就是 O(n3)

4. 实现代码

#include <bits/stdc++.h>
using namespace std;

typedef long long LL;
typedef long double LB;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;

const int INF = 0x3f3f3f3f;
const LL INFL = 0x3f3f3f3f3f3f3f3fLL;
const LB eps = 1e-8;
const int MAXN = 500 + 5;

int n, c[MAXN], dp[MAXN][MAXN];

template<typename T> void umin(T& x, T y) { x = min(x, y); }

int main() {
#ifdef ___LOCAL_WONZY___
    freopen("input.txt", "r", stdin);
#endif // ___LOCAL_WONZY___
    while(~scanf("%d", &n)) {
        memset(dp, 0x3f, sizeof(dp));
        for(int i = 1; i <= n; ++i) {
            scanf("%d", &c[i]);
            dp[i][i] = 1;
        }
        for(int len = 2; len <= n; ++len) {
            for(int i = 1; i + len - 1 <= n; ++i) {
                int j = i + len - 1;
                umin(dp[i][j], dp[i + 1][j] + 1);
                umin(dp[i][j], dp[i][j - 1] + 1);
                for(int k = i + 1; k <= j; ++k) {
                    if(c[i] == c[k]) {
                        int a = i + 1 <= k - 1 ? dp[i + 1][k - 1] : 1;
                        int b = k + 1 <= j ? dp[k + 1][j] : 0;
                        umin(dp[i][j], a + b);
                    }
                }
            }
        }
        printf("%d\n", dp[1][n]);
    }
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值