if !ENV['RUBY_THREAD_VM_STACK_SIZE'] exec({'RUBY_THREAD_VM_STACK_SIZE'=>'10000000'}, '/usr/bin/ruby', $0) else N = gets.to_i E = Array.new(N + 1) { [] } V = Array.new(N + 1) { [] } (N - 1).times do u, v, w = gets.split.map(&:to_i) E[u] << [v, w] E[v] << [u, w] end def dfs1(u, cnt = 0, parent = -1) cnt = 0 E[u].each do |v, w| next if v == parent v_cnt = dfs1(v, cnt, u) cnt += v_cnt V[u] << v_cnt end cnt + 1 end $ans = 0 def dfs2(u, v_cnt = 0, parent = -1) t_cnt = V[u].sum + v_cnt i = 0 E[u].each do |v, w| next if v == parent cnt = V[u][i] $ans += 2 * w * (N - cnt) * cnt dfs2(v, t_cnt - cnt + 1, u) i += 1 end end dfs1(1) dfs2(1) puts $ans end