POJ 百练 2456:Aggressive cows

描述

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?

输入

* Line 1: Two space-separated integers: N and C

* Lines 2..N+1: Line i+1 contains an integer stall location, xi

输出

* Line 1: One integer: the largest minimum distance

样例输入

5 3
1
2
8
4
9

样例输出

3

提示

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.

解答思路:

先得到排序后的隔间坐标 x 0 ,...,x N-1
在[L,R]内用二分法尝试“最大最近距离”D = (L+R)/2 (L,R初值为[1, 1,000,000,000/C]
若D可行,则记住该D,然后在新[L,R]中继续尝试(L= D+1)
若D不可行,则在新[L,R]中继续尝试(R= D-1)
复杂度 log(1,000,000,000/C) * N

如何尝试D呢,把D代入进行检查,从第一个隔间位置开始遍历计数,每经过一个距离大于等于D的隔间就计数,若最终计数大于牛数量,则说明满足要求。

C++编程实现:

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int judge(int , int);
int arr[100000];
int n,c;
int main()
{
    scanf("%d%d",&n,&c);
    for(int i = 0; i < n; i++){   //大规模输入输出采用scanf和printf
        scanf("%d",&arr[i]);
    }
    sort(arr,arr+n);  //对存储着隔间位置的数组排序
    int l = arr[0];   //隔间起点
    int r = arr[n-1] - arr[0];    //隔间终点
    int D;
    while(r >= l){
        D = (l + r) >> 1;     // D = (l + r) / 2;
        if(judge(n, D) >= c)    //判断D是否满足要求
            l = D + 1;
        else
            r = D - 1;
    }
    printf("%d\n",l-1);
    return 0;
}
int judge(int n, int D){
    int i,s = 1,p = arr[0];
    for(i = 1; i < n; i++){
        if(arr[i] - p >= D){
            s++;
            p = arr[i];
        }
    }
    return s;
}

JAVA编程实现:

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static int n,c;
    public static int arr[];
    public static void main(String args[]){
        Scanner scan = new Scanner(System.in);
        n = scan.nextInt();
        c = scan.nextInt();
        arr = new int[n];
        for(int i = 0; i < n; i++)
            arr[i] = scan.nextInt();

        Arrays.sort(arr);
        int l = arr[0];
        int r = arr[n-1] - arr[0];
        int D = 0;
        while(r >= l){
            D = (l + r) >> 1;
            if(judge(D)>=c){
                l = D + 1;
            }else{
                r = D - 1;
            }
        }
        System.out.println(l-1);
    }
    public static int judge(int D){
        int i, s = 1, p = arr[0];
        for(i = 1; i < n; i++){
            if(arr[i] - p >= D){
                s++;
                p = arr[i];
            }
        }
        return s;
    }
}

可恨的是超时了,啊啊啊

猜你喜欢

转载自blog.csdn.net/qq_25406563/article/details/83052179
今日推荐