package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var s = bufio.NewScanner(os.Stdin)

func Scan() string {
	s.Scan()
	return s.Text()
}

func main() {
	fmt.Println(p())
}

func ScanInt() int {
	a, err := strconv.Atoi(Scan())
	if err != nil {
		return 0
	}
	return a
}

func test(n int) string {
	for i := 9; i > 1; i-- {
		if n%i == 0 {
			a := n / i
			if a < 10 {
				return "Yes"
			}
			return "No"
		}
	}
	return "No"
}

func p() string {
	a := ScanInt()
	if a == 0 || a > 81 {
		return "No"
	}
	return test(a)
}


package main

import (
	"bufio"
	"os"
	"strconv"
	"strings"
)

var s = bufio.NewScanner(os.Stdin)

func ScanLine() string {
	s.Scan()
	return s.Text()
}

func main() {
	p()
}

func ScanInts() (int, int) {
	str := ScanLine()
	v := strings.Split(str, " ")
	a, _ := strconv.Atoi(v[0])
	b, _ := strconv.Atoi(v[1])
	return a, b
}

func p() int {
	a, b := ScanInts()
	if a > 10 || b > 10 {
		return -1
	}
	return a * b
}

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Score : 100 points

Problem Statement

Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together. He cannot do any other calculation.

Given are two integers A and B.

If Takahashi can calculate A \times B, print the result; if he cannot, print -1 instead.

Constraints

1 \leq A \leq 20

1 \leq B \leq 20

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

If Takahashi can calculate A \times B, print the result; if he cannot, print -1.

Sample Input 1

2 5

Sample Output 1

10

2 \times 5 = 10.

Sample Input 2

5 10

Sample Output 2

-1

5\times 10 = 50, but Takahashi cannot do this calculation, so print -1 instead.

Sample Input 3

9 9

Sample Output 3

81

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"sort"
	"strconv"
	"strings"
)

func main() {
	A := oneInt()
	B := oneInt()
	ans := A * B
	if 0 < A && A < 10 {

	} else {
		fmt.Print(-1)
		return
	}

	if 0 < B && B < 10 {

	} else {
		fmt.Print(-1)
	}

	if 0 < ans && ans < 82 {
		fmt.Print(ans)
	} else {
		fmt.Print(-1)
	}

}

var sc = bufio.NewScanner(os.Stdin)

func oneInt() int {
	var a int
	fmt.Scan(&a)
	return a
}
func oneStr() string {
	var a string
	fmt.Scan(&a)
	return a
}

func nextLine() string {
	sc.Scan()
	return sc.Text()
}

func scanNums() (nums []int) {
	s := nextLine()
	numStr := strings.Split(s, " ")

	for _, n := range numStr {
		i, _ := strconv.Atoi(n)
		nums = append(nums, i)
	}
	return nums
}

func scanStrings() (strs []string) {
	s := nextLine()
	list := strings.Split(s, " ")
	strs = append(strs, list...)
	return strs
}

func abs(a int) int {
	return int(math.Abs(float64(a)))
}

func pow(p, q int) int {
	return int(math.Pow(float64(p), float64(q)))
}

func min(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton min() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Min(float64(res), float64(nums[i])))
	}
	return res
}

func max(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton max() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Max(float64(res), float64(nums[i])))
	}
	return res
}

func strSearch(a []string, b string) bool {
	for i := 0; i < len(a); i++ {
		if a[i] == b {
			return true
		}
	}
	return false
}

func sortAsc(a []int) []int {
	sort.Ints(a)
	return a
}

func sortDesc(a []int) []int {
	sort.Sort(sort.Reverse(sort.IntSlice(a)))
	return a
}

func gcd(a, b int) int {
	if b == 0 {
		return a
	}
	return gcd(b, a%b)
}

func lcm(a, b int) int {
	if a == 0 && b == 0 {
		return 0
	}
	return a * b / gcd(a, b)
}


package main

import(
    "fmt"
)

func main() {
    var a, b int
    fmt.Scan(&a, &b)
    if a > 9 || b > 9 {
        fmt.Println(-1)
    }else {
        fmt.Println(a*b)
    }
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func main() {
	sc.Split(bufio.ScanWords)
	a := nextInt()
	b := nextInt()

	if 1 <= a && a <= 9 && 1 <= b && b <= 9 {
		fmt.Println(a * b)
	} else {
		fmt.Println(-1)
	}
}


package main

import (
        "fmt"
)

func main() {
        var a, b int
        fmt.Scanf("%d %d", &a, &b)

        if a >= 1 && a <= 9 && b >= 1 && b <= 9 {
                fmt.Println(a * b)
        } else {
                fmt.Println(-1)
        }
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func init() {
	sc.Split(bufio.ScanWords)
}

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func main() {
	a:=nextInt()
	b:=nextInt()

	if a < 1 || a > 9 {
		fmt.Printf("-1")
		return
	}
	if b < 1 || b > 9 {
		fmt.Printf("-1")
		return
	}

	fmt.Printf("%d", a * b)
}


package main

import "fmt"

func main() {
	var a, b int
	fmt.Scan(&a, &b)
	if a < 10 && b < 10 {
		fmt.Println(a * b)
	} else {
		fmt.Println(-1)
	}
}


package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"reflect"
	"sort"
	"strconv"
	"strings"
	// "regexp"
)

/* sort */
type pair struct {
	index  int64
	p1, p2 interface{}
}
type pairs []pair

func (slice pairs) Len() int {
	return len(slice)
}

func (slice pairs) Less(i, j int) bool {
	return slice[i].index < slice[j].index
}

func (slice pairs) Swap(i, j int) {
	slice[i], slice[j] = slice[j], slice[i]
}

/* sort */
type Int64Slice []int64

func (slice Int64Slice) Len() int {
	return len(slice)
}

func (slice Int64Slice) Less(i, j int) bool {
	return slice[i] < slice[j]
}

func (slice Int64Slice) Swap(i, j int) {
	slice[i], slice[j] = slice[j], slice[i]
}
func Int64s(a []int64)                    { sort.Sort(Int64Slice(a)) }
func Int64sSliceAreSorted(a []int64) bool { return sort.IsSorted(Int64Slice(a)) }

const (
	initialBufSize = 1e4
	maxBufSize     = 1e8
	INF            = 1e8
)

var (
	scanner = bufio.NewScanner(os.Stdin)
	writer  = bufio.NewWriter(os.Stdout)
	di      = []int64{-1, 0, 1, 0}
	dj      = []int64{0, -1, 0, 1}
	di8     = []int64{-1, -1, 0, 1, 1, 1, 0, -1}
	dj8     = []int64{0, -1, -1, -1, 0, 1, 1, 1}
)

func main() {
	buf := make([]byte, initialBufSize)
	scanner.Buffer(buf, maxBufSize)
	scanner.Split(bufio.ScanWords)
	S := readString()
	K := readInt()
	// 最初の同じ文字列を抽出、検査する文字列にくっつける
	//	var s string = string(S[0])
	var prev = S[0]
	var ans int64
	// for i := 1; i < len(S); i++ {
	// 	if prev != S[i] {
	// 		break
	// 	}
	// 	prev = S[i]
	// 	s += string(prev)
	// }
	// S += s

	//  連続する部分を数えて / 2 する
	prev = S[0]
	var cont int64 = 1
	for i := 1; i < len(S); i++ {
		if prev != S[i] {
			if cont > 1 {
				ans += cont / 2 * K
			}
			cont = 0
		}
		prev = S[i]
		cont++
	}
	ans += cont / 2 * K
	if cont == int64(len(S)) {
		ans = cont * K / 2
	}
	fmt.Println(ans)
}

/*==========================================
 *             Library
 *==========================================*/
func NextPermutation(x sort.Interface) bool {
	n := x.Len() - 1
	if n < 1 {
		return false
	}
	j := n - 1
	for ; !x.Less(j, j+1); j-- {
		if j == 0 {
			return false
		}
	}
	l := n
	for !x.Less(j, l) {
		l--
	}
	x.Swap(j, l)
	for k, l := j+1, n; k < l; {
		x.Swap(k, l)
		k++
		l--
	}
	return true
}
func doubleAry(h int64, w int64, init int64) (res [][]int64) {
	res = make([][]int64, h)
	for i := int64(0); i < h; i++ {
		res[i] = make([]int64, w)
		for j := int64(0); j < w; j++ {
			res[i][j] = init
		}
	}
	return
}

func aryEq(a []int64, b []int64) bool {
	return reflect.DeepEqual(a, b)
}

func clone(n []int64) (r []int64) {
	r = make([]int64, len(n))
	for i := 0; i < len(n); i++ {
		r[i] = n[i]
	}
	return
}
func write(s string) {
	writer.WriteString(s)
}

func print() {
	writer.Flush()
}

// scanner.Split(bufio.ScanWords) をコメントアウトしないと使用不可
func readLine() (s string) {
	if scanner.Scan() {
		s = scanner.Text()
	}
	return s
}

func readInt() (read int64) {
	scanner.Scan()
	read, err := strconv.ParseInt(scanner.Text(), 10, 64)
	if err != nil {
		panic(err)
	}
	return
}

func readFloat() (read float64) {
	scanner.Scan()
	read, err := strconv.ParseFloat(scanner.Text(), 64)
	if err != nil {
		panic(err)
	}
	return
}

func readRunes() (read []rune) {
	scanner.Scan()
	for _, v := range scanner.Text() {
		read = append(read, v)
	}
	return
}

func readString() (read string) {
	scanner.Scan()
	read = scanner.Text()
	return
}

func readStrings() (read []string) {
	scanner.Scan()
	for _, v := range scanner.Text() {
		read = append(read, string(v))
	}
	return
}

func s2i(s string) int64 {
	var intVal, e = strconv.ParseInt(s, 10, 64)
	if e != nil {
		panic(e)
	}
	return intVal
}

func i2s(i int64) string {
	var strVal = strconv.FormatInt(i, 10)
	return strVal
}

func s2f(s string) float64 {
	var floatVal, e = strconv.ParseFloat(s, 64)
	if e != nil {
		panic(e)
	}
	return floatVal
}

func abs(i int64) int64 {
	return int64(math.Abs(float64(i)))
}

func max(a ...int64) int64 {
	ans := int64(0)
	for i, v := range a {
		if i == 0 {
			ans = v
		}
		if ans < v {
			ans = v
		}
	}
	return ans
}
func min(a ...int64) int64 {
	ans := int64(0)
	for i, v := range a {
		if i == 0 {
			ans = v
		}
		if ans > v {
			ans = v
		}
	}
	return ans
}

func sum(i []int64) int64 {
	sum := int64(0)
	for _, val := range i {
		sum += val
	}
	return sum
}

func split(s string) []string {
	return strings.Fields(s)
}

func strAry2intAry(strs []string) []int64 {
	var ret = make([]int64, 0, len(strs))
	for _, str := range strs {
		var intVal = s2i(str)
		ret = append(ret, intVal)
	}
	return ret
}

func intAry2strAry(nums []int64) []string {
	var ret = make([]string, 0, len(nums))
	for _, num := range nums {
		var strVal = i2s(num)
		ret = append(ret, strVal)
	}
	return ret
}

func ary2str(strs []string) string {
	return strings.Join(strs, " ")
}

func reverse(res []int64) []int64 {
	for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
		res[i], res[j] = res[j], res[i]
	}
	return res
}
func reverseStr(res []string) []string {
	for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
		res[i], res[j] = res[j], res[i]
	}
	return res
}

func ini(res []int, init int) {
	if len(res) == 0 {
		return
	}
	res[0] = init
	for i := 0; i < len(res); i++ {
		copy(res[i:], res[:i])
	}
}

//
// func regexpExample() {
//     // Your code here!
//     var str = "13:20"
//     r := regexp.MustCompile(`(\d+):(\d+)`)
//     fmt.Println(r.FindStringSubmatch(str))
// }

// type Country struct {
//     gold int
//     silver int
//     blonze int
// }

// // 複数ソートのサンプル
// func stableSortExample() []Country{
//     var country = []Country {
//         {gold:1, silver:2, blonze:3},
//         {gold:1, silver:2, blonze:3},
//         {gold:1, silver:3, blonze:2},
//         {gold:1, silver:3, blonze:3},
//     }
//     sort.SliceStable(country, func(i, j int) bool { return country[i].blonze > country[j].blonze })
//     sort.SliceStable(country, func(i, j int) bool { return country[i].silver > country[j].silver })
//     sort.SliceStable(country, func(i, j int) bool { return country[i].gold > country[j].gold })
//     return country
// }

Score : 300 points

Problem Statement

Given is a string S. Let T be the concatenation of K copies of S.
We can repeatedly perform the following operation: choose a character in T and replace it with a different character.
Find the minimum number of operations required to satisfy the following condition: any two adjacent characters in T are different.

Constraints

1 \leq |S| \leq 100

S consists of lowercase English letters.

1 \leq K \leq 10^9

K is an integer.

Input

Input is given from Standard Input in the following format:

S
K

Output

Print the minimum number of operations required.

Sample Input 1

issii
2

Sample Output 1

4

T is issiiissii. For example, we can rewrite it into ispiqisyhi, and now any two adjacent characters are different.

Sample Input 2

qq
81

Sample Output 2

81

Sample Input 3

cooooooooonteeeeeeeeeest
999993333

Sample Output 3

8999939997


package main

import (
        "bufio"
        "fmt"
        "os"
        "strconv"
        "strings"
)

var sc = bufio.NewScanner(os.Stdin)

func readInt() int              { return readIntArray()[0] }
func readInt2() (int, int)      { a := readIntArray(); return a[0], a[1] }
func readInt3() (int, int, int) { a := readIntArray(); return a[0], a[1], a[2] }
func readIntArray() []int {
        a := make([]int, 0, 1000)
        sc.Scan()
        for _, v := range strings.Split(sc.Text(), " ") {
                vv, _ := strconv.Atoi(v)
                a = append(a, vv)
        }
        return a
}
func readString() string        { return readStringArray()[0] }
func readStringArray() []string { sc.Scan(); return strings.Split(sc.Text(), " ") }

func count(s string) (int, bool) {
        prev := s[0]
        alleq := true
        var c int
        for i := 1; i < len(s); i++ {
                if prev == s[i] {
                        c++
                        prev = 0
                } else {
                        prev = s[i]
                        alleq = false
                }
        }
        return c, alleq
}

