package main

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

func main() {
	sc := NewScanner()
	N := sc.NextInt()
	A := sc.NextLine()
	B := sc.NextLine()
	C := sc.NextLine()

	ans := 0
	for i := 0; i < N; i++ {
		mp := map[byte]bool{}
		mp[A[i]] = true
		mp[B[i]] = true
		mp[C[i]] = true

		if len(mp) == 2 {
			ans += 1
		} else if len(mp) == 3 {
			ans += 2
		}
	}
	fmt.Println(ans)

}

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

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

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

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

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

	return mp
}

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

Score : 200 points

Problem Statement

You are given three strings A, B and C. Each of these is a string of length N consisting of lowercase English letters.

Our objective is to make all these three strings equal. For that, you can repeatedly perform the following operation:

Operation: Choose one of the strings A, B and C, and specify an integer i between 1 and N (inclusive). Change the i-th character from the beginning of the chosen string to some other lowercase English letter.

What is the minimum number of operations required to achieve the objective?

Constraints

1 \leq N \leq 100

Each of the strings A, B and C is a string of length N.

Each character in each of the strings A, B and C is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

N
A
B
C

Output

Print the minimum number of operations required.

Sample Input 1

4
west
east
wait

Sample Output 1

3

In this sample, initially A = west、B = east、C = wait. We can achieve the objective in the minimum number of operations by performing three operations as follows:

Change the second character in A to a. A is now wast.

Change the first character in B to w. B is now wast.

Change the third character in C to s. C is now wast.

Sample Input 2

9
different
different
different

Sample Output 2

0

If A, B and C are already equal in the beginning, the number of operations required is 0.

Sample Input 3

7
zenkoku
touitsu
program

Sample Output 3

13


