package main

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

/*
var rdr = bufio.NewReaderSize(os.Stdin, 1000000)
// readLine can read long line string (at least 10^5)
func readLine() string {
	buf := make([]byte, 0, 1000000)
	for {
		l, p, e := rdr.ReadLine()
		if e != nil {
			panic(e)
		}
		buf = append(buf, l...)
		if !p {
			break
		}
	}
	return string(buf)
}
// NextLine reads a line text from stdin, and then returns its string.
func NextLine() string {
	return readLine()
}
*/

var sc = bufio.NewScanner(os.Stdin)

// NextLine reads a line text from stdin, and then returns its string.
func NextLine() string {
	sc.Scan()
	return sc.Text()
}

// NextIntsLine reads a line text, that consists of **ONLY INTEGERS DELIMITED BY SPACES**, from stdin.
// And then returns intergers slice.
func NextIntsLine() []int {
	ints := []int{}
	intsStr := NextLine()
	tmp := strings.Split(intsStr, " ")
	for _, s := range tmp {
		integer, _ := strconv.Atoi(s)
		ints = append(ints, integer)
	}
	return ints
}

// NextStringsLine reads a line text, that consists of **STRINGS DELIMITED BY SPACES**, from stdin.
// And then returns strings slice.
func NextStringsLine() []string {
	str := NextLine()
	return strings.Split(str, " ")
}

// NextRunesLine reads a line text, that consists of **ONLY CHARACTERS ARRANGED CONTINUOUSLY**, from stdin.
// Ant then returns runes slice.
func NextRunesLine() []rune {
	return []rune(NextLine())
}

// Max returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Max(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

// Min returns the min integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Min(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

// PowInt is integer version of math.Pow
func PowInt(a, e int) int {
	if a < 0 || e < 0 {
		panic(errors.New("[argument error]: PowInt does not accept negative integers"))
	}
	fa := float64(a)
	fe := float64(e)
	fanswer := math.Pow(fa, fe)
	return int(fanswer)
}

// AbsInt is integer version of math.Abs
func AbsInt(a int) int {
	fa := float64(a)
	fanswer := math.Abs(fa)
	return int(fanswer)
}

// DeleteElement returns a *NEW* slice, that have the same and minimum length and capacity.
// DeleteElement makes a new slice by using easy slice literal.
func DeleteElement(s []int, i int) []int {
	if i < 0 || len(s) <= i {
		panic(errors.New("[index error]"))
	}
	// appendのみの実装
	n := make([]int, 0, len(s)-1)
	n = append(n, s[:i]...)
	n = append(n, s[i+1:]...)
	return n
}

// Concat returns a *NEW* slice, that have the same and minimum length and capacity.
func Concat(s, t []rune) []rune {
	n := make([]rune, 0, len(s)+len(t))
	n = append(n, s...)
	n = append(n, t...)
	return n
}

// UpperRune is rune version of `strings.ToUpper()`.
func UpperRune(r rune) rune {
	str := strings.ToUpper(string(r))
	return []rune(str)[0]
}

// LowerRune is rune version of `strings.ToLower()`.
func LowerRune(r rune) rune {
	str := strings.ToLower(string(r))
	return []rune(str)[0]
}

// ToggleRune returns a upper case if an input is a lower case, v.v.
func ToggleRune(r rune) rune {
	var str string
	if 'a' <= r && r <= 'z' {
		str = strings.ToUpper(string(r))
	} else if 'A' <= r && r <= 'Z' {
		str = strings.ToLower(string(r))
	} else {
		str = string(r)
	}
	return []rune(str)[0]
}

// ToggleString iteratively calls ToggleRune, and returns the toggled string.
func ToggleString(s string) string {
	inputRunes := []rune(s)
	outputRunes := make([]rune, 0, len(inputRunes))
	for _, r := range inputRunes {
		outputRunes = append(outputRunes, ToggleRune(r))
	}
	return string(outputRunes)
}

// Strtoi is a wrapper of `strconv.Atoi()`.
// If `strconv.Atoi()` returns an error, Strtoi calls panic.
func Strtoi(s string) int {
	if i, err := strconv.Atoi(s); err != nil {
		panic(errors.New("[argument error]: Strtoi only accepts integer string"))
	} else {
		return i
	}
}

// LowerBound returns an index of a slice whose value is EQUAL TO AND LARGER THAN A KEY VALUE.
func LowerBound(s []int, key int) int {
	isLarger := func(index, key int) bool {
		if s[index] >= key {
			return true
		} else {
			return false
		}
	}

	left, right := -1, len(s)

	for right-left > 1 {
		mid := left + (right-left)/2
		if isLarger(mid, key) {
			right = mid
		} else {
			left = mid
		}
	}

	return right
}

// UpperBound returns an index of a slice whose value is EQUAL TO AND SMALLER THAN A KEY VALUE.
func UpperBound(s []int, key int) int {
	isSmaller := func(index, key int) bool {
		if s[index] <= key {
			return true
		} else {
			return false
		}
	}

	left, right := -1, len(s)

	for right-left > 1 {
		mid := left + (right-left)/2
		if isSmaller(mid, key) {
			left = mid
		} else {
			right = mid
		}
	}

	return left
}

// sort package (snippets)
//sort.Sort(sort.IntSlice(s))
//sort.Sort(sort.Reverse(sort.IntSlice(s)))
//sort.Sort(sort.Float64Slice(s))
//sort.Sort(sort.StringSlice(s))

// copy function
//a = []int{0, 1, 2}
//b = make([]int, len(a))
//copy(b, a)

/*******************************************************************/

var a, b, x int

func main() {
	tmp := NextIntsLine()
	a, b, x = tmp[0], tmp[1], tmp[2]

	if a+b >= x && a <= x {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}


package main

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

func main() {
	n := readInt()
	vec := readIntLine()

	// copy
	cpVec := make([]int, len(vec))
	copy(cpVec, vec)
	sort.Ints(cpVec)

	left := cpVec[n/2-1]
	right := cpVec[n/2]

	for _, v := range vec {
		if v <= left {
			fmt.Println(right)
		} else if v >= right {
			fmt.Println(left)
		} else {
			fmt.Println("ERR")
		}
	}

	// fmt.Println(n)
	// fmt.Println(vec)
	// fmt.Println(cpVec)
}

func readInt() int {
	var a int
	fmt.Scan(&a)
	return a
}

func readIntLine() []int {
	var sc = bufio.NewScanner(os.Stdin)
	sc.Scan()
	line := sc.Text()
	vals := strings.Split(line, " ")
	vec := make([]int, 0)
	for _, v := range vals {
		// n, err := strconv.ParseInt(v, 10, 64)
		n, err := strconv.Atoi(v)
		if err != nil {
			panic(err)
		}
		vec = append(vec, n)
	}
	return vec
}

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

Score : 300 points

Problem Statement

When l is an odd number, the median of l numbers a_1, a_2, ..., a_l is the (\frac{l+1}{2})-th largest value among a_1, a_2, ..., a_l.

You are given N numbers X_1, X_2, ..., X_N, where N is an even number.
For each i = 1, 2, ..., N, let the median of X_1, X_2, ..., X_N excluding X_i, that is, the median of X_1, X_2, ..., X_{i-1}, X_{i+1}, ..., X_N be B_i.

Find B_i for each i = 1, 2, ..., N.

Constraints

2 \leq N \leq 200000

N is even.

1 \leq X_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 X_2 ... X_N

Output

Print N lines.
The i-th line should contain B_i.

Sample Input 1

4
2 4 4 3

Sample Output 1

4
3
3
4

Since the median of X_2, X_3, X_4 is 4, B_1 = 4.

Since the median of X_1, X_3, X_4 is 3, B_2 = 3.

Since the median of X_1, X_2, X_4 is 3, B_3 = 3.

Since the median of X_1, X_2, X_3 is 4, B_4 = 4.

Sample Input 2

2
1 2

Sample Output 2

2
1

Sample Input 3

6
5 5 4 4 3 3

Sample Output 3

4
4
4
4
4
4

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.


// 最大値がnで中央値に一番近いやつがmっぽい lower_boundとupper_boundで見つける
package main

import (
	"fmt"
	"sort"
)

func main() {
	var N int
	fmt.Scan(&N)
	A := make([]int, N)
	for i := 0; i < N; i++ {
		fmt.Scan(&A[i])
	}
	sort.Ints(A)
	if N == 2 {
		fmt.Println(A[1], A[0])
	}
	P := A[N-1]
	Q1 := A[sort.Search(N, func(j int) bool {
		return P/2 <= A[j]
	})]
	sort.Sort(sort.Reverse(sort.IntSlice(A)))
	Q2 := A[sort.Search(N, func(j int) bool {
		return P/2 >= A[j]
	})]

	if float64(P)/2.0-float64(Q1) < float64(P)/2.0-float64(Q2) {
		fmt.Println(P, Q1)
	} else {
		fmt.Println(P, Q2)
	}
}

Score : 400 points

Problem Statement

Let {\rm comb}(n,r) be the number of ways to choose r objects from among n objects, disregarding order.
From n non-negative integers a_1, a_2, ..., a_n, select two numbers a_i > a_j so that {\rm comb}(a_i,a_j) is maximized.
If there are multiple pairs that maximize the value, any of them is accepted.

Constraints

2 \leq n \leq 10^5

0 \leq a_i \leq 10^9

a_1,a_2,...,a_n are pairwise distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_n

Output

Print a_i and a_j that you selected, with a space in between.

Sample Input 1

5
6 9 4 2 11

Sample Output 1

11 6

\rm{comb}(a_i,a_j) for each possible selection is as follows:

\rm{comb}(4,2)=6

\rm{comb}(6,2)=15

\rm{comb}(6,4)=15

\rm{comb}(9,2)=36

\rm{comb}(9,4)=126

\rm{comb}(9,6)=84

\rm{comb}(11,2)=55

\rm{comb}(11,4)=330

\rm{comb}(11,6)=462

\rm{comb}(11,9)=55

Thus, we should print 11 and 6.

Sample Input 2

2
100 0

Sample Output 2

100 0


package main

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

func main() {
	r := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscan(r, &n)
	as := make([]int, n)
	mx := -1
	mxIndex := -1
	for i := 0; i < n; i++ {
		fmt.Fscan(r, &as[i])

		if mx < as[i] {
			mx = as[i]
			mxIndex = i
		}
	}

	half := mx / 2
	half2 := mx/2 + 1

	t := 0
	for i := 0; i < n; i++ {
		if i == mxIndex {
			continue
		}
		if abs(half-t) > abs(half-as[i]) {
			t = as[i]
		}
		if abs(half2-t) > abs(half2-as[i]) {
			t = as[i]
		}
	}

	fmt.Printf("%d %d", mx, t)
}

func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

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

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


package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	var n int
	scanner.Scan()
	fmt.Sscanf(scanner.Text(), "%d", &n)

	as := make([]int, n)
	for i := 0; i < n; i++ {
		scanner.Scan()
		fmt.Sscanf(scanner.Text(), "%d", &as[i])
	}
	sort.Sort(sort.IntSlice(as))
	m := as[len(as)-1]
	as = as[0 : len(as)-1]
	index := sort.SearchInts(as, m/2)

	if index == len(as) {
		fmt.Println(m, as[index-1])
		return
	}
	if index == 0 {
		fmt.Println(m, as[index])
		return
	}
	if combination(m, as[index]) > combination(m, as[index-1]) {
		fmt.Println(m, as[index])
	} else {
		fmt.Println(m, as[index-1])
	}
}

func max(ns ...int) int {
	ret := math.MinInt64
	for _, n := range ns {
		if n > ret {
			ret = n
		}
	}
	return ret
}

func combination(a, b int) int {
	if a-b < b {
		return combination(a, a-b)
	}
	prod := 1
	for i := 0; i < b; i++ {
		prod = prod * (a - i) //% MOD
	}
	f := factorial(b)
	//return prod * inverse(f) % MOD
	return prod / f
}

func power(a, pow int) int {
	if pow == 0 {
		return 1
	} else if pow == 1 {
		return a
	} else if pow%2 == 0 {
		rt := power(a, pow/2)
		return rt * rt //% MOD
	} else {
		return a * power(a, pow-1) //% MOD
	}
}

func factorial(n int) int {
	ret := 1
	for n >= 1 {
		ret = ret * n
		n--
	}
	return ret
}


package main

import (
	"fmt"
	"strings"
)

func main() {
	var S string
	fmt.Scan(&S)
	for _, v := range []string{"a", "b", "c"} {
		if !strings.Contains(S, v) {
			fmt.Println("No")
			return
		}
	}
	fmt.Println("Yes")
}

Score : 100 points

Problem Statement

You are given a string S of length 3 consisting of a, b and c. Determine if S can be obtained by permuting abc.

Constraints

|S|=3

S consists of a, b and c.

Input

Input is given from Standard Input in the following format:

S

Output

If S can be obtained by permuting abc, print Yes; otherwise, print No.

Sample Input 1

bac

Sample Output 1

Yes

Swapping the first and second characters in bac results in abc.

Sample Input 2

bab

Sample Output 2

No

Sample Input 3

abc

Sample Output 3

Yes

Sample Input 4

aaa

