A day at the beach. A group of n people are lying on the beach. The beach is represented by the real line R and the location of the i-th person is some integer xi ∈ Z. Your task is to prevent people from getting sunburned by covering them with umbrellas. Each umbrella corresponds to a closed interval I = [a, a + L] of length L ∈ N, and the i-th person is covered by that umbrella if xi ∈ I. Design a greedy algorithm for covering all people with the minimum number of umbrellas. The input consists of the integers x1,...,xn, and L. The output of your algorithm should be the positions of umbrellas. Forexample,iftheinputisx1 =1,x2 =3,x3 =5,andL=2,thenanoptimumsolutionisthe set of two umbrellas placed at positions 2 and 5, covering intervals [1, 3] and [4, 6]. The running time should be polynomial in n
Asked
Active
Viewed 1,218 times
1 Answers
0
The main idea is that when we see someone that is not covered yet, we will place the umbrella at position ( uncoveredPersonPosition + L/2 ), and the umbrella reach will be covering the range (uncoveredPersonPosition, uncoveredPersonPosition + L) .
Here is the code for this idea.
#include <vector>
#include <iostream>
#include <algorithm>
int solve(std::vector<double>& people, int umbrellaCoverage) {
std::sort(people.begin(), people.end() );
int answer = 0;
double umbrellaReach;
for(const auto& p : people) {
if(answer == 0) {
answer += 1;
umbrellaReach = p + umbrellaCoverage;
}
else {
if(p < umbrellaReach) continue;
else {
answer++;
umbrellaReach = p + umbrellaCoverage;
}
}
}
return answer;
}
int main() {
std::vector<double> v(10);
for(int i = 0; i < 10; ++i) v[i] = (double) i;
std::cout << solve(v, 3) << std::endl;
return 0;
}

Francisco Geiman
- 390
- 1
- 7