力扣1882.使用服务器处理任务
-
两个优先队列
- 一个放未使用的服务器
- 一个放已使用的服务器
-
class Solution { using PLI = pair<long long, int>; using PII = pair<int, int>; public: vector<int> assignTasks(vector<int>& servers, vector<int>& tasks) { int m = servers.size(),n = tasks.size(); priority_queue<PLI, vector<PLI>, greater<PLI>> busy; priority_queue<PII, vector<PII>, greater<PII>> idle; for(int i=0;i<m;i++) idle.emplace(servers[i],i); long long ts = 0; //把占用结束的服务器弹出 auto release = [&]() { while(!busy.empty() && busy.top().first <= ts) { auto &&[_,idx] = busy.top(); idle.emplace(servers[idx],idx); busy.pop(); } }; vector<int> res; for(int i=0;i<n;i++) { ts = max(ts, (long long)i); //把占用结束的弹出 release(); if(idle.empty()) { ts = busy.top().first; release(); } //取未占用的服务器 auto&& [_,idx] = idle.top(); res.push_back(idx); busy.emplace(ts+tasks[i] , idx); idle.pop(); } return res; } };