Subset
Time Limit: 30000MS | Memory Limit: 65536K | |
Total Submissions: 3446 | Accepted: 633 |
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
Source
Seventh ACM Egyptian National Programming Contest
解题思路
n是35,2^n太大,采用折半枚举。每次枚举一半的时候,都更新最优解。在枚举后半部分时,采用二分查找法找与其相反数最近的和,在那附近更新最优解。map中的元素会按照key值从小到大排列,因此使用map很容易实现,时间复杂度为O(2^(n/2)logn).
AC代码
#include <iostream>
#include <cstdio>
#include <utility>
#include <map>
using namespace std;
typedef long long LL;
#define INF 0x7fffffff
const int maxn =36;
int n;
LL a[maxn];
LL abs(LL x){
return x>0?x:(-x);
}
int main(){
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
while(scanf("%d",&n)!=EOF&&n){
for(int i=0;i<n;i++){
scanf("%lld",&a[i]);
}
pair<LL,int> res;//最优解,(和的绝对值,元素个数)
map<LL,int> dp;//和→元素个数
res=make_pair(abs(a[0]),1);
int n2=n/2;
//枚举前半部分
for(int i=0;i<(1<<n2);i++){
LL sum=0;
int num=0;
for(int j=0;j<n2;j++){
if((i>>j)&1){
sum+=a[j];
num++;
}
}
if(num==0){
continue;
}
//更新最优解
res=min(res,make_pair(abs(sum),num));
map<LL,int>::iterator it=dp.find(sum);
if(it!=dp.end()){
it->second=min(it->second,num);
}
else{
dp[sum]=num;
}
}
//枚举后半部分
for(int i=0;i<(1<<(n-n2));i++){
LL sum=0;
int num=0;
for(int j=0;j<n-n2;j++){
if((i>>j)&1){
sum+=a[n2+j];
num++;
}
}
if(num==0){
continue;
}
//更新最优解
res=min(res,make_pair(abs(sum),num));
map<LL,int>::iterator it=dp.lower_bound(-sum);//返回key大于等于-sum的指针
//搜索-sum最相近的结果
if(it!=dp.end()){
res=min(res,make_pair(abs(sum+it->first),num+it->second));
}
if(it!=dp.begin()){
it--;
res=min(res,make_pair(abs(sum+it->first),num+it->second));
}
}
printf("%lld %d\n",res.first,res.second);
}
return 0;
}