// ProblemURL : https://atcoder.jp/contests/nikkei2019-qual/tasks/nikkei2019_qual_c
// ---------------------------------------------
package main

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

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}
func diff(a, b int) int {
	if a > b {
		return a - b
	}
	return b - a
}
func larger(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func smaller(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func largest(a, b, c int) (lgst int) {
	if a > b {
		lgst = a
	} else {
		lgst = b
	}
	if c > lgst {
		lgst = c
	}
	return
}
func smallest(a, b, c int) (slst int) {
	if a < b {
		slst = a
	} else {
		slst = b
	}
	if c < slst {
		slst = c
	}
	return
}
func intsMax(a []int) (val int) {
	if len(a) == 0 {
		panic("func intsMax: zero length slice")
	}
	val = a[0]
	for _, aa := range a {
		if aa > val {
			val = aa
		}
	}
	return
}
func intsMaxIdx(a []int) (idx, val int) {
	if len(a) == 0 {
		panic("func intsMaxIdx: zero length slice")
	}
	val = a[0]
	for i, aa := range a {
		if aa > val {
			idx, val = i, aa
		}
	}
	return
}
func intsMin(a []int) (val int) {
	if len(a) == 0 {
		panic("func intsMin: zero length slice")
	}
	val = a[0]
	for _, aa := range a {
		if aa < val {
			val = aa
		}
	}
	return
}
func intsMinIdx(a []int) (idx, val int) {
	if len(a) == 0 {
		panic("func intsMinIdx: zero length slice")
	}
	val = a[0]
	for i, aa := range a {
		if aa < val {
			idx, val = i, aa
		}
	}
	return
}
func intsSum(a []int) int {
	res := 0
	for _, v := range a {
		res += v
	}
	return res
}
func intsAve(s []int) float64 {
	return float64(intsSum(s)) / float64(len(s))
}
func intsAdd(a *[]int, x int)    { *a = append(*a, x) }
func intsDelete(a *[]int, i int) { *a = append((*a)[:i], (*a)[i+1:]...) }
func intsJoin(a, b []int) []int  { return append(a, b...) }
func intsClear(a []int) []int    { return a[:0] }
func intsCopy(a []int) []int     { return append([]int(nil), a...) }
func intsCopySortAsc(a []int) []int {
	s := intsCopy(a)
	sort.Ints(s)
	return s
}
func intsCopySortDesc(a []int) []int {
	s := intsCopy(a)
	sort.Sort(sort.Reverse(sort.IntSlice(s)))
	return s
}
func intsReverse(a []int) {
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
}
func intsFill(a []int, val int) {
	for i := 0; i < len(a); i++ {
		a[i] = val
	}
}
func intsPeekBack(a []int) int {
	if len(a) == 0 {
		panic("func peekBack: zero length slice")
	}
	return a[len(a)-1]
}
func intsPeekFront(a []int) int {
	if len(a) == 0 {
		panic("func peekFront: zero length slice")
	}
	return a[0]
}
func intsPopBack(a *[]int) int {
	if len(*a) == 0 {
		panic("func popBack: zero length slice")
	}
	t := (*a)[len(*a)-1]
	*a = (*a)[:len(*a)-1]
	return t
}
func intsPopFront(a *[]int) int {
	if len(*a) == 0 {
		panic("func popFront: zero length slice")
	}
	h := (*a)[0]
	*a = (*a)[1:]
	return h
}
func intsPushBack(a *[]int, x int) { *a = append(*a, x) }
func intsPushFront(a *[]int, x int) {
	*a = append(*a, 0)
	copy((*a)[1:], (*a)[0:])
	(*a)[0] = x
}
func intsAppendSentinelHead(a *[]int, sentinel int) { intsPushFront(a, sentinel) }
func intsAppendSentinelTail(a *[]int, sentinel int) { intsPushBack(a, sentinel) }
func intsAppendSentinels(a *[]int, sentinel int) {
	intsPushFront(a, sentinel)
	intsPushBack(a, sentinel)
}
func intsIota(n int) []int {
	as := make([]int, n)
	for i := range as {
		as[i] = i
	}
	return as
}
func intsHaveDuplicateElm(a []int) bool {
	m := make(map[int]bool, len(a))
	for _, aa := range a {
		if _, exists := m[aa]; exists {
			return true
		} else {
			m[aa] = true
		}
	}
	return false
}
func isEven(n int) bool     { return n&1 == 0 }
func isOdd(n int) bool      { return n&1 == 1 }
func floor(x float64) int   { return int(x) }
func ceil(x float64) int    { return int(math.Ceil(x)) }
func ceilDiv(x, y int) int  { return ((x) + (y) - 1) / (y) }
func floorDiv(x, y int) int { return (x) / (y) }
func pow(x, y int) int {
	if y < 0 {
		panic("Exponent must be a natural number")
	}
	z := 1
	for ; y != 0; y >>= 1 {
		if y&1 == 1 {
			z *= x
		}
		x *= x
	}
	return z
}
func fact(x int) int {
	fact := 1
	for i := 1; i <= x; i++ {
		fact *= i
	}
	return fact
}
func sigmaK(n int) int  { return n * (n + 1) / 2 }
func sigmaKK(n int) int { return (n * (n + 1) / 2) * (2*n + 1) / 3 }
func euclideanDistance(a, b point) float64 {
	s := diff(a.x, b.x)
	s *= s
	t := diff(a.y, b.y)
	t *= t
	return math.Sqrt(float64(s) + float64(t))
}
func manhattanDistance(a, b point) int {
	s := diff(a.x, b.x)
	t := diff(a.y, b.y)
	return s + t
}
func swap(a, b *int) { *a, *b = *b, *a }
func chmax(a *int, b int) bool {
	if *a < b {
		*a = b
		return true
	}
	return false
}
func chmin(a *int, b int) bool {
	if *a > b {
		*a = b
		return true
	}
	return false
}
func cumsum(a []int) []int {
	b := intsCopy(a)
	for i := 1; i < len(b); i++ {
		b[i] += b[i-1]
	}
	return b
}
func cumsumZeroHead(a []int) []int {
	b := append([]int{0}, a...)
	for i := 1; i < len(b); i++ {
		b[i] += b[i-1]
	}
	return b
}
func runesReverse(a []rune) {
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
	return
}
func bytesReverse(a []byte) {
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
	return
}
func strIsUpperAlphabet(s string) bool {
	if len(s) != 1 {
		panic("wrong arg")
	}
	t := s[0]
	return 'A' <= t && t <= 'Z'
}
func strIsLowerAlphabet(s string) bool {
	if len(s) != 1 {
		panic("wrong arg")
	}
	t := s[0]
	return 'a' <= t && t <= 'z'
}
func strToUpperCase(s string) string { return strings.ToUpper(s) }
func strToLowerCase(s string) string { return strings.ToLower(s) }
func strAlphaUpperCaseToInt(s string) int {
	if len(s) != 1 {
		panic("wrong arg")
	}
	t := s[0]
	if !('A' <= t && t <= 'Z') {
		panic("arg must be upper case alphabet")
	}
	return int(t - 'A')
}
func strAlphaLowerCaseToInt(s string) int {
	if len(s) != 1 {
		panic("wrong arg")
	}
	t := s[0]
	if !('a' <= t && t <= 'z') {
		panic("arg must be lower case alphabet")
	}
	return int(t - 'a')
}
func strCountAlphabets(alphaLower string) (ctAlphas [26]int) {
	ct := [26]int{}
	for _, ss := range alphaLower {
		if !('a' <= ss && ss <= 'z') {
			panic("func strCountAlphabets: argument must be lowercase string")
		}
		ct[ss-'a']++
	}
	return ct
}
func strToInt(s string) int {
	i, err := strconv.Atoi(s)
	if err != nil {
		panic(err)
	}
	return i
}
func intToStr(i int) string           { return strconv.Itoa(i) }
func runeIsUpperAlphabet(r rune) bool { return 'A' <= r && r <= 'Z' }
func runeIsLowerAlphabet(r rune) bool { return 'a' <= r && r <= 'z' }
func CalcMod(a, mod int) int          { return (a%mod + mod) % mod }
func ModSum(a *int, b, mod int)       { *a = (((*a) % mod) + mod + (b % mod)) % mod }
func ModMul(a *int, b, mod int)       { *a = (((*a) % mod) * (b % mod)) % mod }
func ModPow(x, y, mod int) int {
	if y < 0 {
		panic("Exponent must be a natural number")
	}
	z := 1
	for ; y != 0; y >>= 1 {
		if y&1 == 1 {
			z = (z * x) % mod
		}
		x = (x * x) % mod
	}
	return z
}
func ModFact(x, mod int) int {
	fact := 1
	for i := 1; i <= x; i++ {
		fact = fact * i % mod
	}
	return fact
}
func ModInv(x, mod int) int { return ModPow(x, mod-2, mod) }
func initMatrixBool(parentSize, childSize int, initialValue bool) *[][]bool {
	res := make([][]bool, parentSize)
	for i := range res {
		res[i] = make([]bool, childSize)
		for j := range res[i] {
			res[i][j] = initialValue
		}
	}
	return &res
}
func initMatrixInt(parentSize, childSize int, initialValue int) *[][]int {
	res := make([][]int, parentSize)
	for i := range res {
		res[i] = make([]int, childSize)
		for j := range res[i] {
			res[i][j] = initialValue
		}
	}
	return &res
}

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

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

const (
	bwBufSize = 1e6

	alphabetLower = "abcdefghijklmnopqrstuvwxyz"
	alphabetUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

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

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

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

type point struct{ x, y int }

type tuple struct{ a, b, c int }
type byC []tuple

func (p byC) Len() int           { return len(p) }
func (p byC) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
func (p byC) Less(i, j int) bool { return p[i].c < p[j].c }

func solve() {
	n := ri()
	as := make([]int, n)
	bs := make([]int, n)
	for i := 0; i < n; i++ {
		as[i] = ri()
		bs[i] = ri()
	}

	cs := make([]tuple, n)
	for i := 0; i < n; i++ {
		cs[i] = tuple{a: as[i], b: bs[i], c: as[i] + bs[i]}
	}
	sort.Sort(sort.Reverse(byC(cs)))

	score := 0
	for i := range cs {
		if isEven(i) {
			score += cs[i].a
		} else {
			score -= cs[i].b
		}
	}
	pln(score)
}

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

Score : 400 points

Problem Statement

There are N dishes of cuisine placed in front of Takahashi and Aoki.
For convenience, we call these dishes Dish 1, Dish 2, ..., Dish N.

When Takahashi eats Dish i, he earns A_i points of happiness; when Aoki eats Dish i, she earns B_i points of happiness.

Starting from Takahashi, they alternately choose one dish and eat it, until there is no more dish to eat.
Here, both of them choose dishes so that the following value is maximized: "the sum of the happiness he/she will earn in the end" minus "the sum of the happiness the other person will earn in the end".

Find the value: "the sum of the happiness Takahashi earns in the end" minus "the sum of the happiness Aoki earns in the end".

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Output

Print the value: "the sum of the happiness Takahashi earns in the end" minus "the sum of the happiness Aoki earns in the end".

Sample Input 1

3
10 10
20 20
30 30

Sample Output 1

20

In this sample, both of them earns 10 points of happiness by eating Dish 1, 20 points by eating Dish 2, and 30 points by eating Dish 3.

In this case, since Takahashi and Aoki have the same "taste", each time they will choose the dish with which they can earn the greatest happiness. Thus, first Takahashi will choose Dish 3, then Aoki will choose Dish 2, and finally Takahashi will choose Dish 1, so the answer is (30 + 10) - 20 = 20.

Sample Input 2

3
20 10
20 20
20 30

Sample Output 2

20

In this sample, Takahashi earns 20 points of happiness by eating any one of the dishes 1, 2 and 3, but Aoki earns 10 points of happiness by eating Dish 1, 20 points by eating Dish 2, and 30 points by eating Dish 3.

In this case, since only Aoki has likes and dislikes, each time they will choose the dish with which Aoki can earn the greatest happiness. Thus, first Takahashi will choose Dish 3, then Aoki will choose Dish 2, and finally Takahashi will choose Dish 1, so the answer is (20 + 20) - 20 = 20.

Sample Input 3

6
1 1000000000
1 1000000000
1 1000000000
1 1000000000
1 1000000000
1 1000000000

Sample Output 3

-2999999997

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

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 main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)

	nFlowers := scanInt(sc)

	heights := make([]int, nFlowers+1)
	max := 0
	for i := 0; i < nFlowers; i++ {
		heights[i] = scanInt(sc)
		if heights[i] > max {
			max = heights[i]
		}
	}
	heights[nFlowers] = 0

	total := 0
	for min := 0; min < max; min++ {
		cnt := 0
		seq := false
		for _, h := range heights {
			if h <= min {
				if seq {
					cnt += 1
					seq = false
				}
			} else {
				seq = true
			}
		}
		total += cnt
	}

	fmt.Println(total)
}

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

Score : 300 points

Problem Statement

In a flower bed, there are N flowers, numbered 1,2,......,N. Initially, the heights of all flowers are 0.
You are given a sequence h=\{h_1,h_2,h_3,......\} as input. You would like to change the height of Flower k to h_k for all k (1 \leq k \leq N), by repeating the following "watering" operation:

Specify integers l and r. Increase the height of Flower x by 1 for all x such that l \leq x \leq r.

Find the minimum number of watering operations required to satisfy the condition.

Constraints

1 \leq N \leq 100

0 \leq h_i \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 h_3 ...... h_N

Output

Print the minimum number of watering operations required to satisfy the condition.

Sample Input 1

4
1 2 2 1

Sample Output 1

2

The minimum number of watering operations required is 2.
One way to achieve it is:

Perform the operation with (l,r)=(1,3).

Perform the operation with (l,r)=(2,4).

Sample Input 2

5
3 1 2 3 1

Sample Output 2

5

Sample Input 3

8
4 23 75 0 23 96 50 100

Sample Output 3

221


package main

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

var in = bufio.NewScanner(os.Stdin)

func NewxtSlice(num int) []int {

	rep := make([]int, num)
	in.Scan()
	ele := strings.Split(in.Text(), " ")
	for i := 0; i < num; i++ {
		n, _ := strconv.Atoi(ele[i])
		rep[i] = n
	}
	return rep
}
func iszero(num []int) bool {
	for _, v := range num {
		if v == 0 {
			return true
		}
	}
	return false
}
func max(num []int) int {
	max := 0
	for _, v := range num {
		if max < v {
			max = v
		}
	}
	return max
}
func isOrder(num []int) bool {
	for i := 1; i < len(num)-1; i++ {
		if num[i] > num[i-1] && num[i] < num[i+1] {
			continue
		} else {
			return false
		}
	}
	return true
}

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

	rep := NewxtSlice(N)
	temp := 0
	count := 0
	var Maxs []int
LABEL1:
	if iszero(rep) {
		for i := 0; i < N; i++ {
		LABEL2:
			if rep[i] == 0 {
				if i == 0 {
					temp = i + 1
				} else {
					if temp == i {
						temp++
						i++
						goto LABEL2
					} else if isOrder(rep[temp:i]) {
						MaxNum := max(rep[temp:i])
						Maxs = append(Maxs, MaxNum)
						temp = i + 1
					} else {
						for iszero(rep[temp:i]) != true {
							for k := temp; k < i; k++ {
								rep[k]--
							}
							count++
						}
						goto LABEL2
					}
				}
			} else if i == N-1 {
				if isOrder(rep[temp:]) {
					MaxNum := max(rep[temp:])
					Maxs = append(Maxs, MaxNum)
				} else {
					for iszero(rep[temp:i+1]) != true {
						for k := temp; k <= i; k++ {
							rep[k]--
						}
						count++
					}
					temptemp := temp
				LABEL3:
					if iszero(rep[temp : i+1]) {
						for t, v := range rep[temp : i+1] {
							if v == 0 {
								Maxs = append(Maxs, max(rep[temp:temp+t]))
								temp = temp + t + 1
								goto LABEL3
							}
						}
					}
					temp = temptemp
					temp++

					goto LABEL2
				}
			}

		}
	} else {
		for iszero(rep) != true {
			for i := 0; i < len(rep); i++ {
				rep[i]--
			}
			count++
			goto LABEL1
		}
	}

	ans := 0
	for _, v := range Maxs {
		ans += v
	}
	ans += count
	fmt.Println(ans)
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

func readLineToInt() []int {
    sc.Scan()
    line := strings.Split(sc.Text(), " ")
    var intLine []int
    length := len(line)
    for i := 0;i < length; i++ {
        n, _ := strconv.Atoi(line[i])
        intLine = append(intLine, n)
    }
    return intLine
}

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

func main() {
    readInt()
    hList := readLineToInt()
    cnt := 0
    preValue := 0
    for _, value := range hList {
        if preValue < value {
            cnt += value - preValue
        }
        preValue = value
    }
    fmt.Println(cnt)
}


package main

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

const (
	initialBufSize = 100000
	maxBufSize     = 1000000
)

var sc *bufio.Scanner

func initScanner(r io.Reader) *bufio.Scanner {
	buf := make([]byte, initialBufSize)

	sc := bufio.NewScanner(r)
	sc.Buffer(buf, maxBufSize)
	sc.Split(bufio.ScanWords) // bufio.ScanLines
	return sc
}

func main() {
	sc = initScanner(os.Stdin)
	resolve(parseProblem())
}

func parseProblem() string {
	return scanString(sc)
}

const (
	Pre = 0 + iota
	Removing
	Post
)

func resolve(str string) {
	const target = "keyence"
	if strings.HasSuffix(str, target) {
		fmt.Println("YES")
		return
	}
	if str[0:len(target)] == target {
		fmt.Println("YES")
		return
	}
	i := 0
	for ; i < len(str); i++ {
		if str[i] != target[i] {
			break
		}
	}
	if strings.HasSuffix(str, target[i:len(target)]) {
		fmt.Println("YES")
		return
	}
	fmt.Println("NO")
	return
}

// snip-scan-funcs
func scanInt(sc *bufio.Scanner) int {
	sc.Scan()
	i, _ := strconv.Atoi(sc.Text())
	return int(i)
}
func scanString(sc *bufio.Scanner) string {
	sc.Scan()
	return sc.Text()
}

Score : 200 points

Problem Statement

A string is called a KEYENCE string when it can be changed to keyence by removing its contiguous substring (possibly empty) only once.

Given a string S consisting of lowercase English letters, determine if S is a KEYENCE string.

Constraints

The length of S is between 7 and 100 (inclusive).

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S is a KEYENCE string, print YES; otherwise, print NO.

Sample Input 1

keyofscience

Sample Output 1

YES

keyence is an abbreviation of key of science.

Sample Input 2

mpyszsbznf

Sample Output 2

NO

Sample Input 3

ashlfyha

Sample Output 3

NO

Sample Input 4

keyence

Sample Output 4

YES


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

// min, max, asub, absなど基本関数
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 abs(a int) int {
	if a >= 0 {
		return a
	}
	return -a
}

func main() {
	sc.Split(bufio.ScanWords)
	sc.Buffer([]byte{}, 1000000)
	s := getString()

	t := "keyence"
	l := 0
	for i := 0; s[i] == t[i]; i++ {
		l++
		if l == len(t) {
			break
		}
	}
	// out(l)

	rt := "ecneyek"
	r := 0
	for i := 0; i < 7; i++ {
		if s[len(s)-1-i] != rt[i] {
			break
		}
		r++
	}
	// out(r)

	if r+l >= 7 {
		out("YES")
	} else {
		out("NO")
	}

}


// by syu
package main

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

var in = NewScanner(os.Stdin, 0)

func main() {
	s := in.String()
	switch {
	case check(s, "k", "eyence"):
		fallthrough
	case check(s, "ke", "yence"):
		fallthrough
	case check(s, "key", "ence"):
		fallthrough
	case check(s, "keye", "nce"):
		fallthrough
	case check(s, "keyen", "ce"):
		fallthrough
	case check(s, "keyenc", "e"):
		fallthrough
	case check(s, "keyence", ""):
		Rln("YES")
	default:
		Rln("NO")
	}
}
func check(a, x, y string) bool {
	f1 := strings.Index(a, x)
	if f1 < 0 {
		return false
	}
	f2 := strings.Index(a[f1+len(x)-1:], y)
	if f2 < 0 {
		return false
	}
	return true
}

type Scanner struct {
	*bufio.Scanner
}

func NewScanner(r io.Reader, max int) *Scanner {
	s := bufio.NewScanner(r)
	s.Split(scanWords)
	if max <= 0 {
		max = 1048576
	}
	s.Buffer([]byte{}, max)
	return &Scanner{s}
}
func (s *Scanner) String() string {
	s.Scan()
	return s.Text()
}
func isSpace(b byte) bool {
	return b == ' ' || b == '\n' || b == '\r' || b == '\t'
}
func scanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
	start := 0
	for start < len(data) && isSpace(data[start]) {
		start++
	}
	for i := start; i < len(data); i++ {
		if isSpace(data[i]) {
			return i + 1, data[start:i], nil
		}
	}
	if atEOF && len(data) > start {
		return len(data), data[start:], nil
	}
	return start, nil, nil
}
func Rln(s ...interface{}) {
	fmt.Println(s...)
	os.Exit(0)
}

