1. 程式人生 > >POJ 3977 折半搜索

POJ 3977 折半搜索

typedef which fine integer for each esp val event table

Subset
Time Limit: 30000MS Memory Limit: 65536K
Total Submissions: 4128 Accepted: 796

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(n<=35)個數,求一個它的子集,使其中元素和的絕對值最小。

思路:分成兩半來枚舉。 代碼:
#include "cstdio"
#include "stdlib.h"
#include "iostream"
#include "algorithm"
#include "string"
#include "cstring"
#include "queue"
#include "cmath
" #include "vector" #include "map" #include "set" #define db double #define inf 0x3f3f3f #define mj typedef long long ll; using namespace std; const int N=4000*4000+5; const int maxN=40; typedef pair<ll,int> pii; ll ab(ll x){ return x>0?x:-x; } ll a[maxN]; int main() { int n; while(cin>>n&&n){ for(int i=0;i<n;++i) cin>>a[i]; map<ll,int> m; pii res(ab(a[0]),1); for(int i=0;i<1<<(n/2);++i){ ll sum=0; int num=0; for(int j=0;j<n/2;++j) if((i>>j)&1){ sum+=a[j]; ++num; } if(!num) continue; res=min(res,make_pair(ab(sum),num));//取最小值,優先級從前到後 map<ll,int>::iterator iter=m.find(sum); if(iter!=m.end()) iter->second=min(iter->second,num); else m[sum]=num; } for(int i=0;i<1<<(n-n/2);++i){ ll sum=0; int num=0; for(int j=0;j<(n-n/2);++j) if((i>>j)&1){ sum+=a[n/2+j]; ++num; } if(!num) continue; res=min(res,make_pair(ab(sum),num)); map<ll,int>::iterator iter=m.lower_bound(-sum); if(iter!=m.end()) res=min(res,make_pair(ab(sum+iter->first),num+iter->second)); if(iter!=m.begin()){ --iter; res=min(res,make_pair(ab(sum+iter->first),num+iter->second)); } } printf("%lld %d\n",res.first,res.second); } return 0; }

POJ 3977 折半搜索