Subset
Time Limit: 30000MS | Memory Limit: 65536K | |
Total Submissions: 3947 | Accepted: 765 |
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
给定含有 N 个元素的集合,求一个非空子集,使子集中元素之和的绝对值最小。求这个最小的绝对值,和最优子集中的元素个数。
N 最大为 35,直接暴力枚举必定会超时。考虑折半搜索。
首先枚举前 N/2 个元素,保存在 map 中,并记录其中元素个数。
然后枚举后 N-N/2 个元素,同时用二分搜索匹配绝对值最小的子集。
当一个问题规模较大,直接枚举超时的时候,可以考虑折半搜索。把 N 分成两份,对这两份分别进行枚举。最后采用二分等方式将这两部分合并起来。
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<map>
using namespace std;
typedef long long LL;
typedef pair<LL, int> P;
const LL inf = 10000000000000000;
LL A[40];
int N;
LL Abs(LL x)
{
if(x >= 0) return x;
return -x;
}
int main()
{
while(1)
{
scanf("%d", &N);
if(N == 0) break;
for(int i= 0; i< N; i++)
scanf("%lld", &A[i]);
map<LL, int> M;
map<LL, int>::iterator it;
//初始化答案
P res = P(Abs(A[0]), 1);
//枚举前一半的状态
int N2 = N >> 1;
for(int s= 1; s< 1<<N2; s++)
{
LL temp = 0;//和
int cnt = 0;//元素数
for(int i= 0; i< N2; i++)
{
if((s>>i) & 1)
temp += A[i], cnt ++;
}
//保留最小元素数
if(M[temp])
M[temp] = min(M[temp], cnt);
else M[temp] = cnt;
//只有前一半的元素
res = min(res, P(Abs(temp), cnt));
}
//枚举后一半的状态
int N3 = N - N2;
for(int s= 1; s< 1<<N3; s++)
{
LL temp = 0;
int cnt = 0;
for(LL i= 0; i< N3; i++)
{
if(s>>i & 1)
cnt ++, temp += A[i+N2];//加上后一半的元素
}
//只有后一半的元素
res = min(res, P(Abs(temp), cnt));
//二分搜索
it = M.lower_bound(-temp);
if(it != M.end())
res = min(res, P(Abs(it->first+temp), it->second+cnt));
if(it != M.begin())
{
it --;
res = min(res, P(Abs(it->first+temp), it->second+cnt));
}
}
printf("%lld %d\n", res.first, res.second);
}
return 0;
}