use std::io::*; fn dfs(v: usize, p: usize, graph: &Vec>, size: &mut Vec) -> usize { let mut res = 1; for &nv in graph[v].iter() { if nv != p { res += dfs(nv, v, &graph, size); } } size[v] = res; res } fn main() { let mut s: String = String::new(); std::io::stdin().read_to_string(&mut s).ok(); let mut itr = s.trim().split_whitespace(); let n: usize = itr.next().unwrap().parse().unwrap(); let mut graph: Vec> = vec![Vec::new(); n]; let mut edges: Vec<(usize, usize, usize)> = Vec::new(); for _ in 0..n - 1 { let u: usize = itr.next().unwrap().parse::().unwrap() - 1; let v: usize = itr.next().unwrap().parse::().unwrap() - 1; let w: usize = itr.next().unwrap().parse().unwrap(); graph[u].push(v); graph[v].push(u); edges.push((u, v, w)); } let mut size: Vec = vec![0; n]; dfs(0, 0, &graph, &mut size); let mut ans = 0; for &(u, v, w) in edges.iter() { let small = std::cmp::min(size[u], size[v]); ans += (n - small) * small * w * 2; } println!("{}", ans); }