package main

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

)

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

type ReaderEx struct {
	baseScanner *bufio.Scanner
	words       []string
	nextWordIdx func() int
	initWordIdx func(int)
}

func NewScannerEx(stdin io.Reader) *ReaderEx {
	var this ReaderEx
	var idx int
	var wordsCnt int
	this.baseScanner = bufio.NewScanner(stdin)
	this.baseScanner.Buffer(make([]byte, 0), 1E+11)
	this.nextWordIdx = func() int {
		cur := idx
		idx = (idx + 1) % wordsCnt
		return cur
	}
	this.initWordIdx = func(wc int) {
		idx = 0
		wordsCnt = wc
	}
	return &this
}

func (me *ReaderEx) Scan(doSplit bool) (isScanned bool) {
	isScanned = me.baseScanner.Scan()
	if doSplit {
		me.words = strings.Fields(me.baseScanner.Text())
	} else {
		me.words = []string{me.baseScanner.Text()}
	}
	me.initWordIdx(len(me.words))
	return
}

func (me *ReaderEx) nextBytes() []byte {
	return []byte(me.words[me.nextWordIdx()])
}
func (me *ReaderEx) nextString() string {
	return me.words[me.nextWordIdx()]
}

type StringArray []string

func (me *ReaderEx) nextStringArray() StringArray {
	return me.words[me.nextWordIdx():]
}

func (me StringArray) toStrings() []string {
	return me
}

func (me StringArray) toInts() []int {
	strValues := me.toStrings()
	values := make([]int, len(strValues))
	for i, v := range strValues {
		n, err := strconv.Atoi(v)
		if err != nil {
			panic(err)
		}
		values[i] = n
	}
	return values
}
func (me *ReaderEx) nextInt() int {
	n, err := strconv.Atoi(me.words[me.nextWordIdx()])

	defer func() {
		if err != nil {
			panic(fmt.Sprintf("getInt(%d)", n))
		}
	}()
	return n
}

func pow(x, y, mod int) (ans int) {

	ans = 1
	for bit := 1 << uint(math.Floor(math.Log2(float64(y)))); ; bit >>= 1 {
		if y&bit != 0 {
			ans *= x
			if mod > 0 {
				ans %= mod
			}
		}
		if bit <= 1 {
			return
		}
		ans *= ans
		if mod > 0 {
			ans %= mod
		}
	}
}

type factType struct {
	prime int
	count int
}

func fact(n int) (facts []*factType) {

	for i := 2; i*i <= n; i++ {
		if n%i == 0 {
			fa := factType{prime: i}
			for n%fa.prime == 0 {
				n /= fa.prime
				fa.count++
			}
			facts = append(facts, &fa)
		}
	}
	if n > 1 {
		facts = append(facts, &factType{prime: n, count: 1})
	}
	return facts
}
func dec2bin(n int) (ret []bool) {
	for bit := 1 << uint(math.Floor(math.Log2(float64(n)))); ; bit >>= 1 {
		ret = append(ret, n&bit != 0)

		if bit <= 1 {
			return
		}
	}

}

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

func b2i(b bool) (i int) {
	if b {
		i = 1
	} else {
		i = 0
	}
	return
}

//RBNodeDir is
type RBNodeDir int

const (

	//RBNodeLeft is
	RBNodeLeft RBNodeDir = iota

	//RBNodeRight is
	RBNodeRight

	//RBNodeHere is
	RBNodeHere
)

//RBNode is
type RBNode struct {
	isRed    bool
	Index    int
	parent   *RBNode
	children [2]*RBNode
}

//RBTree is
type RBTree struct {
	Node *RBNode
	less func(i int, j int) bool
}

//RBCursor is
type RBCursor RBTree

//NewTree is
func NewTree(less func(i int, j int) bool) *RBTree {
	tree := &RBTree{less: less}
	return tree
}

//Cursor is
func (cur *RBTree) Cursor() *RBCursor {
	wrk := RBCursor(*cur)
	return &wrk
}

func (cur *RBTree) root() *RBTree {

	if cur.Node != nil {
		for ; cur.Node.parent != nil; cur.Node = cur.Node.parent {

		}
	}
	return cur
}

//Move is
func (cur *RBCursor) Move(dir RBNodeDir) *RBCursor {
	rev := dir ^ 1
	if next := cur.Node.children[dir]; next != nil {
		for next.children[rev] != nil {
			next = next.children[rev]
		}
		cur.Node = next
	} else {
		find := false
		for cur.Node.parent != nil {
			now := cur.Node
			cur.Node = cur.Node.parent
			if cur.Node.children[rev] == now {
				find = true
				break
			}
		}
		if !find {
			cur.Node = nil
		}
	}
	return cur
}

//Find is
func (cur *RBTree) Find(Index int) (*RBTree, RBNodeDir) {
	dir := RBNodeLeft
	if cur.Node == nil {
		return cur, dir
	}
	cur.root()
	for {
		if cur.less(Index, cur.Node.Index) {
			dir = RBNodeLeft
			next := cur.Node.children[dir]
			if next == nil {
				break
			}
			cur.Node = next

		} else if cur.less(cur.Node.Index, Index) {
			dir = RBNodeRight
			next := cur.Node.children[dir]
			if next == nil {
				break
			}
			cur.Node = next
		} else {
			dir = RBNodeHere
			break
		}
	}
	return cur, dir
}

//Add is
func (cur *RBTree) Add(Index int) *RBTree {
	newNode := &RBNode{Index: Index, isRed: true}
	cur.root()
	if cur.Node != nil {
		pnode, dir := cur.Find(newNode.Index)
		if dir != RBNodeHere {
			newNode.parent = pnode.Node
			newNode.parent.children[dir] = newNode
			newNode.opt()
		} else {
			pnode.Node.Index = newNode.Index
			newNode = pnode.Node
		}
	}
	cur.Node = newNode
	return cur
}

func (Node *RBNode) flip(dir RBNodeDir) {
	curGranPa := Node.parent
	newParent := Node.children[dir]
	if curGranPa != nil {
		curGranPa.children[Node.dir()] = newParent
	}
	newParent.parent, Node.parent = Node.parent, newParent

	Node.children[dir] = newParent.children[dir^1]
	if Node.children[dir] != nil {
		Node.children[dir].parent = Node
	}
	newParent.children[dir^1] = Node

}
func (Node *RBNode) dir() RBNodeDir {
	dir := RBNodeLeft
	if Node.parent.children[dir] != Node {
		dir = RBNodeRight
	}
	return dir
}
func (Node *RBNode) opt() {
	for Node != nil && Node.isRed {
		parent := Node.parent
		if parent == nil {
			break
		} else if !parent.isRed {
			break
		} else if parent.parent == nil {
			parent.isRed = false
		} else {
			grandparent := parent.parent
			parentsibling := grandparent.children[parent.dir()^1]
			if parentsibling != nil && parentsibling.isRed {
				grandparent.isRed = true
				parent.isRed = false
				parentsibling.isRed = false
				Node = grandparent
			} else {
				dir := parent.dir()

				if parent.children[dir] != Node {
					parent.flip(dir ^ 1)
				}

				grandparent.flip(dir)
				grandparent.parent.isRed = false
				grandparent.isRed = true
				break
			}
		}
	}
}

//End is
func (cur *RBTree) End(dir RBNodeDir) *RBCursor {
	cur.root()
	if cur.Node != nil {
		for ; cur.Node.children[dir] != nil; cur.Node = cur.Node.children[dir] {

		}
	}
	return cur.Cursor()
}

func (Node *RBNode) cut() {
	if Node.parent != nil {
		Node.parent.children[Node.dir()] = nil
	}
}

func (Node *RBNode) hasDir() RBNodeDir {
	dir := RBNodeLeft
	if Node.children[dir] == nil {
		dir = RBNodeRight
		if Node.children[dir] == nil {
			dir = RBNodeHere
		}
	}
	return dir
}

//Delete is
func (cur *RBTree) Delete(Index int) (ret bool) {
	wcur, dir := cur.Find(Index)
	if dir != RBNodeHere {
		return
	}
	delNode := wcur.Node
	ret = true

	dir = delNode.hasDir()

	if delNode.children[RBNodeLeft] != nil &&
		delNode.children[RBNodeRight] != nil {
		var wrk *RBCursor
		if dir != RBNodeHere {
			wrk = wcur.Cursor().Move(dir)
			delNode.Index = wrk.Node.Index
			delNode = wrk.Node
			dir = delNode.hasDir()
		}
	}

	if dir == RBNodeHere {
		if delNode.isRed {
			delNode.cut()
			cur.Node = delNode.parent
			return
		}
	} else {
		wrk := delNode.children[dir]
		delNode.Index = wrk.Index
		wrk.cut()
		return
	}

	Node := delNode
	for {
		parent := Node.parent
		if parent == nil {
			break
		}

		dir := Node.dir()
		dirOther := dir ^ 1
		sibling := parent.children[dirOther]

		if sibling.isRed {
			//sibling is Red
			parent.flip(dirOther)
			sibling.isRed = false
			parent.isRed = true
			sibling = parent.children[dirOther]
		}
		//sibling is Black

		nephew := sibling.children[dirOther]
		if nephew == nil || !nephew.isRed {
			//far nephew is Black
			nephew = sibling.children[dir]
			if nephew == nil || !nephew.isRed {
				//near nephew is Black
				sibling.isRed = true
				if parent.isRed {
					parent.isRed = false
					break
				} else {
					Node = parent
					continue
				}
			}
			//near nephew is Red and far nephew is Black
			sibling.flip(dir)
			sibling, nephew = nephew, sibling
			sibling.isRed = false
			nephew.isRed = true
		}
		//sibling is Black && far nephew is Red

		parent.flip(dirOther)
		sibling.isRed = parent.isRed
		parent.isRed = false
		nephew.isRed = false
		break
	}
	delNode.cut()
	cur.Node = delNode.parent
	return
}

type isA int

const (
	atype isA = 1
	btype     = 2
)

type pair struct {
	a int
	b int
	i int
}
type bup []pair

func (a bup) Len() int      { return len(a) }
func (a bup) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a bup) Less(i, j int) bool {
	switch {
	case a[i].b != a[j].b:
		return a[i].b < a[j].b
	default:
		return a[i].a <= a[j].a
	}
}

type aup []*pair

