// https://atcoder.jp/contests/abc129/tasks/abc129_c

package main

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

var _sw = bufio.NewScanner(os.Stdin)

const mod = 1000000007

func main() {
	N := NextInt()
	M := NextInt()
	broken := make([]bool, N+1)
	for i := 0; i < M; i++ {
		a := NextInt()
		broken[a] = true
	}

	// i 段目まで行く方法
	counts := make([]int, N+1)
	counts[0] = 1

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

		if i == 1 {
			counts[i] = counts[i-1]
		} else {
			counts[i] = (counts[i-1] + counts[i-2]) % mod
		}
	}

	fmt.Println(counts[N] % mod)
}

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

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

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

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

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


package main

import (
	"fmt"
)

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

	a := make([]int, m)
	dp := make([]int, n+2)
	broken := make([]bool, n+2)
	dp[n] = 1
	for i:= range a {
		fmt.Scan(&a[i])
		broken[a[i]] = true
	}
	for i:=n-1; i>=0; i-- {
		if (broken[i]) {
			dp[i] = 0
		} else {
			dp[i] = (dp[i+1] + dp[i+2]) % 1000000007
		}
	}
	fmt.Println(dp[0])
}

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

Score : 300 points

Problem Statement

There is a staircase with N steps. Takahashi is now standing at the foot of the stairs, that is, on the 0-th step.
He can climb up one or two steps at a time.

However, the treads of the a_1-th, a_2-th, a_3-th, \ldots, a_M-th steps are broken, so it is dangerous to set foot on those steps.

How many are there to climb up to the top step, that is, the N-th step, without setting foot on the broken steps?
Find the count modulo 1\ 000\ 000\ 007.

Constraints

1 \leq N \leq 10^5

0 \leq M \leq N-1

1 \leq a_1 < a_2 < ... < a_M \leq N-1

Input

Input is given from Standard Input in the following format:

N M
a_1
a_2
.
.
.
a_M

Output

Print the number of ways to climb up the stairs under the condition, modulo 1\ 000\ 000\ 007.

Sample Input 1

6 1
3

Sample Output 1

4

There are four ways to climb up the stairs, as follows:

0 \to 1 \to 2 \to 4 \to 5 \to 6

0 \to 1 \to 2 \to 4 \to 6

0 \to 2 \to 4 \to 5 \to 6

0 \to 2 \to 4 \to 6

Sample Input 2

10 2
4
5

Sample Output 2

0

There may be no way to climb up the stairs without setting foot on the broken steps.

Sample Input 3

100 5
1
23
45
67
89

Sample Output 3

608200469

Be sure to print the count modulo 1\ 000\ 000\ 007.

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

var scanner = bufio.NewScanner(os.Stdin)

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

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

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

func calc(n int) int {
	if n == 0 || n == 1 {
		return 1
	}

	if n == 2 {
		return 2
	}

	return calc(n-2) + calc(n-1)
}

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

	n := nextInt()
	m := nextInt()
	brokenSteps := nextInts(m)

	if n == 1 {
		fmt.Println(1)
		return
	}

	if n == 2 {
		if len(brokenSteps) == 0 {
			fmt.Println(2)
			return
		}
		fmt.Println(1)
		return
	}

	start := 0
	var answer uint64
	answer = 1
	for _, i := range brokenSteps {
		steps := i - start - 1
		if steps < 0 {
			fmt.Println(0)
			os.Exit(0)
		}
		answer *= uint64(calc(steps))
		start = i + 1
	}

	if start < n {
		steps := n - start
		answer *= uint64(calc(steps))
	}

	fmt.Println(answer % 1000000007)
}


package main

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

const (
	maxwh = 2000
)

/*
 * すみません、自作ではありません。本人には謝りました。
 */

func main() {
	// 入力
	r := bufio.NewReader(os.Stdin)
	var h, w int
	fmt.Fscan(r, &h, &w)
	r.ReadString('\n')
	var s [maxwh + 2][maxwh + 2]bool
	for y := 1; y <= h; y++ {
		line, _ := r.ReadString('\n')
		for x := 1; x <= w; x++ {
			s[x][y] = line[x-1] == '.'
		}
	}

	// 上下左右の計算
	var jo, ge, sa, yu [maxwh + 2][maxwh + 2]int
	for y := 1; y <= h; y++ {
		for x := 1; x <= w; x++ {
			if s[x][y] {
				jo[x][y] = jo[x][y-1] + 1
				sa[x][y] = sa[x-1][y] + 1
			}
		}
	}
	for y := h; y >= 1; y-- {
		for x := w; x >= 1; x-- {
			if s[x][y] {
				ge[x][y] = ge[x][y+1] + 1
				yu[x][y] = yu[x+1][y] + 1
			}
		}
	}

	// 最大値の計算
	res := 0
	for y := 1; y <= h; y++ {
		for x := 1; x <= w; x++ {
			v := jo[x][y] + ge[x][y] + sa[x][y] + yu[x][y] - 3
			if v > res {
				res = v
			}
		}
	}

	// 出力
	fmt.Println(res)
}

Score : 400 points

Problem Statement

There is a grid with H horizontal rows and W vertical columns, and there are obstacles on some of the squares.

Snuke is going to choose one of the squares not occupied by an obstacle and place a lamp on it.
The lamp placed on the square will emit straight beams of light in four cardinal directions: up, down, left, and right.
In each direction, the beam will continue traveling until it hits a square occupied by an obstacle or it hits the border of the grid. It will light all the squares on the way, including the square on which the lamp is placed, but not the square occupied by an obstacle.

Snuke wants to maximize the number of squares lighted by the lamp.

You are given H strings S_i (1 \leq i \leq H), each of length W. If the j-th character (1 \leq j \leq W) of S_i is #, there is an obstacle on the square at the i-th row from the top and the j-th column from the left; if that character is ., there is no obstacle on that square.

Find the maximum possible number of squares lighted by the lamp.

Constraints

1 \leq H \leq 2,000

1 \leq W \leq 2,000

S_i is a string of length W consisting of # and ..

. occurs at least once in one of the strings S_i (1 \leq i \leq H).

Input

Input is given from Standard Input in the following format:

H W
S_1
:
S_H

Output

Print the maximum possible number of squares lighted by the lamp.

Sample Input 1

4 6
#..#..
.....#
....#.
#.#...

Sample Output 1

8

If Snuke places the lamp on the square at the second row from the top and the second column from the left, it will light the following squares: the first through fifth squares from the left in the second row, and the first through fourth squares from the top in the second column, for a total of eight squares.

Sample Input 2

8 8
..#...#.
....#...
##......
..###..#
...#..#.
##....#.
#...#...
###.#..#

Sample Output 2

13


package main
import (
  "fmt"
  "strconv"
)
var mod int64
func main() {
  var l,a,b,m int64
  fmt.Scan(&l,&a,&b,&m)
  mod = m
  c := make([]int64,19)
  t := int64(1)
  k := len(strconv.FormatInt(a,10))
  for d:=0;d<k;d++ { t *= 10 }
  for d:=k;d<19;d++ {
    if t-1 >= a+b*(l-1) { c[d] = l;break }
    c[d] = (t-a-1)/b+1
    t *= 10
  }
  for d:=18;d>0;d-- {
    if c[d] > 0 { c[d] -= c[d-1] }
  }
  t = 1
  y := Identity(3)
  for d:=1;d<19;d++ {
    t = (10*t)%mod
    z := NewMatrix(3)
    z[0].v[0] = t
    z[1].v[0] = 1
    z[1].v[1] = 1
    z[2].v[1] = b
    z[2].v[2] = 1
    y = y.MatMul(z.Pow(c[d]))
  }
  x := Vector{[]int64{0,a,1}}
  fmt.Println(x.DotProduct(y.ColVec(0)))
}
type Vector struct { v []int64 }
func(x Vector) DotProduct(y Vector) int64 {
  if len(x.v) != len(y.v) || len(x.v) == 0 { return 0 }
  d := (x.v[0]*y.v[0])%mod
  for i:=1;i<len(x.v);i++ { d = (d+x.v[i]*y.v[i])%mod }
  return d
}
type Matrix []Vector
func NewMatrix(n int) Matrix {
  m := Matrix{}
  for i:=0;i<n;i++ { m = append(m,Vector{make([]int64,n)}) }
  return m
}
func Identity(n int) Matrix {
  e := NewMatrix(n)
  for i:=0;i<n;i++ { e[i].v[i] = 1 }
  return e
}
func(a Matrix) ColVec(j int) Vector {
  if len(a) == 0 || j >= len(a[0].v) { return Vector{nil} }
  v := make([]int64,len(a))
  for i:=0;i<len(a);i++ { v[i] = a[i].v[j] }
  return Vector{v}
}
func(a Matrix) Transpose() Matrix {
  if len(a) == 0 || len(a[0].v) == 0 { return Matrix{Vector{nil}} }
  m := Matrix{}
  for j:=0;j<len(a[0].v);j++ { m = append(m,a.ColVec(j)) }
  return m
}
func(a Matrix) VecMul(x Vector) Vector {
  if len(a) == 0 || len(a[0].v) != len(x.v) ||
  len(x.v) == 0 { return Vector{nil} }
  v := make([]int64,len(a))
  for i:=0;i<len(a);i++ { v[i] = a[i].DotProduct(x) }
  return Vector{v}
}
func(a Matrix) MatMul(b Matrix) Matrix {
  if len(a) == 0 || len(a[0].v) == 0 || len(b) == 0 || len(b[0].v) == 0 ||
  len(a[0].v) != len(b) { return Matrix{Vector{nil}} }
  m := Matrix{}
  for j:=0;j<len(b[0].v);j++ { m = append(m,a.VecMul(b.ColVec(j))) }
  return m.Transpose()
}
func(a Matrix) Pow(n int64) Matrix {
  if len(a) == 0 || len(a[0].v) == 0 ||
  len(a) != len(a[0].v) { return Matrix{Vector{nil}} }
  if n == 0 { return Identity(len(a)) }
  if n%2 == 0 { c := a.Pow(n/2);return c.MatMul(c) }
  return a.MatMul(a.Pow(n-1))
}

