【题目链接】 http://poj.org/problem?id=3977

【题目大意】

  在n个数(n<36)中选取一些数,使得其和的绝对值最小.

【题解】

  因为枚举所有数选或者不选,复杂度太高无法承受,
  我们考虑减小枚举的范围,我们将前一半进行枚举,保存其子集和,
  然后后一半枚举子集和取反在前一半中寻找最接近的,两部分相加用以更新答案。

【代码】

#include <cstdio>
#include <utility>
#include <algorithm>
#include <map>
using namespace std;
typedef long long LL;
const int N=40;
int n; LL a[N];
LL Abs(LL x){return x<0?-x:x;}
int main(){
while(scanf("%d",&n)&&n){
for(int i=0;i<n;i++)scanf("%lld",&a[i]);
map<LL,int> M;
map<LL,int>::iterator it;
pair<LL,int> ans(Abs(a[0]),1);
for(int i=1;i<1<<(n/2);i++){
LL s=0; int cnt=0;
for(int j=0;j*2<n;j++){if((i>>j)&1)s+=a[j],cnt++;}
ans=min(ans,make_pair(Abs(s),cnt));
if(M[s])M[s]=min(M[s],cnt);
else M[s]=cnt;
}
for(int i=1;i<1<<(n-n/2);i++){
LL s=0; int cnt=0;
for(int j=0;j<(n-n/2);j++){
if((i>>j)&1)s+=a[j+n/2],cnt++;
}ans=min(ans,make_pair(Abs(s),cnt));
it=M.lower_bound(-s);
if(it!=M.end())ans=min(ans,make_pair(Abs(s+it->first),cnt+it->second));
if(it!=M.begin()){
it--;
ans=min(ans,make_pair(Abs(s+it->first),cnt+it->second));
}
}printf("%lld %d\n",ans.first,ans.second);
}return 0;
}

  

最新文章

  1. windows系统路径环境变量
  2. 基于FormsAuthentication的用户、角色身份认证
  3. cookie 操作
  4. NOIP2013 提高组day2 3 华容道 BFS
  5. lintcode :Integer to Roman 整数转罗马数字
  6. dorado7第一次使用感受
  7. 基于GBT28181:SIP协议组件开发-----------第五篇SIP注册流程eXosip2实现(二)
  8. 金蝶KIS专业版替换SXS.dll 遭后门清空数据被修改为【恢复数据联系QQ 735330197,2251434429】解决方法 修复工具。
  9. 单击Echart饼图实现数据钻取
  10. c oth
  11. python 读csv格式的文件
  12. web.config中连接字符串的读写和加密解密
  13. [日常] Go语言圣经-错误,函数值习题
  14. python resize
  15. 压力测试工具ab及centos下单独安装方法 nginx和tomcat静态资源的性能测试
  16. Eclipse------导入项目后出现javax.servlet.jsp cannot be resolved to a type
  17. postgresql 匿名函数(单独执行代码段)
  18. Intelligent Factorial Factorization LightOJ - 1035(水题)
  19. HDU 1521 指数型母函数
  20. LinuxUnix time时间戳的处理转换函数

热门文章

  1. pycharm安装scipy,安装失败
  2. android 自定义控件之下拉刷新源码详解
  3. BI商业智能培训系列——(一)概述
  4. 详解Linux运维工程师应具备的十大技能
  5. [YNOI2017][bzoj4811][luogu3613] 由乃的OJ/睡觉困难综合症 [压位+树链剖分+线段树]
  6. [zoj] 1081 Points Within || 判断点是否在多边形内
  7. BZOJ4890 [Tjoi2017]城市 【树形dp】
  8. 【马克-to-win】学习笔记—— 第五章 异常Exception
  9. Java基础复习--java.util.Timer定时任务
  10. 配置sanmba