type ByteSlice []byte
type IntSlice []byte


package main

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

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

	happiness := make([][]int, n)
	for i := range happiness {
		happiness[i] = sc.Ints(3)
	}

	m := make([][]int, n)
	for i := range m {
		m[i] = make([]int, 3)
	}
	m[0][0] = happiness[0][0]
	m[0][1] = happiness[0][1]
	m[0][2] = happiness[0][2]

	for i := range happiness[1:] {
		m[i+1][0] = Max(m[i][1], m[i][2]) + happiness[i+1][0]
		m[i+1][1] = Max(m[i][0], m[i][2]) + happiness[i+1][1]
		m[i+1][2] = Max(m[i][0], m[i][1]) + happiness[i+1][2]
	}

	fmt.Println(MaxInts(m[n-1]...))
}

// generated by https://github.com/murosan/gollect

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

func MaxInts(n ...int) int {
	max := n[0]
	for _, v := range n[1:] {
		if v > max {
			max = v
		}
	}
	return max
}

type Scanner struct {
	sc *bufio.Scanner
}

func NewScanner(r io.Reader) *Scanner {
	s := &Scanner{sc: bufio.NewScanner(r)}
	s.sc.Split(bufio.ScanWords)
	return s
}

func (s *Scanner) Bytes() []byte {
	s.sc.Scan()
	return s.sc.Bytes()
}

func (s *Scanner) Int() int { return BytesToInt(s.Bytes()) }

func (s *Scanner) Ints(len int) []int {
	a := make([]int, len)
	for i := 0; i < len; i++ {
		a[i] = s.Int()
	}
	return a
}

func BytesToInt(b []byte) (n int) {
	var i int
	negative := b[0] == 45
	if negative {
		i++
	}
	for ; i < len(b); i++ {
		n = n*10 + int(b[i]-'0')
	}
	if negative {
		return -n
	}
	return
}

Score : 100 points

Problem Statement

Taro's summer vacation starts tomorrow, and he has decided to make plans for it now.

The vacation consists of N days.
For each i (1 \leq i \leq N), Taro will choose one of the following activities and do it on the i-th day:

A: Swim in the sea. Gain a_i points of happiness.

B: Catch bugs in the mountains. Gain b_i points of happiness.

C: Do homework at home. Gain c_i points of happiness.

As Taro gets bored easily, he cannot do the same activities for two or more consecutive days.

Find the maximum possible total points of happiness that Taro gains.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq a_i, b_i, c_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N
a_1 b_1 c_1
a_2 b_2 c_2
:
a_N b_N c_N

Output

Print the maximum possible total points of happiness that Taro gains.

Sample Input 1

3
10 40 70
20 50 80
30 60 90

Sample Output 1

210

If Taro does activities in the order C, B, C, he will gain 70 + 50 + 90 = 210 points of happiness.

Sample Input 2

1
100 10 1

Sample Output 2

100

Sample Input 3

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

Sample Output 3

46

Taro should do activities in the order C, A, B, A, C, B, A.


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

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

func maxs(x ...int) int {
	mv := x[0]
	for _, v := range x[1:] {
		if v > mv {
			mv = v
		}
	}
	return mv
}

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

	aa, ab, ac := make([]int, n+1), make([]int, n+1), make([]int, n+1)
	for i := 1; i <= n; i++ {
		aa[i] = a[i-1] + maxs(ab[i-1], ac[i-1])
		ab[i] = b[i-1] + maxs(aa[i-1], ac[i-1])
		ac[i] = c[i-1] + maxs(aa[i-1], ab[i-1])
	}
	fmt.Println(maxs(aa[n], ab[n], ac[n]))
}


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 main() {
	sc.Split(bufio.ScanWords)
	N := getInt()
	a := make([]int, N)
	b := make([]int, N)
	c := make([]int, N)
	for i := 0; i < N; i++ {
		a[i], b[i], c[i] = getInt(), getInt(), getInt()
	}

	var dp [100000][3]int
	dp[0][0] = a[0]
	dp[0][1] = b[0]
	dp[0][2] = c[0]
	for i := 1; i < N; i++ {
		dp[i][0] = max(dp[i-1][1]+a[i], dp[i-1][2]+a[i])
		dp[i][1] = max(dp[i-1][0]+b[i], dp[i-1][2]+b[i])
		dp[i][2] = max(dp[i-1][0]+c[i], dp[i-1][1]+c[i])
	}

	out(max(dp[N-1][0], max(dp[N-1][1], dp[N-1][2])))

}


package main

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

var scanner = bufio.NewScanner(os.Stdin)
var rdr = bufio.NewReaderSize(os.Stdin, 0x100000)
var wtr = bufio.NewWriter(os.Stdout)

// SplitSpace 空白で分割設定
func SplitSpace() {
	scanner.Split(bufio.ScanWords)
}

// NextLine 標準入力から１行読み込む
func NextLine() string {
	scanner.Scan()
	return scanner.Text()
}

// NextInt 標準入力から数値を一つ読み込む
func NextInt() int {
	n, _ := strconv.Atoi(NextLine())
	return n
}

// ReadLine 標準入力から長めの1行を読み込む
func ReadLine() string {
	buf := make([]byte, 0, 0x100000)
	for {
		line, isPrefix, err := rdr.ReadLine()
		if err != nil {
			panic(err)
		}
		buf = append(buf, line...)
		if !isPrefix {
			break
		}
	}
	return string(buf)
}

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

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

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

func ChMin(a *int, b int) bool {
	if *a > b {
		*a = b
		return true
	}
	return false
}

func ChMax(a *int, b int) bool {
	if *a < b {
		*a = b
		return true
	}
	return false
}

//================

func main() {
	SplitSpace()
	N := NextInt()
	W := NextInt()
	w := make([]int, N)
	v := make([]int, N)
	dp := make([][]int, N+1)
	maxv:=0
	for i := 0; i < N; i++ {
		w[i] = NextInt()
		v[i] = NextInt()
		ChMax( &maxv, v[i] )
	}
	maxv *= N
	for i := 0; i <= N; i++ {
		dp[i] = make([]int, maxv+1)
		for j := 0; j < maxv+1; j++ {
			dp[i][j] = 1 << 29
		}
	}
	dp[0][0] = 0
	for i := 0; i < N; i++ {
		for sv := 0; sv <= maxv; sv++ {
			if sv-v[i] >= 0 {
				ChMin(&dp[i+1][sv], dp[i][sv-v[i]]+w[i])
			}
			ChMin(&dp[i+1][sv], dp[i][sv])
		}
	}
	res := 0
	for i := 0; i < maxv; i++ {
		if dp[N][i] <= W {
			res = i
		}
	}
	fmt.Println(res)
}

Score : 100 points

Problem Statement

There are N items, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), Item i has a weight of w_i and a value of v_i.

Taro has decided to choose some of the N items and carry them home in a knapsack.
The capacity of the knapsack is W, which means that the sum of the weights of items taken must be at most W.

Find the maximum possible sum of the values of items that Taro takes home.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq W \leq 10^9

1 \leq w_i \leq W

1 \leq v_i \leq 10^3

Input

Input is given from Standard Input in the following format:

N W
w_1 v_1
w_2 v_2
:
w_N v_N

Output

Print the maximum possible sum of the values of items that Taro takes home.

Sample Input 1

3 8
3 30
4 50
5 60

Sample Output 1

90

Items 1 and 3 should be taken.
Then, the sum of the weights is 3 + 5 = 8, and the sum of the values is 30 + 60 = 90.

Sample Input 2

1 1000000000
1000000000 10

Sample Output 2

10

Sample Input 3

6 15
6 5
5 6
6 4
6 6
3 5
7 2

Sample Output 3

17

Items 2, 4 and 5 should be taken.
Then, the sum of the weights is 5 + 6 + 3 = 14, and the sum of the values is 6 + 6 + 5 = 17.


package main

import (
	"bufio"
	"flag"
	"fmt"
	"io"
	"math"
	"math/big"
	"os"
)

var reader *bufio.Reader
var writer *bufio.Writer

var inputFile = flag.String("input", "", "")

func init() {
	flag.Parse()
	var i io.Reader
	if *inputFile != "" {
		i, _ = os.Open(*inputFile)
	} else {
		i = os.Stdin
	}
	reader = bufio.NewReaderSize(i, 1<<20)
	writer = bufio.NewWriterSize(os.Stdout, 1<<20)
}

func println(a ...interface{}) {
	_, _ = fmt.Fprintln(writer, a...)
}

func printf(format string, a ...interface{}) {
	_, _ = fmt.Fprintf(writer, format, a...)
}

func scanf(format string, a ...interface{}) {
	_, _ = fmt.Fscanf(reader, format, a...)
}

func scan(a interface{}) {
	_, _ = fmt.Fscan(reader, a)
}

func NextInt64() int64 {
	var res int64
	scan(&res)
	return res
}

func NextInt() int {
	var res int
	scan(&res)
	return res
}

func NextIntArray(n int) []int {
	res := make([]int, n)
	for i := range res {
		scan(&res[i])
	}
	return res
}

func NextInt64Array(n int) []int64 {
	res := make([]int64, n)
	for i := range res {
		scan(&res[i])
	}
	return res
}

func NextString() string {
	var res string
	scan(&res)
	return res
}

func NextBigInt() *big.Int {
	n := new(big.Int)
	n, _ = n.SetString(NextString(), 10)
	return n
}

func AbsInt64(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

func MinInt64(x, y int64) int64 {
	if x < y {
		return x
	}
	return y
}

func MaxInt64(x, y int64) int64 {
	if x > y {
		return x
	}
	return y
}

func main() {
	defer writer.Flush()

	n := NextInt()
	W := NextInt64()

	dp := make([]int64, 100001)

	for i := range dp {
		dp[i] = math.MaxInt64 / 2
	}
	dp[0] = 0

	for i := 0; i < n; i++ {
		w := NextInt64()
		v := NextInt()

		for j := 100000; j >= v; j-- {
			dp[j] = MinInt64(dp[j], dp[j - v] + w)
		}
	}

	answer := int64(0)
	for i := 0; i <= 100000; i++ {
		if dp[i] <= W {
			answer = MaxInt64(answer, int64(i))
		}
	}
	println(answer)
}


package main

import (
	"bufio"
	"flag"
	"fmt"
	"io"
	"math/big"
	"os"
)

var reader *bufio.Reader
var writer *bufio.Writer

var inputFile = flag.String("input", "", "")

func init() {
	flag.Parse()
	var i io.Reader
	if *inputFile != "" {
		i, _ = os.Open(*inputFile)
	} else {
		i = os.Stdin
	}
	reader = bufio.NewReaderSize(i, 1<<20)
	writer = bufio.NewWriterSize(os.Stdout, 1<<20)
}

func println(a ...interface{}) {
	_, _ = fmt.Fprintln(writer, a...)
}

func printf(format string, a ...interface{}) {
	_, _ = fmt.Fprintf(writer, format, a...)
}

func scanf(format string, a ...interface{}) {
	_, _ = fmt.Fscanf(reader, format, a...)
}

func scan(a interface{}) {
	_, _ = fmt.Fscan(reader, a)
}

func NextInt64() int64 {
	var res int64
	scan(&res)
	return res
}

func NextInt() int {
	var res int
	scan(&res)
	return res
}

func NextIntArray(n int) []int {
	res := make([]int, n)
	for i := range res {
		scan(&res[i])
	}
	return res
}

func NextInt64Array(n int) []int64 {
	res := make([]int64, n)
	for i := range res {
		scan(&res[i])
	}
	return res
}

func NextString() string {
	var res string
	scan(&res)
	return res
}

func NextBigInt() *big.Int {
	n := new(big.Int)
	n, _ = n.SetString(NextString(), 10)
	return n
}

func AbsInt64(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

func MinInt64(x, y int64) int64 {
	if x < y {
		return x
	}
	return y
}

func MaxInt64(x, y int64) int64 {
	if x > y {
		return x
	}
	return y
}

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

func main() {
	defer writer.Flush()

	n := NextInt()
	m := NextInt()

	g := make([][]int, n)

	for i := 0; i < m; i++ {
		u := NextInt()
		v := NextInt()

		g[u] = append(g[u], v)
	}

	cache := make([]int, n)
	var solve func(x int ) int

	solve = func(x int ) int {
		if cache[x] != 0 {
			return cache[x]
		}
		for _, to := range g[x] {
			t := solve(to) + 1
			if t > cache[x] {
				cache[x] = t
			}
		}
		return cache[x]
	}

	answer := 0

	for i := 0; i < n; i++ {
		t := solve(i)
		if t > answer {
			answer = t
		}
	}

	println(answer)
}

Score : 100 points

Problem Statement

There is a directed graph G with N vertices and M edges.
The vertices are numbered 1, 2, \ldots, N, and for each i (1 \leq i \leq M), the i-th directed edge goes from Vertex x_i to y_i.
G does not contain directed cycles.

Find the length of the longest directed path in G.
Here, the length of a directed path is the number of edges in it.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq x_i, y_i \leq N

All pairs (x_i, y_i) are distinct.

G does not contain directed cycles.

Input

Input is given from Standard Input in the following format:

N M
x_1 y_1
x_2 y_2
:
x_M y_M

Output

Print the length of the longest directed path in G.

Sample Input 1

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

Sample Output 1

3

The red directed path in the following figure is the longest:

Sample Input 2

6 3
2 3
4 5
5 6

Sample Output 2

2

The red directed path in the following figure is the longest:

Sample Input 3

5 8
5 3
2 3
2 4
5 2
5 1
1 4
4 3
1 3

Sample Output 3

3

The red directed path in the following figure is one of the longest:


package main

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

var (
	N, x, y, z int
	dp         [301][301][301]float64
)

func readVariables() {
	N = nextInt()
	for i := 0; i < N; i++ {
		a := nextInt()
		switch a {
		case 1:
			x++
		case 2:
			y++
		case 3:
			z++
		}
	}
}

func solve(x, y, z int) float64 {
	if x == 0 && y == 0 && z == 0 {
		return 0
	}
	if dp[x][y][z] > 0 {
		return dp[x][y][z]
	}
	result := 0.0
	S := x + y + z
	if x > 0 {
		result += solve(x-1, y, z) * float64(x) / float64(S)
	}
	if y > 0 {
		result += solve(x+1, y-1, z) * float64(y) / float64(S)
	}
	if z > 0 {
		result += solve(x, y+1, z-1) * float64(z) / float64(S)
	}
	result += float64(N) / float64(S)
	dp[x][y][z] = result
	return result
}

func main() {
	readVariables()
	fmt.Println(solve(x, y, z))
}

/* 以下、テンプレート*/

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 は、2つの整数を受け取り、最小値を返します。
func MinInt(x, y int) int {
	if x < y {
		return x
	} else {
		return y
	}
}

//MaxInt は、2つの整数を受け取り、最大値を返します。
func MaxInt(x, y int) int {
	if x < y {
		return y
	} else {
		return x
	}
}

//AbsInt は、整数の絶対値を返します。
func AbsInt(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

//ModPow は整数の累乗関数で、剰余もサポートします。
//base^exponentの値をmoduleで割った余りを返します。
//moduloが1以下の場合には、剰余演算をしません。
//baseが負の値である場合には、返す値が負になることがあります。
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)
}

Score : 100 points

Problem Statement

There are N dishes, numbered 1, 2, \ldots, N.
Initially, for each i (1 \leq i \leq N), Dish i has a_i (1 \leq a_i \leq 3) pieces of sushi on it.

Taro will perform the following operation repeatedly until all the pieces of sushi are eaten:

Roll a die that shows the numbers 1, 2, \ldots, N with equal probabilities, and let i be the outcome. If there are some pieces of sushi on Dish i, eat one of them; if there is none, do nothing.

Find the expected number of times the operation is performed before all the pieces of sushi are eaten.

Constraints

All values in input are integers.

1 \leq N \leq 300

1 \leq a_i \leq 3

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_N

Output

Print the expected number of times the operation is performed before all the pieces of sushi are eaten.
The output is considered correct when the relative difference is not greater than 10^{-9}.

Sample Input 1

3
1 1 1

Sample Output 1

5.5

The expected number of operations before the first piece of sushi is eaten, is 1.
After that, the expected number of operations before the second sushi is eaten, is 1.5.
After that, the expected number of operations before the third sushi is eaten, is 3.
Thus, the expected total number of operations is 1 + 1.5 + 3 = 5.5.

Sample Input 2

1
3

Sample Output 2

3

Outputs such as 3.00, 3.000000003 and 2.999999997 will also be accepted.

Sample Input 3

2
1 2

Sample Output 3

4.5

Sample Input 4

10
1 3 2 3 3 2 3 2 1 3

Sample Output 4

54.48064457488221


package main

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

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

/*********** DP sub-functions ***********/

// ChMin accepts a pointer of integer and a target value.
// If target value is SMALLER than the first argument,
//	then the first argument will be updated by the second argument.
func ChMin(updatedValue *int, target int) bool {
	if *updatedValue > target {
		*updatedValue = target
		return true
	}
	return false
}

// ChMax accepts a pointer of integer and a target value.
// If target value is LARGER than the first argument,
//	then the first argument will be updated by the second argument.
func ChMax(updatedValue *int, target int) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

// NthBit returns nth bit value of an argument.
// n starts from 0.
func NthBit(num, nth int) int {
	return num >> uint(nth) & 1
}

/*********** Arithmetic ***********/

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

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

// DigitSum returns digit sum of a decimal number.
// DigitSum only accept a positive integer.
func DigitSum(n int) int {
	if n < 0 {
		return -1
	}

	res := 0

	for n > 0 {
		res += n % 10
		n /= 10
	}

	return res
}

// Sum returns multiple integers sum.
func Sum(integers ...int) int {
	s := 0

	for _, i := range integers {
		s += i
	}

	return s
}

// CeilInt returns the minimum integer larger than or equal to float(a/b).
func CeilInt(a, b int) int {
	res := a / b
	if a%b > 0 {
		res++
	}
	return res
}

// FloorInt returns the maximum integer smaller than or equal to float(a/b)
func FloorInt(a, b int) int {
	res := a / b
	return res
}

// PowInt is integer version of math.Pow
// PowInt calculate a power by Binary Power (二分累乗法(O(log e))).
func PowInt(a, e int) int {
	if a < 0 || e < 0 {
		panic(errors.New("[argument error]: PowInt does not accept negative integers"))
	}

	if e == 0 {
		return 1
	}

	if e%2 == 0 {
		halfE := e / 2
		half := PowInt(a, halfE)
		return half * half
	}

	return a * PowInt(a, e-1)
}

// AbsInt is integer version of math.Abs
func AbsInt(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

// Gcd returns the Greatest Common Divisor of two natural numbers.
// Gcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Gcd uses the Euclidean Algorithm.
func Gcd(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}
	if a < b {
		a, b = b, a
	}

	// Euclidean Algorithm
	for b > 0 {
		div := a % b
		a, b = b, div
	}

	return a
}

// Lcm returns the Least Common Multiple of two natural numbers.
// Lcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Lcd uses the Euclidean Algorithm indirectly.
func Lcm(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2
	// a' and b' are relatively prime numbers
	// gcd consists of prime numbers, that are included in a and b
	gcd := Gcd(a, b)

	// not (a * b / gcd), because of reducing a probability of overflow
	return (a / gcd) * b
}

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

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

//str := ReadString()
//i := ReadInt()
//X := ReadIntSlice(n)
//S := ReadRuneSlice()

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

const MOD = 1000000000 + 7
const ALPHABET_NUM = 26

var n int
var A []int

var dp [301][301][301]float64

func main() {
	n = ReadInt()
	A = ReadIntSlice(n)

	for i := 0; i <= n; i++ {
		for j := 0; j <= n; j++ {
			for k := 0; k <= n; k++ {
				dp[i][j][k] = -1.0
			}
		}
	}
	dp[0][0][0] = 0.0

	one, two, three := 0, 0, 0
	for _, a := range A {
		if a == 1 {
			one++
		} else if a == 2 {
			two++
		} else if a == 3 {
			three++
		}
	}

	sub(one, two, three)

	fmt.Println(dp[one][two][three])
}

func sub(i, j, k int) float64 {
	if i == 0 && j == 0 && k == 0 {
		return dp[0][0][0]
	}

	if dp[i][j][k] >= -0.1 {
		return dp[i][j][k]
	}

	res := 0.0

	if i-1 >= 0 {
		res += sub(i-1, j, k) * float64(i)
	}
	if j-1 >= 0 {
		res += sub(i+1, j-1, k) * float64(j)
	}
	if k-1 >= 0 {
		res += sub(i, j+1, k-1) * float64(k)
	}
	res += float64(n)
	res *= 1.0 / (float64(i + j + k))

	dp[i][j][k] = res

	return dp[i][j][k]
}

// MODはとったか？
// 遷移だけじゃなくて最後の最後でちゃんと取れよ？

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


package main

import "fmt"

var a [100]int
var n int

func solve(k int) int {
	if k < a[0] {
		return -1
	}

	for i := 0; i < n; i++ {
		s := solve(k - a[i])
		if s < 0 {
			return 1
		}
	}

	return -1
}

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

	if solve(k) < 0 {
		fmt.Println("Second")
	} else {
		fmt.Println("First")
	}
}

Score : 100 points

Problem Statement

There is a set A = \{ a_1, a_2, \ldots, a_N \} consisting of N positive integers.
Taro and Jiro will play the following game against each other.

Initially, we have a pile consisting of K stones.
The two players perform the following operation alternately, starting from Taro:

Choose an element x in A, and remove exactly x stones from the pile.

A player loses when he becomes unable to play.
Assuming that both players play optimally, determine the winner.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq K \leq 10^5

1 \leq a_1 < a_2 < \cdots < a_N \leq K

Input

Input is given from Standard Input in the following format:

N K
a_1 a_2 \ldots a_N

Output

If Taro will win, print First; if Jiro will win, print Second.

Sample Input 1

2 4
2 3

Sample Output 1

First

If Taro removes three stones, Jiro cannot make a move.
Thus, Taro wins.

Sample Input 2

2 5
2 3

Sample Output 2

Second

Whatever Taro does in his operation, Jiro wins, as follows:

If Taro removes two stones, Jiro can remove three stones to make Taro unable to make a move.

If Taro removes three stones, Jiro can remove two stones to make Taro unable to make a move.

Sample Input 3

2 7
2 3

Sample Output 3

First

Taro should remove two stones. Then, whatever Jiro does in his operation, Taro wins, as follows:

If Jiro removes two stones, Taro can remove three stones to make Jiro unable to make a move.

If Jiro removes three stones, Taro can remove two stones to make Jiro unable to make a move.

Sample Input 4

3 20
1 2 3

Sample Output 4

Second

Sample Input 5

3 21
1 2 3

Sample Output 5

First

Sample Input 6

1 100000
1

Sample Output 6

Second


package main

import (
	"fmt"
)

var N int
var a [3000]int64
var result [3001][3001]int64
var UNKNOWN = int64(1000000000) * 3000 * 2

func solve(left, right int) int64 {
	if r := result[left][right]; r != UNKNOWN {
		return r
	}

	// fmt.Println(a[left : N-right])

	if left+right+1 == N {
		return a[left]
	}

	a1 := a[left] - solve(left+1, right)
	a2 := a[N-right-1] - solve(left, right+1)

	var result int64
	if a1 > a2 {
		result = a1
	} else {
		result = a2
	}

	return result
}

func main() {
	fmt.Scan(&N)
	for i := 0; i < N; i++ {
		fmt.Scan(&a[i])
	}

	for i := 0; i <= N; i++ {
		for j := 0; j <= N; j++ {
			result[i][j] = UNKNOWN
		}
	}

	fmt.Println(solve(0, 0))
}

Score : 100 points

Problem Statement

Taro and Jiro will play the following game against each other.

Initially, they are given a sequence a = (a_1, a_2, \ldots, a_N).
Until a becomes empty, the two players perform the following operation alternately, starting from Taro:

Remove the element at the beginning or the end of a. The player earns x points, where x is the removed element.

Let X and Y be Taro's and Jiro's total score at the end of the game, respectively.
Taro tries to maximize X - Y, while Jiro tries to minimize X - Y.

Assuming that the two players play optimally, find the resulting value of X - Y.

Constraints

All values in input are integers.

1 \leq N \leq 3000

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_N

Output

Print the resulting value of X - Y, assuming that the two players play optimally.

Sample Input 1

4
10 80 90 30

Sample Output 1

10

The game proceeds as follows when the two players play optimally (the element being removed is written bold):

Taro: (10, 80, 90, 30) → (10, 80, 90)

Jiro: (10, 80, 90) → (10, 80)

Taro: (10, 80) → (10)

Jiro: (10) → ()

Here, X = 30 + 80 = 110 and Y = 90 + 10 = 100.

Sample Input 2

3
10 100 10

Sample Output 2

-80

The game proceeds, for example, as follows when the two players play optimally:

Taro: (10, 100, 10) → (100, 10)

Jiro: (100, 10) → (10)

Taro: (10) → ()

Here, X = 10 + 10 = 20 and Y = 100.

Sample Input 3

1
10

Sample Output 3

10

Sample Input 4

10
1000000000 1 1000000000 1 1000000000 1 1000000000 1 1000000000 1

Sample Output 4

4999999995

The answer may not fit into a 32-bit integer type.

Sample Input 5

6
4 2 9 7 1 5

Sample Output 5

2

The game proceeds, for example, as follows when the two players play optimally:

Taro: (4, 2, 9, 7, 1, 5) → (4, 2, 9, 7, 1)

Jiro: (4, 2, 9, 7, 1) → (2, 9, 7, 1)

Taro: (2, 9, 7, 1) → (2, 9, 7)

Jiro: (2, 9, 7) → (2, 9)

Taro: (2, 9) → (2)

Jiro: (2) → ()

Here, X = 5 + 1 + 9 = 15 and Y = 4 + 7 + 2 = 13.


package main

import "fmt"

var CYCLE = 1000000007
var N, K int
var a [100]int
var results [100][100001]int

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

func main() {
	fmt.Scan(&N, &K)
	for i := 0; i < N; i++ {
		fmt.Scan(&a[i])
	}

	for j := 0; j <= a[N-1] && j <= K; j++ {
		results[N-1][j] = 1
	}

	for i := N - 2; i >= 0; i-- {
		for j := 0; j <= K; j++ {
			r := results[i+1][j]
			if j > 0 {
				r += results[i][j-1]
			}
			if j-1-a[i] >= 0 {
				r -= results[i+1][j-1-a[i]]
			}
			results[i][j] = r % CYCLE
		}
	}

	fmt.Println(results[0][K])

	// for i := 0; i < N; i++ {
	// 	fmt.Println(results[i][:K+1])
	// }
}

Score : 100 points

Problem Statement

There are N children, numbered 1, 2, \ldots, N.

They have decided to share K candies among themselves.
Here, for each i (1 \leq i \leq N), Child i must receive between 0 and a_i candies (inclusive).
Also, no candies should be left over.

Find the number of ways for them to share candies, modulo 10^9 + 7.
Here, two ways are said to be different when there exists a child who receives a different number of candies.

Constraints

All values in input are integers.

1 \leq N \leq 100

0 \leq K \leq 10^5

0 \leq a_i \leq K

Input

Input is given from Standard Input in the following format:

N K
a_1 a_2 \ldots a_N

Output

Print the number of ways for the children to share candies, modulo 10^9 + 7.

Sample Input 1

3 4
1 2 3

Sample Output 1

5

There are five ways for the children to share candies, as follows:

(0, 1, 3)

(0, 2, 2)

(1, 0, 3)

(1, 1, 2)

(1, 2, 1)

Here, in each sequence, the i-th element represents the number of candies that Child i receives.

Sample Input 2

1 10
9

Sample Output 2

0

There may be no ways for the children to share candies.

Sample Input 3

2 0
0 0

Sample Output 3

1

There is one way for the children to share candies, as follows:

(0, 0)

Sample Input 4

4 100000
100000 100000 100000 100000

Sample Output 4

665683269

Be sure to print the answer modulo 10^9 + 7.


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 bitCount(bits int) int {

	bits = (bits & 0x55555555) + (bits >> 1 & 0x55555555)
	bits = (bits & 0x33333333) + (bits >> 2 & 0x33333333)
	bits = (bits & 0x0f0f0f0f) + (bits >> 4 & 0x0f0f0f0f)
	bits = (bits & 0x00ff00ff) + (bits >> 8 & 0x00ff00ff)
	return (bits & 0x0000ffff) + (bits >> 16 & 0x0000ffff)
}

const mod = 1000000007

func rec(N int, a [22][22]int) int {
	var dp [22][1 << 22]int
	dp[0][0] = 1
	for i := 0; i < N; i++ {
		for bit := 0; bit < 1<<uint(N); bit++ {
			if bitCount(bit) == i {
				for j := 0; j < N; j++ {
					if (bit&(1<<uint(j))) == 0 && a[i][j] != 0 {
						pos := bit | (1 << uint(j))
						dp[i+1][pos] += dp[i][bit]
						dp[i+1][pos] %= mod
					}
				}
			}
		}
	}
	return dp[N][(1<<uint(N))-1]
}

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

	N := getInt()
	var a [22][22]int
	for i := 0; i < N; i++ {
		for j := 0; j < N; j++ {
			a[i][j] = getInt()
		}
	}

	res := rec(N, a)
	out(res)
}

Score : 100 points

Problem Statement

There are N men and N women, both numbered 1, 2, \ldots, N.

For each i, j (1 \leq i, j \leq N), the compatibility of Man i and Woman j is given as an integer a_{i, j}.
If a_{i, j} = 1, Man i and Woman j are compatible; if a_{i, j} = 0, they are not.

Taro is trying to make N pairs, each consisting of a man and a woman who are compatible.
Here, each man and each woman must belong to exactly one pair.

Find the number of ways in which Taro can make N pairs, modulo 10^9 + 7.

Constraints

All values in input are integers.

1 \leq N \leq 21

a_{i, j} is 0 or 1.

Input

Input is given from Standard Input in the following format:

N
a_{1, 1} \ldots a_{1, N}
:
a_{N, 1} \ldots a_{N, N}

Output

Print the number of ways in which Taro can make N pairs, modulo 10^9 + 7.

Sample Input 1

3
0 1 1
1 0 1
1 1 1

Sample Output 1

3

There are three ways to make pairs, as follows ((i, j) denotes a pair of Man i and Woman j):

(1, 2), (2, 1), (3, 3)

(1, 2), (2, 3), (3, 1)

(1, 3), (2, 1), (3, 2)

Sample Input 2

4
0 1 0 0
0 0 0 1
1 0 0 0
0 0 1 0

Sample Output 2

1

There is one way to make pairs, as follows:

(1, 2), (2, 4), (3, 1), (4, 3)

Sample Input 3

1
0

Sample Output 3

0

Sample Input 4

21
0 0 0 0 0 0 0 1 1 0 1 1 1 1 0 0 0 1 0 0 1
1 1 1 0 0 1 0 0 0 1 0 0 0 0 1 1 1 0 1 1 0
0 0 1 1 1 1 0 1 1 0 0 1 0 0 1 1 0 0 0 1 1
0 1 1 0 1 1 0 1 0 1 0 0 1 0 0 0 0 0 1 1 0
1 1 0 0 1 0 1 0 0 1 1 1 1 0 0 0 0 0 0 0 0
0 1 1 0 1 1 1 0 1 1 1 0 0 0 1 1 1 1 0 0 1
0 1 0 0 0 1 0 1 0 0 0 1 1 1 0 0 1 1 0 1 0
0 0 0 0 1 1 0 0 1 1 0 0 0 0 0 1 1 1 1 1 1
0 0 1 0 0 1 0 0 1 0 1 1 0 0 1 0 1 0 1 1 1
0 0 0 0 1 1 0 0 1 1 1 0 0 0 0 1 1 0 0 0 1
0 1 1 0 1 1 0 0 1 1 0 0 0 1 1 1 1 0 1 1 0
0 0 1 0 0 1 1 1 1 0 1 1 0 1 1 1 0 0 0 0 1
0 1 1 0 0 1 1 1 1 0 0 0 1 0 1 1 0 1 0 1 1
1 1 1 1 1 0 0 0 0 1 0 0 1 1 0 1 1 1 0 0 1
0 0 0 1 1 0 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1
1 0 1 1 0 1 0 1 0 0 1 0 0 1 1 0 1 0 1 1 0
0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 1 1 0 0 1
0 0 0 1 0 0 1 1 0 1 0 1 0 1 1 0 0 1 1 0 1
0 0 0 0 1 1 1 0 1 0 1 1 1 0 1 1 0 0 1 1 0
1 1 0 1 1 0 0 1 1 0 1 1 0 1 1 1 1 1 0 1 0
1 0 0 1 1 0 1 1 1 1 1 0 1 0 1 1 0 0 0 0 0

Sample Output 4

102515160

Be sure to print the number modulo 10^9 + 7.


package main
import "fmt"

/*
i 的遍历顺序从最高位到最低位
T(i, prefix_remainder, isEqual) 表示第 i 位、
更高位的数字和 mod D 为 prefix_remainder、
状态为 isEqual(true 表示前缀与 K 的相应前缀相等，false < K 的相应前缀) 的方案数
则 T(hi, 0, true) 为最终答案，其中 hi = K 的最高位对应的 i，
比如：98765，则最高位 i = 5

状态转移：
T(i, prefix_remainder, isEqual) =
Sum{
	T(i-1, prefix_remainder + d_i, isEqual && d_i == d[i])
	0 <= d_i <= 9 if !isEqual = false or d[i] if isEqual
}
其中，d_i 表示在 i 位上的数字选择，d[i] 表示 K 在 i 位上的数字

边界条件：
T(0, any, any) = 1，遍历到 0 意味着个位数字都已经确定完了

下面的具体实现与上述推导不符
*/

const MAXL = 1e5+5
const MAXD = 105
const MOD = 1e9+7

var n int
var D int
var d [MAXL]int
var T [MAXL][MAXD]int

func solve(i int, prefix int, isEqual bool) int {
	if i == n {
      	if prefix == 0 {
        	return 1
      	} else {
        	return 0
      	}
	}
	if !isEqual && T[i][prefix] >= 0 {
		return T[i][prefix]
	}
	maxD := 9
	if isEqual {
		maxD = d[i]
	}
	var sum int64
	for digit := 0; digit <= maxD; digit++ {
      	sum += int64(solve(i+1, (prefix+digit) % D, isEqual && digit == maxD))
	}
	sum %= MOD
	if !isEqual {
      	T[i][prefix] = int(sum)
	}
  	return int(sum)
}

func main() {
	var K string
	fmt.Scanln(&K)
	fmt.Scanln(&D)
	n = len(K)
	for i := 0; i < n; i++ {
      	d[i] = int(K[i] - '0')
	}
	for i := 0; i < n; i++ {
		for j := 0; j < D; j++ {
			T[i][j] = -1
		}
	}

    fmt.Println((solve(0, 0, true) - 1 + MOD) % MOD) // minus 1 for 0
}

Score : 100 points

Problem Statement

Find the number of integers between 1 and K (inclusive) satisfying the following condition, modulo 10^9 + 7:

The sum of the digits in base ten is a multiple of D.

Constraints

All values in input are integers.

1 \leq K < 10^{10000}

1 \leq D \leq 100

Input

Input is given from Standard Input in the following format:

K
D

Output

Print the number of integers satisfying the condition, modulo 10^9 + 7.

Sample Input 1

30
4

Sample Output 1

6

Those six integers are: 4, 8, 13, 17, 22 and 26.

Sample Input 2

1000000009
1

Sample Output 2

2

Be sure to print the number modulo 10^9 + 7.

Sample Input 3

98765432109876543210
58

Sample Output 3

635270834


package main

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

var (
	rdr   = bufio.NewReaderSize(os.Stdin, 1000000)
	reply string
)

func main() {
	var a, b, c int
	fmt.Scan(&a, &b, &c)
	if a+b >= c {
		fmt.Println(b + c)
		return
	}
	fmt.Println(a + 2*b + 1)
}

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

func nextSlice() []string {
	return strings.Split(readLine(), "")
}

func atoi(a []string) (b []int) {
	b = make([]int, len(a))
	for i := range a {
		b[i], _ = strconv.Atoi(a[i])
	}
	return
}

func atof(a []string) (b []float64) {
	b = make([]float64, len(a))
	for i := range a {
		b[i], _ = strconv.ParseFloat(a[i], 64)
	}
	return
}

func scanSlice2(n int) (a []int, b []int) {
	a = make([]int, n)
	b = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i], &b[i])
	}
	return
}

func scanFloatSlice2(n int) (a []float64, b []float64) {
	a = make([]float64, n)
	b = make([]float64, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i], &b[i])
	}
	return
}

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

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

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

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

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

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

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

func yesOrNo(b bool) {
	if b {
		reply = "Yes"
		fmt.Println(reply)
		return
	}
	reply = "No"
	fmt.Println(reply)
}

func yesorNO(b bool) {
	if b {
		reply = "YES"
		fmt.Println(reply)
		return
	}
	reply = "NO"
	fmt.Println(reply)
}

Score : 200 points

Problem Statement

Takahashi has A untasty cookies containing antidotes, B tasty cookies containing antidotes and C tasty cookies containing poison.

Eating a cookie containing poison results in a stomachache, and eating a cookie containing poison while having a stomachache results in a death.
As he wants to live, he cannot eat one in such a situation.
Eating a cookie containing antidotes while having a stomachache cures it, and there is no other way to cure stomachaches.

Find the maximum number of tasty cookies that Takahashi can eat.

Constraints

0 \leq A,B,C \leq 10^9

A,B and C are integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the maximum number of tasty cookies that Takahashi can eat.

Sample Input 1

3 1 4

Sample Output 1

5

We can eat all tasty cookies, in the following order:

A tasty cookie containing poison

An untasty cookie containing antidotes

A tasty cookie containing poison

A tasty cookie containing antidotes

A tasty cookie containing poison

An untasty cookie containing antidotes

A tasty cookie containing poison

Sample Input 2

5 2 9

Sample Output 2

10

Sample Input 3

8 8 1

Sample Output 3

9


package main

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

var in = bufio.NewReader(os.Stdin)
var stdin = bufio.NewScanner(os.Stdin)

func nextInt() int {
	_ = stdin.Scan()
	line, _ := strconv.Atoi(stdin.Text())
	return line
}
func nextInts(num int) []int {
	var a = make([]int, num)
	for i := 0; i < num; i++ {
		a[i] = nextInt()
		//a = append(a, temp)
	}
	sort.Ints(a)
	return a
}
func solve(l, n int, a []int) int {
	count := 0
	var temp int
	for i := 0; i < len(a); i++ {
		if (a[i] - temp) > (a[n-1]-l-temp)*(-1) {
			count += a[i] - temp
			temp = a[i]
		} else if (a[i] - temp) < (a[n-1]-l-temp)*(-1) {
			count += (-1) * (a[n-1] - l - temp)
			temp = a[n-1] - l
		} else {
			if a[i+1]-temp > (a[n-2]-l-temp)*(-1) {
				count += a[i] - temp + a[i+1] - temp
				temp = a[i+1] - temp
				i++
			} else if a[i+1]-temp < (a[n-2]-l-temp)*(-1) {
				{
					count += a[i] - temp + (a[n-2]-l-temp)*(-1)
					temp = a[n-2] - l
					i++
				}

			}
		}
		fmt.Println(i, temp)
	}
	return count
}
func main() {
	var l, n int
	fmt.Fscanf(in, "%d %d¥n", &l, &n)

	x := nextInts(n)
	fmt.Println(x)

	ans := solve(l, n, x)
	fmt.Println(ans)

}

Score : 800 points

Problem Statement

Takahashi Lake has a perimeter of L. On the circumference of the lake, there is a residence of the lake's owner, Takahashi.
Each point on the circumference of the lake has a coordinate between 0 and L (including 0 but not L), which is the distance from the Takahashi's residence, measured counter-clockwise.

There are N trees around the lake; the coordinate of the i-th tree is X_i. There is no tree at coordinate 0, the location of Takahashi's residence.

Starting at his residence, Takahashi will repeat the following action:

If all trees are burnt, terminate the process.

Specify a direction: clockwise or counter-clockwise.

Walk around the lake in the specified direction, until the coordinate of a tree that is not yet burnt is reached for the first time.

When the coordinate with the tree is reached, burn that tree, stay at the position and go back to the first step.

Find the longest possible total distance Takahashi walks during the process.

Partial Score

A partial score can be obtained in this problem:

300 points will be awarded for passing the input satisfying N \leq 2000.

Constraints

2 \leq L \leq 10^9

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

1 \leq X_1 < ... < X_N \leq L-1

All values in input are integers.

Input

Input is given from Standard Input in the following format:

L N
X_1
:
X_N

Output

Print the longest possible total distance Takahashi walks during the process.

Sample Input 1

10 3
2
7
9

Sample Output 1

15

Takahashi walks the distance of 15 if the process goes as follows:

Walk a distance of 2 counter-clockwise, burn the tree at the coordinate 2 and stay there.

Walk a distance of 5 counter-clockwise, burn the tree at the coordinate 7 and stay there.

Walk a distance of 8 clockwise, burn the tree at the coordinate 9 and stay there.

Sample Input 2

10 6
1
2
3
6
7
9

Sample Output 2

27

Sample Input 3

314159265 7
21662711
77271666
89022761
156626166
160332356
166902656
298992265

Sample Output 3

1204124749


package main

import "fmt"

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

	xm := make(map[rune]int)
	for _, r := range n {
		xm[r]++
	}
	fmt.Println(xm['2'])
}

Score : 100 points

Problem Statement

You are given an integer N that has exactly four digits in base ten.
How many times does 2 occur in the base-ten representation of N?

Constraints

1000 \leq N \leq 9999

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

1222

Sample Output 1

3

2 occurs three times in 1222. By the way, this contest is held on December 22 (JST).

Sample Input 2

3456

Sample Output 2

0

Sample Input 3

9592

Sample Output 3

1


package main

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

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

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

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

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

