// https://detail.chiebukuro.yahoo.co.jp/qa/question_detail/q1385775538

package main

import (
	"fmt"
)

func main() {
	var n,x int
  var a,b []int
  var ans []int
	fmt.Scan(&n)
	for i := 0; i < n; i++ {
		fmt.Scan(&x)
    a = append(a,x)
	}

  for j:=0; j<n; j++ {
    b = delete(a, j)
    for len(b)>0 {
      b, x = remove(b, b[0])
      ans = append(ans, x)
    }
  }
  for _, r := range ans {
    fmt.Println(combination(r, 2))
  }
}

func delete(s []int, index int) []int {
    ret := make([]int, 0)
    ret = append(ret, s[:index]...)
    return append(ret, s[index+1:]...)
}

func remove(ints []int, search int) ([]int, int) {
    result := []int{}
    res := 0
    for _, v := range ints {
        if v != search {
            result = append(result, v)
        } else {
          res++
        }
    }
    return result, res
}

func permutation(n int, k int) int {
	v := 1
	if 0 < k && k <= n {
		for i := 0; i < k; i++ {
			v *= (n - i)
		}
	} else if k > n {
		v = 0
	}
	return v
}

func factorial(n int) int {
	return permutation(n, n-1)
}

func combination(n int, k int) int {
	return permutation(n, k) / factorial(k)
}

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

Score : 400 points

Problem Statement

We have N balls. The i-th ball has an integer A_i written on it.

For each k=1, 2, ..., N, solve the following problem and print the answer.

Find the number of ways to choose two distinct balls (disregarding order) from the N-1 balls other than the k-th ball so that the integers written on them are equal.

Constraints

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

1 \leq A_i \leq N

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

For each k=1,2,...,N, print a line containing the answer.

Sample Input 1

5
1 1 2 1 2

Sample Output 1

2
2
3
2
3

Consider the case k=1 for example. The numbers written on the remaining balls are 1,2,1,2.

From these balls, there are two ways to choose two distinct balls so that the integers written on them are equal.

Thus, the answer for k=1 is 2.

Sample Input 2

4
1 2 3 4

Sample Output 2

0
0
0
0

No two balls have equal numbers written on them.

Sample Input 3

5
3 3 3 3 3

Sample Output 3

6
6
6
6
6

Any two balls have equal numbers written on them.

Sample Input 4

8
1 2 1 4 2 1 4 1

Sample Output 4

5
7
5
7
7
5
7
5

Submitted source-code file size, in bytes.

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

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


package main

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

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

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

func asub(a, b int) int {
	if a > b {
		return a - b
	}
	return b - a
}

func main() {
	sc.Split(bufio.ScanWords)
	sc.Buffer([]byte{}, 1000000)
	N := getInt()
	a := make([]int, N)
	m := make(map[int]int)
	for i := 0; i < N; i++ {
		a[i] = getInt()
		m[a[i]]++
	}

	w := bufio.NewWriter(os.Stdout)
	defer w.Flush()

	all := 0
	for _, v := range m {
		if v >= 2 {
			all += v * (v - 1) / 2
		}
	}

	for i := 0; i < N; i++ {
		x := m[a[i]]
		y := all
		if x >= 2 {
			y = all - x*(x-1)/2 + (x-1)*(x-2)/2
		}
		fmt.Fprintln(w, y)
	}
}


package main

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

func exec(stdin *Stdin, stdout *Stdout) {
	h := stdin.ReadInt()
	w := stdin.ReadInt()
	k := stdin.ReadInt()
	s := make([][]int, h)
	for i := 0; i < h; i++ {
		line := stdin.Read()
		s[i] = make([]int, w)
		for j := 0; j < w; j++ {
			if line[j] == '0' {
				s[i][j] = 0
			} else {
				s[i][j] = 1
			}
		}
	}

	ans := h * w
	for _, crack := range Combinations(h-1, -1) {
		crack = append(crack, -1)

		x := 0
		cur := make([]int, len(crack)+1)
		for i := 0; i < h; i++ {
			cur[x] += s[i][0]
			if crack[x] == i {
				x++
			}
		}

		ng := false
		count := 0
		for j := 1; j < w; j++ {
			nxt := make([]int, len(crack)+1)
			for i := 0; i < len(cur); i++ {
				if k < cur[i] {
					ng = true
					break
				}
				nxt[i] = cur[i]
			}

			if ng {
				break
			}

			x = 0
			cracking := false
			for i := 0; i < h; i++ {
				nxt[x] += s[i][j]
				if k < nxt[x] {
					cracking = true
				}
				if crack[x] == i {
					x++
				}
			}

			if cracking {
				count++
				for i := 0; i < len(cur); i++ {
					nxt[i] -= cur[i]
				}
			}
			cur = nxt
		}

		if !ng {
			ans = Min(ans, count+len(crack)-1)
		}
	}

	stdout.Println(ans)
}

func Combinations(n int, r int) [][]int {
	ans := [][]int{}
	for x := uint(0); x < (uint(1) << uint(n)); x++ {
		idxs := []int{}
		for i := uint(0); i < uint(n); i++ {
			if x&(uint(1)<<i) != 0 {
				idxs = append(idxs, int(i))
			}
		}
		if r < 0 || len(idxs) == r {
			ans = append(ans, idxs)
		}
	}
	return ans
}

func Min(a int, b ...int) int {
	for _, v := range b {
		if v < a {
			a = v
		}
	}
	return a
}

func main() {
	stdout := NewStdout()
	defer stdout.Flush()
	exec(NewStdin(bufio.ScanWords), stdout)
}

type Stdin struct {
	stdin *bufio.Scanner
}

func NewStdin(split bufio.SplitFunc) *Stdin {
	s := Stdin{bufio.NewScanner(os.Stdin)}
	s.stdin.Split(split)
	s.stdin.Buffer(make([]byte, bufio.MaxScanTokenSize), int(math.MaxInt32))
	return &s
}

func (s *Stdin) Read() string {
	s.stdin.Scan()
	return s.stdin.Text()
}

func (s *Stdin) ReadInt() int {
	n, _ := strconv.Atoi(s.Read())
	return n
}

func (s *Stdin) ReadFloat64() float64 {
	n, _ := strconv.ParseFloat(s.Read(), 64)
	return n
}

type Stdout struct {
	stdout *bufio.Writer
}

func NewStdout() *Stdout {
	return &Stdout{bufio.NewWriter(os.Stdout)}
}

func (s *Stdout) Flush() {
	s.stdout.Flush()
}

func (s *Stdout) Println(a ...interface{}) {
	fmt.Fprintln(s.stdout, a...)
}

Score : 500 points

Problem Statement

We have a chocolate bar partitioned into H horizontal rows and W vertical columns of squares.

The square (i, j) at the i-th row from the top and the j-th column from the left is dark if S_{i,j} is 0, and white if S_{i,j} is 1.

We will cut the bar some number of times to divide it into some number of blocks. In each cut, we cut the whole bar by a line running along some boundaries of squares from end to end of the bar.

How many times do we need to cut the bar so that every block after the cuts has K or less white squares?

Constraints

1 \leq H \leq 10

1 \leq W \leq 1000

1 \leq K \leq H \times W

S_{i,j} is 0 or 1.

Input

Input is given from Standard Input in the following format:

H W K
S_{1,1}S_{1,2}...S_{1,W}
:
S_{H,1}S_{H,2}...S_{H,W}

Output

Print the number of minimum times the bar needs to be cut so that every block after the cuts has K or less white squares.

Sample Input 1

3 5 4
11100
10001
00111

Sample Output 1

2

For example, cutting between the 1-st and 2-nd rows and between the 3-rd and 4-th columns - as shown in the figure to the left - works.

Note that we cannot cut the bar in the ways shown in the two figures to the right.

Sample Input 2

3 5 8
11100
10001
00111

Sample Output 2

0

No cut is needed.

Sample Input 3

4 10 4
1110010010
1000101110
0011101001
1101000111

Sample Output 3

3


package main

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

var sc = bufio.NewScanner(os.Stdin)

func scanInt() int {
	iv, _ := strconv.Atoi(scanString())
	return iv
}

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

func init() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 100001), 100001*100)
}

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

func main() {
	h, w := scanInt(), scanInt()
	dp := make([][]int, h)
	s := make([]string, h)
	for i := range dp {
		dp[i] = make([]int, w)
		for j := range dp[i] {
			dp[i][j] = 100000
		}
		s[i] = scanString()
	}
	if s[0][0] == '#' {
		dp[0][0] = 1
	} else {
		dp[0][0] = 0
	}

	for i := 0; i < h; i++ {
		for j := range s {
			x := 0
			if s[i][j] == '#' {
				x++
			}
			if i > 0 {
				dp[i][j] = min(dp[i][j], dp[i-1][j]+x)
			}
			if j > 0 {
				dp[i][j] = min(dp[i][j], dp[i][j-1]+x)
			}
		}
	}
	fmt.Println(dp[h-1][w-1])
}

Score : 400 points

Problem Statement

Consider a grid with H rows and W columns of squares. Let (r, c) denote the square at the r-th row from the top and the c-th column from the left.
Each square is painted black or white.

The grid is said to be good if and only if the following condition is satisfied:

From (1, 1), we can reach (H, W) by moving one square right or down repeatedly, while always being on a white square.

Note that (1, 1) and (H, W) must be white if the grid is good.

Your task is to make the grid good by repeating the operation below. Find the minimum number of operations needed to complete the task. It can be proved that you can always complete the task in a finite number of operations.

Choose four integers r_0, c_0, r_1, c_1(1 \leq r_0 \leq r_1 \leq H, 1 \leq c_0 \leq c_1 \leq W). For each pair r, c (r_0 \leq r \leq r_1, c_0 \leq c \leq c_1), invert the color of (r, c) - that is, from white to black and vice versa.

Constraints

2 \leq H, W \leq 100

Input

Input is given from Standard Input in the following format:

H W
s_{11} s_{12} \cdots s_{1W}
s_{21} s_{22} \cdots s_{2W}
\vdots
s_{H1} s_{H2} \cdots s_{HW}

Here s_{rc} represents the color of (r, c) - # stands for black, and . stands for white.

Output

Print the minimum number of operations needed.

Sample Input 1

3 3
.##
.#.
##.

Sample Output 1

1

Do the operation with (r_0, c_0, r_1, c_1) = (2, 2, 2, 2) to change just the color of (2, 2), and we are done.

Sample Input 2

2 2
#.
.#

Sample Output 2

2

Sample Input 3

4 4
..##
#...
###.
###.

Sample Output 3

0

No operation may be needed.

Sample Input 4

5 5
.#.#.
#.#.#
.#.#.
#.#.#
.#.#.

Sample Output 4

4


package main

import "fmt"

func main() {
	var h, w int
	fmt.Scan(&h, &w)

	ss := make([]string, h)
	for i := 0; i < h; i++ {
		fmt.Scan(&ss[i])
	}

	const inf int = 1e9
	m := make([][]int, h)
	for i := 0; i < h; i++ {
		m[i] = make([]int, w)
		for j := 0; j < w; j++ {
			m[i][j] = inf
		}
	}

	dx := []int{0, 0, -1, 1}
	dy := []int{-1, 1, 0, 0}

	ans := h * w
	var dfs func(i, j, c, p int)
	dfs = func(i, j, c, p int) {
		if ss[i][j] == '#' {
			c++
			if p == 1 {
				c--
			}
			p = 1
		} else {
			p = 0
		}

		if m[i][j] <= c {
			return
		}
		m[i][j] = c

		if i == h-1 && j == w-1 {
			ans = min(ans, c)
			return
		}

		for d := 0; d < 4; d++ {
			nx, ny := j+dx[d], i+dy[d]
			if 0 <= nx && nx < w && 0 <= ny && ny < h {
				dfs(ny, nx, c, p)
			}
		}
	}
	dfs(0, 0, 0, 0)

	fmt.Println(ans)
}

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


