nikunjsoni

1834

May 28th, 2021
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.10 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     typedef pair<int, int> pii;
  4.     vector<int> getOrder(vector<vector<int>>& tasks) {
  5.         priority_queue<pii, vector<pii>, greater<pii>> pq;
  6.         long int time=0, N=tasks.size();
  7.         vector<int> res;
  8.        
  9.         // Add index to tasks and sort the tasks based on enqueue time.
  10.         for(int i=0; i<N; i++)
  11.             tasks[i].push_back(i);
  12.         sort(tasks.begin(), tasks.end());
  13.        
  14.         int i=0;
  15.         while(!pq.empty() || i<N){
  16.             // If heap is empty and cpu is idle, move time to start of next task.
  17.             if(pq.empty())
  18.                 time = max(time, long(tasks[i][0]));
  19.            
  20.             // Add all tasks whose enqueue time is less than current time.
  21.             while(i<N && tasks[i][0] <= time){
  22.                 pq.push({tasks[i][1], tasks[i][2]});
  23.                 i++;
  24.             }
  25.            
  26.             // Pick up the least processing time task and execute.
  27.             time += pq.top().first;
  28.             res.push_back(pq.top().second);
  29.             pq.pop();
  30.         }
  31.         return res;
  32.     }
  33. };
Advertisement
Add Comment
Please, Sign In to add comment