【题目链接】​点击打开链接​

【题意】给出一个长度为n的序列c[i],每次操作可以删去一个回文子串,求将整个序列删除完需要的最少操作数,n<=500

【解题方法】区间DP.区间dp,记dp[i][j]为删完[i,j]这一段的最少操作次数,一种移是枚举一个k,将这一段分为[i,k]和[k+1,j]两段分别删,那么有dp[i][j]=min(dp[i][k]+dp[k+1][j]),另一种转移是如果满足c[i]==c[j],那么在删完[i+1,j-1]的最后一步时可以顺带把c[i]和c[j]一起删掉,那么有dp[i][j]=min(dp[i-1][j+1]),复杂度O(n^3)


下面代码注释掉的是记忆化搜索的方式,没注释的是区间DP的标准时间。从通过的表现时间来看,普通的区间DP比记忆化好了许多。


//
//Created by just_sort 2016/1/6
//Copyright (c) 2016 just_sort.All Rights Reserved
//

//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
//#include <ext/pb_ds/hash_policy.hpp>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cmath>
#include <cstdio>
#include <time.h>
#include <cstdlib>
#include <cstring>
#include <sstream> //isstringstream
#include <iostream>
#include <algorithm>
using namespace std;
//using namespace __gnu_pbds;
typedef long long LL;
typedef pair<int, LL> pp;
#define REP1(i, a, b) for(int i = a; i < b; i++)
#define REP2(i, a, b) for(int i = a; i <= b; i++)
#define REP3(i, a, b) for(int i = a; i >= b; i--)
#define CLR(a, b) memset(a, b, sizeof(a))
#define MP(x, y) make_pair(x,y)
const int maxn = 2010;
const int maxm = 2e5;
const int maxs = 10;
const int maxp = 1e3 + 10;
const int INF = 1e9;
const int UNF = -1e9;
const int mod = 1e9 + 7;
int gcd(int x, int y) {return y == 0 ? x : gcd(y, x % y);}
//typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update>order_set;
//head
//int n, c[510], dp[510][510];
//void dfs(int l, int r){
// if(dp[l][r] < INF) return;
// if(r <= l){
// dp[l][r] = 1;
// return ;
// }
// int tl = l, tr = r;
// while(tl < tr && c[tl] == c[tr]){
// tl++; tr--;
// dfs(tl, tr);
// dp[l][r] = min(dp[l][r], dp[tl][tr]);
// }
// REP1(k, l, r){
// dfs(l, k);
// dfs(k + 1, r);
// dp[l][r] = min(dp[l][k] + dp[k + 1][r], dp[l][r]);
// }
//}
//int main()
//{
// cin >> n;
// REP2(i, 1, n) cin >> c[i];
// REP1(i, 0, 510){
// REP1(j, 0, 510){
// dp[i][j] = INF;
// }
// }
// dfs(1, n);
// cout << dp[1][n] << endl;
// return 0;
//}

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

int main()
{
cin >> n;
for(int i = 1; i <= n; i++) cin >> c[i];
for(int i = 1; i < 510; i++){
for(int j = 1; j < 510; j++){
dp[i][j] = INF;
}
}
for(int i = 1; i <= n; i++) dp[i][i] = 1;
for(int len = 2; len <= n; len++){
for(int i = 1; i + len - 1 <= n; i++){
if(c[i] == c[i + len - 1])
{
if(len == 2) dp[i][i + 1] = 1;
else dp[i][i + len - 1] = min(dp[i + 1][i + len - 2], dp[i][i + len - 1]);
}
else{
dp[i][i + len - 1] = INF;
}
for(int j = i; j < i + len - 1; j++){
dp[i][i + len - 1] = min(dp[i][i + len - 1], dp[i][j] + dp[j + 1][i + len - 1]);
}
}
}
cout << dp[1][n] << endl;
}