Sample Output 4

No


package main

import (
	"fmt"
)

func main() {
	var a, b, k int
	fmt.Scan(&a, &b, &k)

	max := a
	for i := a; i < a+k; i++ {
		if i <= b {
			fmt.Println(i)
			max = i
		}
	}

	for i := max; i <= b; i++ {
		if i >= b-k+1 {
			fmt.Println(i)
		}
	}

}

Score : 200 points

Problem Statement

Print all the integers that satisfies the following in ascending order:

Among the integers between A and B (inclusive), it is either within the K smallest integers or within the K largest integers.

Constraints

1 \leq A \leq B \leq 10^9

1 \leq K \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B K

Output

Print all the integers that satisfies the condition above in ascending order.

Sample Input 1

3 8 2

Sample Output 1

3
4
7
8

3 is the first smallest integer among the integers between 3 and 8.

4 is the second smallest integer among the integers between 3 and 8.

7 is the second largest integer among the integers between 3 and 8.

8 is the first largest integer among the integers between 3 and 8.

Sample Input 2

4 8 3

Sample Output 2

4
5
6
7
8

Sample Input 3

2 9 100

Sample Output 3

2
3
4
5
6
7
8
9


package main

import "fmt"

func main() {
	var A, B, K int
	fmt.Scan(&A, &B, &K)
	po := false

	for i := 0; i < K; i++ {
		fmt.Println(A + i)
		if A+i == B {
			po = true
			break
		}
	}

	if po {
		return
	}
	for i := 0; i < K; i++ {
		fmt.Println(B - K + i)
	}
}


package main

import "fmt"

func getInput() (int, int, int) {
	a, b, c := 0, 0, 0
	fmt.Scan(&a, &b, &c)
	return a, b, c
}

func sort(c []int) []int {
	if c[0] > c[1] {
		c[0], c[1] = c[1], c[0]
	}
	if c[1] > c[2] {
		c[1], c[2] = c[2], c[1]
	}
	if c[0] > c[1] {
		c[0], c[1] = c[1], c[0]
	}
	return c
}

func C() {
	c := []int{0, 0, 0}
	c[0], c[1], c[2] = getInput()
	c = sort(c)

	diff1 := c[2] - c[1]
	diff2 := c[1] - c[0]

	if diff1%2 == 0 && diff2%2 == 0 {
		count := (diff1*2 + diff2) / 2
		fmt.Println(count)
		return
	}

	if diff1%2 == 1 && diff2%2 == 0 {
		count := diff1 + diff2/2
		fmt.Println(count)
		return
	}

	if diff1%2 == 0 && diff2%2 == 1 {
		count := diff1/2 + (c[2]-c[0]+1)/2 + 1
		fmt.Println(count)
		return
	}

	if diff1%2 == 1 && diff2%2 == 1 {
		count := (diff1+1)/2 + (diff1+diff2)/2 + 1
		fmt.Println(count)
		return
	}
}

func main() {
  C()
}

Score : 300 points

Problem Statement

You are given three integers A, B and C. Find the minimum number of operations required to make A, B and C all equal by repeatedly performing the following two kinds of operations in any order:

Choose two among A, B and C, then increase both by 1.

Choose one among A, B and C, then increase it by 2.

It can be proved that we can always make A, B and C all equal by repeatedly performing these operations.

Constraints

0 \leq A,B,C \leq 50

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the minimum number of operations required to make A, B and C all equal.

Sample Input 1

2 5 4

Sample Output 1

2

We can make A, B and C all equal by the following operations:

Increase A and C by 1. Now, A, B, C are 3, 5, 5, respectively.

Increase A by 2. Now, A, B, C are 5, 5, 5, respectively.

Sample Input 2

2 6 3

Sample Output 2

5

Sample Input 3

31 41 5

Sample Output 3

23


package main

import "fmt"

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

	if s == "zyxwvutsrqponmlkjihgfedcba" {
		fmt.Println("-1")
		return
	}

	if len(s) < 26 {
		alp := make([]int, 'z'-'a'+1)
		for _, ss := range s {
			alp[ss-'a']++
		}
		for i, v := range alp {
			if v == 0 {
				fmt.Println(s + string('a'+i))
				return
			}
		}
	}

	var sl, sr string
	for i := len(s) - 1; i >= 1; i-- {
		if s[i-1] > s[i] {
			sl = s[:i]
			sr = s[i+1:]
			break
		}
	}
	smallest := 'z'
	for _, v := range sr {
		if v < smallest {
			smallest = v
		}
	}
	fmt.Println(sl + string(smallest))
}

Score : 300 points

Problem Statement

Gotou just received a dictionary. However, he doesn't recognize the language used in the dictionary. He did some analysis on the dictionary and realizes that the dictionary contains all possible diverse words in lexicographical order.

A word is called diverse if and only if it is a nonempty string of English lowercase letters and all letters in the word are distinct. For example, atcoder, zscoder and agc are diverse words while gotou and connect aren't diverse words.

Given a diverse word S, determine the next word that appears after S in the dictionary, i.e. the lexicographically smallest diverse word that is lexicographically larger than S, or determine that it doesn't exist.

Let X = x_{1}x_{2}...x_{n} and Y = y_{1}y_{2}...y_{m} be two distinct strings. X is lexicographically larger than Y if and only if Y is a prefix of X or x_{j} > y_{j} where j is the smallest integer such that x_{j} \neq y_{j}.

Constraints

1 \leq |S| \leq 26

S is a diverse word.

Input

Input is given from Standard Input in the following format:

S

Output

Print the next word that appears after S in the dictionary, or -1 if it doesn't exist.

Sample Input 1

atcoder

Sample Output 1

atcoderb

atcoderb is the lexicographically smallest diverse word that is lexicographically larger than atcoder. Note that atcoderb is lexicographically smaller than b.

Sample Input 2

abc

Sample Output 2

abcd

Sample Input 3

zyxwvutsrqponmlkjihgfedcba

Sample Output 3

-1

This is the lexicographically largest diverse word, so the answer is -1.

Sample Input 4

abcdefghijklmnopqrstuvwzyx

Sample Output 4

abcdefghijklmnopqrstuvx


package main

import (
    "fmt"
    // "sort"
)

func main() {
    // var n int
    // fmt.Scan(&n, &x)
    // nums := make([]int,n);
    // m := make(map[int]int)

    var s string
    fmt.Scan(&s)
    a := make([]int ,26)

    for i := 0; i < len(s); i++ {
    	a[s[i]-'a']=i+1
    }
    b := "abcdefghijklmnopqrstuvwxyz"

    for i := 0; i < len(a); i++ {
    	if a[i]==0 {
			fmt.Println(s+b[i:i+1])
			return
    	}
	}

    for i := 0; i < len(s); i++ {
    	a[i]=0
    }
	a[s[25]-'a'] = 1
    for i := 24; 0 <= i; i-- {
    	if s[i]<s[i+1] {
    		for t := int(s[i]-'a'); t < len(s); t++ {
    			if  a[t]>0 {
					fmt.Println(s[0:i]+b[t:t+1])
					return
    			}
    		}
    	} else {
    		a[s[i]-'a'] = 1
    	}
	}

	fmt.Println(-1)
}


package main

import (
	"fmt"
	"strings"
)

var dic = []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}

func main() {
	var S string
	fmt.Scan(&S)
	sar := strings.Split(S, "")

	if len(sar) == 26 {
		for i := len(sar) - 1; i >= 0; i-- {
			lw := sar[i]
			di := indexpath(dic, lw)
			nx := di - 1
			if nx < 0 {
				continue
			}
			si := indexpath(sar, dic[nx])

			if si > i {
				continue
			}
			var restr string
			for j := 0; j < si; j++ {
				restr += sar[j]
			}
			fmt.Println(restr + lw)

			return
		}
		fmt.Println(-1)
	} else {
		res := removes(dic, sar)
		s := S + res[0]
		fmt.Print(s)
	}

}
func index(slice []string, item []string) int {
	n := -1
	for i := 0; i < len(slice); i++ {
		for k := 0; k < len(item); k++ {
			if slice[i] == item[k] {
				if i > n {
					n = i
				}
			}
		}
	}
	return n
}

func indexpath(slice []string, item string) int {
	for i := 0; i < len(slice); i++ {
		if slice[i] == item {
			return i
		}

	}
	return -1
}

func removes(ss []string, search []string) []string {
	result := []string{}
	var res bool
	for i := 0; i < len(ss); i++ {
		res = true
		for k := 0; k < len(search); k++ {
			if ss[i] == search[k] {
				res = false
			}
		}
		if res {
			result = append(result, ss[i])
		}

	}
	return result
}


package main

import (
	"fmt"
	"math"
)

func main() {
	var a, b, c, d float64
	fmt.Scan(&a, &b, &c, &d)

	fmt.Println(math.Min(a, b) + math.Min(c, d))
}

Score : 100 points

Problem Statement

You planned a trip using trains and buses.
The train fare will be A yen (the currency of Japan) if you buy ordinary tickets along the way, and B yen if you buy an unlimited ticket.
Similarly, the bus fare will be C yen if you buy ordinary tickets along the way, and D yen if you buy an unlimited ticket.

Find the minimum total fare when the optimal choices are made for trains and buses.

Constraints

1 \leq A \leq 1 000

1 \leq B \leq 1 000

1 \leq C \leq 1 000

1 \leq D \leq 1 000

All input values are integers.

Input

Input is given from Standard Input in the following format:

A
B
C
D

Output

Print the minimum total fare.

Sample Input 1

600
300
220
420

Sample Output 1

520

The train fare will be 600 yen if you buy ordinary tickets, and 300 yen if you buy an unlimited ticket.
Thus, the optimal choice for trains is to buy an unlimited ticket for 300 yen.
On the other hand, the optimal choice for buses is to buy ordinary tickets for 220 yen.

Therefore, the minimum total fare is 300 + 220 = 520 yen.

Sample Input 2

555
555
400
200

Sample Output 2

755

Sample Input 3

549
817
715
603

Sample Output 3

1152


package main

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

var sc = bufio.NewScanner(os.Stdin)

func main() {
	N := inputLineAsNumArray(1)[0]
	spots := inputLineAsNumArray(N)

    spots = append([]int{0}, spots...)
    spots = append(spots, 0)
    var dirs []bool
    base := int(math.Abs(float64(spots[0])))
	for i:=0; i<N+1; i++ {
        if spots[i] < spots[i+1] {
            dirs = append(dirs, true)
        } else if spots[i] > spots[i+1] {
            dirs = append(dirs, false)
        } else {
            dirs = append(dirs, dirs[i-1])
        }
        base += int(math.Abs(float64(spots[i]-spots[i+1])))
	}

	for i:=1; i<N+1; i++ {
	    diff := 0
        if dirs[i] != dirs[i-1] {
            diff = int(math.Abs(float64(spots[i]-spots[i-1]))) + int(math.Abs(float64(spots[i]-spots[i+1]))) - int(math.Abs(float64(spots[i+1]-spots[i-1])))
        }
        fmt.Println(base-diff)
	}

}

func inputLineAsNumArray(length int) []int {
	line := strings.Split(readLine(), " ")
	var nums []int
	for i := 0; i < length; i++ {
		num, _ := strconv.Atoi(line[i])
		nums = append(nums, num)
	}
	return nums
}

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

Score : 300 points

Problem Statement

There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N.
Spot i is at the point with coordinate A_i.
It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.

You planned a trip along the axis.
In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0.

However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i.
You will visit the remaining spots as planned in the order they are numbered.
You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned.

For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled.

Constraints

2 \leq N \leq 10^5

-5000 \leq A_i \leq 5000 (1 \leq i \leq N)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print N lines.
In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled.

Sample Input 1

3
3 5 -1

Sample Output 1

12
8
10

Spot 1, 2 and 3 are at the points with coordinates 3, 5 and -1, respectively.
For each i, the course of the trip and the total cost of travel when the visit to Spot i is canceled, are as follows:

For i = 1, the course of the trip is 0 \rightarrow 5 \rightarrow -1 \rightarrow 0 and the total cost of travel is 5 + 6 + 1 = 12 yen.

For i = 2, the course of the trip is 0 \rightarrow 3 \rightarrow -1 \rightarrow 0 and the total cost of travel is 3 + 4 + 1 = 8 yen.

For i = 3, the course of the trip is 0 \rightarrow 3 \rightarrow 5 \rightarrow 0 and the total cost of travel is 3 + 2 + 5 = 10 yen.

Sample Input 2

5
1 1 1 2 0

Sample Output 2

4
4
4
2
4

Sample Input 3

6
-679 -2409 -3258 3095 -3291 -4462

Sample Output 3

21630
21630
19932
8924
21630
19288


package main

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

type Point struct {
	x  int
	y  int
	in int
}

type Points []Point

func (l Points) Len() int {
	return len(l)
}

func (l Points) Less(i, j int) bool {
	return l[i].in < l[j].in || l[i].x*l[i].y < l[j].x*l[j].y
}

func (l Points) Swap(i, j int) {
	l[i], l[j] = l[j], l[i]
}

