Poj 3628 bookshelf 2: http://poj.org/problem? Id = 3628
There is a bookshelf with a height of B. Now FJ has n cows, each of which has a height of hi. Now we pile up the cows so that the height of the heap is greater than or equal to B, the minimum height difference is required.
Thought 1: 01 backpack: the total height of the cow minus B, is the capacity of the backpack, fill it, find the maximum size and the capacity of the backpack to do the difference, the result is him.
Code:
1 #include<stdio.h> 2 #include<string.h> 3 int w[100],f[20000000]; 4 int max(int a,int b) 5 { 6 return a>b?a:b; 7 } 8 int main() 9 {10 int n,b,i,j;11 int sum=0;12 while(scanf("%d%d",&n,&b)!=EOF)13 {14 for(i=0;i<=n;i++)15 f[i]=0;16 sum=0;17 for(i=0; i<n; i++)18 {19 scanf("%d",&w[i]);20 sum+=w[i];21 }22 int k=sum-b;23 for(i=0; i<n; i++)24 {25 for(j=k; j>=w[i]; j--)26 {27 f[j]=max(f[j],f[j-w[i]]+w[i]);28 }29 }30 printf("%d\n",k-f[k]);31 }32 return 0;33 }
Train of Thought 2: DFS: (transfer)
1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 #include <cstring> 5 using namespace std; 6 #define maxn 25 7 int n, m; 8 int f[maxn], s[maxn]; 9 int ans;10 void dfs(int cow, int sum)11 {12 if (ans == 0)13 return;14 if (s[cow] + sum < m)15 return;16 if (sum >= m)17 {18 ans = min(ans, sum - m);19 return;20 }21 if (cow == n)22 return;23 dfs(cow + 1, sum);24 dfs(cow + 1, sum + f[cow]);25 }26 int main()27 {28 scanf("%d%d", &n, &m);29 for (int i = 0; i < n; i++)30 scanf("%d", &f[i]);31 s[n] = 0;32 for (int i = n - 1; i >= 0; i--)33 s[i] = s[i + 1] + f[i];34 ans = 0x3f3f3f3f;35 dfs(0,0);36 printf("%d\n", ans);37 return 0;38 }