动态规划 BZOJ1584 [Usaco2009 Mar] Cleaning Up 打扫卫生

1584: [Usaco2009 Mar]Cleaning Up 打扫卫生

Time Limit: 10 Sec  Memory Limit: 64 MB
Submit: 511  Solved: 349
[Submit][Status][Discuss]

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

 

神奇的dp题,懒得写题解了,贴个链接

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

 

posted @ 2017-07-16 08:32  zwube  阅读(157)  评论(0编辑  收藏  举报