[LeetCode] Process Tasks Using Servers

1882. Process Tasks Using Servers

You are given two 0-indexed integer arrays servers and tasks of lengths n​​​​​​ and m​​​​​​ respectively. servers[i] is the weight of the i​​​​​​th​​​​ server, and tasks[j] is the time needed to process the j​​​​​​th​​​​ task in seconds.

You are running a simulation system that will shut down after all tasks are processed. Each server can only process one task at a time. You will be able to process the jth task starting from the jth second beginning with the 0th task at second 0. To process task j, you assign it to the server with the smallest weight that is free, and in case of a tie, choose the server with the smallest index. If a free server gets assigned task j at second t,​​​​​​ it will be free again at the second t + tasks[j].

If there are no free servers, you must wait until one is free and execute the free tasks as soon as possible. If multiple tasks need to be assigned, assign them in order of increasing index.

You may assign multiple tasks at the same second if there are multiple free servers.

Build an array ans​​​​ of length m, where ans[j] is the index of the server the j​​​​​​th task will be assigned to.

Return the array ans​​​​.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public:
vector<int> assignTasks(vector<int>& servers, vector<int>& tasks) {
vector<int> res;
priority_queue<pair<int, int>, vector<pair<int,int>>, greater<pair<int,int>>> s, t, running;
for(int i = 0; i < servers.size(); i++) {
s.push({servers[i], i});
}
for(int i = 0; i < tasks.size(); i++) {
t.push({i, tasks[i]});
while(!running.empty() && running.top().first == i) {
s.push({servers[running.top().second],running.top().second});
running.pop();
}
while(!s.empty() && !t.empty()) {
running.push({i + t.top().second, s.top().second});
res.push_back(s.top().second);
s.pop(); t.pop();
}
}
if(!running.empty())
for(int i = running.top().first; t.size(); i = running.top().first) {
while(!running.empty() && running.top().first == i) {
s.push({servers[running.top().second],running.top().second});
running.pop();
}
while(!s.empty() && !t.empty()) {
running.push({i + t.top().second, s.top().second});
res.push_back(s.top().second);
s.pop(); t.pop();
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/30/PS/LeetCode/process-tasks-using-servers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.