func main() {
	s := wordScanner()

	var n int
	scanInts(s, &n)

	reds := make(Points, n)
	for i := range reds {
		scanInts(s, &reds[i].x, &reds[i].y)
	}

	blues := make(Points, n)
	for i := range blues {
		scanInts(s, &blues[i].x, &blues[i].y)
	}

	sort.Sort(reds)

	for i, b := range blues {
		for _, r := range reds {
			if isInner(r, b) {
				blues[i].in++
			}
		}
	}
	sort.Sort(blues)

	c := 0
	for _, r := range reds {
		for j, b := range blues {
			if isInner(r, b) {
				blues = append(blues[:j], blues[j+1:]...)
				c++
				break
			}
		}
	}
	fmt.Println(c)
}

func isInner(inner, outer Point) bool {
	return outer.x > inner.x && outer.y > inner.y
}

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

func scanInts(s *bufio.Scanner, vals ...*int) {
	for i := range vals {
		s.Scan()
		n, _ := strconv.Atoi(s.Text())
		*vals[i] = n
	}
}

Score : 400 points

Problem Statement

On a two-dimensional plane, there are N red points and N blue points.
The coordinates of the i-th red point are (a_i, b_i), and the coordinates of the i-th blue point are (c_i, d_i).

A red point and a blue point can form a friendly pair when, the x-coordinate of the red point is smaller than that of the blue point, and the y-coordinate of the red point is also smaller than that of the blue point.

At most how many friendly pairs can you form? Note that a point cannot belong to multiple pairs.

Constraints

All input values are integers.

1 \leq N \leq 100

0 \leq a_i, b_i, c_i, d_i < 2N

a_1, a_2, ..., a_N, c_1, c_2, ..., c_N are all different.

b_1, b_2, ..., b_N, d_1, d_2, ..., d_N are all different.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
a_2 b_2
:
a_N b_N
c_1 d_1
c_2 d_2
:
c_N d_N

Output

Print the maximum number of friendly pairs.

Sample Input 1

3
2 0
3 1
1 3
4 2
0 4
5 5

Sample Output 1

2

For example, you can pair (2, 0) and (4, 2), then (3, 1) and (5, 5).

Sample Input 2

3
0 0
1 1
5 2
2 3
3 4
4 5

Sample Output 2

2

For example, you can pair (0, 0) and (2, 3), then (1, 1) and (3, 4).

Sample Input 3

2
2 2
3 3
0 0
1 1

Sample Output 3

0

It is possible that no pair can be formed.

Sample Input 4

5
0 0
7 3
2 2
4 8
1 6
8 5
6 9
5 4
9 1
3 7

Sample Output 4

5

Sample Input 5

5
0 0
1 1
5 5
6 6
7 7
2 2
3 3
4 4
8 8
9 9

Sample Output 5

4


package main

import (
	"fmt"
)

func main() {
	c := make([]string, 3)
	for i := range c {
		fmt.Scan(&c[i])
	}

	for i := 0; i < 3; i++ {
		fmt.Print(string(c[i][i]))
	}
}

Score : 100 points

Problem Statement

We have a 3×3 square grid, where each square contains a lowercase English letters.
The letter in the square at the i-th row from the top and j-th column from the left is c_{ij}.

Print the string of length 3 that can be obtained by concatenating the letters in the squares on the diagonal connecting the top-left and bottom-right corner of the grid, from the top-left to bottom-right.

Constraints

Input consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

c_{11}c_{12}c_{13}
c_{21}c_{22}c_{23}
c_{31}c_{32}c_{33}

Output

Print the string of length 3 that can be obtained by concatenating the letters on the diagonal connecting the top-left and bottom-right corner of the grid, from the top-left to bottom-right.

Sample Input 1

ant
obe
rec

Sample Output 1

abc

The letters in the squares on the diagonal connecting the top-left and bottom-right corner of the grid are a, b and c from top-right to bottom-left. Concatenate these letters and print abc.

Sample Input 2

edu
cat
ion

Sample Output 2

ean


package main

import "fmt"

func main() {
	var a, b int
	fmt.Scan(&a, &b)
	sum := 0
	for i := a; i <= b; i++ {
		if i/10000 == i%10 && i/1000%10 == i/10%10 {
			sum++
		}
	}
	fmt.Println(sum)
}

Score : 200 points

Problem Statement

Find the number of palindromic numbers among the integers between A and B (inclusive).
Here, a palindromic number is a positive integer whose string representation in base 10 (without leading zeros) reads the same forward and backward.

Constraints

10000 \leq A \leq B \leq 99999

All input values are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the number of palindromic numbers among the integers between A and B (inclusive).

Sample Input 1

11009 11332

Sample Output 1

4

There are four integers that satisfy the conditions: 11011, 11111, 11211 and 11311.

Sample Input 2

31415 92653

Sample Output 2

612


package main

import "fmt"

func main() {
        var a, b, count int
        fmt.Scan(&a, &b)
        for i := a; i <= b; i++ {
                if palindromic(i) {
                        count++
                }
        }
        fmt.Printf("%d\n", count)
}

func palindromic(input int) bool {
        tmp := input
        digits := []int{}
        for tmp != 0 {
                digits = append(digits, tmp%10)
                tmp /= 10
        }
        for i := 0; i < len(digits)/2; i++ {
                if digits[i] != digits[len(digits)-1-i] {
                        return false
                }
        }
        return true
}


package main

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

const (
	initialBufSize = 10000
	maxBufSize     = 1000000
	mod            = 1e9 + 7
)

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

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

	if N == 2 || M == 2 {
		fmt.Println(0)
		return
	}

	N -= 2
	M -= 2

	if N <= 0 {
		N = 1
	}
	if M <= 0 {
		M = 1
	}

	fmt.Println(N * M)
}

type Graph struct {
	n     int
	edges [][]int
}

func NewGraph(n int) *Graph {
	g := &Graph{
		n:     n,
		edges: make([][]int, n),
	}
	return g
}

func (g *Graph) AddEdge(u, v int) {
	g.edges[v] = append(g.edges[v], u)
	g.edges[u] = append(g.edges[u], v)
}

func dfs(c int, edges [][]int, visited map[int]struct{}) {
	visited[c] = struct{}{}

	for _, v := range edges[c] {
		_, flag := visited[v]
		if flag {
			continue
		}
		dfs(v, edges, visited)
	}
}

func bfs(c int, graph *Graph) {
	next := make([]int, 0)
	next = append(next, c)
	visited := make(map[int]struct{})

	for ; len(next) != 0; {
		u := next[0]
		next = next[1:]
		visited[u] = struct{}{}

		for _, v := range graph.edges[u] {
			_, flag := visited[v]
			if flag {
				continue
			}

			// なにか処理

			next = append(next, v)
		}
	}
}

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

func getIntArray(n int) []int {
	array := make([]int, n)
	for i := 0; i < n; i++ {
		array[i] = getInt()
	}
	return array
}

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

func getStringArray(n int) []string {
	array := make([]string, n)
	for i := 0; i < n; i++ {
		array[i] = getString()
	}
	return array
}

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 powMod(n, p int) int {
	if p == 0 {
		return 1
	} else if p%2 == 0 {
		t := powMod(n, p/2)
		return calcMod(t * t)
	} else {
		return calcMod(n * powMod(n, p-1))
	}
}

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
}

func reverse(s string) string {
	runes := []rune(s)
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	return string(runes)
}

func isPrime(n int) bool {
	if n < 2 {
		return false
	} else if n == 2 {
		return true
	} else if n % 2 == 0 {
		return false
	}

	sqrtN := int(math.Sqrt(float64(n)))
	for i := 3; i <= sqrtN; i += 2 {
		if n % i == 0 {
			return false
		}
	}

	return true
}

func contains(s []int, e int) bool {
	for _, v := range s {
		if e == v {
			return true
		}
	}
	return false
}

func makeRange(min, max int) []int {
	a := make([]int, max-min+1)
	for i := range a {
		a[i] = min + i
	}
	return a
}

func powerset2(nums []int) [][]int {
	length := int(math.Pow(2, float64(len(nums))))
	result := make([][]int, length)

	index := 0
	result[index] = []int{}
	index++

	for _, n := range nums {
		max := index
		for i := 0; i < max; i++ {
			result[index] = copyAndAppend(result[i], n)
			index++
		}
	}

	return result
}

func copyAndAppend(nums []int, n int) []int {
	dst := make([]int, len(nums)+1)
	copy(dst, nums)
	dst[len(nums)] = n
	return dst
}

func calcGcd(x, y int) int {
	if y == 0 {
		return x
	} else if x >= y {
		return calcGcd(y, x % y)
	} else {
		return calcGcd(x, y % x)
	}
}

func getDivisor(n int) []int {
	var divisor []int
	divisor = append(divisor, 1)
	if n != 1 {
		divisor = append(divisor, n)
	}

	sqrt := int(math.Sqrt(float64(n)))
	for i := 2; i <= sqrt; i++ {
		if n % i == 0 {
			divisor = append(divisor, i)
			divisor = append(divisor, n/i)
		}
	}
	return divisor
}

type intHeap []int

func (h intHeap) Len() int {
	return len(h)
}

func (h intHeap) Less(i, j int) bool {
	return h[i] > h[j]
}

func (h intHeap) Swap(i, j int) {
	h[i], h[j] = h[j], h[i]
}

func (h *intHeap) Push(x interface{}) {
	*h = append(*h, x.(int))
}

func (h *intHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func initHeap() *intHeap {
	ih := &intHeap{}
	heap.Init(ih)
	return ih
}

func (h *intHeap) pushHeap(n int) {
	heap.Push(h, n)
}

func (h *intHeap) popHeap() int {
	return heap.Pop(h).(int)
}

func factMod(n int) int {
	value := 1
	for ; n > 1; n-- {
		value = calcMod(value * n)
	}
	return value
}

func combinationMod(n, k int) int {
	factN := factMod(n)
	factK := factMod(k)
	factNK := factMod(n - k)
	factKR := powMod(factK, mod - 2)
	factNKR := powMod(factNK, mod - 2)
	return calcMod(factN * calcMod(factKR * factNKR))
}

Score : 300 points

Problem Statement

There is a grid with infinitely many rows and columns. In this grid, there is a rectangular region with consecutive N rows and M columns, and a card is placed in each square in this region.
The front and back sides of these cards can be distinguished, and initially every card faces up.

We will perform the following operation once for each square contains a card:

For each of the following nine squares, flip the card in it if it exists: the target square itself and the eight squares that shares a corner or a side with the target square.

It can be proved that, whether each card faces up or down after all the operations does not depend on the order the operations are performed.
Find the number of cards that face down after all the operations.

Constraints

1 \leq N,M \leq 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M

Output

Print the number of cards that face down after all the operations.

Sample Input 1

2 2

Sample Output 1

0

We will flip every card in any of the four operations. Thus, after all the operations, all cards face up.

Sample Input 2

1 7

Sample Output 2

5

After all the operations, all cards except at both ends face down.

Sample Input 3

314 1592

Sample Output 3

496080


// Package main provides
//
// File:  c.go
// Author: ymiyamoto
//
// Created on Sun Dec 30 18:56:23 2018
//
package main

import "fmt"

func main() {
	var N, M int
	fmt.Scan(&N, &M)
	if N == 1 || M == 1 {
		fmt.Println(N*M - 2)
	} else if N == 2 {
		fmt.Println(N*M - 2*M)
	} else if M == 2 {
		fmt.Println(N*M - 2*N)
	} else {
		fmt.Println((N - 2) * (M - 2))
	}
}


package main

import "fmt"

func main() {
    var N, M int
    fmt.Scan(&N, &M)
    defer fmt.Println((N-2)*(M-2))

    if N == 1 {
        N++
    }
    if M == 1 {
        M++
    }
}


package main

import "fmt"

var N, K int

func main() {
	fmt.Scanf("%d %d", &N, &K)

	if K == 0 {
		fmt.Println(N * N)
		return
	}

	// (a, b)
	// 0 < a,b <= N
	// K <= a%b < N
	// K < a <= N
	// K < b <= N

	ans := 0
	for c := K; c < N; c++ {
		for b := c + 1; b <= N; b++ {
			ans += (N-c)/b + 1
		}
	}

	fmt.Println(ans)
}

Score : 400 points

Problem Statement

Takahashi had a pair of two positive integers not exceeding N, (a,b), which he has forgotten.
He remembers that the remainder of a divided by b was greater than or equal to K.
Find the number of possible pairs that he may have had.

Constraints

1 \leq N \leq 10^5

0 \leq K \leq N-1

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the number of possible pairs that he may have had.

Sample Input 1

5 2

Sample Output 1

7

There are seven possible pairs: (2,3),(5,3),(2,4),(3,4),(2,5),(3,5) and (4,5).

Sample Input 2

10 0

Sample Output 2

100

Sample Input 3

31415 9265

Sample Output 3

287927211


package main

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

func main() {
	fmt.Println(solve(ReadInt(), ReadInt()))
}

func solve(n, m int) int {
	n, m = MinMax(n, m)

	if n == 1 && m == 1 {
		return 1
	}

	if n == 1 {
		return m - 2
	}

	if n == 2 {
		return 0
	}

	return (n - 2) * (m - 2)
}

func MinMax(slice ...int) (int, int) {
	min, max := slice[0], slice[0]
	for _, v := range slice[1:] {
		if min > v {
			min = v
		} else if max < v {
			max = v
		}
	}
	return min, max
}

var reader = bufio.NewReader(os.Stdin)

func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(reader, a...); err != nil {
		panic(err)
	}
}
func ReadInt() (i int)       { Scan(&i); return }
func ReadString() (s string) { Scan(&s); return }


