首页 > 代码库 > POJ 3977 折半搜索
POJ 3977 折半搜索
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 折半搜索
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。