codeforces 607B. Zuma 区间dp

题目链接

给一个长度为n的序列, 每一次可以消去其中的一个回文串, 问最少几次才可以消完。

代码很清楚

#include <iostream>
#include <vector>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <string>
#include <queue>
using namespace std;
#define pb(x) push_back(x)
#define ll long long
#define mk(x, y) make_pair(x, y)
#define lson l, m, rt<<1
#define mem(a) memset(a, 0, sizeof(a))
#define rson m+1, r, rt<<1|1
#define mem1(a) memset(a, -1, sizeof(a))
#define mem2(a) memset(a, 0x3f, sizeof(a))
#define rep(i, a, n) for(int i = a; i<n; i++)
#define ull unsigned long long
typedef pair<int, int> pll;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int mod = 1e9+7;
const int inf = 1061109567;
const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
int dp[505][505], a[505];
int dfs(int l, int r) {
    if(dp[l][r])
        return dp[l][r];
    dp[l][r] = inf;
    if(l == r)
        return dp[l][r] = 1;
    if(r-l == 1)
        return dp[l][r] = (a[l]==a[r])?1:2;
    if(a[l] == a[r])
        dp[l][r] = dfs(l+1, r-1);
    for(int i = l; i<=r; i++) {
        dp[l][r] = min(dp[l][r], dfs(l, i)+dfs(i+1, r));
    }
    return dp[l][r];
}
int main()
{
    int n;
    cin>>n;
    for(int i = 1; i<=n; i++) {
        scanf("%d", &a[i]);
    }
    cout<<dfs(1, n);
    return 0;
}

 

posted on 2015-12-24 09:00  yohaha  阅读(244)  评论(0编辑  收藏  举报

导航