zoukankan      html  css  js  c++  java
  • POJ 2456(二分)

    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
     
    分析:由题左右两端一定会有一只,
             然后我们可以二分相隔长度,找到能相隔的最大的长度。
          (挑战书上的最大化最小值类型)
    代码如下:
    #include <cstdio>
    #include <iostream>
    #include <algorithm>
    using namespace std;
    int c[100010];
    int n,m,minn,maxx,l,r,mid;
    int check(int x)
    {
    	int dl,dr;
       int f=1,num;
       int cnt=0;
       dl=c[0];
       dr=c[n-1];
       num=n-2;
       for(int i=1;i<=num;i++)
       {
       	   if(c[i]-dl>=x&&dr-c[i]>=x)
       	   {
       	   	cnt++;
       	    dl=c[i];	
       	   }
       }	
       if(cnt>=m-2)
       return 1;
       return 0; 
    }
    int main()
    {
    	
    	while(scanf("%d%d",&n,&m)!=EOF)
    	{
    		maxx=-1;
    		minn=1e9;
    		for(int i=0;i<n;i++)
    		{
    		scanf("%d",&c[i]);
    		maxx=max(maxx,c[i]);
    		minn=min(minn,c[i]);
    		
    		}
    		sort(c,c+n);
    		l=1;
    		r=(maxx-minn)/(m-1)+1;
    		while(l+1<r)
    		{
                  mid=(l+r)/2;
    			  if(check(mid))
    			    l=mid;	
    			  else
    			    r=mid;		
    		}
    	   printf("%d
    ",l);
    	}
    	return 0;
    }
    

      

     
  • 相关阅读:
    让SiteMapDataSource能选择特定的SiteMap文件
    程序员之路──如何学习C语言(转载)
    Sql Server 2005 Express使用命令工具无法连接问题
    移远公司 NBIoT模块AT指令详细解释
    Excel自动化技术
    解析HTTP报文头
    SOAP报文下发
    双缓冲队列,生产者消费者模式
    夸孩子少用“你真棒”,教你如何夸孩子
    C++面试题相关
  • 原文地址:https://www.cnblogs.com/a249189046/p/6864533.html
Copyright © 2011-2022 走看看