func (a aup) Len() int      { return len(a) }
func (a aup) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a aup) Less(i, j int) bool {
	switch {
	case a[i].a != a[j].a:
		return a[i].a < a[j].a
	default:
		return a[i].b <= a[j].b
	}
}
func solve(stdin io.Reader, stdout io.Writer) {

	r := NewScannerEx(stdin)
	r.Scan(false)
	n := r.nextInt()
	r.Scan(true)
	a := r.nextStringArray().toInts()
	r.Scan(true)
	b := r.nextStringArray().toInts()

	targetB := make([]pair, len(a))
	ansA := make([]*pair, len(a))
	for i := range a {
		p := &targetB[i]
		p.a = a[i]
		p.b = b[i]
		ansA[i] = p
	}
	sort.Sort(bup(targetB))
	sort.Sort(aup(ansA))

	condAltB := true
	condAdpl := false
	for i := range targetB {
		if ansA[i].a > targetB[i].b {
			condAltB = false
			break
		}

		if targetB[i].a == ansA[i].a {
			condAdpl = true
		}

		if i < n-1 && ansA[i+1].a <= targetB[i].b {
			condAdpl = true
		}

	}

	ans := condAltB
	if ans {
		ans = condAdpl
		if !ans {
			for i := range ansA {
				ansA[i].i = i
			}
			cur := targetB[0].i
			cnt := 0
			for cur != 0 {
				cnt++
				cur = targetB[cur].i
			}
			if cnt <= n-2 {
				ans = true
			}
		}
	}
	fmt.Fprintln(stdout, []string{"No", "Yes"}[b2i(ans)])
}

Score : 600 points

Problem Statement

Given are two integer sequences of N elements each: A_1,...,A_N and B_1,...,B_N.
Determine if it is possible to do the following operation at most N-2 times (possibly zero) so that, for every integer i from 1 to N, A_i \leq B_i holds:

Choose two distinct integers x and y between 1 and N (inclusive), and swap the values of A_x and A_y.

Constraints

2 \leq N \leq 10^5

1 \leq A_i,B_i \leq 10^9

Input

Input is given from Standard Input in the following format:

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

Output

If the objective is achievable, print Yes; if it is not, print No.

Sample Input 1

3
1 3 2
1 2 3

Sample Output 1

Yes

We should swap the values of A_2 and A_3.

Sample Input 2

3
1 2 3
2 2 2

Sample Output 2

No

Sample Input 3

6
3 1 2 6 3 4
2 2 8 3 4 3

Sample Output 3

Yes


package main

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

func main() {
	S := ReadString()
	v := make([]int, len(S)+1)

	for i := 0; i < len(S); i++ {
		if S[i] == '<' {
			v[i+1] = v[i] + 1
		}
	}
	for i := len(S) - 1; i >= 0; i-- {
		if S[i] == '>' {
			v[i] = Max(v[i], v[i+1]+1)
		}
	}

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

func Max(xs ...int) int {
	max := xs[0]
	for _, x := range xs[1:] {
		if max < x {
			max = x
		}
	}
	return max
}

var reader = bufio.NewReader(os.Stdin)

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

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

Score : 300 points

Problem Statement

Given is a string S of length N-1.
Each character in S is < or >.

A sequence of N non-negative integers, a_1,a_2,\cdots,a_N, is said to be good when the following condition is satisfied for all i (1 \leq i \leq N-1):

If S_i= <: a_i<a_{i+1}

If S_i= >: a_i>a_{i+1}

Find the minimum possible sum of the elements of a good sequence of N non-negative integers.

Constraints

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

S is a string of length N-1 consisting of < and >.

Input

Input is given from Standard Input in the following format:

S

Output

Find the minimum possible sum of the elements of a good sequence of N non-negative integers.

Sample Input 1

<>>

Sample Output 1

3

a=(0,2,1,0) is a good sequence whose sum is 3.
There is no good sequence whose sum is less than 3.

Sample Input 2

<>>><<><<<<<>>><

Sample Output 2

28

Submitted source-code file size, in bytes.

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

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


package main

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

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

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

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

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

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

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

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

	if len(os.Args) > 1 {
		fp, _ = os.Open(os.Args[1])
		if len(os.Args) > 2 {
			wfp, _ = os.Create(os.Args[2])
		}
	}

	scanner := getScanner(fp)
	writer := bufio.NewWriter(wfp)

	n := getNextInt(scanner)
	ee := make(Enables, n)

	for i := 0; i < n; i++ {
		ee[i].l = getNextInt(scanner)
		ee[i].r = getNextInt(scanner)
	}
	sort.Sort(ee)
	seg := Segment{}
	seg.init(n)
	for i := 0; i < n; i++ {
		seg.minimize(i, ee[i].r)
	}
	var ans int64

	for i := 1; i < n; i++ {
		l := seg.min(0, i) - ee[i-1].l
		if l < 0 {
			l = -1
		}
		r := seg.min(i, n) - ee[n-1].l
		if r < 0 {
			r = -1
		}
		if ans < int64(l+r+2) {
			ans = int64(l + r + 2)
		}
	}

	fmt.Fprintln(writer, ans)
	writer.Flush()
}

type Enable struct {
	l, r int
}

type Enables []Enable

func (a Enables) Len() int           { return len(a) }
func (a Enables) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a Enables) Less(i, j int) bool {
	if a[i].l == a[j].l{
		return a[i].r > a[j].r
	}
	return a[i].l < a[j].l
}

// Segment ...
type Segment struct {
	n, h, i, chunk, inf int
	unit                []int
	bucket              [][]int
}

func (seg *Segment) init(n int) {
	seg.n = n
	seg.unit = make([]int, 1)
	seg.unit[0] = 1
	seg.bucket = make([][]int, 1)
	seg.bucket[0] = make([]int, n)

	chunk := 8
	for i := 0; n > 1; i++ {
		n = (n-1)/chunk + 1
		seg.bucket = append(seg.bucket, make([]int, n))
		seg.unit = append(seg.unit, seg.unit[i]*chunk)
	}
	seg.h = len(seg.unit)
	seg.chunk = chunk
	seg.inf = math.MaxInt32
}

func (seg *Segment) minimize(index, value int) {
	seg.bucket[0][index] = value
	for seg.i = 0; seg.i < seg.h-1; seg.i++ {
		s := index - index%seg.chunk
		t := s + seg.chunk
		if t > len(seg.bucket[seg.i]) {
			t = len(seg.bucket[seg.i])
		}
		parent := index / seg.chunk
		min := seg.inf
		for i := s; i < t; i++ {
			if min > seg.bucket[seg.i][i] {
				min = seg.bucket[seg.i][i]
			}
		}
		seg.bucket[seg.i+1][parent] = min
		index /= seg.chunk
	}
}
func (seg *Segment) min(l, r int) int {
	if seg.n < r {
		r = seg.n
	}
	min := seg.inf
	for index := l; index < r; index += seg.unit[seg.i] {
		for seg.i = 0; seg.i < seg.h-1 && index%seg.unit[seg.i+1] == 0; seg.i++ {
			if index+seg.unit[seg.i+1] >= r {
				break
			}
		}
		if min > seg.bucket[seg.i][index/seg.unit[seg.i]] {
			min = seg.bucket[seg.i][index/seg.unit[seg.i]]
		}
	}

	return min
}

Score : 600 points

Problem Statement

10^9 contestants, numbered 1 to 10^9, will compete in a competition.
There will be two contests in this competition.

The organizer prepared N problems, numbered 1 to N, to use in these contests.
When Problem i is presented in a contest, it will be solved by all contestants from Contestant L_i to Contestant R_i (inclusive), and will not be solved by any other contestants.

The organizer will use these N problems in the two contests.
Each problem must be used in exactly one of the contests, and each contest must have at least one problem.

The joyfulness of each contest is the number of contestants who will solve all the problems in the contest.
Find the maximum possible total joyfulness of the two contests.

Constraints

2 \leq N \leq 10^5

1 \leq L_i \leq R_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
L_1 R_1
L_2 R_2
\vdots
L_N R_N

Output

Print the maximum possible total joyfulness of the two contests.

Sample Input 1

4
4 7
1 4
5 8
2 5

Sample Output 1

6

The optimal choice is:

Use Problem 1 and 3 in the first contest. Contestant 5, 6, and 7 will solve both of them, so the joyfulness of this contest is 3.

Use Problem 2 and 4 in the second contest. Contestant 2, 3, and 4 will solve both of them, so the joyfulness of this contest is 3.

The total joyfulness of these two contests is 6. We cannot make the total joyfulness greater than 6.

Sample Input 2

4
1 20
2 19
3 18
4 17

Sample Output 2

34

Sample Input 3

10
457835016 996058008
456475528 529149798
455108441 512701454
455817105 523506955
457368248 814532746
455073228 459494089
456651538 774276744
457667152 974637457
457293701 800549465
456580262 636471526

Sample Output 3

540049931


package main

import "fmt"
import "sort"

type entry struct {
	lower int
	upper int
}

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

	ee := make([]entry, N)

	var iMaxL, iMinU = 0, 0
	for i := 0; i < N; i++ {
		fmt.Scan(&ee[i].lower, &ee[i].upper)
	}

	sort.Sort(byUpper(ee))

	for i := 0; i < N; i++ {
		if ee[iMaxL].lower < ee[i].lower {
			iMaxL = i
		}
		if ee[iMinU].upper > ee[i].upper {
			iMinU = i
		}
	}

	if iMaxL == iMinU {
		max := 0
		for i := 0; i < N; i++ {
			if i == iMaxL {
				continue
			}
			max = Max(max, ee[i].upper-ee[i].lower+1)
		}

		fmt.Println(max + Max(ee[iMaxL].upper-ee[iMaxL].lower+1, 0))
		return
	}

	for i := 0; i < N; i++ {
		if i == iMaxL || i == iMinU {
			continue
		}
		if ee[i].upper >= ee[iMaxL].upper {
			continue
		}
		if ee[i].lower <= ee[iMinU].lower {
			continue
		}
		scoreL := ee[i].upper - ee[iMinU].lower
		scoreU := ee[iMaxL].upper - ee[i].lower
		if scoreL > scoreU {
			ee[iMaxL].upper = ee[i].upper
		} else {
			ee[iMinU].lower = ee[i].lower
		}
	}

	result := Max(ee[iMaxL].upper-ee[iMaxL].lower+1, 0) + Max(ee[iMinU].upper-ee[iMinU].lower+1, 0)
	fmt.Println(result)
}

type byUpper []entry

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

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

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


package main

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