package main

import "fmt"

func main() {
	var n, m int
	fmt.Scan(&n, &m)

	if n == 1 {
		if m == 1 {
			fmt.Print(1)
			return
		} else {
			fmt.Print(m - 2)
			return
		}
	}

	cal := (n - 2) * (m - 2)
	fmt.Print(cal)
}


package main

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

func configure(scanner *bufio.Scanner) {
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 1000005), 1000005)
}
func getNextString(scanner *bufio.Scanner) string {
	scanned := scanner.Scan()
	if !scanned {
		panic("scan failed")
	}
	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 getNextFloat64(scanner *bufio.Scanner) float64 {
	i, _ := strconv.ParseFloat(getNextString(scanner), 64)
	return i
}
func main() {
	fp := os.Stdin
	wfp := os.Stdout
	extra := 0
	if os.Getenv("I") == "IronMan" {
		fp, _ = os.Open(os.Getenv("END_GAME"))
		extra = 100
	}
	scanner := bufio.NewScanner(fp)
	configure(scanner)
	writer := bufio.NewWriter(wfp)
	defer func() {
		r := recover()
		if r != nil {
			fmt.Fprintln(writer, r)
		}
		writer.Flush()
	}()
	solve(scanner, writer)
	for i := 0; i < extra; i++ {
		fmt.Fprintln(writer, "-----------------------------------")
		solve(scanner, writer)
	}
}
func solve(scanner *bufio.Scanner, writer *bufio.Writer) {
	n := getNextInt(scanner)
	k := getNextInt(scanner)
	s := newSegment(n)
	for i := 1; i < n+1; i++ {
		s.update(0, i, n/i, s.add)
		s.update(1, n%i+1, 1, s.add)
	}
	var ans int64
	for i := k; i < n; i++ {
		ans += int64(s.query(i, 0, s.add))
	}

	fmt.Fprintln(writer, ans)
}

type segment [][]int

func newSegment(n int) segment {
	seg := make(segment, 0)
	for n > 1 {
		seg = append(seg, make([]int, n))
		n = (n + 1) >> 1
	}
	seg = append(seg, make([]int, 1))
	return seg
}
func (seg segment) update(l, r int, v int, f func(int, int) int) {
	for h := 0; h < len(seg) && l < r; h++ {
		if l&1 == 1 {
			seg[h][l] = f(v, seg[h][l])
			l++
		}
		l >>= 1
		if r&1 == 1 {
			seg[h][r-1] = f(v, seg[h][r-1])
		}
		r >>= 1
	}
}
func (seg segment) query(i int, s int, f func(int, int) int) int {
	for h := 0; h < len(seg); h++ {
		s = f(s, seg[h][i>>uint(h)])
	}
	return s
}
func (seg segment) add(x, y int) int {
	return x + y
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

func intScanner() int {
	n, _ := strconv.Atoi(Scanner())
	return n
}

func floatScanner() float64 {
	n, _ := strconv.ParseFloat(Scanner(), 64)
	return n
}
func stringToInt(s string) int {
	n, _ := strconv.Atoi(s)
	return n
}
func stringSliceScanner(n int) []string {
	a := make([]string, n)
	for i := 0; i < n; i++ {
		a[i] = Scanner()
	}
	return a
}
func intSliceScanner(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = intScanner()
	}
	return a
}
func larger(a, b int) int {
	if a < b {
		return b
	} else {
		return a
	}
}
func smaller(a, b int) int {
	if a > b {
		return b
	} else {
		return a
	}
}
func max(a []int) int {
	x := a[0]
	for i := 0; i < len(a); i++ {
		if x < a[i] {
			x = a[i]
		}
	}
	return x
}
func min(a []int) int {
	x := a[0]
	for i := 0; i < len(a); i++ {
		if x > a[i] {
			x = a[i]
		}
	}
	return x
}
func abs(x int) int {
	if x < 0 {
		x = -x
	}
	return x
}

var mod int = 1000000007

func main() {
	buf := make([]byte, 0)
	sc.Buffer(buf, mod)
	sc.Split(bufio.ScanWords)
	n := intScanner()
	fmt.Println(n / 3)
}

Score : 100 points

Problem Statement

There are N students in a school.

We will divide these students into some groups, and in each group they will discuss some themes.

You think that groups consisting of two or less students cannot have an effective discussion, so you want to have as many groups consisting of three or more students as possible.

Divide the students so that the number of groups consisting of three or more students is maximized.

Constraints

1 \leq N \leq 1000

All input values are integers.

Input

Input is given from Standard Input in the following format:

N

Output

If you can form at most x groups consisting of three or more students, print x.

Sample Input 1

8

Sample Output 1

2

For example, you can form a group of three students and another of five students.

Sample Input 2

2

Sample Output 2

0

Sometimes you cannot form any group consisting of three or more students, regardless of how you divide the students.

Sample Input 3

9

Sample Output 3

3


package main

import (
	"bufio"
	"fmt"
	"os"
	"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
}

// Sort
type Val struct {
	id, num int
}
type ByNum []Val

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

func main() {
	sc := NewScanner()
	wtr := bufio.NewWriter(os.Stdout)
	N := sc.nextInt()

	fmt.Fprintln(wtr, N/3)
	wtr.Flush()
}


package main

import (
	"fmt"
)

var N int
var S []string

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

	S = make([]string, N)
	for i := 0; i < N; i++ {
		fmt.Scanf("%s", &S[i])
	}

	m := make(map[string]bool)
	for i := 0; i < len(S); i++ {
		m[S[i]] = true
	}

	ans := 0
	for _, v := range m {
		if v {
			ans++
		}
	}

	if ans == 4 {
		fmt.Println("Four")
	} else if ans == 3 {
		fmt.Println("Three")
	}
}

Score : 200 points

Problem Statement

In Japan, people make offerings called hina arare, colorful crackers, on March 3.

We have a bag that contains N hina arare. (From here, we call them arare.)

It is known that the bag either contains arare in three colors: pink, white and green, or contains arare in four colors: pink, white, green and yellow.

We have taken out the arare in the bag one by one, and the color of the i-th arare was S_i, where colors are represented as follows - pink: P, white: W, green: G, yellow: Y.

If the number of colors of the arare in the bag was three, print Three; if the number of colors was four, print Four.

Constraints

1 \leq N \leq 100

S_i is P, W, G or Y.

There always exist i, j and k such that S_i=P, S_j=W and S_k=G.

Input

Input is given from Standard Input in the following format:

N
S_1 S_2 ... S_N

Output

If the number of colors of the arare in the bag was three, print Three; if the number of colors was four, print Four.

Sample Input 1

6
G W Y P Y W

Sample Output 1

Four

The bag contained arare in four colors, so you should print Four.

Sample Input 2

9
G W W G P W P G G

Sample Output 2

Three

The bag contained arare in three colors, so you should print Three.

Sample Input 3

8
P Y W G Y W Y Y

Sample Output 3

Four


package main

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

var sc = bufio.NewScanner(os.Stdin)

func next() 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 main() {
	sc.Split(bufio.ScanWords)

	N := nextInt()

	m := map[rune]int{'M': 0, 'A': 1, 'R': 2, 'C': 3, 'H': 4}
	v := make([]int, N)
	for i := 0; i < N; i++ {
		s := next()
		v[m[rune(s[0])]]++
	}

	sum := 0
	for i := 0; i < 3; i++ {
		for j := i+1; j < 4; j++ {
			for k := j+1; k < 5; k++ {
				sum += v[i] * v[j] * v[k]
			}
		}
	}

	fmt.Println(sum)
}

Score : 300 points

Problem Statement

There are N people. The name of the i-th person is S_i.

We would like to choose three people so that the following conditions are met:

The name of every chosen person begins with M, A, R, C or H.

There are no multiple people whose names begin with the same letter.

How many such ways are there to choose three people, disregarding order?

Note that the answer may not fit into a 32-bit integer type.

Constraints

1 \leq N \leq 10^5

S_i consists of uppercase English letters.

1 \leq |S_i| \leq 10

S_i \neq S_j (i \neq j)

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

If there are x ways to choose three people so that the given conditions are met, print x.

Sample Input 1

5
MASHIKE
RUMOI
OBIRA
HABORO
HOROKANAI

Sample Output 1

2

We can choose three people with the following names:

MASHIKE, RUMOI, HABORO

MASHIKE, RUMOI, HOROKANAI

Thus, we have two ways.

Sample Input 2

4
ZZ
ZZZ
Z
ZZZZZZZZZZ

Sample Output 2

0

Note that there may be no ways to choose three people so that the given conditions are met.

Sample Input 3

5
CHOKUDAI
RNG
MAKOTO
AOKI
RINGO

Sample Output 3

7


// Package main provides
//
// File:  c.go
// Author: ymiyamoto
//
// Created on Sun Dec 30 22:53:11 2018
//
package main

import "fmt"

func bits(b int) int {
	ret := 0
	for i := byte(0); i < 32; i++ {
		if b&(1<<byte(i)) != 0 {
			ret++
		}
	}
	return ret
}

func main() {
	var N int
	fmt.Scan(&N)

	m := map[byte]int{}
	for i := 0; i < N; i++ {
		var s string
		fmt.Scan(&s)
		m[s[0]]++
	}

	ans := 0
	for i := 0; i < 1<<5; i++ {
		if bits(i) != 3 {
			continue
		}

		t := []byte{'M', 'A', 'R', 'C', 'H'}
		num := 1
		for j := 0; j < 5; j++ {
			if i&(1<<uint8(j)) != 0 {
				num *= m[t[j]]
			}
		}
		ans += num
	}

	fmt.Println(ans)
}


package main

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

func main() {
	sc := NewScanner()
	N := sc.NextInt()
	mp := map[byte]int{}
	for i := 0; i < N; i++ {
		l := sc.NextLine()
		switch l[0] {
		case 'M', 'A', 'R', 'C', 'H':
			mp[l[0]]++
		}
	}
	tup := make([]int, 5)
	i := 0
	for _, v := range mp {
		tup[i] = v
		i++
	}

	ans := 0
	for i := 0; i < 5; i++ {
		for j := i + 1; j < 5; j++ {
			for k := j + 1; k < 5; k++ {
				ans += tup[i] * tup[j] * tup[k]
			}
		}
	}
	fmt.Println(ans)

}

type Scanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewScanner() *Scanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1000)
	return &Scanner{r: rdr}
}
func (s *Scanner) Next() string {
	s.pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	result := string(s.buf[start:s.p])
	s.p++
	return result
}
func (s *Scanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *Scanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}
func (s *Scanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(s.Next(), 10, 64)
	return v
}

func (s *Scanner) NextIntArray() []int {
	s.pre()
	start := s.p
	result := []int{}
	for ; s.p < len(s.buf)+1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 0)
			result = append(result, int(v))
			start = s.p + 1
		}
	}

	return result
}
func (s *Scanner) NextInt64Array() []int64 {
	s.pre()
	start := s.p
	result := []int64{}
	for ; s.p < len(s.buf)+1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 64)
			result = append(result, v)
			start = s.p + 1
		}
	}
	return result
}