Score : 100 points

Problem Statement

Print the K-th element of the following sequence of length 32:

1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51

Constraints

1 \leq K \leq 32

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K

Output

Print the K-th element.

Sample Input 1

6

Sample Output 1

2

The 6-th element is 2.

Sample Input 2

27

Sample Output 2

5

The 27-th element is 5.


package main

import (
	"fmt"
)

func main() {
	var i, h, w, ans int64
	fmt.Scan(&h)
	fmt.Scan(&w)

	if h == 1 || w == 1 {
		ans = 1
	} else {
		if h%2 == 0 && w%2 == 0 {
			for i = 1; i < h+1; i++ {
				ans += w / 2
			}
		} else {
			for i = 1; i < h+1; i++ {
				if i%2 == 0 {
					ans += w / 2
				} else {
					ans += (w / 2) + 1
				}
			}
		}
	}

	fmt.Println(ans)
}

Score : 200 points

Problem Statement

We have a board with H horizontal rows and W vertical columns of squares.
There is a bishop at the top-left square on this board.
How many squares can this bishop reach by zero or more movements?

Here the bishop can only move diagonally.
More formally, the bishop can move from the square at the r_1-th row (from the top) and the c_1-th column (from the left) to the square at the r_2-th row and the c_2-th column if and only if exactly one of the following holds:

r_1 + c_1 = r_2 + c_2

r_1 - c_1 = r_2 - c_2

For example, in the following figure, the bishop can move to any of the red squares in one move:

Constraints

1 \leq H, W \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H \ W

Output

Print the number of squares the bishop can reach.

Sample Input 1

4 5

Sample Output 1

10

The bishop can reach the cyan squares in the following figure:

Sample Input 2

7 3

Sample Output 2

11

The bishop can reach the cyan squares in the following figure:

Sample Input 3

1000000000 1000000000

Sample Output 3

500000000000000000


package main

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Sort
type RuneSlice []rune

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

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

func main() {
	sc := NewScanner()
	wtr := bufio.NewWriter(os.Stdout)
	defer wtr.Flush()
	H, W := sc.nextInt(), sc.nextInt()

	fmt.Fprintln(wtr, ceil(H*W, 2))
}


package main

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

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

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

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

func debug(a ...interface{}) { fmt.Fprintln(os.Stderr, a...) }

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

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

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

	abc := make([]string,3)
	for i := 0; i < 3; i++ {
		abc[i] = scanString()
	}

	ans := len(abc[0])+len(abc[1])+len(abc[2])
	permutationSearch(3, func(a []int) {
		s1 := abc[a[0]]
		s2 := abc[a[1]]
		s3 := abc[a[2]]
		// debug(s3, s1,s2)

		ma := -1
		L: for i := 0; i < len(s2); i++ {
			for j := 0; j < min(i+1,len(s1)); j++ {
				if s2[i-j] != s1[len(s1)-1-j] && s2[i-j] != '?' && s1[len(s1)-1-j] != '?' {
					continue L
				}
			}

			ma = max(ma, i)
		}

		var s string
		if ma == -1 {
			s = s1+s2
		} else {
			if len(s1)>ma {
				s = s1+s2[ma+1:]
			}
		}

		ma = -1
		L1: for i := 0; i < len(s); i++ {
			for j := 0; j < min(i+1, len(s3)); j++ {
				if len(s3)-1-j < 0 {
				}
				if s[i-j] != s3[len(s3)-1-j] && s[i-j] != '?' && s3[len(s3)-1-j] != '?' {
					continue L1
				}
			}

			ma = max(ma, i)
		}

		if ma == -1 {
			s = s3+s
		} else {
			if len(s3)>ma {
				s = s3+s[ma+1:]
			}
		}

		// debug(s, ma)
		ans = min(ans, len(s))
	})

	fmt.Fprintln(wr, ans)

}

func permutationSearch(n int, fn func(a []int)) {
	a := make([]int, n)
	for i := 0; i < n; i++ { a[i] = i }
	swap := func(i,j int) { a[i],a[j] = a[j],a[i] }

	fn(a)
	for i := n-2; i >= 0; i-- {
		if a[i] > a[i+1] { continue }
		for j := n-1; j >= 0; j-- {
			if a[i] > a[j] { continue }
			swap(i,j)
			for k := i+1; k < (n+i+1)/2; k++ { swap(k,n-(k-i)) }
			fn(a)
			i = n-1
			break
		}
	}
}

Score : 500 points

Problem Statement

Snuke has a string s.
From this string, Anuke, Bnuke, and Cnuke obtained strings a, b, and c, respectively, as follows:

Choose a non-empty (contiguous) substring of s (possibly s itself). Then, replace some characters (possibly all or none) in it with ?s.

For example, if s is mississippi, we can choose the substring ssissip and replace its 1-st and 3-rd characters with ? to obtain ?s?ssip.

You are given the strings a, b, and c.
Find the minimum possible length of s.

Constraints

1 \leq |a|, |b|, |c| \leq 2000

a, b, and c consists of lowercase English letters and ?s.

Input

Input is given from Standard Input in the following format:

a
b
c

Output

Print the minimum possible length of s.

Sample Input 1

a?c
der
cod

Sample Output 1

7

For example, s could be atcoder.

Sample Input 2

atcoder
atcoder
???????

Sample Output 2

7

a, b, and c may not be distinct.


package main

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

var (
	ss   [3]string
	conf [3][3][10000]bool //true if conflicts
)

func main() {
	readVariables()
	preCalc()
	answer := 10000
	answer = MinInt(calc(0, 1, 2), answer)
	answer = MinInt(calc(0, 2, 1), answer)
	answer = MinInt(calc(1, 0, 2), answer)
	answer = MinInt(calc(1, 2, 0), answer)
	answer = MinInt(calc(2, 0, 1), answer)
	answer = MinInt(calc(2, 1, 0), answer)
	fmt.Println(answer)
}

func calc(k, l, m int) int {
	result := 10000
	for i := 0; i < len(ss[k])+2; i++ {
		for j := i; j <= len(ss[k])+len(ss[l]); j++ {
			err := conflict(k, l, i) || conflict(k, m, j) || conflict(l, m, j-i)
			if !err {
				result = MinInt(length(k, l, m, i, j), result)
			}
		}
	}
	return result
}

func length(k, l, m, i, j int) int {
	x := len(ss[k])
	y := i + len(ss[l])
	z := j + len(ss[m])
	return MaxInt(x, MaxInt(y, z))
}

func conflict(k, l, i int) bool {
	if i < 10000 {
		return conf[k][l][i]
	} else {
		return false
	}
}

func preCalc() {
	for k := 0; k < 3; k++ {
		for l := 0; l < 3; l++ {
			//k to l
			for i := 0; i < len(ss[k]); i++ {
			OUTER:
				for j := 0; i+j < len(ss[k]) && j < len(ss[l]); j++ {
					c1, c2 := ss[k][i+j], ss[l][j]
					if c1 != '?' && c2 != '?' && c1 != c2 {
						conf[k][l][i] = true
						break OUTER
					}
				}
			}
		}
	}
}

func readVariables() {
	ss[0], ss[1], ss[2] = nextStr(), nextStr(), nextStr()
}

/* Template */

var scanner *bufio.Scanner

func init() {
	Max := 1001001
	scanner = bufio.NewScanner(os.Stdin)
	scanner.Buffer(make([]byte, 0, Max), Max)
	scanner.Split(bufio.ScanWords)
}

//nextInt converts next token from stdin and returns integer value.
//nextInt panics when conversion into an integer fails.
func nextInt() int {
	if !scanner.Scan() {
		panic("No more token.")
	}
	num, err := strconv.Atoi(scanner.Text())
	if err != nil {
		panic("nextInt(): cannot convert to int: " + scanner.Text())
	}
	return num
}

func nextStr() string {
	if !scanner.Scan() {
		panic("No more token.")
	}
	return scanner.Text()
}

// MinInt returns minimum argument
func MinInt(x, y int) int {
	if x < y {
		return x
	} else {
		return y
	}
}

//MaxInt returns maximum argument
func MaxInt(x, y int) int {
	if x < y {
		return y
	} else {
		return x
	}
}

