[dp] Bzoj P1584 打扫卫生

 

Description

有N头奶牛,每头那牛都有一个标号Pi,1 <= Pi <= M <= N <= 40000。现在Farmer John要把这些奶牛分成若干段,定义每段的不河蟹度为:若这段里有k个不同的数,那不河蟹度为k*k。那总的不河蟹度就是所有段的不河蟹度的总和。

Input

第一行:两个整数N,M

第2..N+1行:N个整数代表每个奶牛的编号

Output

一个整数,代表最小不河蟹度

Sample Input

13 4
1
2
1
3
2
2
3
4
3
4
3
1
4

Sample Output

11

 

题解

  • 很容易想到f[i]表示前i个最优答案
  • 直接DP复杂度过不去,我们思考如何优化
  • 注意到如果选取的最后一段超过了根号个种类,那一定不是最优答案,因为n是一种可行解
  • 所以,用数组b[k]表示最小的j使得[j,i]有k个种类
  • 然后每次计算f[i],枚举k,只需要枚举根号
  • 每次i右移时,就更新b数组

 

代码

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <cstring>
 4 #include <cmath> 
 5 #define N 210
 6 using namespace std;
 7 int n,m,tot,a[N*N],f[N*N],b[N],cnt[N],pre[N*N];
 8 int main()
 9 {
10     scanf("%d%d",&n,&m);
11     for (int i=1,x;i<=n;i++) 
12     {
13         scanf("%d",&x);
14         if (x!=a[tot]) a[++tot]=x;
15     }
16     memset(f,63,sizeof(f)),memset(pre,-1,sizeof(pre)),n=tot,m=sqrt(n),f[0]=0;
17     for (int i=1;i<=n;i++)
18     {
19         for (int j=1;j<=m;j++) if (pre[a[i]]<=b[j]) cnt[j]++;
20         pre[a[i]]=i;
21         for (int j=1;j<=m;j++)
22             if (cnt[j]>j)
23             {
24                 int r=b[j]+1;
25                 while (pre[a[r]]>r)    r++;
26                 b[j]=r,cnt[j]--;
27             } 
28         for (int j=1;j<=m;j++) f[i]=min(f[i],f[b[j]]+j*j);
29     } 
30     printf("%d",f[n]);
31 } 

 

posted @ 2019-07-10 16:45  BEYang_Z  阅读(154)  评论(0编辑  收藏  举报