2024年12月20日 星期五

血緣關係

 from collections import defaultdict


def find_furthest_distance(n, edges):

    # 建立鄰接表

    graph = defaultdict(list)

    for a, b in edges:

        graph[a].append(b)

        graph[b].append(a)


    # 單次 DFS

    def dfs(node, visited):

        visited.append(node)

        max_distance, furthest_node = 0, node


        for neighbor in graph[node]:

            if neighbor not in visited:

                distance, far_node = dfs(neighbor, visited)

                if distance + 1 > max_distance:

                    max_distance = distance + 1

                    furthest_node = far_node


        return max_distance, furthest_node


    # 第一次 DFS

    visited = []

    _, node_a = dfs(0, visited)


    # 第二次 DFS

    visited = []

    max_distance, _ = dfs(node_a, visited)


    return max_distance


n = int(input())

lines =[] 

for i in range(n-1):

  lines.append(input())


edges = [ map(int,j.split()) for j in lines]

print(find_furthest_distance(n, edges))


# 8

# 0 1

# 0 2

# 0 3

# 7 0

# 1 4

# 1 5

# 3 6


# Output:


# 4

沒有留言:

張貼留言