package main

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

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

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

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

func newReadString(ior io.Reader) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+11))
	// Split sets the split function for the Scanner. The default split function is ScanLines.
	// Split panics if it is called after scanning has started.
	r.Split(bufio.ScanWords)

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

// ReadInt returns an integer.
func ReadInt() int {
	return int(readInt64())
}
func 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())
}

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

// OnBit returns the integer that has nth ON bit.
// If an argument has nth ON bit, OnBit returns the argument.
func OnBit(num, nth int) int {
	return num | (1 << uint(nth))
}

// OffBit returns the integer that has nth OFF bit.
// If an argument has nth OFF bit, OffBit returns the argument.
func OffBit(num, nth int) int {
	return num & ^(1 << uint(nth))
}

// PopCount returns the number of ON bit of an argument.
func PopCount(num int) int {
	res := 0

	for i := 0; i < 70; i++ {
		if ((num >> uint(i)) & 1) == 1 {
			res++
		}
	}

	return res
}

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

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

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

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

	res := 0

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

	return res
}

// DigitNumOfDecimal returns digits number of n.
// n is non negative number.
func DigitNumOfDecimal(n int) int {
	res := 0

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

	return res
}

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

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

	return s
}

// Kiriage returns Ceil(a/b)
// a >= 0, b > 0
func Kiriage(a, b int) int {
	return (a + (b - 1)) / b
}

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

	if e == 0 {
		return 1
	}

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

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

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

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

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

	return a
}

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

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

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

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

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

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

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

	return string(res)
}

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

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

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

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

const MOD = 1000000000 + 7
const ALPHABET_NUM = 26
const INF_INT64 = math.MaxInt64
const INF_BIT60 = 1 << 60

var n int
var P []int

type Item struct {
	key      int
	val, idx int
}
type ItemList []*Item
type byKey struct {
	ItemList
}

func (l ItemList) Len() int {
	return len(l)
}
func (l ItemList) Swap(i, j int) {
	l[i], l[j] = l[j], l[i]
}

func (l byKey) Less(i, j int) bool {
	return l.ItemList[i].key < l.ItemList[j].key
}

// how to use
// L := make(ItemList, 0, 200000+5)
// L = append(L, &Item{key: intValue})
// sort.Stable(byKey{ L })                // Stable ASC
// sort.Stable(sort.Reverse(byKey{ L }))  // Stable DESC

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

	L := make(ItemList, n)
	for i := 0; i < n; i++ {
		L[i] = &Item{key: P[i], idx: i, val: P[i]}
	}
	sort.Stable(sort.Reverse(byKey{L}))

	ans := 0
	tr := NewTreap()
	for i := 0; i < n; i++ {
		item := L[i]

		right1 := tr.BiggerUpperBound(item.idx)
		left1 := tr.SmallerLowerBound(item.idx)

		if right1 == nil && left1 == nil {
			tr.Insert(item.idx)
			continue
		}

		l, r := 0, 0
		if right1 == nil && left1 != nil {
			// 左側を含めれば右側はどこまでも伸ばせる
			// 左側にさらに大きいものがあったら、それは含んではいけない
			l = left1.key
			left2 := tr.SmallerLowerBound(l)
			l2 := 0
			if left2 == nil {
				l2 = -1
			} else {
				l2 = left2.key
			}
			r = n
			ans += item.val * ((r - item.idx) * (l - l2))
		} else if right1 != nil && left1 == nil {
			// 右側を含めれば左側はどこまでも伸ばせる
			// 右側にさらに大きいものがあったら、それは含んではいけない
			l = -1
			r = right1.key
			right2 := tr.BiggerUpperBound(r)
			r2 := 0
			if right2 == nil {
				r2 = n
			} else {
				r2 = right2.key
			}
			ans += item.val * ((item.idx - l) * (r2 - r))
		} else {
			// 右・左のどちらかを含める場合のすべてを数える
			l = left1.key
			r = right1.key
			left2 := tr.SmallerLowerBound(l)
			l2 := 0
			if left2 == nil {
				l2 = -1
			} else {
				l2 = left2.key
			}
			right2 := tr.BiggerUpperBound(r)
			r2 := 0
			if right2 == nil {
				r2 = n
			} else {
				r2 = right2.key
			}
			// ans += item.val * ((r - item.idx) + (item.idx - l))
			ans += item.val * ((r - item.idx) * (l - l2))
			ans += item.val * ((r2 - r) * (item.idx - l))
		}
		// fmt.Printf("m: %d, l: %d, r: %d\n", item.idx, l, r)

		// ans += item.val * ((r - item.idx) + (item.idx - l))
		tr.Insert(item.idx)
	}

	fmt.Println(ans)
}

// Treap usage
// tr := NewTreap()
// tr.Insert(k)
// node := tr.Find(k)
// min := tr.FindMinimum()
// max := tr.FindMaximum()
// tr.Delete(k)
// node := tr.BigggerLowerBound(x)
// node := tr.BiggerUpperBound(x)
// node := tr.SmallerUpperBound(x)
// node := tr.SmallerLowerBound(x)
// fmt.Println(PrintIntsLine(tr.Inorder()...))
// fmt.Println(PrintIntsLine(tr.Preorder()...))
// tr.InsertBySettingPri(k, p)

type Node struct {
	key, priority int
	right, left   *Node
}

type Treap struct {
	root *Node
}

/*************************************/
// Public method
/*************************************/

// NewTreap returns a pointer of a Treap instance.
func NewTreap() *Treap {
	tr := new(Treap)
	tr.root = nil
	return tr
}

// InsertBySettingPri method inserts a new node consisting of new key and priority.
// A duplicate key is ignored and nothing happens.
func (tr *Treap) InsertBySettingPri(key, priority int) {
	tr.root = tr.insert(tr.root, key, priority)
}

// for XorShift
var _gtx, _gty, _gtz, _gtw = 123456789, 362436069, 521288629, 88675123

// Insert method inserts a new node consisting o new key.
// The priority is automatically set by random value.
// A duplicate key is ignored and nothing happens.
func (tr *Treap) Insert(key int) {
	// XorShiftによる乱数生成
	// 下記URLを参考
	// https://qiita.com/tubo28/items/f058582e457f6870a800#lower_bound-upper_bound
	randInt := func() int {
		tt := (_gtx ^ (_gtx << 11))
		_gtx = _gty
		_gty = _gtz
		_gtz = _gtw
		_gtw = (_gtw ^ (_gtw >> 19)) ^ (tt ^ (tt >> 8))
		return _gtw
	}

	tr.root = tr.insert(tr.root, key, randInt())
}

// Find returns a node that has an argument key value.
// Find returns nil when there is no node that has an argument key value.
func (tr *Treap) Find(k int) *Node {
	u := tr.root
	for u != nil && k != u.key {
		if k < u.key {
			u = u.left
		} else {
			u = u.right
		}
	}
	return u
}

// FindMinimum returns a node that has the minimum key in the treap.
// FindMinimum returns nil when there is no nodes.
func (tr *Treap) FindMinimum() *Node {
	u := tr.root
	for u != nil && u.left != nil {
		u = u.left
	}
	return u
}

// FindMaximum returns a node that has the maximum key in the treap.
// FindMaximum returns nil when there is no nodes.
func (tr *Treap) FindMaximum() *Node {
	u := tr.root
	for u != nil && u.right != nil {
		u = u.right
	}
	return u
}

// Delete method deletes a node that has an argument key value.
// A duplicate key is ignored and nothing happens.
func (tr *Treap) Delete(key int) {
	tr.root = tr.delete(tr.root, key)
}

// Inorder returns a slice consisting of treap nodes in order of INORDER.
// The nodes are sorted by key values.
func (tr *Treap) Inorder() []int {
	res := make([]int, 0, 200000+5)
	tr.inorder(tr.root, &res)
	return res
}

// Preorder returns a slice consisting of treap nodes in order of PREORDER.
func (tr *Treap) Preorder() []int {
	res := make([]int, 0, 200000+5)
	tr.preorder(tr.root, &res)
	return res
}

// BiggerLowerBound returns a node that has MINIMUM KEY MEETING key >= x.
// https://qiita.com/tubo28/items/f058582e457f6870a800#lower_bound-upper_bound
func (tr *Treap) BiggerLowerBound(x int) *Node {
	return tr.biggerLowerBound(tr.root, x)
}

// BiggerUpperBound returns a node that has MINIMUM KEY MEETING key > x.
// https://qiita.com/tubo28/items/f058582e457f6870a800#lower_bound-upper_bound
func (tr *Treap) BiggerUpperBound(x int) *Node {
	return tr.biggerUpperBound(tr.root, x)
}

// SmallerUpperBound returns a node that has MAXIMUM KEY MEETING key <= x.
// for AGC005-B
func (tr *Treap) SmallerUpperBound(x int) *Node {
	return tr.smallerUpperBound(tr.root, x)
}

// SmallerLowerBound returns a node that has MAXIMUM KEY MEETING key < x.
// for AGC005-B
func (tr *Treap) SmallerLowerBound(x int) *Node {
	return tr.smallerLowerBound(tr.root, x)
}

/*************************************/
// Private method
/*************************************/

func (tr *Treap) insert(t *Node, key, priority int) *Node {
	// 葉に到達したら新しい節点を生成して返す
	if t == nil {
		node := new(Node)
		node.key, node.priority = key, priority
		return node
	}

	// 重複したkeyは無視
	if key == t.key {
		return t
	}

	if key < t.key {
		// 左の子へ移動
		t.left = tr.insert(t.left, key, priority) // 左の子へのポインタを更新
		// 左の子の方が優先度が高い場合右回転
		if t.priority < t.left.priority {
			t = tr.rightRotate(t)
		}
	} else {
		// 右の子へ移動
		t.right = tr.insert(t.right, key, priority) // 右の子へのポインタを更新
		if t.priority < t.right.priority {
			// 右の子の方が優先度が高い場合左回転
			t = tr.leftRotate(t)
		}
	}

	return t
}

// 削除対象の節点を回転によって葉まで移動させた後に削除する
func (tr *Treap) delete(t *Node, key int) *Node {
	if t == nil {
		return nil
	}

	// 削除対象を検索
	if key < t.key {
		t.left = tr.delete(t.left, key)
	} else if key > t.key {
		t.right = tr.delete(t.right, key)
	} else {
		// 削除対象を発見、葉ノードとなるように回転を繰り返す
		return tr._delete(t, key)
	}

	return t
}

// 削除対象の節点の場合
func (tr *Treap) _delete(t *Node, key int) *Node {
	if t.left == nil && t.right == nil {
		// 葉の場合
		return nil
	} else if t.left == nil {
		// 右の子のみを持つ場合は左回転
		t = tr.leftRotate(t)
	} else if t.right == nil {
		// 左の子のみを持つ場合は右回転
		t = tr.rightRotate(t)
	} else {
		// 優先度が高い方を持ち上げる
		if t.left.priority > t.right.priority {
			t = tr.rightRotate(t)
		} else {
			t = tr.leftRotate(t)
		}
	}

	return tr.delete(t, key)
}

func (tr *Treap) rightRotate(t *Node) *Node {
	s := t.left
	t.left = s.right
	s.right = t
	return s
}

func (tr *Treap) leftRotate(t *Node) *Node {
	s := t.right
	t.right = s.left
	s.left = t
	return s
}

// rootからスタートする
func (tr *Treap) biggerLowerBound(t *Node, x int) *Node {
	if t == nil {
		return nil
	} else if t.key >= x {
		// 探索キーxが現在のノードキー以下の場合、左を探索する
		node := tr.biggerLowerBound(t.left, x)
		if node != nil {
			return node
		} else {
			return t
		}
	} else {
		// 探索キーxが現在のノードキーより大きい場合、右を探索する
		return tr.biggerLowerBound(t.right, x)
	}
}

// rootからスタートする
func (tr *Treap) biggerUpperBound(t *Node, x int) *Node {
	if t == nil {
		return nil
	} else if t.key > x {
		// 探索キーxが現在のノードキーより小さい場合、左を探索する
		node := tr.biggerUpperBound(t.left, x)
		if node != nil {
			return node
		} else {
			return t
		}
	} else {
		// 探索キーxが現在のノードキー以上の場合、右を探索する
		return tr.biggerUpperBound(t.right, x)
	}
}

// rootからスタートする
func (tr *Treap) smallerUpperBound(t *Node, x int) *Node {
	if t == nil {
		return nil
	} else if t.key <= x {
		node := tr.smallerUpperBound(t.right, x)
		if node != nil {
			return node
		} else {
			return t
		}
	} else {
		return tr.smallerUpperBound(t.left, x)
	}
}

// rootからスタートする
func (tr *Treap) smallerLowerBound(t *Node, x int) *Node {
	if t == nil {
		return nil
	} else if t.key < x {
		node := tr.smallerLowerBound(t.right, x)
		if node != nil {
			return node
		} else {
			return t
		}
	} else {
		return tr.smallerLowerBound(t.left, x)
	}
}

func (tr *Treap) inorder(u *Node, res *[]int) {
	if u == nil {
		return
	}
	tr.inorder(u.left, res)
	*res = append(*res, u.key)
	tr.inorder(u.right, res)
}

func (tr *Treap) preorder(u *Node, res *[]int) {
	if u == nil {
		return
	}
	*res = append(*res, u.key)
	tr.preorder(u.left, res)
	tr.preorder(u.right, res)
}

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

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

Score: 500 points

Problem Statement

Given is a permutation P of \{1, 2, \ldots, N\}.

For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.

Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

Constraints

2 \le N \le 10^5

1 \le P_i \le N

P_i \neq P_j (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1 P_2 \ldots P_N

Output

Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

Sample Input 1

3
2 3 1

Sample Output 1

5

X_{1, 2} = 2, X_{1, 3} = 2, and X_{2, 3} = 1, so the sum is 2 + 2 + 1 = 5.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

30

Sample Input 3

8
8 2 7 3 4 5 6 1

Sample Output 3

136


package main

import "fmt"

func main() {
	var count int
	var forecast, weather string

	fmt.Scanf("%s",&forecast)
	fmt.Scanf("%s",&weather)

	for i:=0; i < len(forecast); i++ {
		if forecast[i] == weather[i] {
			count++
		}
	}

	fmt.Printf("%d",count)
}

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

Score : 100 points

Problem Statement

You will be given a string S of length 3 representing the weather forecast for three days in the past.

The i-th character (1 \leq i \leq 3) of S represents the forecast for the i-th day. S, C, and R stand for sunny, cloudy, and rainy, respectively.

You will also be given a string T of length 3 representing the actual weather on those three days.

The i-th character (1 \leq i \leq 3) of S represents the actual weather on the i-th day. S, C, and R stand for sunny, cloudy, and rainy, respectively.

Print the number of days for which the forecast was correct.

Constraints

S and T are strings of length 3 each.

S and T consist of S, C, and R.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the number of days for which the forecast was correct.

Sample Input 1

CSS
CSR

Sample Output 1

2

For the first day, it was forecast to be cloudy, and it was indeed cloudy.

For the second day, it was forecast to be sunny, and it was indeed sunny.

For the third day, it was forecast to be sunny, but it was rainy.

Thus, the forecast was correct for two days in this case.

Sample Input 2

SSR
SSR

Sample Output 2

3

Sample Input 3

RRR
SSS

Sample Output 3

0

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

func main(){
        var a, b string
        fmt.Scanf( "%s", &a )
        fmt.Scanf( "%s", &b )
        count := 0

        for i, _ := range a{
                if a[ i ] == b[ i ]{
                        count ++
                }
        }
  fmt.Printf( "%d", count )

}


package main

import "fmt"

func main() {
	var A, B int
	fmt.Scanf("%d %d", &A, &B)

	tap := 1 //必要なタップ数．
	if A >= B {
		fmt.Println(tap)
	} else {
		tap += B / A
		fmt.Println(tap)
	}
}

Score : 200 points

Problem Statement

Takahashi's house has only one socket.

Takahashi wants to extend it with some number of power strips, each with A sockets, into B or more empty sockets.

One power strip with A sockets can extend one empty socket into A empty sockets.

Find the minimum number of power strips required.

Constraints

All values in input are integers.

2 \leq A \leq 20

1 \leq B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the minimum number of power strips required.

Sample Input 1

4 10

Sample Output 1

3

3 power strips, each with 4 sockets, extend the socket into 10 empty sockets.

Sample Input 2

8 9

Sample Output 2

2

2 power strips, each with 8 sockets, extend the socket into 15 empty sockets.

Sample Input 3

8 8

Sample Output 3

1


package main

import "fmt"

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

  ans := 1
  c := 1
  for {
    if  ans > b {
    	break;
    }

    ans --
    ans += a
    c++
  }

  fmt.Println(c)

}


package main

import "fmt"

func main() {
	var A, B int
	fmt.Scan(&A, &B)
	a := B / A
	if a*A < B {
		a++
	}
	fmt.Println(a)
}


package main

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

func run() {
	a := nextInt()
	b := nextInt()
	ans := 0
	cur := 1
	for cur < b {
		cur = cur + a - 1
		ans++
	}
	Println(ans)
}

// --- template ---
// Thanks https://gist.github.com/halllllll/853ab587fd82ee3ffe6f7fb7fb499695

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

// Caution: You will get unexpected result if a single token is larger than this size.
const BufferSize = 64 * 1024 * 1024

func Print(a ...interface{}) (n int, err error) {
	return fmt.Fprint(out, a...)
}

func Printf(format string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(out, format, a...)
}

func Println(a ...interface{}) (n int, err error) {
	return fmt.Fprintln(out, a...)
}

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

func nextInt() int {
	a, err := strconv.Atoi(next())
	if err != nil {
		log.Fatal(err)
	}
	return a
}

func nextFloat() float64 {
	a, err := strconv.ParseFloat(next(), 64)
	if err != nil {
		log.Fatal(err)
	}
	return a
}

func main() {
	sc.Buffer(make([]byte, 0, BufferSize), BufferSize)
	sc.Split(bufio.ScanWords)
	run()
	out.Flush()
}


package main

import "fmt"

func main() {
	var a int
	var b int
	fmt.Scanf("%d %d", &a, &b)
	i := 1
	c := i * a
	for {
		if c >= b {
			break
		}
		i++
		c = i*a - (i - 1)
	}
	fmt.Println(i)
}


package main

import "fmt"

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

	fmt.Println(n * (n - 1) / 2)
}

Score : 400 points

Problem Statement

For an integer N, we will choose a permutation \{P_1, P_2, ..., P_N\} of \{1, 2, ..., N\}.

Then, for each i=1,2,...,N, let M_i be the remainder when i is divided by P_i.

Find the maximum possible value of M_1 + M_2 + \cdots + M_N.

Constraints

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

Input

Input is given from Standard Input in the following format:

N

Output

Print the maximum possible value of M_1 + M_2 + \cdots + M_N.

Sample Input 1

2

Sample Output 1

1

When the permutation \{P_1, P_2\} = \{2, 1\} is chosen, M_1 + M_2 = 1 + 0 = 1.

Sample Input 2

13

Sample Output 2

78

Sample Input 3

1

Sample Output 3

0


package main

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

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

func main() {
	sc.Split(bufio.ScanWords)
	defer out.Flush() // !!!!coution!!!! you must use Fprint(out, ) not Print()
	/* --- code ---*/
	N := nextInt()
	ans := (N - 1) * N / 2
	fmt.Fprintln(out, ans)
}

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

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

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

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

// Genericsがないので筋肉で...
// interfaceでの取扱がようわからんし
func containStr(arr []string, target string) bool {
	for _, v := range arr {
		if v == target {
			return true
		}
	}
	return false
}

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

// mapからkeysとvaluesを返す感じのやつ
// なんかしらんけどmap[interface{}]interface{}しか受け付けない。なんのためのinterface{}やねん
// なので呼ぶときのmapはmap[int]stringとかじゃダメ
func splitKeyValue(m map[interface{}]interface{}) (keys, values []interface{}) {
	switch reflect.TypeOf(m).Kind() {
	case reflect.Map:
		s := reflect.ValueOf(m)
		for _, v := range s.MapKeys() {
			keys = append(keys, v)
			values = append(values, s.MapIndex(v))
		}
	default:
		fmt.Fprintln(out, "fuck")
	}
	return
}


