POJ3977-Subset【双向搜索】

原题链接
Subset
Time Limit: 30000MS Memory Limit: 65536K
Total Submissions: 3360 Accepted: 609
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

Seventh ACM Egyptian National Programming Contest
题意:问题很简单,给出一组数,从中挑出n>=1个数让他们的和的绝对值最小。如果最小的绝对值一样那么输出组成的数字最少的答案
思路:如果进行简单的枚举肯定是行不通的,235的复杂度实在是太高了,但是如果降低到214次这个样子久可以接受了,所以我们想到了二分列举所有的可能性然后进行查找。这样的话复杂度就会降下来,需要注意的是答案可能是一个数字也可能只在二分的某一个部分之类,所以需要对这些部分先进行一步判断

//http://poj.åçorg/problem?id=3977
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

typedef long long ll;
const int MOD = int(1e9) + 7;
//int MOD = 99990001;
const int INF = 0x3f3f3f3f;
const ll INFF = (~(0ULL)>>1);
const double EPS = 1e-9;
const double OO = 1e20;
const double PI = acos(-1.0); //M_PI;
const int fx[] = {-1, 1, 0, 0};
const int fy[] = {0, 0, -1, 1};
const int maxn=500000 + 5;
ll a[40];
struct node
{
	ll sum;//一个子集的和
	int num;//子集中的元素的数量
}up[maxn],down[maxn];//代表分成的两部分
ll _fabs(ll x){
	return x<0 ? -x : x;
}
bool cmp(node x,node y){
	if(x.sum != y.sum){
		return x.sum < y.sum;
	}
	else{
		return x.num < y.num;
	}
}
bool _can(int loc,int i,ll minsum,int minnum){
	if(_fabs(up[loc].sum + down[i].sum) == minsum){
		return up[loc].num + down[i].num < minnum ? true : false;
	}
	else{
		return _fabs(up[loc].sum + down[i].sum) < minsum ? true : false;
	}
}
int lower(ll x,int n){
	int l=-1,r=n-1;
	while(r-l>1){
		int mid=(l+r)/2;
		if(up[mid].sum >= x) r=mid;
		else l=mid;
	}
	return r;
}
int main(){
		int n;
		while(scanf("%d",&n)==1 && n){
			for(int i=0;i> a[i];
			if(n==1){
				cout << _fabs(a[0]) << " 1" <>j & 1){
						up[sumup].sum+=a[j];
						up[sumup].num++;
					}
				}
				sumup++;
			}
			sort(up,up+sumup,cmp);
			for(int i=1;i< 1 << (n-mid);i++){
				for(int j=0;j<(n-mid);j++){
					if(i>>j & 1){
						down[sumdown].sum+=a[mid+j];
						down[sumdown].num++;
					}
				}
				sumdown++;
			}
			//对直接可以得到结果的部分进行遍历
			ll minsum=(ll)1<<62,minnum=1;
			for(int i=0;i0){
					loc--;
					loc=lower(up[loc].sum,sumup);
					if(_can(loc,i,minsum,minnum)){
						minsum=_fabs(up[loc].sum + down[i].sum);
						minnum=up[loc].num + down[i].num;
					}
				}
			}
			cout << minsum << " " << minnum << endl;
		}	
        return 0;
}

你可能感兴趣的:(▶︎算法与数据结构)