题目链接:
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=503
背包问题:
#include <iostream> #include <string.h> #include <stdlib.h> #include <algorithm> #include <math.h> #include <stdio.h> using namespace std; int a[105]; int dp[50005]; int t; int n; int num; int main() { scanf("%d",&t); while(t--) { num=0; scanf("%d",&n); for(int i=1;i<=n;i++) { scanf("%d",&a[i]); num+=a[i]; } memset(dp,0,sizeof(dp)); for(int i=1;i<=n;i++) { for(int j=num;j>=a[i];j--) { dp[j]=max(dp[j],dp[j-a[i]]+a[i]); } } int num2=num/2; int num3=0,num4=0; for(int i=num2;i>=1;i--) { if(dp[i]==i) { num3=i; break; } } for(int i=num2;i<=n;i++) { if(dp[i]==i) { num4=i; break; } } int ans1,ans2; ans1=num-num4-num4; ans2=num-num3-num3; printf("%d ",min(ans1,ans2)); } return 0; }