Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Heap & Priority Queue

Single-Threaded CPU

Medium · Heap & Priority Queue · Asked at Google, Amazon, Microsoft

Task i (0-based) becomes available at time e[i] and takes p[i] time units. A single CPU works like this:

Print the order in which the CPU processes the tasks.

Input

First line: n. Next n lines: e[i] p[i].

Output

The task indices in processing order, space-separated.

Constraints

Sort the tasks by availability time. Keep a min-heap of available tasks keyed by (processing time, index). Times can exceed 2^31 — use 64-bit integers.

Example 1

Input

4
1 2
2 4
3 2
4 1

Output

0 2 3 1

Example 2

Input

5
7 10
7 12
7 5
7 4
7 2

Output

4 3 2 0 1

Hints

  1. Simulate time. Sort the tasks by when they become available.
  2. Everything available at the current time goes into a min-heap ordered by (processing time, index).
  3. If the heap is empty, jump the clock forward to the next availability time.

Approach

Keep a pointer into the tasks sorted by availability. Loop until all tasks are done: if the heap is empty and the next task is in the future, move time to its availability. Push every task with e ≤ time. Pop the best task, add its processing time to the clock and record its index. Each task is pushed and popped once. The clock can reach 10^14, so use 64-bit integers.

Complexity: O(n log n) time · O(n) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<array<long long, 3>> t(n); // e, p, index
    for (int i = 0; i < n; i++) {
        cin >> t[i][0] >> t[i][1];
        t[i][2] = i;
    }
    sort(t.begin(), t.end());
    priority_queue<pair<long long, long long>, vector<pair<long long, long long>>, greater<>> pq; // (p, index)
    long long time = 0;
    int i = 0;
    string out;
    for (int done = 0; done < n; done++) {
        if (pq.empty() && time < t[i][0]) time = t[i][0];
        while (i < n && t[i][0] <= time) {
            pq.push({t[i][1], t[i][2]});
            i++;
        }
        auto _b = pq.top();
        auto p = _b.first;
        auto idx = _b.second;
        pq.pop();
        time += p;
        out += to_string(idx);
        out += (done + 1 < n ? ' ' : '\n');
    }
    cout << out;
    return 0;
}

Python solution

import heapq
import sys

data = list(map(int, sys.stdin.read().split()))
n = data[0]
tasks = sorted((data[1 + 2 * i], data[2 + 2 * i], i) for i in range(n))
heap = []
time = i = 0
order = []
while len(order) < n:
    if not heap and time < tasks[i][0]:
        time = tasks[i][0]
    while i < n and tasks[i][0] <= time:
        heapq.heappush(heap, (tasks[i][1], tasks[i][2]))
        i += 1
    p, idx = heapq.heappop(heap)
    time += p
    order.append(idx)
print(*order)

Java solution

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int n = (int) in.nval;
        long[][] t = new long[n][3];
        for (int i = 0; i < n; i++) {
            in.nextToken();
            t[i][0] = (long) in.nval;
            in.nextToken();
            t[i][1] = (long) in.nval;
            t[i][2] = i;
        }
        Arrays.sort(t, (a, b) -> a[0] != b[0] ? Long.compare(a[0], b[0]) : Long.compare(a[2], b[2]));
        PriorityQueue<long[]> pq = new PriorityQueue<>((a, b) -> a[1] != b[1] ? Long.compare(a[1], b[1]) : Long.compare(a[2], b[2]));
        long time = 0;
        int i = 0;
        StringBuilder sb = new StringBuilder();
        for (int done = 0; done < n; done++) {
            if (pq.isEmpty() && time < t[i][0]) time = t[i][0];
            while (i < n && t[i][0] <= time) pq.add(t[i++]);
            long[] cur = pq.poll();
            time += cur[1];
            sb.append(cur[2]).append(done + 1 < n ? " " : "\n");
        }
        System.out.print(sb);
    }
}

Solve Single-Threaded CPU online · All practice problems