比赛的时候不会写。。。。参考网上题解的。。。http://blog.sina.com.cn/s/blog_4a0c4e5d0101dmwg.html
#include <iostream>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <climits>
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 505
#define maxm 600005
#define eps 1e-12
#define mod 998244353
#define INF 0x3f3f3f3f
#define PI (acos(-1.0))
#define lowbit(x) (x&(-x))
#define mp make_pair
#define ls o<<1
#define rs o<<1 | 1
#define lson o<<1, L, mid
#define rson o<<1 | 1, mid+1, R
#pragma comment(linker, "/STACK:102400000,102400000")
#define pii pair<int, int>
typedef long long LL;
typedef unsigned long long ULL;
//typedef int LL;
using namespace std;
LL qpow(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base;base=base*base;b/=2;}return res;}
LL powmod(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base%mod;base=base*base%mod;b/=2;}return res;}
// head
int dp[maxn][maxn];
int res[maxn];
int a[maxn];
int c[maxn];
int n;
void init()
{
memset(dp, INF, sizeof dp);
memset(res, INF, sizeof res);
}
int dfs(int L, int R)
{
if(dp[L][R] != INF) return dp[L][R];
if(L > R) return 0;
vector<pii> v;
for(int i = L; i <= R; i++) v.push_back(mp(a[i], i));
sort(v.begin(), v.end());
for(int i = v[0].second-1, p = 0; i >= L; i--) {
while(p < v.size() && v[p].second > i) p++;
dp[L][R] = min(dp[L][R], dfs(L, i) + dfs(i+1, R) + R - L + 1 - p);
}
for(int i = v[0].second, p = 0; i <= R; i++) {
while(p < v.size() && v[p].second <= i) p++;
dp[L][R] = min(dp[L][R], dfs(L, i) + dfs(i+1, R) + R - L + 1 - p);
}
return dp[L][R];
}
bool check(int L, int R)
{
memset(c, 0, sizeof c);
for(int i = L; i <= R; i++) c[a[i]]++;
bool ok = 1;
for(int i = 1; i <= R - L + 1; i++) if(!c[i]) ok = 0;
return ok;
}
void work()
{
for(int i = 1; i <= n; i++) scanf("%d", &a[i]);
for(int i = 1; i <= n; i++) dp[i][i] = 0;
dfs(1, n);
res[0] = 0;
for(int i = 1; i <= n; i++)
for(int j = 0; j < i; j++)
if(check(j+1, i))
res[i] = min(res[i], res[j] + dp[j+1][i]);
if(res[n] == INF) printf("impossible\n");
else printf("%d\n", res[n]);
}
int main()
{
while(scanf("%d", &n)!=EOF) {
init();
work();
}
return 0;
}