func main() {
	N := nextInt()
	Q := make(pairs, N)

	for i := 0; i < N; i++ {
		l := nextInt()
		r := nextInt()
		Q[i] = pair{l, r}
	}
	sort.Sort(sort.Reverse(Q))

	l1 := -1
	l2 := -1
	r1 := int(1e10 + 1)
	r2 := int(1e10 + 1)

	for i := 0; i < N; i++ {
		// 1回目に入れるか2回目に入れるかを決める
		c1 := score(min(r1, Q[i].r), max(l1, Q[i].l)) + score(r2, l2)
		c2 := score(min(r2, Q[i].r), max(l2, Q[i].l)) + score(r1, l1)

		if c1 > c2 {
			r1 = min(r1, Q[i].r)
			l1 = max(l1, Q[i].l)
		} else {
			r2 = min(r2, Q[i].r)
			l2 = max(l2, Q[i].l)
		}
	}

	s1 := score(r1, l1) + score(r2, l2)

	l1 = -1
	l2 = -1
	r1 = int(1e10 + 1)
	r2 = int(1e10 + 1)

	sort.Sort(Q)

	for i := 0; i < N; i++ {
		// 1回目に入れるか2回目に入れるかを決める
		c1 := score(min(r1, Q[i].r), max(l1, Q[i].l)) + score(r2, l2)
		c2 := score(min(r2, Q[i].r), max(l2, Q[i].l)) + score(r1, l1)

		if c1 > c2 {
			r1 = min(r1, Q[i].r)
			l1 = max(l1, Q[i].l)
		} else {
			r2 = min(r2, Q[i].r)
			l2 = max(l2, Q[i].l)
		}
	}

	s2 := score(r1, l1) + score(r2, l2)

	fmt.Println(max(s1, s2))
}

func score(r, l int) int {
	if l < 0 {
		return 0
	}

	if l > r {
		return 0
	}
	return r - l + 1
}

type pair struct {
	l int
	r int
}

type pairs []pair

func (a pairs) Len() int           { return len(a) }
func (a pairs) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a pairs) Less(i, j int) bool { return a[i].r-a[i].l < a[j].r-a[j].l }

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

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

var stdin = initStdin()

func initStdin() *bufio.Scanner {
	bufsize := 1 * 1024 * 1024 // 1 MB
	var stdin = bufio.NewScanner(os.Stdin)
	stdin.Buffer(make([]byte, bufsize), bufsize)
	stdin.Split(bufio.ScanWords)
	return stdin
}

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

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

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

func nextInt64() int64 {
	i, _ := strconv.ParseInt(nextString(), 10, 64)
	return i
}


package main

import "fmt"

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

	L := make([]int, N)
	U := make([]int, N)

	var iMaxL, iMinU = 0, 0
	for i := 0; i < N; i++ {
		fmt.Scan(&L[i], &U[i])
		if L[iMaxL] < L[i] {
			iMaxL = i
		}
		if U[iMinU] > U[i] {
			iMinU = i
		}
	}

	if iMaxL == iMinU {
		max := 0
		for i := 0; i < N; i++ {
			if i == iMaxL {
				continue
			}
			max = Max(max, U[i]-L[i]+1)
		}

		fmt.Println(max + Max(U[iMaxL]-L[iMaxL]+1, 0))
		return
	}

	uForMaxL := U[iMaxL]
	lForMinU := L[iMinU]
	for i := 0; i < N; i++ {
		if i == iMaxL || i == iMinU {
			continue
		}
		if U[i] >= U[iMaxL] {
			continue
		}
		if L[i] <= L[iMinU] {
			continue
		}
		scoreL := U[i] - L[iMinU]
		scoreU := U[iMaxL] - L[i]
		if scoreL > scoreU {
			uForMaxL = Min(U[i], uForMaxL)
		} else {
			lForMinU = Max(L[i], lForMinU)
		}
	}

	result := Max(uForMaxL-L[iMaxL]+1, 0) + Max(U[iMinU]-lForMinU+1, 0)
	fmt.Println(result)
}

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

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


package main

import (
	"fmt"
	"os"
)

func main() {
	var a int
	fmt.Scan(&a)
	if a > 81 {
		fmt.Println("No")
	} else {
		for i := 1; i < 10; i++ {
			for j := 1; j < 10; j++ {
				if a%(i*j) == 0 && a/(i*j) < 10 {
					fmt.Println("Yes")
					os.Exit(0)
				}
			}
		}
	}
	fmt.Println("No")
}

Score : 200 points

Problem Statement

Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together.

Given an integer N, determine whether N can be represented as the product of two integers between 1 and 9. If it can, print Yes; if it cannot, print No.

Constraints

1 \leq N \leq 100

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N can be represented as the product of two integers between 1 and 9 (inclusive), print Yes; if it cannot, print No.

Sample Input 1

10

Sample Output 1

Yes

10 can be represented as, for example, 2 \times 5.

Sample Input 2

50

Sample Output 2

No

50 cannot be represented as the product of two integers between 1 and 9.

Sample Input 3

81

Sample Output 3

Yes


package main

import "fmt"

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

	min := n
	for i:=1; i<=n; i++{
		for j:=i+1; j<=n; j++{
			if i*j == n && (i-1)+(j-1) < min{
				min = (i-1)+(j-1)
				break
			}
		}
	}

	fmt.Println(min)
}

Score : 300 points

Problem Statement

Takahashi is standing on a multiplication table with infinitely many rows and columns.

The square (i,j) contains the integer i \times j. Initially, Takahashi is standing at (1,1).

In one move, he can move from (i,j) to either (i+1,j) or (i,j+1).

Given an integer N, find the minimum number of moves needed to reach a square that contains N.

Constraints

2 \leq N \leq 10^{12}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum number of moves needed to reach a square that contains the integer N.

Sample Input 1

10

Sample Output 1

5

(2,5) can be reached in five moves. We cannot reach a square that contains 10 in less than five moves.

Sample Input 2

50

Sample Output 2

13

(5, 10) can be reached in 13 moves.

Sample Input 3

10000000019

Sample Output 3

10000000018

Both input and output may be enormous.


package main

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

//Util
func nextStr() string {
	sc.Scan()
	return sc.Text()
}

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

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

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

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

func absFloat64(a float64) float64 {
	if a >= 0 {
		return a
	} else {
		return -a
	}
}

func maxFloat64(a, b float64) float64 {
	if a > b {
		return a
	} else {
		return b
	}
}

func minFloat64(a, b float64) float64 {
	if a > b {
		return b
	} else {
		return a
	}
}

func str2Int(s string) int {
	n, _ := strconv.Atoi(s)
	return n
}

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

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

func isPrime(x int) bool {
	if x == 1 {
		return false
	}
	if x == 2 {
		return true
	}
	if x%2 == 0 {
		return false
	}

	b := true
	rootx := int(math.Sqrt(float64(x)))
	i := 3
	for i <= rootx {
		if x%i == 0 {
			b = false
			break
		}
		i += 2
	}
	return b
}

func PrimeFactors(n int) (pfs []int) {
	// Get the number of 2s that divide n
	for n%2 == 0 {
		pfs = append(pfs, 2)
		n = n / 2
	}

	// n must be odd at this point. so we can skip one element
	// (note i = i + 2)
	for i := 3; i*i <= n; i = i + 2 {
		// while i divides n, append i and divide n
		for n%i == 0 {
			pfs = append(pfs, i)
			n = n / i
		}
	}

	// This condition is to handle the case when n is a prime number
	// greater than 2
	if n > 2 {
		pfs = append(pfs, n)
	}

	return
}

func sumInts(x []int) int {

	total := 0
	for _, v := range x {
		total += v
	}

	return total
}

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

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

var N int

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

	N = nextInt()
	ans := powInt(10, 12)
	sqrtn := int(math.Sqrt(float64(N)))
	for x := 1; x <= sqrtn; x++ {
		if N%x != 0 {
			continue
		}
		ans = minInt(ans, x+(N/x)-2)
	}

	fmt.Println(ans)
}


package main

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

func main() {
	var n, r int
	fmt.Scan(&n)
	var a []int
	for i := 1; i*i <= n; i++ {
		if n%i == 0 {
			a = append(a, i)
			if i != n/i {
				a = append(a, n/i)
			}
		}
	}
	sort.Sort(sort.IntSlice(a))

	min := math.MaxInt64
	for i := 0; i < len(a)-1; i++ {
		for j := i + 1; j < len(a); j++ {
			if a[i]*a[j] == n {
				if min > a[j]-a[i] {
					r = (a[i] - 1) + (a[j] - 1)
					min = a[j] - a[i]
				}
			}
		}
	}
	fmt.Println(r)
}


package main

import "fmt"

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

	for i := n; i >= 1; i-- {
		for j := n; j >= i; j-- {
			if i*j == n {
				ans = i + j - 2
				fmt.Printf("%d", ans)
				goto LOOPEND
			}
		}
	}
LOOPEND:
}


package main

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

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

	n := io.Int64()

	for i := int64(2); i < int64(math.Ceil(math.Sqrt(float64(n)))); i++ {
		if n%i == 0 {
			if i*i == n {
				fmt.Println(i*2 - 1)
			} else {
				fmt.Println(int64(math.Floor(math.Sqrt(float64(n))))*2 - 1)
			}
			os.Exit(0)
		}
	}
	fmt.Println(n - 1)
}

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

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

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

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

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

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

func (io *Io) Int64() int64 {
	i, err := strconv.ParseInt(io.Next(), 10, 64)
	if err != nil {
		panic(err)
	}
	return i
}

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

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

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

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

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

func Log(name string, value interface{}) {
	fmt.Fprintf(os.Stderr, "%s=%+v\n", name, value)
}

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

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

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

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

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

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

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

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

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

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

func BisectLeft(nums []int, left, right int, target int) int {
	if left == right {
		if nums[left] == target {
			return left
		} else if nums[left] < target {
			return left + 1
		} else {
			return left
		}
	}

	mid := (left + right) / 2
	if nums[mid] == target {
		return mid
	}

	if nums[mid] > target {
		return BisectLeft(nums, left, mid, target)
	} else if nums[mid] < target {
		return BisectLeft(nums, mid+1, right, target)
	}
	return 0
}

func Permutations(nums []int) [][]int {
	n := len(nums)
	if n == 0 {
		return [][]int{}
	}
	ans := [][]int{}

	for _, n := range nums {
		rest := remove(nums, n)
		lists := Permutations(rest)
		if len(lists) == 0 {
			lists = [][]int{nil}
		}

		for i := 0; i < len(lists); i++ {
			lists[i] = append(lists[i], n)
			ans = append(ans, lists[i])
		}
	}
	return ans
}

func remove(nums []int, target int) []int {
	result := []int{}
	for i := 0; i < len(nums); i++ {
		if nums[i] != target {
			result = append(result, nums[i])
		}
	}
	return result
}

func PowerSet(nums []int) [][]int {
	size := Pow(2, len(nums))
	result := make([][]int, size)

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

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

	return result
}

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

func Combination(nums []int, k int) [][]int {
	size := len(nums)
	result := make([][]int, CombinationCount(len(nums), k))
	bi := (1 << uint(k)) - 1
	max := 1 << uint(size)
	idx := 0

	for bi < max {
		flags := bi
		s := []int{}
		for _, n := range nums {
			if flags%2 != 0 {
				s = append(s, n)
			}
			flags /= 2
		}
		result[idx] = s
		idx++
		bi = Combination2NextIndex(bi)
	}
	return result
}

func Combination2NextIndex(n int) int {
	smallest := n & -n
	ripple := n + smallest
	newSmallest := ripple & -ripple
	ones := ((newSmallest / smallest) >> 1) - 1
	return ripple | ones
}

func CombinationCount(n, m int) int {
	return Fact(n) / (Fact(n-m) * Fact(m))
}

func Fact(n int) int {
	if n == 0 {
		return 1
	} else {
		return n * Fact(n-1)
	}
}

func Divisors(n int) []int {
	divisors := map[int]bool{}
	for i := 1; i < int(math.Sqrt(float64(n)))+1; i++ {
		if n%i == 0 {
			divisors[i] = true
			//divisors = append(divisors, i)
			if i != n {
				divisors[n/i] = true
				//divisors = append(divisors, n/i)
			}
		}

	}
	ans := []int{}
	for k := range divisors {
		ans = append(ans, k)
	}
	return ans
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

func main() {
	s := strings.Split(nextLine(), " ")
	a, _ := strconv.ParseFloat(s[0], 64)
	b, _ := strconv.ParseFloat(s[1], 64)
	x, _ := strconv.ParseFloat(s[2], 64)
	var result float64

	if hulf := a * a * b / 2; x < hulf {
		result = math.Atan(a*b*b/2/x) * 180 / math.Pi
	} else if x == hulf {
		result = 45
	} else {
		result = math.Atan((a*a*b-x)*2/a/a/a) * 180 / math.Pi
	}

	fmt.Println(result)
}

Score : 400 points

Problem Statement

Takahashi has a water bottle with the shape of a rectangular prism whose base is a square of side a~\mathrm{cm} and whose height is b~\mathrm{cm}. (The thickness of the bottle can be ignored.)

We will pour x~\mathrm{cm}^3 of water into the bottle, and gradually tilt the bottle around one of the sides of the base.

When will the water be spilled? More formally, find the maximum angle in which we can tilt the bottle without spilling any water.

Constraints

All values in input are integers.

1 \leq a \leq 100

1 \leq b \leq 100

1 \leq x \leq a^2b

Input

Input is given from Standard Input in the following format:

a b x

Output

Print the maximum angle in which we can tilt the bottle without spilling any water, in degrees.
Your output will be judged as correct when the absolute or relative error from the judge's output is at most 10^{-6}.

Sample Input 1

2 2 4

Sample Output 1

45.0000000000

This bottle has a cubic shape, and it is half-full. The water gets spilled when we tilt the bottle more than 45 degrees.

Sample Input 2

12 21 10

Sample Output 2

89.7834636934

This bottle is almost empty. When the water gets spilled, the bottle is nearly horizontal.

Sample Input 3

3 1 8

Sample Output 3

4.2363947991

This bottle is almost full. When the water gets spilled, the bottle is still nearly vertical.


package main

import (
	"fmt"
)

func main() {
	var a, b int
	fmt.Scanf("%d %d", &a, &b)
	fmt.Print(getUnhiddenLength(a, b))
}

func getUnhiddenLength(a, b int) int {
	unhiddenLength := a - b*2
	if unhiddenLength <= 0 {
		return 0
	}
	return unhiddenLength
}

Score : 100 points

Problem Statement

The window of Takahashi's room has a width of A. There are two curtains hung over the window, each of which has a horizontal length of B. (Vertically, the curtains are long enough to cover the whole window.)

We will close the window so as to minimize the total horizontal length of the uncovered part of the window.
Find the total horizontal length of the uncovered parts of the window then.

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

A and B are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the total horizontal length of the uncovered parts of the window.

Sample Input 1

12 4

Sample Output 1

4

We have a window with a horizontal length of 12, and two curtains, each of length 4, that cover both ends of the window, for example. The uncovered part has a horizontal length of 4.

Sample Input 2

20 15

Sample Output 2

0

If the window is completely covered, print 0.

Sample Input 3

20 30

Sample Output 3

0

Each curtain may be longer than the window.


package main

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

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

	// N
	scanner.Scan()
	N, err := strconv.Atoi(scanner.Text())
	if err != nil {
		log.Fatal(err)
	}

	// d
	d := make([]int, N)
	for i := 0; i < N; i++ {
		scanner.Scan()
		target, err := strconv.Atoi(scanner.Text())
		if err != nil {
			log.Fatal(err)
		}
		d[i] = target
	}

	all := 0
	for x := 0; x < N; x++ {
		for y := 0; y < N; y++ {
			all += d[x] * d[y]
		}
		all -= d[x] * d[x]
	}

	fmt.Println(all / 2)

}

Score : 200 points

Problem Statement

It's now the season of TAKOYAKI FESTIVAL!

This year, N takoyaki (a ball-shaped food with a piece of octopus inside) will be served. The deliciousness of the i-th takoyaki is d_i.

As is commonly known, when you eat two takoyaki of deliciousness x and y together, you restore x \times y health points.

There are \frac{N \times (N - 1)}{2} ways to choose two from the N takoyaki served in the festival. For each of these choices, find the health points restored from eating the two takoyaki, then compute the sum of these \frac{N \times (N - 1)}{2} values.

Constraints

All values in input are integers.

2 \leq N \leq 50

0 \leq d_i \leq 100

Input

Input is given from Standard Input in the following format:

N
d_1 d_2 ... d_N

Output

Print the sum of the health points restored from eating two takoyaki over all possible choices of two takoyaki from the N takoyaki served.

Sample Input 1

3
3 1 2

Sample Output 1

11

There are three possible choices:

Eat the first and second takoyaki. You will restore 3 health points.

Eat the second and third takoyaki. You will restore 2 health points.

Eat the first and third takoyaki. You will restore 6 health points.

The sum of these values is 11.

Sample Input 2

7
5 0 7 8 3 3 2

Sample Output 2

312


package main

import "fmt"

func main() {
 n := 0
 hp := 0
 //たこ焼きの個数を受け取る
 fmt.Scanf("%d",n)

 //たこ焼きのおいしさを配列に格納
 num := make([]int,n)
 for i:=0; i < n; i++ {
 	fmt.Scanf("%d",num[i])
 }

 for i:=0; i < n-1; i++ {
   for j:=i+1; j<n; j++ {
     hp += num[i] * num[j]
   }
 }
 fmt.Printf("%d",hp)
}


package main

import "fmt"

func main() {
	var N int
	var S string
	fmt.Scan(&N)
	fmt.Scan(&S)
	ans := 1
	for n := 0; n < N-1; n++ {
		if S[n] != S[n+1] {
			ans++
		}
	}
	fmt.Println(ans)
}

Score : 300 points

Problem Statement

There are N slimes lining up from left to right. The colors of these slimes will be given as a string S of length N consisting of lowercase English letters. The i-th slime from the left has the color that corresponds to the i-th character of S.

Adjacent slimes with the same color will fuse into one larger slime without changing the color. If there were a slime adjacent to this group of slimes before fusion, that slime is now adjacent to the new larger slime.

Ultimately, how many slimes will be there?

Constraints

1 \leq N \leq 10^5

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the final number of slimes.

Sample Input 1

10
aabbbbaaca

Sample Output 1

5

Ultimately, these slimes will fuse into abaca.

Sample Input 2

5
aaaaa

Sample Output 2

1

All the slimes will fuse into one.

Sample Input 3

20
xxzaffeeeeddfkkkkllq

Sample Output 3

10


package main
import(
  "fmt"
)
func main(){
  var n, i int
  var s string
  fmt.Scan(&n, &s)
  temp:=0
  for i=1;i<len(s);i++{
    if s[i-1]!=s[i]{
      temp++
    }
  }
  fmt.Println(temp+1)
}


package main

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

func main() {
	log.SetFlags(log.Lshortfile)
	var n int
	fmt.Scan(&n)
	l := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&l[i])
	}
	var cnt int
	sort.Ints(l)
	for i := 0; i < n-2; i++ {
		for j := i + 1; j < n-1; j++ {
			a := l[i]
			b := l[j]
			k := lower_bound(l, a+b)
			cnt += k - j - 1
		}
	}
	fmt.Println(cnt)
}

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

var dy = []int{0, 1, 0, -1}
var dx = []int{1, 0, -1, 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
}

Score : 400 points

Problem Statement

Takahashi has N sticks that are distinguishable from each other. The length of the i-th stick is L_i.

He is going to form a triangle using three of these sticks. Let a, b, and c be the lengths of the three sticks used. Here, all of the following conditions must be satisfied:

a < b + c

b < c + a

c < a + b

How many different triangles can be formed? Two triangles are considered different when there is a stick used in only one of them.

Constraints

All values in input are integers.

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

1 \leq L_i \leq 10^3

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 ... L_N

Constraints

Print the number of different triangles that can be formed.

Sample Input 1

4
3 4 2 1

Sample Output 1

1

Only one triangle can be formed: the triangle formed by the first, second, and third sticks.

Sample Input 2

3
1 1000 1

Sample Output 2

0

No triangles can be formed.

Sample Input 3

7
218 786 704 233 645 728 389

Sample Output 3

23


package main

import (
	"fmt"
	"sort"
)

func main() {
	var n, r int
	fmt.Scan(&n)
	l := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&l[i])
	}
	sort.Sort(sort.IntSlice(l))
	for i := 0; i < n-2; i++ {
		for j := i + 1; j < n-1; j++ {
			t := l[j+1:]
			sum := l[i] + l[j]
			w := sort.Search(len(t), func(i int) bool { return t[i] > sum })
			for k := 0; k < w; k++ {
				if l[i] < l[j]+t[k] && l[j] < t[k]+l[i] && t[k] < l[i]+l[j] {
					r++
				}
			}
		}
	}
	fmt.Println(r)
}


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

// var f, _ = os.Open("input.txt")
// var rdr = bufio.NewReaderSize(f, 1000000)
var rdr = bufio.NewReaderSize(os.Stdin, 1000000)

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

func upper(Ls [] int, val int) int {
    var low int = 0
    var high int = len(Ls)
    mid := (high + low) / 2
    for high - low > 1 {
        if Ls[mid] > val {
            high = mid
        } else {
            low = mid
        }
        mid = (high + low) / 2
    }

    if Ls[low] > val {
        return low
    }
    return high
}

func upper_equal(Ls [] int, val int) int {
    var low int = 0
    var high int = len(Ls)
    mid := (high + low) / 2
    for high - low > 1 {
        if Ls[mid] >= val {
            high = mid
        } else {
            low = mid
        }
        mid = (high + low) / 2
    }

    if Ls[low] >= val {
        return low
    }
    return high
}