func main() {
        s := readString()
        k := readInt()

        c, eq := count(s)

        // a -> 0
        // aa -> 1
        // aaa -> 1
        // aaaa -> 2
        // aaaaa -> 2
        if eq {
                fmt.Println(len(s) * k / 2)
                return
        }

        if s[0] != s[len(s)-1] {
                fmt.Println(c * k)
                return
        }

        // aaabaaa -> 2
        // aaabaaa|aaabaaa|aaabaaa -> 8
        //    |   3   |   3   |
        topcount := len(s) - len(strings.TrimLeft(s, string(s[0])))
        bottomcount := len(s) - len(strings.TrimRight(s, string(s[len(s)-1])))
        in := topcount + bottomcount

        front, _ := count(s[:len(s)-bottomcount])
        back, _ := count(s[topcount:])
        //fmt.Printf("[%s] [%d] [%s]\n", s[:len(s)-bottomcount], in, s[topcount:])

        fmt.Println(front/2 + (in/2)*(k-1) + back/2)
}


package main

import (
        "bufio"
        "fmt"
        "os"
        "strconv"
        "strings"
)

var sc = bufio.NewScanner(os.Stdin)

func readInt() int              { return readIntArray()[0] }
func readInt2() (int, int)      { a := readIntArray(); return a[0], a[1] }
func readInt3() (int, int, int) { a := readIntArray(); return a[0], a[1], a[2] }
func readIntArray() []int {
        a := make([]int, 0, 1000)
        sc.Scan()
        for _, v := range strings.Split(sc.Text(), " ") {
                vv, _ := strconv.Atoi(v)
                a = append(a, vv)
        }
        return a
}
func readString() string        { return readStringArray()[0] }
func readStringArray() []string { sc.Scan(); return strings.Split(sc.Text(), " ") }

func main() {
        s := readString()
        k := readInt()

        var count int
        var prev rune
        for _, r := range s {
                if prev == r {
                        count++
                        prev = 0
                } else {
                        prev = r
                }
        }

        // a x3 -> aaa -> aba
        if len(s) == 1 {
                fmt.Println(k / 2)
                return
        }

        // aa x3 -> aaaaaa -> ababab
        if len(s) == 2 && s[0] == s[1] {
                fmt.Println(k)
                return
        }

        // aaa x3 -> aaaaaaaaa -> abcabcabc
        if len(s) == 3 && s[0] == s[1] && s[0] == s[2] {
                fmt.Println(2 * k)
                return
        }

        var joinChange int
        if s[0] == s[len(s)-1] && s[len(s)-1] != s[len(s)-2] {
                joinChange = 1
        }

        fmt.Println(count*k + joinChange*(k-1))
}


package main

import (
        "bufio"
        "fmt"
        "os"
        "strconv"
        "strings"
)

var sc = bufio.NewScanner(os.Stdin)

func readInt() int              { return readIntArray()[0] }
func readInt2() (int, int)      { a := readIntArray(); return a[0], a[1] }
func readInt3() (int, int, int) { a := readIntArray(); return a[0], a[1], a[2] }
func readIntArray() []int {
        a := make([]int, 0, 1000)
        sc.Scan()
        for _, v := range strings.Split(sc.Text(), " ") {
                vv, _ := strconv.Atoi(v)
                a = append(a, vv)
        }
        return a
}
func readString() string        { return readStringArray()[0] }
func readStringArray() []string { sc.Scan(); return strings.Split(sc.Text(), " ") }

func main() {
        s := readString()
        k := readInt()

        var count int
        var prev rune
        for _, r := range s {
                if prev == r {
                        count++
                        prev = 0
                } else {
                        prev = r
                }
        }

        var joinChange int
        if s[0] == s[len(s)-1] && s[len(s)-1] != s[len(s)-2] {
                joinChange = 1
        }

        fmt.Println(count*k + joinChange*(k-1))
}


package main

import "fmt"

func countPair(S string) (pair int) {
	for i := 0; i+1 < len(S); i++ {
		if S[i] == S[i+1] {
			pair++
			i++
		}
	}
	return pair
}

func main() {
	var s1, s2 string
	var k, ans int
	fmt.Scan(&s1, &k)
	m := make(map[byte]int, 0)
	for i := 0; i < len(s1); i++ {
		m[s1[i]]++
	}
	p1 := countPair(s1)
	s2 = s1 + s1
	p2 := countPair(s2)
	if len(m) == 1 {
		ans = len(s1) * k / 2
	} else if p1*2 == p2 {
		ans = p1 * k
	} else {
		d := p2 - p1*2
		ans = p1*k + (k-1)*d
	}
	fmt.Println(ans)
}


package main

import "fmt"

func countPair(S string) (pair int) {
	for i := 0; i+1 < len(S); i++ {
		if S[i] == S[i+1] {
			pair++
			i++
		}
	}
	return pair
}

func main() {
	var s1, s2 string
	var k, ans int
	fmt.Scan(&s1, &k)
	p1 := countPair(s1)
	s2 = s1 + s1 // 繋げてpairが増えるか?
	p2 := countPair(s2)
	if p1*2 == p2 { // 繋げてもペアの数が増えない
		ans = p1 * k
	} else { // 繋げるとペアの数が増える
		d := p2 - p1*2
		ans = p1*k + (k-1)*d
	}
	fmt.Println(ans)
}


package main

import "fmt"

func main() {
	var (
		s string
		k int
	)
	fmt.Scan(&s, &k)

	cnt := 0
	for i := 0; i < len(s); i++ {
		if i+1 < len(s) && s[i] == s[i+1] {
			cnt++
			i++
		}
	}

	if cnt == len(s)-1 {
		fmt.Println(len(s) * k / 2)
		return
	}

	if s[0] != s[len(s)-1] {
		fmt.Println(k * cnt)
		return
	}

	a := 1
	for i := 1; i < len(s); i++ {
		if s[i] != s[0] {
			break
		}
		a++
	}
	b := 1
	for i := len(s) - 2; i >= 0; i-- {
		if s[i] != s[len(s)-1] {
			break
		}
		b++
	}
	cnt = 0
	for i := a; i < len(s)-b; i++ {
		if i+1 < len(s)-b && s[i] == s[i+1] {
			cnt++
			i++
		}
	}
	fmt.Println(k*cnt + (k-1)*((a+b)/2) + a/2 + b/2)
}


package main

import "fmt"

func main() {
	var (
		s string
		k int
	)
	fmt.Scan(&s, &k)

	cnt := 0
	for i := 0; i < len(s); i++ {
		if i+1 < len(s) && s[i] == s[i+1] {
			cnt++
			i++
		}
	}

	if cnt == len(s)-1 {
		fmt.Println(len(s) * k / 2)
		return
	}

	if s[0] == s[len(s)-1] {
		a := 0
		for i := 1; i < len(s); i++ {
			if s[0] == s[i] {
				a++
				continue
			}
			break
		}
		b := 0
		for i := len(s) - 2; i >= 0; i-- {
			if s[len(s)-1] == s[i] {
				b++
				continue
			}
			break
		}
		fmt.Println(k*cnt + (k-1)*(a/2+b/2-(a+b)/2))
		return
	}

	fmt.Println(k * cnt)
}


package main

import "fmt"

func main() {
	var (
		s string
		k int
	)
	fmt.Scan(&s, &k)

	cnt := 0
	for i := 0; i < len(s); i++ {
		if i+1 < len(s) && s[i] == s[i+1] {
			cnt++
			i++
		}
	}

	if cnt == len(s)-1 {
		fmt.Println(len(s) * k / 2)
		return
	}

	if s[0] == s[len(s)-1] {
		if len(s) == 3 {
			fmt.Println(k - 1)
			return
		}

		a := 0
		for i := 1; i < len(s); i++ {
			if s[0] == s[i] {
				a++
				continue
			}
			break
		}
		b := 0
		for i := 0; i < len(s)-1; i++ {
			if s[len(s)-1] == s[i] {
				b++
				continue
			}
			break
		}
		fmt.Println(k*cnt - (a/2+b/2-(a+b)/2)*(k-1))
		return
	}

	fmt.Println(k * cnt)
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var sc *bufio.Scanner

func nextStr() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func culculate(s string) int {
	rs := []rune(s)
	cnt := 0
	for i := 1; i < len(rs); i++ {
		if rs[i] == rs[i-1] {
			rs[i] = '*'
			cnt++
		}
	}
	return cnt
}

func main() {
	sc = bufio.NewScanner(os.Stdin)
	sc.Buffer(make([]byte, 0), 1000000001*3)
	sc.Split(bufio.ScanWords)
	s, k := nextStr(), nextInt()
	s2 := strings.Join([]string{s, s}, "")

	ans1 := culculate(s)
	ans2 := culculate(s2)
	diff := ans2 - ans1
	fmt.Println(ans1 + (diff * (k - 1)))
}


// ProblemURL : https://atcoder.jp/contests/agc039/tasks/agc039_a
// ---------------------------------------------
package main

import (
	"fmt"
	"strings"
)

func countAlphabet(s string) int {
	m := make(map[rune]int, 26)
	for _, ss := range s {
		m[ss]++
	}
	return len(m)
}

func calcCostNaive(s string) int {
	t := []byte(s)
	cost := 0
	for i := 1; i < len(t); i++ {
		if t[i-1] == t[i] {
			t[i] = '#'
			cost++
		}
	}
	return cost
}

func main() {
	var s string
	var k int
	fmt.Scan(&s, &k)

	if countAlphabet(s) == 1 {
		length := len(s) * k
		cost := length / 2
		fmt.Println(cost)
		return
	}

	if s[0] == s[len(s)-1] {
		t := string(s[0])
		ctHead := len(s) - len(strings.TrimLeft(s, t))
		ctTail := len(s) - len(strings.TrimRight(s, t))
		u := strings.Trim(s, t)
		cost := ctHead/2 + ctTail/2 + calcCostNaive(u)*k + (ctHead+ctTail)/2*(k-1)
		fmt.Println(cost)
	} else {
		cost := calcCostNaive(s)
		cost *= k
		fmt.Println(cost)
	}
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc *bufio.Scanner

func nextLine() string {
	sc.Scan()
	return sc.Text()
}

func main() {
	sc = bufio.NewScanner(os.Stdin)

	input1 := nextLine()
	input2, _ := strconv.Atoi(nextLine())

	baseStrRune := []rune(input1)
	idx := 1
	res := 0

	for idx < len(baseStrRune) {
		left := baseStrRune[idx-1]
		target := baseStrRune[idx]

		if left != target {
			idx = idx + 1
			continue
		}
		baseStrRune[idx] = target + 1
		idx = idx + 1
		res++
	}
	res = res * input2
	if baseStrRune[0] == baseStrRune[len(baseStrRune)-1] {
		res = res + input2 - 1
	}
	fmt.Print(res)
}


package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
)

var (
	sc      = bufio.NewScanner(os.Stdin)
	mod int = 1e9 + 7
)

func init() {
	sc.Split(bufio.ScanWords)
}

func main() {
	S := getString()
	K := getInt()

	oldS := []byte(S)
	newS := []byte(S)

	changeCnt := 0

	if len(newS) == 1 {
		changeCnt = K / 2
	} else {
		for i := 1; i < len(newS); i++ {
			if newS[i] == newS[i-1] {
				newS[i] = '*'
			}
		}

		if len(newS) >= 3 {
			if newS[1] == '*' && newS[0] != newS[2] {
				newS[1] = newS[0]
				newS[0] = '*'
			}
		}

		cnt := 0
		for i := 0; i < len(newS); i++ {
			if newS[i] == newS[0] || newS[i] == '*' {
				cnt++
			} else {
				break
			}
		}

		if cnt%2 == 0 {
			for i := 0; i < cnt/2; i++ {
				newS[2*i+1] = newS[2*i]
				newS[2*i] = '*'
			}
		}

		if newS[0] == newS[len(newS)-1] {
			newS[len(newS)-1] = '*'
		}

		for _, c := range newS {
			if c == '*' {
				changeCnt++
			}
		}

		changeCnt = changeCnt * K

		// 末尾2つが*なら、1回減らす
		if newS[len(newS)-2] == '*' && newS[len(newS)-1] == '*' {
			changeCnt--
		} else if newS[len(newS)-1] == '*' && oldS[len(oldS)-2] != oldS[len(oldS)-1] {
			changeCnt--
		}

		//fmt.Println(string(newS), string(newS))
	}

	fmt.Println(changeCnt)
}

func getInt() int {
	sc.Scan()
	str := sc.Text()
	value, _ := strconv.Atoi(str)
	return value
}

func getString() string {
	sc.Scan()
	return sc.Text()
}

func abs(a int) int {
	return int(math.Abs(float64(a)))
}

func pow(p, q int) int {
	return int(math.Pow(float64(p), float64(q)))
}

func min(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton min() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Min(float64(res), float64(nums[i])))
	}
	return res
}

func max(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton max() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Max(float64(res), float64(nums[i])))
	}
	return res
}

func strSearch(a []string, b string) bool {
	for i := 0; i < len(a); i++ {
		if a[i] == b {
			return true
		}
	}
	return false
}

func printIntArray(array []int) {
	strArray := fmt.Sprint(array)
	fmt.Println(strArray[1 : len(strArray)-1])
}

func calcMod(x int) int {
	return x % mod
}


package main

import (
	"fmt"
	"os"
	"strings"
)

func main() {
	// fmt.Println(8999939997 / 999993333)
	var s string
	var k int
	fmt.Scan(&s, &k)
	ss := strings.Split(s, "")
	var p string
	var count int
	// var j int
	var j = 1
	var f bool
	var fs string
	for i, c := range ss {
		if c == p && i != 0 {
			count++
			f = true
		} else {
			if f {
				j++
			}
			f = false
		}
		p = c
		if len(s)-1 == i {
			fs = c
		}
	}
	// fmt.Println(fs)
	// fmt.Println(count, j)
	var r int
	if j == 0 {
		fmt.Println(k * count)
		os.Exit(0)
	}
	if s[0:1] == fs {
		r = count / (j - 1)
	} else {
		r = (count / (j - 1)) + 1
	}
	fmt.Println(k * r)
}

// cooooooooonteeeeeeeeeest


package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strconv"
)

var scan *bufio.Scanner
var writer io.Writer

func init() {
	scan = bufio.NewScanner(os.Stdin)
	writer = os.Stdout
	scan.Split(bufio.ScanWords)
}

func main() {
	solve()
}

func solve() {
	var s string
	fmt.Scan(&s)
	var k int
	fmt.Scan(&k)

	res := 0
	c := 1
	cs := 1
	csf := true
	for i := 1; i < len(s); i++ {
		if s[i] == s[i-1] {
			c++
			if csf {
				cs++
			}
		} else {
			res += c / 2
			c = 1
			csf = false
		}
	}
	res += c / 2
	res = res * k
	if s[0] == s[len(s)-1] && c%2 == 1 && cs%2 == 1 {
		res += k - 1
	}
	fmt.Fprint(writer, res)
}

