题目描述
陶陶是个贪玩的孩子,他在地上丢了A个瓶盖,为了简化问题,我们可以当作这A个瓶盖丢在一条直线上,现在他想从这些瓶盖里找出B个,使得距离最近的2个距离最大,他想知道,最大可以到多少呢?
输入
第一行,两个整数,A,B。(B<=A<=100000)
第二行,A个整数,分别为这A个瓶盖坐标。
输出
仅一个整数,为所求答案。
样例输入
5 3
1 2 3 4 5
样例输出
2
题目说明
限时3秒
题目思路
二分法,重点在于写check函数,第一个瓶盖是必选的,之后贪心的选择第一个能让距离大于等于所check的答案,然后再以这个瓶盖继续贪心选择下一个。之后判断选择的瓶盖数量。
题目代码
#include <iostream>
#include <cstring>
#include <cmath>
#include <string>
#include <cstdio>
#include <vector>
#include <algorithm>
#define LL long long
#define INF 99999999
using namespace std;
int a, b;
int l, r, mid;
int n[100005];bool check(int x){int tot = 1; int last = 0;for(int i = 1; i < a; i++){if(n[i] - n[last] >= x){tot++;last = i;}}if(tot >= b)return true;elsereturn false;
}int main(){freopen("input.txt", "r", stdin);scanf("%d%d",&a,&b);for(int i = 0; i < a; i++){scanf("%d",&n[i]);}sort(n,n+a);r = n[a-1] - n[0];l = 1;while(l < r){mid = (l+r+1) >> 1;if(check(mid))l = mid;elser = mid - 1;}printf("%d\n",l);return 0;
}