poj2456(二分+贪心)

题目链接:http://poj.org/problem?id=2456

题意:

有n个呈线性排列的牲畜堋,给出其坐标,有c头牛,求把两头牛的最短距离的最大值。

思路:

先将坐标排个序。两头牛的最短距离最小为0,最大为a[n-1]-a[0]。结果一定在这之间,那么就用二分一步步逼近,若m满足要求,则在[m+1,r]之间查找,否则在[l,m-1]之间查找。判断的过程用到贪心的思想。详见代码:

 1 #include<cstdio>
 2 #include<algorithm>
 3 using namespace std;
 4 
 5 int n,c,res;
 6 int a[100005];
 7 
 8 int check(int k){
 9     int last=0,next;
10     for(int i=1;i<c;++i){
11         next=last+1;
12         while(next<n&&a[next]-a[last]<k)
13             ++next;
14         if(next>=n) return 0;
15         last=next;
16     }
17     return 1;
18 }
19 
20 int main(){
21     scanf("%d%d",&n,&c);
22     for(int i=0;i<n;++i)
23         scanf("%d",&a[i]);
24     sort(a,a+n);
25     int l=0,r=a[n-1]-a[0],m;
26     while(l<=r){
27         m=(l+r)>>1;
28         if(check(m)) 
29             res=m,l=m+1;
30         else
31             r=m-1;    
32     }
33     printf("%d
",res);
34     return 0;
35 }
原文地址:https://www.cnblogs.com/FrankChen831X/p/10467568.html