您的位置:首页 > 其它

poj 2456 Aggressive cows 二分

2014-08-04 17:01 232 查看
Aggressive cows

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 6030 Accepted: 3016
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 distance
Sample Input
5 3
1
2
8
4
9

Sample Output
3

反思: 每次写二分都是调试半天:
while(st<ed) {
int mid=(St+ed)>>1;
if(OK(mid)) st=mid;
else ed=mid-1;
}

这个写法的的漏洞在于 当st+1==ed && mid=st && OK(mid) ==1 时候,不能更新st 与ed 的值,所以陷入死循环;

最简单的写法其实就是:
    int st = 0 , ed = INF , mid ;
    while( st + 1 < ed ){
        mid = ( st + ed ) >> 1 ;
        if(OK( mid )) st = mid;
        else ed = mid;
    }
    printf("%d\n",st);
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<string>
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<list>
#include<map>
#include<set>
using namespace std;
const int N = 100010;
const int INF = 1e9 + 100;

int n,C;
int a
;

bool OK( int x ){
int cnt = 1 ;
int fi = 0 , se = 0;
while( fi < n ){
se = fi;
fi = lower_bound( a , a + n, a[se] + x )-a ;
if( fi < n ) cnt ++ ;
}
if(cnt >= C ) return 1;
return 0;
}
void work(){
sort(a , a + n);

int st = 0 , ed = INF , mid ;
while( st + 1 < ed ){
mid = ( st + ed ) >> 1 ;
if(OK( mid )) st = mid;
else ed = mid;
}
printf("%d\n",st);

}
int main()
{

//	freopen("in.in","r",stdin);
while(~scanf("%d%d",&n,&C)){
for(int i = 0 ; i < n ; i ++)
scanf("%d", &a[i]);
work();
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: