結果
問題 | No.1637 Easy Tree Query |
ユーザー |
|
提出日時 | 2022-07-09 17:00:17 |
言語 | Go (1.23.4) |
結果 |
AC
|
実行時間 | 77 ms / 2,000 ms |
コード長 | 1,283 bytes |
コンパイル時間 | 11,590 ms |
コンパイル使用メモリ | 236,784 KB |
実行使用メモリ | 28,240 KB |
最終ジャッジ日時 | 2024-12-31 04:41:37 |
合計ジャッジ時間 | 17,199 ms |
ジャッジサーバーID (参考情報) |
judge5 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 2 |
other | AC * 33 |
ソースコード
package mainimport ("bufio""fmt""os""strconv")var sc = bufio.NewScanner(os.Stdin)var out = bufio.NewWriter(os.Stdout)func solve(n, q int, a, b, p, x []int) []int {// 0-index化は省略edge := make([][]int, n+1)for i := range a {edge[a[i]] = append(edge[a[i]], b[i])edge[b[i]] = append(edge[b[i]], a[i])}size := make([]int, n+1)var dfs func(cur, par int) intdfs = func(cur, par int) int {for _, next := range edge[cur] {if next == par {continue}size[cur] += dfs(next, cur)}size[cur]++return size[cur]}dfs(1, 0)sum := 0var ans []intfor i := 0; i < q; i++ {sum += size[p[i]] * x[i]ans = append(ans, sum)}return ans}func main() {buf := make([]byte, 1024*1024)sc.Buffer(buf, bufio.MaxScanTokenSize)sc.Split(bufio.ScanWords)n, q := nextInt(), nextInt()var a, b []intfor i := 0; i < n-1; i++ {a = append(a, nextInt())b = append(b, nextInt())}var p, x []intfor i := 0; i < q; i++ {p = append(p, nextInt())x = append(x, nextInt())}ans := solve(n, q, a, b, p, x)PrintVertically(ans)}func nextInt() int {sc.Scan()i, _ := strconv.Atoi(sc.Text())return i}func PrintVertically(x []int) {defer out.Flush()for _, v := range x {fmt.Fprintln(out, v)}}