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
解题心得:
- 就是一个双向搜索,要求的是选择出来的元素的总和的绝对值最小,按照双向搜索的思路去做就可以了。但是要注意的一点是在二分搜索最相近的答案的时候可能从这个数的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;
}