Bookshelf题解动态规划DP
2010-08-01 19:32
211 查看
Description
Robby bought a new bookshelf, and he wanted to put all his N books on it. The bookshelf contains K layers, and the heights of each layer are variable. That is, the minimum height of one layer is equal to the maximum height of all the books in this layer. And the height of the bookshelf is the sum of all layers' heights. Now Robby wants to make the height of his bookshelf as low as possible, but he don't want to break the order of the books, that is, each layer must contain the consecutive books of the original book series. And each layer must contain at least one book.Input
There are several test cases in the input. The first line of each test case contains two integers N and K (1 ≤ K ≤ N ≤ 100). The second line contains N integers, indicating the heights of the books. You can assume the height of every book is no more than 1000. The input is terminated with N = K = 0.Output
Output one line for each test case, that is, the minimum height of the bookshelf.Sample Input
4 2 1 4 2 3 4 2 4 1 2 3 4 4 1 2 3 4 0 0Sample Output
5 7 10Hint
For the first sample, the best strategy is 1+max(4,2,3)=5 For the second sample, the best strategy is max(4,1,2)+3=7 For the third sample, the best strategy is 1+2+3+4=10Source
TJU Programming Contest 2007 by RoBa
有序的划分模型
关键是要确定第i本书要放到那层书架上。
另dp[i][j]为第i本书放到第j层书架上时的总高度的最小值。 则dp [k]即为所求。 dp[i][0]=INF
对于第i本书,能放到的书架层数x是有个范围的。 对于第x层书架,能放进去的书也是有个范围的。
dp[i][j]=min{dp[k-1][j-1]+M[k][i],k>=j&&k<=i} ①单独放到j层书架上。 ②第k本书到第i本书放到第j层书架上。 取最小值 其中M[k][i]需要预处理出来第k本书到第i本书之间(包含)的最大书本高度。
因此算法复杂度为O(n^3).
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; int n,m,a[105],mm[105][105],dp[105][105]; int main() { while(scanf("%d%d",&n,&m),n+m) { int i,j,k; for(i=1;i<=n;i++) scanf("%d",a+i); memset(dp,0,sizeof(dp)); for(i=1;i<=n;i++) { mm[i][i]=a[i]; dp[i][0]=999999999; for(j=i+1;j<=n;j++) { mm[i][j]=mm[i][j-1]; if(a[j]>mm[i][j-1]) mm[i][j]=a[j]; } } for(i=1;i<=n;i++) for(j=max(1,m+i-n);j<=i;j++) { int t=999999999; for(k=j;k<=i;k++) if(dp[k-1][j-1]+mm[k][i]<t) t=dp[k-1][j-1]+mm[k][i]; dp[i][j]=t; } printf("%d/n",dp [m]); } }
相关文章推荐
- 【DP】hotel 题解 浅谈动态规划中的状态设计方法
- (动态规划专题)3.25 校内赛 题解(balance)(hill)(draw)(knight)
- 动态规划(DP),最长递增子序列(LIS)
- 华为训练题目:初级——合唱队(递增子序列,DP动态规划问题)
- uva 11795 Mega Man's Mission(动态规划-状态压缩DP)
- leetcode 322. Coin Change 类似背包问题 + 很简单的动态规划DP解决
- 动态规划和背包dp问题
- 动态规划入门(四)DP 基本思想与实现
- HDU 2851.Lode Runner【DP动态规划】【5月11】
- 动态规划、贪心、dynamic programming(DP)
- 动态规划之编号动态规划:hdu 1025(dp+二分 求最长上升子序列)
- 动态规划入门(二)DP 基本思想 具体实现 经典题目 POJ1088 POJ1163 POJ1050
- 动态规划DP问题分类和经典题型
- leetcode 413. Arithmetic Slices 等差子数组 + 一个很简单DP动态规划做法
- HDU 4050 wolf5x(动态规划-概率DP)
- 算法笔记:动态规划(DP)初步
- 100道动态规划——13 UVA 10163 Storage Keepers 有约束条件下的DP,递推,不能使用结构体作为基本单位
- Hdu1087-Super Jumping! Jumping! Jumping!-【dp动态规划】
- DP动态规划【专辑@AbandonZHANG】
- 2.6基本算法之动态规划 7624:山区建小学——区间DP