struct Queue<T> {
var input: [T] = []
var output: [T] = []
var isEmpty: Bool {
return input.isEmpty && output.isEmpty
}
var count: Int {
return input.count + output.count
}
mutating func enqueue(_ element: T) {
input.append(element)
}
mutating func delete() -> T {
if output.isEmpty {
output = input.reversed()
input.removeAll()
}
return output.removeLast()
}
}
struct Edge {
var node: Int
var value: Int
}
let V = Int(readLine()!)!
var tree: [[Edge]] = Array(repeating: [], count: V+1)
var visited = Array(repeating: false, count: V+1)
var distance = Array(repeating: 0, count: V+1)
var queue = Queue<Int>()
for _ in 0..<V {
let input = readLine()!.split(separator: " ").map{ Int(String($0))! }
let v1 = input[0]
var index = 1
while input[index] != -1 {
let (v2, distance) = (input[index], input[index+1])
tree[v1].append(Edge(node: v2, value: distance))
tree[v2].append(Edge(node: v1, value: distance))
index += 2
}
}
bfs(1)
let max = findMaxIndex()
visited = Array(repeating: false, count: V+1)
distance = Array(repeating: 0, count: V+1)
bfs(max)
print(distance[findMaxIndex()])
func bfs(_ v: Int) {
visited[v] = true
queue.enqueue(v)
while !queue.isEmpty {
let now = queue.delete()
for edge in tree[now] {
if !visited[edge.node] {
visited[edge.node] = true
distance[edge.node] = distance[now] + edge.value
queue.enqueue(edge.node)
}
}
}
}
func findMaxIndex() -> Int {
guard let max = distance.max() else { return 0 }
for (index, value) in distance.enumerated() {
if value == max {
return index
}
}
return 0
}