macro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); input_inner!{iter, $($r)*} }; ($($r:tt)*) => { let mut s = { use std::io::Read; let mut s = String::new(); std::io::stdin().read_to_string(&mut s).unwrap(); s }; let mut iter = s.split_whitespace(); input_inner!{iter, $($r)*} }; } macro_rules! input_inner { ($iter:expr) => {}; ($iter:expr, ) => {}; ($iter:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($iter, $t); input_inner!{$iter $($r)*} }; } macro_rules! read_value { ($iter:expr, ( $($t:tt),* )) => { ( $(read_value!($iter, $t)),* ) }; ($iter:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($iter, $t)).collect::>() }; ($iter:expr, chars) => { read_value!($iter, String).chars().collect::>() }; ($iter:expr, usize1) => { read_value!($iter, usize) - 1 }; ($iter:expr, $t:ty) => { $iter.next().unwrap().parse::<$t>().expect("Parse error") }; } struct Tree { g: Vec>, n: usize, } impl Tree { fn new(n: usize, edges: Vec<(usize, usize)>) -> Self { let mut res_edges = vec![Vec::new(); n]; for &(a, b) in edges.iter() { res_edges[a].push(b); } Tree { g: res_edges, n: n } } fn get_subtree_size(&self, root: usize) -> Vec { fn rec(slf: &Tree, sz: &mut Vec, v: usize, par: usize) { sz[v] = 1; for &to in slf.g[v].iter() { if to != par { rec(slf, sz, to, v); sz[v] += sz[to]; } } } let mut res = vec![0usize; self.n]; rec(self, &mut res, 0, self.n); res } } fn main() { input! { n: usize, q: usize, edges: [(usize1, usize1); n-1], queries: [(usize1, usize); q] } let tree = Tree::new(n, edges); let sz = tree.get_subtree_size(0); let mut sum = 0usize; for &(p, x) in queries.iter() { sum += sz[p] * x; println!("{}", sum); } }