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
题目大意:给出一段序列,找一个子序列使得和的绝对值最小。
将序列拆成两半,折半枚举。两边分别枚举子序列并求出和,每次枚举左边的一个,在右边二分查找与它和的绝对值最小的,然后更新答案。
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define ll long long
using namespace std;
const ll INF = 190000000000000000;
const int maxn = 3 * 1e5 + 5;
typedef struct ndoe
{
ll x,y;
}node;
node a[maxn],b[maxn];
ll c[maxn],f[maxn];
ll sum,cc;
ll ab(ll pp)
{
if(pp < 0) pp = -pp;
return pp;
}
bool cmp(node p,node q)
{
return p.x < q.x;
}
int l,r;
void addl(ll su,int st,int en,ll cou)
{
if(st <= en)
{
addl(su + c[st],st + 1,en,cou + 1);
addl(su,st + 1,en,cou);
}
else
{
a[l].x = su,a[l++].y = cou;
if(ab(su) <= sum && cou)
{
if(ab(su) < sum) sum = ab(su),cc = cou;
if(ab(su) == sum && cc > cou) cc = cou;
}
}
}
void addr(ll su,int st,int en,ll cou)
{
if(st <= en)
{
addr(su + c[st],st + 1,en,cou + 1);
addr(su,st + 1,en,cou);
}
else
{
f[r] = su,b[r].x = su,b[r++].y = cou;
if(ab(su) <= sum && cou)
{
if(ab(su) < sum) sum = ab(su),cc = cou;
if(ab(su) == sum && cc > cou) cc = cou;
}
}
}
int main()
{
int n;
while(scanf("%d",&n) && n)
{
sum = cc = INF;
l = r = 0;
for(int i = 1;i <= n; ++i) scanf("%lld",&c[i]);
addl(0,1,n / 2,0);
addr(0,n / 2 + 1,n,0);
--r,--l;
sort(f,f + r);
sort(b,b + r,cmp);
for(int i = 0;i < l; ++i)
{
long long *p = lower_bound(f,f + r,-a[i].x);
int loc = p - f;
if(loc < r && ab(b[loc].x + a[i].x) <= sum)
{
if(ab(b[loc].x + a[i].x) < sum) sum = ab(b[loc].x + a[i].x),cc = a[i].y + b[loc].y;
if(ab(b[loc].x + a[i].x) == sum && (a[i].y + b[loc].y) < cc) cc = a[i].y + b[loc].y;
}
if(loc > 0 && ab(b[loc - 1].x + a[i].x) <= sum)
{
if(ab(b[loc - 1].x + a[i].x) < sum) sum = ab(b[loc - 1].x + a[i].x),cc = a[i].y + b[loc - 1].y;
if(ab(b[loc - 1].x + a[i].x) == sum && (a[i].y + b[loc - 1].y) < cc) cc = a[i].y + b[loc - 1].y;
}
}
printf("%lld %lld\n",sum,cc);
}
return 0;
}