- Separate each data about work into two events: "start of work" and "end of work".
- Add each events to a vector and sort by time.
- Track the change in number of people at work.
- Obtain the maximum number.
#include <iostream>
#include <vector>
#include <algorithm>
struct worker_data {
int first_day;
int end_day;
int something;
};
struct event_data {
int time;
int delta;
bool operator<(const event_data& e) const {
if (time != e.time) return time < e.time; // earlier event comes first
return delta < 0 && e.delta > 0; // if events occur at the same day, end event comes first
}
};
int main(void) {
std::vector<worker_data> workers = {
{1, 5, 1000},
{2, 4, 500},
{3, 6, 100},
{10, 12, 100},
{14, 15, 100}
};
std::vector<event_data> events;
for (const auto& w : workers) {
events.push_back({w.first_day, 1}); // add "start of work" event
events.push_back({w.end_day + 1, -1}); // add "end of work" event
}
std::sort(events.begin(), events.end());
int max = 0, current = 0;
for (const auto& e : events) {
current += e.delta;
if (current > max) max = current;
}
std::cout << max << std::endl;
return 0;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…