01背包 + 数学(平衡) 之 uva 562

来源:互联网 发布:图形界面编程 编辑:程序博客网 时间:2024/04/29 00:22
//  [7/21/2014 Sjm]/*题目关键:Given a bag with a maximum of 100 coins, determine the most fair division between two persons.This means that the difference between the amount each person obtains should be minimised.  思路:两个人分硬币,要公平。那就让一个人所获得的硬币无限接近总的硬币的数目的一半(01背包求解),剩下的硬币给另外一个人。此时,即可做到:"the difference between the amount each person obtains should be minimised. " */
#include <iostream>#include <cstdlib>#include <cstdio>#include <algorithm>#include <cstring>using namespace std;const int MAX = 50005;int arr[105];int dp[MAX];int m, sum, Val;int Solve() {memset(dp, 0, sizeof(dp));for (int i = 1; i <= m; ++i) {for (int j = Val; j >= arr[i]; --j) {dp[j] = max(dp[j], dp[j - arr[i]] + arr[i]);}}return abs(sum - 2 * dp[Val]);}int main(){//freopen("input.txt", "r", stdin);int T;scanf("%d", &T);while (T--) {sum = 0;scanf("%d", &m);for (int i = 1; i <= m; ++i) {scanf("%d", &arr[i]);sum += arr[i];}Val = sum / 2;printf("%d\n", Solve());}return 0;}
0 0