Two-dimensional cost backpack, cannot use a rolling array!
#include<iostream>#include<cstring>#include<cstdio>#define max(x,y) (x>y?x:y)using namespace std;int f[51][23000],a[101];int main(){int n,i,j,k;scanf("%d",&n);int side=(n+1)/2,sum=0;for(i=1;i<=n;i++){scanf("%d",&a[i]);sum+=a[i];}int halfsum=(sum+1)/2;memset(f,0,sizeof(f));for(i=1;i<=n;i++)for(j=(side>i)?i:side;j>=1;j--)for(k=halfsum;k>=a[i];k--)f[j][k]=max(f[j][k],f[j-1][k-a[i]]+a[i]);int ans=max(f[side][halfsum],sum-f[side][halfsum]);printf("%d %d\n",sum-ans,ans);return 0;}
In this case, the initialization of the initial status should be one person.
# Include <iostream> # include <cstring> # include <cstdio> # define max (x, y) (x> Y? X: Y) using namespace STD; int A [101]; bool f [51] [25000]; int main () {int N, I, J, K; scanf ("% d", & N); int side = (n + 1)/2, sum = 0; for (I = 1; I <= N; I ++) {scanf ("% d", & A [I]); sum + = A [I];} int halfsum = (sum + 1)/2; memset (F, 0, sizeof (f); for (I = 0; I <= side; I ++) f [I] [0] = 1; // pay attention to for (I = 1; I <= N; I ++) for (j = (side> I )? I: side; j> = 1; j --) // is there any need for reverse order? For (k = halfsum; k> = A [I]; k --) if (F [J-1] [k-A [I]) f [J] [k] = 1; while (! F [side] [halfsum]) halfsum --; int ans = max (halfsum, Sum-halfsum); printf ("% d \ n", Sum-ans, ans); Return 0 ;}