1
+ #include < vector>
2
+ #include < queue>
3
+ #include < algorithm>
4
+ #include < iostream>
5
+ using namespace std ;
6
+
7
+ typedef long long LL;
8
+ typedef pair<LL, LL> PLL; // pair: 处理时间 -> index
9
+ class Solution {
10
+ public:
11
+ vector<int > getOrder (vector<vector<int >>& tasks) {
12
+ // 加入index, 题目要求在任务池中选任务时需要按下标排序, 下标小的排前面
13
+ for (int i = 0 ; i < tasks.size (); i++)
14
+ tasks[i].push_back (i);
15
+ sort (tasks.begin (), tasks.end ()); // 根据先来先服务的规则, 按每个任务的开始时刻排序
16
+ priority_queue<PLL, vector<PLL>, greater<>> pq;
17
+
18
+ LL cur = 0 ; // 记录当前时间点
19
+ vector<int > res;
20
+ for (int i = 0 ; i < tasks.size (); i++)
21
+ {
22
+ while (cur < tasks[i][0 ] && !pq.empty ()) /* 先去任务池捞一下, 看有没有可以执行的任务, 如果有逐个执行 */
23
+ {
24
+ res.push_back (pq.top ().second );
25
+ cur += pq.top ().first ;
26
+ pq.pop ();
27
+ }
28
+ if (cur < tasks[i][0 ]) cur = (LL)tasks[i][0 ]; /* 如果循环结束时, 时间片还没到达, 那就可以将时间直接跳到最近的下一个任务开始的时刻, 反正也是空等 */
29
+ pq.push ({tasks[i][1 ], tasks[i][2 ]});
30
+ }
31
+ while (!pq.empty ()) /* 再去任务池捞一下, 看有没有可以执行的任务, 如果有逐个执行 */
32
+ {
33
+ res.push_back (pq.top ().second );
34
+ cur += pq.top ().first ;
35
+ pq.pop ();
36
+ }
37
+ return res;
38
+ }
39
+ };
40
+
41
+ // Test
42
+ int main ()
43
+ {
44
+ Solution sol;
45
+ vector<vector<int >> tasks = {{1 ,2 },{2 ,4 },{3 ,2 },{4 ,1 }};
46
+ auto res = sol.getOrder (tasks);
47
+ for (auto & num : res)
48
+ cout << num << " " ;
49
+
50
+ return 0 ;
51
+ }
0 commit comments