func nextWord() string {
	scan.Scan()
	str := scan.Text()
	return str
}

func nextInt() int {
	i, e := strconv.Atoi(nextWord())
	if e != nil {
		panic(e)
	}
	return i
}


package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"os"
	"strconv"
)

func solve(sc *scanner, wr *bufio.Writer) {
	n, m := sc.getInt2()
	pq := newIntPriorityQueue()
	for i := 0; i < n; i++ {
		a := sc.getInt()
		heap.Push(pq, a)
	}

	for i := 0; i < m; i++ {
		(*pq)[0] /= 2
		heap.Fix(pq, 0)
	}

	ans := sum(*pq...)
	fmt.Fprintln(wr, ans)
}

type intPriorityQueue []int

func newIntPriorityQueue() *intPriorityQueue {
	pq := new(intPriorityQueue)
	heap.Init(pq)
	return pq
}

func (pq intPriorityQueue) Len() int           { return len(pq) }
func (pq intPriorityQueue) Less(i, j int) bool { return pq[i] > pq[j] }
func (pq intPriorityQueue) Swap(i, j int)      { pq[i], pq[j] = pq[j], pq[i] }
func (pq *intPriorityQueue) Push(x interface{}) {
	*pq = append(*pq, x.(int))
}
func (pq *intPriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	ret := old[n-1]
	*pq = old[0 : n-1]
	return ret
}

func main() {
	sc := newScanner()
	wr := bufio.NewWriter(os.Stdout)
	maxBufSize := int(1e8)
	sc.Buffer(make([]byte, 4096), maxBufSize)
	sc.Split(bufio.ScanWords)

	solve(sc, wr)
	wr.Flush()
}

// input ------------------------
type scanner struct {
	*bufio.Scanner
}

func newScanner() *scanner {
	sc := bufio.NewScanner(os.Stdin)
	return &scanner{sc}
}
func (sc *scanner) getInt() int {
	sc.Scan()
	ret, err := strconv.Atoi(sc.Text())
	if err != nil {
		panic(err)
	}
	return ret
}
func (sc *scanner) getInt2() (int, int) {
	return sc.getInt(), sc.getInt()
}
func (sc *scanner) getInt3() (int, int, int) {
	return sc.getInt(), sc.getInt(), sc.getInt()
}
func (sc *scanner) getInt4() (int, int, int, int) {
	return sc.getInt(), sc.getInt(), sc.getInt(), sc.getInt()
}
func (sc *scanner) getInts(n int) []int {
	ret := make([]int, n)
	for i := range ret {
		ret[i] = sc.getInt()
	}
	return ret
}
func (sc *scanner) getString() string {
	sc.Scan()
	return sc.Text()
}
func (sc *scanner) getRunes() []rune {
	return []rune(sc.getString())
}
func (sc *scanner) getFloat() float64 {
	sc.Scan()
	ret, err := strconv.ParseFloat(sc.Text(), 64)
	if err != nil {
		panic(err)
	}
	return ret
}
func (sc *scanner) getFloats(n int) []float64 {
	ret := make([]float64, n)
	for i := range ret {
		ret[i] = sc.getFloat()
	}
	return ret
}

// math ----------------------------
func sum(ns ...int) int {
	var sum int
	for _, n := range ns {
		sum += n
	}
	return sum
}

func max(ns ...int) int {
	max := ns[0]
	for i := 1; i < len(ns); i++ {
		if max < ns[i] {
			max = ns[i]
		}
	}
	return max
}

func min(ns ...int) int {
	min := ns[0]
	for i := 1; i < len(ns); i++ {
		if min > ns[i] {
			min = ns[i]
		}
	}
	return min
}

func pow(a, b int) int {
	ret := 1
	for b > 0 {
		if b&1 > 0 {
			ret = ret * a
		}
		a = a * a
		b >>= 1
	}
	return ret
}

Score : 400 points

Problem Statement

Takahashi is going to buy N items one by one.

The price of the i-th item he buys is A_i yen (the currency of Japan).

He has M discount tickets, and he can use any number of them when buying an item.

If Y tickets are used when buying an item priced X yen, he can get the item for \frac{X}{2^Y} (rounded down to the nearest integer) yen.

What is the minimum amount of money required to buy all the items?

Constraints

All values in input are integers.

1 \leq N, M \leq 10^5

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N

Output

Print the minimum amount of money required to buy all the items.

Sample Input 1

3 3
2 13 8

Sample Output 1

9

We can buy all the items for 9 yen, as follows:

Buy the 1-st item for 2 yen without tickets.

Buy the 2-nd item for 3 yen with 2 tickets.

Buy the 3-rd item for 4 yen with 1 ticket.

Sample Input 2

4 4
1 9 3 5

Sample Output 2

6

Sample Input 3

1 100000
1000000000

Sample Output 3

0

We can buy the item priced 1000000000 yen for 0 yen with 100000 tickets.

Sample Input 4

10 1
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 4

9500000000


package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"reflect"
	"sort"
	"strconv"
	"strings"
	// "regexp"
)

/* sort */
type pair struct {
	index  int64
	p1, p2 interface{}
}
type pairs []pair

func (slice pairs) Len() int {
	return len(slice)
}

func (slice pairs) Less(i, j int) bool {
	return slice[i].index < slice[j].index
}

func (slice pairs) Swap(i, j int) {
	slice[i], slice[j] = slice[j], slice[i]
}

/* sort */
type Int64Slice []int64

func (slice Int64Slice) Len() int {
	return len(slice)
}

func (slice Int64Slice) Less(i, j int) bool {
	return slice[i] < slice[j]
}

func (slice Int64Slice) Swap(i, j int) {
	slice[i], slice[j] = slice[j], slice[i]
}
func Int64s(a []int64)                    { sort.Sort(Int64Slice(a)) }
func Int64sSliceAreSorted(a []int64) bool { return sort.IsSorted(Int64Slice(a)) }

const (
	initialBufSize = 1e4
	maxBufSize     = 1e8
	INF            = 1e8
)

var (
	scanner = bufio.NewScanner(os.Stdin)
	writer  = bufio.NewWriter(os.Stdout)
	di      = []int64{-1, 0, 1, 0}
	dj      = []int64{0, -1, 0, 1}
	di8     = []int64{-1, -1, 0, 1, 1, 1, 0, -1}
	dj8     = []int64{0, -1, -1, -1, 0, 1, 1, 1}
)

func main() {
	buf := make([]byte, initialBufSize)
	scanner.Buffer(buf, maxBufSize)
	scanner.Split(bufio.ScanWords)
	N, M := readInt(), readInt()
	A := make([]int64, N)
	for i := int64(0); i < N; i++ {
		A[i] = readInt()
	}
	Int64s(A)
	i := len(A) - 1
	for M > 0 {
		Int64s(A)
		A[i] /= 2
		M--
	}
	fmt.Println(sum(A))
}

/*==========================================
 *             Library
 *==========================================*/
func NextPermutation(x sort.Interface) bool {
	n := x.Len() - 1
	if n < 1 {
		return false
	}
	j := n - 1
	for ; !x.Less(j, j+1); j-- {
		if j == 0 {
			return false
		}
	}
	l := n
	for !x.Less(j, l) {
		l--
	}
	x.Swap(j, l)
	for k, l := j+1, n; k < l; {
		x.Swap(k, l)
		k++
		l--
	}
	return true
}
func doubleAry(h int64, w int64, init int64) (res [][]int64) {
	res = make([][]int64, h)
	for i := int64(0); i < h; i++ {
		res[i] = make([]int64, w)
		for j := int64(0); j < w; j++ {
			res[i][j] = init
		}
	}
	return
}

func aryEq(a []int64, b []int64) bool {
	return reflect.DeepEqual(a, b)
}

func clone(n []int64) (r []int64) {
	r = make([]int64, len(n))
	for i := 0; i < len(n); i++ {
		r[i] = n[i]
	}
	return
}
func write(s string) {
	writer.WriteString(s)
}

func print() {
	writer.Flush()
}

// scanner.Split(bufio.ScanWords) をコメントアウトしないと使用不可
func readLine() (s string) {
	if scanner.Scan() {
		s = scanner.Text()
	}
	return s
}

func readInt() (read int64) {
	scanner.Scan()
	read, err := strconv.ParseInt(scanner.Text(), 10, 64)
	if err != nil {
		panic(err)
	}
	return
}

func readFloat() (read float64) {
	scanner.Scan()
	read, err := strconv.ParseFloat(scanner.Text(), 64)
	if err != nil {
		panic(err)
	}
	return
}

func readRunes() (read []rune) {
	scanner.Scan()
	for _, v := range scanner.Text() {
		read = append(read, v)
	}
	return
}

func readString() (read string) {
	scanner.Scan()
	read = scanner.Text()
	return
}

func readStrings() (read []string) {
	scanner.Scan()
	for _, v := range scanner.Text() {
		read = append(read, string(v))
	}
	return
}

func s2i(s string) int64 {
	var intVal, e = strconv.ParseInt(s, 10, 64)
	if e != nil {
		panic(e)
	}
	return intVal
}

func i2s(i int64) string {
	var strVal = strconv.FormatInt(i, 10)
	return strVal
}

func s2f(s string) float64 {
	var floatVal, e = strconv.ParseFloat(s, 64)
	if e != nil {
		panic(e)
	}
	return floatVal
}

func abs(i int64) int64 {
	return int64(math.Abs(float64(i)))
}

func max(a ...int64) int64 {
	ans := int64(0)
	for i, v := range a {
		if i == 0 {
			ans = v
		}
		if ans < v {
			ans = v
		}
	}
	return ans
}
func min(a ...int64) int64 {
	ans := int64(0)
	for i, v := range a {
		if i == 0 {
			ans = v
		}
		if ans > v {
			ans = v
		}
	}
	return ans
}

func sum(i []int64) int64 {
	sum := int64(0)
	for _, val := range i {
		sum += val
	}
	return sum
}

func split(s string) []string {
	return strings.Fields(s)
}

func strAry2intAry(strs []string) []int64 {
	var ret = make([]int64, 0, len(strs))
	for _, str := range strs {
		var intVal = s2i(str)
		ret = append(ret, intVal)
	}
	return ret
}

func intAry2strAry(nums []int64) []string {
	var ret = make([]string, 0, len(nums))
	for _, num := range nums {
		var strVal = i2s(num)
		ret = append(ret, strVal)
	}
	return ret
}

func ary2str(strs []string) string {
	return strings.Join(strs, " ")
}

func reverse(res []int64) []int64 {
	for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
		res[i], res[j] = res[j], res[i]
	}
	return res
}
func reverseStr(res []string) []string {
	for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
		res[i], res[j] = res[j], res[i]
	}
	return res
}

func ini(res []int, init int) {
	if len(res) == 0 {
		return
	}
	res[0] = init
	for i := 0; i < len(res); i++ {
		copy(res[i:], res[:i])
	}
}

//
// func regexpExample() {
//     // Your code here!
//     var str = "13:20"
//     r := regexp.MustCompile(`(\d+):(\d+)`)
//     fmt.Println(r.FindStringSubmatch(str))
// }

// type Country struct {
//     gold int
//     silver int
//     blonze int
// }

// // 複数ソートのサンプル
// func stableSortExample() []Country{
//     var country = []Country {
//         {gold:1, silver:2, blonze:3},
//         {gold:1, silver:2, blonze:3},
//         {gold:1, silver:3, blonze:2},
//         {gold:1, silver:3, blonze:3},
//     }
//     sort.SliceStable(country, func(i, j int) bool { return country[i].blonze > country[j].blonze })
//     sort.SliceStable(country, func(i, j int) bool { return country[i].silver > country[j].silver })
//     sort.SliceStable(country, func(i, j int) bool { return country[i].gold > country[j].gold })
//     return country
// }


package main

import (
	"fmt"
	"math"
	"sort"
)

const MOD = 1000000007

func ModAdd(a, b int64) int64 {
	return (a + b) % MOD
}

func ModMul(a, b int64) int64 {
	return a * b % MOD
}

func ModSub(a, b int64) int64 {
	r := (a%MOD - b%MOD) % MOD
	if r < 0 {
		r += MOD
	}
	return r
}

func ModDiv(a, b int64) int64 {
	return a % MOD * ModInv(b) % MOD
}

func ModPow(a, n int64) int64 {
	var r int64 = 1
	for n > 0 {
		if n&1 == 1 {
			r = r * a % MOD
		}
		a = a * a % MOD
		n >>= 1
	}
	return r
}

func ModInv(a int64) int64 {
	var b, u, v int64 = MOD, 1, 0
	for b > 0 {
		t := a / b
		a -= t * b
		a, b = b, a
		u -= t * v
		u, v = v, u
	}
	u %= MOD
	if u < 0 {
		u += MOD
	}
	return u
}

type Q struct {
	idx, value int
}

type QS []*Q

func (p QS) Len() int           { return len(p) }
func (p QS) Less(i, j int) bool { return p[i].value > p[j].value }
func (p QS) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }

func main() {
	var N, M int
	fmt.Scanf("%d %d\n", &N, &M)

	A := make(sort.IntSlice, N)
	for i := 0; i < N; i++ {
		var a int
		fmt.Scan(&a)
		A[i] = a
	}
	sort.Sort(sort.Reverse(A))

	q := make(QS, N)
	for i, d := range A {
		q[i] = &Q{
			idx: i, value: d,
		}
	}
	if N == 1 {
		fmt.Println(A[0] / int(math.Pow(2, float64(M))))
		return
	}
	for M > 0 {
		qi := q[0]
		next := q[1]
		q = q[1:]
		for M > 0 && qi.value >= next.value {
			qi.value /= 2
			M--
		}
		A[qi.idx] = qi.value
		q = append(q, qi)
		sort.Sort(q)

	}

	sum := 0

	for i := 0; i < N; i++ {
		sum += A[i]
	}

	fmt.Println(sum)

}


package main

import (
	"fmt"
	"sort"
)

func main() {
	var n, m int
	fmt.Scan(&n, &m)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}
	// sort.Sort(sort.Reverse(sort.IntSlice(a)))

	// a[0] /= 2
	for i := 0; i < m; i++ {
		sort.Sort(sort.Reverse(sort.IntSlice(a)))
		a[0] /= 2

		// index := 0
		// loop := i + 1
		// if loop > n {
		// 	loop = n
		// }
		// for j := 0; j < loop; j++ {
		// 	if a[j] > a[index] {
		// 		index = j
		// 	}
		// }
		// a[index] /= 2
	}

	res := 0
	for i := 0; i < n; i++ {
		res += a[i]
	}
	fmt.Println(res)
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func nextFloat() float64 {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return float64(i)
}