//AbsInt returns |x| for x
func AbsInt(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

//ModPow calculates integer power with modulo operation
//if modulo <= 1, it powers w/o module operation
//if base < 0, return value might be negative too.
func ModPow(base, exponent, modulo int) (result int) {
	result = 1
	for exponent > 0 {
		if exponent%2 == 1 {
			result *= base
			if modulo > 1 {
				result %= modulo
			}
		}
		base *= base
		if modulo > 1 {
			base %= modulo
		}
		exponent /= 2
	}
	return
}

//Gcd
func Gcd(vals ...int) (result int) {
	if len(vals) == 0 {
		return
	}
	result = vals[0]
	for i := 1; i < len(vals); i++ {
		result = gcd(result, vals[i])
	}
	return
}

func gcd(x, y int) int {
	x, y = AbsInt(x), AbsInt(y)
	for y > 0 {
		x, y = y, x%y
	}
	return x
}

//Lcm
func Lcm(vals ...int) (result int) {
	if len(vals) == 0 {
		return
	}
	result = vals[0]
	for i := 1; i < len(vals); i++ {
		result = lcm(result, vals[i])
	}
	return
}

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


package main

import "fmt"

func main() {
	// Code for A - Hitachi String
	var S string
	fmt.Scanf("%s", &S)

	if len(S)%2 != 0 {
		fmt.Println("No")
	} else {
		var ans string
		for i := 0; i < len(S); i++ {
			if i%2 == 0 {
				ans += "h"
			} else {
				ans += "i"
			}
		}

		if S == ans {
			fmt.Println("Yes")
		} else {
			fmt.Println("No")
		}
	}
}

Score : 100 points

Problem Statement

A Hitachi string is a concatenation of one or more copies of the string hi.

For example, hi and hihi are Hitachi strings, while ha and hii are not.

Given a string S, determine whether S is a Hitachi string.

Constraints

The length of S is between 1 and 10 (inclusive).

S is a string consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S is a Hitachi string, print Yes; otherwise, print No.

Sample Input 1

hihi

Sample Output 1

Yes

hihi is the concatenation of two copies of hi, so it is a Hitachi string.

Sample Input 2

hi

Sample Output 2

Yes

Sample Input 3

ha

Sample Output 3

No


package main

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

func min(nums ...int) int {
	ret := nums[0]
	for _, v := range nums {
		if v < ret {
			ret = v
		}
	}
	return ret
}

func main() {
	sc.Split(bufio.ScanWords)
	A, B, m := nextInt(), nextInt(), nextInt()
	a, b := nextInts(A), nextInts(B)

	ans := min(a...) + min(b...)
	for i := 0; i < m; i++ {
		x, y, c := nextInt()-1, nextInt()-1, nextInt()
		ans = min(ans, a[x]+b[y]-c)
	}

	puts(ans)
	wt.Flush()
}

var (
	sc  = bufio.NewScanner(os.Stdin)
	rdr = bufio.NewReaderSize(os.Stdin, 1000000)
	wt  = bufio.NewWriter(os.Stdout)
)

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

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

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

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

func nextFloat64s(n int) []float64 {
	slice := make([]float64, n)
	for i := 0; i < n; i++ {
		slice[i] = nextFloat64()
	}
	return slice
}

func nextMega() string {
	buf := make([]byte, 0, 1000000)
	for {
		l, p, _ := rdr.ReadLine()
		buf = append(buf, l...)
		if !p {
			break
		}
	}
	return string(buf)
}

func putf(format string, a ...interface{}) {
	fmt.Fprintf(wt, format, a...)
}

func puts(a ...interface{}) {
	fmt.Fprintln(wt, a...)
}

Score : 200 points

Problem Statement

You are visiting a large electronics store to buy a refrigerator and a microwave.

The store sells A kinds of refrigerators and B kinds of microwaves. The i-th refrigerator ( 1 \le i \le A ) is sold at a_i yen (the currency of Japan), and the j-th microwave ( 1 \le j \le B ) is sold at b_j yen.

You have M discount tickets. With the i-th ticket ( 1 \le i \le M ), you can get a discount of c_i yen from the total price when buying the x_i-th refrigerator and the y_i-th microwave together. Only one ticket can be used at a time.

You are planning to buy one refrigerator and one microwave. Find the minimum amount of money required.

Constraints

All values in input are integers.

1 \le A \le 10^5

1 \le B \le 10^5

1 \le M \le 10^5

1 \le a_i , b_i , c_i \le 10^5

1 \le x_i \le A

1 \le y_i \le B

c_i \le a_{x_i} + b_{y_i}

Input

Input is given from Standard Input in the following format:

A B M
a_1 a_2 ... a_A
b_1 b_2 ... b_B
x_1 y_1 c_1
\vdots
x_M y_M c_M

Output

Print the answer.

Sample Input 1

2 3 1
3 3
3 3 3
1 2 1

Sample Output 1

5

With the ticket, you can get the 1-st refrigerator and the 2-nd microwave for 3+3-1=5 yen.

Sample Input 2

1 1 2
10
10
1 1 5
1 1 10

Sample Output 2

10

Note that you cannot use more than one ticket at a time.

Sample Input 3

2 2 1
3 5
3 5
2 2 2

Sample Output 3

6

You can get the 1-st refrigerator and the 1-st microwave for 6 yen, which is the minimum amount to pay in this case.
Note that using a ticket is optional.


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(A ...*int) {
  L := strings.Split(NextLine(), " ")
  for i, a := range A {
    *a, _ = strconv.Atoi(L[i])
  }
}
func NextIntVec(A *[]int) {
  L := strings.Split(NextLine(), " ")
  (*A) = make([]int, len(L))
  for i, l := range L {
    (*A)[i], _ = strconv.Atoi(l)
  }
}
func NextFloat(A ...*float64) {
  L := strings.Split(NextLine(), " ")
  for i, a := range A {
    *a, _ = strconv.ParseFloat(L[i], 64)
  }
}
func NextFloatVec(A *[]float64) {
  L := strings.Split(NextLine(), " ")
  (*A) = make([]float64, len(L))
  for i, l := range L {
    (*A)[i], _ = strconv.ParseFloat(l, 64)
  }
}
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 MinInt(A ...int) int {
  min := A[0]
  for _, a := range A {
    if a < min { min = a }
  }
  return min
}
func SumInt(A ...int) int {
  sum := 0
  for _, a := range A {
    sum += a
  }
  return sum
}
func AbsInt(x int) int {
  if x < 0 { x = -x }
  return x
}

func Mod(I []int, P int) int {
  N := 0
  for _, i := range I {
    N = N * 10 + i
    N %= P
  }
  return N
}

func Solve() {
  var N int
  NextInt(&N)
  T := make([][]int, N)
  for i := range T {
    T[i] = make([]int, 0)
  }
  var a, b int
  for i := 1; i < N; i++ {
    NextInt(&a, &b)
    a, b = a - 1, b - 1
    T[a] = append(T[a], b)
    T[b] = append(T[b], a)
  }
  D := make([]int, N)
  D[0] = 1
  pos := 1
  Q := make([]int, N)
  for _, q := range Q {
    for _, adj := range T[q] {
      if 0 < D[adj] { continue }
      D[adj] = D[q] + 1
      Q[pos] = adj
      pos++
    }
  }
  for i := range D {
    D[i] = -1
  }
  Q[0] = Q[N - 1]
  D[Q[0]] = 1
  pos = 1
  for _, q := range Q {
    for _, adj := range T[q] {
      if 0 < D[adj] { continue }
      D[adj] = D[q] + 1
      Q[pos] = adj
      pos++
    }
  }
  k1, k2, k3 := 0, 0, 0
  A := make([]int, N)
  if D[Q[N - 1]] < 4 {
    for i := range A { A[i] = i + 1 }
    WriteIntVec(A)
    return
  }
  for i := N - 1; 0 <= i; i-- {
    q := Q[i]
    d := D[q]
    if d % 2 == 0 {
      if 3 * k1 + 1 <= N {
        A[q] = 3 * k1 + 1
        k1++
      } else if 3 * k3 + 3 <= N {
        A[q] = 3 * k3 + 3
        k3++
      }
    } else {
      if 3 * k2 + 2 <= N {
        A[q] = 3 * k2 + 2
        k2++
      } else if 3 * k3 + 3 <= N {
        A[q] = 3 * k3 + 3
        k3++
      }
    }
  }
  if MinInt(A...) == 0 {
    Write(-1)
    return
  }
  WriteIntVec(A)
}

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

Score : 600 points

Problem Statement

We have a tree with N vertices. The vertices are numbered 1 to N, and the i-th edge connects Vertex a_i and Vertex b_i.

Takahashi loves the number 3. He is seeking a permutation p_1, p_2, \ldots , p_N of integers from 1 to N satisfying the following condition:

For every pair of vertices (i, j), if the distance between Vertex i and Vertex j is 3, the sum or product of p_i and p_j is a multiple of 3.

Here the distance between Vertex i and Vertex j is the number of edges contained in the shortest path from Vertex i to Vertex j.

Help Takahashi by finding a permutation that satisfies the condition.

Constraints

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

1\leq a_i, b_i \leq N

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
a_2 b_2
\vdots
a_{N-1} b_{N-1}

Output

If no permutation satisfies the condition, print -1.

Otherwise, print a permutation satisfying the condition, with space in between.
If there are multiple solutions, you can print any of them.

Sample Input 1

5
1 2
1 3
3 4
3 5

Sample Output 1

1 2 5 4 3

The distance between two vertices is 3 for the two pairs (2, 4) and (2, 5).

p_2 + p_4 = 6

p_2\times p_5 = 6

Thus, this permutation satisfies the condition.


package main

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

func main() {
	io := NewIo(os.Stdin, os.Stdout)
	defer io.Flush()
	s := io.Next()
	first := s[0]
	for i := 1; i < len(s); i++ {
		if s[i] != first {
			io.Println("Yes")
			return
		}
	}
	io.Println("No")
}

// Io is I/O object
type Io struct {
	reader    *bufio.Reader
	writer    *bufio.Writer
	tokens    []string
	nextToken int
}

// NewIo returns a new Io instance
func NewIo(r io.Reader, w io.Writer) *Io {
	return &Io{
		reader: bufio.NewReader(r),
		writer: bufio.NewWriter(w),
	}
}

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

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

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

// Println is a wrapper of fmt.Fprintln
func (io *Io) Println(a ...interface{}) {
	fmt.Fprintln(io.writer, a...)
}

Score : 100 points

Problem Statement

In AtCoder City, there are three stations numbered 1, 2, and 3.

Each of these stations is operated by one of the two railway companies, A and B. A string S of length 3 represents which company operates each station. If S_i is A, Company A operates Station i; if S_i is B, Company B operates Station i.

To improve the transportation condition, for each pair of a station operated by Company A and one operated by Company B, there will be a bus service connecting them.

Determine if there is a pair of stations that will be connected by a bus service.

Constraints

Each character of S is A or B.

|S| = 3

Input

Input is given from Standard Input in the following format:

S

Output

If there is a pair of stations that will be connected by a bus service, print Yes; otherwise, print No.

Sample Input 1

ABA

Sample Output 1

Yes

Company A operates Station 1 and 3, while Company B operates Station 2.

There will be a bus service between Station 1 and 2, and between Station 2 and 3, so print Yes.

Sample Input 2

BBA

Sample Output 2

Yes

Company B operates Station 1 and 2, while Company A operates Station 3.

There will be a bus service between Station 1 and 3, and between Station 2 and 3, so print Yes.

Sample Input 3

BBB

Sample Output 3

No

Company B operates all the stations. Thus, there will be no bus service, so print No.


package main

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

func main() {
	s := ScanWord()
//P(s)
	aCount := 0
	bCount := 0
	if s[0] == 'A' {
		aCount++
	} else {
		bCount++
	}

	if s[1] == 'A' {
		aCount++
	} else {
		bCount++
	}
	if s[2] == 'A' {
		aCount++
	} else {
		bCount++
	}

	if aCount > 0 && bCount > 0 {
		P("YES")
	} else {
		P("NO")
	}
}

/*********************** I/O ***********************/

var in *bufio.Scanner
var P func(a ...interface{}) (n int, err error)

func init() {
	P = fmt.Println

	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(1e+9))
	in.Split(bufio.ScanWords)

}

func ScanWord() string {in.Scan(); return in.Text() }
func ScanInt() int {i, _ := strconv.Atoi(ScanWord()); return i}
func ScanInt64() int64 {i, _ := strconv.ParseInt(ScanWord(), 10, 64); return i}
func ScanStringSlice(n int) []string {s := make([]string, n); for i := 0; i < n; i++ {s[i] = ScanWord()}; return s}
func ScanIntSlice(n int) []int {arr := make([]int, n); for i := 0; i < n; i++ {arr[i] = ScanInt()}; return arr}
func ScanInt64Slice(n int) []int64 {arr := make([]int64, n); for i := 0; i < n; i++ {arr[i] = ScanInt64()}; return arr}


package main

import "fmt"

func main(){
	var n,a,b,ans int
	fmt.Scan(&n,&a,&b)
	temp := n/(a+b)
	ans = temp*a
	temp = n%(a+b)
	if temp < a {
		ans += temp
	} else {
		ans += a
	}
	fmt.Println(ans)
}

Score : 200 points

Problem Statement

Takahashi has many red balls and blue balls. Now, he will place them in a row.

Initially, there is no ball placed.

Takahashi, who is very patient, will do the following operation 10^{100} times:

Place A blue balls at the end of the row of balls already placed. Then, place B red balls at the end of the row.

How many blue balls will be there among the first N balls in the row of balls made this way?

Constraints

1 \leq N \leq 10^{18}

A, B \geq 0

0 < A + B \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print the number of blue balls that will be there among the first N balls in the row of balls.

Sample Input 1

8 3 4

Sample Output 1

4

Let b denote a blue ball, and r denote a red ball. The first eight balls in the row will be bbbrrrrb, among which there are four blue balls.

Sample Input 2

8 0 4

Sample Output 2

0

He placed only red balls from the beginning.

Sample Input 3

6 2 4

Sample Output 3

2

Among bbrrrr, there are two blue balls.


package main

import "fmt"

func main() {
	var N, A, B int
	fmt.Scan(&N, &A, &B)
	C := N / (A + B)
	fmt.Println(C*A + N - (A+B)*C)
}


package main

import (
	"bufio"
	"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()
	A := getInt()
	B := getInt()

	x := N / (A + B)
	y := N % (A + B)

	sum := A * x
	if A <= y {
		sum += A
	} else {
		sum += y
	}
	fmt.Println(sum)
}

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 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()
}

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 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
}


package main

import "fmt"

