Subset
Time Limit: 30000MS | Memory Limit: 65536K | |
Total Submissions: 5161 | Accepted: 952 |
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
思路:
折半搜索, 每个x找另一个集合的-x,如果不存在-x,就看这个数前一个后一个,跟他和的绝对值
map也可以low_bound,学习下pair, 这题map特别好用,相等的sum,直接存最小的num就好了, pair
先比较first, 在比较second, 这题正好要求两个都是小的,所以用map跟pair记录答案很好
#include <iostream>
#include <cstring>
#include <cstdio>
#include <map>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 40;
const ll INF = 1e18;
ll ABS(ll x)
{
if(x >= 0) return x;
else return -x;
}
map<ll, int> mp;
ll a[maxn];
int main()
{
int n;
while(~scanf("%d", &n), n)
{
mp.clear();
for(int i = 0; i < n; i++)
scanf("%lld", &a[i]);
pair<ll, int> ans = make_pair(INF, 0);
int len1 = n/2, len2 = n-len1;
for(int i = 1; i < 1<<len1; i++) //两个集合都从状态1开始枚举, 防止两个集合同时没拿集合,每个集合都从1开始
{ //同时把每个集合单个集合最小的更新到答案里,这样保证了一种集合不拿另一种集合
ll sum = 0; //拿的正确性, 另一个集合同理, 其余的就都是两个集合拿东西了
int num = 0;
for(int j = 0; j < len1; j++)
if(i&(1<<j))
sum += a[j], num++;
if(!mp[sum] || mp[sum] > num) //如果这个数没有,或者他不是最小的
mp[sum] = num;
pair<ll, int> t = make_pair(ABS(sum), num);
if (t < ans) ans = t;
}
for(int i = 1; i < 1<<len2; i++) //从1开始枚举
{
ll sum = 0;
int num = 0;
for(int j = 0; j < len2; j++)
if(i&(1<<j))
sum += a[len1+j], num++;
pair<ll, int> t = make_pair(ABS(sum), num);
if (t < ans) ans = t;
map<ll, int>::iterator it = mp.lower_bound(-sum); //mp的 low_bound ,返回答案位置所在迭代器
if(it != mp.end()) //如果不是最后一个,说明有比他大的第一个
{
t = make_pair(ABS(it->first + sum), num + it->second);
if (t < ans) ans = t;
}
if(it != mp.begin()) //这里要看他前面那个答案怎么样, 之前说了 没有相同的要比较前后两个数跟他的答案,注意判断不是第一个
{
it--;
t = make_pair(ABS(it->first + sum), num + it->second);
if (t < ans) ans = t;
}
}
cout << ans.first << ' ' << ans.second << endl;
}
return 0;
}