P1316 丢瓶盖

题目描述

陶陶是个贪玩的孩子,他在地上丢了A个瓶盖,为了简化问题,我们可以当作这A个瓶盖丢在一条直线上,现在他想从这些瓶盖里找出B个,使得距离最近的2个距离最大,他想知道,最大可以到多少呢?

输入输出格式

输入格式:

第一行,两个整数,A,B。(B<=A<=100000)

第二行,A个整数,分别为这A个瓶盖坐标。

输出格式:

仅一个整数,为所求答案。

输入输出样例

输入样例#1:

5 3
1 2 3 4 5
输出样例#1:

2

说明

限时3秒

P1824 进击的奶牛

题目描述

Farmer John建造了一个有N(2<=N<=100,000)个隔间的牛棚,这些隔间分布在一条直线上,坐标是x1,...,xN (0<=xi<=1,000,000,000)。

他的C(2<=C<=N)头牛不满于隔间的位置分布,它们为牛棚里其他的牛的存在而愤怒。为了防止牛之间的互相打斗,Farmer John想把这些牛安置在指定的隔间,所有牛中相邻两头的最近距离越大越好。那么,这个最大的最近距离是多少呢?

输入输出格式

输入格式:

第1行:两个用空格隔开的数字N和C。

第2~N+1行:每行一个整数,表示每个隔间的坐标。

输出格式:

输出只有一行,即相邻两头牛最大的最近距离。

输入输出样例

输入样例#1:

5 3
1
2
8
4
9
输出样例#1:

3

【题解】

二分答案

从第一个开始贪心放即可,证明显然

 #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm> inline void read(int &x)
{
x = ;char ch = getchar(), c = ch;
while(ch < '' || ch > '')c = ch, ch = getchar();
while(ch <= '' && ch >= '')x = x * + ch - '', ch = getchar();
if(c == '-')x = -x;
} const int MAXN = + ; int n,num[MAXN],m,ans; bool check(int k)
{
int pre = , cnt = ;
for(register int i = ;i <= n;++ i)
if(num[i] - num[pre] >= k)++ cnt, pre = i;
if(cnt >= m)return ;
return ;
} int main()
{
freopen("data.txt", "r", stdin);
read(n);read(m);
for(register int i = ;i <= n;++ i)
read(num[i]);
std::sort(num + , num + + n);
register int l = , r = num[n] - num[],mid;
while(l <= r)
{
mid = (l + r) >> ;
if(check(mid))l = mid + , ans = mid;
else r = mid - ;
}
printf("%d", ans);
return ;
}

洛谷P1316 P1824

05-11 19:48