func main() {
	var a, b int
	fmt.Scanf("%d %d", &a, &b)
	max := 12*a + a/2
	min := 10 * b
	for i := min; i <= max; i++ {
		if 8*i/100 == a && i/10 == b {
			fmt.Println(i)
			return
		}
	}
	fmt.Println("-1")
	return
}

Score : 300 points

Problem Statement

Find the price of a product before tax such that, when the consumption tax rate is 8 percent and 10 percent, the amount of consumption tax levied on it is A yen and B yen, respectively. (Yen is the currency of Japan.)

Here, the price before tax must be a positive integer, and the amount of consumption tax is rounded down to the nearest integer.

If multiple prices satisfy the condition, print the lowest such price; if no price satisfies the condition, print -1.

Constraints

1 \leq A \leq B \leq 100

A and B are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

If there is a price that satisfies the condition, print an integer representing the lowest such price; otherwise, print -1.

Sample Input 1

2 2

Sample Output 1

25

If the price of a product before tax is 25 yen, the amount of consumption tax levied on it is:

When the consumption tax rate is 8 percent: \lfloor 25 \times 0.08 \rfloor = \lfloor 2 \rfloor = 2 yen.

When the consumption tax rate is 10 percent: \lfloor 25 \times 0.1 \rfloor = \lfloor 2.5 \rfloor = 2 yen.

Thus, the price of 25 yen satisfies the condition. There are other possible prices, such as 26 yen, but print the minimum such price, 25.

Sample Input 2

8 10

Sample Output 2

100

If the price of a product before tax is 100 yen, the amount of consumption tax levied on it is:

When the consumption tax rate is 8 percent: \lfloor 100 \times 0.08 \rfloor = 8 yen.

When the consumption tax rate is 10 percent: \lfloor 100 \times 0.1 \rfloor = 10 yen.

Sample Input 3

19 99

Sample Output 3

-1

There is no price before tax satisfying this condition, so print -1.


package main

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

const (
	initialBufSize = 64 * 1024
	maxBufSize     = 10000000
)

var (
	scanner = bufio.NewScanner(os.Stdin)
	writer  = bufio.NewWriter(os.Stdout)
)

func main() {
	scanner.Buffer(make([]byte, maxBufSize), maxBufSize)
	scanner.Split(bufio.ScanWords)
	s := scanText()
	q := scanInt()

	isReverse := false
	head, tail := "", ""
	for i := 0; i < q; i++ {

		if scanInt() == 1 {
			isReverse = !isReverse
			continue
		}

		if f := scanInt(); (f == 1 && !isReverse) || (f == 2 && isReverse) {
			head += scanText()
		} else {
			tail += scanText()
		}
	}

	ans := reverse(head) + s + tail

	if isReverse {
		fmt.Print(reverse(ans))
	} else {
		fmt.Print(ans)
	}
}

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

func scanInt() int {
	i, _ := strconv.Atoi(scanText())
	return i
}

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

func scanText() string {
	scanner.Scan()
	return scanner.Text()
}

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

func pow(x, y int) int {
	return int(math.Pow(float64(x), float64(y)))
}

Score : 400 points

Problem Statement

Takahashi has a string S consisting of lowercase English letters.

Starting with this string, he will produce a new one in the procedure given as follows.

The procedure consists of Q operations. In Operation i (1 \leq i \leq Q), an integer T_i is provided, which means the following:

If T_i = 1: reverse the string S.

If T_i = 2: An integer F_i and a lowercase English letter C_i are additionally provided.

If F_i = 1 : Add C_i to the beginning of the string S.

If F_i = 2 : Add C_i to the end of the string S.

Help Takahashi by finding the final string that results from the procedure.

Constraints

1 \leq |S| \leq 10^5

S consists of lowercase English letters.

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

T_i = 1 or 2.

F_i = 1 or 2, if provided.

C_i is a lowercase English letter, if provided.

Input

Input is given from Standard Input in the following format:

S
Q
Query_1
:
Query_Q

In the 3-rd through the (Q+2)-th lines, Query_i is one of the following:

1

which means T_i = 1, and:

2 F_i C_i

which means T_i = 2.

Output

Print the resulting string.

Sample Input 1

a
4
2 1 p
1
2 2 c
1

Sample Output 1

cpa

There will be Q = 4 operations. Initially, S is a.

Operation 1: Add p at the beginning of S. S becomes pa.

Operation 2: Reverse S. S becomes ap.

Operation 3: Add c at the end of S. S becomes apc.

Operation 4: Reverse S. S becomes cpa.

Thus, the resulting string is cpa.

Sample Input 2

a
6
2 2 a
2 1 b
1
2 2 c
1
1

Sample Output 2

aabc

There will be Q = 6 operations. Initially, S is a.

Operation 1: S becomes aa.

Operation 2: S becomes baa.

Operation 3: S becomes aab.

Operation 4: S becomes aabc.

Operation 5: S becomes cbaa.

Operation 6: S becomes aabc.

Thus, the resulting string is aabc.

Sample Input 3

y
1
2 1 x

Sample Output 3

xy


package main

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

var scanner = bufio.NewScanner(os.Stdin)

func main() {
	scanner.Split(bufio.ScanWords)
	s := scanText()
	q := scanInt()

	isReverse := false
	head, tail := "", ""
	for i := 0; i < q; i++ {

		if scanInt() == 1 {
			isReverse = !isReverse
			continue
		}

		if f := scanInt(); (f == 1 && !isReverse) || (f == 2 && isReverse) {
			head += scanText()
		} else {
			tail += scanText()
		}
	}

	ans := reverse(head) + s + tail

	if isReverse {
		fmt.Print(reverse(ans))
	} else {
		fmt.Print(ans)
	}
}

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

func scanInt() int {
	i, _ := strconv.Atoi(scanText())
	return i
}

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

func scanText() string {
	scanner.Scan()
	return scanner.Text()
}

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

func pow(x, y int) int {
	return int(math.Pow(float64(x), float64(y)))
}


package main

import (
	"fmt"
)

func main() {
	var S, fw, lw string
	fmt.Scan(&S)
	var Q, c1 int
	fmt.Scan(&Q)
	w := S
	for i := 0; i < Q; i++ {
		var t, f int
		var c string
		fmt.Scan(&t)
		if t == 2 {
			fmt.Scan(&f, &c)
			if f == 1 {
				if c1%2 == 0 {
					fw += c
				} else {
					lw += c
				}
			} else {
				if c1%2 == 0 {
					lw += c
				} else {
					fw += c
				}
			}
		} else {
			c1++
		}
	}
	var r string
	if len(fw) > 0 {
		r = Reverse(fw) + w
	}
	if len(lw) > 0 {
		r += lw
	}
	if c1%2 == 1 {
		r = Reverse(r)
	}
	fmt.Println(r)
}

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)
}


package main

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

var sc = bufio.NewScanner(os.Stdin)
var out = bufio.NewWriter(os.Stdout)
var bufferSize = 1024 * 1024

type t struct {
	t int64
	f int64
	c byte
}

func solve(s []byte, q int64, qs []t) []byte {
	edges := make([][]byte, 2)
	edges[0] = make([]byte, 0, q)
	edges[1] = make([]byte, 0, q)
	frontIdx := 0

	reversed := false
	for _, tt := range qs {
		if tt.t == 1 {
			reversed = !reversed
			frontIdx = 1 - frontIdx
			continue
		}
		if tt.f == 1 {
			edges[frontIdx] = append(edges[frontIdx], tt.c)
		} else {
			edges[1 - frontIdx] = append(edges[1 - frontIdx], tt.c)
		}
	}

	ret := make([]byte, 0, len(s) + len(edges[0]) + len(edges[1]))
	for i := len(edges[frontIdx]) - 1; i >= 0; i-- {
		ret = append(ret, edges[frontIdx][i])
	}
	if reversed {
		for i := len(s) - 1; i >= 0; i-- {
			ret = append(ret, s[i])
		}
	} else {
		for _, b := range s  {
			ret = append(ret, b)
		}
	}
	for _, b := range edges[1 - frontIdx] {
		ret = append(ret, b)
	}
	return ret
}

func main() {
	scanBuffer := make([]byte, bufferSize)
	sc.Buffer(scanBuffer, bufferSize)
	sc.Split(bufio.ScanWords)
	defer out.Flush()

	s := nextStringAsBytes()
	q := nextInt()

	qs := make([]t, q)
	for i := int64(0); i < q; i++ {
		qs[i].t = nextInt()
		if qs[i].t == 2 {
			qs[i].f  = nextInt()
			qs[i].c  = nextStringAsBytes()[0]
		}
	}

	bytes := solve(s, q, qs)
	fmt.Fprintln(out, string(bytes))
}

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

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

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

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

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

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

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

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

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


package main

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

func main() {
	resolve(parseProblem(os.Stdin))
}

func parseProblem(r io.Reader) (string, chan query) {
	sc := bufio.NewScanner(r)
	sc.Split(bufio.ScanWords) // bufio.ScanLines
	const (
		initialBufSize = 100000
		maxBufSize     = 100000
	)
	buf := make([]byte, initialBufSize)
	sc.Buffer(buf, maxBufSize)

	sc.Scan()
	s := sc.Text()
	n := scanint(sc)

	ch := make(chan query)
	go func() {
		for i := 0; i < n; i++ {
			ch <- parseQuery(sc)
		}
		close(ch)
	}()
	return s, ch
}

const (
	Switch = 1 + iota
	Append
)

type query struct {
	cmd int
	sub int
	c   string
}

func parseQuery(sc *bufio.Scanner) query {
	cmd := scanint(sc)
	if cmd == Switch {
		return query{cmd, 0, ""}
	}
	sub := scanint(sc)
	sc.Scan()
	t := sc.Text()
	return query{Append, sub, t}
}

func scanint(sc *bufio.Scanner) int {
	sc.Scan()
	i, _ := strconv.Atoi(sc.Text())
	return int(i)
}

func resolve(base string, queries chan query) {
	state := 0
	fixies := [2][]string{}
	for q := range queries {
		if q.cmd == Switch {
			state += 1
		} else {
			// state 0; 1 -> 1(prefix), 2 -> 0 (suffix)
			fixies[(state+q.sub)%2] = append(fixies[(state+q.sub)%2], q.c)
		}
	}

	normal := state%2 == 0
	prefix := fixies[(state+1)%2]
	suffix := fixies[(state+2)%2]

	for i := len(prefix); i > 0; i-- {
		fmt.Printf("%s", prefix[i-1])
	}
	if normal {
		fmt.Printf("%s", base)
	} else {
		runes := []rune(base)
		for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
			runes[i], runes[j] = runes[j], runes[i]
		}
		fmt.Printf("%s", string(runes))
	}

	for i := 0; i < len(suffix); i++ {
		fmt.Printf("%s", suffix[i])
	}
}


package main

import (
	"fmt"
	"strings"
)

func swap(s string) string {
	if len(s) == 1 {
		return s
	}
	return s[len(s)-1:] + s[1:len(s)-1] + s[:1]
}

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 main() {
	var s string
	var n int
	fmt.Scan(&s, &n)

	var q, f int
	var c string
	var reverse bool
	front := make([]string, 0)
	back := make([]string, 0)
	for i := 0; i < n; i++ {
		fmt.Scan(&q)
		if q == 1 {
			if reverse {
				reverse = false
			} else {
				reverse = true
			}
		} else {
			fmt.Scan(&f, &c)
			if f == 1 {
				if reverse {
					back = append(back, c)
				} else {
					front = append([]string{c}, front...)
				}
			} else {
				if reverse {
					front = append([]string{c}, front...)
				} else {
					back = append(back, c)
				}
			}
		}
	}

	s = strings.Join(front, "") + s + strings.Join(back, "")
	if reverse {
		s = Reverse(s)
	}
	fmt.Println(s)
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

func main() {
	sc.Split(bufio.ScanWords)
	s, q := next(), nextInt()

	for i := 0; i < q; i++ {
		qa := nextInt()
		if qa == 1 {
			sl := len(s)
			if sl > 1 {
				rs := []rune(s)
				rs[0], rs[sl-1] = rs[sl-1], rs[0]
				s = string(rs)
			}
		}
		if qa == 2 {
			f, c := nextInt(), next()
			if f == 1 {
				s = c + s
			}
			if f == 2 {
				s = s + c
			}
		}
	}
	fmt.Println(s)
}

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


package main

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

// N: [1, 2e5]
// len(S) = N
// P: [2, 10000], prime
func main() {
	sc := newInputScanner(true, 256)
	N, P, S := sc.nextInt(), sc.nextInt(), sc.nextStr()
	// N := 20000
	// P := 127
	// S := ""
	// for i := 0; i < N; i++ {
	// 	S += string(strconv.Itoa(rand.Intn(10)))
	// }
	// fmt.Println(S)
	answer := checkSubNumbers(N, P, S)
	fmt.Println(answer)
}

func checkSubNumbers(N int, P int, S string) int {
	switch P {
	case 2, 5:
		return checkTwoOrFive(N, P, S)
	default:
		return checkNotTwoNorFive(N, P, S)
	}
}

func checkTwoOrFive(N int, P int, S string) int {
	answer := 0
	var n int
	for i := N - 1; i >= 0; i-- {
		n, _ = strconv.Atoi(S[i : i+1])
		if n%P == 0 {
			answer += i + 1
		}
	}
	return answer
}

func checkNotTwoNorFive(N int, P int, S string) int {
	bigP := big.NewInt(int64(P))
	ten := big.NewInt(10)
	multiplier := big.NewInt(1)
	answer := 0
	remainderLookup := make([]int, P)
	currentBigInt := big.NewInt(0)
	prevRemaider := -1
	var digit, remainder, count int
	var n *big.Int
	for i := N - 1; i >= 0; i-- {
		digit, _ = strconv.Atoi(S[i : i+1])
		if digit == 0 {
			if prevRemaider == -1 {
				remainder = 0
			} else {
				remainder = prevRemaider
			}
		} else {
			n = big.NewInt(int64(digit))
			n = n.Mul(n, multiplier)
			n = n.Add(currentBigInt, n)
			currentBigInt.Set(n)
			remainder = int(n.Mod(n, bigP).Int64())
		}
		if remainder == 0 {
			answer++
		}
		count = remainderLookup[remainder]
		answer += count
		count++
		remainderLookup[remainder] = count
		prevRemaider = remainder
		multiplier = multiplier.Mul(multiplier, ten)
	}
	return answer
}

type inputScanner struct {
	*bufio.Scanner
}

func newInputScanner(enabledScanWords bool, sizeInKB int) *inputScanner {
	scanner := bufio.NewScanner(os.Stdin)
	if enabledScanWords {
		scanner.Split(bufio.ScanWords)
	}
	capacity := sizeInKB * 1024
	buf := make([]byte, capacity)
	scanner.Buffer(buf, capacity)
	return &inputScanner{
		Scanner: scanner,
	}
}

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

func (inputSc *inputScanner) nextUInt64() uint64 {
	i, e := strconv.ParseUint(inputSc.nextStr(), 10, 64)
	if e != nil {
		panic(e)
	}
	return i
}

func (inputSc *inputScanner) nextStr() string {
	inputSc.Scan()
	return inputSc.Text()
}

Score : 500 points

Problem Statement

Takahashi has a string S of length N consisting of digits from 0 through 9.

He loves the prime number P. He wants to know how many non-empty (contiguous) substrings of S - there are N \times (N + 1) / 2 of them - are divisible by P when regarded as integers written in base ten.

Here substrings starting with a 0 also count, and substrings originated from different positions in S are distinguished, even if they are equal as strings or integers.

Compute this count to help Takahashi.

Constraints

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

S consists of digits.

|S| = N

2 \leq P \leq 10000

P is a prime number.

Input

Input is given from Standard Input in the following format:

N P
S

Output

Print the number of non-empty (contiguous) substrings of S that are divisible by P when regarded as an integer written in base ten.

Sample Input 1

4 3
3543

Sample Output 1

6

Here S = 3543. There are ten non-empty (contiguous) substrings of S:

3: divisible by 3.

35: not divisible by 3.

354: divisible by 3.

3543: divisible by 3.

5: not divisible by 3.

54: divisible by 3.

543: divisible by 3.

4: not divisible by 3.

43: not divisible by 3.

3: divisible by 3.

Six of these are divisible by 3, so print 6.

Sample Input 2

4 2
2020

Sample Output 2

10

Here S = 2020. There are ten non-empty (contiguous) substrings of S, all of which are divisible by 2, so print 10.

Note that substrings beginning with a 0 also count.

Sample Input 3

20 11
33883322005544116655

Sample Output 3

68


package main

import (
	"fmt"
	"math"
	"math/big"
)

func main() {
	var n, p int64
	var s string
	fmt.Scanf("%d %d", &n, &p)
	fmt.Scanf("%s", &s)
	answer := countDivisible(n, p, s)
	fmt.Println(answer)
}

func countDivisible(n, p int64, s string) int64 {
	modMatrix := make([][]int64, len(s))

	for i := 0; i < len(s); i++ {
		modMatrix[i] = make([]int64, len(s))
		for j := 0; j < len(s)-i; j++ {
			// i: index in s, j: 10 ** j
			if j < 14 { // rough estimation for avoiding int overflow
				modMatrix[i][j] = (int64(s[i]) - 48) * int64(math.Pow10(j)) % p
			} else {
				bigP := big.NewInt(p)
				bigSi := big.NewInt(int64(s[i]) - 48)
				ten := big.NewInt(10)
				ten.Exp(ten, big.NewInt(int64(j)), nil)
				bigSi.Mul(bigSi, ten)
				bigSi.Mod(bigSi, bigP)
				modMatrix[i][j] = bigSi.Int64()
			}
		}
	}

	var cnt int64
	for i := 0; i < len(s); i++ {
		for j := i; j < len(s); j++ {
			var sumOfMod int64
			for k := i; k <= j; k++ {
				sumOfMod += modMatrix[k][j-k]
			}
			if sumOfMod%p == 0 {
				cnt++
			}
		}
	}
	return cnt
}


package main

import (
	"fmt"
	"strconv"
)

func main() {
	var n, p int
	fmt.Scan(&n, &p)
	var s []byte
	fmt.Scan(&s)

	var sum int
	ms := make([]map[int]int, n)
	for i := range s {
		ms[i] = make(map[int]int)
		t, _ := strconv.Atoi(string([]byte{s[i]}))
		ms[i][t%p]++
		if i > 0 {
			for k, v := range ms[i-1] {
				u := (k*10 + t) % p
				ms[i][u] += v
			}
		}
		if cnt, ok := ms[i][0]; ok {
			sum += cnt
		}
	}
	fmt.Println(sum)
}


package main

import (
	"fmt"
)

func main() {

	var N int
	fmt.Scanf("%d", &N)

	var result int
	result = result + N/2 + N%2

	fmt.Println(result)

}

Score : 100 points

Problem Statement

Takahashi wants to print a document with N pages double-sided, where two pages of data can be printed on one sheet of paper.

At least how many sheets of paper does he need?

Constraints

N is an integer.

1 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

5

Sample Output 1

3

By printing the 1-st, 2-nd pages on the 1-st sheet, 3-rd and 4-th pages on the 2-nd sheet, and 5-th page on the 3-rd sheet, we can print all the data on 3 sheets of paper.

Sample Input 2

2

Sample Output 2

1

Sample Input 3

100

Sample Output 3

50


package main

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

var huge = int(math.Pow(10, 18))

const maxS = 50*50 + 5

func main() {
	var n int
	InputInt(" ", &n)
	Write(n/2 + n%2)
	Flush()
}

/*----------文字列関連----------*/

// ReverseByte byte列の反転
func ReverseByte(list []byte) []byte {
	l := len(list)
	res := make([]byte, l)
	for i := 0; i < l; i++ {
		res[i] = list[l-i-1]
	}
	return res
}

/*----------Intでの基本計算関数----------*/

// MinInt 最大値導出関数
func MinInt(nums ...int) int {
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		switch {
		case nums[i] < res:
			res = nums[i]
		}
	}
	return res
}

// MaxInt 最大値導出関数
func MaxInt(nums ...int) int {
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		switch {
		case nums[i] > res:
			res = nums[i]
		}
	}
	return res
}

// PowInt Int型での冪乗計算
func PowInt(n int, x int) int {
	res := 1
	for i := 0; i < x; i++ {
		res *= n
	}
	return res
}

// SumInt Int型での合計計算
func SumInt(A ...int) int {
	sum := 0
	for _, a := range A {
		sum += a
	}
	return sum
}

// AbsInt Int型での絶対値計算
func AbsInt(x int) int {
	if x < 0 {
		x = -x
	}
	return x
}

/*----------Int型スライスの基本計算関数----------*/

// MinIntVec 最大値導出関数 インデックスも返す
func MinIntVec(nums []int) (int, []int) {
	res := nums[0]
	var index []int
	for i := 0; i < len(nums); i++ {
		switch {
		case nums[i] < res:
			res = nums[i]
			index = []int{i}
		case nums[i] == res:
			index = append(index, i)
		}
	}
	return res, index
}

// MaxIntVec 最大値導出関数 インデックスも返す
func MaxIntVec(nums []int) (int, []int) {
	res := nums[0]
	var index []int
	for i := 0; i < len(nums); i++ {
		switch {
		case nums[i] > res:
			res = nums[i]
			index = []int{i}
		case nums[i] == res:
			index = append(index, i)
		}
	}
	return res, index
}

// SumIntVec Int型での合計計算
func SumIntVec(A []int) int {
	sum := 0
	for _, a := range A {
		sum += a
	}
	return sum
}

/*----------標準入力・出力用の関数----------*/
var reader = bufio.NewReader(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

// InputLine 次の標準入力をstring型として取得
func InputLine() string {
	buffer := make([]byte, 0)
	for true {
		line, isPrefix, _ := reader.ReadLine()
		buffer = append(buffer, line...)
		if !isPrefix {
			break
		}
	}
	return string(buffer)
}

// InputString いくつかの文字列をstring型で取得
func InputString(delim string, A ...*string) {
	L := strings.Split(InputLine(), delim)
	for i, a := range A {
		*a = L[i]
	}
}

// InputStringVec delim区切りの文字列をstring型のスライスとして取得
func InputStringVec(delim string,A *[]string) {
	L := strings.Split(InputLine(), delim)
  *A = make([]string,len(L))
  for i := range L {
		(*A)[i] = L[i]
	}
}

// InputInt いくつかの数値をint型で取得
func InputInt(delim string, A ...*int) {
	L := strings.Split(InputLine(), delim)
	for i, a := range A {
		*a, _ = strconv.Atoi(L[i])
	}
}

// InputIntVec delim区切りの数値をint型のスライスとして取得
func InputIntVec(delim string, A *[]int) {
	L := strings.Split(InputLine(), delim)
	*A = make([]int, len(L))
	for i := range L {
		(*A)[i], _ = strconv.Atoi(L[i])
	}
}

// Write バッファに対応した出力関数
func Write(s interface{}) {
	fmt.Fprintln(writer, s)
}

// WriteIntVec バッファに対応したInt型スライスの出力関数
func WriteIntVec(A []int) {
	S := make([]string, len(A))
	for i, a := range A {
		S[i] = strconv.Itoa(a)
	}
	Write(strings.Join(S, " "))
}

// Flush バッファした出力をフラッシュ
func Flush() {
	_ = writer.Flush()
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

	n := nextInt()

	fmt.Println(n/2 + (n % 2))
}

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


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

func main() {
     sc.Split(bufio.ScanWords)
     n := nextInt()
     ans := n / 2 + n % 2

     fmt.Println(ans)
}


package main

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

const (
	initialBufSize = 10000
	maxBufSize     = 1000000009
)

var buf []byte = make([]byte, maxBufSize)
var sc = bufio.NewScanner(os.Stdin)

func init() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(buf, maxBufSize)
}