package main

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

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Scan()
	N, _ := strconv.Atoi(sc.Text())

	table := make([][]int, N)
	for i := 0; i < N; i++ {
		sc.Scan()
		elems := strings.Split(sc.Text(), " ")
		table[i] = make([]int, N-1)
		for j, elem := range elems {
			table[i][j], _ = strconv.Atoi(elem)
			table[i][j]--
		}
	}

	nissuu := 0
	siaisuu := 0

	madaaru := make(map[int]bool)
	for i := 0; i < N; i++ {
		madaaru[i] = true
	}

	for siaisuu < N*(N-1)/2 {
		zoubunn := 0

		yatta := make([]bool, N)

		for i := range madaaru {
			if yatta[i] {
				continue
			}

			if len(table[i]) == 0 {
				delete(madaaru, i)
				continue
			}

			aite := table[i][0]
			if len(table[aite]) == 0 {
				fmt.Println(-1)
				return
			}

			if yatta[aite] {
				continue
			}

			if table[aite][0] != i {
				continue
			}

			siaisuu++
			zoubunn++
			table[i] = table[i][1:]
			table[aite] = table[aite][1:]
			yatta[i] = true
			yatta[aite] = true
		}
		if zoubunn == 0 {
			fmt.Println(-1)
			return
		}
		nissuu++
	}

	fmt.Println(nissuu)
}

Score : 500 points

Problem Statement

N players will participate in a tennis tournament. We will call them Player 1, Player 2, \ldots, Player N.

The tournament is round-robin format, and there will be N(N-1)/2 matches in total.
Is it possible to schedule these matches so that all of the following conditions are satisfied? If the answer is yes, also find the minimum number of days required.

Each player plays at most one matches in a day.

Each player i (1 \leq i \leq N) plays one match against Player A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} in this order.

Constraints

3 \leq N \leq 1000

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

A_{i, j} \neq i

A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} are all different.

Input

Input is given from Standard Input in the following format:

N
A_{1, 1} A_{1, 2} \ldots A_{1, N-1}
A_{2, 1} A_{2, 2} \ldots A_{2, N-1}
:
A_{N, 1} A_{N, 2} \ldots A_{N, N-1}

Output

If it is possible to schedule all the matches so that all of the conditions are satisfied, print the minimum number of days required; if it is impossible, print -1.

Sample Input 1

3
2 3
1 3
1 2

Sample Output 1

3

All the conditions can be satisfied if the matches are scheduled for three days as follows:

Day 1: Player 1 vs Player 2

Day 2: Player 1 vs Player 3

Day 3: Player 2 vs Player 3

This is the minimum number of days required.

Sample Input 2

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

Sample Output 2

4

All the conditions can be satisfied if the matches are scheduled for four days as follows:

Day 1: Player 1 vs Player 2, Player 3 vs Player 4

Day 2: Player 1 vs Player 3

Day 3: Player 1 vs Player 4, Player 2 vs Player 3

Day 4: Player 2 vs Player 4

This is the minimum number of days required.

Sample Input 3

3
2 3
3 1
1 2

Sample Output 3

-1

Any scheduling of the matches violates some condition.


package main

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

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

func MaxFloat(x, y float64) float64 {
  if x < y { return y }
  return x
}
func Dist02(A *[]float64) float64 {
  x, y := (*A)[0], (*A)[1]
  return x * x + y * y
}
func InnerProduct(A, B *[]float64) float64 {
  return (*A)[0] * (*B)[0] + (*A)[1] * (*B)[1]
}
func Angle(A, B *[]float64) float64 {
  acos := math.Acos(InnerProduct(A, B) / math.Sqrt(Dist02(A)) / math.Sqrt(Dist02(B)))
  return acos / math.Pi * 180.0
}

type Engines [][]float64
func (E Engines) Len() int { return len(E) }
func (E Engines) Less(i, j int) bool { return E[i][2] < E[j][2] }
func (E Engines) Swap(i, j int) { E[i], E[j] = E[j], E[i] }

func main() {
  N := NextInt()
  E := make([][]float64, 0)
  X := []float64{1.0, 0.0}
  for i := 0; i < N; i++ {
    XY := NextFloatVec()
    if XY[0] != 0.0 || XY[1] != 0.0 {
      angle := Angle(&X, &XY)
      if XY[1] < 0 { angle = 360.0 - angle }
      XY = append(XY, angle)
      E = append(E, XY)
      E = append(E, []float64{0.0, 0.0, angle - 180.0})
      E = append(E, []float64{XY[0], XY[1], angle + 360.0})
      E = append(E, []float64{0.0, 0.0, angle + 540.0})
    }
  }
  sort.Sort(Engines(E))
  ans := 0.0
  t := 0
  D := []float64{0.0, 0.0}
  for _, e := range E {
    if 360.0 <= e[2] { break }
    for E[t][2] - e[2] <= 180.0 {
      D[0] += E[t][0]
      D[1] += E[t][1]
      t++
    }
    ans = MaxFloat(math.Sqrt(Dist02(&D)), ans)
    D[0] -= e[0]
    D[1] -= e[1]
  }
  Write(ans)
  Output()
}

Score: 600 points

Problem Statement

E869120 is initially standing at the origin (0, 0) in a two-dimensional plane.

He has N engines, which can be used as follows:

When E869120 uses the i-th engine, his X- and Y-coordinate change by x_i and y_i, respectively. In other words, if E869120 uses the i-th engine from coordinates (X, Y), he will move to the coordinates (X + x_i, Y + y_i).

E869120 can use these engines in any order, but each engine can be used at most once. He may also choose not to use some of the engines.

He wants to go as far as possible from the origin.
Let (X, Y) be his final coordinates. Find the maximum possible value of \sqrt{X^2 + Y^2}, the distance from the origin.

Constraints

1 \leq N \leq 100

-1 \ 000 \ 000 \leq x_i \leq 1 \ 000 \ 000

-1 \ 000 \ 000 \leq y_i \leq 1 \ 000 \ 000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
: :
x_N y_N

Output

Print the maximum possible final distance from the origin, as a real value.
Your output is considered correct when the relative or absolute error from the true answer is at most 10^{-10}.

Sample Input 1

3
0 10
5 -5
-5 -5

Sample Output 1

10.000000000000000000000000000000000000000000000000

The final distance from the origin can be 10 if we use the engines in one of the following three ways:

Use Engine 1 to move to (0, 10).

Use Engine 2 to move to (5, -5), and then use Engine 3 to move to (0, -10).

Use Engine 3 to move to (-5, -5), and then use Engine 2 to move to (0, -10).

The distance cannot be greater than 10, so the maximum possible distance is 10.

Sample Input 2

5
1 1
1 0
0 1
-1 0
0 -1

Sample Output 2

2.828427124746190097603377448419396157139343750753

The maximum possible final distance is 2 \sqrt{2} = 2.82842....
One of the ways to achieve it is:

Use Engine 1 to move to (1, 1), and then use Engine 2 to move to (2, 1), and finally use Engine 3 to move to (2, 2).

Sample Input 3

5
1 1
2 2
3 3
4 4
5 5

Sample Output 3

21.213203435596425732025330863145471178545078130654

If we use all the engines in the order 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5, we will end up at (15, 15), with the distance 15 \sqrt{2} = 21.2132... from the origin.

Sample Input 4

3
0 0
0 1
1 0

Sample Output 4

1.414213562373095048801688724209698078569671875376

There can be useless engines with (x_i, y_i) = (0, 0).

Sample Input 5

1
90447 91000

Sample Output 5

128303.000000000000000000000000000000000000000000000000

Note that there can be only one engine.

Sample Input 6

2
96000 -72000
-72000 54000

Sample Output 6

120000.000000000000000000000000000000000000000000000000

There can be only two engines, too.

Sample Input 7

10
1 2
3 4
5 6
7 8
9 10
11 12
13 14
15 16
17 18
19 20

Sample Output 7

148.660687473185055226120082139313966514489855137208


package main

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

var sc *bufio.Scanner

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

func main() {
	sc = bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	m, d := nextInt(), nextInt()

	ans := 0
	for mth := 1; mth <= m; mth++ {
		for div := 2; div <= 9; div++ {
			if mth/div < 10 && mth/div > 1 && mth%div == 0 {
				if (mth/div)*10+div <= d {
					ans++
				}
				if div*10+(mth/div) <= d {
					ans++
				}
			}
		}
	}
	fmt.Println(ans / 2)
}

Score : 200 points

Problem Statement

Today is August 24, one of the five Product Days in a year.

A date m-d (m is the month, d is the date) is called a Product Day when d is a two-digit number, and all of the following conditions are satisfied (here d_{10} is the tens digit of the day and d_1 is the ones digit of the day):

d_1 \geq 2

d_{10} \geq 2

d_1 \times d_{10} = m

Takahashi wants more Product Days, and he made a new calendar called Takahashi Calendar where a year consists of M month from Month 1 to Month M, and each month consists of D days from Day 1 to Day D.

In Takahashi Calendar, how many Product Days does a year have?

Constraints

All values in input are integers.

1 \leq M \leq 100

1 \leq D \leq 99

Input

Input is given from Standard Input in the following format:

M D

Output

Print the number of Product Days in a year in Takahashi Calender.

Sample Input 1

15 40

Sample Output 1

10

There are 10 Product Days in a year, as follows (m-d denotes Month m, Day d):

4-22

6-23

6-32

8-24

9-33

10-25

12-26

12-34

14-27

15-35

Sample Input 2

12 31

Sample Output 2

5

Sample Input 3

1 1

Sample Output 3

0


// https://atcoder.jp/contests/jsc2019-qual/tasks/jsc2019_qual_b

package main

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

var _sw = bufio.NewScanner(os.Stdin)

func main() {
	N := nextInt()
	K := nextInt()
	A := make([]int, N)

	for i := range A {
		A[i] = nextInt()
	}

	w := 0
	h := 0
	for i := range A {
		for j := range A {
			if A[i] > A[j] {
				w++
				if i < j {
					h++
				}
			}
		}
	}

	D := 1000000000 + 7
	ans := (K*h%D + ((K-1)*K/2%D)*w) % D
	fmt.Println(ans)
}

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
}

Score : 300 points

Problem Statement

We have a sequence of N integers A~=~A_0,~A_1,~...,~A_{N - 1}.

