Birds on a Wire

The problem input provides us the length of the wire, the minimum distance between two birds, and the positions of each bird so far. All we need to do to maximize the number of additional birds on the wire is to greedily place a new bird wherever it can fit, i.e. the minimum distance from the previous bird. Although we don't need to place one bird at a time--since the minimum distance is constant, the number of birds we can fit on an empty section of the wire that spans [start,end] is (end-start)/minimum distance + 1. The tricky part is determining the start and end of each section. Once that is done, simply cram as many birds onto the wire as possible and report the total.

birds.cpp
birds.py

_34
#include <iostream>
_34
#include <vector>
_34
#include <algorithm>
_34
_34
using namespace std;
_34
using ll = long long;
_34
_34
// birds can't sit any closer to the poles than this
_34
const ll offset = 6;
_34
_34
int main() {
_34
ll n, l, d;
_34
cin >> l >> d >> n;
_34
vector<ll> birds(n);
_34
for (auto &b : birds)
_34
cin >> b;
_34
sort(birds.begin(), birds.end());
_34
_34
if (n == 0) {
_34
cout << (l - 2 * offset) / d + 1 << '\n';
_34
return;
_34
}
_34
_34
int totalBirds = 0;
_34
for (int i = 0; i <= n; i++) {
_34
ll start = i == 0 ? offset : birds[i - 1] + d;
_34
ll end = i == n ? l - offset : birds[i] - d;
_34
if (start <= end) {
_34
totalBirds += (end - start) / d + 1;
_34
}
_34
}
_34
cout << totalBirds << '\n';
_34
return 0;
_34
}

If you found this solution helpful, consider leaving a star!