func main() {
	A := make([][]int, 3)
	for i := 0; i < 3; i++ {
		A[i] = make([]int, 3)
	}
	for i := 0; i < 3; i++ {
		for j := 0; j < 3; j++ {
			A[i][j] = nextInt()
		}
	}
	var N int
	N = nextInt()
	matrix := [][]int{{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}
	for i := 0; i < N; i++ {
		b := nextInt()
		for j := 0; j < 3; j++ {
			for k := 0; k < 3; k++ {
				if A[j][k] == b {
					matrix[j][k] = 1
				}
				if matrix[j][0]+matrix[j][1]+matrix[j][2] == 3 {
					fmt.Println("Yes")
					return
				}
			}
		}
		if matrix[0][0]+matrix[1][0]+matrix[2][0] == 3 || matrix[0][1]+matrix[1][1]+matrix[1][1] == 3 || matrix[0][2]+matrix[1][2]+matrix[2][2] == 3 || matrix[0][0]+matrix[1][1]+matrix[2][2] == 3 || matrix[2][0]+matrix[1][1]+matrix[0][2] == 3 {
			fmt.Println("Yes")
			return
		}
	}
	fmt.Println("No")
}

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

Score : 200 points

Problem Statement

We have a bingo card with a 3\times3 grid. The square at the i-th row from the top and the j-th column from the left contains the number A_{i, j}.

The MC will choose N numbers, b_1, b_2, \cdots, b_N. If our bingo sheet contains some of those numbers, we will mark them on our sheet.

Determine whether we will have a bingo when the N numbers are chosen, that is, the sheet will contain three marked numbers in a row, column, or diagonal.

Constraints

All values in input are integers.

1 \leq A_{i, j} \leq 100

A_{i_1, j_1} \neq A_{i_2, j_2} ((i_1, j_1) \neq (i_2, j_2))

1 \leq N \leq 10

1 \leq b_i \leq 100

b_i \neq b_j (i \neq j)

Input

Input is given from Standard Input in the following format:

A_{1, 1} A_{1, 2} A_{1, 3}
A_{2, 1} A_{2, 2} A_{2, 3}
A_{3, 1} A_{3, 2} A_{3, 3}
N
b_1
\vdots
b_N

Output

If we will have a bingo, print Yes; otherwise, print No.

Sample Input 1

84 97 66
79 89 11
61 59 7
7
89
7
87
79
24
84
30

Sample Output 1

Yes

We will mark A_{1, 1}, A_{2, 1}, A_{2, 2}, A_{3, 3}, and complete the diagonal from the top-left to the bottom-right.

Sample Input 2

41 7 46
26 89 2
78 92 8
5
6
45
16
57
17

Sample Output 2

No

We will mark nothing.

Sample Input 3

60 88 34
92 41 43
65 73 48
10
60
43
88
11
48
73
65
41
92
34

Sample Output 3

Yes

We will mark all the squares.


package main

import (
	"fmt"
	"sort"
)

func insert(a []int, x int) []int {
	i := sort.SearchInts(a, x)
	return append(append(a[:i], x), a[i:]...)
}

func remove(a []int, x int) []int {
	i := sort.SearchInts(a, x)
	if i < len(a)-1 {
		return append(a[:i], a[i+1:]...)
	}
	return a[:i]
}

func main() {
	var n, q int
	var str string
	fmt.Scan(&n, &str, &q)

	s := []byte(str)
	abc := [26][]int{}
	for i := 0; i < n; i++ {
		c := s[i] - 'a'
		abc[c] = append(abc[c], i)
	}

	for k := 0; k < q; k++ {
		var t int
		fmt.Scan(&t)

		if t == 1 {
			var i int
			var a string
			fmt.Scan(&i, &a)
			i--

			c := s[i] - 'a'
			abc[c] = remove(abc[c], i)
			s[i] = a[0]
			c = s[i] - 'a'
			abc[c] = insert(abc[c], i)
		} else {
			var l, r int
			fmt.Scan(&l, &r)
			l--

			cnt := 0
			for c := 0; c < 26; c++ {
				i := sort.SearchInts(abc[c], l)
				if i < len(abc[c]) && abc[c][i] < r {
					cnt++
				}
			}
			fmt.Println(cnt)
		}

	}
}

Score : 500 points

Problem Statement

You are given a string S of length N consisting of lowercase English letters.

Process Q queries of the following two types:

Type 1: change the i_q-th character of S to c_q. (Do nothing if the i_q-th character is already c_q.)

Type 2: answer the number of different characters occurring in the substring of S between the l_q-th and r_q-th characters (inclusive).

Constraints

N, Q, i_q, l_q, and r_q are integers.

S is a string consisting of lowercase English letters.

c_q is a lowercase English letter.

1 \leq N \leq 500000

1 \leq Q \leq 20000

|S| = N

1 \leq i_q \leq N

1 \leq l_q \leq r_q \leq N

There is at least one query of type 2 in each testcase.

Input

Input is given from Standard Input in the following format:

N
S
Q
Query_1
\vdots
Query_Q

Here, Query_i in the 4-th through (Q+3)-th lines is one of the following:

1 i_q c_q

2 l_q r_q

Output

For each query of type 2, print a line containing the answer.

Sample Input 1

7
abcdbbd
6
2 3 6
1 5 z
2 1 1
1 4 a
1 7 d
2 1 7

Sample Output 1

3
1
5

In the first query, cdbb contains three kinds of letters: b , c , and d, so we print 3.

In the second query, S is modified to abcdzbd.

In the third query, a contains one kind of letter: a, so we print 1.

In the fourth query, S is modified to abcazbd.

In the fifth query, S does not change and is still abcazbd.

In the sixth query, abcazbd contains five kinds of letters: a, b, c, d, and z, so we print 5.


package main

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

/*********** I/O ***********/

var (
	// ReadString returns a WORD string.
	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)) // for AtCoder
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	// Split sets the split function for the Scanner. The default split function is ScanLines.
	// Split panics if it is called after scanning has started.
	r.Split(bufio.ScanWords)

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

// ReadInt returns an integer.
func ReadInt() int {
	return int(readInt64())
}
func ReadInt2() (int, int) {
	return int(readInt64()), int(readInt64())
}
func ReadInt3() (int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64())
}
func ReadInt4() (int, int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64()), int(readInt64())
}

// ReadInt64 returns as integer as int64.
func ReadInt64() int64 {
	return readInt64()
}
func ReadInt64_2() (int64, int64) {
	return readInt64(), readInt64()
}
func ReadInt64_3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func ReadInt64_4() (int64, int64, int64, int64) {
	return readInt64(), readInt64(), readInt64(), readInt64()
}

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

// ReadIntSlice returns an integer slice that has n integers.
func ReadIntSlice(n int) []int {
	b := make([]int, n)
	for i := 0; i < n; i++ {
		b[i] = ReadInt()
	}
	return b
}

// ReadInt64Slice returns as int64 slice that has n integers.
func ReadInt64Slice(n int) []int64 {
	b := make([]int64, n)
	for i := 0; i < n; i++ {
		b[i] = ReadInt64()
	}
	return b
}

// ReadFloat64 returns an float64.
func ReadFloat64() float64 {
	return float64(readFloat64())
}

func readFloat64() float64 {
	f, err := strconv.ParseFloat(ReadString(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// ReadFloatSlice returns an float64 slice that has n float64.
func ReadFloat64Slice(n int) []float64 {
	b := make([]float64, n)
	for i := 0; i < n; i++ {
		b[i] = ReadFloat64()
	}
	return b
}

// ReadRuneSlice returns a rune slice.
func ReadRuneSlice() []rune {
	return []rune(ReadString())
}

/*********** Debugging ***********/

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

// 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
	}
}

// PrintIntsLine returns integers string delimited by a space.
func PrintIntsLine(A ...int) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// PrintIntsLine returns integers string delimited by a space.
func PrintInts64Line(A ...int64) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.FormatInt(A[i], 10) // 64bit int version
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// PrintDebug is wrapper of fmt.Fprintf(os.Stderr, format, a...)
func PrintDebug(format string, a ...interface{}) {
	fmt.Fprintf(os.Stderr, format, a...)
}

/********** FAU standard libraries **********/

//fmt.Sprintf("%b\n", 255) 	// binary expression

/********** I/O usage **********/

//str := ReadString()
//i := ReadInt()
//X := ReadIntSlice(n)
//S := ReadRuneSlice()
//a := ReadFloat64()
//A := ReadFloat64Slice(n)

//str := ZeroPaddingRuneSlice(num, 32)
//str := PrintIntsLine(X...)

/*
ASCII code

ASCII   10進数  ASCII   10進数  ASCII   10進数
!       33      "       34      #       35
$       36      %       37      &       38
'       39      (       40      )       41
*       42      +       43      ,       44
-       45      .       46      /       47
0       48      1       49      2       50
3       51      4       52      5       53
6       54      7       55      8       56
9       57      :       58      ;       59
<       60      =       61      >       62
?       63      @       64      A       65
B       66      C       67      D       68
E       69      F       70      G       71
H       72      I       73      J       74
K       75      L       76      M       77
N       78      O       79      P       80
Q       81      R       82      S       83
T       84      U       85      V       86
W       87      X       88      Y       89
Z       90      [       91      \       92
]       93      ^       94      _       95
`       96      a       97      b       98
c       99      d       100     e       101
f       102     g       103     h       104
i       105     j       106     k       107
l       108     m       109     n       110
o       111     p       112     q       113
r       114     s       115     t       116
u       117     v       118     w       119
x       120     y       121     z       122
{       123     |       124     }       125
~       126             127
*/

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

const (
	// General purpose
	MOD          = 1000000000 + 7
	ALPHABET_NUM = 26
	INF_INT64    = math.MaxInt64
	INF_BIT60    = 1 << 60
	INF_INT32    = math.MaxInt32
	INF_BIT30    = 1 << 30
	NIL          = -1

	// for dijkstra, prim, and so on
	WHITE = 0
	GRAY  = 1
	BLACK = 2
)

var (
	n int
	S []rune
	q int
)

// [1, n]
var bit [ALPHABET_NUM][100000 + 5]int
var lenS int

func sum(i, alpha int) int {
	s := 0

	for i > 0 {
		s += bit[alpha][i]
		i -= i & (-i)
	}

	return s
}

func add(i, alpha, x int) {
	for i <= lenS {
		bit[alpha][i] += x
		i += i & (-i)
	}
}

func main() {
	n = ReadInt()
	S = ReadRuneSlice()
	q = ReadInt()
	lenS = len(S)

	for i := 0; i < len(S); i++ {
		r := S[i]
		c := int(r - 'a')
		add(i+1, c, 1)
	}

	for i := 0; i < q; i++ {
		query := ReadInt()
		if query == 1 {
			idx := ReadInt()
			R := ReadRuneSlice()
			newc := R[0]
			newcint := int(newc - 'a')
			oldc := S[idx-1]
			oldcint := int(oldc - 'a')

			add(idx, newcint, 1)
			add(idx, oldcint, -1)
			S[idx-1] = newc
		} else {
			l, r := ReadInt2()
			res := 0
			for alpha := 0; alpha < ALPHABET_NUM; alpha++ {
				ss := sum(r, alpha) - sum(l-1, alpha)
				if ss > 0 {
					res++
				}
			}
			fmt.Println(res)
		}
	}
}

/*
- まずは全探索を検討しましょう
- MODは最後にとりましたか？
- ループを抜けた後も処理が必要じゃありませんか？
- 和・積・あまりを求められたらint64が必要ではありませんか？
- いきなりオーバーフローはしていませんか？
- MOD取る系はint64必須ですよ？
- 後ろ・逆・ゴールから考えましたか？
- 3者のうち真ん中に着目しましたか？
*/

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


package main

import "fmt"

func main() {
	N, R := read(), read()

	if N >= 10 {
		fmt.Println(R)
		return
	} else {
		fmt.Println(R + 1000 - 100*N)
	}
}

func read() int {
	var v int
	fmt.Scan(&v)
	return v
}

Score : 100 points

Problem Statement

Takahashi is a member of a programming competition site, ButCoder.

Each member of ButCoder is assigned two values: Inner Rating and Displayed Rating.

The Displayed Rating of a member is equal to their Inner Rating if the member has participated in 10 or more contests. Otherwise, the Displayed Rating will be their Inner Rating minus 100 \times (10 - K) when the member has participated in K contests.

Takahashi has participated in N contests, and his Displayed Rating is R. Find his Inner Rating.

Constraints

All values in input are integers.

1 \leq N \leq 100

0 \leq R \leq 4111

Input

Input is given from Standard Input in the following format:

N R

Output

Print his Inner Rating.

Sample Input 1

2 2919

Sample Output 1

3719

Takahashi has participated in 2 contests, which is less than 10, so his Displayed Rating is his Inner Rating minus 100 \times (10 - 2) = 800.

Thus, Takahashi's Inner Rating is 2919 + 800 = 3719.

Sample Input 2

22 3051

Sample Output 2

3051


package main

import (
	"fmt"
)

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

	if N >= 10 {
		fmt.Println(R)
	} else {
		fmt.Println(R + 100*(10-N))
	}
}


