MOOSACO Solution: Bullies

The approach is to find the maximum and minimum valued cows at each ($2*R-1$) by ($2*R-1$) square, and simply output whether there exists a square where the maximum - the minimum > the bullying threshold.

To do this, you can use a sliding window to find the max and min cows at each interval on a 1D scale and save it in an array, and do it for each row. Then, you can do the same thing, but vertically and on the array resulting from the previous operation. Now, you have the maximums and minimums of each square.

Using a multiset, this solution is (N log N)$^2$, which will TLE. Instead, you can use the monotonic queue algorithm instead of a multiset to run in N$^2$ time and be fast enough.

Code not available