1. 程式人生 > >POJ 3977 Subset

POJ 3977 Subset

ostream clas 查找 enter d+ esc light first ins

Subset
Time Limit: 30000MS Memory Limit: 65536K
Total Submissions: 4862 Accepted: 892

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

Solution:

折半搜索,處理出前半組數所能組成的所有和,以及後半組數所能組成的所有和,先用這些和更新答案,然後再把這兩組和分別排序,對於第一組中的每一個數,在另一組二分查找到能和他組成的絕對值最小的和,再更新答案.

Code:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
using namespace std;
#define pii pair<ll,int>
#define ll long long
const int MAXN=35;
const int MAXTOT=300000;
int n;
ll a[MAXN+10];
pii res1[MAXTOT+10],res2[MAXTOT+10];
int tot1,tot2;
int cnt;ll sum;
ll myabs(ll a){return (a<0)?(-a):a;}
void solve(int k,int n,pii* res,int& tot)
{
	if(k>n){if(cnt)res[++tot]=make_pair(sum,cnt);return;}
	solve(k+1,n,res,tot);
	++cnt;sum+=a[k];
	solve(k+1,n,res,tot);
	--cnt;sum-=a[k];
}
pii tmp[MAXTOT+10];
void doit(pii* res,int& tot)
{
	int now=1;
	for(int i=2;i<=tot;++i)
	{
		if(res[i].first!=res[i-1].first)tmp[++now]=res[i];
	}
	tot=now;
	for(int i=2;i<=tot;++i)res[i]=tmp[i];
}
void cmp(ll& ans,int& cnt,ll res,int t)
{
	res=myabs(res);
	if(ans==res)cnt=min(cnt,t);
	else if(ans>res)
	{
		ans=res;
		cnt=t;
	}
}
int main()
{
	//freopen("in.txt","r",stdin);
	//freopen("out.txt","w",stdout);
	while(scanf("%d",&n),n)
	{
		for(int i=1;i<=n;++i)scanf("%lld",a+i);
		if(n==1){printf("%lld 1\n",myabs(a[1]));continue;}
		int mid=(n>>1);
		cnt=sum=tot1=tot2=0;
		solve(1,mid,res1,tot1);
		solve(mid+1,n,res2,tot2);
		sort(res1+1,res1+tot1+1);
		sort(res2+1,res2+tot2+1);
		doit(res1,tot1);
		doit(res2,tot2);
		ll ans=1e18;int cnt;
		for(int i=1;i<=tot1;++i)
		{
			int left=1,mid,right=tot2,res=1;
			while(left<=right)
			{
				mid=(left+right)>>1;
				if(res2[mid].first<=-res1[i].first)
				{
					res=mid;
					left=mid+1;
				}
				else right=mid-1;
			}
			cmp(ans,cnt,res2[res].first+res1[i].first,res2[res].second+res1[i].second);
			if(res<tot2)cmp(ans,cnt,res2[res+1].first+res1[i].first,res2[res+1].second+res1[i].second);
		}
		for(int i=1;i<=tot1;++i)cmp(ans,cnt,res1[i].first,res1[i].second);
		for(int i=1;i<=tot2;++i)cmp(ans,cnt,res2[i].first,res2[i].second);
		printf("%lld %d\n",myabs(ans),cnt);
	}
	return 0;
}

  

POJ 3977 Subset