Aggressive cows(c语言)

题目描述
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?

输入

  • Line 1: Two space-separated integers: N and C

  • Lines 2…N+1: Line i+1 contains an integer stall location, xi
    输出

  • Line 1: One integer: the largest minimum distance
    题目描述
    农民约翰建造了一个新的长谷仓,有N(2<= N<= 100,000)摊位。摊位位于 x1,…,xN 位置的直线上(0 < = xi < = 1,000,000,000)。

他的C(2 <= C <= N)奶牛不喜欢这种牛舍布局,一旦被放进马厩,就会变得相互攻击。为了防止奶牛互相伤害,FJ希望将奶牛分配到牛舍,以便它们之间的最小距离尽可能大。最大最小距离是多少?
输入

  • 第 1 行:两个空格分隔的整数:N 和 C

  • 第 2 行…N+1:第 i+1 行包含一个整数停滞位置 xi
    输出

  • 第 1 行:一个整数:最大最小距离
    样例输入
    5 3
    1
    2
    8
    4
    9
    样例输出
    3
    提示
    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可以将他的3头奶牛放在1,4和8位置的畜栏中,从而产生最小距离为3。
    输入数据量大,建议使用扫描。

#include<stdio.h>
int judge(int mid,int n,int c,int a[])
{
    int i,count=1,t=a[0]; //count是指放了几头牛,从1开始。t用来表示当前的房间号
    for(i=1; i<n; i++)
    {
        if(a[i]-t>=mid)//判断两个房间之间的距离
        {
            count++;
            t=a[i];//修改t的值,即修改当前房间号,例如原来t=1,a[2]=4,若a[2]-t>=mid符合,那么t=4,然后算a[3]或者a[4]与t之间的距离。
            if(count>=c)//可以放下C头牛
                return 1;
        }
    }
    return 0;
}
int binary(int a[],int n,int c)//二分搜索符合条件的最小距离的最大值
{
    int low=0,high=a[n-1]-a[0],mid;
    while(low<=high)
    {
        mid=(low+high)/2;//mid即为最小房间号与最大房间号之间的距离
        if(judge(mid,n,c, a))
            low=mid+1;//所求距离>=mid,可以继续增大试探
        else
            high=mid-1;//所求距离<mid,所以必须减小来试探
    }
    return low-1; //由于在之前距离+1,所以此时-1
}
int main()
{   int a[100005],n,c;
    while(~scanf("%d%d",&n,&c))
    {
        int i;
        for(i=0; i<n; i++)
            scanf("%d",&a[i]);
        for(int i=0;i<n-1;i++)
        for(int j=i+1;j<n;j++)
        if(a[i]>a[j]){
        	int t=a[i];
        	a[i]=a[j],a[j]=t;
        }
        printf("%d\n",binary(a,n,c));
    }
    return 0;
}

  • 6
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值