UVA-562 Dividing coins---01背包+平分钱币

题目链接:

https://vjudge.net/problem/UVA-562

题目大意:

给定n个硬币,要求将这些硬币平分以使两个人获得的钱尽量多,求两个人分到的钱最小差值

思路:

它所给出的n个钱币加起来sum,将sum/2当作体积,求出在sum/2下的最大值,sum-2*dp[sum/2]

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int maxn = 105;
 4 const int maxm = 1e5+10;
 5 int a[maxn];
 6 int dp[maxm];
 7 int T, n, m;
 8 int main()
 9 {
10     cin >> T;
11     while(T--)
12     {
13         cin >> n;
14         int sum = 0;
15         memset(dp, 0, sizeof(dp));
16         for(int i = 0; i < n; i++)cin >> a[i], sum += a[i];
17         for(int i = 0; i < n; i++)
18         {
19             for(int j = sum / 2; j >= a[i]; j--)
20                 dp[j] = max(dp[j], dp[j - a[i]] + a[i]);
21         }
22         cout<<(sum - 2 * dp[sum / 2])<<endl;
23     }
24     return 0;
25 }

 

posted @ 2018-04-10 21:39  _努力努力再努力x  阅读(161)  评论(0编辑  收藏  举报