Aggressive cows(POJ 2456)
2024-09-02 16:54:27
- 原题如下:
Aggressive cows
Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 20524 Accepted: 9740 Description
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 distanceSample Input
5 3
1
2
8
4
9Sample Output
3
Hint
OUTPUT DETAILS:FJ can put his 3 cows in the stalls at positions 1, 4 and 8, resulting in a minimum distance of 3.
Huge input data,scanf is recommended.
- 题解:类似的最大化最小值或者最小化最大值的问题,通常用二分搜索法解决。
我们定义:C(d):=可以安排牛的位置使得最近的两头牛的距离不小于d,那么问题就变成了求满足C(d)的最大的d。另外,最近的间距不小于d也可以说成是所有牛的间距都不小于d,因此就有C(d)=可以安排牛的位置使得任意的牛的间距都不小于d,这个问题的判断使用贪心法就可以解决。 - 代码:
#include <cstdio>
#include <cctype>
#include <algorithm>
#include <cmath>
#define num s-'0' using namespace std; const int MAX_N=;
const int INF=0x3f3f3f3f;
int N,M;
int x[MAX_N]; void read(int &x){
char s;
x=;
bool flag=;
while(!isdigit(s=getchar()))
(s=='-')&&(flag=true);
for(x=num;isdigit(s=getchar());x=x*+num);
(flag)&&(x=-x);
} void write(int x)
{
if(x<)
{
putchar('-');
x=-x;
}
if(x>)
write(x/);
putchar(x%+'');
} bool C(int); int main()
{
read(N);read(M);
for (int i=; i<N; i++) read(x[i]);
sort(x, x+N);
int lb=, ub=INF;
while (ub-lb>)
{
int mid=(lb+ub)/;
if (C(mid)) lb=mid;
else ub=mid;
}
write(lb);
putchar('\n');
} bool C(int d)
{
int last=;
for (int i=; i<M; i++)
{
int crt=last+;
while (crt<N && x[crt]-x[last]<d) crt++;
if (crt==N) return false;
last=crt;
}
return true;
}
最新文章
- 悟javascript ---------------20160705
- 学习bootstrap心得
- DP小乐乐化妆品
- 大数据分析的众包平台&mdash;Kaggle
- IIS部署网站
- HDU 5071 Chat(2014鞍山B,模拟)
- LeetCode OJ学习
- phpstorm 强大的活动模板 可以自定义注释,代码段,根据cms订制自动提示
- Unity5.0 手动激活
- FullCalendar 的学习笔记(二)
- Table显示边框
- PencilDraw: 用简化的C语言画图!
- A WPF/MVVM Countdown Timer
- 前端开发——移动bug整理
- BroadcastReceiver基础总结
- spring mvc常用注解的说明
- 常见的磁盘I/O和网络I/O优化技巧
- Git里有些费解的术语和设计
- springboot-全局异常处理类
- Struts2的常见的配置文件介绍