fn dfs(cur: usize, prev: usize, paths: &Vec>, children: &mut Vec) -> usize { let mut ret = 1usize; for &(v, qidx) in paths[cur].iter() { if v == prev { continue; } let val = dfs(v, cur, paths, children); children[qidx] = val; ret += val; } ret } fn main() { let mut n = String::new(); std::io::stdin().read_line(&mut n).ok(); let n: usize = n.trim().parse().unwrap(); let mut paths = vec![vec![]; n]; let mut weights = vec![0usize; n-1]; for i in 0..n-1 { let mut temp = String::new(); std::io::stdin().read_line(&mut temp).ok(); let temp: Vec = temp.trim().split_whitespace().map(|s| s.parse().unwrap()).collect(); let u = temp[0]-1; let v = temp[1]-1; let w = temp[2]; paths[u].push((v, i)); paths[v].push((u, i)); weights[i] = w; } let mut children = vec![0usize; n-1]; dfs(0, 0, &paths, &mut children); let mut result = 0usize; for i in 0..n-1 { result += children[i] * (n - children[i]) * weights[i]; } println!("{}", result * 2); }