http://poj.org/problem?id=3628
Test instructions: There is a bookshelf, N cow, the farmer wants to put these cows on the shelf, of course, the bookshelf has a fixed height. Now I ask you, among these cows, what is the minimum difference between the heights of some cows and the height of a bookshelf?
Analysis:
Two methods: (1) 01 backpack, calculate the height of all the cattle, and then DP again, and then find a higher than the bookshelf of the minimum value, two number subtraction.
(2) Dfs,dfs (cow's coordinates, the sum of the cow's height), if in the DFS process, the total height of the cow >= bookshelf height, you can ask for the value we need
01 Backpack:
#include <stdio.h>#include<math.h>#include<string.h>#include<ctype.h>#include<stdlib.h>#include<iostream>#include<algorithm>#include<queue>#defineMAXN 1100#defineOO 0x3f3f3f3fusing namespacestd;intdp[maxn*MAXN], W[MAXN];intMain () {intN, M; while(SCANF ("%d%d", &n, &m)! =EOF) { intsum =0; for(intI=1; i<=n; i++) {scanf ("%d", &W[i]); Sum+=W[i]; } memset (DP,0,sizeof(DP)); for(intI=1; i<=n; i++) { for(intJ=sum; j>=w[i]; j--) {Dp[j]=max (Dp[j], dp[j-w[i]]+W[i]); } } intmins =Oo; for(intI=1; i<=sum; i++) { if(dp[i]>=m) {mins=min (mins, dp[i]-m); }} printf ("%d\n", mins); } return 0;}
View Code
Dfs:
#include <stdio.h>#include<math.h>#include<string.h>#include<ctype.h>#include<stdlib.h>#include<iostream>#include<algorithm>#include<queue>#defineMAXN 1100#defineOO 0x3f3f3f3fusing namespacestd;intA[MAXN], V[MAXN];intN, m, mins;voidDFS (intXintsum) { if(Sum >=m) {mins=min (mins, sum-m); return ; } if(X>n | | mins==0)return ; for(intI=x; i<=n; i++) { if(!V[i]) {V[i]=1; DFS (i+1, sum+A[i]); V[i]=0; } }}intMain () { while(SCANF ("%d%d", &n, &m)! =EOF) { for(intI=1; i<=n; i++) scanf ("%d", &A[i]); memset (V,0,sizeof(v)); Mins=Oo; DFS (1,0); printf ("%d\n", mins); } return 0;}
View Code
Bookshelf 2 poj3628 (01 backpack/dfs)