01揹包 + 數學(平衡) 之 uva 562

//  [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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章