Khó 1 người đã giải Tỷ lệ chấp nhận 100.0%

Course Schedule Order

Order courses so every prerequisite comes first.

Bạn sẽ học được gì

  • Order tasks by prerequisites with Kahn's algorithm
  • Track in-degrees with a queue
  • Detect impossible schedules

Đề bài

Xem bản dịch

Courses are numbered 0..n−1. Each pair [course, prerequisite] means the prerequisite must be taken before the course. Return an order to take all courses; when several courses are available, take the lowest-numbered one first so the answer is unique.

Implement course_order(n, prerequisites).

Input

n: The number of courses. prerequisites: Pairs [course, prerequisite].

Output

Return the course order, or an empty list if a cycle makes it impossible.

Ràng buộc

1 ≤ n ≤ 100,000; 0 ≤ pairs ≤ 200,000

Ví dụ

Ví dụ 1
Đầu vào:
n = 4
prerequisites = [
    [1, 0],
    [2, 0],
    [3, 1],
    [3, 2]
]

Kết quả mong đợi:
expected = [0, 1, 2, 3]
Đầu vào:
long long n = 4;
std::vector<std::vector<long long>> prerequisites = {
    {1, 0},
    {2, 0},
    {3, 1},
    {3, 2}
};

Kết quả mong đợi:
std::vector<long long> expected = {0, 1, 2, 3};
Đầu vào:
long n = 4;
long[][] prerequisites = new long[][] {
    new long[] {1, 0},
    new long[] {2, 0},
    new long[] {3, 1},
    new long[] {3, 2}
};

Kết quả mong đợi:
long[] expected = new long[] {0, 1, 2, 3};

Giải thích

0 first, then 1 and 2 (lowest first), then 3: [0, 1, 2, 3].

Ví dụ 2
Đầu vào:
n = 2
prerequisites = [
    [0, 1],
    [1, 0]
]

Kết quả mong đợi:
expected = []
Đầu vào:
long long n = 2;
std::vector<std::vector<long long>> prerequisites = {
    {0, 1},
    {1, 0}
};

Kết quả mong đợi:
std::vector<long long> expected = {};
Đầu vào:
long n = 2;
long[][] prerequisites = new long[][] {
    new long[] {0, 1},
    new long[] {1, 0}
};

Kết quả mong đợi:
long[] expected = new long[] {};

Giải thích

Each course requires the other, so no order exists: [].

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

This is a dependency ordering problem: courses with no unmet prerequisites must be taken first.

Gợi ý 2

Use topological sorting, and when multiple courses are ready, always choose the smallest-numbered one to make the order deterministic.

Gợi ý 3

If you cannot process all courses, a cycle exists; also, duplicate prerequisite pairs should not break the result.

Độ phức tạp mong đợi

O(n + p log n) time, O(n + p) extra space

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Lời giải đạt tốt nhất của mỗi người. Lời giải nhanh hơn, tốn ít bộ nhớ hơn và được đánh giá cao hơn sẽ đứng trên.

# Người giải Ngôn ngữ Thời gian Bộ nhớ AI đánh giá Lời giải
1 Н"Никита "Programmer" Python 795 ms - 5/5 Xem code

Học hỏi từ người khác

Lời giải cộng đồng

Cảnh báo: Có 1 lời giải đầy đủ bên dưới Hãy thử tự giải trước. Bạn vẫn có thể xem code của người khác và nhận xét của AI. Đăng nhập và giải thử thách để tham gia thảo luận.