POJ 3977

Subset
Time Limit: 30000MS   Memory Limit: 65536K
Total Submissions: 1373   Accepted: 228

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

Source

 
 
把集合分成两个 N / 2的集合,然后生成一种一个集合2 ^ (n - 1)种状态的和,对于另一个集合的所有状态的和 在前一个集合中二分找到一个最接近的
并找到集合元素最小的即是所求答案
 
 #include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <utility> using namespace std; typedef long long ll;
typedef pair<ll,int> pii; const ll INF = (1e17) + ;
const int MAX = ; int N;
ll w[MAX];
pii ps[( << ) + ];
int cal[ << ],dx[] = {-,-,,}; ll Abs(ll x) {
return x > ? x : -x;
} void init() {
for(int s = ; s < ( << ); ++s) {
int sum = ;
for(int i = ; i < ; ++i) {
if(s >> i & ) ++sum;
}
cal[s] = sum;
}
}
void solve() {
int n = N / ;
ll sw = ;
for(int s = ; s < ( << n); ++s) {
sw = ;
for(int j = ; j < n; ++j) {
if(s >> j & ) sw += w[j];
}
ps[s] = make_pair(sw,cal[s]);
}
sort(ps,ps + ( << n)); int n1 = N - n;
ll ansv = INF;
int anss = N;
for(int s = ; s < ( << n1); ++s) {
sw = ;
for(int j = n; j < N; ++j) {
if(s >> (j - n) & ) sw += w[j];
}
int pos = lower_bound(ps,ps + ( << n),make_pair(-sw,-)) - ps;
ll v = INF,t = INF;
for(int i = ; i < ; ++i) {
int id = pos + dx[i];
if(id >= && id < ( << n)
&& (ps[id].second || s)) {
if(Abs(ps[id].first + sw) < t) {
t = Abs(ps[id].first + sw);
v = ps[id].first;
}
}
}
pos = lower_bound(ps,ps + ( << n),make_pair(v,-)) - ps;
if(s == && ps[pos].second == ) ++pos;
if(ansv > Abs(v + sw) || ansv == Abs(v + sw) && anss > cal[s] + ps[pos].second) {
ansv = Abs(v + sw);
anss = cal[s] + ps[pos].second;
}
} printf("%I64d %d\n",ansv,anss);
} int main()
{
freopen("sw.in","r",stdin);
init();
while(~scanf("%d",&N) && N) {
for(int i = ; i < N; ++i) scanf("%I64d",&w[i]);
solve();
} return ;
}
上一篇:java调用第三方的webservice应用实例【转载】


下一篇:php中CURL技术模拟登陆抓取数据实战,抓取某校教务处学生成绩。