package main

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

var stdin = bufio.NewScanner(os.Stdin)

func main() {
	stdin.Split(bufio.ScanWords)
	N := nextInt()
	x := make([]int, N)
	total := 0
	for i := 0; i < N; i++ {
		x[i] = nextInt()
		total += x[i]
	}
	if N == 1 {
		fmt.Println(0)
		os.Exit(0)
	}
	sort.Ints(x)

	avg := total / N
	min := 10000000
	for j := (avg - x[0]) / 2; j < (avg+x[N-1])/2; j++ {
		tmp := 0
		for i := 0; i < N; i++ {
			tmp += (x[i] - j) * (x[i] - j)
		}
		if tmp < min {
			min = tmp
		}
	}
	fmt.Println(min)
}

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

Score : 300 points

Problem Statement

There are N people living on a number line.

The i-th person lives at coordinate X_i.

You are going to hold a meeting that all N people have to attend.

The meeting can be held at any integer coordinate. If you choose to hold the meeting at coordinate P, the i-th person will spend (X_i - P)^2 points of stamina to attend the meeting.

Find the minimum total points of stamina the N people have to spend.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq X_i \leq 100

Input

Input is given from Standard Input in the following format:

N
X_1 X_2 ... X_N

Output

Print the minimum total stamina the N people have to spend.

Sample Input 1

2
1 4

Sample Output 1

5

Assume the meeting is held at coordinate 2. In this case, the first person will spend (1 - 2)^2 points of stamina, and the second person will spend (4 - 2)^2 = 4 points of stamina, for a total of 5 points of stamina. This is the minimum total stamina that the 2 people have to spend.

Note that you can hold the meeting only at an integer coordinate.

Sample Input 2

7
14 14 2 13 56 2 37

Sample Output 2

2354


package main

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

func main() {
	n := readInt()
	x := make([]int, n)
	for i := range x {
		x[i] = readInt()
	}

	ans := math.MaxInt64
	for p := 1; p < 101; p++ {
		c := 0
		for i := range x {
			c += (x[i] - p) * (x[i] - p)
		}
		ans = min(ans, c)
	}

	fmt.Println(ans)
}

// sort ------------------------------------------------------------

type xxx struct {
	x int
}

type sortArray []xxx

func (s sortArray) Len() int           { return len(s) }
func (s sortArray) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s sortArray) Less(i, j int) bool { return s[i].x < s[j].x }

// -----------------------------------------------------------------

var (
	readString func() string
	readBytes  func() []byte
)

func init() {
	log.SetFlags(log.Lshortfile)
	readString, readBytes = newReadString(os.Stdin)
}

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

	f1 := func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
	f2 := func() []byte {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Bytes()
	}
	return f1, f2
}

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

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