Let B be a sequence of K \times N integers obtained by concatenating K copies of A. For example, if A~=~1,~3,~2 and K~=~2, B~=~1,~3,~2,~1,~3,~2.

Find the inversion number of B, modulo 10^9 + 7.

Here the inversion number of B is defined as the number of ordered pairs of integers (i,~j)~(0 \leq i < j \leq K \times N - 1) such that B_i > B_j.

Constraints

All values in input are integers.

1 \leq N \leq 2000

1 \leq K \leq 10^9

1 \leq A_i \leq 2000

Input

Input is given from Standard Input in the following format:

N K
A_0 A_1 ... A_{N - 1}

Output

Print the inversion number of B, modulo 10^9 + 7.

Sample Input 1

2 2
2 1

Sample Output 1

3

In this case, B~=~2,~1,~2,~1. We have:

B_0 > B_1

B_0 > B_3

B_2 > B_3

Thus, the inversion number of B is 3.

Sample Input 2

3 5
1 1 1

Sample Output 2

0

A may contain multiple occurrences of the same number.

Sample Input 3

10 998244353
10 9 8 7 5 6 3 4 2 1

Sample Output 3

185297239

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


package main

import "fmt"

func main() {
	var N, K, a, out int
	fmt.Scanf("%d %d", &N, &K)
	A := make([]int, N)
	for i := 0; i < N; i++ {
		fmt.Scanf("%d", &a)
		A[i] = a
	}
	out = 0
	var h, r int // A内の転倒数, A内で自分より小さい値の個数
	// 成分番号ごとにカウントする
	for i := 0; i < N; i++ {
		// h,rを計算
		h = 0
		r = 0
		for ii := 0; ii < N; ii++ {
			if A[ii] < A[i] {
				h++
				if ii > i {
					r++
				}
			}
		}
		//fmt.Printf("h:%d\n", h)
		//fmt.Printf("r:%d\n", r)
		out += h*K + r*(K-1)*K/2
		//fmt.Printf("h:%d\n", h)
		//fmt.Printf("r%d\n", r)
		//fmt.Printf("K%d\n", K)
		//fmt.Printf("out:%d\n", out)
	}
	//fmt.Println(A)
	// fmt.Printf("out:%d\n", out)
	fmt.Println(out % (1000000000 + 7))
}


package main

import "fmt"

func main() {
	var n int
	var ans float64

	fmt.Scan(&n)

	for i := 0; i < n; i++ {
		var a int
		fmt.Scan(&a)

		ans += 1.0 / float64(a)
	}

	fmt.Printf("%f\n", 1.0/ans)

}

Score : 200 points

Problem Statement

Given is a sequence of N integers A_1, \ldots, A_N.

Find the (multiplicative) inverse of the sum of the inverses of these numbers, \frac{1}{\frac{1}{A_1} + \ldots + \frac{1}{A_N}}.

Constraints

1 \leq N \leq 100

1 \leq A_i \leq 1000

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_N

Output

Print a decimal number (or an integer) representing the value of \frac{1}{\frac{1}{A_1} + \ldots + \frac{1}{A_N}}.

Your output will be judged correct when its absolute or relative error from the judge's output is at most 10^{-5}.

Sample Input 1

2
10 30

Sample Output 1

7.5

\frac{1}{\frac{1}{10} + \frac{1}{30}} = \frac{1}{\frac{4}{30}} = \frac{30}{4} = 7.5.

Printing 7.50001, 7.49999, and so on will also be accepted.

Sample Input 2

3
200 200 200

Sample Output 2

66.66666666666667

\frac{1}{\frac{1}{200} + \frac{1}{200} + \frac{1}{200}} = \frac{1}{\frac{3}{200}} = \frac{200}{3} = 66.6666....

Printing 6.66666e+1 and so on will also be accepted.

Sample Input 3

1
1000

Sample Output 3

1000

\frac{1}{\frac{1}{1000}} = 1000.

Printing +1000.0 and so on will also be accepted.


package main

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

