• 二分 例题2


    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.
     1 #include <stdio.h>
     2 #include <string.h>
     3 #include <math.h>
     4 #include <algorithm>
     5 using namespace std;
     6 const int INF=1e9+7;
     7 
     8 int N,m;
     9 int a[100005];
    10 
    11 bool C(int d)
    12 {
    13     int last=1;
    14     for(int i=1;i<m;i++)
    15     {
    16         int crt=last+1;
    17         while(crt<=N && a[crt]-a[last]<d)
    18         {
    19             crt++;
    20         }
    21         if(crt==N+1)
    22             return false;
    23         last=crt;
    24     }
    25     return true;
    26 }
    27 
    28 int main()
    29 {
    30     int i,j;
    31     while(scanf("%d %d",&N,&m)!=EOF)
    32     {
    33         for(i=1;i<=N;i++)
    34             scanf("%d",&a[i]);
    35         sort(a+1,a+N+1);
    36         int lb=0,ub=INF;
    37         while(ub-lb>1)
    38         {
    39             int mid=(lb+ub)/2;
    40             if(C(mid))
    41                 lb=mid;
    42             else
    43                 ub=mid;
    44         }
    45         printf("%d
    ",lb);
    46     }
    47     return 0;
    48 }
    View Code
  • 相关阅读:
    一个涉及到浮点寄存器的CM
    树和二叉树一篇就搞定!
    串的两种模式匹配方式(BF/KMP算法)
    队列的知识讲解与基本实现(数据结构)
    如何用C++实现栈
    判断List集合为空还是null的正确打开方式
    双链表的基本实现与讲解(C++描述)
    Redis从认识安装到实现增删改查
    如何使用C++实现单链表
    线性表——顺序表的实现与讲解(C++描述)
  • 原文地址:https://www.cnblogs.com/cyd308/p/4693662.html
Copyright © 2020-2023  润新知