func readFloat64() float64 {
	f, err := strconv.ParseFloat(readString(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

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

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

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

func sum(a []int) int {
	var ret int
	for i := range a {
		ret += a[i]
	}
	return ret
}

func sumFloat64(a []float64) float64 {
	var ret float64
	for i := range a {
		ret += a[i]
	}
	return ret
}

func gcd(m, n int) int {
	for m%n != 0 {
		m, n = n, m%n
	}
	return n
}

func lcm(m, n int) int {
	return m / gcd(m, n) * n
}


package main

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

var sc *bufio.Scanner

func init() {
	// 100MB
	bufsize := 100 * 1024 * 1024
	sc = bufio.NewScanner(os.Stdin)
	sc.Buffer(make([]byte, bufio.MaxScanTokenSize), bufsize)
	sc.Split(bufio.ScanWords)
}
func readInt() int              { return readIntArray(1)[0] }
func readInt2() (int, int)      { a := readIntArray(2); return a[0], a[1] }
func readInt3() (int, int, int) { a := readIntArray(3); return a[0], a[1], a[2] }
func readIntArray(n int) []int {
	s := readStringArray(n)
	a := make([]int, n)
	for i := range a {
		a[i], _ = strconv.Atoi(s[i])
	}
	return a
}
func readString() string            { return readStringArray(1)[0] }
func readString2() (string, string) { a := readStringArray(2); return a[0], a[1] }
func readStringArray(n int) []string {
	a := make([]string, n)
	for i := 0; i < n; i++ {
		sc.Scan()
		a[i] = sc.Text()
	}
	return a
}
func max(ns ...int) int {
	max := ns[0]
	for _, n := range ns {
		if n > max {
			max = n
		}
	}
	return max
}
func min(ns ...int) int {
	min := ns[0]
	for _, n := range ns {
		if n < min {
			min = n
		}
	}
	return min
}
func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

func main() {
	n, a, b := readInt3()

	base := big.NewInt(0).Exp(big.NewInt(2), big.NewInt(int64(n)), nil)
	nca := comb(n, a)
	ncb := comb(n, b)

	result := big.NewInt(0).Sub(
		big.NewInt(0).Sub(
			big.NewInt(0).Sub(
				base, nca,
			), ncb,
		), big.NewInt(1),
	)

	fmt.Printf(big.NewInt(0).Mod(result, big.NewInt(1000000007)).String())

	//fmt.Printf("2**n-1: %s\n", big.NewInt(0).Exp(big.NewInt(2), big.NewInt(int64(n)), nil).String())
	//fmt.Printf("nCa: %s\n", comb(n, a).String())
	//fmt.Printf("nCb: %s\n", comb(n, b).String())
}

//func total(n int) int {
//	var total int
//	for i := 1; i <= n; i++ {
//		c := comb(n, i)
//		//fmt.Println(c)
//		total += c
//	}
//	return total
//}

func comb(n, c int) *big.Int {
	upper := big.NewInt(0).MulRange(1, int64(n))

	ll := big.NewInt(0).MulRange(1, int64(c))

	lr := big.NewInt(0).MulRange(1, int64(n-c))

	lower := big.NewInt(0).Mul(ll, lr)
	result := big.NewInt(0).Div(upper, lower)
	return result
}

Score : 400 points

Problem Statement

Akari has n kinds of flowers, one of each kind.

She is going to choose one or more of these flowers to make a bouquet.

However, she hates two numbers a and b, so the number of flowers in the bouquet cannot be a or b.

How many different bouquets are there that Akari can make?

Find the count modulo (10^9 + 7).

Here, two bouquets are considered different when there is a flower that is used in one of the bouquets but not in the other bouquet.

Constraints

All values in input are integers.

2 \leq n \leq 10^9

1 \leq a < b \leq \textrm{min}(n, 2 \times 10^5)

Input

Input is given from Standard Input in the following format:

n a b

Output

Print the number of bouquets that Akari can make, modulo (10^9 + 7). (If there are no such bouquets, print 0.)

Sample Input 1

4 1 3

Sample Output 1

7

In this case, Akari can choose 2 or 4 flowers to make the bouquet.

There are 6 ways to choose 2 out of the 4 flowers, and 1 way to choose 4, so there are a total of 7 different bouquets that Akari can make.

Sample Input 2

1000000000 141421 173205

Sample Output 2

34076506

Print the count modulo (10^9 + 7).


package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	result := "APPROVED"
	for i:=0; i<n; i++{
		fmt.Scan(&a[i])
		if a[i] % 2 == 0 && a[i] % 3 != 0 && a[i] % 5 != 0{
			result = "DENIED"
		}
	}

	fmt.Println(result)
}

Score: 200 points

Problem Statement

You are an immigration officer in the Kingdom of AtCoder. The document carried by an immigrant has some number of integers written on it, and you need to check whether they meet certain criteria.

According to the regulation, the immigrant should be allowed entry to the kingdom if and only if the following condition is satisfied:

All even numbers written on the document are divisible by 3 or 5.

If the immigrant should be allowed entry according to the regulation, output APPROVED; otherwise, print DENIED.

Notes

The condition in the statement can be rephrased as "If x is an even number written on the document, x is divisible by 3 or 5".
Here "if" and "or" are logical terms.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq A_i \leq 1000

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \dots A_N

Output

If the immigrant should be allowed entry according to the regulation, print APPROVED; otherwise, print DENIED.

Sample Input 1

5
6 7 9 10 31

Sample Output 1

APPROVED

The even numbers written on the document are 6 and 10.

All of them are divisible by 3 or 5, so the immigrant should be allowed entry.

Sample Input 2

3
28 27 24

Sample Output 2

DENIED

28 violates the condition, so the immigrant should not be allowed entry.


package main

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

func main() {

	var n int
	fmt.Scan(&n)

	s := make([]int, n)

	sc := bufio.NewScanner(os.Stdin)
	sc.Scan()

	for i, v := range strings.Split(sc.Text(), " ") {
		s[i], _ = strconv.Atoi(v)
	}

	result := true
	for _, i := range s {
		if i%2 == 1 {
			continue
		}
		if i%3 != 0 && i%5 != 0 {
			result = false
		}
	}
	if result {
		fmt.Println("APPROVED")
	} else {
		fmt.Println("DENIED")
	}
}


package main

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

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

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

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

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

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

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

	n := scanInt()
	a := scanInts(n)

	f := true
	for i := 0; i < n; i++ {
		if a[i]%2 == 0 {
			if !(a[i]%3 == 0 || a[i]%5 == 0) {
				f = false
			}
		}
	}

	if f {
		fmt.Println("APPROVED")
	} else {
		fmt.Println("DENIED")
	}
}


package main

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

func main() {
	var N, input = mrLine(1)
	var check = make(map[string]int)
	var checkb = make([][]string, N[0])

	for i := 0; i < N[0]; i++ {
		check[input[i][0]]++
	}

	var max int

	for name, i := range check {
		if max < i {
			max = i
			checkb[max-1] = []string{name}
		} else if i == max {
			checkb[max-1] = append(checkb[max-1], name)
		}
	}

	qsSort(checkb[max-1])

	for _, name := range checkb[max-1] {
		fmt.Printf("%s\n", name)
	}

	return
}

//round returns rounded integer number
func round(x float64) int {
	if x < float64(int(x))+0.5 {
		return int(x)
	}
	return int(x) + 1
}

//minf returns min{a, b}(a, b: float64)
func minf(a, b float64) float64 {
	if a > b {
		return b
	}
	return a
}

//mini returns min{a, b} (a, b: int)
func mini(a, b int) int {
	if a > b {
		return b
	}
	return a
}

//minf returns max{a, b}(a, b: float64)
func maxf(a, b float64) float64 {
	if a > b {
		return a
	}
	return b
}

//maxi returns max{a, b} (a, b: int)
func maxi(a, b int) int {
	if a > b {
		return a
	}
	return b
}

//pawf paw returns f^num(f:float64)
func pawf(f float64, num int) float64 {
	var result float64 = 1
	for i := 0; num > i; i++ {
		result *= f
	}
	return result
}

//pawi paw returns f^num(f:int)
func pawi(f int, num int) int {
	var result int = 1
	for i := 0; num > i; i++ {
		result *= f
	}
	return result
}

//rLine Read all standard input data
func rLine(line int) [][]string {
	var rdr = bufio.NewReaderSize(os.Stdin, 1000000)
	var buf = make([]byte, 0, 1000000)
	var stringInput [][]string

	for i := 0; i < line; {
		l, p, e := rdr.ReadLine()
		if e != nil {
			panic(e)
		}
		buf = append(buf, l...)
		if !p {
			stringInput = append(stringInput, strings.Split(strings.TrimSpace(conByte(buf)), " "))
			buf = []byte{}
			i++
		}
	}
	return stringInput
}

//irLine Read Standard input data and convert into integer
func irLine(i int) [][]int {
	return alitoas(rLine(i))
}

//mtrLine Read multi-line standard input data
// put the location of data of the number of lines in a first line
//ex:
// 3 5
// 1 2
// 2 3
// 3 5
// you have to put 1, where the number 3 put in the first line
func mrLine(line int) (first []int, other [][]string) {
	var rdr = bufio.NewReaderSize(os.Stdin, 1000000)
	var buf = make([]byte, 0, 1000000)
	var Input []string
	var stringInput [][]string

	{
		l, p, e := rdr.ReadLine()
		if e != nil {
			panic(e)
		}
		buf = append(buf, l...)
		if !p {
			Input = strings.Split(strings.TrimSpace((conByte(buf))), " ")
			buf = []byte{}
		}
	}

	first = itoas(Input)

	for i := 0; i < first[line-1]; {
		l, p, e := rdr.ReadLine()
		if e != nil {
			panic(e)
		}
		buf = append(buf, l...)
		if !p {
			stringInput = append(stringInput, strings.Split(strings.TrimSpace((conByte(buf))), " "))
			buf = []byte{}
			i++
		}
	}
	return first, stringInput
}

//mirLine  Read multi-line standard input data and convert into integer data
// put the location of data of the number of lines in a first line
//ex:
// 3 5
// 1 2
// 2 3
// 3 5
// you have to put 1, where the number 3 put in the first line
func mirLine(line int) (first []int, other [][]int) {
	var f, o = mrLine(line)
	return f, alitoas(o)
}

//itoa converts string to integer
func itoa(s string) int {
	var i, _ = strconv.Atoi(s)
	return i
}

//itoas converts string slice to integer slice
func itoas(S []string) []int {
	var result = make([]int, len(S))
	for i, s := range S {
		result[i] = itoa(s)
	}
	return result
}

//alitoas converts string 2 dimention slice to intger one
func alitoas(S [][]string) [][]int {
	var result = make([][]int, len(S))
	for i, s := range S {
		result[i] = itoas(s)
	}
	return result
}

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

func gcd3(a, b, c int) int {
	return gcd(gcd(a, b), c)
}

//medi3 return median of 3 intger values
func medi3(x, y, z int) int {
	switch {
	case x < y:
		switch {
		case x > z:
			return x
		case z > y:
			return y
		default:
			return z
		}
	default:
		switch {
		case z < y:
			return y
		case x < z:
			return x
		default:
			return z
		}
	}
}

//meds3 return median of 3 stringer values
func meds3(x, y, z string) string {
	switch {
	case x < y:
		switch {
		case x > z:
			return x
		case z > y:
			return y
		default:
			return z
		}
	default:
		switch {
		case z < y:
			return y
		case x < z:
			return x
		default:
			return z
		}
	}
}

//iQuicksort sort integer slice by quick sort
func iQuicksort(a []int, left, right int) {
	if left < right {
		var i, j, tmp int = left, right, 0
		var pivot int = medi3(a[i], a[i+(j-i)/2], a[j])

		for {
			for ; a[i] < pivot; i++ {
			}
			for ; pivot < a[j]; j-- {
			}
			if i >= j {
				break
			}
			tmp = a[i]
			a[i] = a[j]
			a[j] = tmp /* a[i], a[j] を交換 */
			i++
			j--
		}
		iQuicksort(a, left, i-1)  /* 分割した左を再帰的にソート */
		iQuicksort(a, j+1, right) /* 分割した右を再帰的にソート */
	}
}

//qiSort sort integer slie by quick sort
func qiSort(a []int) {
	iQuicksort(a, 0, len(a)-1)
}

//qiSort sort stringer slie by quick sort
func qsSort(a []string) {
	sQuicksort(a, 0, len(a)-1)
}

//iQuicksort sort integer slice by quick sort
func sQuicksort(a []string, left, right int) {
	if left < right {
		var i, j int = left, right
		var tmp string
		var pivot string = meds3(a[i], a[i+(j-i)/2], a[j])

		for {
			for ; a[i] < pivot; i++ {
			}
			for ; pivot < a[j]; j-- {
			}
			if i >= j {
				break
			}
			tmp = a[i]
			a[i] = a[j]
			a[j] = tmp /* a[i], a[j] を交換 */
			i++
			j--
		}
		sQuicksort(a, left, i-1)  /* 分割した左を再帰的にソート */
		sQuicksort(a, j+1, right) /* 分割した右を再帰的にソート */
	}
}

func conStr(s *string) []byte {
	return *(*[]byte)(unsafe.Pointer(s))
}

func conByte(b []byte) string {
	return *(*string)(unsafe.Pointer(&b))
}

Score: 300 points

Problem Statement

We have N voting papers. The i-th vote (1 \leq i \leq N) has the string S_i written on it.

Print all strings that are written on the most number of votes, in lexicographical order.

Constraints

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

S_i (1 \leq i \leq N) are strings consisting of lowercase English letters.

The length of S_i (1 \leq i \leq N) is between 1 and 10 (inclusive).

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

Print all strings in question in lexicographical order.

Sample Input 1

7
beat
vet
beet
bed
vet
bet
beet

Sample Output 1

beet
vet

beet and vet are written on two sheets each, while beat, bed, and bet are written on one vote each. Thus, we should print the strings beet and vet.

Sample Input 2

8
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo

Sample Output 2

buffalo

Sample Input 3

7
bass
bass
kick
kick
bass
kick
kick

Sample Output 3

kick

Sample Input 4

4
ushi
tapu
nichia
kun

Sample Output 4

kun
nichia
tapu
ushi


package main

import "fmt"

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

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

	texts := make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&texts[i])
	}

	var num int
	ans := make([]string, 0)
	maps := make(map[string]int, n)
	// mapで同じものをカウント
	for i := 0; i < n; i++ {
		maps[texts[i]]++
		num = max(maps[texts[i]], num)
	}

	// value(数値)とmaxのカウント数が同じなのであれば、ansに追加
	for key, value := range maps {
		if value == num {
			ans = append(ans, key)
		}
	}

	for _, text := range ans {
		fmt.Println(text)
	}
}


package main

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

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

	N := getInt()
	s := make([]string, N)
	m := make(map[string]int)
	max := 0
	for i := 0; i < N; i++ {
		s[i] = getString()
		m[s[i]]++
		if max < m[s[i]] {
			max = m[s[i]]
		}
	}
	sel := make([]string, 0)
	for i, v := range m {
		if v == max {
			sel = append(sel, i)
		}
	}

	sort.Strings(sel)
	for _, v := range sel {
		fmt.Println(v)
	}
}


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(A ...*int) {
  L := strings.Split(NextLine(), " ")
  for i, a := range A {
    *a, _ = strconv.Atoi(L[i])
  }
}
func NextIntVec(A *[]int) {
  L := strings.Split(NextLine(), " ")
  (*A) = make([]int, len(L))
  for i, l := range L {
    (*A)[i], _ = strconv.Atoi(l)
  }
}
func NextFloat(A ...*float64) {
  L := strings.Split(NextLine(), " ")
  for i, a := range A {
    *a, _ = strconv.ParseFloat(L[i], 64)
  }
}
func NextFloatVec(A *[]float64) {
  L := strings.Split(NextLine(), " ")
  (*A) = make([]float64, len(L))
  for i, l := range L {
    (*A)[i], _ = strconv.ParseFloat(l, 64)
  }
}
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 MinInt(A ...int) int {
  min := A[0]
  for _, a := range A {
    if a < min { min = a }
  }
  return min
}

func Solve() {
  N := NextLine()
  n := len(N)
  ans := 0
  c, d := 0, 0
  for i := n - 1; 0 <= i; i-- {
    C := int(N[i]) - int('0') + c
    if C < 5 {
      ans += C - d
      c = 0
      d = 0
    } else if C == 5 {
      ans += C
      c = 1
      d++
    } else {
      ans += 10 - C
      c = 1
      d = 0
    }
  }
  Write(ans + c - d)
  return
}

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

Score: 500 points

Problem Statement

In the Kingdom of AtCoder, only banknotes are used as currency. There are 10^{100}+1 kinds of banknotes, with the values of 1, 10, 10^2, 10^3, \dots, 10^{(10^{100})}. You have come shopping at a mall and are now buying a takoyaki machine with a value of N. (Takoyaki is the name of a Japanese snack.)

To make the payment, you will choose some amount of money which is at least N and give it to the clerk. Then, the clerk gives you back the change, which is the amount of money you give minus N.

What will be the minimum possible number of total banknotes used by you and the clerk, when both choose the combination of banknotes to minimize this count?

Assume that you have sufficient numbers of banknotes, and so does the clerk.

Constraints

N is an integer between 1 and 10^{1,000,000} (inclusive).

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum possible number of total banknotes used by you and the clerk.

Sample Input 1

36

Sample Output 1

8

If you give four banknotes of value 10 each, and the clerk gives you back four banknotes of value 1 each, a total of eight banknotes are used.

The payment cannot be made with less than eight banknotes in total, so the answer is 8.

Sample Input 2

91

Sample Output 2

3

If you give two banknotes of value 100, 1, and the clerk gives you back one banknote of value 10, a total of three banknotes are used.

Sample Input 3

314159265358979323846264338327950288419716939937551058209749445923078164062862089986280348253421170

Sample Output 3

243