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;
    }
    

      

     
  • 相关阅读:
    Go语言v1.8正式发布,有显著的性能提升和变化(go适合服务器编程、网络编程)
    NET生成二维码
    组合模式
    Spring MVC
    前端事件
    Play Framework + ReactiveMongo
    DDD领域驱动设计初探
    jsRender模板引擎
    C#分布式缓存Couchbase
    ABP
  • 原文地址:https://www.cnblogs.com/a249189046/p/6864533.html
Copyright © 2011-2022 走看看