func main() {
	var a int
	var st string
	fmt.Scan(&a)
	fmt.Scan(&st)
	sts := strings.Split(st, " ")
	var total float64
	for i := 0; i < a; i++ {
		v := sts[i]
		n, _ := strconv. ParseFloat(v, 64)
		var x float64
		x = 1 / n
		total = total + x
	}

	var ans float64
	ans = 1 / total
	fmt.Println(ans)
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

func lowerBound(a []int, x int) int {
        n := len(a)
        ok := n
        ng := -1
        for ok-ng > 1 {
                mid := (ok + ng) / 2
                if a[mid] >= x {
                        ok = mid
                } else {
                        ng = mid
                }
        }
        return ok
}

func main() {
        var s string
        var t string

        s = readLine()
        t = readLine()

        idxs := make([][]int, 256)

        for i := 0; i < len(s); i++ {
                idxs[s[i]] = append(idxs[s[i]], i)
        }

        n := int64(len(s))
        cur := int64(0)
        ng := false

        for i := 0; i < len(t); i++ {
                is := idxs[t[i]]
                if is == nil || len(is) == 0 {
                        ng = true
                        break
                }
                base := (cur / n) * n

                nidx := lowerBound(is, int(cur%n))
                if nidx == len(is) {
                        cur = base + int64(is[0]) + n + 1
                } else {
                        cur = base + int64(is[nidx]) + 1
                }
        }
        if ng {
                fmt.Println(-1)
        } else {
                fmt.Println(cur)
        }
}

Score : 500 points

Problem Statement

Given are two strings s and t consisting of lowercase English letters. Determine if there exists an integer i satisfying the following condition, and find the minimum such i if it exists.

Let s' be the concatenation of 10^{100} copies of s. t is a subsequence of the string {s'}_1{s'}_2\ldots{s'}_i (the first i characters in s').

Notes

A subsequence of a string a is a string obtained by deleting zero or more characters from a and concatenating the remaining characters without changing the relative order. For example, the subsequences of contest include net, c, and contest.

Constraints

1 \leq |s| \leq 10^5

1 \leq |t| \leq 10^5

s and t consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s
t

Output

If there exists an integer i satisfying the following condition, print the minimum such i; otherwise, print -1.

Sample Input 1

contest
son

Sample Output 1

10

t = son is a subsequence of the string contestcon (the first 10 characters in s' = contestcontestcontest...), so i = 10 satisfies the condition.

On the other hand, t is not a subsequence of the string contestco (the first 9 characters in s'), so i = 9 does not satisfy the condition.

Similarly, any integer less than 9 does not satisfy the condition, either. Thus, the minimum integer i satisfying the condition is 10.

Sample Input 2

contest
programming

Sample Output 2

-1

t = programming is not a substring of s' = contestcontestcontest.... Thus, there is no integer i satisfying the condition.

Sample Input 3

contest
sentence

Sample Output 3

33

Note that the answer may not fit into a 32-bit integer type, though we cannot put such a case here.


package main

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

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

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

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

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

/* sort */
type Int64Slice []int64

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

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

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

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

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

func main() {
	buf := make([]byte, initialBufSize)
	scanner.Buffer(buf, maxBufSize)
	scanner.Split(bufio.ScanWords)
	S := readString()
	ans := int64(0)
	p := ""
	for i := 0; i < len(S); i++ {
		if p != string(S[i]) {
			ans++
			p = string(S[i])
		} else {
			if i+1 < len(S) {
				ans++
				i++
				p = string(S[i : i+2])
			}
		}
	}
	fmt.Println(ans)
}

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

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

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

func print() {
	writer.Flush()
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Score : 300 points

Problem Statement

Given is a string S consisting of lowercase English letters. Find the maximum positive integer K that satisfies the following condition:

There exists a partition of S into K non-empty strings S=S_1S_2...S_K such that S_i \neq S_{i+1} (1 \leq i \leq K-1).

Here S_1S_2...S_K represents the concatenation of S_1,S_2,...,S_K in this order.

Constraints

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

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum positive integer K that satisfies the condition.

Sample Input 1

aabbaa

Sample Output 1

4

We can, for example, divide S into four strings aa, b, ba, and a.

Sample Input 2

aaaccacabaababc

Sample Output 2

12


package main

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

var H int
var A []*pair

type pair struct {
	index int
	value int
}

func maxHeapify(i int) {
	l := 2 * i
	r := 2*i + 1
	var largest int
	if l <= H && A[l].value > A[i].value {
		largest = l
	} else {
		largest = i
	}
	if r <= H && A[r].value > A[largest].value {
		largest = r
	}
	if largest != i {
		A[i], A[largest] = A[largest], A[i]
		maxHeapify(largest)
	}
}

func extract() *pair {
	var maxv *pair
	// if H < 1 {
	// 	return &pair{
	// 		index: -1,
	// 		value: -9999999999999,
	// 	}
	// }
	maxv = A[1]
	A[1] = A[H]
	H--
	maxHeapify(1)
	return maxv
}

func increaseKey(i int, key *pair) {
	if key.value < A[i].value {
		return
	}
	A[i] = key
	for i > 1 && A[i/2].value < A[i].value {
		A[i], A[i/2] = A[i/2], A[i]
		i /= 2
	}
}

func insert(key *pair) {
	H++
	A[H] = &pair{
		index: -1,
		value: 0,
	}
	increaseKey(H, key)
}

// 1万回以上scanするならこっち(10万回で600msとかだった)
var sc = bufio.NewScanner(os.Stdin)

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

func ri() int {
	s := rs()
	a, _ := strconv.Atoi(s)
	return a
}

func main() {
	sc.Split(bufio.ScanWords)
	n := ri()
	A = make([]*pair, n+10)
	ar := make([]int, n)
	for i := range ar {
		ar[i] = ri()
	}
	br := make([]int, n)
	for i := 0; i < n; i++ {
		br[i] = ri()
		insert(&pair{
			index: i,
			value: br[i],
		})
	}
	sum := 0
	for H > 0 {
		p := extract()
		if ar[p.index] == p.value {
			continue
		}
		left := p.index - 1
		right := p.index + 1
		if left < 0 {
			left = n - 1
		}
		if right == n {
			right = 0
		}
		se := extract()
		second := se.value
		insert(se)
		mv := second
		if mm := (p.value - mv) / (br[left] + br[right]); mm >= 100 {
			value := p.value - (br[left]-br[right])*(mm-10)

			if value < ar[p.index] {
				fmt.Println(-1)
				return
			}
			sum += mm - 10
			p.value = value
			insert(p)
			br[p.index] = value
		} else {
			value := p.value - br[left] - br[right]

			if value < ar[p.index] {
				fmt.Println(-1)
				return
			}
			sum++
			p.value = value
			insert(p)
			br[p.index] = value
		}
	}
	fmt.Println(sum)
}

Score : 800 points

Problem Statement

There are N positive integers arranged in a circle.

Now, the i-th number is A_i. Takahashi wants the i-th number to be B_i. For this objective, he will repeatedly perform the following operation:

Choose an integer i such that 1 \leq i \leq N.

Let a, b, c be the (i-1)-th, i-th, and (i+1)-th numbers, respectively. Replace the i-th number with a+b+c.

Here the 0-th number is the N-th number, and the (N+1)-th number is the 1-st number.

Determine if Takahashi can achieve his objective.
If the answer is yes, find the minimum number of operations required.

Constraints

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

1 \leq A_i, B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N
B_1 B_2 ... B_N

Output

Print the minimum number of operations required, or -1 if the objective cannot be achieved.

Sample Input 1

3
1 1 1
13 5 7

Sample Output 1

4

Takahashi can achieve his objective by, for example, performing the following operations:

Replace the second number with 3.

Replace the second number with 5.

Replace the third number with 7.

Replace the first number with 13.

Sample Input 2

4
1 2 3 4
2 3 4 5

Sample Output 2

-1

Sample Input 3

5
5 6 5 2 1
9817 1108 6890 4343 8704

Sample Output 3

25


package main

import "fmt"

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

  if a + b > a - b {
    if a + b > a * b {
      fmt.Println(a + b)
    } else {
      fmt.Println(a * b)
    }
  } else {
    if a - b > a * b {
      fmt.Println(a - b)
    } else {
      fmt.Println(a * b)
    }
  }
}

Score : 100 points

Problem Statement

We have two integers: A and B.

Print the largest number among A + B, A - B, and A \times B.

Constraints

All values in input are integers.

-100 \leq A,\ B \leq 100

Input

Input is given from Standard Input in the following format:

A B

Output

Print the largest number among A + B, A - B, and A \times B.

Sample Input 1

-13 3

Sample Output 1

-10

The largest number among A + B = -10, A - B = -16, and A \times B = -39 is -10.

Sample Input 2

1 -33

Sample Output 2

34

The largest number among A + B = -32, A - B = 34, and A \times B = -33 is 34.

Sample Input 3

13 3

Sample Output 3

39

The largest number among A + B = 16, A - B = 10, and A \times B = 39 is 39.


package main

import "fmt"

func main() {
	var a, b int

	fmt.Scan(&a, &b)

	n := [3]int{a + b, a - b, a * b}
	m := n[0]
	for i := 1; i < len(n); i++ {
		if m < n[i] {
			m = n[i]
		}
	}

	fmt.Println(m)
}


package main

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

var stdin = bufio.NewScanner(os.Stdin)

func main() {
	arr := scanArrayInt()
	out := make([]string, arr[0]+(arr[0]-1))
	j := 0
	for i := arr[1] - (arr[0] - 1); i < arr[1]+(arr[0]); i++ {
		out[j] = fmt.Sprintf("%v", i)
		j++
	}
	fmt.Println(strings.Join(out, " "))
}
func scanArrayInt() []int {
	var ret = []int{}
	stdin.Scan()
	for _, s := range strings.Split(stdin.Text(), " ") {
		i, _ := strconv.Atoi(s)
		ret = append(ret, i)
	}
	return ret
}

Score : 200 points

Problem Statement

There are 2000001 stones placed on a number line. The coordinates of these stones are -1000000, -999999, -999998, \ldots, 999999, 1000000.

Among them, some K consecutive stones are painted black, and the others are painted white.

Additionally, we know that the stone at coordinate X is painted black.

Print all coordinates that potentially contain a stone painted black, in ascending order.

Constraints

1 \leq K \leq 100

0 \leq X \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K X

Output

Print all coordinates that potentially contain a stone painted black, in ascending order, with spaces in between.

Sample Input 1

3 7

Sample Output 1

5 6 7 8 9

We know that there are three stones painted black, and the stone at coordinate 7 is painted black. There are three possible cases:

The three stones painted black are placed at coordinates 5, 6, and 7.

The three stones painted black are placed at coordinates 6, 7, and 8.

The three stones painted black are placed at coordinates 7, 8, and 9.

Thus, five coordinates potentially contain a stone painted black: 5, 6, 7, 8, and 9.

Sample Input 2

4 0

Sample Output 2

-3 -2 -1 0 1 2 3

Negative coordinates can also contain a stone painted black.

Sample Input 3

1 100

Sample Output 3

100


package main

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

const pi = math.Pi

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

func main() {
	reader.Split(bufio.ScanWords)
	K, _ := strconv.Atoi(read())
	X, _ := strconv.Atoi(read())

	for i := -1000000; i <= 1000000; i++ {
		if X-K < i && i < X+K {
			fmt.Printf("%d ", i)
		}
	}
	fmt.Printf("\n")
}

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

var reader = bufio.NewScanner(os.Stdin)

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

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

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

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

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

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

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

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

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

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

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

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

type SortBy [][]int

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

type PriorityQueue []int

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


// B - One Clue
package main

import "fmt"

func main() {
	var K, X int
	fmt.Scanf("%d %d", &K, &X)

	from := X - K + 1
	to := X + K - 1
	fmt.Print(from)
	for i := from + 1; i <= to; i++ {
		fmt.Printf(" %d", i)
	}
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

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

	S := make([]string, N)
	for i := 0; i < N; i++ {
		sc.Scan()
		S[i] = sc.Text()

		sp := strings.Split(S[i], "")
		sort.Strings(sp)
		S[i] = strings.Join(sp, "")
	}

	sort.Strings(S)
	ans := 0
	cnt := 1
	for i := 1; i < N; i++ {
		if S[i] == S[i-1] {
			cnt++
		} else {
			ans += ((cnt) * (cnt - 1)) / 2
			cnt = 1
		}
	}
	ans += ((cnt) * (cnt - 1)) / 2

	fmt.Println(ans)
}

Score : 300 points

Problem Statement

We will call a string obtained by arranging the characters contained in a string a in some order, an anagram of a.

For example, greenbin is an anagram of beginner. As seen here, when the same character occurs multiple times, that character must be used that number of times.

Given are N strings s_1, s_2, \ldots, s_N. Each of these strings has a length of 10 and consists of lowercase English characters. Additionally, all of these strings are distinct. Find the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j.

Constraints

2 \leq N \leq 10^5

s_i is a string of length 10.

Each character in s_i is a lowercase English letter.

s_1, s_2, \ldots, s_N are all distinct.

Input

Input is given from Standard Input in the following format:

N
s_1
s_2
:
s_N

Output

Print the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j.

Sample Input 1

3
acornistnt
peanutbomb
constraint

Sample Output 1

1

s_1 = acornistnt is an anagram of s_3 = constraint. There are no other pairs i, j such that s_i is an anagram of s_j, so the answer is 1.

Sample Input 2

2
oneplustwo
ninemodsix

Sample Output 2

0

If there is no pair i, j such that s_i is an anagram of s_j, print 0.

Sample Input 3

5
abaaaaaaaa
oneplustwo
aaaaaaaaba
twoplusone
aaaabaaaaa

Sample Output 3

4

Note that the answer may not fit into a 32-bit integer type, though we cannot put such a case here.


//THIS IS A UBER HUGE BLACKISH DICK MOVE!
package main

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

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

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

//str := PrintlnInts(X...)

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

type freq [26]int

func str2freq(s string) freq {
	var f freq
	for i := 0; i < len(s); i++ {
		f[s[i]-'a']++
	}
	return f
}

func main() {
	n := ReadInt()
	f := make(map[freq]int)
	for i := 0; i < n; i++ {
		s := ReadString()
		f[str2freq(s)]++
	}
	ans := 0
	for _, v := range f {
		ans += v * (v - 1) / 2
	}
	fmt.Println(ans)
}

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

func min(args ...int) int {
	if len(args) == 0 {
		panic("empty!")
	}
	min := args[0]
	for i := 1; i < len(args); i++ {
		if args[i] < min {
			min = args[i]
		}
	}
	return min
}

func max(args ...int) int {
	if len(args) == 0 {
		panic("empty!")
	}
	max := args[0]
	for i := 1; i < len(args); i++ {
		if args[i] > max {
			max = args[i]
		}
	}
	return max
}

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

func gcd(args ...int) int {
	if len(args) == 0 {
		panic("empty!")
	}
	gcd := args[0]
	for i := 1; i < len(args); i++ {
		gcd = _gcd(gcd, args[i])
	}
	return gcd
}

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

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

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

func newReadString(ior io.Reader) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+11))
	// Split sets the split function for the Scanner. The default split function is ScanLines.
	// Split panics if it is called after scanning has started.
	r.Split(bufio.ScanWords)

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

// ReadInt returns an integer.
func ReadInt() int {
	return int(readInt64())
}
func 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())
}

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

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

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

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

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

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

// PrintIntsLine returns integers string delimited by a space.
func PrintlnInts(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)
}


package main

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

var s = bufio.NewScanner(os.Stdin)

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

func getInt() int {
	s.Scan()
	a, _ := strconv.Atoi(s.Text())
	return int(a)
}

func main() {
	s.Split(bufio.ScanWords)
	n := getInt()

	nums := make(map[int]uint64, n)
	for i := 0; i < n; i++ {
		str := getString()
		for j := 0; j < 10; j++ {
			n += int(str[j])
		}
		nums[n]++
	}
	fmt.Println(nums)
	var ans uint64
	ans = 0
	for _, v := range nums {
		ans += (v * (v - 1)) / 2
	}
	fmt.Println(ans)
}


package main

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

// input に使うやつ
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)
}

// string から int へ
func atoi(s string) int {
	i, _ := strconv.Atoi(s)
	return i
}

// 一つの文字を int として読み込み
func readInt() int {
	return atoi(readLine())
}