/* sort */
type Int64Slice []int64

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

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

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

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

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

func main() {
	buf := make([]byte, initialBufSize)
	scanner.Buffer(buf, maxBufSize)
	scanner.Split(bufio.ScanWords)
	N, H, W := readInt(), readInt(), readInt()
	A := make([]int64, N)
	B := make([]int64, N)
	for i := int64(0); i < N; i++ {
		A[i], B[i] = readInt(), readInt()
	}
	var ans int64
	for i := int64(0); i < N; i++ {
		ans += min(A[i]/H, B[i]/W)
	}
	fmt.Println(ans)
}

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

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

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

func print() {
	writer.Flush()
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Score : 200 points

Problem Statement

There are N rectangular plate materials made of special metal called AtCoder Alloy.
The dimensions of the i-th material are A_i \times B_i (A_i vertically and B_i horizontally).

Takahashi wants a rectangular plate made of AtCoder Alloy whose dimensions are exactly H \times W.
He is trying to obtain such a plate by choosing one of the N materials and cutting it if necessary.
When cutting a material, the cuts must be parallel to one of the sides of the material.
Also, the materials have fixed directions and cannot be rotated.
For example, a 5 \times 3 material cannot be used as a 3 \times 5 plate.

Out of the N materials, how many can produce an H \times W plate if properly cut?

Constraints

1 \leq N \leq 1000

1 \leq H \leq 10^9

1 \leq W \leq 10^9

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N H W
A_1 B_1
A_2 B_2
:
A_N B_N

Output

Print the answer.

Sample Input 1

3 5 2
10 3
5 2
2 5

Sample Output 1

2

Takahashi wants a 5 \times 2 plate.

The dimensions of the first material are 10 \times 3. We can obtain a 5 \times 2 plate by properly cutting it.

The dimensions of the second material are 5 \times 2. We can obtain a 5 \times 2 plate without cutting it.

The dimensions of the third material are 2 \times 5. We cannot obtain a 5 \times 2 plate, whatever cuts are made. Note that the material cannot be rotated and used as a 5 \times 2 plate.

Sample Input 2

10 587586158 185430194
894597290 708587790
680395892 306946994
590262034 785368612
922328576 106880540
847058850 326169610
936315062 193149191
702035777 223363392
11672949 146832978
779291680 334178158
615808191 701464268

Sample Output 2

8


package main

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

type Entry struct {
	prime int64
	count int64
}

type Entries []Entry

func (es Entries) Len() int {
	return len(es)
}

func (es Entries) Less(i, j int) bool {
	return es[i].count > es[j].count
}

func (es Entries) Swap(i, j int) {
	es[i], es[j] = es[j], es[i]
}

func main() {
	var n, p int64
	fmt.Scanf("%d %d\n", &n, &p)

	primeLimit := int64(math.Sqrt(float64(p)))
	allPrimes := listPrimes(primeLimit)
	entries := countPrimes(p, allPrimes)

	sort.Sort(Entries(entries))

	factor := int64(1)
	for _, e := range entries {
		if e.count >= n {
			v := e.prime * (e.count / n)
			factor *= v
		}
	}

	fmt.Println(factor)
}

func countPrimes(n int64, allPrimes []int64) []Entry {
	es := []Entry{}

	for _, p := range allPrimes {
		if p*p > n {
			break
		}
		cnt := int64(0)
		for n%p == 0 {
			cnt += 1
			n /= p
		}
		if cnt > 0 {
			es = append(es, Entry{p, cnt})
		}
	}
	if n > 1 {
		es = append(es, Entry{n, 1})
	}

	return es
}

func listPrimes(limit int64) []int64 {
	ns := make([]int64, limit-1)
	for i := int64(2); i <= limit; i++ {
		ns[i-2] = i
	}

	divided := make([]bool, limit+1)

	ps := make([]int64, 0)
	for _, n := range ns {
		if divided[n] {
			continue
		}
		ps = append(ps, n)
		for i := n; i < int64(len(divided)); i += n {
			divided[i] = true
		}
	}

	return ps
}

Score : 300 points

Problem Statement

There are N integers a_1, a_2, ..., a_N not less than 1.
The values of a_1, a_2, ..., a_N are not known, but it is known that a_1 \times a_2 \times ... \times a_N = P.

Find the maximum possible greatest common divisor of a_1, a_2, ..., a_N.

Constraints

1 \leq N \leq 10^{12}

1 \leq P \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N P

Output

Print the answer.

Sample Input 1

3 24

Sample Output 1

2

The greatest common divisor would be 2 when, for example, a_1=2, a_2=6 and a_3=2.

Sample Input 2

5 1

Sample Output 2

1

As a_i are positive integers, the only possible case is a_1 = a_2 = a_3 = a_4 = a_5 = 1.

Sample Input 3

1 111

Sample Output 3

111

Sample Input 4

4 972439611840

Sample Output 4

206


package main

import (
	"fmt"
	"math"
)

var memo map[int][]int

func main() {
	memo = make(map[int][]int)

	var n int
	fmt.Scan(&n)
	var p int
	fmt.Scan(&p)

	mp := make(map[int]int)
	for _, a := range fact(p) {
		mp[a] = mp[a] + 1
	}

	direct := 1
	for k, v := range mp {
		if v >= n {
			direct = direct * k
		}
	}
	fmt.Println(direct)

}

func fact(n int) []int {
	_, exist := memo[n]
	if exist {
		return memo[n]
	}

	ret := make([]int, 0)
	flag := false
	for i := 2; i <= int(math.Floor(float64(n)/2)); i++ {
		if (n % i) == 0 {
			ret = append(ret, i)
			ret = append(ret, fact(n/i)...)
			flag = true
			break
		}
	}
	if !flag {
		ret = append(ret, n)
	}
	return ret
}

/*
func isPrime(n int) bool {
	for i := 2; i <= int(math.Floor(float64(n)/2)); i++ {
		if n%i == 0 {
			return false
		}
	}
	return n > 1
}
*/


package main

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

func main() {
	N, P := ReadInt(), ReadInt()
	factors := Factorization(P)
	ans := 1
	for i := 0; i < len(factors); i++ {
		factor, cnt := factors[i][0], factors[i][1]
		ans *= Pow(factor, cnt/N)
	}
	fmt.Println(ans)
}

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

func Factorization(n int) [][]int {
	res := [][]int{}
	for i := 2; i*i <= n; i++ {
		if n%i != 0 {
			continue
		}
		cnt := 0
		for n%i == 0 {
			n /= i
			cnt++
		}
		res = append(res, []int{i, cnt})
	}
	if n != 1 {
		res = append(res, []int{n, 1})
	}
	return res
}

var reader = bufio.NewReader(os.Stdin)

func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(reader, a...); err != nil {
		panic(err)
	}
}
func ReadInt() (i int)       { Scan(&i); return }
func ReadString() (s string) { Scan(&s); return }
func ReadInts(n int) []int {
	v := make([]int, n)
	for i := 0; i < n; i++ {
		Scan(&v[i])
	}
	return v
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

func swap(a int64, b int64) (int64, int64) {
	return b, a
}

func GCD(a int64, b int64) int64 {
	if b > a {
		a, b = swap(a, b)
	}
	if b == 0 {
		return a
	} else {
		return GCD(a%b, b)
	}
}

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

func nextLong() int64 {
	sc.Scan()
	i, e := strconv.ParseInt(sc.Text(),10,64)
	if e != nil {
		panic(e)
	}
	return i
}

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

func CheckniconiLevel(s []rune) int {
	n := len(s)
	mx := 0
	tmp := 0
	fmt.Printf("%d\n", n)
	for i := 0; i < n-1; i++ {
		if s[i] == '2' && s[i+1] == '5' {
			tmp += 2
			i += 1
			mx = int(math.Max(float64(tmp), float64(mx)))
		} else {
			tmp = 0
		}
	}
	return int(mx)
}

func main() {
	sc.Split(bufio.ScanWords)
	ans := 1
	N := nextLong()
	P := nextLong()
	var times int64
	times=1
	if N==1{
		fmt.Printf("%d\n", P)
		return
	}
	for i:=2; i<=int(math.Sqrt(float64(P)));i++{
		var tmp int64
		tmp=1
		times=0
		for{
			times++
			tmp*=int64(i)
			if tmp*times>=P || times==N-1{
				break
			}
		}
		if(times<=N && P%tmp==0){
		ans = int(math.Max(float64(ans),math.Min(float64(i), float64(GCD(P/tmp,int64(i))))))
		}
	}
	fmt.Printf("%d\n", ans)
}


package main

import "fmt"

func main() {
	var s string
	var total, wtotal int
	fmt.Scanf("%s\n", &s)

	for i := 0; i < len(s); i++ {

		if string(s[i]) == "W" {
			total += i - wtotal
			wtotal++
		}
	}
	fmt.Println(total)

}

Score : 300 points

Problem Statement

There are N Reversi pieces arranged in a row. (A Reversi piece is a disc with a black side and a white side.)
The state of each piece is represented by a string S of length N.
If S_i=B, the i-th piece from the left is showing black;
If S_i=W, the i-th piece from the left is showing white.

Consider performing the following operation:

Choose i (1 \leq i < N) such that the i-th piece from the left is showing black and the (i+1)-th piece from the left is showing white, then flip both of those pieces. That is, the i-th piece from the left is now showing white and the (i+1)-th piece from the left is now showing black.

Find the maximum possible number of times this operation can be performed.

Constraints

1 \leq |S| \leq 2\times 10^5

S_i=B or W

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum possible number of times the operation can be performed.

Sample Input 1

BBW

Sample Output 1

2

The operation can be performed twice, as follows:

Flip the second and third pieces from the left.

Flip the first and second pieces from the left.

Sample Input 2

BWBWBW

Sample Output 2

6


package main

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

var sc = bufio.NewScanner(os.Stdin)
var rdr = bufio.NewReaderSize(os.Stdin, 100000)

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

func main() {
	s := readLine()

	ans := int64(0)
	cnt := 0
	for i, ch := range s {
		if ch == 'W' {
			ans += int64(i - cnt)
			cnt++
		}
	}

	fmt.Println(ans)
}

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

func readLine() string {
	buf := make([]byte, 0, 100000)
	for {
		l, p, e := rdr.ReadLine()
		if e != nil {
			panic(e)
		}
		buf = append(buf, l...)
		if !p {
			break
		}
	}
	return string(buf)
}

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

func nextI64() int64 {
	sc.Scan()
	i, e := strconv.ParseInt(sc.Text(), 10, 64)
	if e != nil {
		panic(e)
	}
	return i
}

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

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

func anser(b bool, y string, n string) string {
	if b {
		return y
	}
	return n
}


package main

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

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

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

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

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

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

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

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

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

	scanner := getScanner(fp)
	writer := bufio.NewWriter(wfp)
	solve(scanner, writer)
	for i := 0; i < cnt; i++ {
		solve(scanner, writer)
	}
	writer.Flush()
}

