洛谷 [P1182] 数列分段
来源:互联网 发布:ubuntu 国内源 编辑:程序博客网 时间:2024/05/16 12:59
这是一道典型的二分答案问题(最大值最小,最小值最大)关键是对于细节的处理。
二分的框架:
//l=max{num[i]},r=sum{num[i]}while(l<=r){ int m=(l+r)>>1; if(chk(m)){ r=m-1; }else l=m+1; } cout<<l;
二分的框架是普遍使用的,关键是检验函数的设计,此处的检验函数的含义为: 是否存在一种合法的划分,使得每段的最大值都不大于m。
设计好了检验函数,就要思考l与r的转移:若存在这种合法的划分,说明m偏大,r=m-1;反之,l=m+1.
此处应注意l的初始值为num中的最大值。
#include <iostream>#include <cstdio>#include <algorithm>#include <cstring>using namespace std;int read(){ int rv=0,fh=1; char c=getchar(); while(c<'0'||c>'9'){ if(c=='-') fh=-1; c=getchar(); } while(c>='0'&&c<='9'){ rv=(rv<<1)+(rv<<3)+c-'0'; c=getchar(); } return fh*rv;}int n,m,num[100005],pre[100005];bool chk(int x){ int tot=0,last=0; for(int i=1;i<=n;i++){ if((pre[i]-pre[last])>x){ tot++; last=i-1; } } tot++; if(tot<=m) return 1; else return 0;} int main(){ freopen("in.txt","r",stdin); n=read();m=read(); int l=1,r,m=0; for(int i=1;i<=n;i++){ num[i]=read(); l=max(l,num[i]); pre[i]=pre[i-1]+num[i]; } r=pre[n]; while(l<=r){ int m=(l+r)>>1; if(chk(m)){ r=m-1; }else l=m+1; } cout<<l; int t; fclose(stdin); return 0;}
阅读全文
0 0
- 洛谷 [P1182] 数列分段
- 洛谷 P1182数列分段Section II
- 洛谷 P1182 数列分段Section II
- |洛谷|二分|P1182 数列分段Section II
- 洛谷 P1182 数列分段Section II
- 【分治】洛谷 P1182 数列分段Section II
- P1182 数列分段Section II
- 水——洛谷P1182 数列分段Section II
- 洛谷P1182 数列分段Section II(二分)
- luogu P1182 数列分段Section II
- 数列分段-洛谷 1181
- 洛谷P1181 数列分段
- 数列分段
- 数列分段
- 数列分段
- 数列分段
- 数列分段
- 数列分段
- Android:一个设备安装多个包(生产包,测试包等)
- 20171019—每日一练
- C++重载与多态的区别
- USB Power Delivery Specification(USB-PD)
- Gradle 下载文件很慢
- 洛谷 [P1182] 数列分段
- 最完整,增删改查,月份 id 过滤
- YUV数据格式
- 集成学习——Boosting总结
- 框架
- font-size:0的妙用
- 如何使用AsyncTask防止内存泄漏(Handler同理)
- PBE加解密
- Servlet API中主要的接口与类