func (s *Scanner) NextMap() map[int]bool {
	s.pre()
	start := s.p
	mp := map[int]bool{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			mp[v] = true
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	mp[v] = true

	return mp
}

func (s *Scanner) pre() {
	if s.p >= len(s.buf) {
		s.readLine()
		s.p = 0
	}
}
func (s *Scanner) readLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, e := s.r.ReadLine()
		if e != nil {
			panic(e)
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}


package main

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

var reader = bufio.NewReaderSize(os.Stdin, 1000000)
var writer = bufio.NewWriter(os.Stdout)
func NextLine() string {
  buffer := make([]byte, 0)
  for true {
    line, isPrefix, err := reader.ReadLine()
    if err != nil { panic(err) }
    buffer = append(buffer, line...)
    if !isPrefix { break }
  }
  return string(buffer)
}
func NextInt() int {
  n, _ := strconv.Atoi(NextLine())
  return n
}
func NextFloatVec() []float64 {
  L := strings.Split(NextLine(), " ")
  N := make([]float64, len(L))
  for i := range N {
    N[i], _ = strconv.ParseFloat(L[i], 64)
  }
  return N
}
func Write(s interface{}) {
  fmt.Fprintln(writer, s)
}
func Output() {
  _ = writer.Flush()
}

func Dist(mode int, A ...*[]float64) float64 {
  if len(A) < 1 { return 0.0 }
  if len(A) < 2 { A = append(A, &[]float64{0.0, 0.0}) }
  D := 0.0
  for i := range (*A[0]) {
    x := (*A[0])[i] - (*A[1])[i]
    D += x * x
  }
  if mode == 1 { D = math.Sqrt(D) }
  return D
}
func InnerProduct(A, B *[]float64) float64 {
  IP := 0.0
  for i, a := range (*A) {
    IP += a * (*B)[i]
  }
  return IP
}
func Angle(A ...*[]float64) float64 {
  if len(A) < 2 { return 0.0 }
  if len(A) < 3 {
    a := make([]float64, len((*A[0])))
    A = append(A, &a)
  }
  _A := make([]float64, len((*A[0])))
  _B := make([]float64, len((*A[0])))
  for i := range (*A[0]) {
    _A[i] = (*A[0])[i] - (*A[2])[i]
    _B[i] = (*A[1])[i] - (*A[2])[i]
  }
  acos := math.Acos(InnerProduct(&_A, &_B) / Dist(1, &_A) / Dist(1, &_B))
  theta := acos / math.Pi * 180.0
  _A_ := []float64{-_A[1], _A[0]}
  if InnerProduct(&_A_, &_B) < 0 { theta = 360 - theta }
  return theta
}
func TriangleArea(mode int, A ...*[]float64) float64 {
  if len(A) < 2 { return 0.0 }
  if len(A) < 3 {
    _A := make([]*[]float64, 0)
    a := make([]float64, len((*A[0])))
    _A = append(_A, &a)
    A = append(_A, A...)
  }
  AB := []float64{(*A[1])[0] - (*A[0])[0], (*A[1])[1] - (*A[0])[1]}
  AC := []float64{(*A[2])[0] - (*A[0])[0], (*A[2])[1] - (*A[0])[1]}
  S := math.Abs(AB[0] * AC[1] - AB[1] * AC[0])
  if mode == 1 { S /= 2.0 }
  return S
}
func OuterCircle(A, B, C *[]float64) (X, Y, R float64) {
  AB := []float64{(*B)[0] - (*A)[0], (*B)[1] - (*A)[1]}
  AC := []float64{(*C)[0] - (*A)[0], (*C)[1] - (*A)[1]}
  AB2 := Dist(2, &AB)
  AC2 := Dist(2, &AC)
  IP := InnerProduct(&AB, &AC)
  b := AC2 * (IP - AB2) / (2 * (IP * IP - AB2 * AC2))
  c := AB2 * (IP - AC2) / (2 * (IP * IP - AB2 * AC2))
  X = (*A)[0] + AB[0] * b + AC[0] * c
  Y = (*A)[1] + AB[1] * b + AC[1] * c
  S := TriangleArea(1, A, B, C)
  ab := math.Sqrt(AB2)
  bc := Dist(1, B, C)
  ca := math.Sqrt(AC2)
  R = ab * bc * ca / (4 * S)
  return
}
func Less(A *[][]float64, i, j int) bool {
  if (*A)[i][0] == (*A)[j][0] { return (*A)[i][1] < (*A)[j][1] }
  return (*A)[i][0] < (*A)[j][0]
}
func Convex(A *[][]float64) []int {
  C := make([]int, 0)
  h := 0
  for i := range (*A) {
    if Less(A, h, i) { h = i }
  }
  next := h
  for len(C) == 0 || next != h {
    C = append(C, next)
    p := (*A)[next]
    for i, a := range (*A) {
      if i == next { continue }
      _A := []float64{a[0] - p[0], a[1] - p[1]}
      D1 := Dist(2, &a, &p)
      convex := true
      for j, b := range (*A) {
        if j == next || j == i { continue }
        _B := []float64{b[0] - p[0], b[1] - p[1]}
        D2 := Dist(2, &b, &p)
        OP := _A[0] * _B[1] - _A[1] * _B[0]
        if math.Abs(OP) < 1e-5 {
          if D2 < D1 { continue }
        } else if 0.0 < OP {
          continue
        }
        convex = false
        break
      }
      if !convex { continue }
      next = i
      break
    }
  }
  return C
}

func Solve() {
  N := NextInt()
  A := make([][]float64, N)
  for i := range A {
    A[i] = NextFloatVec()
  }
  C := Convex(&A)
  C = append(C, C...)
  R := make([]float64, N)
  for i := 0; i < len(C) / 2; i++ {
    if C[i] == C[i + 2] {
      R[C[i + 1]] = 180.0
      continue
    }
    x, y, _ := OuterCircle(&A[C[i]], &A[C[i + 1]], &A[C[i + 2]])
    _A := []float64{A[C[i + 2]][0] - x, A[C[i + 2]][1] - y}
    _B := []float64{A[C[i]][0] - x, A[C[i]][1] - y}
    theta := Angle(&_A, &_B)
    R[C[i + 1]] = theta / 2.0
  }
  for _, r := range R {
    Write(r / 360.0)
  }
  return
}

func main() {
  Solve()
  Output()
}

Score : 600 points

Problem Statement

There are N holes in a two-dimensional plane. The coordinates of the i-th hole are (x_i,y_i).

Let R=10^{10^{10^{10}}}. Ringo performs the following operation:

Randomly choose a point from the interior of a circle of radius R centered at the origin, and put Snuke there. Snuke will move to the hole with the smallest Euclidean distance from the point, and fall into that hole. If there are multiple such holes, the hole with the smallest index will be chosen.

For every i (1 \leq i \leq N), find the probability that Snuke falls into the i-th hole.

Here, the operation of randomly choosing a point from the interior of a circle of radius R is defined as follows:

Pick two real numbers x and y independently according to uniform distribution on [-R,R].

If x^2+y^2\leq R^2, the point (x,y) is chosen. Otherwise, repeat picking the real numbers x,y until the condition is met.

Constraints

2 \leq N \leq 100

|x_i|,|y_i| \leq 10^6(1\leq i\leq N)

All given points are pairwise distinct.

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print N real numbers. The i-th real number must represent the probability that Snuke falls into the i-th hole.

The output will be judged correct when, for all output values, the absolute or relative error is at most 10^{-5}.

Sample Input 1

2
0 0
1 1

Sample Output 1

0.5
0.5

If Ringo put Snuke in the region x+y\leq 1, Snuke will fall into the first hole. The probability of this happening is very close to 0.5.
Otherwise, Snuke will fall into the second hole, the probability of which happening is also very close to 0.5.

Sample Input 2

5
0 0
2 8
4 5
2 6
3 10

Sample Output 2

0.43160120892732328768
0.03480224363653196956
0.13880483535586193855
0.00000000000000000000
0.39479171208028279727


package main

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

var reader = bufio.NewReaderSize(os.Stdin, 1000000)
var writer = bufio.NewWriter(os.Stdout)
func NextLine() string {
  buffer := make([]byte, 0)
  for true {
    line, isPrefix, err := reader.ReadLine()
    if err != nil { panic(err) }
    buffer = append(buffer, line...)
    if !isPrefix { break }
  }
  return string(buffer)
}
func NextInt() int {
  n, _ := strconv.Atoi(NextLine())
  return n
}
func NextIntVec() []int {
  L := strings.Split(NextLine(), " ")
  N := make([]int, len(L))
  for i := range N {
    N[i], _ = strconv.Atoi(L[i])
  }
  return N
}
func NextFloat() float64 {
  n, _ := strconv.ParseFloat(NextLine(), 64)
  return n
}
func NextFloatVec() []float64 {
  L := strings.Split(NextLine(), " ")
  N := make([]float64, len(L))
  for i := range N {
    N[i], _ = strconv.ParseFloat(L[i], 64)
  }
  return N
}
func Write(s interface{}) {
  fmt.Fprintln(writer, s)
}
func WriteIntVec(A []int) {
  S := make([]string, len(A))
  for i, a := range A {
    S[i] = strconv.Itoa(a)
  }
  Write(strings.Join(S, " "))
}
func Output() {
  _ = writer.Flush()
}

func MaxInt(A ...int) int {
  max := A[0]
  for _, a := range A {
    if max < a { max = a }
  }
  return max
}

func Solve() {
  S := NextLine()
  N := len(S)
  K := NextInt()
  M := make([][]int, 26)
  for i := range M {
    M[i] = make([]int, N)
  }
  for i, s := range S {
    m := int(s) - int('a')
    M[m][i] = i + 1
  }
  for i := range M {
    for j := N - 1; 0 < j; j-- {
      if 0 < M[i][j - 1] { continue }
      M[i][j - 1] = M[i][j]
    }
  }
  DP := make([][][]int, K + 1)
  for i := range DP {
    DP[i] = make([][]int, N)
    for j := range DP[i] {
      DP[i][j] = make([]int, N)
      for k := 0; k < i + 1; k++ {
        if N <= j + k { continue }
        DP[i][j][j + k] = k + 1
      }
    }
  }
  for i := range DP {
    for j := N - 1; 0 <= j; j-- {
      for k := j + 1; k < N; k++ {
        DP[i][j][k] = MaxInt(DP[i][j][k - 1], DP[i][j][k])
        l := M[int(S[k]) - int('a')][j]
        if l <= k {
          DP[i][j][k] = MaxInt(DP[i][l][k - 1] + 2, DP[i][j][k])
        }
        if j < N - 1 {
          DP[i][j][k] = MaxInt(DP[i][j + 1][k], DP[i][j][k])
        }
        if 0 < i {
          DP[i][j][k] = MaxInt(DP[i - 1][j][k], DP[i][j][k])
          DP[i][j][k] = MaxInt(DP[i - 1][j + 1][k - 1] + 2, DP[i][j][k])
        }
      }
    }
  }
  Write(DP[K][0][N - 1])
  return
}

func main() {
  Solve()
  Output()
}

Score : 900 points

Problem Statement

Takahashi has decided to give a string to his mother.

The value of a string T is the length of the longest common subsequence of T and T', where T' is the string obtained by reversing T.
That is, the value is the longest length of the following two strings that are equal: a subsequence of T (possibly non-contiguous), and a subsequence of T' (possibly non-contiguous).

Takahashi has a string S. He wants to give her mother a string of the highest possible value, so he would like to change at most K characters in S to any other characters in order to obtain a string of the highest possible value.
Find the highest possible value achievable.

Constraints

1 \leq |S| \leq 300

0 \leq K \leq |S|

S consists of lowercase English letters.

K is an integer.

Input

Input is given from Standard Input in the following format:

S
K

Output

Print the highest possible value achievable.

Sample Input 1

abcabcabc
1

Sample Output 1

7

Changing the first character to c results in cbcabcabc.
Let this tring be T, then one longest common subsequence of T and T' is cbabcbc, whose length is 7.

Sample Input 2

atcodergrandcontest
3

Sample Output 2

15


// ProblemURL : https://atcoder.jp/contests/abc088/tasks/abc088_a
// ---------------------------------------------
package main

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

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}
func diff(a, b int) int {
	if a > b {
		return a - b
	}
	return b - a
}
func larger(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func smaller(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func largest(a, b, c int) (lgst int) {
	if a > b {
		lgst = a
	} else {
		lgst = b
	}
	if c > lgst {
		lgst = c
	}
	return
}
func smallest(a, b, c int) (slst int) {
	if a < b {
		slst = a
	} else {
		slst = b
	}
	if c < slst {
		slst = c
	}
	return
}
func intsMax(a []int) (idx, val int) {
	if len(a) == 0 {
		panic("func max: argument slice length must not be zero")
	}
	val = a[0]
	for i, aa := range a {
		if aa > val {
			idx, val = i, aa
		}
	}
	return
}
func intsMin(a []int) (idx, val int) {
	if len(a) == 0 {
		panic("func min: argument slice length must not be zero")
	}
	val = a[0]
	for i, aa := range a {
		if aa < val {
			idx, val = i, aa
		}
	}
	return
}
func intsSum(a []int) int {
	res := 0
	for _, v := range a {
		res += v
	}
	return res
}
func isEven(n int) bool            { return n&1 == 0 }
func isOdd(n int) bool             { return n&1 == 1 }
func swap(a int, b int) (int, int) { return b, a }
func ceil(x float64) int           { return int(math.Ceil(x)) }
func ceilDiv(x, y int) int         { return (x + y - 1) / y }
func pow(x, y int) int {
	if y < 0 {
		panic("Exponent must be a natural number")
	}
	z := 1
	for i := y; i != 0; i >>= 1 {
		if i&1 == 1 {
			z *= x
		}
		x *= x
	}
	return z
}
func fact(x int) int {
	fact := 1
	for i := 1; i <= x; i++ {
		fact *= i
	}
	return fact
}
func sigmaK(n int) int  { return n * (n + 1) / 2 }
func sigmaKK(n int) int { return (n * (n + 1) / 2) * (2*n + 1) / 3 }
func euclideanDistance(a, b point) float64 {
	s := diff(a.x, b.x)
	s *= s
	t := diff(a.y, b.y)
	t *= t
	return math.Sqrt(float64(s) + float64(t))
}
func manhattanDistance(a, b point) int {
	s := diff(a.x, b.x)
	t := diff(a.y, b.y)
	return s + t
}
func intsJoin(a, b []int) []int { return append(a, b...) }
func intsClear(a []int) []int   { return a[:0] }
func intsCopy(a []int) []int    { return append([]int(nil), a...) }
func intsSorted(a []int) []int {
	s := intsCopy(a)
	sort.Ints(s)
	return s
}
func intsReverse(a []int) {
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
	return
}
func intsFill(a []int, val int) {
	for i := 0; i < len(a); i++ {
		a[i] = val
	}
	return
}
func intsPeekBack(a []int) int {
	if len(a) == 0 {
		panic("func peekBack: zero length slice")
	}
	return a[len(a)-1]
}
func intsPeekFront(a []int) int {
	if len(a) == 0 {
		panic("func peekFront: zero length slice")
	}
	return a[0]
}
func intsPopBack(a []int) (int, []int) {
	if len(a) == 0 {
		panic("func popBack: zero length slice")
	}
	return a[len(a)-1], a[:len(a)-1]
}
func intsPopFront(a []int) (int, []int) {
	if len(a) == 0 {
		panic("func popFront: zero length slice")
	}
	return a[0], a[1:]
}
func intsPushBack(a []int, x int) []int  { return append(a, x) }
func intsPushFront(a []int, x int) []int { return append([]int{x}, a...) }
func chmax(a *int, b int) {
	if *a < b {
		*a = b
	}
}
func chmin(a *int, b int) {
	if *a > b {
		*a = b
	}
}
func cumSum(a []int) []int {
	b := append([]int{0}, a...)
	for i := 1; i < len(b); i++ {
		b[i] += b[i-1]
	}
	return b
}
func runesReverse(a []rune) {
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
	return
}
func bytesReverse(a []byte) {
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
	return
}
func strUpperCase(s string) string { return strings.ToUpper(s) }
func strLowerCase(s string) string { return strings.ToLower(s) }
func strToInt(s string) int {
	i, err := strconv.Atoi(s)
	if err != nil {
		panic(err)
	}
	return i
}
func intToStr(i int) string  { return strconv.Itoa(i) }
func CalcMod(a, mod int) int { return (a%mod + mod) % mod }
func ModPow(x, y, mod int) int {
	if y < 0 {
		panic("Exponent must be a natural number")
	}
	z := 1
	for i := y; i != 0; i >>= 1 {
		if i&1 == 1 {
			z = (z * x) % mod
		}
		x = (x * x) % mod
	}
	return z
}
func ModFact(x, mod int) int {
	fact := 1
	for i := 1; i <= x; i++ {
		fact = fact * i % mod
	}
	return fact
}
func ModInv(x, mod int) int { return ModPow(x, mod-2, mod) }

var (
	sc = bufio.NewScanner(os.Stdin)
	bw = bufio.NewWriterSize(os.Stdout, bwBufSize)
)

func init() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 1e7), 1e7)
}
func ru() (n int) {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	for _, v := range sc.Bytes() {
		n = n*10 + int(v-48)
	}
	return
}
func ri() (n int) {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	b := sc.Bytes()
	neg := false
	if b[0] == 45 {
		neg = true
		b = b[1:]
	}
	for _, v := range b {
		n = n*10 + int(v-48)
	}
	if neg {
		n = -n
	}
	return
}
func ri64() (n int64) {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	b := sc.Bytes()
	neg := false
	if b[0] == 45 {
		neg = true
		b = b[1:]
	}
	for _, v := range b {
		n = n*10 + int64(v-48)
	}
	if neg {
		n = -n
	}
	return
}
func rf64() float64 {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	f, err := strconv.ParseFloat(sc.Text(), 64)
	if err != nil {
		panic(err)
	}
	return f
}
func rs() string {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	return sc.Text()
}
func rb() []byte {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	return sc.Bytes()
}
func rr() []rune {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}
	return []rune(sc.Text())
}
func ris(n int) []int {
	s := make([]int, n)
	for i := range s {
		s[i] = ri()
	}
	return s
}
func risZeroBased(n int) []int {
	s := make([]int, n)
	for i := range s {
		s[i] = ri() - 1
	}
	return s
}
func ri64s(n int) []int64 {
	s := make([]int64, n)
	for i := range s {
		s[i] = ri64()
	}
	return s
}
func rss(n int) []string {
	s := make([]string, n)
	for i := range s {
		s[i] = rs()
	}
	return s
}
func pf(format string, a ...interface{}) {
	if _, err := fmt.Fprintf(bw, format, a...); err != nil {
		panic(err)
	}
}
func pln(a ...interface{}) {
	if _, err := fmt.Fprintln(bw, a...); err != nil {
		panic(err)
	}
}
func pints(a []int) {
	for _, v := range a {
		fmt.Fprintln(bw, v)
	}
}
func pintsol(a []int) {
	s := fmt.Sprint(a)
	if _, err := fmt.Fprintln(bw, s[1:len(s)-1]); err != nil {
		panic(err)
	}
}
func dbg(a ...interface{}) {
	if _, err := fmt.Fprintln(os.Stderr, a...); err != nil {
		panic(err)
	}
}
func YESorNO(b bool) string {
	if b {
		return "YES"
	} else {
		return "NO"
	}
}
func YesOrNo(b bool) string {
	if b {
		return "Yes"
	} else {
		return "No"
	}
}
func main() {
	solve()
	bw.Flush()
}

