POJ:3977-Subset(双向搜索)

Subset

Time Limit: 30000MS Memory Limit: 65536K
Total Submissions: 5961 Accepted: 1129

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


解题心得:

  1. 就是一个双向搜索,要求的是选择出来的元素的总和的绝对值最小,按照双向搜索的思路去做就可以了。但是要注意的一点是在二分搜索最相近的答案的时候可能从这个数的lower_bound产生的结果,或者lower_bound的位置-1产生绝对值最小的答案。

#include <algorithm>
#include <cstring>
#include <map>
#include <stdio.h>
using namespace std;
typedef long long ll;
const ll maxn = 45;
const ll MAX = 1e15;

map <ll,ll> M;
pair <ll,ll> ans;
ll n,num[maxn];

ll Abs(ll x) {
    if(x < 0)
        return -x ;
    return x;
}

void init() {
    M.clear();
    ans = make_pair(MAX,MAX);
    for(int i=0;i<n;i++) scanf("%lld",&num[i]);
}

void get_sum(ll mid) {
    ll cnt,sum;
    for(ll i=1;i<(1<<mid);i++) {
        cnt = sum = 0;
        for(ll j=0;j<mid;j++) {
            if(1&(i>>j)) {
                sum += num[j];
                cnt++;
            }
        }
        ans = min(ans,make_pair(Abs(sum),cnt));
        if(M[sum]) {
            M[sum] = min(M[sum],cnt);
        } else
            M[sum] = cnt;
    }
}

void solve(ll mid) {
    map<ll,ll> :: iterator iter;
    for(ll i=1;i<(1<<(n-mid));i++) {
        ll sum,cnt;
        sum = cnt = 0;
        for(int j=0;j<(n-mid);j++) {
            if(1&(i>>j)) {
                sum += num[mid+j];
                cnt++;
            }
        }
        ans = min(ans,make_pair(Abs(sum),cnt));

        iter = M.lower_bound(-sum);
        if(iter != M.end()) {
            ans = min(ans,make_pair(Abs(iter->first+sum),cnt+iter->second));
        }
        if(iter != M.begin()) {
            iter--;
            ans = min(ans,make_pair(Abs(iter->first+sum),iter->second+cnt));
        }
    }
    printf("%lld %lld\n",ans.first,ans.second);
}

int main() {
    while(scanf("%lld",&n) && n) {
        init();
        ll mid = n>>1;
        get_sum(mid);
        solve(mid);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值