http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=114&page=show_problem&problem=503
以sum/2为背包总量,结果为sum-d*dp[V]
#include <iostream> #include <string> #include <cstring> #include <cstdlib> #include <cstdio> #include <cmath> #include <algorithm> #include <stack> using namespace std; #define MEM(a,b) memset(a,b,sizeof(a)) #define pf printf #define sf scanf #define debug printf("! ") #define INF 8000 #define MAX(a,b) a>b?a:b #define blank pf(" ") #define LL long long #define ep 1e-6 int dp[INF]; int way[INF][INF];//保存路径 int ci[INF];//容量 int wi[INF];//价值 int n,V,i,j,v,t,sum; double G; void zeroOnePack(int cost,int weight) { for(v = V;v>=cost;v--) { dp[v] =MAX(dp[v],dp[v-cost]+weight); } } int main() { int t; sf("%d",&t); while(t--) { MEM(dp,0); MEM(way,0); MEM(wi,0); sf("%d",&n); sum = 0; for(i = 1;i<=n;i++) { sf("%d",&wi[i]); sum+=wi[i]; } G = (double)sum/2; V = (int)G; for(i = 1;i<=n;i++) { zeroOnePack(wi[i],wi[i]); } pf("sum:%d ",sum-2*dp[V]); } return 0; }