func solve(scanner *bufio.Scanner, writer *bufio.Writer) {
	n := getNextInt(scanner)
	aa := make([]int, n)
	im := IntMap{}

	for i := 0; i < n; i++ {
		aa[i] = getNextInt(scanner)
		im.increment(aa[i])
	}

	sort.Ints(aa)

	ans := 0
	for i := n - 1; i >= 0; i-- {
		if im.get(aa[i]) == 0 {
			continue
		}
		im[aa[i]] = im.get(aa[i]) - 1
		for j := 30; j >= 0; j-- {
			p := 1<<uint(j) - aa[i]
			if im.get(p) == 0 {
				continue
			}
			im[p] = im.get(p) - 1
			ans++
			break
		}
	}

	fmt.Fprintln(writer, ans)
}

// IntMap ...
type IntMap map[int]int

func (m IntMap) get(key int) int {
	if _, ok := m[key]; ok {
		return m[key]
	}
	return 0
}

func (m IntMap) increment(key int) {
	m[key] = m.get(key) + 1
}

Score : 600 points

Problem Statement

Takahashi has N balls with positive integers written on them. The integer written on the i-th ball is A_i.
He would like to form some number of pairs such that the sum of the integers written on each pair of balls is a power of 2.
Note that a ball cannot belong to multiple pairs.
Find the maximum possible number of pairs that can be formed.

Here, a positive integer is said to be a power of 2 when it can be written as 2^t using some non-negative integer t.

Constraints

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

1 \leq A_i \leq 10^9

A_i is an integer.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible number of pairs such that the sum of the integers written on each pair of balls is a power of 2.

Sample Input 1

3
1 2 3

Sample Output 1

1

We can form one pair whose sum of the written numbers is 4 by pairing the first and third balls.
Note that we cannot pair the second ball with itself.

Sample Input 2

5
3 11 14 5 13

Sample Output 2

2


package main

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

const (
	initialBufSize = 1e4
	maxBufSize     = 1e8
)

var sc = bufio.NewScanner(os.Stdin)

func init() {
	buf := make([]byte, initialBufSize)
	sc.Buffer(buf, maxBufSize)
	sc.Split(bufio.ScanWords)
}

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

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

func sum(x []int) int {
	s := x[0]
	for i := 1; i < len(x); i++ {
		s += x[i]
	}
	return s
}

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

func main() {
	N := nextInt()
	p := make([]int, N)
	for i := 0; i < N; i++ {
		p[i] = nextInt()
	}
	fmt.Println(sum(p) - max(p)/2)
}

Score : 200 points

Problem Statement

In some other world, today is the day before Christmas Eve.

Mr. Takaha is buying N items at a department store. The regular price of the i-th item (1 \leq i \leq N) is p_i yen (the currency of Japan).

He has a discount coupon, and can buy one item with the highest price for half the regular price. The remaining N-1 items cost their regular prices. What is the total amount he will pay?

Constraints

2 \leq N \leq 10

100 \leq p_i \leq 10000

p_i is an even number.

Input

Input is given from Standard Input in the following format:

N
p_1
p_2
:
p_N

Output

Print the total amount Mr. Takaha will pay.

Sample Input 1

3
4980
7980
6980

Sample Output 1

15950

The 7980-yen item gets the discount and the total is 4980 + 7980 / 2 + 6980 = 15950 yen.

Note that outputs such as 15950.0 will be judged as Wrong Answer.

Sample Input 2

4
4320
4320
4320
4320

Sample Output 2

15120

Only one of the four items gets the discount and the total is 4320 / 2 + 4320 + 4320 + 4320 = 15120 yen.


package main

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

var sc = bufio.NewScanner(os.Stdin)

func maxScanTokenSize(size int) {
	buf := make([]byte, 0, size)
	sc.Buffer(buf, size)
}

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

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

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

func scanTwoInts() (int, int) {
	var a, b int
	fmt.Scan(&a, &b)
	return a, b
}

func scanThreeInts() (int, int, int) {
	var a, b, c int
	fmt.Scan(&a, &b, &c)
	return a, b, c
}

func main() {
	// maxScanTokenSize(100000)
	// sc.Split(bufio.ScanWords)

	N := nextInt()

	max := 0
	ans := 0
	for i := 0; i < N; i++ {
		p := nextInt()
		ans += p
		if p > max {
			max = p
		}
	}
	ans -= max / 2
	fmt.Println(ans)
}


package main

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

var N, K int
var hist map[int]int
var low, high int

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

	fmt.Sscanf(scanner.Text(), "%d %d", &N, &K)

	hist = make(map[int]int)
	for i := 0; i < N; i++ {
		var v int
		scanner.Scan()
		fmt.Sscanf(scanner.Text(), "%d", &v)
		hist[v] = hist[v] + 1
		low = min(low, v)
		high = max(high, v)
	}

	index := sort.Search(N, func(i int) bool {
		return check(i)
	})
	fmt.Println(index)
}

func check(width int) bool {
	for i := low; i <= high-width; i++ {
		sum := 0
		for j := 0; j <= width; j++ {
			sum = sum + hist[i+j]
		}
		if sum >= K {
			return true
		}
	}
	return false
}

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
}

Score : 300 points

Problem Statement

In some other world, today is Christmas Eve.

There are N trees planted in Mr. Takaha's garden. The height of the i-th tree (1 \leq i \leq N) is h_i meters.

He decides to choose K trees from these trees and decorate them with electric lights. To make the scenery more beautiful, the heights of the decorated trees should be as close to each other as possible.

More specifically, let the height of the tallest decorated tree be h_{max} meters, and the height of the shortest decorated tree be h_{min} meters. The smaller the value h_{max} - h_{min} is, the better. What is the minimum possible value of h_{max} - h_{min}?

Constraints

2 \leq K < N \leq 10^5

1 \leq h_i \leq 10^9

h_i is an integer.

Input

Input is given from Standard Input in the following format:

N K
h_1
h_2
:
h_N

Output

Print the minimum possible value of h_{max} - h_{min}.

Sample Input 1

5 3
10
15
11
14
12

Sample Output 1

2

If we decorate the first, third and fifth trees, h_{max} = 12, h_{min} = 10 so h_{max} - h_{min} = 2. This is optimal.

Sample Input 2

5 3
5
7
5
7
7

Sample Output 2

0

If we decorate the second, fourth and fifth trees, h_{max} = 7, h_{min} = 7 so h_{max} - h_{min} = 0. This is optimal.

There are not too many trees in these sample inputs, but note that there can be at most one hundred thousand trees (we just can't put a sample with a hundred thousand lines here).


package main

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

func Calc(i []int, n, k int) int {
	mn := math.MaxInt32
	for j := 0; j < n-k+1; j++ {
		diff := i[j+k-1] - i[j]
		if diff < mn {
			mn = diff
		}
		fmt.Println(j+k-1, j)
	}
	return mn
}
func HeightInput(num int) []int {
	var mat = make([]int, num)
	for i := 0; i < num; i++ {
		mat[i] = nextInt()
	}
	// sort.Sort(sort.IntSlice(mat))
	sort.Ints(mat)
	return mat
}
func nextInt() int {
	var stdin = bufio.NewScanner(os.Stdin)
	stdin.Split(bufio.ScanWords)

	_ = stdin.Scan()
	line, _ := strconv.Atoi(stdin.Text())
	return line
}
func main() {
	n := nextInt()
	k := nextInt()

	hei := HeightInput(n)
	ans := Calc(hei, n, k)
	fmt.Println(hei)
	fmt.Println(ans)
}


package main

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

func main() {
	var N, X uint
	fmt.Scan(&N, &X)

	debug("X=%d\n", X)
	//時間がかかるので文字列を直接求めるのはダメ
	/*
		barger := makeBarger(N)
		debug("level:%d -> %s\n", N, barger)
	*/
	debug("length->%d\n", bargerLength(N))
	debug("all p num -> %d\n", countP(N))
	fmt.Printf("%d\n", eatP(N, X))
}

var bargers = make(map[uint]string)

//levelのハンバーガをしたからx枚食べた時のPの枚数
func eatP(level uint, x uint) uint {
	if level == 0 && x >= 1 {
		return 1
	}
	if x <= 1 {
		return 0
	}

	bargerLen := bargerLength(level)
	if x > bargerLen {
		return countP(level)
	}
	nextLen := bargerLength(level - 1)
	if x <= nextLen+1 {
		return eatP(level-1, x-1)
	} else if x == nextLen+2 {
		return eatP(level-1, x-1) + 1
	} else if x <= 2*nextLen+2 {
		return eatP(level-1, x-2-nextLen) + 1 + countP(level-1)
	} else {
		return 2*countP(level-1) + 1
	}

}

func bargerLength(level uint) uint {
	return 1<<(level+2) - 3
}

func countP(level uint) uint {
	return 1<<(level+1) - 1
}

func makeBarger(level uint) string {
	if barger, ok := bargers[level]; ok {
		return barger
	}
	if level == 0 {
		bargers[0] = "P"
		return bargers[0]
	} else {
		tmp := make([]string, 0)
		pBarger := makeBarger(level - 1)
		tmp = append(tmp, "B")
		tmp = append(tmp, pBarger)
		tmp = append(tmp, "P")
		tmp = append(tmp, pBarger)
		tmp = append(tmp, "B")
		bargers[level] = strings.Join(tmp, "")
		return bargers[level]
	}
}

//** DEBUG **/
const DEBUG_ENABLE = false

func debug(format string, a ...interface{}) (n int, err error) {
	if DEBUG_ENABLE {
		return fmt.Fprintf(os.Stdout, format, a...)
	} else {
		return 0, nil
	}
}

Score : 400 points

Problem Statement

In some other world, today is Christmas.

Mr. Takaha decides to make a multi-dimensional burger in his party. A level-L burger (L is an integer greater than or equal to 0) is the following thing:

A level-0 burger is a patty.

A level-L burger (L \geq 1) is a bun, a level-(L-1) burger, a patty, another level-(L-1) burger and another bun, stacked vertically in this order from the bottom.

For example, a level-1 burger and a level-2 burger look like BPPPB and BBPPPBPBPPPBB (rotated 90 degrees), where B and P stands for a bun and a patty.

The burger Mr. Takaha will make is a level-N burger. Lunlun the Dachshund will eat X layers from the bottom of this burger (a layer is a patty or a bun). How many patties will she eat?

Constraints

1 \leq N \leq 50

1 \leq X \leq ( the total number of layers in a level-N burger )

N and X are integers.

Input

Input is given from Standard Input in the following format:

N X

Output

Print the number of patties in the bottom-most X layers from the bottom of a level-N burger.

Sample Input 1

2 7

Sample Output 1

4

There are 4 patties in the bottom-most 7 layers of a level-2 burger (BBPPPBPBPPPBB).

Sample Input 2

1 1

Sample Output 2

0

The bottom-most layer of a level-1 burger is a bun.

Sample Input 3

50 4321098765432109

Sample Output 3

2160549382716056

A level-50 burger is rather thick, to the extent that the number of its layers does not fit into a 32-bit integer.