中級 1件解決済み 正答率100.0%

Tree Diameter

A tree is a connected undirected graph with no cycles.

このチャレンジで学べること

  • Find the farthest node with a traversal
  • Use two BFS passes to get the diameter
  • Represent a tree with adjacency lists

問題

翻訳を表示

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
入力:
vertices = 5
edges = [
    [1, 2],
    [2, 3],
    [3, 4],
    [2, 5]
]

期待される出力:
expected = 3
入力:
long long vertices = 5;
std::vector<std::vector<long long>> edges = {
    {1, 2},
    {2, 3},
    {3, 4},
    {2, 5}
};

期待される出力:
long long expected = 3;
入力:
long vertices = 5;
long[][] edges = new long[][] {
    new long[] {1, 2},
    new long[] {2, 3},
    new long[] {3, 4},
    new long[] {2, 5}
};

期待される出力:
long expected = 3;

解説

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

例 2
入力:
vertices = 1
edges = []

期待される出力:
expected = 0
入力:
long long vertices = 1;
std::vector<std::vector<long long>> edges = {};

期待される出力:
long long expected = 0;
入力:
long vertices = 1;
long[][] edges = new long[][] {};

期待される出力:
long expected = 0;

解説

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

解き方のヒント

まずは自分で考えてから、ヒントを1つずつ開いてみましょう。

ヒント 1

In a tree, the longest path can be found by two graph searches instead of checking every pair of vertices.

ヒント 2

Start from any vertex, find the farthest vertex, then search again from there to measure the longest distance.

ヒント 3

Count edges, not vertices, and remember a single-vertex tree has diameter zero.

目安の計算量

O(vertices) time, O(vertices) extra space

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

# コーダー 言語 時間 メモリ AI 評価 解答
1 Н"Никита "Programmer" Python 825 ms - 5/5 コードを見る

他の人の解答から学ぶ

コミュニティの解答

ネタバレ注意: この下に解答が1件あります まずは自分で挑戦してみましょう。他の開発者のコードやAIレビューも見ることができます。 サインインして課題を解くと議論に参加できます。