Subset
| Time Limit: 30000MS | Memory Limit: 65536K | |
| Total Submissions:5715 | Accepted: 1081 |
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<algorithm>
#include<map>
using namespace std;
typedef long long ll;
ll a1[22],a2[22],d[2000003];
map<ll,int>mp;//去重
struct node
{
int num;
ll cost;
} c[2000003];
bool cmp(const node& a,const node& b)
{
return a.cost<b.cost;
}
ll abs1(ll x)
{
if(x<0)x=-x;
return x;
}
int main()
{
int n;
while(~scanf("%d",&n),n)
{
int i,j,k1=n/2,k2=n-k1,y=0;
for(i=0; i<k1; i++)
scanf("%lld",&a1[i]);
for(i=0; i<k2; i++)
scanf("%lld",&a2[i]);
for(int t=0; t<1<<k1; t++)
{
ll cost=0;int num=0;
for(i=0; i<k1; i++)
{
if(t>>i&1)
{
cost+=a1[i];
num++;
}
}
if(mp[cost])c[mp[cost]].num=min(c[mp[cost]].num,num);
else
{
mp[cost]=y;
c[y].cost=cost;
c[y++].num=num;
}
}
sort(c,c+y,cmp);
y--;
for(i=0; i<=y; i++)
d[i]=c[i].cost;
ll mi=1e17;
int sum=0;
for(int t=0; t<1<<k2; t++)
{
ll cost=0;
int num=0;
for(i=0; i<k2; i++)
{
if(t>>i&1)
{
cost+=a2[i];
num++;
}
}
int id;
ll ta;
id=lower_bound(d+1,d+y+1,-cost)-d;
if(id<=y)//防止越界
{
ta=abs1(cost+d[id]);
num=num+c[id].num;
if(ta<mi&&num)mi=ta,sum=num;
else if(ta==mi&&num)sum=min(sum,num);
num-=c[id].num;
}
if(id-1>=0)//判断两个边界情况
{
id--;
ta=abs1(cost+d[id]);
num+=c[id].num;
if(ta<mi&&num)mi=ta,sum=num;
else if(ta==mi&&num)sum=min(sum,num);
}
}
printf("%lld %d\n",mi,sum);
mp.clear();
}
return 0;
}
解决一个给定整数列表的子集求和问题,寻找绝对值最小的非空子集和,通过两分搜索和排序优化算法实现。
2322

被折叠的 条评论
为什么被折叠?



