結果

問題 No.1637 Easy Tree Query
ユーザー HimaHima
提出日時 2022-07-09 17:00:17
言語 Go
(1.22.1)
結果
AC  
実行時間 77 ms / 2,000 ms
コード長 1,283 bytes
コンパイル時間 12,255 ms
コンパイル使用メモリ 203,204 KB
実行使用メモリ 28,672 KB
最終ジャッジ日時 2023-08-30 00:40:32
合計ジャッジ時間 18,916 ms
ジャッジサーバーID
(参考情報)
judge11 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,376 KB
testcase_01 AC 1 ms
4,376 KB
testcase_02 AC 62 ms
18,664 KB
testcase_03 AC 2 ms
4,380 KB
testcase_04 AC 25 ms
9,984 KB
testcase_05 AC 45 ms
10,484 KB
testcase_06 AC 33 ms
10,216 KB
testcase_07 AC 16 ms
7,856 KB
testcase_08 AC 20 ms
7,912 KB
testcase_09 AC 52 ms
12,808 KB
testcase_10 AC 25 ms
10,052 KB
testcase_11 AC 63 ms
16,560 KB
testcase_12 AC 58 ms
14,484 KB
testcase_13 AC 16 ms
7,084 KB
testcase_14 AC 37 ms
12,204 KB
testcase_15 AC 60 ms
14,448 KB
testcase_16 AC 59 ms
14,436 KB
testcase_17 AC 17 ms
8,004 KB
testcase_18 AC 43 ms
12,248 KB
testcase_19 AC 43 ms
10,176 KB
testcase_20 AC 59 ms
16,528 KB
testcase_21 AC 35 ms
10,120 KB
testcase_22 AC 73 ms
16,560 KB
testcase_23 AC 18 ms
7,948 KB
testcase_24 AC 30 ms
10,140 KB
testcase_25 AC 45 ms
12,308 KB
testcase_26 AC 64 ms
16,532 KB
testcase_27 AC 77 ms
18,520 KB
testcase_28 AC 33 ms
10,172 KB
testcase_29 AC 52 ms
14,216 KB
testcase_30 AC 26 ms
8,688 KB
testcase_31 AC 30 ms
10,224 KB
testcase_32 AC 25 ms
8,092 KB
testcase_33 AC 41 ms
10,288 KB
testcase_34 AC 43 ms
28,672 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

package main

import (
	"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) int
	dfs = 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 := 0
	var ans []int
	for 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 []int
	for i := 0; i < n-1; i++ {
		a = append(a, nextInt())
		b = append(b, nextInt())
	}
	var p, x []int
	for 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)
	}
}
0