const (
	bwBufSize = 1e6

	alphabetUpper = "abcdefghijklmnopqrstuvwxyz"
	alphabetLower = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

	// maxInt64  = 9223372036854775807  // 9e18
	// maxInt32  = 2147483647           // 2e9
	// maxUint64 = 18446744073709551615 // 1e19
	inf = 1 << 60
	mod = 1e9 + 7
)

type pair struct{ fi, se int }
type byFiSe []pair

func (p byFiSe) Len() int      { return len(p) }
func (p byFiSe) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p byFiSe) Less(i, j int) bool {
	if p[i].fi == p[j].fi {
		return p[i].se < p[j].se
	}
	return p[i].fi < p[j].fi
}

type point struct{ x, y int }

func solve() {
	n := ri()
	a := ri()
	rest := n % 500
	pln(YesOrNo(rest <= a))
}

Score: 100 points

Problem Statement

E869120 has A 1-yen coins and infinitely many 500-yen coins.

Determine if he can pay exactly N yen using only these coins.

Constraints

N is an integer between 1 and 10000 (inclusive).

A is an integer between 0 and 1000 (inclusive).

Input

Input is given from Standard Input in the following format:

N
A

Output

If E869120 can pay exactly N yen using only his 1-yen and 500-yen coins, print Yes; otherwise, print No.

Sample Input 1

2018
218

Sample Output 1

Yes

We can pay 2018 yen with four 500-yen coins and 18 1-yen coins, so the answer is Yes.

Sample Input 2

2763
0

Sample Output 2

No

When we have no 1-yen coins, we can only pay a multiple of 500 yen using only 500-yen coins. Since 2763 is not a multiple of 500, we cannot pay this amount.

Sample Input 3

37
514

Sample Output 3

Yes


package main

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

var sc = bufio.NewScanner(os.Stdin)

func main() {
	scanInit()

	c := nextIntMat(3, 3)

	a0tri := c[0][0] + c[0][1] + c[0][2]
	a1tri := c[1][0] + c[1][1] + c[1][2]
	a2tri := c[2][0] + c[2][1] + c[2][2]
	for b0i := 0; b0i <= 300; b0i++ {
		for b1i := 0; b1i <= 300; b1i++ {
			for b2i := 0; b2i <= 300; b2i++ {
				bsum := b1i + b1i + b2i
				a0 := a0tri - bsum
				a1 := a1tri - bsum
				a2 := a2tri - bsum
				if a0%3 != 0 || a1%3 != 0 || a2%3 != 0 {
					continue
				}
				fmt.Println("Yes")
				return
			}
		}
	}

	fmt.Println("No")
	return

}

// ---- readfunc
func scanInit() {
	const cap = 200 * 1024 // default=64*1024
	var buf = make([]byte, cap)
	sc.Buffer(buf, cap)
	sc.Split(bufio.ScanWords)
	return
}
func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}
func nextIntMat(a int, b int) [][]int {
	mat := make([][]int, a)
	for i := 0; i < a; i++ {
		mat[i] = make([]int, b)
		for j := 0; j < b; j++ {
			mat[i][j] = nextInt()
		}
	}
	return mat
}

Score: 300 points

Problem Statement

We have a 3 \times 3 grid. A number c_{i, j} is written in the square (i, j), where (i, j) denotes the square at the i-th row from the top and the j-th column from the left.

According to Takahashi, there are six integers a_1, a_2, a_3, b_1, b_2, b_3 whose values are fixed, and the number written in the square (i, j) is equal to a_i + b_j.

Determine if he is correct.

Constraints

c_{i, j} \ (1 \leq i \leq 3, 1 \leq j \leq 3) is an integer between 0 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

c_{1,1} c_{1,2} c_{1,3}
c_{2,1} c_{2,2} c_{2,3}
c_{3,1} c_{3,2} c_{3,3}

Output

If Takahashi's statement is correct, print Yes; otherwise, print No.

Sample Input 1

1 0 1
2 1 2
1 0 1

Sample Output 1

Yes

Takahashi is correct, since there are possible sets of integers such as: a_1=0,a_2=1,a_3=0,b_1=1,b_2=0,b_3=1.

Sample Input 2

2 2 2
2 1 2
2 2 2

Sample Output 2

No

Takahashi is incorrect in this case.

Sample Input 3

0 8 8
0 8 8
0 8 8

Sample Output 3

Yes

Sample Input 4

1 8 6
2 9 7
0 7 7

Sample Output 4

No


package main

import "fmt"

func main() {
	grid := make([][3]int, 3)
	for i := 0; i < 3; i++ {
		grid[i] = [3]int{}
		for j := 0; j < 3; j++ {
			fmt.Scan(&grid[i][j])
		}
	}
	// fmt.Println(grid)

	var a1, a2, a3, b1, b2, b3 int
	b1 = grid[0][0] - a1
	b2 = grid[1][0] - a1
	b3 = grid[2][0] - a1
	a2 = grid[0][1] - b1
	a3 = grid[0][2] - b1

	flag := true
	if grid[1][1] != a2 + b2 {
		flag = false
	}
	if grid[1][2] != a3 + b2 {
		flag = false
	}
	if grid[2][1] != a2 + b3 {
		flag = false
	}
	if grid[2][2] != a3 + b3 {
		flag = false
	}

	if flag == true {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}

}


package main

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

const (
	n = 3
	m = 3
)

type C [][]int

func newC() C {
	var c C
	c = make([][]int, m)
	for i := 0; i < m; i++ {
		c[i] = make([]int, n)
	}

	return c
}

func (c C) check(a, b []int) bool {
	for i := 0; i < m; i++ {
		for j := 0; j < n; j++ {
			if a[i]+b[j] != c[i][j] {
				return false
			}
		}
	}

	return true
}

func main() {
	var input []string

	sc := bufio.NewScanner(os.Stdin)
	for sc.Scan() {
		input = append(input, sc.Text())
	}

	c := newC()

	for i := 0; i < m; i++ {
		line := strings.Split(input[i], " ")
		for j := 0; j < n; j++ {
			vInt, _ := strconv.Atoi(line[j])
			c[i][j] = vInt
		}
	}

	mMax := make([]int, m)
	nMax := make([]int, n)

	for i := 0; i < m; i++ {
		for j := 0; j < n; j++ {
			if mMax[i] < c[i][j] {
				mMax[i] = c[i][j]
			}
		}
	}

	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if nMax[i] < c[i][j] {
				nMax[i] = c[i][j]
			}
		}
	}

	a := make([]int, m)
	b := make([]int, n)

	for i := 0; i <= mMax[0]; i++ {
		a[0] = i
		for j := 0; j <= mMax[1]; j++ {
			a[1] = j
			for k := 0; k <= mMax[2]; k++ {
				a[2] = k
				for l := 0; l <= nMax[0]; l++ {
					b[0] = l
					for m := 0; m <= nMax[1]; m++ {
						b[1] = m
						for n := 0; n <= nMax[2]; n++ {
							b[2] = n

							if c.check(a, b) {
								fmt.Println("Yes")
								return
							}
						}
					}
				}
			}
		}
	}

	fmt.Println("No")
}


package main

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

func out(x ...interface{}) {
	fmt.Println(x...)
}

var sc = bufio.NewScanner(os.Stdin)

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

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

// Priority Queue
type Item struct {
	priority, value, index int
}

type PQ []*Item

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

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

func (pq PQ) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *PQ) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Item)
	item.index = n
	*pq = append(*pq, item)
}

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

// End Priority Queue
// Path
type Edge struct {
	to, cost int
}

type Path struct {
	edges []Edge
}

// Dijkstra
type Route struct {
	path []int
}

