#define _USE_MATH_DEFINES #include using namespace std; #define FOR(i,m,n) for(int i=(m);i<(n);++i) #define REP(i,n) FOR(i,0,n) #define ALL(v) (v).begin(),(v).end() using ll = long long; constexpr int INF = 0x3f3f3f3f; constexpr long long LINF = 0x3f3f3f3f3f3f3f3fLL; constexpr double EPS = 1e-8; constexpr int MOD = 1000000007; // constexpr int MOD = 998244353; constexpr int DY[]{1, 0, -1, 0}, DX[]{0, -1, 0, 1}; constexpr int DY8[]{1, 1, 0, -1, -1, -1, 0, 1}, DX8[]{0, -1, -1, -1, 0, 1, 1, 1}; template inline bool chmax(T& a, U b) { return a < b ? (a = b, true) : false; } template inline bool chmin(T& a, U b) { return a > b ? (a = b, true) : false; } struct IOSetup { IOSetup() { std::cin.tie(nullptr); std::ios_base::sync_with_stdio(false); std::cout << fixed << setprecision(20); } } iosetup; template struct Edge { int src, dst; CostType cost; Edge(int src, int dst, CostType cost = 0) : src(src), dst(dst), cost(cost) {} inline bool operator<(const Edge &x) const { return cost != x.cost ? cost < x.cost : dst != x.dst ? dst < x.dst : src < x.src; } inline bool operator<=(const Edge &x) const { return !(x < *this); } inline bool operator>(const Edge &x) const { return x < *this; } inline bool operator>=(const Edge &x) const { return !(*this < x); } }; int main() { int n; cin >> n; vector> edges; vector>> graph(n); REP(i, n - 1) { int a, b, c; cin >> a >> b >> c; --a; --b; edges.emplace_back(a, b, c); graph[a].emplace_back(a, b, i); graph[b].emplace_back(b, a, i); } vector ord(n - 1); iota(ALL(ord), 0); sort(ALL(ord), [&](int a, int b) -> bool { return edges[a].cost > edges[b].cost; }); int s = edges[ord.front()].src, t = edges[ord.front()].dst, s_par = t, t_par = s; set s_side, t_side, ng; const auto f = [&](auto&& f, int par, int ver, set& side) -> void { for (const Edge& e : graph[ver]) { if (e.dst == par) continue; side.emplace(e.cost); f(f, ver, e.dst, side); } }; f(f, s_par, s, s_side); f(f, t_par, t, t_side); int ans = (n - 1 == 1 ? 0 : edges[ord[1]].cost), m = edges[ord.front()].cost; FOR(i, 1, n - 1) { if (ng.count(ord[i])) break; const auto g = [&](auto&& g, int par, int ver, set& side) -> int { if (ver == edges[ord[i]].src || ver == edges[ord[i]].dst) return ver; int ans = -1; for (const Edge& e : graph[ver]) { if (e.dst == par) continue; side.erase(e.cost); if (const int tmp = g(g, ver, e.dst, side); tmp != -1) { chmin(m, edges[e.cost].cost); ans = tmp; } else { ng.emplace(e.cost); } } return ans; }; if (s_side.count(ord[i])) { s_side.erase(ord[i]); s_par = g(g, s_par, s, s_side); assert(s_par != -1); s = (s_par == edges[ord[i]].src ? edges[ord[i]].dst : edges[ord[i]].src); } else if (t_side.count(ord[i])) { t_side.erase(ord[i]); t_par = g(g, t_par, t, t_side); assert(t_par != -1); t = (t_par == edges[ord[i]].src ? edges[ord[i]].dst : edges[ord[i]].src); } chmin(m, edges[ord[i]].cost); chmin(ans, max(edges[ord.front()].cost - m, i + 1 == n - 1 ? 0 : edges[ord[i + 1]].cost)); } cout << ans << '\n'; return 0; }