zoukankan      html  css  js  c++  java
  • POJ_2456_Agressive_cows_(二分,最大化最小值)

    描述


    http://poj.org/problem?id=2456

    有n个小屋,线性排列在不同位置,m头牛,每头牛占据一个小屋,求最近的两头牛之间距离的最大值.

    Aggressive cows
    Time Limit: 1000MS   Memory Limit: 65536K
    Total Submissions: 10095   Accepted: 4997

    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.

    Source

    分析


    二分.

    最大化最小值.

    C(x)表示使两头牛之间最小距离为x,问题转化为求满足C(x)的x的最大值.可知x<=(总长)/(c-1).那么1~(总长)/(c-1)二分求解即可.

     1 #include<cstdio>
     2 #include<algorithm>
     3 using std :: sort;
     4 
     5 const int maxn=100005;
     6 int n,c;
     7 int a[maxn];
     8 
     9 void init()
    10 {
    11     scanf("%d%d",&n,&c);
    12     for(int i=1;i<=n;i++) scanf("%d",&a[i]);
    13     sort(a+1,a+n+1);
    14 }
    15 
    16 bool judge(int x)
    17 {
    18     int last=1;
    19     for(int i=2;i<=c;i++)
    20     {
    21         int now=last+1;
    22         while(now<=n&&(a[now]-a[last]<x)) now++;
    23         if(now>n) return false;
    24         last=now;
    25     }
    26     return true;
    27 }
    28 
    29 
    30 int bsearch(int x,int y)
    31 {
    32     while(x<y)
    33     {
    34         int m=x+(y-x+1)/2;
    35         if(judge(m)) x=m;
    36         else y=m-1;
    37     }
    38     return x;
    39 }
    40 
    41 void solve()
    42 {
    43     int INF=(a[n]-a[1])/(c-1);
    44     printf("%d
    ",bsearch(1,INF));
    45 }
    46 
    47 int main()
    48 {
    49     freopen("cow.in","r",stdin);
    50     freopen("cow.out","w",stdout);
    51     init();
    52     solve();
    53     fclose(stdin);
    54     fclose(stdout);
    55     return 0;
    56 }
    View Code
  • 相关阅读:
    Google笔试题
    OpenStack Ceilometer简介
    OpenStack Object Storage(Swift)架构、原理及特性
    【大话存储2读书笔记】磁盘IO的重要概念
    递归,汉诺塔游戏
    函数定义与使用
    字符串操作
    for循环:用turtle画一颗五角星
    列表、元组、字典、集合的定义、操作与综合练习
    npm 相关
  • 原文地址:https://www.cnblogs.com/Sunnie69/p/5423173.html
Copyright © 2011-2022 走看看