func main() {
	sc.Split(bufio.ScanWords)
	n := nextInt()
	m := nextInt()
	prices := make([]float64, n)
	for i := 0; i < n; i++ {
		prices[i] = nextFloat()
	}
	sort.Float64s(prices)
	for i := 0; i < m; i++ {
		half := prices[n-1] / 2.0
		for i := 2; i <= n; i++ {
			if i == 2 && half > prices[n-2] {
				prices[n-1] = half
				break
			} else if half > prices[n-i] {
				prices = append(prices[:n-i+1], append([]float64{half}, prices[n-i+1:n-1]...)...)
				break
			}
		}
	}
	var sum int
	for i := 0; i < n; i++ {
		sum += int(prices[i])
	}
	fmt.Println(sum)
}


package main

import (
	"fmt"
)

var (
	N, M int
)

// PriorityQueue is something.
type PriorityQueue struct {
	HeapSize int
	heap     []int
	size     int
	Reverse  bool
}

// Push pushs a number to queue
func (p *PriorityQueue) Push(x int) {

	// initialization
	if p.HeapSize == 0 {
		p.HeapSize = 100
	}
	if len(p.heap) == 0 && p.HeapSize > 0 {
		p.heap = make([]int, p.HeapSize)
	}
	i := p.size
	p.size++
	for i > 0 {
		n := (i - 1) / 2
		if p.Reverse {
			if p.heap[n] > x {
				break
			}
		} else {
			if p.heap[n] <= x {
				break
			}
		}

		p.heap[i] = p.heap[n]
		i = n
	}
	p.heap[i] = x
}

// Pop pops a number
func (p *PriorityQueue) Pop() int {
	ret := p.heap[0]
	p.size--
	x := p.heap[p.size]
	i := 0
	for (i*2 + 1) < p.size {
		a := i*2 + 1
		b := i*2 + 2
		if p.Reverse {
			if b < p.size && p.heap[b] >= p.heap[a] {
				a = b
			}
			if p.heap[a] < x {
				break
			}
		} else {
			if b < p.size && p.heap[b] < p.heap[a] {
				a = b
			}
			if p.heap[a] >= x {
				break
			}
		}

		p.heap[i] = p.heap[a]
		i = a
	}
	p.heap[i] = x
	return ret
}

func main() {

	fmt.Scan(&N, &M)
	pq := PriorityQueue{
		HeapSize: 1000*100 + 10,
		Reverse:  true,
	}

	var a int
	for i := 0; i < N; i++ {
		fmt.Scan(&a)
		pq.Push(a)
	}
	for i := 0; i < M; i++ {
		max := pq.Pop() / 2
		pq.Push(max)
	}

	ans := uint64(0)
	for i := 0; i < N; i++ {
		ans += uint64(pq.Pop())
	}
	fmt.Println(ans)
}


package main
import (
	"bufio"
	"container/heap"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func next() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	sc.Scan()
	i, _ := strconv.Atoi(sc.Text())
	return i
}

func nextInt64() int64 {
	sc.Scan()
	i, _ := strconv.ParseInt(sc.Text(), 10, 64)
	return i
}

type Item struct {
  Price int
}

type PriorityQueue []*Item

func (pq PriorityQueue) Len() int {
  return len(pq)
}

func (pq PriorityQueue) Less(i, j int) bool {
  return pq[j].Price < pq[i].Price
}

func (pq PriorityQueue) Swap(i, j int) {
  pq[i], pq[j] = pq[j], pq[i]
}

func (pq *PriorityQueue) Pop() interface{} {
  old := *pq
  n := len(old)
  item := old[n-1]
  *pq = old[0:n-1]
  return item
}

func (pq *PriorityQueue) Push(x interface{}) {
  item := x.(*Item)
  *pq = append(*pq, item)
}

func main() {
  sc.Buffer(make([]byte, 500000), 500000)
  sc.Split(bufio.ScanWords)

  n := nextInt()
  m := nextInt()

  as := make([]int, n)
  for i := 0; i < n; i++ {
    as[i] = nextInt()
  }
  priorityQueue := make(PriorityQueue, n, 1000*n)
  result := 0
  for i, a := range as {
    item := Item{}
    item.Price = a
    priorityQueue[i] = &item
    result += a
  }
  heap.Init(&priorityQueue)

  for i := 0; i < m; i++ {
    item := heap.Pop(&priorityQueue).(*Item)
    newPrice := item.Price/2
    discountedPrice := item.Price - newPrice
    result -= discountedPrice
    newItem := Item{}
    newItem.Price = newPrice
    heap.Push(&priorityQueue, &newItem)
  }
  fmt.Println(result)

}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func getScanner(fp *os.File) *bufio.Scanner {
	scanner := bufio.NewScanner(fp)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 500001), 500000)
	return scanner
}

func getNextString(scanner *bufio.Scanner) string {
	scanner.Scan()
	return scanner.Text()
}

func getNextInt(scanner *bufio.Scanner) int {
	i, _ := strconv.Atoi(getNextString(scanner))
	return i
}

func getNextInt64(scanner *bufio.Scanner) int64 {
	i, _ := strconv.ParseInt(getNextString(scanner), 10, 64)
	return i
}

func getNextUint64(scanner *bufio.Scanner) uint64 {
	i, _ := strconv.ParseUint(getNextString(scanner), 10, 64)
	return i
}

func getNextFloat64(scanner *bufio.Scanner) float64 {
	i, _ := strconv.ParseFloat(getNextString(scanner), 64)
	return i
}

func main() {
	fp := os.Stdin
	if len(os.Args) > 1 {
		fp, _ = os.Open(os.Args[1])
	}
	scanner := getScanner(fp)
	writer := bufio.NewWriter(os.Stdout)

	n := getNextInt(scanner)
	m := getNextInt(scanner)
	seg := Segment{}
	seg.init(n)
	for i := 0; i < n; i++ {
		seg.maximize(i, getNextInt(scanner))
	}
	for i := 0; i < m; i++ {
		seg.maximize(seg.top(), seg.bucket[seg.h-1][0]>>1)
	}

	var ans int64
	for i := 0; i < n; i++ {
		ans += int64(seg.bucket[0][i])
	}

	fmt.Fprintln(writer, ans)
	writer.Flush()
}

// Segment ...
type Segment struct {
	n, h, i, chunk int
	unit           []int
	bucket         [][]int
}

func (seg *Segment) init(n int) {
	seg.n = n
	seg.unit = make([]int, 1)
	seg.unit[0] = 1
	seg.bucket = make([][]int, 1)
	seg.bucket[0] = make([]int, n)

	chunk := 2
	for i := 0; n > 1; i++ {
		n = (n-1)/chunk + 1
		seg.bucket = append(seg.bucket, make([]int, n))
		seg.unit = append(seg.unit, seg.unit[i]*chunk)
	}
	seg.h = len(seg.unit)
	seg.chunk = chunk
}

func (seg *Segment) maximize(index, value int) {
	seg.bucket[0][index] = value
	for seg.i = 0; seg.i < seg.h-1; seg.i++ {
		s := index - index%seg.chunk
		t := s + seg.chunk
		if t > len(seg.bucket[seg.i]) {
			t = len(seg.bucket[seg.i])
		}
		parent := index / seg.chunk
		max := 0
		for i := s; i < t; i++ {
			if max < seg.bucket[seg.i][i] {
				max = seg.bucket[seg.i][i]
			}
		}
		seg.bucket[seg.i+1][parent] = max
		index /= seg.chunk
	}
}

func (seg *Segment) top() int {
	index := 0
	for seg.i = seg.h - 2; seg.i >= 0; seg.i-- {
		s := index * seg.chunk
		t := s + seg.chunk
		if t > len(seg.bucket[seg.i]) {
			t = len(seg.bucket[seg.i])
		}
		for i := s; i < t; i++ {
			if seg.bucket[seg.i][i] == seg.bucket[seg.i+1][index] {
				index = i
				break
			}
		}
	}

	return index
}


package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"sort"
	"strconv"
)

type Diff struct {
	Num int
}

type Diffs []Diff

func (d Diffs) Len() int {
	return len(d)
}

func (d Diffs) Swap(i, j int) {
	d[i], d[j] = d[j], d[i]
}

func (d Diffs) Less(i, j int) bool {
	return d[i].Num > d[j].Num
}

var (
	sc = bufio.NewScanner(os.Stdin)
	mod int = 1e9 + 7
)

func init() {
	sc.Split(bufio.ScanWords)
}

func main() {
	N := getInt()
	M := getInt()

	sum := 0
	var diffs Diffs
	for i := 0; i < N; i++ {
		input := getInt()
		sum += input

		for i := 0; i < M; i++ {
			before := input / pow(2, i)
			after := input / pow(2, i+1)
			diff := before - after

			if diff != 0 {
				diffs = append(diffs, Diff{Num: diff})
			}
		}
	}

	sort.Sort(diffs)

	diffSum := 0
	for i := 0; i < M; i++ {
		diffSum += diffs[i].Num
	}

	fmt.Println(sum - diffSum)
}

func getInt() int {
	sc.Scan()
	str := sc.Text()
	value, _ := strconv.Atoi(str)
	return value
}

func getString() string {
	sc.Scan()
	return sc.Text()
}

func abs(a int) int {
	return int(math.Abs(float64(a)))
}

func pow(p, q int) int {
	return int(math.Pow(float64(p), float64(q)))
}

func min(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton min() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Min(float64(res), float64(nums[i])))
	}
	return res
}

func max(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton max() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Max(float64(res), float64(nums[i])))
	}
	return res
}

func strSearch(a []string, b string) bool {
	for i := 0; i < len(a); i++ {
		if a[i] == b {
			return true
		}
	}
	return false
}

func printIntArray(array []int) {
	strArray := fmt.Sprint(array)
	fmt.Println(strArray[1 : len(strArray) - 1])
}

func calcMod(x int) int {
	return x % mod
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

func getScanner(fp *os.File) *bufio.Scanner {
	scanner := bufio.NewScanner(fp)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 500001), 500000)
	return scanner
}

func getNextString(scanner *bufio.Scanner) string {
	scanner.Scan()
	return scanner.Text()
}

func getNextInt(scanner *bufio.Scanner) int {
	i, _ := strconv.Atoi(getNextString(scanner))
	return i
}

func getNextInt64(scanner *bufio.Scanner) int64 {
	i, _ := strconv.ParseInt(getNextString(scanner), 10, 64)
	return i
}

func getNextUint64(scanner *bufio.Scanner) uint64 {
	i, _ := strconv.ParseUint(getNextString(scanner), 10, 64)
	return i
}

func getNextFloat64(scanner *bufio.Scanner) float64 {
	i, _ := strconv.ParseFloat(getNextString(scanner), 64)
	return i
}

func main() {
	fp := os.Stdin
	if len(os.Args) > 1 {
		fp, _ = os.Open(os.Args[1])
	}
	scanner := getScanner(fp)
	writer := bufio.NewWriter(os.Stdout)

	n := getNextInt(scanner)
	m := getNextInt(scanner)
	bits := make([]int, 32)
	aa := make([]int, n)
	for i := 0; i < n; i++ {
		aa[i] = getNextInt(scanner)
		for ii := 31; ii >= 0; ii-- {
			on := 1 & (aa[i] >> uint(ii))
			bits[ii] += on
			if on == 1 {
				break
			}
		}
	}
	sort.Ints(aa)
	var ans int64
	for i := 31; i >= 0; i-- {
		minus := minint(bits[i], m)
		if bits[i] >= m {
			sort.Ints(aa)
		}
		bits[i] -= minus
		if i > 0 {
			bits[i-1] += minus
		}
		for ii := 0; ii < minus; ii++ {
			aa[n-1-ii] >>= 1
		}
		m -= minus
	}
	for i := 0; i < n; i++ {
		ans += int64(aa[i])
	}
	fmt.Fprintln(writer, ans)
	writer.Flush()
}

func minint(a int, b int) int {
	if a < b {
		return a
	}
	return b
}


package main

import (
	"bufio"
	_ "container/heap"
	"fmt"
	"os"
	_ "sort"
	"strconv"
)

// I/O
type Scanner struct {
	sc *bufio.Scanner
}

func NewScanner() *Scanner {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 1024), int(1e+9))
	return &Scanner{sc}
}

func (s *Scanner) nextStr() string {
	s.sc.Scan()
	return s.sc.Text()
}

func (s *Scanner) nextInt() int {
	i, e := strconv.Atoi(s.nextStr())
	if e != nil {
		panic(e)
	}
	return i
}

func (s *Scanner) nextFloat() float64 {
	f, e := strconv.ParseFloat(s.nextStr(), 64)
	if e != nil {
		panic(e)
	}
	return f
}

func (s *Scanner) nextRuneSlice() []rune {
	return []rune(s.nextStr())
}

func (s *Scanner) nextIntSlice(n int) []int {
	res := make([]int, n)
	for i := 0; i < n; i++ {
		res[i] = s.nextInt()
	}
	return res
}

func (s *Scanner) nextFloatSlice(n int) []float64 {
	res := make([]float64, n)
	for i := 0; i < n; i++ {
		res[i] = s.nextFloat()
	}
	return res
}

// Arithmetic
func max(nums ...int) int {
	m := nums[0]
	for _, i := range nums {
		if m < i {
			m = i
		}
	}
	return m
}

func min(nums ...int) int {
	m := nums[0]
	for _, i := range nums {
		if m > i {
			m = i
		}
	}
	return m
}

func abs(x int) int {
	if x > 0 {
		return x
	}
	return -x
}

func pow(x, y int) int {
	res := 1
	for i := 0; i < y; i++ {
		res *= x
	}
	return res
}

func ceil(a, b int) int {
	if a%b == 0 {
		return a / b
	} else {
		return a/b + 1
	}
}

func gcd(a, b int) int {
	if b == 0 {
		return a
	}
	return gcd(b, a%b)
}

func lcm(a, b int) int {
	return a / gcd(a, b) * b
}

// Sort
type RuneSlice []rune

func (a RuneSlice) Len() int           { return len(a) }
func (a RuneSlice) Less(i, j int) bool { return a[i] < a[j] }
func (a RuneSlice) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

// Main
const MOD = int(1e+9) + 7
const INF = 1 << 60

func main() {
	sc := NewScanner()
	wtr := bufio.NewWriter(os.Stdout)
	defer wtr.Flush()
	N := sc.nextInt()
	S := sc.nextStr()
	l := 0
	r := N/2 + 1
	for (r - l) > 1 {
		mid := (r + l) / 2
		if f(mid, S) {
			l = mid
		} else {
			r = mid
		}
	}

	fmt.Fprintln(wtr, l)
}

