import scala.collection.mutable.* import scala.io.StdIn.* import scala.util.chaining.* import scala.math.* import scala.reflect.ClassTag import scala.util.* import scala.annotation.tailrec import scala.collection.mutable @main def main = val n = readLine.toInt val edges = Array.fill(n - 1){ val Array(a, b, c) = readLine.split(' ').map(_.toInt) (a - 1, b - 1, c) } val graph = Array.fill(n){ArrayBuffer[(Int, Int)]()} for (a, b, c) <- edges do graph(a).addOne((b, c)) graph(b).addOne((a, c)) val sortedEdge = edges.sortBy(-_._3) val root = sortedEdge.head._1 val depth = Array.fill(n){-1}.tap(_(root) = 0) val parent = Array.fill(n){-1} val cost = Array.fill(n){-1} val stack = mutable.Stack[Int](root) while stack.nonEmpty do val top = stack.pop() for (next, c) <- graph(top) do if depth(next) == -1 then depth(next) = depth(top) + 1 parent(next) = top cost(next) = c stack.push(next) val degree = Array.fill(n){0} var canReduceAll = true var currentMin = Int.MaxValue val onPath = Array.fill(n){false}.tap(_(root) = true) var result = sortedEdge(0)._3 for i <- sortedEdge.indices do if canReduceAll then val (a, b, _) = sortedEdge(i) val nextCost = if sortedEdge.indices.contains(i + 1) then sortedEdge(i + 1)._3 else 0 val start = if depth(a) < depth(b) then b else a if !onPath(start) then var current = start while !onPath(current) do currentMin = min(currentMin, cost(current)) onPath(current) = true current = parent(current) degree(current) += 1 if (current != root && degree(current) > 1) || (current == root && degree(current) > 2) then canReduceAll = false else result = min(result, max(nextCost, sortedEdge.head._3 - currentMin)) else result = min(result, max(nextCost, sortedEdge.head._3 - currentMin)) println(result)