Friday, 5 June 2020

AGGRCOW - Aggressive cows

See on SPOJ

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 wants 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

t – the number of test cases, then t test cases follows.
* Line 1: Two space-separated integers: N and C
* Lines 2..N+1: Line i+1 contains an integer stall location, xi

Output
For each test case output one integer: the largest minimum distance.

Example
Input:
1
5 3
1
2
8
4
9
Output:
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.



Solution: Binary Search

Well, the hint is already given in the SPOJ problem page. But it is confusing at the same time. Because you won't get the solution using Binary Search. Binary search will get you the optimal solution, but you need to still find a way to get all possible solutions.

Let Lim =1,000,000,000
To start thinking of a solution you need first choose the minimum difference between any 2 stable and then verify whether that minimum distance would work or not. Let suppose you have devised a function Fn(x), which tells you whether minimum distance x would is possible or not. Now what, now you will check this for all the numbers 0....Xi.....Lim.

0 is always possible since you can fill all the cows in one stable.

0, 1, 2 ...... Xi, Xi+1,......Lim


you will see that it is always possible to have a small number as a difference between stable, and as you increase the x you might reach a point where it is unstable. In other ways, you need to find Xi where Fn(Xi) is possible but Fn (Xi+1) is not. And X will be your answer. So to find X you can apply binary search on 0 to Lim and find X.

Now our job is to write Fn(X) and binary search which uses this Fn. 
Let me give you time to try this before I post my solution.