func Dijkstra(N, S int, path []Path) ([]int, []Route) {
	pq := make(PQ, 0)
	heap.Init(&pq)
	d := make([]int, N+1)
	r := make([]Route, N+1)
	// init
	for i := 0; i <= N; i++ {
		d[i] = math.MaxInt32
	}
	d[S] = 0
	r[S].path = []int{S}
	heap.Push(&pq, &Item{0, S, 0})
	for pq.Len() > 0 {
		item := heap.Pop(&pq).(*Item)
		v := item.value
		if d[v] < item.priority {
			continue
		}
		for _, e := range path[v].edges {
			if d[e.to] > d[v]+e.cost {
				d[e.to] = d[v] + e.cost
				r[e.to].path = append(r[v].path, e.to)
				heap.Push(&pq, &Item{d[e.to], e.to, 0})
			}
		}
	}
	return d, r

}

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

	H, W := getInt(), getInt()
	s := make([]string, H)
	for i := 0; i < H; i++ {
		s[i] = getString()
	}

	path := make([]Path, W*H)
	cnt := 0
	for y := 0; y < H; y++ {
		for x := 0; x < W; x++ {
			if s[y][x] == '#' {
				cnt++
				continue
			}
			f := y*W + x
			if x != 0 && s[y][x-1] != '#' {
				t := f - 1
				path[f].edges = append(path[f].edges, Edge{t, 1})
			}
			if x != W-1 && s[y][x+1] != '#' {
				t := f + 1
				path[f].edges = append(path[f].edges, Edge{t, 1})
			}
			if y != 0 && s[y-1][x] != '#' {
				t := f - W
				path[f].edges = append(path[f].edges, Edge{t, 1})
			}
			if y != H-1 && s[y+1][x] != '#' {
				t := f + W
				path[f].edges = append(path[f].edges, Edge{t, 1})
			}
		}
	}
	d, _ := Dijkstra(W*H, 0, path)
	pos := W*H - 1

	if d[pos] == math.MaxInt32 {
		out(-1)
	} else {
		out(W*H - cnt - d[pos] - 1)
	}
}

Score: 400 points

Problem statement

We have an H \times W grid whose squares are painted black or white. The square at the i-th row from the top and the j-th column from the left is denoted as (i, j).

Snuke would like to play the following game on this grid. At the beginning of the game, there is a character called Kenus at square (1, 1). The player repeatedly moves Kenus up, down, left or right by one square. The game is completed when Kenus reaches square (H, W) passing only white squares.

Before Snuke starts the game, he can change the color of some of the white squares to black. However, he cannot change the color of square (1, 1) and (H, W). Also, changes of color must all be carried out before the beginning of the game.

When the game is completed, Snuke's score will be the number of times he changed the color of a square before the beginning of the game. Find the maximum possible score that Snuke can achieve, or print -1 if the game cannot be completed, that is, Kenus can never reach square (H, W) regardless of how Snuke changes the color of the squares.

The color of the squares are given to you as characters s_{i, j}. If square (i, j) is initially painted by white, s_{i, j} is .; if square (i, j) is initially painted by black, s_{i, j} is #.

Constraints

H is an integer between 2 and 50 (inclusive).

W is an integer between 2 and 50 (inclusive).

s_{i, j} is . or # (1 \leq i \leq H, 1 \leq j \leq W).

s_{1, 1} and s_{H, W} are ..

Input

Input is given from Standard Input in the following format:

H W
s_{1, 1}s_{1, 2}s_{1, 3} ... s_{1, W}
s_{2, 1}s_{2, 2}s_{2, 3} ... s_{2, W}
: :
s_{H, 1}s_{H, 2}s_{H, 3} ... s_{H, W}

Output

Print the maximum possible score that Snuke can achieve, or print -1 if the game cannot be completed.

Sample Input 1

3 3
..#
#..
...

Sample Output 1

2

The score 2 can be achieved by changing the color of squares as follows:

Sample Input 2

10 37
.....................................
...#...####...####..###...###...###..
..#.#..#...#.##....#...#.#...#.#...#.
..#.#..#...#.#.....#...#.#...#.#...#.
.#...#.#..##.#.....#...#.#.###.#.###.
.#####.####..#.....#...#..##....##...
.#...#.#...#.#.....#...#.#...#.#...#.
.#...#.#...#.##....#...#.#...#.#...#.
.#...#.####...####..###...###...###..
.....................................

Sample Output 2

209


package main

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

var (
	readString func() string
	stdout     *bufio.Writer
)

func init() {
	readString = newReadString(os.Stdin)
	stdout = bufio.NewWriter(os.Stdout)
}

func newReadString(ior io.Reader) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+11))
	r.Split(bufio.ScanWords)

	return func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
}

func readInt() int {
	return int(readInt64())
}

func readInt64() int64 {
	i, err := strconv.ParseInt(readString(), 0, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

func readIntSlice(n int) []int {
	b := make([]int, n)
	for i := 0; i < n; i++ {
		b[i] = readInt()
	}
	return b
}

func readLengthAndSlice() []int {
	n := readInt()
	return readIntSlice(n)
}

func printf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(stdout, f, args...)
}

func println(args ...interface{}) (int, error) {
	return fmt.Fprintln(stdout, args...)
}

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

func minUint(a, b uint) uint {
	if a < b {
		return a
	}
	return b
}

func minInt64(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}

func minUint64(a, b uint64) uint64 {
	if a < b {
		return a
	}
	return b
}

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

func maxUint(a, b uint) uint {
	if a < b {
		return b
	}
	return a
}
func maxInt64(a, b int64) int64 {
	if a < b {
		return b
	}
	return a
}

func maxUint64(a, b uint64) uint64 {
	if a < b {
		return b
	}
	return a
}

func absInt(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

func absInt64(a int64) int64 {
	if a < 0 {
		return -a
	}
	return a
}

// readString() string
// readInt() int
// readIntSlice(n int) []int
// readLengthAndSlice() []int
func gcd(a, b int) int {
	if b == 0 {
		return a
	}
	return gcd(b, a%b)
}

func main() {
	defer stdout.Flush()

	x := readInt()
	y := readInt()

	if x == y {
		println(-1)
		return
	}

	g := gcd(x, y)
	if g == x {
		x, y = y, x
	}

	yg := y / g
	i := 2
	for ; i < yg; i++ {
		if yg%i != 0 {
			println(int64(x) * int64(i))
			return
		}
	}
	for {
		if i%yg != 0 {
			println(int64(x) * int64(i))
			return
		}
		i++
	}
}

Score : 100 points

Problem Statement

You are given positive integers X and Y.
If there exists a positive integer not greater than 10^{18} that is a multiple of X but not a multiple of Y, choose one such integer and print it.
If it does not exist, print -1.

Constraints

1 ≤ X,Y ≤ 10^9

X and Y are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

Print a positive integer not greater than 10^{18} that is a multiple of X but not a multiple of Y, or print -1 if it does not exist.

Sample Input 1

8 6

Sample Output 1

16

For example, 16 is a multiple of 8 but not a multiple of 6.

Sample Input 2

3 3

Sample Output 2

-1

A multiple of 3 is a multiple of 3.


///
// File:  a.go
// Author: ymiyamoto
//
// Created on Sat Feb  3 23:01:46 2018
//
package main

import (
	"fmt"
)

func main() {
	var X, Y int

	if X%Y == 0 {
		fmt.Println(-1)
		return
	}

	for i := 0; ; i++ {
		if X*i%Y != 0 {
			fmt.Println(X)
			return
		}
	}
}


package main

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

const pi = math.Pi

var mod int = pow(10, 9) + 7
var Umod uint64 = 1000000007
var ans, cnt, sum int = 0, 0, 0

func main() {
	reader.Split(bufio.ScanWords)
	N, _ := strconv.Atoi(read())
	a, b := make([]int, N), make([]int, N)
	for i := 0; i < N; i++ {
		a[i], _ = strconv.Atoi(read())
	}
	for i := 0; i < N; i++ {
		b[i], _ = strconv.Atoi(read())
	}
	for i := 0; i < N-1; i++ {
		if a[i] < b[i] {
			if (b[i]-a[i])%2 == 0 {
				b[i+1] += (b[i] - a[i]) / 2
				a[i] = b[i]
			} else {
				b[i+1] += (b[i] - a[i] + 2 - 1) / 2
				a[i+1] += 2
				b[i]++
				a[i] = b[i]
			}
		}
		if a[i] > b[i] {
			a[i+1] += (a[i] - b[i]) * 2
			b[i] = a[i]
		}
	}

	if a[N-1] <= b[N-1] {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
}

/*  ----------------------------------------  */

var reader = bufio.NewScanner(os.Stdin)

func read() string {
	reader.Scan()
	return reader.Text()
}

func lcm(x, y int) int {
	return (x / gcd(x, y)) * y
}

func gcd(x, y int) int {
	if x%y == 0 {
		return y
	} else {
		r := x % y
		return gcd(y, r)
	}
}

var fac [1000000]int
var finv [1000000]int
var inv [1000000]int

func combination_init() {
	fac[0], fac[1] = 1, 1
	finv[0], finv[1] = 1, 1
	inv[1] = 1

	// invは a^(-1) mod p
	// pをaで割ることを考える

	// p/a*(a) + p%a = p
	// p/a*(a) + p%a = 0          (mod p)
	// -p%a = p/a*(a)             (mod p)
	// -p%a *a^(-1)= p/a          (mod p)
	// a^(-1)= p/a * (-p%a)^(-1)  (mod p)
	// a^(-1) =

	for i := 2; i < 1000000; i++ {
		fac[i] = fac[i-1] * i % mod
		inv[i] = mod - inv[mod%i]*(mod/i)%mod
		finv[i] = finv[i-1] * inv[i] % mod
	}
}

func combination(x, y int) int {
	if x < y {
		return 0
	}
	if fac[0] != 1 {
		combination_init()
	}
	return fac[x] * (finv[y] * finv[x-y] % mod) % mod
	//return fac[x] / (fac[y] * fac[x-y])
}

func permutation(x, y int) int {
	if x < y {
		return 0
	}
	if fac[0] != 1 {
		combination_init()
	}
	return fac[x] * (finv[x-y] % mod) % mod
	//return fac[x] / fac[x-y]
}

func max(x ...int) int {
	var res int = x[0]
	for i := 1; i < len(x); i++ {
		res = int(math.Max(float64(x[i]), float64(res)))
	}
	return res
}

func min(x ...int) int {
	var res int = x[0]
	for i := 1; i < len(x); i++ {
		res = int(math.Min(float64(x[i]), float64(res)))
	}
	return res
}
func pow(x, y int) int { return int(math.Pow(float64(x), float64(y))) }
func abs(x int) int    { return int(math.Abs(float64(x))) }
func floor(x int) int  { return int(math.Floor(float64(x))) }
func ceil(x int) int   { return int(math.Ceil(float64(x))) }

type SortBy []int

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

type PriorityQueue []int

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

Score : 300 points

Problem Statement

You are given two integer sequences of length N: a_1,a_2,..,a_N and b_1,b_2,..,b_N.
Determine if we can repeat the following operation zero or more times so that the sequences a and b become equal.

Operation: Choose two integers i and j (possibly the same) between 1 and N (inclusive), then perform the following two actions simultaneously:

Add 2 to a_i.

Add 1 to b_j.

Constraints

1 ≤ N ≤ 10 000

0 ≤ a_i,b_i ≤ 10^9 (1 ≤ i ≤ N)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 .. a_N
b_1 b_2 .. b_N

Output

If we can repeat the operation zero or more times so that the sequences a and b become equal, print Yes; otherwise, print No.

Sample Input 1

3
1 2 3
5 2 2

Sample Output 1

Yes

For example, we can perform three operations as follows to do our job:

First operation: i=1 and j=2. Now we have a = \{3,2,3\}, b = \{5,3,2\}.

Second operation: i=1 and j=2. Now we have a = \{5,2,3\}, b = \{5,4,2\}.

Third operation: i=2 and j=3. Now we have a = \{5,4,3\}, b = \{5,4,3\}.

Sample Input 2

5
3 1 4 1 5
2 7 1 8 2

Sample Output 2

No

Sample Input 3

5
2 7 1 8 2
3 1 4 1 5

Sample Output 3

No


package main

import (
	"bufio"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"sort"
	"strconv"
	"strings"
)

func main() {

	body, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		log.Println(err)
	}
	scanner := bufio.NewScanner(strings.NewReader(string(body)))
	scanner.Split(bufio.ScanWords)
	if err := scanner.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "reading input:", err)
	}
	inputs := make([]int, 0)
	for scanner.Scan() {
		word, _ := strconv.Atoi(scanner.Text())
		inputs = append(inputs, word)
	}

	alice := make([]int, 0, 100)
	bob := make([]int, 0, 100)

	cards := inputs[1:]
	sort.Sort(sort.Reverse(sort.IntSlice(cards)))
	turn := 1
	for i := 0; i < len(cards); i++ {
		if turn%2 == 1 {
			alice = append(alice, cards[i])
		} else {
			bob = append(bob, cards[i])
		}
		turn++
	}

	aliceSum := 0
	for _, i := range alice {
		aliceSum = aliceSum + i
	}
	bobSum := 0
	for _, i := range bob {
		bobSum = bobSum + i
	}

	fmt.Println(aliceSum - bobSum)
}

Score : 100 points

Problem Statement

You went shopping to buy cakes and donuts with X yen (the currency of Japan).

First, you bought one cake for A yen at a cake shop.
Then, you bought as many donuts as possible for B yen each, at a donut shop.

How much do you have left after shopping?

Constraints

1 \leq A, B \leq 1 000

A + B \leq X \leq 10 000

X, A and B are integers.

Input

Input is given from Standard Input in the following format:

X
A
B

Output

Print the amount you have left after shopping.

Sample Input 1

1234
150
100

Sample Output 1

84

You have 1234 - 150 = 1084 yen left after buying a cake.
With this amount, you can buy 10 donuts, after which you have 84 yen left.

Sample Input 2

1000
108
108

