B-bookshelf 2Time
limit:1000MS
Memory Limit:65536KB
64bit IO Format:%lld &%llu< /c7> SubmitStatus
Description
Farmer John recently bought another bookshelf for the Cow library, but the shelf was getting filled up quite quickly, and N ow the only available space was at the top.
FJ have n cows (1≤ n ≤20) each with some height of hi (1≤ hi ≤1,000,000-these is Very tall cows). The bookshelf has a height of b (1≤ b ≤ S, where S are the sum of the heights of all C OWS).
To reach the top of the bookshelf, one or more of the cows can stand on top of each and the a stack, so that their total Height is the sum of each of their individual heights. This total height must is 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 was 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 1631356
Sample Output
1
Test instructions: There are n cows, bookshelf height m, to list the height of each cow, to ask the cow to stack up over the minimum height of the bookshelf.
Topic Idea: Find out all the heights that the cow can reach, and save it with dp[], and finally go through it, find out the dp[with the least H difference) is the answer.
Code:
#include <stdio.h>
#include <string.h>
#define MAX (A, B) (a > B a:b)
#define N 1000010
int main (void)
{
int dp[n];
int I, J, N, M;
int w[n];
while (scanf ("%d%d", &n, &m)! = EOF)
{
int sum = 0;//The total height of all cows combined.
memset (DP, 0, sizeof (DP));
for (i = 1; I <= n; i++)
{
scanf ("%d", &w[i]);
Sum + = W[i];
}
int ans = 0;
for (i = 1; I <= n; i++)
{
for (j = sum; J >= W[i], j--)//j to be inverted to ensure that Max Dp[j] and Dp[j] are saved when push Dp[j-w[i]].
{
DP[J] = max (Dp[j], Dp[j-w[i]] + w[i]);
}
}
for (i = 1; I <= sum; i++)//traverse the DP array to find the minimum height over the bookshelf to save the bounce loop directly.
{
if (Dp[i] >= m)
{
ans = dp[i];
Break
}
}
printf ("%d\n", ans-m);
}
return 0;
}
Bookshelf 2 01 Backpack