func f(m int, S string) bool {
	res := false
	for i := 0; i <= len(S)-2*m; i++ {
		str := S[i : i+m]
		for j := i + m; j <= len(S)-m; j++ {
			if str == S[j:j+m] {
				res = true
				break
			}
		}
	}
	return res
}

Score : 500 points

Problem Statement

Given is a string S of length N.

Find the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping.

More formally, find the maximum positive integer len such that there exist integers l_1 and l_2 ( 1 \leq l_1, l_2 \leq N - len + 1 ) that satisfy the following:

l_1 + len \leq l_2

S[l_1+i] = S[l_2+i] (i = 0, 1, ..., len - 1)

If there is no such integer len, print 0.

Constraints

2 \leq N \leq 5 \times 10^3

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping. If there is no such non-empty string, print 0 instead.

Sample Input 1

5
ababa

Sample Output 1

2

The strings satisfying the conditions are: a, b, ab, and ba. The maximum length among them is 2, which is the answer.
Note that aba occurs twice in S as contiguous substrings, but there is no pair of integers l_1 and l_2 mentioned in the statement such that l_1 + len \leq l_2.

Sample Input 2

2
xy

Sample Output 2

0

No non-empty string satisfies the conditions.

Sample Input 3

13
strangeorange

Sample Output 3

5


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func getScanner(fp *os.File) *bufio.Scanner {
	scanner := bufio.NewScanner(fp)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 500001), 500000)
	return scanner
}

func getNextString(scanner *bufio.Scanner) string {
	scanner.Scan()
	return scanner.Text()
}

func getNextInt(scanner *bufio.Scanner) int {
	i, _ := strconv.Atoi(getNextString(scanner))
	return i
}

func getNextInt64(scanner *bufio.Scanner) int64 {
	i, _ := strconv.ParseInt(getNextString(scanner), 10, 64)
	return i
}

func getNextUint64(scanner *bufio.Scanner) uint64 {
	i, _ := strconv.ParseUint(getNextString(scanner), 10, 64)
	return i
}

func getNextFloat64(scanner *bufio.Scanner) float64 {
	i, _ := strconv.ParseFloat(getNextString(scanner), 64)
	return i
}

func main() {
	fp := os.Stdin
	wfp := os.Stdout

	if os.Getenv("MASPY") == "ますピ" {
		fp, _ = os.Open(os.Getenv("BEET_THE_HARMONY_OF_PERFECT"))
	}
	if os.Getenv("MASPYPY") == "ますピッピ" {
		wfp, _ = os.Create(os.Getenv("NGTKANA_IS_GENIUS10"))
	}

	scanner := getScanner(fp)
	writer := bufio.NewWriter(wfp)

	n := getNextInt(scanner)
	s := getNextString(scanner)

	mp := MP{}
	for l := n >> 1; l > 0; l-- {
		for i := 0; i < n-l*2; i++ {
			ss := s[i : i+l]
			mp.init(ss)
			j := 0
			for k := i + l; j < l && k < n; k++ {
				if ss[j] != s[k] {
					for j >= 0 && ss[j] != s[k] {
						j = mp.table[j]
					}
				}
				j++
			}
			if j == l {
				fmt.Println(l)
				return
			}

		}
	}
	fmt.Println(0)

	writer.Flush()
}

// MP ...
type MP struct {
	s     string
	table []int
}

