Http://acm.hdu.edu.cn/showproblem.php? PID = 1, 1171
Meaning: There are n kinds of items, which give the value and quantity of each item. Divide these items into two equal portions A and B as much as possible and Output A and B.
The primary function can be used, but the most direct method should be multiple backpacks.
In the case of a primary function, the value is also calculated by half of the total value, from half to small enumeration until B is found if the coefficient is not 0.
#include <stdio.h>#include <iostream>#include <map>#include <set>#include <stack>#include <vector>#include <math.h>#include <string.h>#include <queue>#include <string>#include <stdlib.h>#include <algorithm>#define LL long long#define _LL __int64#define eps 1e-12#define PI acos(-1.0)using namespace std;int main(){int n;int val[55],num[55];int sum;int c1[125010],c2[125010];while(~scanf("%d",&n)){if(n < 0) break;sum = 0;for(int i = 1; i <= n; i++){cin >> val[i] >> num[i];sum += val[i]*num[i];}int tmp = sum/2;memset(c1,0,sizeof(c1));memset(c2,0,sizeof(c2));for(int i = 0; i <= val[1]*num[1]; i += val[1])c1[i] = 1;for(int i = 2; i <= n; i++){for(int j = 0; j <= tmp; j++){for(int k = 0; k+j <= tmp && k <= val[i]*num[i]; k += val[i])c2[k+j] += c1[j];}for(int j = 0; j <= tmp; j++){c1[j] = c2[j];c2[j] = 0;}}int i;for(i = tmp; i >= 0; i--)if(c1[i] != 0)break;printf("%d %d\n",sum-i,i);}return 0;}
Multiple backpacks are carried out in half of the total value, which is faster than the primary function and faster than the two-dimensional time.
Unoptimized multiple backpacks:
# Include <stdio. h> # include <string. h ># include <algorithm> using namespace STD; int Val [55], num [55]; int DP [125010]; int N; int main () {While (~ Scanf ("% d", & N) {If (n <0) break; int sum = 0; For (INT I = 1; I <= N; I ++) {scanf ("% d", & Val [I], & num [I]); sum + = Val [I] * num [I];} int TMP = sum/2; memset (DP, 0, sizeof (DP); DP [0] = 1; int ans =-1; for (INT I = 1; I <= N; I ++) {for (Int J = 0; j <= num [I]; j ++) {for (INT v = TMP; V> = J * val [I]; V --) // reverse order if (DP [V-J * val [I]) {DP [v] = 1; ans = max (ANS, v );}}} printf ("% d \ n", Sum-ans, ANS);} return 0 ;}