- pq_ 使用std::map充当优先队列,存储(priority, taskId) -> userId
- m_ 使用std::unordered_map,存储taskId -> pq_的迭代器
所有操作都是O(logn)
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 TaskManager { public: TaskManager(vector<vector<int>>& tasks) { for (const auto& task : tasks) add(task[0], task[1], task[2]); } void add(int userId, int taskId, int priority) { m_[taskId] = pq_.emplace(make_pair(priority, taskId), userId).first; } void edit(int taskId, int newPriority) { const int userId = m_[taskId]->second; rmv(taskId); add(userId, taskId, newPriority); } void rmv(int taskId) { auto it = m_.find(taskId); pq_.erase(it->second); m_.erase(it); } int execTop() { if (pq_.empty()) return -1; auto it = pq_.rbegin(); const int userId = it->second; const int taskId = (it->first.second); rmv(taskId); return userId; } private: map<std::pair<int,int>, int> pq_; // (priority, taskId) -> userId; unordered_map<int, map<std::pair<int,int>, int>::iterator> m_; // taskId -> pq iterator }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment