const MOD: usize = 1e9 as usize + 7; struct UnionFind { n: usize, parents: Vec, } impl UnionFind { fn new(n: usize) -> Self { UnionFind { n: n, parents: (0..n).collect(), } } fn equiv(&mut self, a: usize, b: usize) -> bool { self.find(a) == self.find(b) } fn unite(&mut self, a: usize, b: usize) { if self.equiv(a, b) { return; } let (a, b) = (a.min(b), a.max(b)); let x = self.parents[a]; let y = self.parents[b]; self.parents[y] = self.parents[x]; } fn find(&mut self, a: usize) -> usize { if self.parents[a] == a { return a; } let p = self.find(self.parents[a]); self.parents[a] = p; p } } fn main() { let mut n = String::new(); std::io::stdin().read_line(&mut n).ok(); let n: usize = n.trim().parse().unwrap(); let lines = (0..n-1).map(|_| { 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(); (temp[0]-1, temp[1]-1, temp[2]) }) .collect::>(); let mut result = 0usize; for i in 0..30 { let mut uf = UnionFind::new(n); let mut size = vec![1usize; n]; for &(a, b, c) in lines.iter() { if ((c >> i) & 1) == 1 { let pa = uf.find(a); let pb = uf.find(b); uf.unite(pa, pb); let p = uf.find(pa); if p == pa { size[pa] += size[pb]; size[pb] = 0; } else { size[pb] += size[pa]; size[pa] = 0; } } } for j in 0..n { if size[j] > 0 { result += size[j] * (size[j]-1) / 2 * (1usize << i) % MOD; result %= MOD; } } } println!("{}", result); }