Aggressive Cows — SPOJ

Rushyab
2 min readAug 5, 2019

Being the most upvoted problem on SPOJ, Aggressive Cows forces you to think like an Algorithmist. I have seen a lot of people (including me) who are getting started with competitive programming, struggle with this problem.

But once you get the gist of how to approach it, the implementation part becomes fairly straightforward.

The problem description can be read here.

Overview: All the C cows must be placed in the N stalls such that the minimum distance between any two of them is as large as possible. Print the largest distance.

Solution: Lets first define a function chk(x) that checks if a distance x is possible between each of the cows. We can use a greedy approach here by placing cows at the leftmost possible stalls such that they are at least x distance away from the last-placed cow.

As you can see in the above picture, we have taken the stall locations in increasing…

--

--