uva 10032 Problem F: Tug of War

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=973

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <algorithm>
 4 #define ll long long
 5 using namespace std;
 6 
 7 int w[5000];
 8 int n;
 9 ll dp[50000];
10 
11 int main()
12 {
13     int t;
14     scanf("%d",&t);
15     while(t--)
16     {
17         scanf("%d",&n);
18         int sum=0;
19         for(int i=0; i<n; i++)
20         {
21             scanf("%d",&w[i]);
22             sum+=w[i];
23         }
24         memset(dp,0,sizeof(dp));
25         dp[0]=1;
26         for(int i=0; i<n; i++)
27         {
28             for(int j=sum; j>=w[i]; j--)
29             {
30                 dp[j] |= dp[j-w[i]]<<1;
31             }
32         }
33         int ans1=0,ans2=0x3f3f3f3f;
34         for(int i=0; i<=sum; i++)
35         {
36             for(int j=0; j<=(n+1)/2; j++)
37             {
38                 if(dp[i]&(1ll<<j) && abs(2*j-n)<=1)
39                 {
40                     if(abs(sum-2*i)<ans2-ans1)
41                     {
42                         ans2=max(sum-i,i);
43                         ans1=min(sum-i,i);
44                     }
45                 }
46             }
47         }
48         printf("%d %d\n",ans1,ans2);
49         if(t) printf("\n");
50     }
51     return 0;
52 }
View Code

 

posted @ 2014-10-13 00:37  null1019  阅读(244)  评论(0编辑  收藏  举报