Sample Output 2

28

Sample Input 3

579
123
456

Sample Output 3

0

Sample Input 4

7477
549
593

Sample Output 4

405


package main

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

/*
var rdr = bufio.NewReaderSize(os.Stdin, 1000000)
// readLine can read long line string (at least 10^5)
func readLine() string {
	buf := make([]byte, 0, 1000000)
	for {
		l, p, e := rdr.ReadLine()
		if e != nil {
			panic(e)
		}
		buf = append(buf, l...)
		if !p {
			break
		}
	}
	return string(buf)
}
// NextLine reads a line text from stdin, and then returns its string.
func NextLine() string {
	return readLine()
}
*/

var sc = bufio.NewScanner(os.Stdin)

// NextLine reads a line text from stdin, and then returns its string.
func NextLine() string {
	sc.Scan()
	return sc.Text()
}

// NextIntsLine reads a line text, that consists of **ONLY INTEGERS DELIMITED BY SPACES**, from stdin.
// And then returns intergers slice.
func NextIntsLine() []int {
	ints := []int{}
	intsStr := NextLine()
	tmp := strings.Split(intsStr, " ")
	for _, s := range tmp {
		integer, _ := strconv.Atoi(s)
		ints = append(ints, integer)
	}
	return ints
}

// NextStringsLine reads a line text, that consists of **STRINGS DELIMITED BY SPACES**, from stdin.
// And then returns strings slice.
func NextStringsLine() []string {
	str := NextLine()
	return strings.Split(str, " ")
}

// NextRunesLine reads a line text, that consists of **ONLY CHARACTERS ARRANGED CONTINUOUSLY**, from stdin.
// Ant then returns runes slice.
func NextRunesLine() []rune {
	return []rune(NextLine())
}

// Max returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Max(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

// Min returns the min integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Min(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

// PowInt is integer version of math.Pow
func PowInt(a, e int) int {
	if a < 0 || e < 0 {
		panic(errors.New("[argument error]: PowInt does not accept negative integers"))
	}
	fa := float64(a)
	fe := float64(e)
	fanswer := math.Pow(fa, fe)
	return int(fanswer)
}

// AbsInt is integer version of math.Abs
func AbsInt(a int) int {
	fa := float64(a)
	fanswer := math.Abs(fa)
	return int(fanswer)
}

// DeleteElement returns a *NEW* slice, that have the same and minimum length and capacity.
// DeleteElement makes a new slice by using easy slice literal.
func DeleteElement(s []int, i int) []int {
	if i < 0 || len(s) <= i {
		panic(errors.New("[index error]"))
	}
	// appendのみの実装
	n := make([]int, 0, len(s)-1)
	n = append(n, s[:i]...)
	n = append(n, s[i+1:]...)
	return n
}

// Concat returns a *NEW* slice, that have the same and minimum length and capacity.
func Concat(s, t []rune) []rune {
	n := make([]rune, 0, len(s)+len(t))
	n = append(n, s...)
	n = append(n, t...)
	return n
}

// UpperRune is rune version of `strings.ToUpper()`.
func UpperRune(r rune) rune {
	str := strings.ToUpper(string(r))
	return []rune(str)[0]
}

// LowerRune is rune version of `strings.ToLower()`.
func LowerRune(r rune) rune {
	str := strings.ToLower(string(r))
	return []rune(str)[0]
}

// ToggleRune returns a upper case if an input is a lower case, v.v.
func ToggleRune(r rune) rune {
	var str string
	if 'a' <= r && r <= 'z' {
		str = strings.ToUpper(string(r))
	} else if 'A' <= r && r <= 'Z' {
		str = strings.ToLower(string(r))
	} else {
		str = string(r)
	}
	return []rune(str)[0]
}

// ToggleString iteratively calls ToggleRune, and returns the toggled string.
func ToggleString(s string) string {
	inputRunes := []rune(s)
	outputRunes := make([]rune, 0, len(inputRunes))
	for _, r := range inputRunes {
		outputRunes = append(outputRunes, ToggleRune(r))
	}
	return string(outputRunes)
}

// Strtoi is a wrapper of `strconv.Atoi()`.
// If `strconv.Atoi()` returns an error, Strtoi calls panic.
func Strtoi(s string) int {
	if i, err := strconv.Atoi(s); err != nil {
		panic(errors.New("[argument error]: Strtoi only accepts integer string"))
	} else {
		return i
	}
}

// sort package (snippets)
//sort.Sort(sort.IntSlice(s))
//sort.Sort(sort.Reverse(sort.IntSlice(s)))
//sort.Sort(sort.Float64Slice(s))
//sort.Sort(sort.StringSlice(s))

// copy function
//a = []int{0, 1, 2}
//b = make([]int, len(a))
//copy(b, a)

/*******************************************************************/

var x, a, b int

func main() {
	x = NextIntsLine()[0]
	a = NextIntsLine()[0]
	b = NextIntsLine()[0]
	fmt.Println((x - a) % b)
}


package main

import "fmt"

func main() {
	var X, A, B int

	fmt.Scan(&X, &A, &B)
	fmt.Println((X - A) % B)
}


package main

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

func configure(scanner *bufio.Scanner) {
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 1000005), 1000005)
}
func getNextString(scanner *bufio.Scanner) string {
	scanned := scanner.Scan()
	if !scanned {
		panic("scan failed")
	}
	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 getNextFloat64(scanner *bufio.Scanner) float64 {
	i, _ := strconv.ParseFloat(getNextString(scanner), 64)
	return i
}
func main() {
	fp := os.Stdin
	wfp := os.Stdout
	extra := 0
	if os.Getenv("I") == "IronMan" {
		fp, _ = os.Open(os.Getenv("END_GAME"))
		extra = 100
	}
	scanner := bufio.NewScanner(fp)
	configure(scanner)
	writer := bufio.NewWriter(wfp)
	defer func() {
		r := recover()
		if r != nil {
			fmt.Fprintln(writer, r)
		}
		writer.Flush()
	}()
	solve(scanner, writer)
	for i := 0; i < extra; i++ {
		fmt.Fprintln(writer, "-----------------------------------")
		solve(scanner, writer)
	}
}
func solve(scanner *bufio.Scanner, writer *bufio.Writer) {
	n := getNextInt(scanner)
	m := getNextInt(scanner)
	s := getNextInt(scanner) - 1
	t := getNextInt(scanner) - 1
	g := newGraph(n)
	for i := 0; i < m; i++ {
		u := getNextInt(scanner) - 1
		v := getNextInt(scanner) - 1
		d := getNextInt64(scanner)
		g.appendEdge(u, v, i, d)
		g.appendEdge(v, u, i, d)
	}
	dd := &daikes{}
	heap.Push(dd, newDaike(s, 0, 1))
	for i := 0; i < n; i++ {
		g.v[i].d = math.MaxInt64
	}
	for dd.Len() > 0 {
		p := heap.Pop(dd).(daike)
		if g.v[p.i].d < p.d {
			continue
		}
		if g.v[p.i].d == p.d {
			g.v[p.i].c.addAs(p.c)
			continue
		}
		g.v[p.i].c = p.c
		g.v[p.i].d = p.d
		for _, e := range g.e[p.i] {
			heap.Push(dd, newDaike(e.to, p.d+e.d, g.v[p.i].c))
		}
	}
	fmt.Fprintln(writer, g.v[t].c.mul(g.v[t].c.sub(1)))
}

func newDaike(i int, d int64, c mint) daike {
	return daike{i: i, d: d, c: c}
}

type daike struct {
	i int
	d int64
	c mint
}

type daikes []daike

func (h daikes) Len() int { return len(h) }
func (h daikes) Less(i, j int) bool {
	return h[i].d < h[j].d
}
func (h daikes) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *daikes) Push(x interface{}) {
	*h = append(*h, x.(daike))
}
func (h *daikes) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

type vertex struct {
	d int64
	c mint
}
type edge struct {
	to, id int
	d      int64
}
type graph struct {
	v []vertex
	e [][]edge
}

func newGraph(n int) graph {
	return graph{
		v: make([]vertex, n),
		e: make([][]edge, n),
	}
}
func (g *graph) appendEdge(from, to, id int, d int64) {
	g.e[from] = append(g.e[from], edge{
		to: to,
		id: id,
		d:  d,
	})
}

type mint int64

func (mt mint) mod() mint {
	m := mint(1e9 + 7)
	mt %= m
	if mt < 0 {
		return mt + m
	}
	return mt
}
func (mt mint) inv() mint {
	return mt.pow(mint(0).sub(2))
}
func (mt mint) pow(n mint) mint {
	p := mint(1)
	for n > 0 {
		if n&1 == 1 {
			p.mulAs(mt)
		}
		mt.mulAs(mt)
		n >>= 1
	}
	return p
}
func (mt mint) add(x mint) mint {
	return (mt + x).mod()
}
func (mt mint) sub(x mint) mint {
	return (mt - x).mod()
}
func (mt mint) mul(x mint) mint {
	return (mt * x).mod()
}
func (mt mint) div(x mint) mint {
	return mt.mul(x.inv())
}
func (mt *mint) addAs(x mint) *mint {
	*mt = mt.add(x)
	return mt
}
func (mt *mint) subAs(x mint) *mint {
	*mt = mt.sub(x)
	return mt
}
func (mt *mint) mulAs(x mint) *mint {
	*mt = mt.mul(x)
	return mt
}
func (mt *mint) divAs(x mint) *mint {
	*mt = mt.div(x)
	return mt
}

Score : 700 points

Problem Statement

We have a graph with N vertices and M edges, and there are two people on the graph: Takahashi and Aoki.

The i-th edge connects Vertex U_i and Vertex V_i.
The time it takes to traverse this edge is D_i minutes, regardless of direction and who traverses the edge (Takahashi or Aoki).

Takahashi departs Vertex S and Aoki departs Vertex T at the same time. Takahashi travels to Vertex T and Aoki travels to Vertex S, both in the shortest time possible.
Find the number of the pairs of ways for Takahashi and Aoki to choose their shortest paths such that they never meet (at a vertex or on an edge) during the travel, modulo 10^9 + 7.

Constraints

1 \leq N \leq 100 000

1 \leq M \leq 200 000

1 \leq S, T \leq N

S \neq T

1 \leq U_i, V_i \leq N (1 \leq i \leq M)

1 \leq D_i \leq 10^9 (1 \leq i \leq M)

If i \neq j, then (U_i, V_i) \neq (U_j, V_j) and (U_i, V_i) \neq (V_j, U_j).

U_i \neq V_i (1 \leq i \leq M)

D_i are integers.

The given graph is connected.

Input

Input is given from Standard Input in the following format:

N M
S T
U_1 V_1 D_1
U_2 V_2 D_2
:
U_M V_M D_M

Output

Print the answer.

Sample Input 1

4 4
1 3
1 2 1
2 3 1
3 4 1
4 1 1

Sample Output 1

2

There are two ways to choose shortest paths that satisfies the condition:

Takahashi chooses the path 1 \rightarrow 2 \rightarrow 3, and Aoki chooses the path 3 \rightarrow 4 \rightarrow 1.

Takahashi chooses the path 1 \rightarrow 4 \rightarrow 3, and Aoki chooses the path 3 \rightarrow 2 \rightarrow 1.

Sample Input 2

3 3
1 3
1 2 1
2 3 1
3 1 2

Sample Output 2

2

Sample Input 3

3 3
1 3
1 2 1
2 3 1
3 1 2

Sample Output 3

2

Sample Input 4

8 13
4 2
7 3 9
6 2 3
1 6 4
7 6 9
3 8 9
1 2 2
2 8 12
8 6 9
2 5 5
4 2 18
5 3 7
5 1 515371567
4 8 6

Sample Output 4

6


package main

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

func main() {
	var (
		In    = strings.Split(ReadLine(), " ")
		ab, _ = strconv.ParseFloat(In[0]+In[1], 64)
	)

	sq := math.Sqrt(ab)

	//整数か判定
	if float64(int(sq)) != sq {
		fmt.Println("No")
	} else {
		fmt.Println("Yes")
	}

}

/////////////////////////////////////////

func fln(format string, elements ...interface{}) {
	fmt.Printf(format+"\n", elements...)
}

var BufReader = bufio.NewReaderSize(os.Stdin, 1e6)

func ReadLine() string {
	a, _, _ := BufReader.ReadLine()
	return string(a)
}

func ReadLineInt() (result []int) {
	in := strings.Split(ReadLine(), " ")
	result = make([]int, 0, 2)
	for _, v := range in {
		t, _ := strconv.Atoi(v)
		result = append(result, t)
	}
	return
}

Score : 200 points

Problem Statement

AtCoDeer the deer has found two positive integers, a and b.
Determine whether the concatenation of a and b in this order is a square number.

Constraints

1 ≤ a,b ≤ 100

a and b are integers.

Input

Input is given from Standard Input in the following format:

a b

Output

If the concatenation of a and b in this order is a square number, print Yes; otherwise, print No.

Sample Input 1

1 21

Sample Output 1

Yes

As 121 = 11 × 11, it is a square number.

Sample Input 2

100 100

Sample Output 2

No

100100 is not a square number.

Sample Input 3

12 10

Sample Output 3

No