func main() {
    // as := make([] int, 5)
    // for i, word := range strings.Split(read_line(), " ") {
    //     as[i], _ = strconv.Atoi(word)
    // }

    N, _ := strconv.Atoi(read_line())
    Ls := make([] int, N)
    for i, L := range strings.Split(read_line(), " ") {
        Ls[i], _ = strconv.Atoi(L)
    }

    sort.Ints(Ls)

    var res int = 0
    for i := 0; i < N; i++ {
        for j := i + 1; j < N; j++ {
            max_index := upper_equal(Ls, Ls[j] + Ls[i])
            min_index := upper(Ls, Ls[j] - Ls[i])
            res += max_index - min_index
            if min_index <= i && i < max_index {
                res--
            }
            if min_index <= j && j < max_index {
                res--
            }
        }
    }

    fmt.Println(res / 3)
}


package main

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

func main() {
	scanner := makeWordScanner()
	n := eGetInt(scanner)
	ls := make([]int, n)
	for i := 0; i < n; i++ {
		ls[i] = eGetInt(scanner)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(ls)))
	count := 0
	for i := 0; i < n-2; i++ {
		a := ls[i]
		for j := i + 1; j < n-1; j++ {
			b := ls[j]
			left := j + 1
			right := n
			mid := (left + right) / 2
			for right-left >= 1 {
				if a < b+ls[mid] {
					left = mid + 1
				} else {
					right = mid
				}
				mid = (left + right) / 2
			}
			count += left - (j + 1)
			// for k := j + 1; k < n; k++ {
			// 	c := ls[k]
			// 	ここを二分探索で検索可能
			//
			// 	if b+c > a {
			// 		count++
			// 	} else {
			// 		break
			// 	}
			// }
		}
	}
	fmt.Println(count)
}

////////////////////////////////////////////////////////////////////////////////
// ライブラリ
////////////////////////////////////////////////////////////////////////////////
func makeScanner(maxByte int) *bufio.Scanner {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Buffer(make([]uint8, 0, 8192), maxByte)
	return scanner
}
func makeCharScanner() *bufio.Scanner {
	scanner := makeScanner(8192)
	scanner.Split(bufio.ScanRunes)
	return scanner
}
func makeWordScanner() *bufio.Scanner {
	scanner := makeScanner(8192)
	scanner.Split(bufio.ScanWords)
	return scanner
}
func eGetLine(r *bufio.Scanner) string {
	if r.Scan() {
		return r.Text()
	}
	err := r.Err()
	if err != nil {
		log.Fatal(err)
	}
	// EOF
	return ""
}
func eGetInt(r *bufio.Scanner) int {
	line := eGetLine(r)
	return eAtoi(line)
}
func eGetInt64(r *bufio.Scanner) int64 {
	line := eGetLine(r)
	return eAtoInt64(line)
}
func eGetFields(r *bufio.Scanner) []string {
	line := eGetLine(r)
	return strings.Fields(line)
}
func eGetInts(r *bufio.Scanner) []int {
	fields := eGetFields(r)
	ints := make([]int, len(fields))
	for i := 0; i < len(ints); i++ {
		ints[i] = eAtoi(fields[i])
	}
	return ints
}
func eGetInt64s(r *bufio.Scanner) []int64 {
	fields := eGetFields(r)
	ints := make([]int64, len(fields))
	for i := 0; i < len(ints); i++ {
		ints[i] = eAtoInt64(fields[i])
	}
	return ints
}
func eGetChars(r *bufio.Scanner) []string {
	line := eGetLine(r)
	return strings.Split(line, "")
}
func eAtoi(s string) int {
	n, err := strconv.Atoi(s)
	if err != nil {
		log.Fatal(err)
	}
	return n
}
func eAtoInt64(s string) int64 {
	n, err := strconv.ParseInt(s, 10, 64)
	if err != nil {
		log.Fatal(err)
	}
	return n
}


package main

import (
	"fmt"
	"sort"
)

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

	inputs := scanNums(N)
	sort.Sort(sort.Reverse(sort.IntSlice(inputs)))
	res := 0
	for i := 0; i < N; i++ {
		for j := i + 1; j < N; j++ {
			if inputs[i] >= 2*inputs[j] {
				break
			}
			if inputs[i] == inputs[j] {
				continue
			}
			for k := j + 1; k < N; k++ {

				a := inputs[i]
				b := inputs[j]
				c := inputs[k]
				if a >= b+c {
					break
				}
				// if a >= b+c {
				// 	continue
				// }
				// if b >= a+c {
				// 	continue
				// }
				// if c >= a+b {
				// 	continue
				// }
				res++
			}
		}
	}

	fmt.Println(res)

}

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"
	"strconv"
	"strings"
    "os"
)

func main() {
	var N int

	var ln []int

	fmt.Scanf("%d", &N)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	dn := scanner.Text()
	dn = strings.TrimSpace(dn)

	dnn := strings.Fields(dn)

	for j := range dnn {
		var iparam int
		iparam, _ = strconv.Atoi(dnn[j])
		ln = append(ln, iparam)
	}

	sum := 0

	for i:=0; i<(N-2); i++ {
		for j:=i+1; j<(N-1); j++ {
			for k:=j+1; k<N; k++ {
				if( ln[i] < ln[j] + ln[k] &&
					ln[j] < ln[i] + ln[k] &&
					ln[k] < ln[i] + ln[j]) {
						sum++
				}
			}
		}
	}
	fmt.Printf("%d\n", sum)
}


package main
import (
  "fmt"
  "sort"
)
func main() {
  var n,x int
  fmt.Scan(&n)
  a := make([]int,n)
  s := make([]int,n+1)
  for i:=0;i<n;i++ {
    fmt.Scan(&x)
    a[x-1]++
  }
  sort.Ints(a)
  for i:=0;i<n;i++ { s[i+1] = s[i]+a[i] }
  ans := n
  i := n
  for k:=1;k<=n;k++ {
    for {
      for i > 0 && a[i-1] >= ans { i-- }
      if ans*(n-i)+s[i] >= ans*k { break }
      ans--
    }
    fmt.Println(ans)
  }
}

Score : 600 points

Problem Statement

Takahashi has N cards. The i-th of these cards has an integer A_i written on it.

Takahashi will choose an integer K, and then repeat the following operation some number of times:

Choose exactly K cards such that the integers written on them are all different, and eat those cards. (The eaten cards disappear.)

For each K = 1,2, \ldots, N, find the maximum number of times Takahashi can do the operation.

Constraints

1 \le N \le 3 \times 10^5

1 \le A_i \le N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_N

Output

Print N integers.
The t-th (1 \le t \le N) of them should be the answer for the case K=t.

Sample Input 1

3
2 1 2

Sample Output 1

3
1
0

For K = 1, we can do the operation as follows:

Choose the first card to eat.

Choose the second card to eat.

Choose the third card to eat.

For K = 2, we can do the operation as follows:

Choose the first and second cards to eat.

For K = 3, we cannot do the operation at all. Note that we cannot choose the first and third cards at the same time.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

5
2
1
1
1

Sample Input 3

4
1 3 3 3

Sample Output 3

4
1
0
0


package main

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

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

	scanner.Scan()

	N, err := strconv.Atoi(scanner.Text())
	if err != nil {
		log.Fatal(err)
	}

	if N%2 == 0 {
		fmt.Println(float32((N / 2)) / float32(N))
	} else {
		fmt.Println(float32(((N - 1) / 2)) / float32(N))
	}
}

Score : 100 points

Problem Statement

Given is an integer N.

Takahashi chooses an integer a from the positive integers not greater than N with equal probability.

Find the probability that a is odd.

Constraints

1 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the probability that a is odd.
Your output will be considered correct when its absolute or relative error from the judge's output is at most 10^{-6}.

Sample Input 1

4

Sample Output 1

0.5000000000

There are four positive integers not greater than 4: 1, 2, 3, and 4. Among them, we have two odd numbers: 1 and 3. Thus, the answer is \frac{2}{4} = 0.5.

Sample Input 2

5

Sample Output 2

0.6000000000

Sample Input 3

1

Sample Output 3

1.0000000000


package main

import (
 "fmt"
)

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

    half := n / 2
    ans := float64(n - half) / float64(n)
    fmt.Println(ans)
}


package main

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

func main() {
	N, K := ReadInt(), ReadInt()
	hs := ReadInts(N)

	ans := 0
	for i := 0; i < N; i++ {
		if hs[i] >= K {
			ans++
		}
	}

	fmt.Println(ans)
}

var reader = bufio.NewReader(os.Stdin)

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

func ReadInts(n int) []int {
	v := make([]int, n)
	for i := 0; i < n; i++ {
		Scan(&v[i])
	}
	return v
}

Score : 200 points

Problem Statement

N friends of Takahashi has come to a theme park.

To ride the most popular roller coaster in the park, you must be at least K centimeters tall.

The i-th friend is h_i centimeters tall.

How many of the Takahashi's friends can ride the roller coaster?

Constraints

1 \le N \le 10^5

1 \le K \le 500

1 \le h_i \le 500

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
h_1 h_2 \ldots h_N

Output

Print the number of people among the Takahashi's friends who can ride the roller coaster.

Sample Input 1

4 150
150 140 100 200

Sample Output 1

2

Two of them can ride the roller coaster: the first and fourth friends.

Sample Input 2

1 500
499

Sample Output 2

0

Sample Input 3

5 1
100 200 300 400 500

Sample Output 3

5


package main

import "fmt"

func main() {
	var N, K, w, cnt int
	fmt.Scan(&N, &K)
	for i := 0; i < N; i++ {
		fmt.Scan(&w)
		if w >= K {
			cnt++
		}
	}
	fmt.Println(cnt)
}


package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	nums := make([]int, n)
	ans := make([]int, n)
	for i, _ := range nums{
		fmt.Scan(&nums[i])
	}

	for i:=1; i<=n; i++{
		for j:=0; j<n; j++{
			if i == nums[j]{
				ans[i-1] = j+1
				break
			}
		}
	}

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

Score : 300 points

Problem Statement

Takahashi is a teacher responsible for a class of N students.

The students are given distinct student numbers from 1 to N.

Today, all the students entered the classroom at different times.

According to Takahashi's record, there were A_i students in the classroom when student number i entered the classroom (including student number i).

From these records, reconstruct the order in which the students entered the classroom.

Constraints

1 \le N \le 10^5

1 \le A_i \le N