func (mp *MP) init(s string) {
	mp.s = s
	n := len(s)
	table := make([]int, n+1)
	table[0] = -1
	j := -1
	for i := 0; i < n; i++ {
		for j >= 0 && s[i] != s[j] {
			j = table[j]
		}
		j++
		table[i+1] = j
	}
	mp.table = table
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

const (
	B = 100000007
)

func main() {
	N := readInt()
	S := readString()
	ms := 0
	for i := 1; i < N; i++ {
		ts := 0
		for j := 0; j < N - i; j++ {
			if S[j] == S[j + i] {
				ts++
				if ts > ms {
					ms = ts
				}
				if ts == i {
					break
				}
			} else {
				ts = 0
			}
		}
	}
	fmt.Println(ms)
}

const (
	ioBufferSize = 1 * 1024 * 1024 // 1 MB
)

var stdinScanner = func() *bufio.Scanner {
	result := bufio.NewScanner(os.Stdin)
	result.Buffer(make([]byte, ioBufferSize), ioBufferSize)
	result.Split(bufio.ScanWords)
	return result
}()

func readString() string {
	stdinScanner.Scan()
	return stdinScanner.Text()
}

func readInt() int {
	result, err := strconv.Atoi(readString())
	if err != nil {
		panic(err)
	}
	return result
}


package main

import "fmt"
import "bufio"
import "os"
import "strconv"
import "sort"

var _sw = bufio.NewScanner(os.Stdin)

type node struct {
	next  [26]*node
	len   int
	debug string
	start int
}

func main() {
	var n int
	fmt.Scan(&n)
	var s string
	fmt.Scan(&s)

	mkNode := func(len int, debug string, start int) *node {
		return &node{
			next:  [26]*node{},
			len:   len,
			debug: debug,
			start: start,
		}
	}

	root := mkNode(0, "", 0)
	set := []*node{
		root,
	}
	max := 0
	for i := range s {
		c := s[i]
		for j, n := range set {
			if n.next[c-'a'] == nil {
				n.next[c-'a'] = mkNode(n.len+1, "", i)
			} else {
				if n.start < i-(n.len+1) {
					max = Max(n.len+1, max)
				}
			}
			set[j] = n.next[c-'a']
		}
		set = append(set, root)
	}
	fmt.Println(max)
}

func init() {
	_sw.Split(bufio.ScanWords)
}

func NextInt() int {
	if _sw.Scan() == false {
		panic(_sw.Err())
	}
	i, e := strconv.Atoi(_sw.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func NextInts(n int) []int {
	a := make([]int, n)
	for i := range a {
		a[i] = NextInt()
	}
	return a
}

func NextString() string {
	if _sw.Scan() == false {
		panic(_sw.Err())
	}
	return _sw.Text()
}

func Max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

func Min(x, y int) int {
	if x > y {
		return y
	}
	return x
}

func Bounded(lower, n, upper int) int {
	return Min(upper, Max(lower, n))
}

func SortInts(xs []int) {
	sort.Sort(sort.IntSlice(xs))
}

func ReverseSortInts(xs []int) {
	sort.Sort(sort.Reverse(sort.IntSlice(xs)))
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func nextInt() int {
	sc.Scan()
	num, err := strconv.Atoi(sc.Text())
	if err != nil {
		panic(err)
	}
	return num
}

func nextString() string {
	sc.Scan()
	return sc.Text()
}

func main() {
	sc.Split(bufio.ScanWords)

	a := nextInt()
	s := nextString()

	if a >= 3200 {
		fmt.Println(s)
	} else {
		fmt.Println("red")
	}
}

Score : 100 points

Problem Statement

You will be given an integer a and a string s consisting of lowercase English letters as input.

Write a program that prints s if a is not less than 3200 and prints red if a is less than 3200.

Constraints

2800 \leq a < 5000

s is a string of length between 1 and 10 (inclusive).

Each character of s is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

a
s

Output

If a is not less than 3200, print s; if a is less than 3200, print red.

Sample Input 1

3200
pink

Sample Output 1

pink

a = 3200 is not less than 3200, so we print s = pink.

Sample Input 2

3199
pink

Sample Output 2

red

a = 3199 is less than 3200, so we print red.

Sample Input 3

4049
red

Sample Output 3

red

a = 4049 is not less than 3200, so we print s = red.


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func nextLine() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	sc.Scan()
	i, err := strconv.Atoi(sc.Text())
	if err != nil {
		panic(err)
	}
	return i
}

func main() {
	sc.Split(bufio.ScanWords)
	a, s := nextInt(), nextLine()
	if a > 3200 {
		fmt.Println(s)
	} else {
		fmt.Println("red")
	}
}


package main

import "fmt"

func main() {
	var a int
	var s string
	fmt.Scan(&a, &s)

	if a >= 3200 {
		fmt.Println(s)
	} else {
		fmt.Println("red")
	}
}


package main

import (
	"fmt"
)

func main() {
	var a int
	var s string
	fmt.Scan(&a, &s)
	if a>=3200 {
		fmt.Println(s)
		return
	}
	fmt.Println("red")
}


package main

import (
	"fmt"
)

func main() {
	var number int
	var str string
	fmt.Scanf("%d", &number)
	fmt.Scanf("%s", &str)
	if number >= 3200 {
		fmt.Println(str)
	} else {
		fmt.Println("red")
	}
}


package main

import (
  "fmt"
)

func main() {
  var a int
  var s string
  fmt.Scan(&a)
  fmt.Scan(&s)

  if (a >= 3200 ) {
    fmt.Println(s)
  } else {
    fmt.Println("red")
  }
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"reflect"
	"sort"
	"strconv"
)

const (
	maxBufSize = 1024 * 1024
)

var (
	sc = func() *bufio.Scanner {
		sc := bufio.NewScanner(os.Stdin)
		buf := make([]byte, 1)
		sc.Buffer(buf, maxBufSize)
		sc.Split(bufio.ScanWords)
		return sc
	}()
	out = bufio.NewWriter(os.Stdout)
)

type edge struct {
	a int64
	b int64
}

type operation struct {
	p int64
	q int64
}

func solve(n int64, q int64, es []edge, os []operation) []int64 {
	ret := make([]int64, n)
	sort.Slice(es, func(i, j int) bool {
		return es[i].a < es[j].a
	})
	for _, o := range os {
		ret[o.p] += o.q
	}
	for _, e := range es {
		ret[e.b] += ret[e.a]
	}
	return ret
}

func main() {
	defer out.Flush()

	n := nextInt()
	q := nextInt()

	es := make([]edge, n-1)
	for i, _ := range es {
		es[i].a = nextInt() - 1
		es[i].b = nextInt() - 1
	}
	os := make([]operation, q)
	for i, _ := range os {
		os[i].p = nextInt() - 1
		os[i].q = nextInt()
	}
	res := solve(n, q, es, os)
	for i, r := range res {
		fmt.Fprint(out, r)
		if int64(i) < n - 1 {
			fmt.Fprint(out, " ")
		} else {
			fmt.Fprintln(out)
		}
	}
}

func next() string {
	sc.Scan()
	return sc.Text()
}

func nextStringAsBytes() []byte {
	sc.Scan()
	return []byte(sc.Text())
}

func nextInt() int64 {
	a, _ := strconv.ParseInt(next(), 10, 64)
	return a
}

func nextFloat() float64 {
	a, _ := strconv.ParseFloat(next(), 64)
	return a
}

func nextInts(n int64) []int64 {
	ret := make([]int64, n)
	for i := int64(0); i < n; i++ {
		ret[i] = nextInt()
	}
	return ret
}

func nextFloats(n int64) []float64 {
	ret := make([]float64, n)
	for i := int64(0); i < n; i++ {
		ret[i] = nextFloat()
	}
	return ret
}
func nextStrings(n int64) []string {
	ret := make([]string, n)
	for i := int64(0); i < n; i++ {
		ret[i] = next()
	}
	return ret
}

func containStr(arr []string, target string) bool {
	for _, v := range arr {
		if v == target {
			return true
		}
	}
	return false
}

func PrintOut(src interface{}, joinner string) {
	switch reflect.TypeOf(src).Kind() {
	case reflect.Slice:
		s := reflect.ValueOf(src)
		for idx := 0; idx < s.Len(); idx++ {
			fmt.Fprintf(out, "%v", s.Index(idx))
			if idx < s.Len()-1 {
				fmt.Fprintf(out, "%s", joinner)
			} else {
				fmt.Fprintln(out)
			}
		}
	default:
		fmt.Fprintln(out, "orz")
	}
}

// mapからkeysとvaluesを返す
func splitKeyValue(m map[interface{}]interface{}) (keys, values []interface{}) {
	switch reflect.TypeOf(m).Kind() {
	case reflect.Map:
		s := reflect.ValueOf(m)
		for _, v := range s.MapKeys() {
			keys = append(keys, v)
			values = append(values, s.MapIndex(v))
		}
	default:
		fmt.Fprintln(out, "orz")
	}
	return
}

Score : 400 points

Problem Statement

Given is a rooted tree with N vertices numbered 1 to N.
The root is Vertex 1, and the i-th edge (1 \leq i \leq N - 1) connects Vertex a_i and b_i.

Each of the vertices has a counter installed. Initially, the counters on all the vertices have the value 0.

Now, the following Q operations will be performed:

Operation j (1 \leq j \leq Q): Increment by x_j the counter on every vertex contained in the subtree rooted at Vertex p_j.

Find the value of the counter on each vertex after all operations.

Constraints

2 \leq N \leq 2 \times 10^5

1 \leq Q \leq 2 \times 10^5

1 \leq a_i < b_i \leq N

1 \leq p_j \leq N

1 \leq x_j \leq 10^4

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
a_1 b_1
:
a_{N-1} b_{N-1}
p_1 x_1
:
p_Q x_Q

Output

Print the values of the counters on Vertex 1, 2, \ldots, N after all operations, in this order, with spaces in between.

Sample Input 1

4 3
1 2
2 3
2 4
2 10
1 100
3 1

Sample Output 1

100 110 111 110

The tree in this input is as follows:

Each operation changes the values of the counters on the vertices as follows:

Operation 1: Increment by 10 the counter on every vertex contained in the subtree rooted at Vertex 2, that is, Vertex 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 0, 10, 10, 10, respectively.

Operation 2: Increment by 100 the counter on every vertex contained in the subtree rooted at Vertex 1, that is, Vertex 1, 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 110, 110, respectively.

Operation 3: Increment by 1 the counter on every vertex contained in the subtree rooted at Vertex 3, that is, Vertex 3. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 111, 110, respectively.

Sample Input 2

6 2
1 2
1 3
2 4
3 6
2 5
1 10
1 10

Sample Output 2

20 20 20 20 20 20


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var (
	N, Q int
	to	[][]int
)

func dfs(v, p int, ans []int) {
	for _, u := range to[v] {
		if u == p {
			continue
		}
		ans[u] += ans[v]
		dfs(u, v, ans)
	}
}

func main() {
	io := NewIo()
	defer io.Flush()

	N, Q = io.readInt(), io.readInt()
	to = make([][]int, N+5)
	for i := 0; i < N-1; i++  {
		var a, b int
		fmt.Scan(&a, &b)
		a--; b--
		to[a] = append(to[a], b)
		to[b] = append(to[b], a)
	}

	ans := make([]int, N)
	for i := 0; i < Q; i++ {
		p, x := io.readInt(), io.readInt()
		ans[p-1] += x
	}
	dfs(0, -1, ans)
	io.printIntSlice(ans)
}

type Io struct {
	reader *bufio.Reader
	writer *bufio.Writer
	tokens []string
	nextToken int
}

func NewIo() *Io {
	return &Io{
		reader: bufio.NewReader(os.Stdin),
		writer: bufio.NewWriter(os.Stdout),
	}
}

func (io *Io) readStringLine() string {
	var buffer []byte
	for  {
		line, isPrefix, err := io.reader.ReadLine()
		if err != nil {
			panic(err)
		}
		buffer = append(buffer, line...)
		if !isPrefix {
			break
		}
	}
	return string(buffer)
}

func (io *Io) readString() string {
	for io.nextToken >= len(io.tokens) {
		line := io.readStringLine()
		io.tokens = strings.Fields(line)
		io.nextToken = 0
	}
	r := io.tokens[io.nextToken]
	io.nextToken++
	return r
}

func (io *Io) readInt() int {
	i, err := strconv.Atoi(io.readString())
	if err != nil {
		panic(err)
	}
	return i
}

func (io *Io) println(a ...interface{}) {
	fmt.Fprintln(io.writer, a...)
}

func (io *Io) printf(format string, a ...interface{}) {
	fmt.Fprintf(io.writer, format, a...)
}

func (io *Io) printStringSlice(a []string) {
	var b []interface{}
	for _, v := range a {
		b = append(b, v)
	}
	io.println(b...)
}

func (io *Io) printIntSlice(a []int) {
	var b []interface{}
	for _, v := range a {
		b = append(b, v)
	}
	io.println(b...)
}

func max(a, b int) int {
	if a < b {
		return b
	}
	return a
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func (io *Io) Flush() {
	err := io.writer.Flush()
	if err != nil {
		panic(err)
	}
}


package main

import "fmt"

var (
	N, Q int
	to	[][]int
)

func dfs(v, p int, ans []int) {
	for _, u := range to[v] {
		if u == p {
			continue
		}
		ans[u] += ans[v]
		dfs(u, v, ans)
	}
}

func main() {
	fmt.Scan(&N, &Q)
	to = make([][]int, N+5)
	for i := 0; i < N-1; i++  {
		var a, b int
		fmt.Scan(&a, &b)
		a--; b--
		to[a] = append(to[a], b)
		to[b] = append(to[b], a)
	}

	ans := make([]int, N)
	for i := 0; i < Q; i++ {
		var p, x int
		fmt.Scan(&p, &x)
		ans[p-1] += x
	}
	dfs(0, -1, ans)
	for i := 0; i < N; i++ {
		fmt.Println(ans[i])
	}
}


package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"reflect"
	"sort"
	"strconv"
	"strings"
	// "regexp"
)

/* sort */
type pair struct {
	index  int64
	p1, p2 interface{}
}
type pairs []pair

func (slice pairs) Len() int {
	return len(slice)
}

func (slice pairs) Less(i, j int) bool {
	return slice[i].index < slice[j].index
}

func (slice pairs) Swap(i, j int) {
	slice[i], slice[j] = slice[j], slice[i]
}

/* sort */
type Int64Slice []int64

func (slice Int64Slice) Len() int {
	return len(slice)
}

func (slice Int64Slice) Less(i, j int) bool {
	return slice[i] < slice[j]
}

func (slice Int64Slice) Swap(i, j int) {
	slice[i], slice[j] = slice[j], slice[i]
}
func Int64s(a []int64)                    { sort.Sort(Int64Slice(a)) }
func Int64sSliceAreSorted(a []int64) bool { return sort.IsSorted(Int64Slice(a)) }

const (
	initialBufSize = 1e4
	maxBufSize     = 1e8
	INF            = 1e8
)

var (
	scanner = bufio.NewScanner(os.Stdin)
	writer  = bufio.NewWriter(os.Stdout)
	di      = []int64{-1, 0, 1, 0}
	dj      = []int64{0, -1, 0, 1}
	di8     = []int64{-1, -1, 0, 1, 1, 1, 0, -1}
	dj8     = []int64{0, -1, -1, -1, 0, 1, 1, 1}
	cnt     []int64
	N, Q    int64
	m       map[int64][]int64
	mpq     map[int64]int64
)

func main() {
	buf := make([]byte, initialBufSize)
	scanner.Buffer(buf, maxBufSize)
	scanner.Split(bufio.ScanWords)
	N, Q = readInt(), readInt()
	m = make(map[int64][]int64, N)
	cnt = make([]int64, N+1)
	for i := int64(0); i < N-1; i++ {
		a, b := readInt(), readInt()
		m[a] = append(m[a], b)
		m[b] = append(m[b], a)
	}
	for i := int64(0); i < Q; i++ {
		p, q := readInt(), readInt()
		cnt[p] += q
	}
	dfsCnt(1, -1)
	s2 := intAry2strAry(cnt)
	s := strings.Join(s2[1:], " ")
	fmt.Println(s)
}

func dfsCnt(n int64, p int64) {
	for i := int64(0); i < int64(len(m[n])); i++ {
		if m[n][i] != p {
			cnt[m[n][i]] += cnt[n]
			dfsCnt(m[n][i], n)
		}
	}
}

/*==========================================
 *             Library
 *==========================================*/
func NextPermutation(x sort.Interface) bool {
	n := x.Len() - 1
	if n < 1 {
		return false
	}
	j := n - 1
	for ; !x.Less(j, j+1); j-- {
		if j == 0 {
			return false
		}
	}
	l := n
	for !x.Less(j, l) {
		l--
	}
	x.Swap(j, l)
	for k, l := j+1, n; k < l; {
		x.Swap(k, l)
		k++
		l--
	}
	return true
}
func doubleAry(h int64, w int64, init int64) (res [][]int64) {
	res = make([][]int64, h)
	for i := int64(0); i < h; i++ {
		res[i] = make([]int64, w)
		for j := int64(0); j < w; j++ {
			res[i][j] = init
		}
	}
	return
}

func aryEq(a []int64, b []int64) bool {
	return reflect.DeepEqual(a, b)
}

func clone(n []int64) (r []int64) {
	r = make([]int64, len(n))
	for i := 0; i < len(n); i++ {
		r[i] = n[i]
	}
	return
}
func write(s string) {
	writer.WriteString(s)
}

func print() {
	writer.Flush()
}

// scanner.Split(bufio.ScanWords) をコメントアウトしないと使用不可
func readLine() (s string) {
	if scanner.Scan() {
		s = scanner.Text()
	}
	return s
}

func readInt() (read int64) {
	scanner.Scan()
	read, err := strconv.ParseInt(scanner.Text(), 10, 64)
	if err != nil {
		panic(err)
	}
	return
}

func readFloat() (read float64) {
	scanner.Scan()
	read, err := strconv.ParseFloat(scanner.Text(), 64)
	if err != nil {
		panic(err)
	}
	return
}

func readRunes() (read []rune) {
	scanner.Scan()
	for _, v := range scanner.Text() {
		read = append(read, v)
	}
	return
}

func readString() (read string) {
	scanner.Scan()
	read = scanner.Text()
	return
}

func readStrings() (read []string) {
	scanner.Scan()
	for _, v := range scanner.Text() {
		read = append(read, string(v))
	}
	return
}

func s2i(s string) int64 {
	var intVal, e = strconv.ParseInt(s, 10, 64)
	if e != nil {
		panic(e)
	}
	return intVal
}

func i2s(i int64) string {
	var strVal = strconv.FormatInt(i, 10)
	return strVal
}

func s2f(s string) float64 {
	var floatVal, e = strconv.ParseFloat(s, 64)
	if e != nil {
		panic(e)
	}
	return floatVal
}

func abs(i int64) int64 {
	return int64(math.Abs(float64(i)))
}

func max(a ...int64) int64 {
	ans := int64(0)
	for i, v := range a {
		if i == 0 {
			ans = v
		}
		if ans < v {
			ans = v
		}
	}
	return ans
}
func min(a ...int64) int64 {
	ans := int64(0)
	for i, v := range a {
		if i == 0 {
			ans = v
		}
		if ans > v {
			ans = v
		}
	}
	return ans
}

func sum(i []int64) int64 {
	sum := int64(0)
	for _, val := range i {
		sum += val
	}
	return sum
}

func split(s string) []string {
	return strings.Fields(s)
}

func strAry2intAry(strs []string) []int64 {
	var ret = make([]int64, 0, len(strs))
	for _, str := range strs {
		var intVal = s2i(str)
		ret = append(ret, intVal)
	}
	return ret
}

func intAry2strAry(nums []int64) []string {
	var ret = make([]string, 0, len(nums))
	for _, num := range nums {
		var strVal = i2s(num)
		ret = append(ret, strVal)
	}
	return ret
}

func ary2str(strs []string) string {
	return strings.Join(strs, " ")
}

func reverse(res []int64) []int64 {
	for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
		res[i], res[j] = res[j], res[i]
	}
	return res
}
func reverseStr(res []string) []string {
	for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
		res[i], res[j] = res[j], res[i]
	}
	return res
}

func ini(res []int, init int) {
	if len(res) == 0 {
		return
	}
	res[0] = init
	for i := 0; i < len(res); i++ {
		copy(res[i:], res[:i])
	}
}

//
// func regexpExample() {
//     // Your code here!
//     var str = "13:20"
//     r := regexp.MustCompile(`(\d+):(\d+)`)
//     fmt.Println(r.FindStringSubmatch(str))
// }

// type Country struct {
//     gold int
//     silver int
//     blonze int
// }

// // 複数ソートのサンプル
// func stableSortExample() []Country{
//     var country = []Country {
//         {gold:1, silver:2, blonze:3},
//         {gold:1, silver:2, blonze:3},
//         {gold:1, silver:3, blonze:2},
//         {gold:1, silver:3, blonze:3},
//     }
//     sort.SliceStable(country, func(i, j int) bool { return country[i].blonze > country[j].blonze })
//     sort.SliceStable(country, func(i, j int) bool { return country[i].silver > country[j].silver })
//     sort.SliceStable(country, func(i, j int) bool { return country[i].gold > country[j].gold })
//     return country
// }


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var G map[int][]int
var X []int
var sc = bufio.NewScanner(os.Stdin)

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func dfs(v, p int) {
	for _, r := range G[v] {
		if r == p {
			continue
		}
		X[r-1] += X[v-1]
		dfs(r, v)
	}
}

func main() {
	sc.Split(bufio.ScanWords)
	n := nextInt()
	q := nextInt()
	G = make(map[int][]int)
	for i := 1; i < n; i++ {
		a, b := nextInt(), nextInt()
		G[a] = append(G[a], b)
		G[b] = append(G[b], a)
	}
	X = make([]int, n)
	for i := 0; i < q; i++ {
		X[nextInt()-1] += nextInt()
	}
	dfs(1, -1)
	for _, x := range X {
		fmt.Printf("%d ", x)
	}
	fmt.Println()
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func newScanner() *bufio.Scanner {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	return scanner
}

var sc = newScanner()

func scanInt() int {
	sc.Scan()
	v, _ := strconv.Atoi(sc.Text())
	return v
}

func scanInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = scanInt()
	}
	return a
}

func scanString() string {
	if sc.Scan() {
		return sc.Text()
	}
	panic(sc.Err())
}

func main() {
	n, q := scanInt(), scanInt()
	tree := newTree(n)
	for i := 0; i < q; i++ {
		p, x := scanInt()-1, scanInt()
		debug("p", p, "x", x)
		setCounters(tree, p, x)
	}
	updateCounters(tree)
	for i := 0; i < n; i++ {
		separator := " "
		if i == n-1 {
			separator = "\n"
		}
		fmt.Print(tree[i].counter, separator)
	}
}

func debug(a ...interface{}) {
	// fmt.Println(a...)
}

type Node struct {
	id       int
	children []Node
	counter  int
}

func newTree(n int) map[int]*Node {
	tree := make(map[int]*Node)
	path := make(map[int][]int)
	for i := 0; i < n; i++ {
		tree[i] = &Node{id: i, counter: 0, children: []Node{}}
		debug(i, n, tree[i])
	}

	for i := 0; i < n-1; i++ {
		a, b := scanInt()-1, scanInt()-1
		path[a] = append(path[a], b)
		path[b] = append(path[b], a)
	}
	processed := make(map[int]bool)
	processed[0] = true
	for parentList := []int{0}; len(parentList) > 0; {
		nextParentList := []int{}
		for _, parent := range parentList {
			for _, v := range path[parent] {
				if _, exists := processed[v]; !exists {
					tree[parent].children = append(tree[parent].children, *tree[v])
					nextParentList = append(nextParentList, v)
					processed[v] = true
				}
			}
		}
		parentList = nextParentList
	}

	for i := 0; i < len(tree); i++ {
		debug(i, tree[i])
	}
	return tree
}

func setCounters(tree map[int]*Node, p, x int) {
	debug("p", p, "x", x)
	tree[p].counter += x
}

type PrevCurrentNode struct {
	prev    int
	current int
}

func updateCounters(tree map[int]*Node) {
	for targetLayer := []PrevCurrentNode{{0, 0}}; len(targetLayer) > 0; {
		nextLayer := []PrevCurrentNode{}
		for _, v := range targetLayer {
			prevNode := v.prev
			node := v.current
			if node != 0 {
				tree[node].counter += tree[prevNode].counter
			}
			for _, child := range tree[node].children {
				nextLayer = append(nextLayer, PrevCurrentNode{node, child.id})
			}
		}
		targetLayer = nextLayer
		debug(targetLayer)
	}
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func newScanner() *bufio.Scanner {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	return scanner
}

var sc = newScanner()

func scanInt() int {
	sc.Scan()
	v, _ := strconv.Atoi(sc.Text())
	return v
}

func scanInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = scanInt()
	}
	return a
}

func scanString() string {
	if sc.Scan() {
		return sc.Text()
	}
	panic(sc.Err())
}

func main() {
	n, q := scanInt(), scanInt()
	tree := newTree(n)
	for i := 0; i < q; i++ {
		p, x := scanInt()-1, scanInt()
		addCounters(tree, p, x)
	}
	for i := 0; i < n; i++ {
		separator := " "
		if i == n-1 {
			separator = "\n"
		}
		fmt.Print(tree[i].counter, separator)
	}
}

func debug(a ...interface{}) {
	// fmt.Println(a...)
}

type Node struct {
	id       int
	children []Node
	counter  int
}

