概述
Bookshelf 2
题目链接http://poj.org/problem?id=3628
Time Limit: 1000MS Memory Limit: 65536K
Description
Farmer John recently bought another bookshelf for the cow library, but the shelf is getting filled up quite quickly, and now the only available space is at the top.
FJ has N cows (1 ≤ N ≤ 20) each with some height of Hi (1 ≤ Hi ≤ 1,000,000 - these are very tall cows). The bookshelf has a height of B (1 ≤ B ≤ S, where S is the sum of the heights of all cows).
To reach the top of the bookshelf, one or more of the cows can stand on top of each other in a stack, so that their total height is the sum of each of their individual heights. This total height must be no less than the height of the bookshelf in order for the cows to reach the top.
Since a taller stack of cows than necessary can be dangerous, your job is to find the set of cows that produces a stack of the smallest height possible such that the stack can reach the bookshelf. Your program should print the minimal ‘excess’ height between the optimal stack of cows and the bookshelf.
Input
- Line 1: Two space-separated integers: N and B
- Lines 2…N+1: Line i+1 contains a single integer: Hi
Output
- Line 1: A single integer representing the (non-negative) difference between the total height of the optimal set of cows and the height of the shelf.
Sample Input
5 16
3
1
3
5
6
Sample Output
1
题目大意:给你N头牛,和一个架子的高度,你可以将牛一层层叠上去,使得最后一头牛能够够到书架的顶部,然后让我们计算最后一头牛与架子的最小高度差。
看出这是01背包并不难,唯一的难点就是我们的dp的上限在哪?可以想一想,如果我们以架子的高度m为上限,它可能无法达到架子的顶部,所以要在m的基础上加一点点,那到底要加多少呢?这个我们无法知晓,所以我们只能枚举:枚举从m到所有牛的高度之和,那么我们就应该先将dp[1–所以牛高度之和]求解出来(01背包直接用):
for (int i=1; i<=n; i++)
for (int j=sum; j>=h[i]; j--)
dp[j]=max(dp[j],dp[j-h[i]]+h[i]);
然后筛选:
for (int i=1; i<=sum; i++)
if (dp[i]>=m) {
printf ("%dn",dp[i]-m);
return 0;
}
整体AC代码:
#include <cstdio>
#include <algorithm>
using namespace std;
int dp[20000100],h[30];
int max(int a,int b)
{
return a>b?a:b;
}
int main()
{
int n,m,sum=0;
scanf ("%d%d",&n,&m);
for (int i=1; i<=n; i++){
scanf ("%d",&h[i]);
sum+=h[i];
}
sort(h+1,h+1+n);
for (int i=1; i<=n; i++)
for (int j=sum; j>=h[i]; j--)
dp[j]=max(dp[j],dp[j-h[i]]+h[i]);
for (int i=m; i<=sum; i++){
if (dp[i]>=m) {
printf ("%dn",dp[i]-m);
return 0;
}
}
return 0;
}
最后
以上就是无辜白羊为你收集整理的POJ-3628-Bookshelf 2(枚举+01背包)Bookshelf 2的全部内容,希望文章能够帮你解决POJ-3628-Bookshelf 2(枚举+01背包)Bookshelf 2所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复