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

Tree Diameter

A tree is a connected undirected graph with no cycles.

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

  • หาโหนดที่ไกลที่สุดด้วยการท่องกราฟ
  • ใช้ BFS สองครั้งเพื่อหาเส้นผ่านศูนย์กลาง
  • แทนต้นไม้ด้วยรายการประชิด

โจทย์

A tree is a connected undirected graph with no cycles. Its diameter is the largest number of edges on a path between any two vertices. Return that length; you do not need to return the path. No root is specified.

Implement tree_diameter(vertices, edges).

Input

vertices: The number of vertices.

edges: Undirected connections [u, v].

Output

Return the diameter measured in edges, not vertices.

เงื่อนไข

1 ≤ vertices ≤ 200,000. Exactly vertices − 1 edges, with distinct endpoints in 1…vertices. Inputs always form a tree. A one-vertex tree has diameter 0.

ตัวอย่าง

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

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

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

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

คำอธิบาย

The path 5–2–3–4 contains three edges. No path in this tree is longer.

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

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

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

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

คำอธิบาย

A single vertex has no edges, so the longest path length is 0.

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

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

คำใบ้ 1

ใน tree หาเส้นทางที่ยาวที่สุดได้ด้วยการค้นหา graph สองครั้ง แทนที่จะเช็กทุกคู่จุดยอด

คำใบ้ 2

เริ่มจากจุดใดก็ได้ หา vertex ที่ไกลที่สุด แล้วค้นหาอีกครั้งจากจุดนั้นเพื่อวัดระยะทางยาวสุด

คำใบ้ 3

นับเป็นจำนวน edge ไม่ใช่จำนวน vertex และ tree ที่มีจุดเดียวมี diameter เป็นศูนย์

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

เวลา O(vertices), หน่วยความจำเพิ่ม O(vertices)

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

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

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

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

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