// 複数の文字を int のスライスとして読み込み
func readInts() []int {
	in := readLine()
	ins := strings.Split(in, " ")
	out := make([]int, len(ins))
	for i, v := range ins {
		out[i] = atoi(v)
	}
	return out
}

// sortしたスライスを返す
func sorted(a []int) []int {
	b := make([]int, len(a))
	copy(b, a)
	sort.Ints(b)
	return b
}

// 逆順のsort
func reverse(a []int) []int {
	b := make([]int, len(a))
	copy(b, a)
	sort.Sort(sort.Reverse(sort.IntSlice(b)))
	return b
}

func main() {
	n := readInt()
	s := make([]string, n)
	var c int
	for i := 0; i < n; i++ {
		a := strings.Split(readLine(), "")
		sort.Strings(a)
		s[i] = strings.Join(a, "")
		for j := 0; j < i; j++ {
			if s[i] == s[j] {
				c++
			}
		}
	}
	fmt.Println(c)
}


package main

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

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

var sc = newScanner()

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

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

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

type Task struct {
	a int
	b int
}

type sortTasks []Task

func (s sortTasks) Less(i, j int) bool {
	if s[i].a == s[j].a {
		return s[i].b > s[j].b
	}
	return s[i].a < s[j].a
}

func (s sortTasks) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func (s sortTasks) Len() int {
	return len(s)
}

func main() {
	n, m := scanInt(), scanInt()
	tasks := make([]Task, n)
	for i := 0; i < n; i++ {
		tasks[i] = Task{scanInt(), scanInt()}
	}
	answer := maxRevenue(n, m, tasks)
	fmt.Println(answer)
}

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

func maxRevenue(n, m int, tasks []Task) int {
	sort.Sort(sortTasks(tasks))
	edges := make([]int, m+1)
	for i := 0; i < m+1; i++ {
		edges[i] = -1
	}

	for i, nextEdge := 0, 1; i < n && nextEdge <= m; {
		debug(i, nextEdge, tasks[i])
		if tasks[i].a == nextEdge {
			edges[nextEdge] = i
			nextEdge++
			continue
		} else if tasks[i].a > nextEdge {
			nextEdge++
		} else {
			i++
		}
	}
	revenue := 0
	debug(edges)
	debug(tasks)
	// 5 3 1
	// 4 2
	for i := 1; i <= m; i++ {
		maxForDay := 0
		selected := -1
		debug("search task for day ", i)
		for j := i; j > 0; j-- {
			debug(edges)
			if edges[j] == -1 {
				continue
			}
			t := tasks[edges[j]]
			if t.a <= j && t.b > maxForDay {
				maxForDay = tasks[edges[j]].b
				selected = j
			}
		}
		if selected != -1 {
			debug("selected", selected)
			debug("selected for day ", i, " :", selected, tasks[edges[selected]])
			edges[selected]++
			revenue += maxForDay
		}
	}
	return revenue
}

Score : 400 points

Problem Statement

There are N one-off jobs available. If you take the i-th job and complete it, you will earn the reward of B_i after A_i days from the day you do it.

You can take and complete at most one of these jobs in a day.

However, you cannot retake a job that you have already done.

Find the maximum total reward that you can earn no later than M days from today.

You can already start working today.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i \leq 10^5

1 \leq B_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

Print the maximum total reward that you can earn no later than M days from today.

Sample Input 1

3 4
4 3
4 1
2 2

Sample Output 1

5

You can earn the total reward of 5 by taking the jobs as follows:

Take and complete the first job today. You will earn the reward of 3 after four days from today.

Take and complete the third job tomorrow. You will earn the reward of 2 after two days from tomorrow, that is, after three days from today.

Sample Input 2

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

Sample Output 2

10

Sample Input 3

1 1
2 1

Sample Output 3

0


package main

import (
	"fmt"
	"io"
	"os"
	"sort"

)

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

type inInfo struct {
	in    int
	after int
}

type inInfoSorter []inInfo

func (a inInfoSorter) Len() int      { return len(a) }
func (a inInfoSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a inInfoSorter) Less(i, j int) bool {
	switch {
	case a[i].in > a[j].in:
		return true
	case a[i].in < a[j].in:
		return false
	case a[i].after > a[j].after:
		return true
	default:
		return false
	}
}

func sum(w []int) int {
	s := 0
	for _, v := range w {
		s += v
	}
	return s
}

type ptr []int

func (x ptr) top(i int) int {
	ptrs := []int(x)
	var his []int
	cur := i
	for ; cur >= 0 && ptrs[cur] != cur; cur = ptrs[cur] {
		his = append(his, cur)
	}
	for _, v := range his {
		ptrs[v] = cur - 1
	}
	if cur >= 0 {
		ptrs[cur] = cur - 1
	}
	return cur
}

func solve(stdin io.Reader, stdout io.Writer) {
	var n, m int
	var infos []inInfo

	fmt.Fscanln(stdin, &n, &m)

	for i := 0; i < n; i++ {
		var info inInfo
		fmt.Fscanln(stdin, &info.after, &info.in)
		infos = append(infos, info)
	}

	sort.Sort(inInfoSorter(infos))

	var ans = make([]int, m)
	var p = make([]int, m)
	for i := range p {
		p[i] = i
	}
	ptrs := ptr(p)

	for _, w := range infos {
		i := ptrs.top(m - w.after)
		if i >= 0 {
			ans[i] = w.in
		}
	}

	fmt.Fprintln(stdout, sum(ans))

}


package main

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

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

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

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

type item struct {
	index int
	A     int
	B     int
}

type priorityQueue []*item

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

func (pq priorityQueue) Less(i, j int) bool {
	return pq[i].B > pq[j].B
}

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

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

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

func main() {
	input := bufio.NewReader(os.Stdin)

	var N, M int
	fmt.Fscanf(input, "%d %d\n", &N, &M)
	A := make([]int, N)
	B := make([]int, N)
	for n := 0; n < N; n++ {
		fmt.Fscanf(input, "%d %d\n", &A[n], &B[n])
	}

	m := make([][]int, M+1)
	for i := range m {
		m[i] = make([]int, 0)
	}
	for n := 0; n < N; n++ {
		if A[n] <= M {
			m[A[n]] = append(m[A[n]], n)
		}
	}

	pq := make(priorityQueue, 0)
	heap.Init(&pq)
	var ans int
	for i := 1; i <= M; i++ {
		for _, n := range m[i] {
			item := &item{
				A: A[n],
				B: B[n],
			}
			heap.Push(&pq, item)
			heap.Fix(&pq, item.index)
		}
		if pq.Len() > 0 {
			x := heap.Pop(&pq)
			item := x.(*item)
			ans += item.B
		}
	}
	fmt.Println(ans)
}


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

func Inverse(p int) []int {
  Inv := make([]int, p)
  Inv[0] = 1
  Inv[1] = 1
  for i := 2; i < p; i++ {
    Inv[i] = p - Inv[p % i] * (p / i) % p
  }
  return Inv
}

type ModIntOperator struct {
  Inv []int
  Mod int
}
func InitMIO(p int) ModIntOperator {
  Inv := Inverse(p)
  return ModIntOperator{Inv, p}
}
func (M ModIntOperator) Num(a int) int {
  a %= M.Mod
  if a < 0 { a += M.Mod }
  return a
}
func (M ModIntOperator) Add(a, b int) int {
  return (M.Num(a) + M.Num(b)) % M.Mod
}
func (M ModIntOperator) Sub(a, b int) int {
  return (M.Num(a) - M.Num(b) + M.Mod) % M.Mod
}
func (M ModIntOperator) Mul(a, b int) int {
  return M.Num(a) * M.Num(b) % M.Mod
}
func (M ModIntOperator) Div(a, b int) int {
  return M.Num(a) * M.Inv[M.Num(b)] % M.Mod
}

func Solve() {
  var p, d, m int
  var A []int
  NextInt(&p)
  NextIntVec(&A)
  M := InitMIO(p)
  B := make([][]int, p)
  for i := range B {
    B[i] = make([]int, p)
    B[i][0]++
    for j := range B[i][1:] {
      B[i][j + 1] = M.Mul(B[i][j], i)
    }
  }
  for i := 0; i < p; i++ {
    d = B[i][i]
    for j := i; j < p; j++ { B[i][j] = M.Div(B[i][j], d) }
    A[i] = M.Div(A[i], d)
    for j := 1; j < p; j++ {
      if i == j { continue }
      m = B[j][i]
      for k := i; k < p; k++ {
        B[j][k] = M.Sub(B[j][k], M.Mul(B[i][k], m))
      }
      A[j] = M.Sub(A[j], M.Mul(A[i], m))
    }
  }
  for _, b := range B { fmt.Println(b) }
  WriteIntVec(A)
}

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

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

Score : 600 points

Problem Statement

Given are a prime number p and a sequence of p integers a_0, \ldots, a_{p-1} consisting of zeros and ones.

Find a polynomial of degree at most p-1, f(x) = b_{p-1} x^{p-1} + b_{p-2} x^{p-2} + \ldots + b_0, satisfying the following conditions:

For each i (0 \leq i \leq p-1), b_i is an integer such that 0 \leq b_i \leq p-1.

For each i (0 \leq i \leq p-1), f(i) \equiv a_i \pmod p.

Constraints

2 \leq p \leq 2999

p is a prime number.

0 \leq a_i \leq 1

Input

Input is given from Standard Input in the following format:

p
a_0 a_1 \ldots a_{p-1}

Output

Print b_0, b_1, \ldots, b_{p-1} of a polynomial f(x) satisfying the conditions, in this order, with spaces in between.

It can be proved that a solution always exists. If multiple solutions exist, any of them will be accepted.

Sample Input 1

2
1 0

Sample Output 1

1 1

f(x) = x + 1 satisfies the conditions, as follows:

f(0) = 0 + 1 = 1 \equiv 1 \pmod 2

f(1) = 1 + 1 = 2 \equiv 0 \pmod 2

Sample Input 2

3
0 0 0

Sample Output 2

0 0 0

f(x) = 0 is also valid.

Sample Input 3

5
0 1 0 1 0

Sample Output 3

0 2 0 1 3


package main

import (
	"fmt"
)

func main() {
	var A, B, C int
	fmt.Scanln(&A, &B, &C)

	ans := C - (A - B)
	if ans < 0 {
		ans = 0
	}
	fmt.Println(ans)
}

Score : 100 points

Problem Statement

We have two bottles for holding water.

Bottle 1 can hold up to A milliliters of water, and now it contains B milliliters of water.

Bottle 2 contains C milliliters of water.

We will transfer water from Bottle 2 to Bottle 1 as much as possible.

How much amount of water will remain in Bottle 2?

Constraints

All values in input are integers.

1 \leq B \leq A \leq 20

1 \leq C \leq 20

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the integer representing the amount of water, in milliliters, that will remain in Bottle 2.

Sample Input 1

6 4 3

Sample Output 1

1

We will transfer two milliliters of water from Bottle 2 to Bottle 1, and one milliliter of water will remain in Bottle 2.

Sample Input 2

8 3 9

Sample Output 2

4

Sample Input 3

12 3 7

Sample Output 3

0


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

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

func main(){
	sc.Split(bufio.ScanWords)
	a, b, c := nextInt(), nextInt(), nextInt()
	ans := c - a + b
  if ans < 0 {
    ans = 0
  }
  fmt.Println(ans)
}


package main

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

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

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

	if a-b >= c {
		fmt.Println(0)
	} else {
		fmt.Println(c - a + b)
	}
}

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

var dx = []int{0, 1, 0, -1, 0}
var dy = []int{1, 0, -1, 0, 0}
var inf = int(1e9)

func pow(a, b int) int {
	return int(math.Pow(float64(a), float64(b)))
}

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

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

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

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

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

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

type pair struct {
	a, b int
}

type pairs []pair

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

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

func (p pairs) Less(i, j int) bool {
	if p[i].a == p[j].a {
		return p[i].b < p[j].b
	}
	return p[i].a < p[j].a
}

var nextReader func() []byte

func init() {
	nextReader = newScanner()
	log.SetFlags(log.Lshortfile)
}

func newScanner() func() []byte {
	r := bufio.NewScanner(os.Stdin)
	r.Buffer(make([]byte, 1024), int(1e+11))
	r.Split(bufio.ScanWords)
	return func() []byte {
		r.Scan()
		return r.Bytes()
	}
}

func nextBytes() []byte {
	return nextReader()
}

func nextString() string {
	return string(nextReader())
}

func nextInt64() int64 {
	v, _ := strconv.ParseInt(string(nextReader()), 10, 64)
	return v
}

func nextInt() int {
	v, _ := strconv.Atoi(string(nextReader()))
	return v
}

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

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


package main

import "fmt"

func main() {
	var N int
	fmt.Scanf("%d", &N)
	count := 0
	for i := 1; i <= N; i++ {
		if 1 <= i && i < 10 || 100 <= i && i < 1000 || 10000 <= i && i < 100000 {
			count++
		}
	}
	fmt.Println(count)
}

Score : 200 points

Problem Statement

Given is an integer N. Find the number of positive integers less than or equal to N that have an odd number of digits (in base ten without leading zeros).

Constraints

1 \leq N \leq 10^5

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of positive integers less than or equal to N that have an odd number of digits.

Sample Input 1

11

Sample Output 1

9

Among the positive integers less than or equal to 11, nine integers have an odd number of digits: 1, 2, \ldots, 9.

Sample Input 2

136

Sample Output 2

46

In addition to 1, 2, \ldots, 9, another 37 integers also have an odd number of digits: 100, 101, \ldots, 136.

Sample Input 3

100000

Sample Output 3

90909


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 scanText() string {
	sc.Scan()
	return sc.Text()
}

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

	n := scanInt()

	ans := 0
	d := 1
	for i := 1; i < n+1; i*=10 {
		if d%2 == 0 {
			d++
			continue
		}

		if n/i/10 == 0 {
			ans += n-i+1
		} else {
			ans += i*10-i
		}
		d++
	}

	fmt.Println(ans)
}


package main

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

var sc = bufio.NewScanner(os.Stdin)
var ReadString func() string
var ReadLine func() string
var ReadInt64 func() int64
var ReadInt func() int
var ReadIntSlice func(int) []int
var ReadInt64Slice func(int) []int64
var GetIntAbs func(int) int
var Atoi func(string) int
var FindMin func([] int) int
var FindMax func([] int) int
var StrReverse func(string) string

func init() {
	ReadString = newReadString()
	ReadLine = readLine
	ReadInt64 = readInt64
	ReadInt = readInt
	ReadIntSlice = readIntSlice
	FindMin = findMin
	FindMax = findMax
	StrReverse = strReverse
  GetIntAbs = getIntAbs
}

func main() {
	n := ReadInt()
  var ans int
  for i := 1; i <= n; i++ {
    s := len(strconv.Itoa(i))
    if s % 2 == 1 {
      ans++
    }
  }
  fmt.Println(ans)
}

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

func newReadString() func() string {
	sc.Buffer(make([]byte, 1024), 2048)
	sc.Split(bufio.ScanWords)
	return func() string {
		if !sc.Scan() {
			panic("scanできなかった")
		}
		return sc.Text()
	}
}

func readLine() string {
	if !sc.Scan() {
		panic("line をscanできなかった")
	}
	return sc.Text()
}

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

func readInt() int {
	i := ReadInt64()
	return int(i)
}

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

func readInt64Slice(n int) []int64 {
	arr := make([]int64, n)
	for i := 0; i < n; i++ {
		arr[i] = ReadInt64()
	}
	return arr
}

/*------ number util ------*/

func getIntAbs(n int) int {
	if n < 0 {
		return -n
	}
	return n
}

func atoi(a string) int {
	i, err := strconv.Atoi(a)
	if err != nil {
		panic(err.Error())
	}
	return i
}

func findMin(arr []int) int {
	if len(arr) == 0 {
		return 0
	}
	min := arr[0]
	for _, v := range arr {
		if v < min {
			min = v
		}
	}
	return min
}

func findMax(arr []int) int {
	if len(arr) == 0 {
		return 0
	}
	max := arr[0]
	for _, v := range arr {
		if v > max {
			max = v
		}
	}
	return max
}


package main

import (
	"fmt"
)

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

	keta := 6
	warukazu := 100000
	for N/warukazu < 1 {
		warukazu /= 10
		keta--
	}

	var count int
	if keta <= 1 {
		count = 1
	} else if keta <= 2 {
		count = 9
	} else if keta <= 3 {
		count = N - 90
	} else if keta <= 4 {
		count = 909
	} else if keta <= 5 {
		count = N - 9090
	} else if keta <= 6 {
		count = 90909
	}

	fmt.Printf("%d\n", count)

}


package main

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

func gcdInt64(m, n int64) int64 {
	for m%n != 0 {
		m, n = n, m%n
	}
	return n
}

func lcmInt64(m, n int64) int64 {
	return m / gcdInt64(m, n) * n
}

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

type int64Array []int64

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

type xxx struct {
	x int
}

type sortArray []xxx

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

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

func main() {
	s := readString()
	ans := make([]int, len(s))

	for i := range s {
		c := s[i]
		j := 1
		if c == 'R' {
			for s[i+j] == 'R' {
				j++
			}
			if j%2 == 0 {
				ans[i+j]++
			} else {
				ans[i+j-1]++
			}
		} else {
			for s[i-j] == 'L' {
				j++
			}
			if j%2 == 0 {
				ans[i-j]++
			} else {
				ans[i-j+1]++
			}
		}
	}

	for i := range ans {
		fmt.Printf("%v ", ans[i])
	}
}

Score : 400 points

Problem Statement

Given is a string S consisting of L and R.

Let N be the length of S. There are N squares arranged from left to right, and the i-th character of S from the left is written on the i-th square from the left.

The character written on the leftmost square is always R, and the character written on the rightmost square is always L.

Initially, one child is standing on each square.

Each child will perform the move below 10^{100} times:

Move one square in the direction specified by the character written in the square on which the child is standing. L denotes left, and R denotes right.

Find the number of children standing on each square after the children performed the moves.

Constraints

S is a string of length between 2 and 10^5 (inclusive).

Each character of S is L or R.

The first and last characters of S are R and L, respectively.

Input

Input is given from Standard Input in the following format:

S

Output

Print the number of children standing on each square after the children performed the moves, in order from left to right.

Sample Input 1

RRLRL

Sample Output 1

0 1 2 1 1

After each child performed one move, the number of children standing on each square is 0, 2, 1, 1, 1 from left to right.

After each child performed two moves, the number of children standing on each square is 0, 1, 2, 1, 1 from left to right.

After each child performed 10^{100} moves, the number of children standing on each square is 0, 1, 2, 1, 1 from left to right.

Sample Input 2

RRLLLLRLRRLL

Sample Output 2

0 3 3 0 0 0 1 1 0 2 2 0

Sample Input 3

RRRLLRLLRRRLLLLL

Sample Output 3

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


package main

import (
	"fmt"
	"math"
)

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

	nums := make([]int, int(math.Pow(2, float64(n))))
	max := 0
	for i := 0; i < int(math.Pow(2, float64(n))); i++ {
		fmt.Scan(&nums[i])
		if nums[i] > max {
			max = nums[i]
		}
	}

	maxCount := 0
	condition := 0
	for _, num := range nums {
		if num == max {
			maxCount++
		}
		if maxCount > 1 {
			break
		}
	}
	condition = 1
	if maxCount > condition {
		fmt.Println("No")
		return
	}

	maxCount = 0
	for _, num := range nums {
		if num == max-1 {
			maxCount++
		}
		if maxCount > n {
			break
		}
	}
	condition = n
	if maxCount > condition {
		fmt.Println("No")
		return
	}

	maxCount = 0
	for _, num := range nums {
		if num == max-2 {
			maxCount++
		}
		if maxCount > ((n * (n - 1)) / 2) {
			break
		}
	}
	if ((n * (n - 1)) / 2) > n {
		condition = ((n * (n - 1)) / 2)
	}
	if maxCount > condition {
		fmt.Println("No")
		return
	}

	maxCount = 0
	for _, num := range nums {
		if num == max-3 {
			maxCount++
		}
		if maxCount > ((n * (n - 1) * (n - 2)) / 6) {
			break
		}
	}
	if ((n * (n - 1) * (n - 2)) / 6) > n {
		condition = ((n * (n - 1) * (n - 2)) / 6)
	}
	if maxCount > condition {
		fmt.Println("No")
		return
	}

	maxCount = 0
	for _, num := range nums {
		if num == max-4 {
			maxCount++
		}
		if maxCount > ((n * (n - 1) * (n - 2) * (n - 3)) / 24) {
			break
		}
	}
	if ((n * (n - 1) * (n - 2) * (n - 3)) / 24) > n {
		condition = ((n * (n - 1) * (n - 2) * (n - 3)) / 24)
	}
	if maxCount > condition {
		fmt.Println("No")
		return
	}

	maxCount = 0
	for _, num := range nums {
		if num == max-5 {
			maxCount++
		}
		if maxCount > ((n * (n - 1) * (n - 2) * (n - 3) * (n - 4)) / 120) {
			break
		}
	}
	if ((n * (n - 1) * (n - 2) * (n - 3) * (n - 4)) / 120) > n {
		condition = ((n * (n - 1) * (n - 2) * (n - 3) * (n - 4)) / 120)
	}
	if maxCount > condition {
		fmt.Println("No")
		return
	}

	fmt.Println("Yes")
}

