POJ 3977:Subset(折半枚举+二分)
2024-09-07 18:56:00
【题目链接】 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;
}
最新文章
- windows系统路径环境变量
- 基于FormsAuthentication的用户、角色身份认证
- cookie 操作
- NOIP2013 提高组day2 3 华容道 BFS
- lintcode :Integer to Roman 整数转罗马数字
- dorado7第一次使用感受
- 基于GBT28181:SIP协议组件开发-----------第五篇SIP注册流程eXosip2实现(二)
- 金蝶KIS专业版替换SXS.dll 遭后门清空数据被修改为【恢复数据联系QQ 735330197,2251434429】解决方法 修复工具。
- 单击Echart饼图实现数据钻取
- c oth
- python 读csv格式的文件
- web.config中连接字符串的读写和加密解密
- [日常] Go语言圣经-错误,函数值习题
- python resize
- 压力测试工具ab及centos下单独安装方法 nginx和tomcat静态资源的性能测试
- Eclipse------导入项目后出现javax.servlet.jsp cannot be resolved to a type
- postgresql 匿名函数(单独执行代码段)
- Intelligent Factorial Factorization LightOJ - 1035(水题)
- HDU 1521 指数型母函数
- LinuxUnix time时间戳的处理转换函数
热门文章
- pycharm安装scipy,安装失败
- android 自定义控件之下拉刷新源码详解
- BI商业智能培训系列——(一)概述
- 详解Linux运维工程师应具备的十大技能
- [YNOI2017][bzoj4811][luogu3613] 由乃的OJ/睡觉困难综合症 [压位+树链剖分+线段树]
- [zoj] 1081 Points Within || 判断点是否在多边形内
- BZOJ4890 [Tjoi2017]城市 【树形dp】
- 【马克-to-win】学习笔记—— 第五章 异常Exception
- Java基础复习--java.util.Timer定时任务
- 配置sanmba