A_i \neq A_j (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_N

Output

Print the student numbers of the students in the order the students entered the classroom.

Sample Input 1

3
2 3 1

Sample Output 1

3 1 2

First, student number 3 entered the classroom.

Then, student number 1 entered the classroom.

Finally, student number 2 entered the classroom.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

1 2 3 4 5

Sample Input 3

8
8 2 7 3 4 5 6 1

Sample Output 3

8 2 4 5 6 7 3 1


package main

import (
	"fmt"
)

func main() {

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

	A := make([]int, N)
	for i := 0; i < N; i++ {
		fmt.Scanf("%d", &A[i])

	}

	flag := make(map[int]int, N)
	for i, j := range A {
		flag[j] = i + 1
	}

	for i := 1; i <= N; i++ {
		fmt.Printf("%d ", flag[i])
	}
	fmt.Printf("\n")
}


package main

import (
	"fmt"
	"strconv"
)

func main() {
	var n int
	fmt.Scan(&n)
	a := map[string]int{}
	for i := 1; i <= n; i++ {
		var tmp int
		fmt.Scan(&tmp)
		a[strconv.Itoa(tmp)] = i
	}

	for i := 1; i <= n; i++ {
		fmt.Print(a[strconv.Itoa(i)])
		fmt.Print(" ")
	}
	fmt.Println()
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

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

type sortable [][]int

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

func (s sortable) Less(i, j int) bool {
	return s[i][0] < s[j][0]
}

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

func main() {
	sc.Split(bufio.ScanWords)
	n := inputInt()
	as := splitInt(n)
	ords := make(sortable, n)
	for i := 0; i < n; i++ {
		ords[i] = []int{as[i], i + 1}
	}
	sort.Sort(ords)
	result := make([]int, n)
	for i, x := range ords {
		result[i] = x[1]
	}
	fmt.Print(result)
}


package main

import (
  "fmt"
)

//2つの入力値の最大公約数を返す
func max_div(num1 int, num2 int) int {

  if num1 < num2 {
    temp := num1
    num1 = num2
    num2 = temp
  }
  //ユークリッド互除法
  var rem int
  for {
    rem = num1 % num2
    if rem == 0 {
      break
    }
    num1 = num2
    num2 = rem
  }
    return num2
}

func main() {

  var a,b int
  fmt.Scan(&a,&b)
  m := max_div(a,b)

  //A,Bの最大公約数の約数を求める
  var div []int
  count := 0

  //約数を保持
  for i := 1; i <= m; i++ {
    if m % i == 0 {
        div = append(div,i)
        count++
    }
  }

  ans := 1 //答えは必ず1以上
  var p bool
  p = true //素数

  //保持した約数と、その約数以下の値との最大公約数を計算
  for i := count-1; i > 0; i-- {
    for j := 2; j < i; j++ {
      //最大公約数が1以外ならその約数は素数ではない⇒探索終了
      if max_div(div[i],j) != 1 {
        p = !p
        break
      }
    }
    //最後までtrueなら素数
    if p {
      ans++
    }
    p = true
  }
  fmt.Println(ans)
}

Score : 400 points

Problem Statement

Given are positive integers A and B.

Let us choose some number of positive common divisors of A and B.

Here, any two of the chosen divisors must be coprime.

At most, how many divisors can we choose?

Definition of common divisor

An integer d is said to be a common divisor of integers x and y when d divides both x and y.

Definition of being coprime

Integers x and y are said to be coprime when x and y have no positive common divisors other than 1.

Definition of dividing

An integer x is said to divide another integer y when there exists an integer \alpha such that y = \alpha x.

Constraints

All values in input are integers.

1 \leq A, B \leq 10^{12}

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of divisors that can be chosen to satisfy the condition.

Sample Input 1

12 18

Sample Output 1

3

12 and 18 have the following positive common divisors: 1, 2, 3, and 6.

1 and 2 are coprime, 2 and 3 are coprime, and 3 and 1 are coprime, so we can choose 1, 2, and 3, which achieve the maximum result.

Sample Input 2

420 660

Sample Output 2

4

Sample Input 3

1 2019

Sample Output 3

1

1 and 2019 have no positive common divisors other than 1.


package main

import (
	"fmt"
	"sort"
)

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

	// 最大公約数を求める
	r := a % b
	for r != 0 {
		a = b
		b = r
		r = a % b
	}

	if b == 1 {
		fmt.Println(1)
		return
	}
	// 約数を求める
	// 約数を求める際の右の列の最小の数
	minRight := b
	var divisors []int
	for i := 1; i < minRight; i++ {
		if b%i == 0 {
			divisors = append(divisors, i)
			divisors = append(divisors, b/i)
			minRight = b / i
		}
	}

	// 互いに素な整数の配列を返す
	sort.Ints(divisors[:])
	result := 0
	tmp := b
	for _, num := range divisors {
		if num == 1 {
			result++
			continue
		}
		if tmp == 1 {
			break
		}
		for tmp%num == 0 {
			tmp = tmp / num
		}
		result++
	}
	fmt.Println(result)
}


package main

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

var (
	sc = bufio.NewScanner(os.Stdin)
	mod int = 1e9 + 7
)

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

func main() {
	A := uint64(getInt())
	B := uint64(getInt())

	gcm := gcd(A, B)
	primes := primes(int(gcm))

	fmt.Println(len(primes) + 1)
}

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

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

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

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

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

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

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

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

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

func gcd(m, n uint64) uint64 {
	x := new(big.Int)
	y := new(big.Int)
	z := new(big.Int)
	a := new(big.Int).SetUint64(m)
	b := new(big.Int).SetUint64(n)
	return z.GCD(x, y, a, b).Uint64()
}

func primes(n int) []int {
	var results []int
	for i := 1; i <= n; i++ {
		if n % i == 0 && big.NewInt(int64(i)).ProbablyPrime(1) {
			results = append(results, i)
		}
	}
	return results
}


// https://atcoder.jp/contests/abc142/tasks/abc142_d

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
	"reflect"
	"runtime"
	"sort"
	"strconv"
	"strings"
)

// d: debug IO. it can print debug in test.
func solve(io *Io, d *Io) {
	A := io.NextInt()
	B := io.NextInt()

	// 公約数のペアに含まれる素数と 1

	max := Max(A, B)
	nums := []int{}

	tried := 0

	for num := 2; num*num <= max; num++ {
		tried = num * num
		if A%num == 0 && B%num == 0 {
			nums = append(nums, num)
		}
	}

	if A%B == 0 && B > tried && B != 1 {
		nums = append(nums, B)
	} else if B%A == 0 && A > tried && A != 1 {
		nums = append(nums, A)
	}

	res := 1

	for i, num := range nums {
		prime := true

		for j := 0; j < i; j++ {
			other := nums[j]

			if num%other == 0 {
				prime = false
				break
			}
		}

		if prime {
			res++
		}
	}

	io.Println(res)
}

func main() {
	io := NewIo()
	defer io.Flush()
	solve(io, nil)
}

/* IO Helpers */

// Io combines reader, writer, & tokens as the state when processing the input
type Io struct {
	reader    *bufio.Reader
	writer    *bufio.Writer
	tokens    []string
	nextToken int
}

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

// Flush calls the writer's Flush
func (io *Io) Flush() {
	io.writer.Flush()
}

// NextLine returns the string from reader.ReadLine()
func (io *Io) NextLine() string {
	if io.nextToken < len(io.tokens) {
		panic("io.nextToken < len(io.tokens)")
	}

	var buffer bytes.Buffer

	for {
		line, isPrefix, err := io.reader.ReadLine()
		if err != nil {
			panic(err)
		}
		buffer.Write(line)
		if !isPrefix {
			break
		}
	}

	return buffer.String()
}

// NextLines returns []string from next n lines
func (io *Io) NextLines(n int) []string {
	res := make([]string, n)
	for i := 0; i < n; i++ {
		res[i] = io.NextLine()
	}
	return res
}

// Next returns the string token (partial string of the line divided by spaces)
func (io *Io) Next() string {
	if io.nextToken >= len(io.tokens) {
		line := io.NextLine()
		io.tokens = strings.Fields(line)
		io.nextToken = 0
	}

	res := io.tokens[io.nextToken]
	io.nextToken++
	return res
}

// NextStrings returns the []string from the next n tokens
func (io *Io) NextStrings(n int) []string {
	res := make([]string, n)
	for i := 0; i < n; i++ {
		res[i] = io.Next()
	}
	return res
}

// NextRunes returns next string as []rune
func (io *Io) NextRunes() []rune {
	return []rune(io.Next())
}

// NextInt returns the int from the next token
func (io *Io) NextInt() int {
	res, err := strconv.Atoi(io.Next())
	if err != nil {
		panic(err)
	}
	return res
}

// NextInts returns the []int from the next n tokens
func (io *Io) NextInts(n int) []int {
	res := make([]int, n)
	for i := 0; i < n; i++ {
		res[i] = io.NextInt()
	}
	return res
}

// NextFloat returns the float64 from the next token
func (io *Io) NextFloat() float64 {
	res, err := strconv.ParseFloat(io.Next(), 64)
	if err != nil {
		panic(err)
	}
	return res
}

// NextFloats returns the []float64 from the next n tokens
func (io *Io) NextFloats(n int) []float64 {
	res := make([]float64, n)
	for i := 0; i < n; i++ {
		res[i] = io.NextFloat()
	}
	return res
}

// Println prints the input to the writer in an easy-to-see form
func (io *Io) Println(a ...interface{}) {
	var values []string
	for i := 0; i < len(a); i++ {
		values = append(values, "%v")
	}
	io.Printfln(strings.Join(values, " "), a...)
}

// Print calls Fprint to the writer
func (io *Io) Print(a interface{}) {
	fmt.Fprint(io.writer, a)
}

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

// Printfln calls Fprint to the writer
func (io *Io) Printfln(format string, a ...interface{}) {
	fmt.Fprintf(io.writer, format+"\n", a...)
}

// PrintInts prints ints with space and new line at the end
func (io *Io) PrintInts(ints []int) {
	for i, e := range ints {
		io.Print(e)

		if i == len(ints)-1 {
			io.Println()
		} else {
			io.Print(" ")
		}
	}
}

// Debug calls Println and Flush immediately
func (io *Io) Debug(a ...interface{}) {
	if io == nil {
		return
	}

	io.Println(a...)
	io.Flush()
}

// Assert checks the value equality for debug
func (io *Io) Assert(a, b interface{}) {
	if io == nil {
		return
	}

	if !reflect.DeepEqual(a, b) {
		_, _, line, _ := runtime.Caller(1)
		io.Debug("Diff:", line, "\na:", a, "\nb:", b)
	}
}

/* Math Helpers */

// MOD is 10^9 + 7
const MOD = 1000000007

// Max of the ints
func Max(numbers ...int) int {
	max := numbers[0]
	for i, number := range numbers {
		if i == 0 {
			continue
		}
		if number > max {
			max = number
		}
	}
	return max
}

// Min of the ints
func Min(numbers ...int) int {
	min := numbers[0]
	for i, number := range numbers {
		if i == 0 {
			continue
		}
		if min > number {
			min = number
		}
	}
	return min
}

// Sum of the ints
func Sum(numbers ...int) int {
	sum := 0

	for _, number := range numbers {
		sum += number
	}

	return sum
}

