码迷,mamicode.com
首页 > 其他好文 > 详细

Aggressive cows

时间:2014-07-26 00:23:36      阅读:286      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   java   color   使用   os   

Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u

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

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.
 

FJ 有一个很长的 barn ,然后里面有 N 棚, N 个棚在一条直线上,第 i 个棚的位置为 xi.

然后他有 c 只羊,为了防止羊相互攻击,则要找出最大的两只羊之间距离,前提是这 c 只羊都必须能放下哈。

解题思路:先将 xi 由小到大排序, xn 最大。设这个最大距离为 s;0<s<=(xn-x1)/(c-1), 因为 c 只羊需要 c-1 个间隔。使用二分找 s 的可能取值,然后用贪心看是否成立。

Left=0;

right=(xn-x1)/(c-1);

mid=(left+right)/2; 如果间隔 mid 能够放下 c 只羊,则最大间隔在 [mid,right] ;

否则 [left,mid-1]. 继续寻找。

二分+贪心

#include <iostream> 
#include <stdio.h> 
#include<stdlib.h>
using namespace std; 
#define MAXN 100003 

int cmp(const void *x,const void *y){ 

    return *(int *)x-*(int *)y;  

} 

int a[MAXN]; 
int N,C; 
bool greed(int x)

{ 
     int cn=0; 
     int p=a[0]; 
     for (int i=1;i<N;i++) 
         if (a[i]>=p+x) 
         { 
              cn++; 
              p=a[i]; 
         } 
     if (cn>=C-1) 
         return true ; 
     return false ; 
} 

int main() 

{ 
     while (scanf("%d%d" ,&N,&C)!=EOF) 
     { 
         for (int i=0;i<N;i++) 
              scanf("%d" ,&a[i]); 
         qsort(a,N,sizeof (a[0]),cmp);
         int left,right,mid; 
         left=0; 
         right=(a[N-1]-a[0])/(C-1);
         while (left<=right) 
         { 
              mid=(left+right)/2; 
              //printf("%d %d %d\n" ,left,right,mid); 
              if (greed(mid))
                   left=mid+1; 
              else
                   right=mid-1; 
         } 
         printf("%d\n" ,left-1);

     } 
     return 0; 

} 

Aggressive cows,布布扣,bubuko.com

Aggressive cows

标签:des   style   blog   http   java   color   使用   os   

原文地址:http://www.cnblogs.com/lipching/p/3868326.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!