Subset

Time Limit: 30000MS Memory Limit: 65536K

Description

Given a list of N integers with absolute values no larger than 1015, find a non empty subset of these numbers which minimizes the absolute value of the sum of its elements. In case there are multiple subsets, choose the one with fewer elements.

Input

The input contains multiple data sets, the first line of each data set contains N <= 35, the number of elements, the next line contains N numbers no larger than 1015 in absolute value and separated by a single space. The input is terminated with N = 0

Output

For each data set in the input print two integers, the minimum absolute sum and the number of elements in the optimal subset.

Sample Input

1
10
3
20 100 -100
0

Sample Output

10 1
0 2

思路:

折半枚举的话,首先就是先拿出一半,然后进行2 n/2的次数运算,然后就是将最小的存入pair,然后其余的存入map,因为long long太大,无法用数组,然后再枚举另一半,先看看枚举的值会不会最小,然后用lower_bound找map里的与-sum相近的值,这个值可能在前面,可能在后面,所以还要判断,因为要和的绝对值最大,所以要用-sum找。

#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
typedef long long ll;
const int maxn = 40;	
ll absn(ll x) {
	if (x < 0) return -x;
	else return x;
}
int main() {
	int n; 
	ll a[maxn];
	while (scanf("%d", &n) != EOF && n) {
		for (int i = 0; i < n; i++) scanf("%lld", &a[i]);
		map<ll, int> mp;
		pair<ll, int> opt(absn(a[0]), 1);
		int m = n / 2;
		for (int i = 0; i < 1 << m; i++) {
			ll sum = 0;
			int ans = 0;
			for (int j = 0; j < m; j++) {
				if (i >> j & 1) {
					sum += a[j];
					ans++;	
				}
				if (ans == 0) continue;
				opt = min(opt, make_pair(absn(sum), ans));
				map<ll, int>::iterator it = mp.find(sum);
				if (it == mp.end()) mp[sum] = ans;
				else it->second = min(it->second, ans);
			}
		}
		for (int i = 0; i < 1 << (n - m); i++) {
			ll sumn = 0;
			int ansn = 0;
			for (int j = 0; j < n - m; j++) {
				if (i >> j & 1) {
					sumn += a[j + m];
					ansn++;
				}
			}
			if (ansn == 0) continue;
			opt = min(opt, make_pair(absn(sumn), ansn));
			map<ll, int>::iterator it = mp.lower_bound(-sumn);
			if (it != mp.end()) {
				opt = min(opt, make_pair(absn(it->first + sumn), it->second + ansn));
			} 
			if (it != mp.begin()) {
				it--;
				opt = min(opt, make_pair(absn(it->first + sumn), it->second + ansn));
			}
		}
		printf("%lld %d\n", opt.first, opt.second);
	}
	return 0;
}