Score : 600 points

Problem Statement

There is an arithmetic progression with L terms: s_0, s_1, s_2, ... , s_{L-1}.

The initial term is A, and the common difference is B. That is, s_i = A + B \times i holds.

Consider the integer obtained by concatenating the terms written in base ten without leading zeros. For example, the sequence 3, 7, 11, 15, 19 would be concatenated into 37111519. What is the remainder when that integer is divided by M?

Constraints

All values in input are integers.

1 \leq L, A, B < 10^{18}

2 \leq M \leq 10^9

All terms in the arithmetic progression are less than 10^{18}.

Input

Input is given from Standard Input in the following format:

L A B M

Output

Print the remainder when the integer obtained by concatenating the terms is divided by M.

Sample Input 1

5 3 4 10007

Sample Output 1

5563

Our arithmetic progression is 3, 7, 11, 15, 19, so the answer is 37111519 mod 10007, that is, 5563.

Sample Input 2

4 8 1 1000000

Sample Output 2

891011

Sample Input 3

107 10000000000007 1000000000000007 998244353

Sample Output 3

39122908


package main

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

func main() {
	_, A, B, C, D := ReadInt(), ReadInt()-1, ReadInt()-1, ReadInt()-1, ReadInt()-1
	S := ReadString()

	// A -> C
	preBlock := false
	for i := A; i <= C; i++ {
		if S[i] == '#' {
			if preBlock {
				fmt.Println("No")
				return
			}
		}
		preBlock = S[i] == '#'
	}

	// B -> D
	preBlock = false
	for i := B; i <= D; i++ {
		if S[i] == '#' {
			if preBlock {
				fmt.Println("No")
				return
			}
		}
		preBlock = S[i] == '#'
	}

	if C < D {
		fmt.Println("Yes")
		return
	}

	// B -> D
	seq := 0
	for i := B - 1; i <= D+1; i++ {
		if S[i] == '.' {
			seq++
			if seq >= 3 {
				fmt.Println("Yes")
				return
			}
		} else {
			seq = 0
		}
	}
	fmt.Println("No")
}

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
}

Score : 400 points

Problem Statement

There are N squares arranged in a row, numbered 1, 2, ..., N from left to right.
You are given a string S of length N consisting of . and #. If the i-th character of S is #, Square i contains a rock; if the i-th character of S is ., Square i is empty.

In the beginning, Snuke stands on Square A, and Fnuke stands on Square B.

You can repeat the following operation any number of times:

Choose Snuke or Fnuke, and make him jump one or two squares to the right. The destination must be one of the squares, and it must not contain a rock or the other person.

You want to repeat this operation so that Snuke will stand on Square C and Fnuke will stand on Square D.

Determine whether this is possible.

Constraints

4 \leq N \leq 200\ 000

S is a string of length N consisting of . and #.

1 \leq A, B, C, D \leq N

Square A, B, C and D do not contain a rock.

A, B, C and D are all different.

A < B

A < C

B < D

Input

Input is given from Standard Input in the following format:

N A B C D
S

Output

Print Yes if the objective is achievable, and No if it is not.

Sample Input 1

7 1 3 6 7
.#..#..

Sample Output 1

Yes

The objective is achievable by, for example, moving the two persons as follows. (A and B represent Snuke and Fnuke, respectively.)

A#B.#..

A#.B#..

.#AB#..

.#A.#B.

.#.A#B.

.#.A#.B

.#..#AB

Sample Input 2

7 1 3 7 6
.#..#..

Sample Output 2

No

Sample Input 3

15 1 3 15 13
...#.#...#.#...

Sample Output 3

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 check1(f, t, n int, s string) bool {
	for i := f + 1; i <= t; i++ {
		if s[i] == '#' && s[i-1] == '#' {
			return false
		}
	}
	return true
}

func check2(b, d int, s string) bool {
	if b == 0 {
		b++
	}
	if d == len(s)-1 {
		d--
	}
	for i := b; i <= d; i++ {
		if s[i-1] == '.' && s[i] == '.' && s[i+1] == '.' {
			return true
		}
	}

	return false
}

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

	N, A, B, C, D := getInt(), getInt()-1, getInt()-1,
		getInt()-1, getInt()-1
	s := getString()

	ans := true
	if s[C] == '#' || s[D] == '#' {
		ans = false
	}
	ret := check1(A, C, N, s)
	ans = ans && ret

	ret = check1(B, D, N, s)
	ans = ans && ret

	if C > D {
		ret = check2(B, D, s)
		ans = ans && ret
	}
	if ans {
		out("Yes")
	} else {
		out("No")
	}
}


package main

import "fmt"

func main() {
	var n, a, b, c, d int
	var s string
	fmt.Scan(&n, &a, &b, &c, &d, &s)
	a--
	b--
	c--
	d--
	if c < d {
		for {
			if b+1 == d || b+2 == d {
				break
			}
			if s[b+1] == '.' {
				b++
				continue
			}
			if s[b+2] == '.' {
				b += 2
				continue
			}
			fmt.Println("No")
			return
		}
		for {
			if a+1 == c || a+2 == c {
				break
			}
			if s[a+1] == '.' {
				a++
				continue
			}
			if s[a+2] == '.' {
				a += 2
				continue
			}
			fmt.Println("No")
			return
		}
		fmt.Println("Yes")
		return
	}
	for {
		no := true
		for a != c {
			if s[a+1] == '.' && a+1 != b {
				a++
				no = false
				continue
			}
			if s[a+2] == '.' && a+2 != b {
				a += 2
				no = false
				continue
			}
			break
		}
		for {
			if b == d {
				if a == c {
					fmt.Println("Yes")
					return
				}
				break
			}
			if s[b+1] == '.' && b+1 != a {
				b++
				no = false
				break
			}
			if s[b+2] == '.' && b+2 != a {
				b += 2
				no = false
				break
			}
		}
		if a > c || b > d {
			fmt.Println("No")
			return
		}
		if no {
			fmt.Println("No")
			return
		}
	}
}


package main

import (
	"fmt"
	"strings"
)

func main() {
	var str string
	fmt.Scan(&str)
	results := strings.Split(str, "")
	winCount := 0
	for _, result := range results {
		if result == "o" {
			winCount++
		}
	}

	if winCount + 15 - len(results) >= 8 {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

Score : 200 points

Problem Statement

Takahashi is competing in a sumo tournament.
The tournament lasts for 15 days, during which he performs in one match per day.
If he wins 8 or more matches, he can also participate in the next tournament.

The matches for the first k days have finished.
You are given the results of Takahashi's matches as a string S consisting of o and x.
If the i-th character in S is o, it means that Takahashi won the match on the i-th day; if that character is x, it means that Takahashi lost the match on the i-th day.

Print YES if there is a possibility that Takahashi can participate in the next tournament, and print NO if there is no such possibility.

Constraints

1 \leq k \leq 15

S is a string of length k consisting of o and x.

Input

Input is given from Standard Input in the following format:

S

Output

Print YES if there is a possibility that Takahashi can participate in the next tournament, and print NO otherwise.

Sample Input 1

oxoxoxoxoxoxox

Sample Output 1

YES

Takahashi has 7 wins and 7 losses before the last match. If he wins that match, he will have 8 wins.

Sample Input 2

xxxxxxxx

Sample Output 2

NO


package main

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

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

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

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

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

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

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

	n := scanInt()

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

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

	c := scanInts(n)
	sort.Ints(c)

	cnt := &verts{}
	heap.Init(cnt)
	ec := make([]int, n)

	for i := 0; i < n; i++ {
		ec[i] = len(t[i])
		heap.Push(cnt, vert{i,ec[i]})
	}

	done := make([]bool, n)
	d := make([]int, n)
	m := 0

	for i := 0; i < n; i++ {
		next := -1
		for cnt.Len() != 0 {
			v := heap.Pop(cnt).(vert)
			if !done[v.num] {
				next = v.num
				break
			}
		}

		d[next] = c[i]
		done[next] = true
		m += c[i]*ec[next]

		for _, e := range t[next] {
			ec[e]--
			heap.Push(cnt, vert{e, ec[e]})
		}
	}

	fmt.Println(m)

	for i, e := range d {
		fmt.Fprint(wr, e)
		if i != len(d)-1 { fmt.Fprint(wr, " ") }
	}
	fmt.Fprintln(wr)
	wr.Flush()
}

type vert struct {
	num int
	cnt int
}

type verts []vert

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

func (a *verts) Push(x interface{}) {
	*a = append(*a, x.(vert))
}

func (a *verts) Pop() interface{} {
	old := *a
	n := len(old)
	x := old[n-1]
	*a = old[0:n-1]

	return x
}

Score : 500 points

Problem Statement

You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N.
The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.

We will write a positive integer on each vertex in T and calculate our score as follows:

On each edge, write the smaller of the integers written on the two endpoints.

Let our score be the sum of the integers written on all the edges.

Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on one vertex in T, and show one way to achieve it. If an integer occurs multiple times in c_1,c_2,\ldots,c_N, we must use it that number of times.

Constraints

1 \leq N \leq 10000

1 \leq a_i,b_i \leq N

1 \leq c_i \leq 10^5

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N

Output

Use the following format:

M
d_1 \ldots d_N

where M is the maximum possible score, and d_i is the integer to write on Vertex i.
d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N.
If there are multiple ways to achieve the maximum score, any of them will be accepted.

Sample Input 1

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

Sample Output 1

10
1 2 3 4 5

If we write 1,2,3,4,5 on Vertex 1,2,3,4,5, respectively, the integers written on the four edges will be 1,2,3,4, for the score of 10. This is the maximum possible score.

Sample Input 2

5
1 2
1 3
1 4
1 5
3141 59 26 53 59

Sample Output 2

197
59 26 3141 59 53

c_1,c_2,\ldots,c_N may not be pairwise distinct.


package main

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

const (
	mod = int64(1000003)
)

func pow(x, y int64) int64 {
	if y == 0 {
		return 1
	}
	if y == 1 {
		return x
	}
	if y%2 == 0 {
		x2 := x * x % mod
		return pow(x2, y/2) % mod
	}
	return x * pow(x, y-1) % mod
}

func divide(x, y int64) int64 {
	return x * pow(y, mod-2) % mod
}

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

	factorial := make([]int64, mod)
	factorial[0] = 1
	for i := int64(1); i < mod; i++ {
		factorial[i] = factorial[i-1] * i % mod
	}

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

	for i := 0; i < q; i++ {
		scanner.Scan()
		xi, _ := strconv.Atoi(scanner.Text())
		x := int64(xi)
		scanner.Scan()
		di, _ := strconv.Atoi(scanner.Text())
		d := int64(di)
		scanner.Scan()
		ni, _ := strconv.Atoi(scanner.Text())
		n := int64(ni)

		if d == 0 {
			fmt.Println(pow(x, n))
			break
		}

		xdd := divide(x, d)
		ret := int64(1)
		for j := xdd; j < xdd+n; j++ {
			if j%mod == 0 {
				fmt.Println(0)
				break
			}
			ret = ret * j % mod
		}
		ret = divide(factorial[xdd+n-1], factorial[xdd-1]) % mod
		ret = ret * pow(d, n) % mod
		fmt.Println(ret)
	}
}

