24h購物| | PChome| 登入
2012-12-16 17:36:06| 人氣4,157| 回應0 | 上一篇 | 下一篇

[UVA][bitmask+背包] 10032 - Tug of War

推薦 0 收藏 0 轉貼0 訂閱站台

Problem F: Tug of War


A tug of war is to be arranged at the local office picnic. For the tug of war, the picnickers must be divided into two teams. Each person must be on one team or the other; the number of people on the two teams must not differ by more than 1; the total weight of the people on each team should be as nearly equal as possible.

Input

The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.

The first line of input contains n the number of people at the picnic. n lines follow. The first line gives the weight of person 1; the second the weight of person 2; and so on. Each weight is an integer between 1 and 450. There are at most 100 people at the picnic.

Output

For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line.

Your output will be a single line containing 2 numbers: the total weight of the people on one team, and the total weight of the people on the other team. If these numbers differ, give the lesser first.

Sample Input

1

3
100
90
200

Sample Output

190 200

這題比較特殊點,要求左右兩邊人數差距小於等於一。
因此原本是要會這麼寫的 dp[重量][人數] = 0 or 1
那麼因為人數至多 50,轉移一下方程將資料壓成一個 long long(64 bits)。

dp[j] |= dp[j-w]<<1;

#include <stdio.h>

int main() {
int t, n, i, j;
int A[100];
scanf("%d", &t);
while(t--) {
scanf("%d", &n);
int sum = 0;
for(i = 0; i < n; i++)
scanf("%d", &A[i]), sum += A[i];
int hsum = sum/2, hn = n/2;
long long dp[hsum+1];
for(i = 0; i <= hsum; i++)
dp[i] = 0;
dp[0] = 1;
for(i = 0; i < n; i++) {
for(j = hsum; j >= A[i]; j--)
dp[j] |= dp[j-A[i]]<<1LL;
}
if(n%2)
while(!(dp[hsum]&(1LL<<hn)) && !(dp[hsum]&(1LL<<(hn+1))))
hsum--;
else
while(!(dp[hsum]&(1LL<<hn)))
hsum--;

printf("%d %d\n", hsum, sum-hsum);
if(t)
puts("");
}
return 0;
}
 

台長: Morris
人氣(4,157) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA][因數] 12573 - Sohel Sir's Assignment
此分類上一篇:[UVA][解二][二分+負環] 11090 - Going in Cycle!!

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文