Subset
Time Limit: 30000MS | Memory Limit: 65536K | |
Total Submissions: 3295 | Accepted: 594 |
Description
Given a list of N integers with absolute values no larger than 10
15, 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 10
15 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 <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long LL;
const int N = 1100000;
LL a[N];
struct node
{
LL num;
int cnt;
} p1[N], p2[N];
int cmp(node a,node b)
{
if(a.num!=b.num)
return a.num<b.num;
else
return a.cnt<b.cnt;
}
int p;
int binary(LL x)
{
int l=0, r=p-1, mid;
while(l<=r)
{
mid=(l+r)/2;
if(p2[mid].num>x)
{
r=mid-1;
}
else
{
l=mid+1;
}
}
return r;
}
int main()
{
int n;
while(scanf("%d", &n),n!=0)
{
for(int i=0; i<n; i++)
{
scanf("%lld",&a[i]);
}
int m=n/2;
int s=1<<(n-m);
for(int i=1;i<s;i++)
{
p1[i].num=0, p1[i].cnt=0;
for(int j=0;j<(n-m);j++)
{
if((i>>j)&1)
{
p1[i].num+=a[j+m];
p1[i].cnt++;
}
}
}
sort(p1+1,p1+s,cmp);
p2[0].num=0,p2[0].cnt=0;
p2[1]=p1[1];
p=2;
for(int i=2; i<s; i++)
{
if(p1[i].num!=p2[p-1].num)
{
p2[p++]=p1[i];
}
}
sort(p2,p2+p,cmp);
LL ans=1e15+5;
int res=50;
s=(1<<m);
for(int x=0; x<s; x++)
{
LL tt=x,tmp=0;
int cnt=0;
for(int i=0; i<m; i++)
{
if(tt&1)
{
tmp+=a[i];
cnt++;
}
tt>>=1;
}
int pos=binary(-tmp);
int pos1=max(pos-1,0),pos2=min(pos+1,p-1);
for(int i=pos1; i<=pos2; i++)
{
LL tmp1=p2[i].num+tmp;
int tmp2=p2[i].cnt+cnt;
if(tmp1==0&&tmp2==0) continue; //不能什么都不取
if(tmp1<0) tmp1=-tmp1;
if(tmp1<ans||(tmp1==ans&&tmp2<res))
{
ans=tmp1;
res=tmp2;
}
}
}
printf("%lld %d\n",ans,res);
}
return 0;
}