一道简单而经典的二分,借用一点挑战上的方法
来源:互联网 发布:编程一小时网站登录 编辑:程序博客网 时间:2024/06/07 01:56
Aggressive cows
题目:Farmer John has built a new long barn, with N (2 <= N <= 100,000) stalls. The stalls are located along a straight line at positions x1,...,xN (0 <= xi <= 1,000,000,000).
His C (2 <= C <= N) cows don't like this barn layout and become aggressive towards each other once put into a stall. To prevent the cows from hurting each other, FJ want to assign the cows to the stalls, such that the minimum distance between any two of them is as large as possible. What is the largest minimum distance?
Input:
* Line 1: Two space-separated integers: N and C
* Lines 2..N+1: Line i+1 contains an integer stall location, xi
Output:
* Line 1: One integer: the largest minimum distance
Simple Input:
5 3
1
2
8
4
9
Simple Output:
3
题目大意:
约翰新建了一座谷仓,谷仓的N个摊位的位置分别为x1,...,xN (0 <= xi <= 1,000,000,000)。
他的C头牛对于谷仓的布局不满意,经常在进入摊位后相互侵略。为了防止它们继续发生冲突,约翰要将这些牛放进摊位中使得每两头牛之间的最小距离尽可能大,请设计一个程序将其计算出来。
代码如下:
#include <cstdio>#include <algorithm>using namespace std;int N,C,l,u,mid;const int Max=1e9+15;const int maxn=1e5+100;int X[maxn]; //摊位的位置;bool OK(int d){ int crt=1,last=0; for(int i=1;i<N;i++){ if(X[i]-X[last]>=d){ last=i; crt++; } } if(crt>=C) return true; else return false; //通过计算最后满足所选中间值的摊位数量与牛的数量进行比较来将摊位间的距离缩小;}int main(){ while(~scanf("%d%d",&N,&C)){ for(int i=0;i<N;i++){ scanf("%d",&X[i]); } sort(X,X+N); //将摊位的位置进行排序,方便后面的二分时遍历; u=Max; l=0; //定义初始上下限; while(u-l>1){ mid=(u+l)/2; if(OK(mid)) l=mid; else u=mid; //逐渐缩小范围,直到无法继续缩小时结束二分,取最后一次的下限作为最终取值; } printf("%d\n",l); }}
个人觉得这个题目是一个极其经典的二分,可以作为一个模板。
阅读全文
1 0
- 一道简单而经典的二分,借用一点挑战上的方法
- 五子棋接龙:一个简单而有趣的挑战
- 练习题(4) -- 一道简单而有有趣的题目
- GLSurfaceView的简单分析及巧妙借用
- 经典的一道题目.
- 一道看似简单的sql需求却难倒各路高手 - 你也来挑战下吗
- 一道神奇的二分题
- 一个简单而经典的RTX51 Tiny应用实例
- 一道经典的笔试题
- 一道经典的面试题
- 一道表达式的经典试题
- 一道表达式的经典试题
- 一道经典的C++竞赛题
- hdu1016(一道经典的dfs)
- js的一道经典题目
- js的一道经典题目
- 一道简单的题目
- 一道简单的题
- java快速排序
- 6. PIBOT的通讯协议
- MySQL基础(二)数据库、表的创建及操作
- 搭建调试符号服务器
- JavaScript基础总结
- 一道简单而经典的二分,借用一点挑战上的方法
- php 数据库连接代码
- Six Degrees of Cowvin Bacon poj 2139
- 如何比较不同浏览器的页面加载时间
- 使用maven 安装第三方jar包
- 7. PIBOT的Firmware的代码分析(1)
- 多线程下载原理及核心代码
- bzoj 1804: [Ioi2007]Flood 洪水
- 云计算