b_lc_单线程 CPU(堆)

有n个任务,且tasks[i] = [enqueueTimei, processingTimei] 意味着第 i​​​​​​​​​​ 项任务将会于 enqueueTimei 时进入任务队列,需要 processingTimei 的时长完成执行。现有一个单线程 CPU ,同一时间只能执行 最多一项 任务,该 CPU 将会按照下述方式运行:

  • 如果 CPU 空闲,且任务队列中没有需要执行的任务,则 CPU 保持空闲状态。
  • 如果 CPU 空闲,但任务队列中有需要执行的任务,则 CPU 将会选择 执行时间最短 的任务开始执行。如果多个任务具有同样的最短执行时间,则选择下标最小的任务开始执行。
  • 一旦某项任务开始执行,CPU 在 执行完整个任务 前都不会停止。
  • CPU 可以在完成一项任务后,立即开始执行一项新任务。

返回 CPU 处理任务的顺序。

const int N=1e5+5;
struct node{
    int id, inqTime, time;
}A[N];
struct cmp{
    bool operator()(node& a, node& b){
        if (a.time != b.time)
            return a.time > b.time;
        return a.id > b.id;
    }
};
bool cmp1(const node &a, const node &b){
    return a.inqTime < b.inqTime;
}
class Solution {
public:
    vector<int> getOrder(vector<vector<int>>& ts) {
        int n = ts.size();
        vector<int> ans(n);

        for (int i=0; i<n; i++) A[i] = {i, ts[i][0], ts[i][1]};
        sort(A, A+n, cmp1);
        priority_queue<node, vector<node>, cmp> q;
        
        long long j = 0, cur = 0;
        for (int i = 0; i < n || !q.empty(); ) {
            if (q.empty()) {
                cur = max(cur, (long long) A[i].inqTime);
            }
            while (i < n && A[i].inqTime <= cur) q.push(A[i++]); //只要当期任务的入队时机在我的执行时间cur前面,就需要入队等待
            ans[j++] = q.top().id; //所有任务都入队完毕,选一个执行时间最少的执行
            cur += q.top().time;
            q.pop();
        }
        return ans;
    }
};
posted @ 2021-04-18 12:27  童年の波鞋  阅读(46)  评论(0编辑  收藏  举报