ปานกลาง 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Parallel Task Completion Order

Run tasks concurrently with at most k at a time and report the order in which they finish.

สิ่งที่คุณจะได้เรียนรู้

  • Run tasks with a limit on parallelism
  • Simulate time with a priority queue
  • Break ties between tasks that finish together

โจทย์

ดูฉบับแปล

With async/await you can start several tasks and let them run at the same time. A SemaphoreSlim often caps how many run at once.

Tasks numbered 0 to n − 1 take durations[i] time units. At time 0 start as many tasks as the limit allows, in index order. Whenever tasks finish, record them (if several finish at the same moment, lower index first) and immediately start the next waiting tasks, in index order, to fill the free slots.

Implement parallel_task_order(durations, limit).

Input

durations: How long each task takes.

limit: The maximum number of tasks running at the same time.

Output

Return the task indices in the order they finish.

เงื่อนไข

1 ≤ n ≤ 100,000

1 ≤ durations[i] ≤ 10^6; 1 ≤ limit ≤ n

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
limit = 2
durations = [4, 2, 3, 1]

ผลลัพธ์ที่คาดหวัง:
expected = [1, 0, 2, 3]
อินพุต:
long long limit = 2;
std::vector<long long> durations = {4, 2, 3, 1};

ผลลัพธ์ที่คาดหวัง:
std::vector<long long> expected = {1, 0, 2, 3};
อินพุต:
long limit = 2;
long[] durations = new long[] {4, 2, 3, 1};

ผลลัพธ์ที่คาดหวัง:
long[] expected = new long[] {1, 0, 2, 3};

คำอธิบาย

Tasks 0 and 1 start. Task 1 ends at 2 and task 2 starts (ends at 5). Task 0 ends at 4 and task 3 starts (ends at 5). Tasks 2 and 3 finish together, lower index first: [1, 0, 2, 3].

ตัวอย่างที่ 2
อินพุต:
limit = 3
durations = [3, 1, 2]

ผลลัพธ์ที่คาดหวัง:
expected = [1, 2, 0]
อินพุต:
long long limit = 3;
std::vector<long long> durations = {3, 1, 2};

ผลลัพธ์ที่คาดหวัง:
std::vector<long long> expected = {1, 2, 0};
อินพุต:
long limit = 3;
long[] durations = new long[] {3, 1, 2};

ผลลัพธ์ที่คาดหวัง:
long[] expected = new long[] {1, 2, 0};

คำอธิบาย

All tasks run at once and finish at 1, 2 and 3: [1, 2, 0].

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

Keep the running tasks ordered by finish time, then by index.

คำใบ้ 2

Each step jumps to the next finish time and collects every task ending then.

คำใบ้ 3

Refill free slots with the next waiting tasks in index order.

ความซับซ้อนที่คาดหวัง

O(n log limit) time, O(limit) extra space

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก