Aggressive Cows
Finds the largest minimum distance to place cows in stalls using Binary Search on the answer.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool canPlace(vector<int>& stalls, int c, int dist) {
int count = 1, last = stalls[0];
for (int i = 1; i < stalls.size(); i++) {
if (stalls[i] - last >= dist) {
count++;
last = stalls[i];
}
}
return count >= c;
}
int main() {
cout << "INSTRUCTIONS: Enter n (stalls) and c (cows), followed by n stall positions." << endl;
int n, c;
cin >> n >> c;
vector<int> stalls(n);
for (int i = 0; i < n; i++) cin >> stalls[i];
sort(stalls.begin(), stalls.end());
int low = 0, high = stalls[n - 1], ans = 0;
while (low <= high) {
int mid = (low + high) / 2;
if (canPlace(stalls, c, mid)) {
ans = mid;
low = mid + 1;
} else
high = mid - 1;
}
cout << ans;
}Aggressive Cows — Free C++, C, Python Code Example
Finds the largest minimum distance to place cows in stalls using Binary Search on the answer. This free code example is available in C++, C, Python and can be copied and run immediately — no account or signup required. Use the language tabs above to switch between implementations.
How to Use This Code
- Select your language — click the language tab (C, Java, C++, or Python) above the code viewer.
- Copy the code — use the copy button in the top-right corner of the code block.
- Run it — paste into a file with the correct extension (.c, .java, .cpp, .py), compile, and run using your terminal or IDE.
- Follow the on-screen instructions in the terminal to provide any required inputs.
Frequently Asked Questions
What does this program do?
Finds the largest minimum distance to place cows in stalls using Binary Search on the answer.
Which languages is it available in?
Available in C++, C, Python. Switch between implementations using the tabs at the top of the code viewer.
How do I run this code?
Copy the code, save it with the right file extension (.c, .java, .cpp, or .py), then compile or run it with your installed compiler or interpreter (GCC, JDK, G++, Python 3).
Is this code free?
Yes — free to view, copy, and use. No account required.