2025-09-26 23:47:52 +09:00

54 lines
1.6 KiB
Swift

func findNode(from start: Int, of graph: [[(node: Int, weight: Int)]]) -> (node: Int, length: Int) {
var result = (node: start, length: 0)
var visited = Array(repeating: false, count: graph.count)
var stack = [(node: Int, length: Int)]()
stack.append(result)
visited[start] = true
while !stack.isEmpty {
if let (now, cur_len) = stack.popLast()
{
if cur_len > result.length {
result = (node: now, length: cur_len)
}
for next in graph[now] {
if !visited[next.node] {
visited[next.node] = true
stack.append((node: next.node, length: cur_len + next.weight))
}
}
}
}
return result
}
if let N = Int(readLine() ?? "0")
{
if N == 1 {
print(0)
}
else {
var graph = Array(repeating: [(node: Int, weight: Int)](), count: N+1)
for _ in 0..<N-1 {
if let line = readLine(),
let data = line.split(separator: " ").compactMap({Int($0)}) as? [Int],
data.count == 3
{
let parent = data[0]
let child = data[1]
let weight = data[2]
graph[parent].append((node: child, weight: weight))
graph[child].append((node: parent, weight: weight))
}
}
let startNode: Int = findNode(from: 1, of: graph).node
print(findNode(from: startNode, of: graph).length)
}
}