func newTree(n int) map[int]*Node {
	tree := make(map[int]*Node)
	path := make(map[int][]int)
	for i := 0; i < n; i++ {
		tree[i] = &Node{id: i, counter: 0, children: []Node{}}
	}

	for i := 0; i < n-1; i++ {
		a, b := scanInt()-1, scanInt()-1
		path[a] = append(path[a], b)
		path[b] = append(path[b], a)
	}
	processed := make(map[int]bool)
	processed[0] = true
	for parentList := []int{0}; len(parentList) > 0; {
		nextParentList := []int{}
		for _, parent := range parentList {
			for _, v := range path[parent] {
				if _, exists := processed[v]; !exists {
					tree[parent].children = append(tree[parent].children, *tree[v])
					nextParentList = append(nextParentList, v)
					processed[v] = true
				}
			}
		}
		parentList = nextParentList
	}

	for i := 0; i < len(tree); i++ {
		debug(tree[i])
	}
	return tree
}

func addCounters(tree map[int]*Node, p, x int) {
	subtreeRoot := tree[p]
	debug("subtree root", subtreeRoot, "add", x)
	subtreeRoot.counter += x
	for _, node := range subtreeRoot.children {
		addCounters(tree, node.id, x)
	}
}

func sumCounters(tree map[int]*Node) int {
	sum := 0
	for i := 0; i < len(tree); i++ {
		sum += tree[i].counter
	}
	return sum
}


package main

import (
        "bufio"
        "fmt"
        "os"
        "strconv"
        "strings"
)

var si = bufio.NewScanner(os.Stdin)

type Node struct {
        Id     int
        Parent int
        Count  int
        Child  []int
}

func readInt() int {
        si.Scan()
        ret, _ := strconv.Atoi(si.Text())
        return ret
}
func main() {
        si.Split(bufio.ScanWords)
        N, Q := readInt(), readInt()
        Parent := make([]int, N+1, N+1)
        Count := make([]int, N+1, N+1)
        Child := make([][]int, N+1, N+1)
        for i := 0; i < N-1; i++ {
                a, b := readInt(), readInt()
                Child[a] = append(Child[a], b)
                Child[b] = append(Child[b], a)

        }
        for i := 0; i < Q; i++ {
                p, x := readInt(), readInt()
                Count[p] += x
        }
        ret := make([]int, N+1, N+1)
        stack := []int{1}
        for len(stack) > 0 {
                t := stack[len(stack)-1]
                for i := range Child[t] {
                        if Parent[Child[t][i]] == 0 {
                                Parent[Child[t][i]] = t
                        }
                }
                stack = stack[:len(stack)-1]
                ret[t] = Count[t] + ret[Parent[t]]
                for _, v := range Child[t] {
                        if v != Parent[t] {
                                stack = append(stack, v)
                        }
                }
        }
        fmt.Println(strings.Trim(fmt.Sprint(ret[1:]), "[]"))

}


package main

import (
        "bufio"
        "fmt"
        "os"
        "strconv"
        "strings"
)

var si = bufio.NewScanner(os.Stdin)

type Node struct {
        Id     int
        Parent int
        Count  int
        Child  []int
}

func readInt() int {
        si.Scan()
        ret, _ := strconv.Atoi(si.Text())
        return ret
}
func main() {
        si.Split(bufio.ScanWords)
        N, Q := readInt(), readInt()
        Parent := make([]int, N+1, N+1)
        Count := make([]int, N+1, N+1)
        Child := make([][]int, N+1, N+1)
        for i := 0; i < N-1; i++ {
                a, b := readInt(), readInt()
                Parent[b] = a
                Child[a] = append(Child[a], b)

        }
        for i := 0; i < Q; i++ {
                p, x := readInt(), readInt()
                Count[p] += x
        }
        ret := make([]int, N+1, N+1)
        stack := []int{1}
        for len(stack) > 0 {
                t := stack[len(stack)-1]
                stack = stack[:len(stack)-1]
                ret[t] = Count[t] + ret[Parent[t]]
                stack = append(stack, Child[t]...)
        }
        fmt.Println(strings.Trim(strings.Join(strings.Fields(fmt.Sprint(ret[1:])), " "), "[]"))

}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc, wr = bufio.NewScanner(os.Stdin), bufio.NewWriter(os.Stdout)

func scanString() string { sc.Scan(); return sc.Text() }
func scanInt() int { a,_ := strconv.Atoi(scanString()); return a }
func scanInt64() int64 { a,_ := strconv.ParseInt(scanString(),10,64); return a }
func scanFloat64() float64 { a,_ := strconv.ParseFloat(scanString(),64); return a }

func scanInts(n int) []int {
	res := make([]int, n); for i := 0; i < n; i++ { res[i] = scanInt() }; return res
}

func abs(a int) int { if a<0 { return -a }; return a }
func min(a,b int) int { if a<b { return a }; return b }
func max(a,b int) int { if a>b { return a }; return b }

//•*¨*•.¸¸♪Main•*¨*•.¸¸♪(　-ω-)ノ　(　・ω・)

func main() {
	defer wr.Flush()
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 10000), 1001001)

	n := scanInt()
	q := scanInt()

	g := make([][]int, n)
	done := make([]bool, n)
	cnt := make([]int, n)

	for i := 0; i < n-1; i++ {
		a,b := scanInt()-1, scanInt()-1
		g[a] = append(g[a], b)
		g[b] = append(g[b], a)
	}

	for i := 0; i < q; i++ {
		p := scanInt()-1
		x := scanInt()
		cnt[p] += x
	}

	var fn func(next, sum int)
	fn = func(next, sum int) {
		done[next] = true
		cnt[next] += sum
		for _, v := range g[next] {
			if done[v] {
				continue
			}

			fn(v, cnt[next])
		}
	}

	fn(0,0)

	for _, e := range cnt {
		fmt.Fprintf(wr, "%d ", e)
	}

	fmt.Fprintln(wr)

}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	io := newIo()
	defer io.Flush()
	N, Q := io.NextInt(), io.NextInt()
	points := map[int]int{}
	edges := map[int][]int{}
	for i := 0; i < N-1; i++ {
		a, b := io.NextInt(), io.NextInt()
		edges[a] = append(edges[a], b)
		edges[b] = append(edges[b], a)
	}
	for i := 0; i < Q; i++ {
		a, point := io.NextInt(), io.NextInt()
		points[a] = points[a] + point
	}
	visits := map[int]bool{}
	visits[1] = true
	totalPoints := make([]int, N+1)
	totalPoints[1] = points[1]
	q := []int{1}
	for len(q) > 0 {
		qq := q[0]
		q = q[1:]
		currentPoint := totalPoints[qq]
		for _, edge := range edges[qq] {
			_, exists := visits[edge]
			if exists {
				continue
			}
			visits[edge] = true
			totalPoints[edge] = currentPoint + points[edge]
			q = append(q, edge)
		}
	}
	io.PrintIntLn(totalPoints[1:])
}

type io struct {
	reader    *bufio.Reader
	writer    *bufio.Writer
	tokens    []string
	nextToken int
}

func newIo() *io {
	return &io{
		reader: bufio.NewReader(os.Stdin),
		writer: bufio.NewWriter(os.Stdout),
	}
}

func (io *io) Flush() {
	err := io.writer.Flush()
	if err != nil {
		panic(err)
	}
}

func (io *io) NextLine() string {
	var buffer []byte
	for {
		line, isPrefix, err := io.reader.ReadLine()
		if err != nil {
			panic(err)
		}
		buffer = append(buffer, line...)
		if !isPrefix {
			break
		}
	}
	return string(buffer)
}

func (io *io) Next() string {
	for io.nextToken >= len(io.tokens) {
		line := io.NextLine()
		io.tokens = strings.Fields(line)
		io.nextToken = 0
	}
	r := io.tokens[io.nextToken]
	io.nextToken++
	return r
}

func (io *io) NextInt() int {
	i, err := strconv.Atoi(io.Next())
	if err != nil {
		panic(err)
	}
	return i
}

func (io *io) NextFloat() float64 {
	i, err := strconv.ParseFloat(io.Next(), 64)
	if err != nil {
		panic(err)
	}
	return i
}

func (io *io) PrintLn(a ...interface{}) {
	fmt.Fprintln(io.writer, a...)
}

func (io *io) Printf(format string, a ...interface{}) {
	fmt.Fprintf(io.writer, format, a...)
}

func (io *io) PrintIntLn(a []int) {
	b := []interface{}{}
	for _, x := range a {
		b = append(b, x)
	}
	io.PrintLn(b...)
}

func (io *io) PrintStringLn(a []string) {
	b := []interface{}{}
	for _, x := range a {
		b = append(b, x)
	}
	io.PrintLn(b...)
}

func log(name string, value interface{}) {
	fmt.Fprintf(os.Stderr, "%s=%+v\n", name, value)
}


package main

import (
	"fmt"
)

// Node is tree
type Node struct {
	Count int
	Value int
	Right *Node
	Left  *Node
}

// NewNode is constractor
func NewNode(value int) *Node {
	l := new(Node)
	l.Value = value
	l.Right = nil
	l.Left = nil
	return l
}

func main() {
	var n, q int
	_, err := fmt.Scan(&n, &q)
	if err != nil {
		panic("error")
	}
	a := make([]*Node, n)
	for i := 0; i < n; i++ {
		a[i] = NewNode(i)
	}

	var parent, child int
	for i := 0; i < n-1; i++ {
		_, err := fmt.Scan(&parent, &child)
		if err != nil {
			panic("ERROR:1")
		}
		if a[parent-1].Right == nil {
			a[parent-1].Right = a[child-1]
		} else if a[parent-1].Left == nil {
			a[parent-1].Left = a[child-1]
		} else {
			panic("ERROR:2")
		}
	}

	for i := 0; i < q; i++ {
		var val, number int
		_, err := fmt.Scan(&number, &val)
		if err != nil {
			panic("ERROR:3")
		}
		count(val, a[number-1])
	}

	for i := 0; i < len(a); i++ {
		fmt.Print(a[i].Count)
        fmt.Print(" ")
	}
	fmt.Println()
}

func count(value int, point *Node) {
	point.Count += value
	if point.Right != nil {
		count(value, point.Right)
	}
    if point.Left != nil {
		count(value, point.Left)
	}
    return

}


package main

import (
	"fmt"
	"strconv"
)

type node struct {
	number int
	related []int
	point int64
}

var nodes [200000 + 5]node
var points [200000 + 5]int64

func main() {
	var N, Q int
	fmt.Scanf("%d", &N)
	fmt.Scanf("%d", &Q)

	//nodes = make([]node, N+1)
	var a, b int
	for i := 0; i < N-1; i++ {
		fmt.Scanf("%d", &a)
		fmt.Scanf("%d", &b)
		nodes[a].related = append(nodes[a].related, b)
		nodes[b].related = append(nodes[b].related, a)
	}

	//points = make([]int64, N+1)
	var target, point int
	for i := 0; i < Q; i++ {
		fmt.Scanf("%d", &target)
		fmt.Scanf("%d", &point)
		points[target] += int64(point)
	}

	//fmt.Println(nodes)
	//fmt.Println(points)

	calcPoint(1, 0, -1)
	for i := 1; i <= N; i++ {
		fmt.Print(strconv.FormatInt(nodes[i].point, 10) + " ")
	}
	//for i, n := range nodes {
	//	if i == 0 {
	//		continue
	//	}
	//	fmt.Print(strconv.FormatInt(n.point, 10) + " ")
	//}
}

func calcPoint(nodeNumber int, accumulated int64, parent int) {
	accumulated += points[nodeNumber]
	nodes[nodeNumber].point = accumulated
	for _, r := range nodes[nodeNumber].related {
		if r == parent {
			continue
		}
		calcPoint(r, accumulated, nodeNumber)
	}
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func nextInt() int {
	sc.Scan()
	i, err := strconv.Atoi(sc.Text())
	if err != nil {
		panic(err)
	}
	return i
}

func init() {
	// read one word/char/int separated by space(s).
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 8000000), 8000000)

	// read one line.
	// sc.Split(bufio.ScanLines)
}

func main() {
	var n, q int
	n = nextInt()
	q = nextInt()
	var g = make([][]int, n+1)
	for i := 1; i < n; i++ {
		var a, b int
		a = nextInt()
		b = nextInt()
		g[a] = append(g[a], b)
		g[b] = append(g[b], a)
	}
	var v = make([]int, n+1)
	for i := 0; i < q; i++ {
		var p, x int
		p = nextInt()
		x = nextInt()
		v[p] += x
	}

	que := make([]int, 0)
	que = append(que, 1)
	done := make([]bool, n+1)

	for len(que) != 0 {
		parent := que[0]
		que = que[1:]
		done[parent] = true

		for _, child := range g[parent] {
			if done[child] {
				continue
			}
			v[child] += v[parent]
			que = append(que, child)
		}
	}
	for i := 1; i < n+1; i++ {
		if i > 1 {
			fmt.Print(" ")
		}
		fmt.Print(v[i])
	}
	fmt.Println("")
}


package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func init() {
	sc.Split(bufio.ScanWords)
}

func main() {
	n, q := getInt(), getInt()

	values := make([]int, n)
	parents := make([]int, n)

	for i := 0; i < n-1; i++ {
		a, b := getInt(), getInt()
		parents[b-1] = a
	}

	for i := 0; i < q; i++ {
		p, x := getInt(), getInt()
		values[p-1] += x
	}

	for i := 0; i < n; i++ {
		if parents[i] != 0 {
			values[i] += values[parents[i] - 1]
		}
	}

	printIntArray(values)
}

func getInt() int {
	sc.Scan()
	str := sc.Text()
	value, _ := strconv.Atoi(str)
	return value
}

func scanStrings(len int) (strings []string) {
	for i := 0; i < len; i++ {
		sc.Scan()
		strings = append(strings, sc.Text())
	}
	return
}

func abs(a int) int {
	return int(math.Abs(float64(a)))
}

func pow(p, q int) int {
	return int(math.Pow(float64(p), float64(q)))
}

func min(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton min() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Min(float64(res), float64(nums[i])))
	}
	return res
}

func max(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton max() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Max(float64(res), float64(nums[i])))
	}
	return res
}

func strSearch(a []string, b string) bool {
	for i := 0; i < len(a); i++ {
		if a[i] == b {
			return true
		}
	}
	return false
}

func printIntArray(array []int) {
	strArray := fmt.Sprint(array)
	fmt.Println(strArray[1 : len(strArray) - 1])
}


package main

import (
	"bufio"
	"fmt"
	"io"
	"math"
	"os"
	"strconv"
	"strings"

)

func main() {
	solve(os.Stdin, os.Stdout)
}

