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

Strongly Connected Components

Count groups of nodes that can all reach each other.

In a directed graph with nodes 0..n−1, a strongly connected component is a maximal group of nodes where every node can reach every other. Count the components (Kosaraju's or Tarjan's algorithm).

Implement count_scc(n, edges).

Input

n: The number of nodes. edges: Directed edges as [from, to].

Output

Return the number of components.

เงื่อนไข

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

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
n = 5
edges = [
    [0, 1],
    [1, 2],
    [2, 0],
    [3, 4]
]

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

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

ผลลัพธ์ที่คาดหวัง:
long expected = 3;

คำอธิบาย

0, 1, 2 form a cycle (one component); 3 and 4 can't reach each other, so they are separate: 3.

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

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

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

ผลลัพธ์ที่คาดหวัง:
long expected = 1;

คำอธิบาย

All three nodes reach each other: 1.

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

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

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

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

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