Score : 600 points

Problem Statement

We have a set S of N points in a two-dimensional plane. The coordinates of the i-th point are (x_i, y_i). The N points have distinct x-coordinates and distinct y-coordinates.

For a non-empty subset T of S, let f(T) be the number of points contained in the smallest rectangle, whose sides are parallel to the coordinate axes, that contains all the points in T. More formally, we define f(T) as follows:

f(T) := (the number of integers i (1 \leq i \leq N) such that a \leq x_i \leq b and c \leq y_i \leq d, where a, b, c, and d are the minimum x-coordinate, the maximum x-coordinate, the minimum y-coordinate, and the maximum y-coordinate of the points in T)

Find the sum of f(T) over all non-empty subset T of S. Since it can be enormous, print the sum modulo 998244353.

Constraints

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

-10^9 \leq x_i, y_i \leq 10^9

x_i \neq x_j (i \neq j)

y_i \neq y_j (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the sum of f(T) over all non-empty subset T of S, modulo 998244353.

Sample Input 1

3
-1 3
2 1
3 -2

Sample Output 1

13

Let the first, second, and third points be P_1, P_2, and P_3, respectively. S = \{P_1, P_2, P_3\} has seven non-empty subsets, and f has the following values for each of them:

f(\{P_1\}) = 1

f(\{P_2\}) = 1

f(\{P_3\}) = 1

f(\{P_1, P_2\}) = 2

f(\{P_2, P_3\}) = 2

f(\{P_3, P_1\}) = 3

f(\{P_1, P_2, P_3\}) = 3

The sum of these is 13.

Sample Input 2

4
1 4
2 1
3 3
4 2

Sample Output 2

34

Sample Input 3

10
19 -11
-3 -12
5 3
3 -15
8 -14
-9 -20
10 -9
0 2
-7 17
6 -6

Sample Output 3

7222

Be sure to print the sum modulo 998244353.


package main

import "fmt"

func main() {
	var a, b int
	fmt.Scan(&a, &b)
	if (a+b)%2 == 0 {
		fmt.Println((a + b) / 2)
	} else {
		fmt.Println("IMPOSSIBLE")
	}
}

Score: 100 points

Problem Statement

We have two distinct integers A and B.

Print the integer K such that |A - K| = |B - K|.

If such an integer does not exist, print IMPOSSIBLE instead.

Constraints

All values in input are integers.

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

A and B are distinct.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the integer K satisfying the condition.

If such an integer does not exist, print IMPOSSIBLE instead.

Sample Input 1

2 16

Sample Output 1

9

|2 - 9| = 7 and |16 - 9| = 7, so 9 satisfies the condition.

Sample Input 2

0 3

Sample Output 2

IMPOSSIBLE

No integer satisfies the condition.

Sample Input 3

998244353 99824435

Sample Output 3

549034394


package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scanf("%d", &n)
	before := 0
	count := 0
	for i := 0; i < n; i++ {
		var v int
		fmt.Scanf("%d", &v)
		if v - before != 1 {
			count++
		}
		before++
	}
	fmt.Println(count)
	if count == 2 || count == 0 {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

Score : 200 points

Problem Statement

We have a sequence p = {p_1,\ p_2,\ ...,\ p_N} which is a permutation of {1,\ 2,\ ...,\ N}.

You can perform the following operation at most once: choose integers i and j (1 \leq i < j \leq N), and swap p_i and p_j. Note that you can also choose not to perform it.

Print YES if you can sort p in ascending order in this way, and NO otherwise.

Constraints

All values in input are integers.

2 \leq N \leq 50

p is a permutation of {1,\ 2,\ ...,\ N}.

Input

Input is given from Standard Input in the following format:

N
p_1 p_2 ... p_N

Output

Print YES if you can sort p in ascending order in the way stated in the problem statement, and NO otherwise.

Sample Input 1

5
5 2 3 4 1

Sample Output 1

YES

You can sort p in ascending order by swapping p_1 and p_5.

Sample Input 2

5
2 4 3 5 1

Sample Output 2

NO

In this case, swapping any two elements does not sort p in ascending order.

Sample Input 3

7
1 2 3 4 5 6 7

Sample Output 3

YES

p is already sorted in ascending order, so no operation is needed.


package main

import (
	"fmt"
	//"strings"
)

func main() {
	var n int
	fmt.Scan(&n)
	p := scanNums(n)
	count := 0
	for i := 0; i < n; i++ {
		if p[i] != i+1 {
			count++
		}
	}
	if count == 2 || count == 0 {
		fmt.Print("YES")
	} else {
		fmt.Print("NO")
	}
}

func scanNums(len int) (nums []int) {
	var num int
	for i := 0; i < len; i++ {
		fmt.Scan(&num)
		nums = append(nums, num)
	}
	return
}


package main

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

func main() {
	n := getInt()
	ps := getIntSlice(n)

	cnt := 0
	for i, p := range ps {
		if p != i+1 {
			cnt++
		}
	}

	ans := "YES"
	if cnt > 2 {
		ans = "NO"
	}
	fmt.Println(ans)
}

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

var scanner = wordScanner()

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

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

func getIntSlice(n int) []int {
	is := make([]int, n)
	for i := range is {
		is[i] = getInt()
	}
	return is
}

func getString() string {
	scanner.Scan()
	s := scanner.Text()
	return s
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

func main() {
	var n int
	fmt.Scanf("%d", &n)
	l := nextLine()

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

	for i, h := range strings.Split(l, " ") {
		integer, _ := strconv.Atoi(h)
		a[i] = integer
	}

	l = nextLine()

	for i, h := range strings.Split(l, " ") {
		integer, _ := strconv.Atoi(h)
		b[i] = integer
	}

	total := 0
	for i:=0; i<n ; i++ {
		if a[i] < b[i] {
			total += a[i]
			b[i] = b[i] - a[i]
			a[i] = 0
		} else {
			total += b[i]
			a[i] = a[i] - b[i]
			b[i] = 0
		}

		if a[i+1] < b[i] {
			total += a[i+1]
			b[i] = b[i] - a[i+1]
			a[i+1] = 0
		} else {
			total += b[i]
			a[i+1] = a[i+1] - b[i]
			b[i] = 0
		}
	}

	fmt.Printf("%d", total)
}

Score : 300 points

Problem Statement

There are N+1 towns. The i-th town is being attacked by A_i monsters.

We have N heroes. The i-th hero can defeat monsters attacking the i-th or (i+1)-th town, for a total of at most B_i monsters.

What is the maximum total number of monsters the heroes can cooperate to defeat?

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_{N+1}
B_1 B_2 ... B_N

Output

Print the maximum total number of monsters the heroes can defeat.

Sample Input 1

2
3 5 2
4 5

Sample Output 1

9

If the heroes choose the monsters to defeat as follows, they can defeat nine monsters in total, which is the maximum result.

The first hero defeats two monsters attacking the first town and two monsters attacking the second town.

The second hero defeats three monsters attacking the second town and two monsters attacking the third town.

Sample Input 2

3
5 6 3 8
5 100 8

Sample Output 2

22

Sample Input 3

2
100 1 1
1 100

Sample Output 3

3


package main

import (
	"fmt"
)

const MOD = 1000000007

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

	n := len(s)
	dp := make([][]int, n)
	for i := 0; i < n; i++ {
		dp[i] = make([]int, 13)
	}

	if s[n-1] == '?' {
		for i := 0; i < 13; i++ {
			if i < 10 {
				dp[n-1][i] = 1
			} else {
				dp[n-1][i] = 0
			}
		}
	} else {
		c := int(s[n-1] - '0')
		for i := 0; i < 13; i++ {
			if i == c {
				dp[n-1][i] = 1
			} else {
				dp[n-1][i] = 0
			}
		}
	}

	digit := 10
	for i := n - 2; i >= 0; i-- {
		if s[i] == '?' {
			for m := 0; m < 10; m++ {
				for mod, cnt := range dp[i+1] {
					shifted := (mod + m * digit) % 13
					dp[i][shifted] += cnt
				}
			}
		} else {
			m := int(s[i] - '0')
			for mod, cnt := range dp[i+1] {
				shifted := (mod + m * digit) % 13
				dp[i][shifted] += cnt
			}
		}

		for j := 0; j < 13; j++ {
			dp[i][j] %= MOD
		}
		digit = (digit * 10) % 13
	}

	fmt.Println(dp[0][5])
}

Score : 400 points

Problem Statement

Given is a string S. Each character in S is either a digit (0, ..., 9) or ?.

Among the integers obtained by replacing each occurrence of ? with a digit, how many have a remainder of 5 when divided by 13? An integer may begin with 0.

Since the answer can be enormous, print the count modulo 10^9+7.

Constraints

S is a string consisting of digits (0, ..., 9) and ?.

1 \leq |S| \leq 10^5

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

??2??5

Sample Output 1

768

For example, 482305, 002865, and 972665 satisfy the condition.

Sample Input 2

?44

Sample Output 2

1

Only 044 satisfies the condition.

Sample Input 3

7?4

Sample Output 3

0

We may not be able to produce an integer satisfying the condition.

Sample Input 4

?6?42???8??2??06243????9??3???7258??5??7???????774????4?1??17???9?5?70???76???

Sample Output 4

153716888