// Pow calculates the pow for int with O(log e)
func Pow(a, e int) int {
	if a < 0 || e < 0 {
		panic(fmt.Sprintf("Pow was called for a < 0 or e < 0, a: %d, e: %d", a, e))
	}

	if e == 0 {
		return 1
	}

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

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

// Abs returns the absolute value of the input
func Abs(a int) int {
	if a < 0 {
		return -a
	}

	return a
}

/* Structure Helpers */

// Set is orderless List
type Set map[interface{}]struct{}

// NewSet returns empty Set
func NewSet() *Set {
	return &Set{}
}

// Add the value to the set
func (set *Set) Add(value interface{}) {
	(*set)[value] = struct{}{}
}

// Includes check the set has the value
func (set *Set) Includes(value interface{}) bool {
	_, included := (*set)[value]
	return included
}

// Remove deletes the value from the set if exists
func (set *Set) Remove(value interface{}) {
	if !set.Includes(value) {
		return
	}

	delete(*set, value)
}

// ImmutableSort returns sorted slice without mutating original one
func ImmutableSort(slice []int) []int {
	res := make([]int, len(slice))
	copy(res, slice)
	sort.Ints(res)
	return res
}

/* Util helpers */

// Ternary is like `cond ? a : b`. should assert the returned value like `Ternary(cond, a, b).(int)`
func Ternary(cond bool, a, b interface{}) interface{} {
	if cond {
		return a
	}

	return b
}

// TernaryInt uses Ternary and assert the value as int
func TernaryInt(cond bool, a, b int) int {
	return Ternary(cond, a, b).(int)
}

// TernaryString uses Ternary and assert the value as string
func TernaryString(cond bool, a, b string) string {
	return Ternary(cond, a, b).(string)
}


package main

import "fmt"

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

func divisors(n int) (r map[int]int) {
	r = make(map[int]int, 0)
	for i := 2; i*i <= n; i++ {
		for n%i == 0 {
			n /= i
			r[i]++
		}
	}
	if n > 1 {
		r[n]++
	}
	return r
}

func main() {
	var A, B int
	fmt.Scan(&A, &B)
	// fmt.Println("A", A, "B", B, "GCD", gcd(A, B), "divs(GCD)", divisors(gcd(A, B)))
	fmt.Println(len(divisors(gcd(A, B))) + 1)
}


package main

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

func main() {
	var h, w, a, b int
	fmt.Scanf("%d %d %d %d", &h, &w, &a, &b)
	//h, w, a, b = 3, 3, 1, 1

	// fmt.Println(gen(h, w, 2), a, b)
	max, _ := strconv.ParseInt(strings.Repeat("1", h*w), 2, 64)

	// fmt.Println(max)
	for i := 0; int64(i) <= max; i++ {
		if check2(i, h, w, a, b) {
			print(gen(h, w, i))
			return
		}
		// g := gen(h, w, i)
		// if check(g, h, w, a, b) {
		// 	print(g)
		// 	return
		// }

	}
	fmt.Print("No")

}

func check2(v, h, w, a, b int) bool {
	val := strconv.FormatInt(int64(v), 2)
	for i := 0; i < h; i++ {
		rowCount := 0
		for j := 0; j < w; j++ {
			num := "0"[0]
			if len(val) > i*w+j {
				num = val[i*w+j]
				if num == '1' {
					rowCount++
				}
			}
		}
		if rowCount == a || rowCount == w-a {
			continue
		}
		return false
	}
	for i := 0; i < w; i++ {
		wCount := 0
		for j := 0; j < h; j++ {
			num := "0"[0]
			if len(val) > j*w+i {
				num = val[j*w+i]
				if num == '1' {
					wCount++
				}
			}
		}
		if wCount == b || wCount == h-b {
			continue
		}
		return false
	}
	return true
}

func check(g [][]int, h, w, a, b int) bool {
	for i := 0; i < h; i++ {
		rowCount := 0
		for j := 0; j < w; j++ {
			if g[i][j] == 1 {
				rowCount++
			}
		}
		if rowCount == a || rowCount == w-a {
			continue
		}
		return false
	}
	for i := 0; i < w; i++ {
		wCount := 0
		for j := 0; j < h; j++ {
			if g[j][i] == 1 {
				wCount++
			}
		}
		if wCount == b || wCount == h-b {
			continue
		}
		return false
	}
	return true

}

func gen(h, w, v int) [][]int {
	rows := make([][]int, h)
	val := strconv.FormatInt(int64(v), 2)
	for i := 0; i < h; i++ {
		row := make([]int, w)
		for j := 0; j < w; j++ {
			num := "0"[0]
			if len(val) > i*w+j {
				num = val[i*w+j]
			}
			if num == '1' {
				row[j] = 1
			}
		}
		rows[i] = row
	}
	return rows
}

func print(g [][]int) {
	for _, row := range g {
		for _, cell := range row {
			fmt.Print(cell)
		}
		fmt.Print("\n")
	}
}

Score : 300 points

Problem Statement

We have a square grid with H rows and W columns.
Snuke wants to write 0 or 1 in each of the squares.
Here, all of the following conditions have to be satisfied:

For every row, the smaller of the following is A: the number of 0s contained in the row, and the number of 1s contained in the row. (If these two numbers are equal, “the smaller” should be read as “either”.)

For every column, the smaller of the following is B: the number of 0s contained in the column, and the number of 1s contained in the column.

Determine if these conditions can be satisfied by writing 0 or 1 in each of the squares. If the answer is yes, show one way to fill the squares so that the conditions are satisfied.

Constraints

1 \leq H,W \leq 1000

0 \leq A

2 \times A \leq W

0 \leq B

2 \times B \leq H

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H W A B

Output

If the conditions cannot be satisfied by writing 0 or 1 in each of the squares, print -1.

If the conditions can be satisfied, print one way to fill the squares so that the conditions are satisfied, in the following format:

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

Here s_{ij} is the digit written in the square at the i-th row from the top and the j-th column from the left in the grid.

If multiple solutions exist, printing any of them will be accepted.

Sample Input 1

3 3 1 1

Sample Output 1

100
010
001

Every row contains two 0s and one 1, so the first condition is satisfied.
Also, every column contains two 0s and one 1, so the second condition is satisfied.

Sample Input 2

1 5 2 0

Sample Output 2

01010


package main

import (
	"fmt"
	"strings"
)

func main() {
	var s string
	fmt.Scan(&s)
	dances := strings.Split(s, "")
	easy := true
	for i, dance := range dances {
		if i%2 != 0 {
			if dance == "R" {
				easy = false
				break
			}
		} else {
			if dance == "L" {
				easy = false
				break
			}
		}
	}
	if easy {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
}

Score: 200 points

Problem Statement

Takahashi will do a tap dance. The dance is described by a string S where each character is L, R, U, or D. These characters indicate the positions on which Takahashi should step. He will follow these instructions one by one in order, starting with the first character.

S is said to be easily playable if and only if it satisfies both of the following conditions:

Every character in an odd position (1-st, 3-rd, 5-th, \ldots) is R, U, or D.

Every character in an even position (2-nd, 4-th, 6-th, \ldots) is L, U, or D.

Your task is to print Yes if S is easily playable, and No otherwise.

Constraints

S is a string of length between 1 and 100 (inclusive).

Each character of S is L, R, U, or D.

Input

Input is given from Standard Input in the following format:

S

Output

Print Yes if S is easily playable, and No otherwise.

Sample Input 1

RUDLUDR

Sample Output 1

Yes

Every character in an odd position (1-st, 3-rd, 5-th, 7-th) is R, U, or D.

Every character in an even position (2-nd, 4-th, 6-th) is L, U, or D.

Thus, S is easily playable.

Sample Input 2

DULL

Sample Output 2

No

The 3-rd character is not R, U, nor D, so S is not easily playable.

Sample Input 3

UUUUUUUUUUUUUUU

Sample Output 3

Yes

Sample Input 4

ULURU

Sample Output 4

No

Sample Input 5

RDULULDURURLRDULRLR

Sample Output 5

Yes


package main

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

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

	sc.Scan()
	N, _ := strconv.Atoi(sc.Text())

	sc.Scan()
	K, _ := strconv.Atoi(sc.Text())

	sc.Scan()
	Q, _ := strconv.Atoi(sc.Text())

	A := make([]int, Q)
	for i := 0; i < Q; i++ {
		sc.Scan()
		A[i], _ = strconv.Atoi(sc.Text())
	}

	points := make([]int, N)
	for i := 0; i < N; i++ {
		points[i] = K - Q
	}

	for _, person := range A {
		points[person-1]++
	}

	writer := bufio.NewWriter(os.Stdout)
	for _, point := range points {
		if point > 0 {
			writer.WriteString("Yes\n")
		} else {
			writer.WriteString("No\n")
		}
	}
	writer.Flush()
}

Score: 300 points

Problem Statement

Takahashi has decided to hold fastest-finger-fast quiz games. Kizahashi, who is in charge of making the scoreboard, is struggling to write the program that manages the players' scores in a game, which proceeds as follows.

A game is played by N players, numbered 1 to N. At the beginning of a game, each player has K points.

When a player correctly answers a question, each of the other N-1 players receives minus one (-1) point. There is no other factor that affects the players' scores.

At the end of a game, the players with 0 points or lower are eliminated, and the remaining players survive.

In the last game, the players gave a total of Q correct answers, the i-th of which was given by Player A_i.
For Kizahashi, write a program that determines whether each of the N players survived this game.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq K \leq 10^9

1 \leq Q \leq 10^5

1 \leq A_i \leq N\ (1 \leq i \leq Q)

Input

Input is given from Standard Input in the following format:

N K Q
A_1
A_2
.
.
.
A_Q

Output

Print N lines. The i-th line should contain Yes if Player i survived the game, and No otherwise.

Sample Input 1

6 3 4
3
1
3
2

Sample Output 1

No
No
Yes
No
No
No

In the beginning, the players' scores are (3, 3, 3, 3, 3, 3).

Player 3 correctly answers a question. The players' scores are now (2, 2, 3, 2, 2, 2).

Player 1 correctly answers a question. The players' scores are now (2, 1, 2, 1, 1, 1).

Player 3 correctly answers a question. The players' scores are now (1, 0, 2, 0, 0, 0).

Player 2 correctly answers a question. The players' scores are now (0, 0, 1, -1, -1, -1).

Players 1, 2, 4, 5 and 6, who have 0 points or lower, are eliminated, and Player 3 survives this game.

Sample Input 2

6 5 4
3
1
3
2

Sample Output 2

Yes
Yes
Yes
Yes
Yes
Yes

Sample Input 3

10 13 15
3
1
4
1
5
9
2
6
5
3
5
8
9
7
9

Sample Output 3

No
No
No
No
Yes
No
No
No
Yes
No


package main

import (
	"fmt"
)

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

	as := make([]int, q)

	for i := 0; i < q; i++ {
		fmt.Scanf("%d", &as[i])
	}

	for _, v := range *check(n, k, q ,&as) {
		fmt.Println(v)
	}
}

