Home » Data Structure

Aggressive Cows (On Binary Search)

Here, we are discussing problem named Aggressive Cows based on Binary and its solution.
Submitted by Indrajeet Das, on October 23, 2018

A farmer has built a long barn with N stalls. The stalls are placed in a straight manner at positions from x1, x2, ...xN. But his cows (C) are aggressive and don’t want to be near other cows. To prevent cows from hurting each other, he wants to place them in such a way so that the minimum distance between them is as large as possible. What is the largest minimum distance?


    N: 2<=N<=100,000
    C: 2<=C<=N
    Xi: 0<=Xi<=1,000,000,000


    Line1: Two integers N and C
    Next N lines: An integer for Xi stall's position


    5 3
    1 2 4 8 9



If the cows are placed at 1,4 and 9, it will result in minimum distance from 3.


Since the range of xi is from 0 to 10^9, one can say that the minimum distance between the cows will lie between the range. The minimum distance between 2 stalls can be 0 (lower bound) and maximum distance is 10^9 (upper bound). So, one can check for each value from lower bound to upper bound.

Let's say for k minimum distance, we can check if it is possible to place cows in the stall. In case, you have reached the last stall but didn’t have placed all cows, then it is not possible else it is possible.

A point to note is that if, for a k, it is possible to place the cows. Then all the values less than k will be true. Also, if k is false, then all the values greater than k will be false. We can say it is creating a monotonic function and we have to check for the transition from true to false and return that value.

It can be quickly and easily done with Binary Search from the range of 0 to 10^9.


#include <bits/stdc++.h>
using namespace std;

int N,C;

int check(int num,int stalls[])
	int cows=1,pos=stalls[0];
	for (int i=1; i<N; i++)
		if (stalls[i]-pos>=num)
			if (cows==C)
				return 1;
	return 0;

int binarySearch(int stalls[])
	int start=0,end=stalls[N-1],max=-1;
	while (end>start)
		int mid=(start+end)/2;
		if (check(mid,stalls)==1)
			if (mid>max)
	return max;

int main()
	int t;

	while (t--)
		int stalls[N];
		for (int i=0; i<N; i++)
		int k=binarySearch(stalls);
	return 0;


Aggressive Cows (On Binary Search)

Comments and Discussions

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.