思路:
维护两个堆分别存储空闲的服务器和正在使用的服务器,遍历任务分别进行处理。均摊时间复杂度n*log(m)(n是任务数量,m是服务器数量)。
实现:
1 class Solution 2 { 3 public: 4 vector<int> assignTasks(vector<int>& servers, vector<int>& tasks) 5 { 6 int n = servers.size(), m = tasks.size(); 7 using pii = pair<int, int>; 8 using tup = tuple<int, int, int>; 9 priority_queue<tup, vector<tup>, greater<tup>> t; 10 priority_queue<pii, vector<pii>, greater<pii>> q; 11 for (int i = 0; i < n; i++) 12 { 13 t.push({0, servers[i], i}); 14 } 15 vector<int> res; 16 for (int i = 0; i < m; i++) 17 { 18 while (!t.empty()) 19 { 20 auto tmp = t.top(); 21 int time = get<0>(tmp), weight = get<1>(tmp), server_id = get<2>(tmp); 22 if (time > i) break; 23 t.pop(); 24 q.push({weight, server_id}); 25 } 26 if (q.empty()) 27 { 28 auto tmp = t.top(); t.pop(); 29 int time = get<0>(tmp), weight = get<1>(tmp), server_id = get<2>(tmp); 30 res.push_back(server_id); 31 t.push({time + tasks[i], weight, server_id}); 32 } 33 else 34 { 35 auto tmp = q.top(); q.pop(); 36 int server_id = tmp.second; 37 res.push_back(server_id); 38 t.push({i + tasks[i], servers[server_id], server_id}); 39 } 40 } 41 return res; 42 } 43 };