Score : 600 points

Problem Statement

Consider the following arithmetic progression with n terms:

x, x + d, x + 2d, \ldots, x + (n-1)d

What is the product of all terms in this sequence?
Compute the answer modulo 1\ 000\ 003.

You are given Q queries of this form.
In the i-th query, compute the answer in case x = x_i, d = d_i, n = n_i.

Constraints

1 \leq Q \leq 10^5

0 \leq x_i, d_i \leq 1\ 000\ 002

1 \leq n_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

Q
x_1 d_1 n_1
:
x_Q d_Q n_Q

Output

Print Q lines.

In the i-th line, print the answer for the i-th query.

Sample Input 1

2
7 2 4
12345 67890 2019

Sample Output 1

9009
916936

For the first query, the answer is 7 \times 9 \times 11 \times 13 = 9009.
Don't forget to compute the answer modulo 1\ 000\ 003.


package main

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

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

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}
func main() {
	a, p := nextInt(), nextInt()
	p += a * 3
	pie := p / 2
	fmt.Println(pie)
}

Score : 100 points

Problem Statement

We have A apples and P pieces of apple.

We can cut an apple into three pieces of apple, and make one apple pie by simmering two pieces of apple in a pan.

Find the maximum number of apple pies we can make with what we have now.

Constraints

All values in input are integers.

0 \leq A, P \leq 100

Input

Input is given from Standard Input in the following format:

A P

Output

Print the maximum number of apple pies we can make with what we have.

Sample Input 1

1 3

Sample Output 1

3

We can first make one apple pie by simmering two of the three pieces of apple. Then, we can make two more by simmering the remaining piece and three more pieces obtained by cutting the whole apple.

Sample Input 2

0 1

Sample Output 2

0

We cannot make an apple pie in this case, unfortunately.

Sample Input 3

32 21

Sample Output 3

58


package main

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

const mod = 1000000007

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

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

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

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

type Restaurant struct {
	City  string
	Score int
	Index int
}

type Restaurants []Restaurant

func (r Restaurants) Len() int {
	return len(r)
}

func (r Restaurants) Less(i, j int) bool {
	if r[i].City != r[j].City {
		return r[i].City < r[j].City
	} else {
		return r[i].Score > r[j].Score
	}
}

func (r Restaurants) Swap(i, j int) {
	r[i], r[j] = r[j], r[i]
}

func main() {
	n := nextInt()
	r := make([]Restaurant, n)

	for i := 0; i < n; i++ {
		r[i] = Restaurant{
			next(), nextInt(), i,
		}
	}

	sort.Sort(Restaurants(r))

	for _, res := range r {
		fmt.Println(res.Index + 1)
	}
}

Score : 200 points

Problem Statement

You have decided to write a book introducing good restaurants.
There are N restaurants that you want to introduce: Restaurant 1, Restaurant 2, ..., Restaurant N. Restaurant i is in city S_i, and your assessment score of that restaurant on a 100-point scale is P_i.
No two restaurants have the same score.

You want to introduce the restaurants in the following order:

The restaurants are arranged in lexicographical order of the names of their cities.

If there are multiple restaurants in the same city, they are arranged in descending order of score.

Print the identification numbers of the restaurants in the order they are introduced in the book.

Constraints

1 ≤ N ≤ 100

S is a string of length between 1 and 10 (inclusive) consisting of lowercase English letters.

0 ≤ P_i ≤ 100

P_i is an integer.

P_i ≠ P_j (1 ≤ i < j ≤ N)

Input

Input is given from Standard Input in the following format:

N
S_1 P_1
:
S_N P_N

Output

Print N lines. The i-th line (1 ≤ i ≤ N) should contain the identification number of the restaurant that is introduced i-th in the book.

Sample Input 1

6
khabarovsk 20
moscow 10
kazan 50
kazan 35
moscow 60
khabarovsk 40

Sample Output 1

3
4
6
1
5
2

The lexicographical order of the names of the three cities is kazan < khabarovsk < moscow. For each of these cities, the restaurants in it are introduced in descending order of score. Thus, the restaurants are introduced in the order 3,4,6,1,5,2.

Sample Input 2

10
yakutsk 10
yakutsk 20
yakutsk 30
yakutsk 40
yakutsk 50
yakutsk 60
yakutsk 70
yakutsk 80
yakutsk 90
yakutsk 100

Sample Output 2

10
9
8
7
6
5
4
3
2
1


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

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

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

func main() {
	n := scanInt()
	type restaurant struct {
		n    string
		p, i int
	}
	rs := make([]restaurant, n)
	for i := 0; i < n; i++ {
		rs[i].i = i + 1
		rs[i].n, rs[i].p = scanString(), scanInt()
	}

	sort.Slice(rs, func(i, j int) bool {
		if rs[i].n == rs[j].n {
			return rs[i].p > rs[j].p
		}
		return rs[i].n < rs[j].n
	})

	var wr = bufio.NewWriter(os.Stdout)
	for _, v := range rs {
		wr.WriteString(strconv.Itoa(v.i) + "\n")
	}
	wr.Flush()
}


package main

import (
	"fmt"
	"sort"
)

type Restaurant struct {
	idx int
	city string
	point int
}

type Restaurants []Restaurant

func (p Restaurants) Len() int {
	return len(p)
}

func (p Restaurants) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

func (p Restaurants) Less(i, j int) bool {
	if p[i].city != p[j].city {
		return p[i].city < p[j].city
	} else {
		return p[j].point < p[i].point
	}
}

func main()  {
	var n int

	fmt.Scan(&n)

	res := make(Restaurants, 0, n)

	for i := 0; i < n; i++ {
		var city string
		var point int
		fmt.Scan(&city, &point)

		res = append(res, Restaurant{idx: i+1, city: city, point:point})
	}

	sort.Sort(res)
	for _, v := range res {
		fmt.Println(v.idx)
	}
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

func init() {
	const maxWord = (1 << 30)
	buf := []byte{}
	sc.Buffer(buf, maxWord)
	sc.Split(bufio.ScanWords)
}

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

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

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

func solve(n, k int, v []int) int {
	r := min(n, k)
	ans := 0
	for a := 0; a <= r; a++ {
		for b := 0; b <= r-a; b++ {
			selected := make([]int, 0, r)
			for i := 0; i < a; i++ {
				selected = append(selected, v[i])
			}
			for i := n - 1; i >= n-b; i-- {
				selected = append(selected, v[i])
			}

			sort.Ints(selected)
			limit := min(len(selected), k-(a+b))
			for i := 0; i < limit; i++ {
				if selected[i] >= 0 {
					break
				}
				selected[i] = 0
			}

			sum := 0
			for _, num := range selected {
				sum += num
			}
			ans = max(ans, sum)
		}
	}
	return ans
}

func main() {
	n, _ := strconv.Atoi(input())
	k, _ := strconv.Atoi(input())
	v := make([]int, n)
	for i := 0; i < n; i++ {
		v[i], _ = strconv.Atoi(input())
	}
	fmt.Println(solve(n, k, v))
}

Score : 400 points

Problem Statement

Your friend gave you a dequeue D as a birthday present.

D is a horizontal cylinder that contains a row of N jewels.

The values of the jewels are V_1, V_2, ..., V_N from left to right. There may be jewels with negative values.

In the beginning, you have no jewel in your hands.

You can perform at most K operations on D, chosen from the following, at most K times (possibly zero):

Operation A: Take out the leftmost jewel contained in D and have it in your hand. You cannot do this operation when D is empty.

Operation B: Take out the rightmost jewel contained in D and have it in your hand. You cannot do this operation when D is empty.

Operation C: Choose a jewel in your hands and insert it to the left end of D. You cannot do this operation when you have no jewel in your hand.

Operation D: Choose a jewel in your hands and insert it to the right end of D. You cannot do this operation when you have no jewel in your hand.

Find the maximum possible sum of the values of jewels in your hands after the operations.

Constraints

All values in input are integers.

1 \leq N \leq 50

1 \leq K \leq 100

-10^7 \leq V_i \leq 10^7

Input

Input is given from Standard Input in the following format:

N K
V_1 V_2 ... V_N

Output

Print the maximum possible sum of the values of jewels in your hands after the operations.

Sample Input 1

6 4
-10 8 2 1 2 6

Sample Output 1

14

After the following sequence of operations, you have two jewels of values 8 and 6 in your hands for a total of 14, which is the maximum result.

Do operation A. You take out the jewel of value -10 from the left end of D.

Do operation B. You take out the jewel of value 6 from the right end of D.

Do operation A. You take out the jewel of value 8 from the left end of D.

Do operation D. You insert the jewel of value -10 to the right end of D.

Sample Input 2

6 4
-6 -100 50 -2 -5 -3

Sample Output 2

44

Sample Input 3

6 3
-6 -100 50 -2 -5 -3

Sample Output 3

0

It is optimal to do no operation.


package main

import "fmt"

func main() {
    var a, b int
    fmt.Scan(&a, &b)
    switch {
    case a>12:
    case a>5:
        b/=2
    default:
        b=0
    }
    fmt.Println(b)
}

Score : 100 points

Problem Statement

Takahashi, who is A years old, is riding a Ferris wheel.

It costs B yen (B is an even number) to ride the Ferris wheel if you are 13 years old or older, but children between 6 and 12 years old (inclusive) can ride it for half the cost, and children who are 5 years old or younger are free of charge. (Yen is the currency of Japan.)

Find the cost of the Ferris wheel for Takahashi.

Constraints

0 ≤ A ≤ 100

2 ≤ B ≤ 1000

B is an even number.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the cost of the Ferris wheel for Takahashi.

Sample Input 1

30 100

Sample Output 1

100

Takahashi is 30 years old now, and the cost of the Ferris wheel is 100 yen.

Sample Input 2

12 100

Sample Output 2

50

Takahashi is 12 years old, and the cost of the Ferris wheel is the half of 100 yen, that is, 50 yen.

Sample Input 3

0 100

Sample Output 3

0

Takahashi is 0 years old, and he can ride the Ferris wheel for free.


package main

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

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

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

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

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

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

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

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

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

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

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

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

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

	A := io.NextInt()
	B := io.NextInt()

	if A >= 13 {
		io.PrintLn(B)
	} else if A >= 6 {
		io.PrintLn(B / 2)
	} else {
		io.PrintLn(0)
	}
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

func iScan() int {
	n, _ := strconv.Atoi(Scan())
	return n
}

func fScan() float64 {
	n, _ := strconv.ParseFloat(Scan(), 64)
	return n
}
func stringToInt(s string) int {
	n, _ := strconv.Atoi(s)
	return n
}
func SScan(n int) []string {
	a := make([]string, n)
	for i := 0; i < n; i++ {
		a[i] = Scan()
	}
	return a
}
func iSScan(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = iScan()
	}
	return a
}
func abs(x int) int {
	if x < 0 {
		x = -x
	}
	return x
}
func larger(a, b int) int {
	if a < b {
		return b
	} else {
		return a
	}
}
func smaller(a, b int) int {
	if a > b {
		return b
	} else {
		return a
	}
}
func max(a []int) int {
	x := a[0]
	for i := 0; i < len(a); i++ {
		if x < a[i] {
			x = a[i]
		}
	}
	return x
}
func min(a []int) int {
	x := a[0]
	for i := 0; i < len(a); i++ {
		if x > a[i] {
			x = a[i]
		}
	}
	return x
}
func sum(a []int) int {
	x := 0
	for _, v := range a {
		x += v
	}
	return x
}

