UVa 11851 - Celebrity Split

contents

  1. 1. Problem
  2. 2. Sample Input
  3. 3. Output for Sample Input
  4. 4. Solution

Problem

家產劃分給兩個人,兩個人分配的房子總價值必須相同,剩下無法劃分的房子將換成現金分配給兩個人,求換成現金的總額最小為何?

Sample Input

1
2
3
4
5
6
7
5
6000000
30000000
3000000
11000000
3000000
0

Output for Sample Input

1
41000000

Solution

窮舉分配情況,並且試圖將後期分配肯定會失敗的情況剪掉。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <functional>
using namespace std;
int n;
long long A[32], suffix[32], ret;
void dfs(int i, long long x, long long y, long long sold) {
if(sold >= ret || abs(x - y) > suffix[i]) return;
if(x == y)
ret = min(ret, sold + suffix[i]);
if(i == n)
return;
if(x == y) {
dfs(i+1, x + A[i], y, sold);
dfs(i+1, x, y, sold + A[i]);
} else {
dfs(i+1, x + A[i], y, sold);
if(x)
dfs(i+1, x, y + A[i], sold);
dfs(i+1, x, y, sold + A[i]);
}
}
int main() {
while(scanf("%d", &n) == 1 && n) {
for(int i = 0; i < n; i++)
scanf("%lld", &A[i]);
sort(A, A+n, greater<long long>());
suffix[n] = 0;
for(int i = n-1; i >= 0; i--)
suffix[i] = suffix[i+1] + A[i];
ret = 1LL<<60;
dfs(0, 0, 0, 0);
printf("%lld\n", ret);
}
return 0;
}