| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 8271 | Accepted: 3772 |
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
小结:
01背包水题,不过我打算从头开始,我感觉我对于DP的感觉还很弱,所以我打算慢慢建立所谓的感觉,“欲速则不达”。
说实话,我真的不知道,怎么样才算超时,怎么样才算超内存。
以下是AC代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define maxn 1000050
int dp[1000050];
int height[30];
int min(int a,int b)
{
return a<b?a:b;
}
int main()
{
int num1,num2,sum=0;
scanf("%d%d",&num1,&num2);
//Init();
for(int i=1;i<=1000000;i++)
dp[i]=0;
dp[0]=1;
//printf("a\n");
for(int i=1;i<=num1;i++)
{
scanf("%d",&height[i]);
sum+=height[i];
int temp=min(sum,1000000);
for(int j=temp;j>=height[i];j--)
{
if(dp[j-height[i]])
dp[j]=1;
}
}
//printf("a\n");
for(int i=num2;;i++)
{
if(dp[i])
{
printf("%d\n",i-num2);
break;
}
}
return 0;
}

980

被折叠的 条评论
为什么被折叠?