var mod int = 1000000007

func main() {
	buf := make([]byte, 0)
	sc.Buffer(buf, mod)
	sc.Split(bufio.ScanWords)
	r := iScan()
	d := iScan()
	x := iScan()
	for i := 0; i < 10; i++ {
		x = r*x - d
		fmt.Println(x)
	}
}

Score : 200 points

Problem Statement

The development of algae in a pond is as follows.

Let the total weight of the algae at the beginning of the year i be x_i gram. For i≥2000, the following formula holds:

x_{i+1} = rx_i - D

You are given r, D and x_{2000}. Calculate x_{2001}, ..., x_{2010} and print them in order.

Constraints

2 ≤ r ≤ 5

1 ≤ D ≤ 100

D < x_{2000} ≤ 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r D x_{2000}

Output

Print 10 lines. The i-th line (1 ≤ i ≤ 10) should contain x_{2000+i} as an integer.

Sample Input 1

2 10 20

Sample Output 1

30
50
90
170
330
650
1290
2570
5130
10250

For example, x_{2001} = rx_{2000} - D = 2 \times 20 - 10 = 30 and x_{2002} = rx_{2001} - D = 2 \times 30 - 10 = 50.

Sample Input 2

4 40 60

Sample Output 2

200
760
3000
11960
47800
191160
764600
3058360
12233400
48933560


package main

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

var sc = bufio.NewScanner(os.Stdin)
func scanInt() int {
	sc.Scan()
	a,_ := strconv.Atoi(sc.Text())
	return a
}

func main() {
	sc.Split(bufio.ScanWords)
	n := scanInt()
	m := scanInt()

	p,q := 1,n

	for i:=0; i<m; i++ {
		l := scanInt()
		r := scanInt()

		if p<l {
			p = l
		}

		if q>r {
			q = r
		}
	}

	if q-p+1 < 0 {
		fmt.Println(0)
	} else {
		fmt.Println(q-p+1)
	}
}

Score : 300 points

Problem Statement

We have N ID cards, and there are M gates.

We can pass the i-th gate if we have one of the following ID cards: the L_i-th, (L_i+1)-th, ..., and R_i-th ID cards.

How many of the ID cards allow us to pass all the gates alone?

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq L_i \leq R_i \leq N

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1
L_2 R_2
\vdots
L_M R_M

Output

Print the number of ID cards that allow us to pass all the gates alone.

Sample Input 1

4 2
1 3
2 4

Sample Output 1

2

Two ID cards allow us to pass all the gates alone, as follows:

The first ID card does not allow us to pass the second gate.

The second ID card allows us to pass all the gates.

The third ID card allows us to pass all the gates.

The fourth ID card does not allow us to pass the first gate.

Sample Input 2

10 3
3 6
5 7
6 9

Sample Output 2

1

Sample Input 3

100000 1
1 100000

Sample Output 3

100000


package main

import (
	"fmt"
)

func main() {
	N := 0
	M := 0
	fmt.Scan(&N, &M)

	Lmin := 0
	Rmax := 100001

	for i := 0; i < M; i++ {
		L, R := 0, 0
		fmt.Scan(&L, &R)
		if L > Lmin {
			Lmin = L
		}

		if R < Rmax {
			Rmax = R
		}
	}

	t := Rmax - Lmin
	if t < 0 {
		fmt.Println(0)
	} else {
		fmt.Println((Rmax - Lmin) + 1)
	}
}


package main

import (
	"fmt"
)

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

	l := make([]int, m)
	r := make([]int, m)
	for i := 0; i < m; i++ {
		fmt.Scan(&l[i], &r[i])
	}

	var min, max int
	max = 0
	for _, v := range l {
		if v > max {
			max = v
		}
	}

	min = 100000
	for i := range r {
		if r[i] < min {
			min = r[i]
		}
	}

	fmt.Println(min - max + 1)

}


package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"math"
	"os"
	"sort"
	"strings"
)

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

type Heap struct {
	data []int
}

func (h *Heap) Len() int           { return len(h.data) }
func (h *Heap) Less(i, j int) bool { return h.data[i] > h.data[j] }
func (h *Heap) Swap(i, j int)      { h.data[i], h.data[j] = h.data[j], h.data[i] }
func (h *Heap) Push(i interface{}) { h.data = append(h.data, i.(int)) }
func (h *Heap) Pop() interface{} {
	i := h.data[len(h.data)-1]
	h.data = h.data[:len(h.data)-1]
	return i
}

func main() {
	nm := scanNums(2)
	n, m := nm[0], nm[1]
	input := scanNums(n)

	ans := calc(input, n, m)
	fmt.Println(ans)

}

func calc(input []int, n, m int) int {
	h := &Heap{}
	heap.Init(h)
	for _, a := range input {
		heap.Push(h, a)
	}
	for i := 0; i < m; i++ {
		b, c := oneInt(), oneInt()
		for j := 0; j < b; j++ {
			heap.Push(h, c)
		}
	}

	sum := 0
	for i := 0; i < n; i++ {
		if m, ok := heap.Pop(h).(int); ok {
			sum += m
		}
	}

	return sum
}

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

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 scanNums(len int) (nums []int) {
	var num int
	for i := 0; i < len; i++ {
		fmt.Scan(&num)
		nums = append(nums, num)
	}
	return
}

func scanStrings() []string {
	str := readLine()
	s := strings.Split(str, " ")

	return s
}

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

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

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

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

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

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

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

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

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

func cumSum(nums []int) []int {
	sums := []int{0}

	for i := 0; i < len(nums); i++ {
		sums = append(sums, sums[i]+nums[i])
	}
	return sums
}

Score : 400 points

Problem Statement

You have N cards. On the i-th card, an integer A_i is written.

For each j = 1, 2, ..., M in this order, you will perform the following operation once:

Operation: Choose at most B_j cards (possibly zero). Replace the integer written on each chosen card with C_j.

Find the maximum possible sum of the integers written on the N cards after the M operations.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i, C_i \leq 10^9

1 \leq B_i \leq N

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N
B_1 C_1
B_2 C_2
\vdots
B_M C_M

Output

Print the maximum possible sum of the integers written on the N cards after the M operations.

Sample Input 1

3 2
5 1 4
2 3
1 5

Sample Output 1

14

By replacing the integer on the second card with 5, the sum of the integers written on the three cards becomes 5 + 5 + 4 = 14, which is the maximum result.

Sample Input 2

10 3
1 8 5 7 100 4 52 33 13 5
3 10
4 30
1 4

Sample Output 2

338

Sample Input 3

3 2
100 100 100
3 99
3 99

Sample Output 3

300

Sample Input 4

11 3
1 1 1 1 1 1 1 1 1 1 1
3 1000000000
4 1000000000
3 1000000000

Sample Output 4

10000000001

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


package main

import (
	"fmt"
	"sort"
)

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

	nums := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&nums[i])
	}
	sort.Ints(nums)

	var b int
	var c int
	for i := 0; i < m; i++ {
		fmt.Scan(&b)
		fmt.Scan(&c)

		changed := 0
		for j := 0; j < n; j++ {
			if nums[j] <= c {
				nums[j] = c
				changed++
			}
			if changed == b {
				break
			}
		}
		sort.Ints(nums)
	}

	sum := 0
	for i := 0; i < n; i++ {
		sum += nums[i]
	}

	fmt.Println(sum)
}


package main

import (
	"fmt"
	"strings"
)

func main() {
	var (
		n, k int
		s    string
	)
	fmt.Scan(&n, &k, &s)
	fmt.Println(s[:k-1] + strings.ToLower(s[k-1:k]) + s[k:])
}

Score : 100 points

Problem Statement

You are given a string S of length N consisting of A, B and C, and an integer K which is between 1 and N (inclusive).
Print the string S after lowercasing the K-th character in it.

Constraints

1 ≤ N ≤ 50

1 ≤ K ≤ N

S is a string of length N consisting of A, B and C.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the string S after lowercasing the K-th character in it.

Sample Input 1

3 1
ABC

Sample Output 1

aBC

Sample Input 2

4 3
CABA

Sample Output 2

CAbA


package main

import(
    "fmt"
    "strconv"
)

func main() {
    var s string
    fmt.Scan(&s)
    a := s[:2]
    b := s[2:]
    c, _ := strconv.Atoi(a)
    d, _ := strconv.Atoi(b)
    ans := "NA"
    switch{
        case c>=1 && c<=12 && d>=1 && d<=12:
            ans = "AMBIGUOUS"
        case (c==0 && d>12) || (c>12 && d==0):
            ans = "NA"
        case c>=1 && c<=12:
            ans = "MMYY"
        default:
            ans = "YYMM"
    }
    fmt.Println(ans)
}

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

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

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

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

func min64(a, b int64) int64 {
    if a >= b {
        return b
    }
    return a
}

func max64(a, b int64) int64 {
    if a >= b {
        return a
    }
    return b
}

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

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

Score : 200 points

Problem Statement

You have a digit sequence S of length 4. You are wondering which of the following formats S is in:

YYMM format: the last two digits of the year and the two-digit representation of the month (example: 01 for January), concatenated in this order

MMYY format: the two-digit representation of the month and the last two digits of the year, concatenated in this order

If S is valid in only YYMM format, print YYMM; if S is valid in only MMYY format, print MMYY; if S is valid in both formats, print AMBIGUOUS; if S is valid in neither format, print NA.

Constraints

S is a digit sequence of length 4.

Input

Input is given from Standard Input in the following format:

S

Output

Print the specified string: YYMM, MMYY, AMBIGUOUS or NA.

Sample Input 1

1905

Sample Output 1

YYMM

May XX19 is a valid date, but 19 is not valid as a month. Thus, this string is only valid in YYMM format.

Sample Input 2

0112

Sample Output 2

AMBIGUOUS

Both December XX01 and January XX12 are valid dates. Thus, this string is valid in both formats.

Sample Input 3

1700

Sample Output 3

NA

Neither 0 nor 17 is valid as a month. Thus, this string is valid in neither format.


package main

import (
	"fmt"
	"strconv"
	"strings"
)

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

	nn := strings.Split(n, "")
	a := nn[0] + nn[1]
	b := nn[2] + nn[3]

	c, _ := strconv.Atoi(a)
	d, _ := strconv.Atoi(b)

	switch {
	case 0 < c && c <= 12 && 0 < d && d <= 12:
		fmt.Println("AMBIGUOUS")
	case (0 == c) || (0 == d || d > 12):
		fmt.Println("NA")
	case c > 12 && 0 < d && d <= 12:
		fmt.Println("YYMM")
	case d > 12 && 0 < c && c <= 12:
		fmt.Println("MMYY")
	}
}


package main

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

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

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

  yymm := false
  mmyy := false

  a, _ := strconv.Atoi(s[:2])
  if a > 0 && a < 13 {
    mmyy = true
  }
  a, _ = strconv.Atoi(s[2:])
  if a > 0 && a < 13 {
    yymm = true
  }

  if yymm && mmyy {
    fmt.Println("AMBIGUOUS")
  } else if yymm {
    fmt.Println("YYMM")
  } else if mmyy {
    fmt.Println("MMYY")
  } else {
    fmt.Println("NA")
  }
}


package main

import (
  "fmt"
  "strconv"
)

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

  n1, _ := strconv.Atoi(s[0:2])
  n2, _ := strconv.Atoi(s[2:])

  fmt.Println(ret(n1,n2))
}

func ret(n1, n2 int) string {
  if n1 == 0 {
    switch {
    case n2 == 0:
      return "NA"
    case 1 <= n2 && n2 <= 12:
      return "YYMM"
    case 13 <= n2:
      return "NA"
    }
  }
  if 1 <= n1 && n1 <= 12 {
    switch {
    case n2 == 0:
      return "MMYY"
    case 1 <= n2 && n2 <= 12:
      return "AMBIGUOUS"
    case 13 <= n2:
      return "MMYY"
    }
  }
  if 13 <= n1 {
    switch {
    case n2 == 0:
      return "NA"
   	case 1 <= n2 && n2 <= 12:
      return "YYMM"
    case 13 <= n2:
      return "NA"
    }
  }
  return "NA"
}


package main

import "fmt"

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

	ans := 0.0
	for i := 1; i <= n; i++ {
		p := 1.0 / float64(n)
		for score := i; score < k; score *= 2 {
			p /= 2
		}
		ans += p
	}

	fmt.Println(ans)
}

Score : 300 points

Problem Statement

Snuke has a fair N-sided die that shows the integers from 1 to N with equal probability and a fair coin. He will play the following game with them:

Throw the die. The current score is the result of the die.

As long as the score is between 1 and K-1 (inclusive), keep flipping the coin. The score is doubled each time the coin lands heads up, and the score becomes 0 if the coin lands tails up.

The game ends when the score becomes 0 or becomes K or above. Snuke wins if the score is K or above, and loses if the score is 0.

You are given N and K. Find the probability that Snuke wins the game.

Constraints

1 ≤ N ≤ 10^5

1 ≤ K ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the probability that Snuke wins the game. The output is considered correct when the absolute or relative error is at most 10^{-9}.

Sample Input 1

3 10

Sample Output 1

0.145833333333

If the die shows 1, Snuke needs to get four consecutive heads from four coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^4 = \frac{1}{48}.

If the die shows 2, Snuke needs to get three consecutive heads from three coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^3 = \frac{1}{24}.

If the die shows 3, Snuke needs to get two consecutive heads from two coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^2 = \frac{1}{12}.

Thus, the probability that Snuke wins is \frac{1}{48} + \frac{1}{24} + \frac{1}{12} = \frac{7}{48} \simeq 0.1458333333.

Sample Input 2

100000 5

Sample Output 2

0.999973749998


package main

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

var scanner = bufio.NewScanner(os.Stdin)

func scanInt() int {
	scanner.Scan()
	a, err := strconv.Atoi(scanner.Text())
	if err != nil {
		fmt.Println(err)
	}
	return a
}

type To struct {
	e int
	w int
}

func makeLengths(n int, to map[int][]To, l []int) {
	l[0] = 0
	var impl func(p, gp int)
	impl = func(p, gp int) {
		if to[p] == nil {
			return
		}
		for _, nextTo := range to[p] {
			if nextTo.e == gp {
				continue
			}
			l[nextTo.e] = nextTo.w + l[p]
			impl(nextTo.e, p)
		}
	}
	impl(0, -1)
}

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

	n := scanInt()

	to := map[int][]To{}

	for i := 0; i < n-1; i++ {
		u := scanInt()
		v := scanInt()
		w := scanInt()

		if to[u-1] == nil {
			to[u-1] = []To{{e: v - 1, w: w}}
		} else {
			to[u-1] = append(to[u-1], To{e: v - 1, w: w})
		}

		if to[v-1] == nil {
			to[v-1] = []To{{e: u - 1, w: w}}
		} else {
			to[v-1] = append(to[v-1], To{e: u - 1, w: w})
		}
	}

	l := make([]int, n)
	makeLengths(n, to, l)

	for i := range l {
		if l[i]%2 == 0 {
			fmt.Println(0)
		} else {
			fmt.Println(1)
		}
	}
}

Score : 400 points

Problem Statement

We have a tree with N vertices numbered 1 to N.
The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i.
Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:

For any two vertices painted in the same color, the distance between them is an even number.

Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq u_i < v_i \leq N

1 \leq w_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}

Output

Print a coloring of the vertices that satisfies the condition, in N lines.
The i-th line should contain 0 if Vertex i is painted white and 1 if it is painted black.

If there are multiple colorings that satisfy the condition, any of them will be accepted.

Sample Input 1

3
1 2 2
2 3 1

Sample Output 1

0
0
1

Sample Input 2

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

Sample Output 2

1
0
1
0
1


package main

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

var (
	sc    = bufio.NewScanner(os.Stdin)
	edges map[int]map[int]int
	dists []int
)

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

func pop(stack []int) (int, []int) {
	e := stack[len(stack)-1]
	updatedStack := stack[:len(stack)-1]
	return e, updatedStack
}

func dfs(v int) {
	var stack []int
	var current int
	var currentDist int
	stack = append(stack, v)
	current = v
	for {
		if len(stack) == 0 {
			break
		}

		current, stack = pop(stack)
		currentDist = dists[current]

		for neibor, w := range edges[current] {
			if dists[neibor] == -1 {
				stack = append(stack, neibor)
				dists[neibor] = (w + currentDist) % 2
			}
		}

	}
}

func main() {

	edges = make(map[int]map[int]int)

	sc.Split(bufio.ScanWords)
	n := newLineInt()
	for i := 0; i < n; i++ {
		edges[i] = make(map[int]int)
	}
	for i := 0; i < n-1; i++ {
		u, v, w := newLineInt(), newLineInt(), newLineInt()
		edges[u-1][v-1] = w % 2
		edges[v-1][u-1] = w % 2
	}
	dists = make([]int, n)
	for i := 0; i < n; i++ {
		dists[i] = -1
	}
	dists[0] = 0
	dfs(0)
	for i := 0; i < n; i++ {
		fmt.Println(dists[i])
	}
}


package main

import (
	"fmt"
	"strconv"
)

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

	c, _ := strconv.Atoi(n)
	s := newSlice(0, c, 1)

	p := 0
	intK, _ := strconv.Atoi(k)
	i := 0
	for i < len(s) {
		if i+intK <= len(s) {
			p++
		}
		i++
	}
	fmt.Println(p)
}

func newSlice(start, count, step int) []int {
	s := make([]int, count)
	for i := range s {
		s[i] = start
		start += step
	}
	return s
}

Score : 100 points

Problem Statement

Snuke has N integers: 1,2,\ldots,N.
He will choose K of them and give those to Takahashi.

How many ways are there to choose K consecutive integers?

Constraints

All values in input are integers.

1 \leq K \leq N \leq 50

Input

Input is given from Standard Input in the following format:

N K

Output

Print the answer.

Sample Input 1

3 2

Sample Output 1

2

There are two ways to choose two consecutive integers: (1,2) and (2,3).

Sample Input 2

13 3

Sample Output 2

11


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)
	R, G, B, N := readInt(), readInt(), readInt(), readInt()
	var ans int64
	for r := int64(0); r <= 3000; r++ {
		for g := int64(0); g <= 3000; g++ {
			var sum = R*r + G*g
			if N >= sum && (N-sum)%B == 0 {
				ans++
			}
		}
	}
	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

Snuke has come to a store that sells boxes containing balls. The store sells the following three kinds of boxes:

Red boxes, each containing R red balls

Green boxes, each containing G green balls

Blue boxes, each containing B blue balls

Snuke wants to get a total of exactly N balls by buying r red boxes, g green boxes and b blue boxes.
How many triples of non-negative integers (r,g,b) achieve this?

Constraints

All values in input are integers.

1 \leq R,G,B,N \leq 3000

Input

Input is given from Standard Input in the following format:

R G B N

Output

Print the answer.

Sample Input 1

1 2 3 4

Sample Output 1

4

Four triples achieve the objective, as follows:

(4,0,0)

(2,1,0)

(1,0,1)

(0,2,0)

Sample Input 2

13 1 4 3000

Sample Output 2

87058


package main

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

func getNextLine(scanner *bufio.Reader) string {
	var buffer string
	for {
		line, isPrefix, _ := scanner.ReadLine()
		buffer += string(line)
		if isPrefix == false {
			break
		}
	}
	return buffer
}

func getIntList(scanner *bufio.Reader) []int {
	list := strings.Split(getNextLine(scanner), " ")
	l := len(list)
	result := make([]int, l)
	for i := 0; i < l; i++ {
		result[i], _ = strconv.Atoi(list[i])
	}
	return result
}

func main() {
	fp := os.Stdin
	if len(os.Args) > 1 {
		fp, _ = os.Open(os.Args[1])
	}

	scanner := bufio.NewReader(fp)

	var r, g, b, n int

	fmt.Sscan(getNextLine(scanner), &r, &g, &b, &n)

	arr := make([]int, n+1)
	ans := 0
	for i := 0; i <= n; i += r {
		for j := 0; j <= n; j += g {
			t := i + j
			if t > n {
				break
			}
			arr[t]++
		}
	}
	for i := 0; i <= n; i++ {
		for j := 0; j <= n; j += b {
			t := i + j
			if t > n {
				break
			}
			if t == n {
				ans += arr[i]
			}
		}
	}

	fmt.Println(ans)
}


package main

import "fmt"

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

func main() {
	var (
		n int
		s string
	)
	fmt.Scan(&n)
	count, bxa, bx, xa := 0, 0, 0, 0
	for i := 0; i < n; i++ {
		fmt.Scan(&s)
		for j := 0; j < len(s)-1; j++ {
			if s[j] == 'A' && s[j+1] == 'B' {
				count++
			}
		}
		if s[0] == 'B' && s[len(s)-1] == 'A' {
			bxa++
		} else if s[0] == 'B' {
			bx++
		} else if s[len(s)-1] == 'A' {
			xa++
		}
	}

	if bxa == 0 {
		count += min(bx, xa)
	} else if bx == 0 && xa == 0 {
		count += bxa - 1
	} else {
		count += bxa + min(bx, xa)
	}
	fmt.Println(count)
}

Score : 400 points

Problem Statement

Snuke has N strings. The i-th string is s_i.

Let us concatenate these strings into one string after arranging them in some order.
Find the maximum possible number of occurrences of AB in the resulting string.

Constraints

1 \leq N \leq 10^{4}

2 \leq |s_i| \leq 10

s_i consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
s_1
\vdots
s_N

Output

Print the answer.

Sample Input 1

3
ABCA
XBAZ
BAD

Sample Output 1

2

For example, if we concatenate ABCA, BAD and XBAZ in this order, the resulting string ABCABADXBAZ has two occurrences of AB.

Sample Input 2

9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA

Sample Output 2

4

Sample Input 3

7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA

Sample Output 3

4


package main

import (
	"fmt"
	"strings"
)

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

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

	ans := 0
	hb := 0
	ta := 0
	hbta := 0
	for _, v := range s {
		c := strings.Count(v, "AB")
		if c > 0 {
			strings.Replace(v, "AB", "", c)
			ans += c
		}
		if strings.HasPrefix(v, "B") && strings.HasSuffix(v, "A") {
			hbta++
			continue
		}
		if strings.HasPrefix(v, "B") {
			hb++
		}
		if strings.HasSuffix(v, "A") {
			ta++
		}
	}
	if hb < ta {
		ans += hb
		ta -= hb
		if ta < hbta {
			ans += ta
			hbta -= ta
			ans += hbta
		} else {
			ans += hbta
		}
	} else {
		ans += ta
		hb -= ta
		if hb < hbta {
			ans += hb
			hbta -= hb
			ans += hbta
		} else {
			ans += hbta
		}
	}
	fmt.Println(ans)
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

func main() {
	var counter int
	N := oneInt()
	var sentences []string
	for index := 0; index < N; index++ {
		s := oneStr()
		counter += strings.Count(s, "AB")
		sentences = append(sentences, s)
	}
	sumOfA := countLastA(sentences)
	sumOfB := countFirstB(sentences)
	sumOfAB := countAB(sentences)

	var result int

	if sumOfA == sumOfB && sumOfAB == sumOfA {
		fmt.Printf("%v", counter+sumOfAB-1)
		return
	}

	if sumOfB >= sumOfA {
		result = sumOfA + counter
	} else {
		result = sumOfB + counter
	}

	fmt.Printf("%v", result)
}

func countLastA(sentence []string) int {
	counter := 0
	for _, s := range sentence {
		if s[len(s)-1] == 'A' {
			counter++
		}
	}
	return counter
}

func countFirstB(sentence []string) int {
	counter := 0
	for _, s := range sentence {
		if s[0] == 'B' {
			counter++
		}
	}
	return counter
}

func countAB(sentence []string) int {
	counter := 0
	for _, s := range sentence {
		if s[0] == 'B' && s[len(s)-1] == 'A' {
			counter++
		}
	}
	return counter
}


package main

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

func primeFactors(n uint64) (pfs map[uint64]uint64) {
	pfs = make(map[uint64]uint64)
	for n%2 == 0 {
		pfs[2]++
		n = n / 2
	}

	var i uint64
	for i = 3; i*i <= n; i = i + 2 {
		for n%i == 0 {
			pfs[i]++
			n = n / i
		}
	}

	if n > 2 {
		pfs[n]++
	}
	return
}

func pow(x uint64, y uint64) uint64 {
	//_, _ = fmt.Printf("pow: %v, %v\n", x,y)
	z := x
	if y == 0 {
		return 1
	}
	var i uint64
	for i =1;i<y;i++ {
		z = z * x
	}
	return z
}

func incIdx(idx *[]uint64, max *[]uint64) bool {
	for i:=0;i<len(*idx);i++ {
		if (*idx)[i] < (*max)[i] {
			(*idx)[i]++
			return true
		} else {
			(*idx)[i] = 0
		}
	}
	return false
}

func answer(reader io.Reader, writer io.Writer) {
	var n uint64
	_, _ = fmt.Fscan(reader, &n)
	var sum uint64
	pfs := primeFactors(n)
	//_, _ = fmt.Printf("%v, %v\n", pfs, len(pfs))
	numPf := len(pfs)
	idx := make([]uint64, len(pfs))
	max := make([]uint64, len(pfs))
	listPf := make([]uint64, len(pfs))
	c := 0
	for k, v := range pfs {
		listPf[c] = k
		max[c] = v
		c++
	}

	for {
		var pf uint64
		pf = 1
		for i:=0;i<numPf;i++{
			pf = pf * pow(listPf[i],idx[i])
		}
		//_, _ = fmt.Printf("pf: %v\n", pf)
		if pf > 2 {
			if n / pf <= pf {
				sum += pf - 1
				//_, _ = fmt.Printf("m: %v, %v, %v\n", pf-1, n/(pf-1), n%(pf-1))
			}
		}
		if !incIdx(&idx, &max) {
			break
		}
	}
	//_, _ = fmt.Printf("%v\n", sum)
	_, _ = fmt.Fprintf(writer, "%v", sum)
}

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

Score : 500 points

Problem Statement

Snuke received a positive integer N from Takahashi.
A positive integer m is called a favorite number when the following condition is satisfied:

The quotient and remainder of N divided by m are equal, that is, \lfloor \frac{N}{m} \rfloor = N \bmod m holds.

Find all favorite numbers and print the sum of those.

Constraints

All values in input are integers.

1 \leq N \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

8

Sample Output 1

10

There are two favorite numbers: 3 and 7. Print the sum of these, 10.

Sample Input 2

1000000000000

Sample Output 2

2499686339916

Watch out for overflow.


/*
URL:
https://atcoder.jp/contests/agc033/tasks/agc033_c
*/

package main

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

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

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

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

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

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

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

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

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

func init() {
	// bufio.ScanWords <---> bufio.ScanLines
	ReadString = newReadString(os.Stdin, bufio.ScanWords)
	stdout = bufio.NewWriter(os.Stdout)
}

func main() {
	n = ReadInt()
	for i := 0; i < n-1; i++ {
		a, b := ReadInt2()
		a--
		b--

		G[a] = append(G[a], Edge{to: b, cost: 1})
		G[b] = append(G[b], Edge{to: a, cost: 1})
	}

	dfs(0, -1)
	rdfs(0, -1, 0)
	res := 0
	for i := 0; i < n; i++ {
		res = Max(res, ans[i])
	}

	if res%3 == 1 {
		fmt.Println("Second")
	} else {
		fmt.Println("First")
	}
}

type Edge struct {
	to, cost int
}

var (
	n int

	G   [100000 + 50][]Edge
	dp  [100000 + 50]int
	ans [100000 + 50]int
)

func rdfs(cid, pid int, dpar int) {
	V := []int{}
	for _, e := range G[cid] {
		if e.to == pid {
			V = append(V, dpar+e.cost)
			dpar += e.cost // 都合上ここで更新する
			continue
		}
		V = append(V, dp[e.to]+e.cost)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(V)))
	if len(V) == 1 {
		ans[cid] = V[0]
	} else {
		ans[cid] = V[0] + V[1]
	}

	cdp := []int{0}
	nexts := []int{-1}
	for _, e := range G[cid] {
		if e.to == pid {
			continue
		}
		cdp = append(cdp, dp[e.to]+e.cost)
		nexts = append(nexts, e.to)
	}
	cdp = append(cdp, 0)
	nexts = append(nexts, -1)

	N := len(cdp)
	L, R := make([]int, N), make([]int, N)
	L[0], R[0], L[N-1], R[N-1] = 0, 0, 0, 0
	for i := 1; i <= N-2; i++ {
		L[i] = Max(L[i-1], cdp[i])
	}
	for i := N - 2; i >= 1; i-- {
		R[i] = Max(R[i+1], cdp[i])
	}

	for i := 1; i <= N-2; i++ {
		ndpar := Max(dpar, L[i-1], R[i+1])
		rdfs(nexts[i], cid, ndpar)
	}
}

func dfs(cid, pid int) {
	res := 0
	for _, e := range G[cid] {
		if e.to == pid {
			continue
		}

		dfs(e.to, cid)
		res = Max(res, dp[e.to]+e.cost)
	}
	dp[cid] = res
}

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

func solve() {
}

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

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

var (
	// ReadString returns a WORD string.
	ReadString func() string
	stdout     *bufio.Writer
)

func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	r.Split(sf)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

	return string(res)
}

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

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

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

	return string(res)
}

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

// PrintfBufStdout is function for output strings to buffered os.Stdout.
// You may have to call stdout.Flush() finally.
func PrintfBufStdout(format string, a ...interface{}) {
	fmt.Fprintf(stdout, format, a...)
}

Score : 800 points

Problem Statement

Takahashi and Aoki will play a game on a tree.
The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.

At the beginning of the game, each vertex contains a coin.
Starting from Takahashi, he and Aoki will alternately perform the following operation:

Choose a vertex v that contains one or more coins, and remove all the coins from v.

Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.

The player who becomes unable to play, loses the game.
That is, the player who takes his turn when there is no coin remaining on the tree, loses the game.
Determine the winner of the game when both players play optimally.

Constraints

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

1 \leq a_i, b_i \leq N

a_i \neq b_i

The graph given as input is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}

Output

Print First if Takahashi will win, and print Second if Aoki will win.

Sample Input 1

3
1 2
2 3

Sample Output 1

First

Here is one possible progress of the game:

Takahashi removes the coin from Vertex 1. Now, Vertex 1 and Vertex 2 contain one coin each.

Aoki removes the coin from Vertex 2. Now, Vertex 2 contains one coin.

Takahashi removes the coin from Vertex 2. Now, there is no coin remaining on the tree.

Aoki takes his turn when there is no coin on the tree and loses.

Sample Input 2

6
1 2
2 3
2 4
4 6
5 6

Sample Output 2

Second

Sample Input 3

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

Sample Output 3

First


package main

import (
	"fmt"
)

func main() {

	var A, B, T int
	fmt.Scan(&A, &B, &T)

	bisket := 0
	for i := 1; i <= T; i++ {
		if i%A == 0 {
			bisket += B
		}
	}

	fmt.Println(bisket)
}

Score : 100 points

Problem Statement

A biscuit making machine produces B biscuits at the following moments: A seconds, 2A seconds, 3A seconds and each subsequent multiple of A seconds after activation.

Find the total number of biscuits produced within T + 0.5 seconds after activation.

Constraints

All values in input are integers.

1 \leq A, B, T \leq 20

Input

Input is given from Standard Input in the following format:

A B T

Output

Print the total number of biscuits produced within T + 0.5 seconds after activation.

Sample Input 1

3 5 7

Sample Output 1

10

Five biscuits will be produced three seconds after activation.

Another five biscuits will be produced six seconds after activation.

Thus, a total of ten biscuits will be produced within 7.5 seconds after activation.

Sample Input 2

3 2 9

Sample Output 2

6

Sample Input 3

20 20 19

Sample Output 3

0


package main

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

var sc = bufio.NewScanner(os.Stdin)

func main() {
	scanInit()

	a := nextInt()
	b := nextInt()
	t := nextInt()

	cnt := 0
	for i := 1; i <= t; i++ {
		if i%a == 0 {
			cnt += b
		}
	}

	fmt.Println(cnt)

}

// ---- readfunc
func scanInit() {
	const cap = 200 * 1024 // Default=64
	var buf = make([]byte, cap)
	sc.Buffer(buf, cap)
	sc.Split(bufio.ScanWords)
	return
}
func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}
func nextStr() string {
	sc.Scan()
	return sc.Text()
}


package main

import (
	"fmt"
)

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

	if a > t {
		fmt.Print(0)
		return
	}

	time := 0
	maked := 0
	cnt := 1
	for time < t {
		maked += b
		cnt++
		time = a * cnt
	}

	fmt.Print(maked)

}


package main

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

var (
	BufferSize = 10*10*10*10*10 + 10
)

func scanStr(sc *bufio.Scanner) string {
	if !sc.Scan() {
		panic(nil)
	}

	return sc.Text()
}

func scanInt(sc *bufio.Scanner) int {
	if !sc.Scan() {
		panic(nil)
	}

	i, err := strconv.Atoi(sc.Text())
	if err != nil {
		panic(err)
	}

	return i
}

func check() {
	sc := bufio.NewScanner(os.Stdin)
	buf := make([]byte, BufferSize)
	sc.Buffer(buf, BufferSize)
	sc.Split(bufio.ScanWords)

	a := scanInt(sc)
	b := scanInt(sc)
	t := scanInt(sc)

	var i int
	for ; (i+1)*a <= t; i++ {
	}

	fmt.Printf("%d\n", i*b)
	return

}

func main() {
	check()
}


package main

import "fmt"

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

	fmt.Println(t / a * b)
}


package main

import (
  "fmt"
)

func main() {
  var n int
  fmt.Scan(&n)
  res := 0
  v := make([]int, n)
  c := make([]int, n)
  for i := 0; i < n; i++ {
    fmt.Scan(&v[i])
  }
  for i := 0; i < n; i++ {
    fmt.Scan(&c[i])
  }
  for i := 0; i < n; i++ {
    if v[i] > c[i] {
      res += v[i] - c[i]
    }
  }
  fmt.Println(res)
}

Score : 200 points

Problem Statement

There are N gems. The value of the i-th gem is V_i.

You will choose some of these gems, possibly all or none, and get them.

However, you need to pay a cost of C_i to get the i-th gem.

Let X be the sum of the values of the gems obtained, and Y be the sum of the costs paid.

Find the maximum possible value of X-Y.

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq C_i, V_i \leq 50

Input

Input is given from Standard Input in the following format:

N
V_1 V_2 ... V_N
C_1 C_2 ... C_N

Output

Print the maximum possible value of X-Y.

Sample Input 1

3
10 2 5
6 3 4

Sample Output 1

5

If we choose the first and third gems, X = 10 + 5 = 15 and Y = 6 + 4 = 10.
We have X-Y = 5 here, which is the maximum possible value.

Sample Input 2

4
13 21 6 19
11 30 6 15

Sample Output 2

6

Sample Input 3

1
1
50

Sample Output 3

0


package main

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

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

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

func main() {
	N := getInt()
	A := getIntArray(N)

	total := 0
	min := pow(10, 6)
	mCnt := 0
	for i := 0; i < N; i++ {
		total += abs(A[i])

		if abs(A[i]) < min {
			min = abs(A[i])
		}

		if A[i] < 0 {
			mCnt++
		}
	}
	if mCnt % 2 == 1 {
		total -= min*2
	}
	fmt.Println(total)
}

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

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

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

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

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

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

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

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

			// なにか処理

			next = append(next, v)
		}
	}
}

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

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

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

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

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

func powMod(n, p int) int {
	if p == 0 {
		return 1
	} else if p%2 == 0 {
		t := powMod(n, p/2)
		return calcMod(t * t)
	} else {
		return calcMod(n * powMod(n, p-1))
	}
}

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

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

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

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

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

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

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

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

	return true
}

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

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

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

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

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

	return result
}

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

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

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

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

type intHeap []int

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

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

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

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

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

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

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

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

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

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

Score : 400 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, arranged in a row in this order.

You can perform the following operation on this integer sequence any number of times:

Operation: Choose an integer i satisfying 1 \leq i \leq N-1. Multiply both A_i and A_{i+1} by -1.

Let B_1, B_2, ..., B_N be the integer sequence after your operations.

Find the maximum possible value of B_1 + B_2 + ... + B_N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

-10^9 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible value of B_1 + B_2 + ... + B_N.

Sample Input 1

3
-10 5 -4

Sample Output 1

19

If we perform the operation as follows:

Choose 1 as i, which changes the sequence to 10, -5, -4.

Choose 2 as i, which changes the sequence to 10, 5, 4.

we have B_1 = 10, B_2 = 5, B_3 = 4. The sum here, B_1 + B_2 + B_3 = 10 + 5 + 4 = 19, is the maximum possible result.

Sample Input 2

5
10 -4 -8 -11 3

Sample Output 2

30

Sample Input 3

11
-1000000000 1000000000 -1000000000 1000000000 -1000000000 0 1000000000 -1000000000 1000000000 -1000000000 1000000000

Sample Output 3

10000000000

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


package main

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

func main() {
	N, S, K := ReadInt(), ReadString(), ReadInt()
	c := S[K-1]
	v := make([]byte, N)
	for i := 0; i < N; i++ {
		v[i] = S[i]
		if v[i] != c {
			v[i] = '*'
		}
	}
	fmt.Println(string(v))
}

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
}

Score : 200 points

Problem Statement

You are given a string S of length N consisting of lowercase English letters, and an integer K.
Print the string obtained by replacing every character in S that differs from the K-th character of S, with *.

Constraints

1 \leq K \leq N\leq 10

S is a string of length N consisting of lowercase English letters.

N and K are integers.

Input

Input is given from Standard Input in the following format:

N
S
K

Output

Print the string obtained by replacing every character in S that differs from the K-th character of S, with *.

Sample Input 1

5
error
2

Sample Output 1

*rr*r

The second character of S is r. When we replace every character in error that differs from r with *, we get the string *rr*r.

Sample Input 2

6
eleven
5

Sample Output 2

e*e*e*

Sample Input 3

9
education
7

Sample Output 3

******i**


package main

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

var rdr = bufio.NewReaderSize(os.Stdin, 10000)

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

func main() {
	_ = readLine()
	s := strings.Split(readLine(), "")
	k, _ := strconv.Atoi(readLine())

	match := s[k-1]

	for i := 0; i < len(s); i++ {
		if s[i] != match {
			fmt.Print("*")
		} else {
			fmt.Print(s[i])
		}
	}

	fmt.Println()
}


package main

import "fmt"

func main() {
	var n int
	var s string
	fmt.Scan(&n, &s)
	var sum int
	for i := n - 1; i >= 1; i-- {
		if s[i:i+1] == "." {
			if s[i-1:i] == "#" {
				sum++
			}
		}
	}
	fmt.Println(sum)
}

Score : 300 points

Problem Statement

There are N stones arranged in a row. Every stone is painted white or black.
A string S represents the color of the stones. The i-th stone from the left is white if the i-th character of S is ., and the stone is black if the character is #.

Takahashi wants to change the colors of some stones to black or white so that there will be no white stone immediately to the right of a black stone.
Find the minimum number of stones that needs to be recolored.

Constraints

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

S is a string of length N consisting of . and #.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the minimum number of stones that needs to be recolored.

Sample Input 1

3
#.#

Sample Output 1

1

It is enough to change the color of the first stone to white.

Sample Input 2

5
#.##.

Sample Output 2

2

Sample Input 3

9
.........

Sample Output 3

0


package main

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

var sc = bufio.NewScanner(os.Stdin)

func main() {
	sc.Split(bufio.ScanWords)
	a := readInt()
	b := readInt()
	if a == b {
		fmt.Println(a + b)
	} else if a > b {
		fmt.Println(a + (a - 1))
	} else {
		fmt.Println(b + (b - 1))
	}
}

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

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

Score : 100 points

Problem Statement

There are two buttons, one of size A and one of size B.

When you press a button of size X, you get X coins and the size of that button decreases by 1.

You will press a button twice. Here, you can press the same button twice, or press both buttons once.

At most how many coins can you get?

Constraints

All values in input are integers.

3 \leq A, B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of coins you can get.

Sample Input 1

5 3

Sample Output 1

9

You can get 5 + 4 = 9 coins by pressing the button of size 5 twice, and this is the maximum result.

Sample Input 2

3 4

Sample Output 2

7

Sample Input 3

6 6

Sample Output 3

12


package main

import (
  "fmt"
)

var (
  a,b,x,y int
)

func main() {
  fmt.Scanf("%d%d",&a,&b)
  if a > b {
    x = a
    a--
  } else {
    x = b
    b--
  }
  if a > b {
    y = a
    a--
  } else {
    y = b
    b--
  }
  fmt.Println(x + y)
}


package main

import (
	"fmt"
	"log"
	"math"
)

func main() {

	var A, B int //
	var result int

		_, err := fmt.Scan(&A, &B)
		if err != nil {
			log.Fatal(err)
		}

		if A == B{
			result = A + B
		}else{
			result = int(math.Max(float64(A),float64(B))) * 2 - 1
		}

		fmt.Println(result)
}


package main

import "fmt"

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

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


package main

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

func main() {
	sc := bufio.NewScanner(os.Stdin)
	buf := make([]byte, 10000)
	sc.Buffer(buf, 100000+1024)

	s := readLine(sc)
	sInts := strings.Split(s, "")

	outputValue := 0
	var tileColorNumber string

	for index, sInt := range sInts {
		if index == 0 {
			tileColorNumber = sInt
			continue
		}

		if tileColorNumber == sInt {
			outputValue++
			if tileColorNumber == "0" {
				tileColorNumber = "1"
			} else {
				tileColorNumber = "0"
			}
		} else {
			tileColorNumber = sInt
		}
	}

	fmt.Println(outputValue)
}

// helper

func readLine(sc *bufio.Scanner) string {
	sc.Scan()
	return strings.TrimSpace(sc.Text())
}

func readLineToInt(sc *bufio.Scanner) int {
	intValue, err := strconv.Atoi(readLine(sc))
	if err != nil {
		panic(err)
	}

	return intValue
}

func explodeString(delimiter string, inputValue string) []string {
	splittedValue := strings.Split(inputValue, delimiter)

	var trimmedValues []string

	for _, value := range splittedValue {
		if value != "" {
			trimmedValues = append(trimmedValues, value)
		}
	}

	return trimmedValues
}

func explodeInt(delimiter string, inputValue string) []int {
	inputStrings := explodeString(" ", inputValue)

	var splittedInts []int

	for _, inputString := range inputStrings {
		var (
			intValue int
			err      error
		)
		intValue, err = strconv.Atoi(inputString)

		if err != nil {
			panic(err)
		}
		splittedInts = append(splittedInts, intValue)
	}

	return splittedInts
}

Score : 300 points

Problem Statement

N tiles are arranged in a row from left to right. The initial color of each tile is represented by a string S of length N.

The i-th tile from the left is painted black if the i-th character of S is 0, and painted white if that character is 1.

You want to repaint some of the tiles black or white, so that any two adjacent tiles have different colors.

At least how many tiles need to be repainted to satisfy the condition?

Constraints

1 \leq |S| \leq 10^5

S_i is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum number of tiles that need to be repainted to satisfy the condition.

Sample Input 1

000

Sample Output 1

1

The condition can be satisfied by repainting the middle tile white.

Sample Input 2

10010010

Sample Output 2

3

Sample Input 3

0

Sample Output 3

0


package main

import (
	"fmt"
)

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

	var E0, E1, O0, O1 int
	for i, t := range text {
		if i%2 == 0 {
			if t == '0' {
				E0++
			} else {
				E1++
			}
		} else {
			if t == '0' {
				O0++
			} else {
				O1++
			}
		}
	}
//	fmt.Println(min(E0+O1, E1+O0))
if 	E0+O1 < E1+O0 {
	fmt.Println(E0+O1)
	}else {
	fmt.Println(E1+O0)
}

}

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


package main

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

var sc = bufio.NewScanner(os.Stdin)

func init() {
	sc.Buffer(make([]byte, 101000), 101000)
}

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

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

func main() {
	s := rb()

	x := 0
	for i, v := range s {
		if i&1 == 0 && v == '0' { // Odd
			x++
		} else if i&1 != 0 && v == '1' {
			x++
		}
	}

	y := 0
	for i, v := range s {
		if i&1 == 0 && v == '1' { // Odd
			y++
		} else if i&1 != 0 && v == '0' {
			y++
		}
	}

	fmt.Println(smaller(x, y))
}


package main

import (
	"fmt"
)

func maxInt(a, b int) int {
	switch {
	case a >= b:
		return a
	default:
		return b
	}
}

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

	var partLength []int
	prevChar := str[0:1]
	cnt := 1
	for i := 1; i < n; i++ {
		if str[i:i+1] == prevChar {
			cnt++
		} else {
			partLength = append(partLength, cnt)
			prevChar = str[i : i+1]
			cnt = 1
		}
	}
	partLength = append(partLength, cnt)

	var cumSum []int
	cumSum = append(cumSum, 0)
	for i := range partLength {
		cumSum = append(cumSum, cumSum[i]+partLength[i])
	}
	if str[0:1] == "0" {
		cumSum = append([]int{0}, cumSum...)
	}
	if str[n-1:n] == "0" {
		cumSum = append(cumSum, n)
	}

	if len(cumSum) <= 2*k+2 {
		fmt.Println(n)
	} else {
		maxRet := 0
		for i := 0; i < len(cumSum)-(2*k+1); i += 2 {
			maxRet = maxInt(maxRet, cumSum[i+(2*k+1)]-cumSum[i])
		}
		fmt.Println(maxRet)
	}

}

Score : 400 points

Problem Statement

N people are arranged in a row from left to right.

You are given a string S of length N consisting of 0 and 1, and a positive integer K.

The i-th person from the left is standing on feet if the i-th character of S is 0, and standing on hands if that character is 1.

You will give the following direction at most K times (possibly zero):

Direction: Choose integers l and r satisfying 1 \leq l \leq r \leq N, and flip the l-th, (l+1)-th, ..., and r-th persons. That is, for each i = l, l+1, ..., r, the i-th person from the left now stands on hands if he/she was standing on feet, and stands on feet if he/she was standing on hands.

Find the maximum possible number of consecutive people standing on hands after at most K directions.

Constraints

N is an integer satisfying 1 \leq N \leq 10^5.

K is an integer satisfying 1 \leq K \leq 10^5.

The length of the string S is N.

Each character of the string S is 0 or 1.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the maximum possible number of consecutive people standing on hands after at most K directions.

Sample Input 1

5 1
00010

Sample Output 1

4

We can have four consecutive people standing on hands, which is the maximum result, by giving the following direction:

Give the direction with l = 1, r = 3, which flips the first, second and third persons from the left.

Sample Input 2

14 2
11101010110011

Sample Output 2

8

Sample Input 3

1 1
1

Sample Output 3

1

No directions are necessary.