1. 程式人生 > >POJ 百練 2456:Aggressive cows

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

可恨的是超時了,啊啊啊