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

      

     
  • 相关阅读:
    银行卡号每隔4位插入空格
    IE6-8下自定义标签的表现
    Sql Server尝试读取或写入受保护的内存。这通常指示其他内存已损坏
    儿童编程教学scratch 3.0
    Shell 教程入门
    自定义vs2005代码段
    解决Adobe ReaderXI自动关闭问题
    WPF——给button添加背景图片
    WPF 异步加载数据
    Caliburn.Micro中的WindowManager
  • 原文地址:https://www.cnblogs.com/a249189046/p/6864533.html
Copyright © 2011-2022 走看看