func check(n int, k int, q int, as *[]int) *[]string {
	p := make([]int, n)
	results := make([]string, n)
	for i := 0; i < n; i++ {
		p[i] = k
	}
	for _, a := range *as {
		for i, _ := range p {
			if a != i+1 {
				p[i] -= 1
			}
		}
	}
	for k, v := range p {
		if v <= 0 {
			results[k] = "No"
		} else {
			results[k] = "Yes"
		}
	}
	return &results
}


package main

import (
	"fmt"
)

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

	var a = make([]int, q)
	for i:=0; i<q; i++ {
		fmt.Scan(&a[i])
	}

	var nn = make(map[int]int, n)
	for i:=0; i<n; i++ {
		nn[i] = k
	}

	for i:=0; i<q; i++ {
		s := a[i] - 1
		for j:=0; j<n && nn[j] > 0; j++ {
			if j == s {
				continue
			}
			nn[j] -= 1
		}
	}

	for i:=0; i<n; i++ {
		if nn[i] > 0 {
			fmt.Println("Yes")
		} else {
			fmt.Println("No")
		}
	}
}


package main

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

var (
	scanner = bufio.NewScanner(os.Stdin)
)

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

func main() {
	n := readInt()
	fmt.Println(n * n * n)
}

Score : 100 points

Problem Statement

Takahashi is going to set a 3-character password.

How many possible passwords are there if each of its characters must be a digit between 1 and N (inclusive)?

Constraints

1 \leq N \leq 9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of possible passwords.

Sample Input 1

2

Sample Output 1

8

There are eight possible passwords: 111, 112, 121, 122, 211, 212, 221, and 222.

Sample Input 2

1

Sample Output 2

1

There is only one possible password if you can only use one kind of character.


package main

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

func main() {
	N := nextInt()

	fmt.Println(N * N * N)
}

var stdin = initStdin()

func initStdin() *bufio.Scanner {
	bufsize := 1 * 1024 * 1024 // 1 MB
	var stdin = bufio.NewScanner(os.Stdin)
	stdin.Buffer(make([]byte, bufsize), bufsize)
	stdin.Split(bufio.ScanWords)
	return stdin
}

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

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

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

func nextInt64() int64 {
	i, _ := strconv.ParseInt(nextString(), 10, 64)
	return i
}


package main

import "fmt"

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

	a := make([]int, n)
	for i := range a {
		fmt.Scan(&a[i])
	}

	b := make([]int, n)
	for i := range b {
		fmt.Scan(&b[i])
	}

	c := make([]int, n-1)
	for i := range c {
		fmt.Scan(&c[i])
	}

	y := len(a) + 1
	for _, v := range a {
		v = v - 1
		sum += b[v]
		if y == v-1 {
			sum += c[y]
		}
		y = v
	}
	fmt.Println(sum)
}

Score : 200 points

Problem Statement

Takahashi went to an all-you-can-eat buffet with N kinds of dishes and ate all of them (Dish 1, Dish 2, \ldots, Dish N) once.

The i-th dish (1 \leq i \leq N) he ate was Dish A_i.

When he eats Dish i (1 \leq i \leq N), he gains B_i satisfaction points.

Additionally, when he eats Dish i+1 just after eating Dish i (1 \leq i \leq N - 1), he gains C_i more satisfaction points.

Find the sum of the satisfaction points he gained.

Constraints

All values in input are integers.

2 \leq N \leq 20

1 \leq A_i \leq N

A_1, A_2, ..., A_N are all different.

1 \leq B_i \leq 50

1 \leq C_i \leq 50

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N
B_1 B_2 ... B_N
C_1 C_2 ... C_{N-1}

Output

Print the sum of the satisfaction points Takahashi gained, as an integer.

Sample Input 1

3
3 1 2
2 5 4
3 6

Sample Output 1

14

Takahashi gained 14 satisfaction points in total, as follows:

First, he ate Dish 3 and gained 4 satisfaction points.

Next, he ate Dish 1 and gained 2 satisfaction points.

Lastly, he ate Dish 2 and gained 5 + 3 = 8 satisfaction points.

Sample Input 2

4
2 3 4 1
13 5 8 24
45 9 15

Sample Output 2

74

Sample Input 3

2
1 2
50 50
50

Sample Output 3

150


package main

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

const (
	initialBufSize = 1024
	maxBufSize     = 1e6
)

var (
	scanner = bufio.NewScanner(os.Stdin)
	writer  = bufio.NewWriterSize(os.Stdout, 1000000)
)

func main() {
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, initialBufSize), maxBufSize)
	defer writer.Flush()
	n := scanInt()
	b := scanInts(n - 1)

	if n == 2 {
		fmt.Println(b[0] * 2)
		return
	}

	min := func(n ...int) int {
		ret := math.MaxInt64
		for _, v := range n {
			if v < ret {
				ret = v
			}
		}
		return ret
	}

	ans := b[0] + b[n-2]
	for i := 1; i < n-1; i++ {
		ans += min(b[i-1], b[i])
	}

	fmt.Println(ans)
}

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

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

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

func scanFloat64s(size int) []float64 {
	f := make([]float64, size)
	for i := 0; i < size; i++ {
		f[i] = scanFloat64()
	}
	return f
}

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

func scanStrings(size int) []string {
	s := make([]string, size)
	for i := 0; i < size; i++ {
		s[i] = scanString()
	}
	return s
}

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

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

// greatest common divisor(最大公約数)
func gcd(a, b int) int {
	for {
		mod := a % b
		if mod == 0 {
			return b
		}
		a, b = b, mod
	}
}

// latest common multiple(最小公倍数)
func lcm(a, b int) int {
	return (a / gcd(a, b)) * b
}

func fact(n int) int {
	ret := 1
	for i := 1; i <= n; i++ {
		ret *= i
	}
	return ret
}

func perm(n, r int) int {
	ret := 1
	for i := 0; i < r; i++ {
		ret *= n
		n--
	}
	return ret
}

func isPrimeNum(n int) bool {

	if n <= 1 {
		return false
	}

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

	return true
}

Score : 300 points

Problem Statement

There is an integer sequence A of length N whose values are unknown.

Given is an integer sequence B of length N-1 which is known to satisfy the following:

B_i \geq \max(A_i, A_{i+1})

Find the maximum possible sum of the elements of A.

Constraints

All values in input are integers.

2 \leq N \leq 100

0 \leq B_i \leq 10^5

Input

Input is given from Standard Input in the following format:

N
B_1 B_2 ... B_{N-1}

Output

Print the maximum possible sum of the elements of A.

Sample Input 1

3
2 5

Sample Output 1

9

A can be, for example, ( 2 , 1 , 5 ), ( -1 , -2 , -3 ), or ( 2 , 2 , 5 ). Among those candidates, A = ( 2 , 2 , 5 ) has the maximum possible sum.

Sample Input 2

2
3

Sample Output 2

6

Sample Input 3

6
0 153 10 10 23

Sample Output 3

53


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

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

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

	B := strings.Split(gets(), " ")

	// fmt.Println(A)
	// fmt.Println(B)

	for i := 0; i < n-2; i++ {
		if atoi(B[i+1]) < (atoi(B[i])) {
			A = append(A, atoi(B[i+1]))
		} else {
			A = append(A, atoi(B[i]))
		}
	}
	A = append(A, atoi(B[n-2]))

	// fmt.Println(A[:n])

	sum := 0

	for _, a := range A {
		sum += a
	}

	fmt.Println(sum)
}


package main

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

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

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

func main() {
	N := getInt()
	K := getInt()
	S := getString()

	row := make([]int, N)
	for i := 0; i < N; i++ {
		if S[i] == 'L' {
			row[i] = 0
		} else {
			row[i] = 1
		}
	}

	startTarget := 0
	endTarget := 0
	if row[0] == 0 {
		startTarget = 1
		endTarget = 0
	} else {
		startTarget = 0
		endTarget = 1
	}

	for i := 0; i < K; i++ {
		l := -1
		r := -1

		for index, p := range row {
			if l == -1 {
				if p == startTarget {
					l = index
				}
			}

			if l != -1 {
				if p == endTarget {
					r = index - 1
					break
				} else if index == N-1 {
					r = index
					break
				}
			}
		}

		if l == -1 || r == -1 {
			break
		}

		for index := l; index <= r; index++ {
			row[index] = endTarget
		}

		//fmt.Println(row)
	}

	result := 0
	for i := 0; i < N; i++ {
		if i == 0 && row[i] == 0 {
			continue
		} else if i == N-1 && row[i] == 1 {
			continue
		}

		if row[i] == 0 && row[i-1] == 0 {
			result++
		} else if row[i] == 1 && row[i+1] == 1 {
			result++
		}
	}
	fmt.Println(result)
}

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

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

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

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

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

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

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

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

			// なにか処理

			next = append(next, v)
		}
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return true
}

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

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

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

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

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

	return result
}

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

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

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

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

type intHeap []int

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

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

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

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

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

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

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

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

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

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

Score : 400 points

Problem Statement

There are N people standing in a queue from west to east.

Given is a string S of length N representing the directions of the people.
The i-th person from the west is facing west if the i-th character of S is L, and east if that character of S is R.

A person is happy if the person in front of him/her is facing the same direction.
If no person is standing in front of a person, however, he/she is not happy.

You can perform the following operation any number of times between 0 and K (inclusive):

Operation: Choose integers l and r such that 1 \leq l \leq r \leq N, and rotate by 180 degrees the part of the queue: the l-th, (l+1)-th, ..., r-th persons. That is, for each i = 0, 1, ..., r-l, the (l + i)-th person from the west will stand the (r - i)-th from the west after the operation, facing east if he/she is facing west now, and vice versa.

What is the maximum possible number of happy people you can have?

Constraints

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

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

|S| = N

Each character of S is L or R.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the maximum possible number of happy people after at most K operations.

Sample Input 1

6 1
LRLRRL

Sample Output 1

3

If we choose (l, r) = (2, 5), we have LLLRLL, where the 2-nd, 3-rd, and 6-th persons from the west are happy.

Sample Input 2

13 3
LRRLRLRRLRLLR

Sample Output 2

9

Sample Input 3

10 1
LLLLLRRRRR

Sample Output 3

9

Sample Input 4

9 2
RRRLRLRLL

Sample Output 4

7


package main

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

func run() {
	n := nextInt()
	k := nextInt()
	s := next()

	v := make([]int, 0)

	for i := 0; i < n; i++ {
		if(string(s[i]) == "R"){
			v = append(v, 1)
		}else {
			v = append(v, 0)
		}
	}

	count := 0
	count2 := 1
	te := v[0]

	for i := 1; i < n; i++ {
		if(te == v[i]){
			count ++
		}else{
			count2 ++
			te = v[i]
		}
	}

	if (count2 / 2 < k) {
		Println(count + (count2 / 2) * 2)
	} else{
		Println(count + k * 2 - (count2 % 2))
	}

}

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