type ReaderEx struct {
	baseScanner *bufio.Scanner
	words       []string
	nextWordIdx func() int
	initWordIdx func(int)
}

func NewScannerEx(stdin io.Reader) *ReaderEx {
	var this ReaderEx
	var idx int
	var wordsCnt int
	this.baseScanner = bufio.NewScanner(stdin)
	this.baseScanner.Buffer(make([]byte, 0), 1E+11)
	this.nextWordIdx = func() int {
		cur := idx
		idx = (idx + 1) % wordsCnt
		return cur
	}
	this.initWordIdx = func(wc int) {
		idx = 0
		wordsCnt = wc
	}
	return &this
}

func (me *ReaderEx) Scan(doSplit bool) (isScanned bool) {
	isScanned = me.baseScanner.Scan()
	if doSplit {
		me.words = strings.Fields(me.baseScanner.Text())
	} else {
		me.words = []string{me.baseScanner.Text()}
	}
	me.initWordIdx(len(me.words))
	return
}

func (me *ReaderEx) nextBytes() []byte {
	return []byte(me.words[me.nextWordIdx()])
}
func (me *ReaderEx) nextString() string {
	return me.words[me.nextWordIdx()]
}

type StringArray []string

func (me *ReaderEx) nextStringArray() StringArray {
	return me.words[me.nextWordIdx():]
}

func (me StringArray) toStrings() []string {
	return me
}

func (me StringArray) toInts() []int {
	strValues := me.toStrings()
	values := make([]int, len(strValues))
	for i, v := range strValues {
		n, err := strconv.Atoi(v)
		if err != nil {
			panic(err)
		}
		values[i] = n
	}
	return values
}
func (me *ReaderEx) nextInt() int {
	n, err := strconv.Atoi(me.words[me.nextWordIdx()])

	defer func() {
		if err != nil {
			panic(fmt.Sprintf("getInt(%d)", n))
		}
	}()
	return n
}

func pow(x, y, mod int) (ans int) {

	ans = 1
	for bit := 1 << uint(math.Floor(math.Log2(float64(y)))); ; bit >>= 1 {
		if y&bit != 0 {
			ans *= x
			if mod > 0 {
				ans %= mod
			}
		}
		if bit <= 1 {
			return
		}
		ans *= ans
		if mod > 0 {
			ans %= mod
		}
	}
}

type factType struct {
	prime int
	count int
}

func fact(n int) (facts []*factType) {

	for i := 2; i*i <= n; i++ {
		if n%i == 0 {
			fa := factType{prime: i}
			for n%fa.prime == 0 {
				n /= fa.prime
				fa.count++
			}
			facts = append(facts, &fa)
		}
	}
	if n > 1 {
		facts = append(facts, &factType{prime: n, count: 1})
	}
	return facts
}
func dec2bin(n int) (ret []bool) {
	for bit := 1 << uint(math.Floor(math.Log2(float64(n)))); ; bit >>= 1 {
		ret = append(ret, n&bit != 0)

		if bit <= 1 {
			return
		}
	}

}

func abs(v int) int {
	if v < 0 {
		v = -v
	}
	return v
}

func b2i(b bool) (i int) {
	if b {
		i = 1
	} else {
		i = 0
	}
	return
}

//Edge is
type Edge struct {
	node   *Node
	Bridge *Bridge
}

//Node is
type Node struct {
	id      int
	edges   []*Edge
	counter int
	add     int
}

//Bridge is
type Bridge struct {
	edges [2]Edge
}

//NewBridge is
func NewBridge(a, b *Node) (bridge *Bridge) {
	bridge = &Bridge{edges: [...]Edge{{node: a, Bridge: bridge}, {node: b, Bridge: bridge}}}
	a.edges = append(a.edges, &bridge.edges[1])
	//b.edges = append(b.edges, &bridge.edges[0])
	return
}

//Another is
func (edge *Edge) Another() (another *Edge) {
	Bridge := edge.Bridge
	if &Bridge.edges[0] == edge {
		another = &Bridge.edges[1]
	} else {
		another = &Bridge.edges[0]
	}
	return
}

func solve(stdin io.Reader, stdout io.Writer) {

	r := NewScannerEx(stdin)
	r.Scan(true)
	n, q := r.nextInt(), r.nextInt()

	nodes := make([]Node, n+1)
	for i := 1; i <= n; i++ {
		nodes[i] = Node{id: i}
	}

	for i := 0; i < n-1; i++ {
		r.Scan(true)
		a, b := r.nextInt(), r.nextInt()
		NewBridge(&nodes[a], &nodes[b])
	}

	for i := 0; i < q; i++ {
		r.Scan(true)
		p, x := r.nextInt(), r.nextInt()
		nodes[p].add += x
	}

	nodePack := make([]*Node, 0, n)
	nodePack = append(nodePack, &nodes[1])

	for len(nodePack) > 0 {
		cur := nodePack[len(nodePack)-1]
		nodePack = nodePack[0 : len(nodePack)-1]

		cur.counter += cur.add
		for _, next := range cur.edges {
			next.node.add += cur.add
			nodePack = append(nodePack, next.node)
		}
	}

	out := make([]string, 0, n)
	for i := 1; i <= n; i++ {
		out = append(out, fmt.Sprint(nodes[i].counter))
	}
	fmt.Fprintln(stdout, strings.Join(out, " "))
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var t [][]int
var a []int

func dfs(v int, p int) {
	for _, u := range t[v] {
		if u != p {
			a[u] += a[v]
			dfs(u, v)
		}
	}
}

func main() {
	var n, q int

	fmt.Scan(&n, &q)

	t = make([][]int, n)
	a = make([]int, n)

	scanner := bufio.NewScanner(os.Stdin)

	for i := 0; i < n-1; i++ {
		scanner.Scan()
		inputs := strings.Split(scanner.Text(), " ")

		p, _ := strconv.Atoi(inputs[0])
		c, _ := strconv.Atoi(inputs[1])

		p--
		c--

		t[p] = append(t[p], c)
		t[c] = append(t[c], p)
	}

	for i := 0; i < q; i++ {
		scanner.Scan()
		inputs := strings.Split(scanner.Text(), " ")

		p, _ := strconv.Atoi(inputs[0])
		x, _ := strconv.Atoi(inputs[1])

		p--

		a[p] += x
	}

	dfs(0, -1)

	buffer := bufio.NewWriter(os.Stdout)

	for _, v := range a {
      buffer.WriteString(strconv.Itoa(v))
		buffer.WriteString("\n")
	}

	buffer.Flush()
}


package main

import (
        "bufio"
        "os"
        "strconv"
)

func main() {
        scanner := bufio.NewScanner(os.Stdin)
        scanner.Split(bufio.ScanWords)

        scanner.Scan()
        N, _ := strconv.Atoi(scanner.Text())
        scanner.Scan()
        Q, _ := strconv.Atoi(scanner.Text())

        edges := make([][]int, N+1)
        for i := 0; i < len(edges); i++ {
                edges[i] = make([]int, 0)
        }
        for i := 1; i <= N-1; i++ {
                scanner.Scan()
                a, _ := strconv.Atoi(scanner.Text())
                scanner.Scan()
                b, _ := strconv.Atoi(scanner.Text())
                edges[a] = append(edges[a], b)
        }

        counts := make([]int, N+1)
        for j := 1; j <= Q; j++ {
                scanner.Scan()
                p, _ := strconv.Atoi(scanner.Text())
                scanner.Scan()
                x, _ := strconv.Atoi(scanner.Text())
                counts[p] += x
        }

        for i := 1; i <= N; i++ {
                if counts[i] == 0 {
                        continue
                }
                edges := edges[i]
                for k := 0; k < len(edges); k++ {
                        counts[edges[k]] += counts[i]
                }
        }

        w := bufio.NewWriter(os.Stdout)
        for i := 1; i <= N-1; i++ {
                w.WriteString(strconv.Itoa(counts[i]) + " ")
        }
        w.WriteString(strconv.Itoa(counts[N]) + "\n")
        w.Flush()
}


package main

import (
	"fmt"
)

var m = map[int][]int{}
var tree = map[int]int{}

func recursive(p int, x int) {
	tree[p] += x
	for i := 0; i < len(m[p]); i++ {
		recursive(m[p][i], x)
	}
	return
}

func main() {
	var n, q int
	fmt.Scan(&n)
	fmt.Scan(&q)
	a := make([]int, n-1)
	b := make([]int, n-1)
	// m := map[int]string{}
	m = map[int][]int{}
	tree = map[int]int{}
	for i := 0; i < n-1; i++ {
		fmt.Scan(&a[i])
		fmt.Scan(&b[i])
		m[a[i]] = append(m[a[i]], b[i])
		tree[a[i]] = 0
	}
	for i := 0; i < q; i++ {
		var p, x int
		fmt.Scan(&p)
		fmt.Scan(&x)
		recursive(p, x)
	}
	for i := 1; i < n; i++ {
		fmt.Printf("%d ", tree[i])
	}
	fmt.Println(tree[n])
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var n, q int
var ps [][]int
var xm []int
var pt []int
var ptd []bool

func main() {

	fmt.Scan(&n, &q)
	ps = make([][]int, n)

	var sc = bufio.NewScanner(os.Stdin)

	for i := 0; i < n-1; i++ {
		sc.Scan()
		s := strings.Split(sc.Text(), " ")
		a, _ := strconv.Atoi(s[0])
		b, _ := strconv.Atoi(s[1])
		a--
		b--
		ps[a] = append(ps[a], b)
		ps[b] = append(ps[b], a)
	}

	xm = make([]int, n)
	for i := 0; i < q; i++ {
		sc.Scan()
		s := strings.Split(sc.Text(), " ")
		p, _ := strconv.Atoi(s[0])
		x, _ := strconv.Atoi(s[1])
		p--
		xm[p] += x
	}

	pt = make([]int, n)
	ptd = make([]bool, n)
	next(0, 0)

	for i := range pt {
		if i == n-1 {
			fmt.Println(pt[i])
		} else {
			fmt.Printf("%d ", pt[i])
		}
	}
}

func next(p, cp int) {
	cp += xm[p]
	pt[p] = cp
	ptd[p] = true
	for _, v := range ps[p] {
		if ptd[v] {
			continue
		}
		ptd[v] = true
		next(v, cp)
	}
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var n, q int
var ps [][]int
var xm []int
var par []int
var pt []int
var ptd []bool
var pls []int

func main() {

	fmt.Scan(&n, &q)
	ps = make([][]int, n)

	var sc = bufio.NewScanner(os.Stdin)

	for i := 0; i < n-1; i++ {
		sc.Scan()
		s := strings.Split(sc.Text(), " ")
		a, _ := strconv.Atoi(s[0])
		b, _ := strconv.Atoi(s[1])
		a--
		b--
		ps[a] = append(ps[a], b)
		ps[b] = append(ps[b], a)
	}

	xm = make([]int, n)
	for i := 0; i < q; i++ {
		sc.Scan()
		s := strings.Split(sc.Text(), " ")
		p, _ := strconv.Atoi(s[0])
		x, _ := strconv.Atoi(s[1])
		p--
		xm[p] += x
	}

	par = make([]int, n)
	for i := range par {
		par[i] = -2
	}
	par[0] = -1
	next(0)

	pt = make([]int, n)
	ptd = make([]bool, n)
	for i := n - 1; i >= 0; i-- {
		if ptd[i] {
			continue
		}
		pls = make([]int, 0)
		point(i)
	}

	for i := range pt {
		if i == n-1 {
			fmt.Println(pt[i])
		} else {
			fmt.Printf("%d ", pt[i])
		}
	}
}

func point(p int) {
	pls = append(pls, p)
	if xm[p] > 0 {
		for _, v := range pls {
			pt[v] += xm[p]
		}
	}
	prt := par[p]
	if prt == -1 {
		for _, v := range pls {
			ptd[v] = true
		}
		return
	}
	if ptd[prt] {
		for _, v := range pls {
			pt[v] += pt[prt]
			ptd[v] = true
		}
		return
	}
	point(prt)
}

func next(p int) {
	for _, v := range ps[p] {
		if par[v] != -2 {
			continue
		}
		par[v] = p
		next(v)
	}
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	sc := bufio.NewScanner(os.Stdin)

	sc.Scan()
	elems := strings.Split(sc.Text(), " ")
	N, _ := strconv.Atoi(elems[0])
	Q, _ := strconv.Atoi(elems[1])

	tree := make([][]int, N)
	for i := 0; i < N; i++ {
		tree[i] = []int{}
	}
	sousa := make([]int, N)

	for i := 0; i < N-1; i++ {
		sc.Scan()
		text := sc.Text()
		elems := strings.Split(text, " ")
		a, _ := strconv.Atoi(elems[0])
		b, _ := strconv.Atoi(elems[1])
		a--
		b--
		tree[a] = append(tree[a], b)
		tree[b] = append(tree[b], a)
	}

	for i := 0; i < Q; i++ {
		sc.Scan()
		text := sc.Text()
		elems := strings.Split(text, " ")
		p, _ := strconv.Atoi(elems[0])
		x, _ := strconv.Atoi(elems[1])
		p--
		sousa[p] += x
	}

	counter := make([]int, N)

	rec(0, -1, 0, counter, sousa, tree)

	fmt.Print(counter[0])
	for i := 1; i < N; i++ {
		fmt.Printf(" %d", counter[i])
	}
	fmt.Println("")
}

func rec(pos, parent, count int, counter, sousa []int, tree [][]int) {
	counter[pos] += sousa[pos] + count
	children := tree[pos]
	for _, child := range children {
		if child == parent {
			continue
		}
		rec(child, pos, sousa[pos]+count, counter, sousa, tree)
	}
}


package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scan(&n)
	var q int
	fmt.Scan(&q)
	g := make([][]int, n)
	for i := 0; i < n; i++ {
		g[i] = make([]int, 0)
	}

	for i := 0; i+1 < n; i++ {
		var a, b int
		fmt.Scan(&a, &b)
		a--
		b--
		g[a] = append(g[a], b)
		g[b] = append(g[b], a)
	}

	value := make([]int, n)
	for i := 0; i < q; i++ {
		var p, x int
		fmt.Scan(&p, &x)
		p--
		value[p] += x
	}

	used := make([]bool, n)
	queue := make(chan int, n+10)

	queue <- 0
	used[0] = true

	for i := 0; i < n; i++ {
		cur := <-queue
		for _, u := range g[cur] {
			if used[u] {
				continue
			}
			used[u] = true
			value[u] += value[cur]
			queue <- u
		}
	}
	for _, x := range value {
		fmt.Println(x)
	}
}