# [BZOJ1032][JSOI2007]祖码Zuma 区间dp

## 1032: [JSOI2007]祖码Zuma

Time Limit: 10 Sec  Memory Limit: 162 MB Submit: 1105  Solved: 576 [Submit][Status][Discuss]

## Sample Input

9
1 1 2 2 3 3 2 1 1

## Sample Output

1

 1 #include<iostream>
2 #include<cstring>
3 #include<cstdio>
4 #include<cstdlib>
5 #include<cmath>
6 #include<algorithm>
7 using namespace std;
8 int n;
9 int a[505];
10 int f[505][505];
11 int cnt[505];
12 int sum;
13 int main() {
14     scanf("%d",&n);
15     for(int i=1;i<=n;i++) scanf("%d",&a[i]);
16     a[0]=-10;
17     for(int i=1;i<=n;i++) {
18         if(a[i]==a[i-1]) {
19             cnt[sum]++;
20         }
21         else {
22             a[++sum]=a[i];
23             cnt[sum]=1;
24         }
25     }
26     memset(f,97,sizeof(f));
27     for(int i=1;i<=sum;i++) if(cnt[i]>1) f[i][i]=1;else f[i][i]=2;
28     for(int len=2;len<=sum;len++) {
29         for(int i=1;i+len-1<=sum;i++) {
30             int j=i+len-1;
31             for(int k=i;k<j;k++) f[i][j]=min(f[i][j],f[i][k]+f[k+1][j]);
32             if(a[i]==a[j]) {
33                 if(i+1==j) f[i][j]=1;
34                 else if(cnt[i]>1||cnt[j]>1) f[i][j]=min(f[i][j],f[i+1][j-1]);
35                 else f[i][j]=min(f[i][j],f[i+1][j-1]+1);
36             }
37         }
38     }
39     printf("%d",f[1][sum]);
40 }
View Code

posted @ 2017-10-17 15:58  wls001  阅读(138)  评论(0编辑  收藏  举报