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

Tree Diameter

A tree is a connected undirected graph with no cycles.

โจทย์

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.

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

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

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

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

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