pub mod io { use std::io::{BufRead, ErrorKind}; pub fn scan(r: &mut R) -> Vec { let mut res = Vec::new(); loop { let buf = match r.fill_buf() { Ok(buf) => buf, Err(e) if e.kind() == ErrorKind::Interrupted => continue, Err(e) => panic!(e), }; let (done, used, buf) = { match buf.iter().position(u8::is_ascii_whitespace) { Some(i) => (i > 0 || res.len() > 0, i + 1, &buf[..i]), None => (buf.is_empty(), buf.len(), buf), } }; res.extend_from_slice(buf); r.consume(used); if done { return res; } } } #[macro_export] macro_rules! scan { ($r:expr, [$t:tt; $n:expr]) => { (0..$n).map(|_| scan!($r, $t)).collect::>() }; ($r:expr, [$t:tt]) => { scan!($r, [$t; scan!($r, usize)]) }; ($r:expr, ($($t:tt),*)) => { ($(scan!($r, $t)),*) }; ($r:expr, Usize1) => { scan!($r, usize) - 1 }; ($r:expr, Bytes) => { io::scan($r) }; ($r:expr, String) => { String::from_utf8(scan!($r, Bytes)).unwrap() }; ($r:expr, $t:ty) => { scan!($r, String).parse::<$t>().unwrap() }; } #[macro_export] macro_rules! input { ($($($v:ident)* : $t:tt),* $(,)?) => { let stdin = std::io::stdin(); let ref mut reader = std::io::BufReader::new(stdin.lock()); $(let $($v)* = scan!(reader, $t);)* }; } } struct Dfs { graph: Vec>, count: Vec, } impl Dfs { fn search(&mut self, prev: usize, from: usize) { let mut count = 1; for to in self.graph[from].clone() { if to == prev { continue; } self.search(from, to); count += self.count[to]; } self.count[from] = count; } } use std::io::Write; fn main() { input! { n: usize, q: usize, edges: [(Usize1, Usize1); n - 1], queries: [(Usize1, u64); q], } let mut graph = vec![vec![]; n]; for (a, b) in edges { graph[a].push(b); graph[b].push(a); } let count = vec![0; n]; let mut dfs = Dfs { graph, count }; dfs.search(!0, 0); let stdout = std::io::stdout(); let mut writer = std::io::BufWriter::new(stdout.lock()); let mut ans = 0; for (p, x) in queries { ans += dfs.count[p] * x; writeln!(writer, "{}", ans).ok(); } }