func findMaxLenNode(start n: Int, of graph: [[(node: Int, dist: Int)]]) -> (node: Int, dist: Int) { var result = (node: n, dist: 0) var visited = Array(repeating: false, count: graph.count+1) var stack: [(node: Int, dist: Int)] = [] stack.append(result) visited[n] = true while !stack.isEmpty { if let (cur_node, cur_dist) = stack.popLast(){ if cur_dist > result.dist { result = (node: cur_node, dist: cur_dist) } for next in graph[cur_node] { if !visited[next.node] { stack.append((node: next.node, dist: cur_dist + next.dist)) visited[next.node] = true } } } } return result } if let V = Int(readLine() ?? "") { var tree: [[(node: Int, dist: Int)]] = Array(repeating: [], count: V+1) for _ in 1...V { if let line = readLine(), let info = line.split(separator: " ").compactMap({Int($0)}) as? [Int] { let u = info[0] var i = 1 while info[i] != -1 { tree[u].append((node: info[i], dist: info[i+1])) i += 2 } } } let start = findMaxLenNode(start: 1, of: tree).node print(findMaxLenNode(start: start, of: tree).dist) }