- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 55 lines of C++ from the credited upstream file 1882.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 3 loop blocks detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1struct T {2 int weight;3 int index;4 int freeTime;5};6 7class Solution {8 public:9 vector<int> assignTasks(vector<int>& servers, vector<int>& tasks) {10 const int n = servers.size();11 const int m = tasks.size();12 vector<int> ans(m);13 auto compareFree = [](const T& a, const T& b) {14 return a.weight == b.weight ? a.index > b.index : a.weight > b.weight;15 };16 auto compareUsed = [](const T& a, const T& b) {17 if (a.freeTime != b.freeTime)18 return a.freeTime > b.freeTime;19 if (a.weight != b.weight)20 return a.weight > b.weight;21 return a.index > b.index;22 };23 priority_queue<T, vector<T>, decltype(compareFree)> free(compareFree);24 priority_queue<T, vector<T>, decltype(compareUsed)> used(compareUsed);25 26 for (int i = 0; i < n; ++i)27 free.emplace(servers[i], i, 0);28 29 for (int i = 0; i < m; ++i) { 30 const int executionTime = tasks[i];31 32 while (!used.empty() && used.top().freeTime <= i) {33 const T curr = used.top();34 used.pop();35 free.push(curr);36 }37 if (free.empty()) {38 T server = used.top();39 used.pop();40 ans[i] = server.index;41 server.freeTime += executionTime;42 used.push(server);43 } else {44 T server = free.top();45 free.pop();46 ans[i] = server.index;47 server.freeTime = i + executionTime;48 used.push(server);49 }50 }51 52 return ans;53 }54};55