POJ 3977 Subset

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;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值