package main

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

var sc *bufio.Scanner

const BufferSize = 1024

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

var production bool

func debugf(format string, v ...interface{}) {
	if !production {
		fmt.Printf(format, v...)
	}
}

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

func answer(reader io.Reader, writer io.Writer) {
	sc = bufio.NewScanner(reader)
	buf := make([]byte, BufferSize)
	sc.Buffer(buf, 1e+6)
	sc.Split(bufio.ScanWords)
	a := nextInt()
	b := nextInt()

	_, _ = fmt.Fprintf(writer, "%d", max(a+b, a-b, a*b))
}

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


package main

import (
	"fmt"
	"strconv"
)

func main() {
	var K, X int
	fmt.Scan(&K, &X)

	ans := ""
	for i := 0; i < K-1; i++ {
		ans += strconv.Itoa(X - K + 1 + i)
		ans += " "
	}
	ans += strconv.Itoa(X) + " "
	for i := 0; i < K-1; i++ {
		ans += strconv.Itoa(X + i + 1)
		ans += " "
	}

	fmt.Println(ans)
}

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

Score : 200 points

Problem Statement

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

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

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

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

Constraints

1 \leq K \leq 100

0 \leq X \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K X

Output

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

Sample Input 1

3 7

Sample Output 1

5 6 7 8 9

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

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

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

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

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

Sample Input 2

4 0

Sample Output 2

-3 -2 -1 0 1 2 3

Negative coordinates can also contain a stone painted black.

Sample Input 3

1 100

Sample Output 3

100

Submitted source-code file size, in bytes.

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

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


package main

import (
	"fmt"
)

// 以下の問題
// https://atcoder.jp/contests/abc137/tasks/abc137_b

func main() {
	var K, X int
	fmt.Scan(&K, &X)

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


package main

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

func main() {
	var k, x int
	s := wordScanner(100)
	scanInts(s, &k, &x)

	l := make([]string, 0)
	for i := max(x-k+1, -1000000); i <= min(x+k-1, 1000000); i++ {
		l = append(l, strconv.Itoa(i))
	}

	fmt.Println(strings.Join(l, " "))
}

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

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

func wordScanner(n int) *bufio.Scanner {
	s := bufio.NewScanner(os.Stdin)
	s.Split(bufio.ScanWords)
	b := make([]byte, n)
	s.Buffer(b, n)
	return s
}

func scanInts(s *bufio.Scanner, vals ...*int) {
	for i := range vals {
		s.Scan()
		n, _ := strconv.Atoi(s.Text())
		*vals[i] = n
	}
}


package main

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

type PairInt struct {
	first, second int
}

func NewPairInt(first, second int) PairInt {
	return PairInt{first, second}
}

type PairsInt []PairInt

func (p PairsInt) Less(i, j int) bool {
	if p[i].first == p[j].first {
		return p[i].second < p[j].second
	} else {
		return p[i].first < p[j].first
	}
}

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

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

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 solve() {
	var n, m int
	fmt.Scan(&n, &m)
	a := make([]int, n)
	b := make([]int, n)
	sc := bufio.NewScanner(os.Stdin)
	for i := 0; sc.Scan(); i++ {
		fmt.Println(sc.Text())
		args := strings.Split(sc.Text(), " ")
		a[i], _ = strconv.Atoi(args[0])
		b[i], _ = strconv.Atoi(args[1])
	}

	pairs := make(PairsInt, n)
	for i := 0; i < n; i++ {
		pairs[i] = NewPairInt(a[i], b[i])
	}
	sort.Sort(pairs)

	h := &IntHeap{}
	heap.Init(h)
	sum := 0
	j := 0
	for i := n; i > 0; i-- {
		for j < n && pairs[j].first+i <= m+1 {
			heap.Push(h, pairs[j].second)
			j++
		}
		if h.Len() != 0 {
			sum += heap.Pop(h).(int)
		}
	}

	fmt.Println(sum)
}

func main() {
	solve()
}

Score : 400 points

Problem Statement

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

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

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

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

You can already start working today.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i \leq 10^5

1 \leq B_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

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

Sample Input 1

3 4
4 3
4 1
2 2

Sample Output 1

5

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

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

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

Sample Input 2

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

Sample Output 2

10

Sample Input 3

1 1
2 1

Sample Output 3

0


package main

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

)

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

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

func NewScannerEx(stdin io.Reader) *ReaderEx {
	var this ReaderEx
	var idx int
	this.baseScanner = bufio.NewScanner(stdin)
	this.nextWordIdx = func() int {
		cur := idx
		idx++
		return cur
	}
	this.initWordIdx = func() {
		idx = 0
	}
	return &this
}

func (me *ReaderEx) ScanAndSplit() (isScanned bool) {
	isScanned = me.baseScanner.Scan()

	me.words = strings.Fields(me.baseScanner.Text())
	me.initWordIdx()
	return
}

func (me *ReaderEx) getString() string {
	return me.baseScanner.Text()
}

func (me *ReaderEx) getInt() int {
	n, err := strconv.Atoi(me.baseScanner.Text())
	defer func() {
		if err != nil {
			fmt.Fprintln(os.Stderr, "getInt()")
		}
	}()

	return n
}

func (me *ReaderEx) nextBytes() []byte {
	return []byte(me.words[me.nextWordIdx()])
}
func (me *ReaderEx) nextString() string {
	return me.words[me.nextWordIdx()]
}
func (me *ReaderEx) nextInt() int {
	n, err := strconv.Atoi(me.words[me.nextWordIdx()])

	defer func() {
		if err != nil {
			fmt.Fprintln(os.Stderr, "getInt(", n, ")")
		}
	}()
	return n
}

type inInfo struct {
	in    int
	after int
}

type inInfoSorter []inInfo

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

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

type ptr []int

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

func solve(stdin io.Reader, stdout io.Writer) {
	var n, m int
	var infos []inInfo
	reader := NewScannerEx(stdin)
	reader.ScanAndSplit()
	n, m = reader.nextInt(), reader.nextInt()

	for i := 0; i < n; i++ {
		reader.ScanAndSplit()
		infos = append(infos, inInfo{after: reader.nextInt(), in: reader.nextInt()})
	}

	sort.Sort(inInfoSorter(infos))

	var ans = make([]int, m)

	for _, w := range infos {
		i := m - w.after
		for ; i >= 0 && ans[i] > 0; i-- {

		}
		if i >= 0 {
			ans[i] = w.in
		}
	}

	fmt.Fprintln(stdout, sum(ans))

}


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

	hash := make(map[int][]int)

	for i := 0; i < n; i++ {
		a := nextInt()
		b := nextInt()

		if a > m {
			continue
		}

		hash[a] = append(hash[a], b)
	}

	result := 0
	bucket := make([]int, m)

	for day := 1; day <= m; day++ {
		d := hash[day]

		if len(d) > 0 {
			bucket = append(d, bucket...)
			sort.Sort(sort.Reverse(sort.IntSlice(bucket)))
			bucket = bucket[:m]
		}

		if len(bucket) > 0 {
			result += bucket[0]
			bucket = bucket[1:]
		}
	}

	fmt.Println(result)
}

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


package main

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

var sc *bufio.Scanner

const BufferSize = 1024

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

var production bool

func debugf(format string, v ...interface{}) {
	if !production {
		fmt.Printf(format, v...)
	}
}

type bc struct {
	num   int
	value int
}

type bcs []bc

func (b bcs) Len() int { return len(b) }
func (b bcs) Less(i, j int) bool {
	if b[i].num != b[j].num {
		return b[i].num < b[j].num
	}
	return b[i].value > b[j].value
}
func (b bcs) Swap(i, j int) { b[i], b[j] = b[j], b[i] }

// Btree represents an AVL tree
type Btree struct {
	root   *Node
	values []Val
	len    int
}

// Val interface to define the compare method used to insert and find values
type Val interface {
	Comp(val Val) int8
}

// Node represents a node in the tree with a value, left and right children, and a height/balance of the node.
type Node struct {
	Value       Val
	left, right *Node
	height      int8
}

// New returns a new btree
func New() *Btree { return new(Btree).Init() }

// Init initializes all values/clears the tree and returns the tree pointer
func (t *Btree) Init() *Btree {
	t.root = nil
	t.values = nil
	t.len = 0
	return t
}

// String returns a string representation of the tree values
func (t *Btree) String() string {
	return fmt.Sprint(t.Values())
}

// Empty returns true if the tree is empty
func (t *Btree) Empty() bool {
	return t.root == nil
}

// NotEmpty returns true if the tree is not empty
func (t *Btree) NotEmpty() bool {
	return t.root != nil
}

func (t *Btree) balance() int8 {
	if t.root != nil {
		return balance(t.root)
	}
	return 0
}

// Insert inserts a new value into the tree and returns the tree pointer
func (t *Btree) Insert(value Val) *Btree {
	added := false
	t.root = insert(t.root, value, &added)
	if added {
		t.len++
	}
	t.values = nil
	return t
}

func insert(n *Node, value Val, added *bool) *Node {
	if n == nil {
		*added = true
		return (&Node{Value: value}).Init()
	}
	c := value.Comp(n.Value)
	if c >= 0 {
		n.right = insert(n.right, value, added)
	} else if c < 0 {
		n.left = insert(n.left, value, added)
	} /*else {
		n.Value = value
		*added = false
		return n
	}*/

	n.height = n.maxHeight() + 1
	c = balance(n)

	if c > 1 {
		c = value.Comp(n.left.Value)
		if c < 0 {
			return n.rotateRight()
		} else if c > 0 {
			n.left = n.left.rotateLeft()
			return n.rotateRight()
		}
	} else if c < -1 {
		c = value.Comp(n.right.Value)
		if c > 0 {
			return n.rotateLeft()
		} else if c < 0 {
			n.right = n.right.rotateRight()
			return n.rotateLeft()
		}
	}
	return n
}

// InsertAll inserts all the values into the tree and returns the tree pointer
func (t *Btree) InsertAll(values []Val) *Btree {
	for _, v := range values {
		t.Insert(v)
	}
	return t
}

// Contains returns true if the tree contains the specified value
func (t *Btree) Contains(value Val) bool {
	return t.Get(value) != nil
}

// ContainsAny returns true if the tree contains any of the values
func (t *Btree) ContainsAny(values []Val) bool {
	for _, v := range values {
		if t.Contains(v) {
			return true
		}
	}
	return false
}

// ContainsAll returns true if the tree contains all of the values
func (t *Btree) ContainsAll(values []Val) bool {
	for _, v := range values {
		if !t.Contains(v) {
			return false
		}
	}
	return true
}

// Get returns the node value associated with the search value
func (t *Btree) Get(value Val) Val {
	var node *Node
	if t.root != nil {
		node = t.root.get(value)
	}
	if node != nil {
		return node.Value
	}
	return nil
}

// Len return the number of nodes in the tree
func (t *Btree) Len() int {
	return t.len
}

// Head returns the first value in the tree
func (t *Btree) Head() Val {
	if t.root == nil {
		return nil
	}
	var beginning = t.root
	for beginning.left != nil {
		beginning = beginning.left
	}
	if beginning == nil {
		for beginning.right != nil {
			beginning = beginning.right
		}
	}
	if beginning != nil {
		return beginning.Value
	}
	return nil
}

// Tail returns the last value in the tree
func (t *Btree) Tail() Val {
	if t.root == nil {
		return nil
	}
	var beginning = t.root
	for beginning.right != nil {
		beginning = beginning.right
	}
	if beginning == nil {
		for beginning.left != nil {
			beginning = beginning.left
		}
	}
	if beginning != nil {
		return beginning.Value
	}
	return nil
}

// Values returns a slice of all the values in tree in order
func (t *Btree) Values() []Val {
	if t.values == nil {
		t.values = make([]Val, t.len)
		t.Ascend(func(n *Node, i int) bool {
			t.values[i] = n.Value
			return true
		})
	}
	return t.values
}

// Delete deletes the node from the tree associated with the search value
func (t *Btree) Delete(value Val) *Btree {
	deleted := false
	t.root = deleteNode(t.root, value, &deleted)
	if deleted {
		t.len--
	}
	t.values = nil
	return t
}

// DeleteAll deletes the nodes from the tree associated with the search values
func (t *Btree) DeleteAll(values []Val) *Btree {
	for _, v := range values {
		t.Delete(v)
	}
	return t
}

func deleteNode(n *Node, value Val, deleted *bool) *Node {
	if n == nil {
		return n
	}

	c := value.Comp(n.Value)

	if c < 0 {
		n.left = deleteNode(n.left, value, deleted)
	} else if c > 0 {
		n.right = deleteNode(n.right, value, deleted)
	} else {
		if n.left == nil {
			t := n.right
			n.Init()
			return t
		} else if n.right == nil {
			t := n.left
			n.Init()
			return t
		}
		t := n.right.min()
		n.Value = t.Value
		n.right = deleteNode(n.right, t.Value, deleted)
		*deleted = true
	}

	//re-balance
	if n == nil {
		return n
	}
	n.height = n.maxHeight() + 1
	bal := balance(n)
	if bal > 1 {
		if balance(n.left) >= 0 {
			return n.rotateRight()
		}
		n.left = n.left.rotateLeft()
		return n.rotateRight()
	} else if bal < -1 {
		if balance(n.right) <= 0 {
			return n.rotateLeft()
		}
		n.right = n.right.rotateRight()
		return n.rotateLeft()
	}

	return n
}

// Pop deletes the last node from the tree and returns its value
func (t *Btree) Pop() Val {
	value := t.Tail()
	if value != nil {
		t.Delete(value)
	}
	return value
}

// Pull deletes the first node from the tree and returns its value
func (t *Btree) Pull() Val {
	value := t.Head()
	if value != nil {
		t.Delete(value)
	}
	return value
}

// NodeIterator expresses the iterator function used for traversals
type NodeIterator func(n *Node, i int) bool

// Ascend performs an ascending order traversal of the tree calling the iterator function on each node
// the iterator will continue as long as the NodeIterator returns true
func (t *Btree) Ascend(iterator NodeIterator) {
	var i int
	if t.root != nil {
		t.root.iterate(iterator, &i, true)
	}
}

// Descend performs a descending order traversal of the tree using the iterator
// the iterator will continue as long as the NodeIterator returns true
func (t *Btree) Descend(iterator NodeIterator) {
	var i int
	if t.root != nil {
		t.root.rIterate(iterator, &i, true)
	}
}

// Debug prints out useful debug information about the tree for debugging purposes
func (t *Btree) Debug() {
	fmt.Println("----------------------------------------------------------------------------------------------")
	if t.Empty() {
		fmt.Println("tree is empty")
	} else {
		fmt.Println(t.Len(), "elements")
	}

	t.Ascend(func(n *Node, i int) bool {
		if t.root.Value == n.Value {
			fmt.Print("ROOT ** ")
		}
		n.Debug()
		return true
	})
	fmt.Println("----------------------------------------------------------------------------------------------")
}

// Init initializes the values of the node or clears the node and returns the node pointer
func (n *Node) Init() *Node {
	n.height = 1
	n.left = nil
	n.right = nil
	return n
}

// String returns a string representing the node
func (n *Node) String() string {
	return fmt.Sprint(n.Value)
}

// Debug prints out useful debug information about the tree node for debugging purposes
func (n *Node) Debug() {
	var children string
	if n.left == nil && n.right == nil {
		children = "no children |"
	} else if n.left != nil && n.right != nil {
		children = fmt.Sprint("left child:", n.left.String(), " right child:", n.right.String())
	} else if n.right != nil {
		children = fmt.Sprint("right child:", n.right.String())
	} else {
		children = fmt.Sprint("left child:", n.left.String())
	}

	fmt.Println(n.String(), "|", "height", n.height, "|", "balance", balance(n), "|", children)
}

func height(n *Node) int8 {
	if n != nil {
		return n.height
	}
	return 0
}

func balance(n *Node) int8 {
	if n == nil {
		return 0
	}
	return height(n.left) - height(n.right)
}

func (n *Node) get(val Val) *Node {
	var node *Node
	c := val.Comp(n.Value)
	if c < 0 {
		if n.left != nil {
			node = n.left.get(val)
		}
	} else if c > 0 {
		if n.right != nil {
			node = n.right.get(val)
		}
	} else {
		node = n
	}
	return node
}

func (n *Node) rotateRight() *Node {
	l := n.left
	// Rotation
	l.right, n.left = n, l.right

	// update heights
	n.height = n.maxHeight() + 1
	l.height = l.maxHeight() + 1

	return l
}

func (n *Node) rotateLeft() *Node {
	r := n.right
	// Rotation
	r.left, n.right = n, r.left

	// update heights
	n.height = n.maxHeight() + 1
	r.height = r.maxHeight() + 1

	return r
}

func (n *Node) iterate(iterator NodeIterator, i *int, cont bool) {
	if n != nil && cont {
		n.left.iterate(iterator, i, cont)
		cont = iterator(n, *i)
		*i++
		n.right.iterate(iterator, i, cont)
	}
}

func (n *Node) rIterate(iterator NodeIterator, i *int, cont bool) {
	if n != nil && cont {
		n.right.iterate(iterator, i, cont)
		cont = iterator(n, *i)
		*i++
		n.left.iterate(iterator, i, cont)
	}
}

func (n *Node) min() *Node {
	current := n
	for current.left != nil {
		current = current.left
	}
	return current
}

func (n *Node) maxHeight() int8 {
	rh := height(n.right)
	lh := height(n.left)
	if rh > lh {
		return rh
	}
	return lh
}

// IntVal represents an integer tree val
type IntVal int

// Comp returns 1 if i > val, -1 if i < val and 0 if i equal to val
func (i IntVal) Comp(val Val) int8 {
	v := val.(IntVal)
	if i > v {
		return 1
	} else if i < v {
		return -1
	} else {
		return 0
	}
}

func answer(reader io.Reader, writer io.Writer) {
	sc = bufio.NewScanner(reader)
	buf := make([]byte, BufferSize)
	sc.Buffer(buf, 1e+6)
	sc.Split(bufio.ScanWords)
	n := nextInt()
	m := nextInt()
	a := make([]bc, n)

	for i := range a {
		a[i].num = nextInt()
		a[i].value = nextInt()
	}
	sort.Sort(bcs(a))
	//debugf("%v\n", a)
	idx := 0
	ans := 0
	/*
		b := make([]int, 0, n)
		for i := 0; i < m; i++ {
			for idx < n && a[idx].num <= i+1 {
				b = append(b, a[idx].value)
				idx++
			}
			sort.Sort(sort.Reverse(sort.IntSlice(b)))
			if len(b) > 0 {
				ans += b[0]
				b[0] = 0
			}
		}
	*/

	b := new(Btree).Init()

	//debugf("%v\n", a)
	for i := 0; i < m; i++ {
		for idx < n && a[idx].num <= i+1 {
			b.Insert(IntVal(a[idx].value))
			idx++
		}
		//debugf("i: %d, ans: %d, %v\n", i, ans, b.String())
		n := b.Tail()
		if n != nil {
			ans += int(n.(IntVal))
			b.Delete(n)
		}
		//debugf("end i: %d, ans: %d, %v\n", i, ans, b.String())
	}

	_, _ = fmt.Fprintf(writer, "%d", ans)
}

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


package main

import (
	"fmt"
)

const MOD = 1000000007

func ModAdd(a, b int64) int64 {
	return (a + b) % MOD
}

func ModMul(a, b int64) int64 {
	return a * b % MOD
}

func ModSub(a, b int64) int64 {
	r := (a%MOD - b%MOD) % MOD
	if r < 0 {
		r += MOD
	}
	return r
}

func ModDiv(a, b int64) int64 {
	return a % MOD * ModInv(b) % MOD
}

func ModPow(a, n int64) int64 {
	var r int64 = 1
	for n > 0 {
		if n&1 == 1 {
			r = r * a % MOD
		}
		a = a * a % MOD
		n >>= 1
	}
	return r
}

func ModInv(a int64) int64 {
	var b, u, v int64 = MOD, 1, 0
	for b > 0 {
		t := a / b
		a -= t * b
		a, b = b, a
		u -= t * v
		u, v = v, u
	}
	u %= MOD
	if u < 0 {
		u += MOD
	}
	return u
}

type Q struct {
	idx, value int
	a, b       int
	index      int
}

type QS []*Q

func (p QS) Len() int           { return len(p) }
func (p QS) Less(i, j int) bool { return p[i].value > p[j].value }
func (pq QS) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

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

func (pq *QS) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	old[n-1] = nil  // avoid memory leak
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

func main() {
	var A, B, C int
	fmt.Scanf("%d %d %d\n", &A, &B, &C)
	remain := A - B
	if remain > C {
		fmt.Println(C)
	} else {
		fmt.Println(remain)
	}

}

Score : 100 points

Problem Statement

We have two bottles for holding water.

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

Bottle 2 contains C milliliters of water.

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

How much amount of water will remain in Bottle 2?

Constraints

All values in input are integers.

1 \leq B \leq A \leq 20

1 \leq C \leq 20

Input

Input is given from Standard Input in the following format:

A B C

Output

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

Sample Input 1

6 4 3

Sample Output 1

1

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

Sample Input 2

8 3 9

Sample Output 2

4

Sample Input 3

12 3 7

Sample Output 3

0


package main

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

type int64Array []int64

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

type xxx struct {
	x int
}

type sortArray []xxx

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

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

func main() {
	n := readInt()
	ans := 0
	for i := 1; i < n+1; i++ {
		s := strconv.Itoa(i)
		if len(s)%2 == 1 {
			ans++
		}
	}

	fmt.Println(ans)
}

Score : 200 points

Problem Statement

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

Constraints

1 \leq N \leq 10^5

Input

Input is given from Standard Input in the following format:

N

Output

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

Sample Input 1

11

Sample Output 1

9

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

Sample Input 2

136

Sample Output 2

46

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

Sample Input 3

100000

Sample Output 3

90909


package main

import (
	"fmt"
	"strconv"
)

func main() {
	var n string
	fmt.Scan(&n)
	nInt, _ := strconv.Atoi(n)
	ans := 0
	for i:=1; i<nInt+1; i++ {
		if i < 10 {
			ans++
		} else if 99 < i && i < 1000 {
			ans++
		} else if 9999 < i && i < 100000 {
			ans++
		}
	}
	fmt.Println(ans)
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

func main() {
	// Get a number from stdio and convert it
	sc.Split(bufio.ScanWords)
	sc.Scan()

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

	result := 0
	for i > 0 {
		if i/100000 != 0 {
			i = i - 1
		} else if i/10000 != 0 {
			if i == 10000 {
				result++
				i--
				continue
			}
			result += ((i/10000)-1)*10000 + (i % 10000) + 1 //just 10000
			i = i % 10000
		} else if i/1000 != 0 {
			if i == 1000 {
				i--
				continue
			}
			i = i % 1000
		} else if i/100 != 0 {
			if i == 100 {
				result++
				i--
				continue
			}
			result += ((i/100)-1)*100 + (i % 100) + 1 //just 100
			i = i % 100
		} else if i/10 != 0 {
			result += 9
			break
		} else {
			result += i
			break
		}
	}
	fmt.Println(result)
}


// 自分（自分含む）より右側にある直近のLと自分（自分含む）より左側にある直近のRの位置を表す配列を作る
// 10^100は偶数なので距離の偶奇で判別
package main

import "fmt"

func main() {
	var s string
	fmt.Scan(&s)
	runes := []rune(s)
	LindiciesOfRight, RindiciesOfLeft := make([]int, len(runes)), make([]int, len(runes))
	LindiciesOfRight[len(runes)-1] = len(runes) - 1
	for i := 1; i < len(runes); i++ {
		now := string(runes[i])
		if now == "R" {
			RindiciesOfLeft[i] = i
		} else {
			RindiciesOfLeft[i] = RindiciesOfLeft[i-1]
		}
	}
	for i := len(runes) - 2; i >= 0; i-- {
		now := string(runes[i])
		if now == "L" {
			LindiciesOfRight[i] = i
		} else {
			LindiciesOfRight[i] = LindiciesOfRight[i+1]
		}
	}
	ans := make([]int, len(runes))
	for i := 0; i < len(runes); i++ {
		now := string(runes[i])
		if now == "R" {
			dist := LindiciesOfRight[i] - i
			if dist%2 == 0 {
				ans[LindiciesOfRight[i]]++
			} else {
				ans[LindiciesOfRight[i]-1]++
			}
		} else {
			dist := i - RindiciesOfLeft[i]
			if dist%2 == 0 {
				ans[RindiciesOfLeft[i]]++
			} else {
				ans[RindiciesOfLeft[i]+1]++
			}
		}
	}
	for i, a := range ans {
		fmt.Print(a)
		if i == len(ans)-1 {
			fmt.Println()
		} else {
			fmt.Print(" ")
		}
	}
}

Score : 400 points

Problem Statement

Given is a string S consisting of L and R.

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

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

Initially, one child is standing on each square.

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

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

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

Constraints

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

Each character of S is L or R.

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

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

RRLRL

Sample Output 1

0 1 2 1 1

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

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

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

Sample Input 2

RRLLLLRLRRLL

Sample Output 2

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

Sample Input 3

RRRLLRLLRRRLLLLL

Sample Output 3

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


package main

import (
	"fmt"
)

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 reverseInts(input []int) []int {
	if len(input) == 0 {
		return input
	}
	return append(reverseInts(input[1:]), input[0])
}

func main() {
	var S string
	fmt.Scan(&S)
	var N []int = make([]int, len(S))

	for i := 0; i < 2; i++ {
		cnt := 0
		for j, s := range S {
			if string([]rune{s}) == "R" {
				cnt++
			} else {
				N[j] += cnt / 2
				N[j-1] += (cnt + 1) / 2
				cnt = 0
			}
		}
		N = reverseInts(N)
		S = Reverse(S)
		rev := ""
		for _, s := range S {
			if string([]rune{s}) == "L" {
				rev += "R"
			} else {
				rev += "L"
			}
		}
		S = rev
	}

	for _, i := range N {
		fmt.Print(i, " ")
	}
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

var mod int = 1000000007

func main() {
	buf := make([]byte, 0)
	sc.Buffer(buf, mod)
	sc.Split(bufio.ScanWords)
	n, k := iScan(), iScan()
	a := iSScan(n)
	x := sum(a)
	d := make([]int, 0)
	for i := 1; i*i <= x; i++ {
		if x%i == 0 {
			d = append(d, i)
			if i != x/i {
				d = append(d, x/i)
			}
		}
	}
	sort.Sort(sort.Reverse(sort.IntSlice(d)))
	for _, v := range d {
		y := make([]int, n)
		z := make([]int, n)
		for i := 0; i < n; i++ {
			y[i] = a[i] % v
		}
		sort.Ints(y)
		yy := make([]int, n)
		copy(yy, y)
		for i := 0; i < n; i++ {
			z[i] = v - y[i]
		}
		for i := 1; i < n; i++ {
			y[i] += y[i-1]
		}
		for i := n - 2; i >= 0; i-- {
			z[i] += z[i+1]
		}
		c := 0
		for i := 0; i < n-1; i++ {
			c += yy[i]
			if y[i] == z[i+1] {
				break
			}
		}
		if c <= k {
			fmt.Println(v)
			break
		}
	}
}

Score : 500 points

Problem Statement

We have a sequence of N integers: A_1, A_2, \cdots, A_N.

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

Choose two integers i and j such that i \neq j, each between 1 and N (inclusive). Add 1 to A_i and -1 to A_j, possibly producing a negative element.

Compute the maximum possible positive integer that divides every element of A after the operations. Here a positive integer x divides an integer y if and only if there exists an integer z such that y = xz.

Constraints

2 \leq N \leq 500

1 \leq A_i \leq 10^6

0 \leq K \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \cdots A_{N-1} A_{N}

Output

Print the maximum possible positive integer that divides every element of A after the operations.

Sample Input 1

2 3
8 20

Sample Output 1

7

7 will divide every element of A if, for example, we perform the following operation:

Choose i = 2, j = 1. A becomes (7, 21).

We cannot reach the situation where 8 or greater integer divides every element of A.

Sample Input 2

2 10
3 5

Sample Output 2

8

Consider performing the following five operations:

Choose i = 2, j = 1. A becomes (2, 6).

Choose i = 2, j = 1. A becomes (1, 7).

Choose i = 2, j = 1. A becomes (0, 8).

Choose i = 2, j = 1. A becomes (-1, 9).

Choose i = 1, j = 2. A becomes (0, 8).

Then, 0 = 8 \times 0 and 8 = 8 \times 1, so 8 divides every element of A. We cannot reach the situation where 9 or greater integer divides every element of A.

Sample Input 3

4 5
10 1 2 22

Sample Output 3

7

Sample Input 4

8 7
1 7 5 6 8 2 6 5

Sample Output 4

5


package main

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

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

	n, k := io.Int(), io.Int()

	aa := make([]int, n)

	sum := 0

	for i := 0; i < n; i++ {
		aa[i] = io.Int()
		sum += aa[i]
	}

	possibe := Divisors(sum)

	SortDesc(possibe)

	ans := calc(possibe, aa, k)

	fmt.Println(ans)

}

func calc(possibe []int, aa []int, k int) int {
	//fmt.Println(-9 % 8)
	ans := 1
	for _, p := range possibe {
		cnt := 0

		for _, a := range aa {
			cnt += a % p
		}

		if cnt/2 == k {
			ans = p
			break

		}

	}
	return ans
}

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

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

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

func findK(a, b int) string {
	sum := a + b
	if sum%2 == 1 {
		return "IMPOSSIBLE"
	}
	return strconv.Itoa(sum / 2)
}

func main() {
	a, b := nextInt(), nextInt()
	r := findK(a, b)
	fmt.Println(r)
}

Score: 100 points

Problem Statement

We have two distinct integers A and B.

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

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

Constraints

All values in input are integers.

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

A and B are distinct.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the integer K satisfying the condition.

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

Sample Input 1

2 16

Sample Output 1

9

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

Sample Input 2

0 3

Sample Output 2

IMPOSSIBLE

No integer satisfies the condition.

Sample Input 3

998244353 99824435

Sample Output 3

549034394


//go:generate echo "https://atcoder.jp/contests/abc135/tasks/abc135_b"
package main

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

var scan = newScanner(os.Stdin)

func solve(ps []int) bool {
	cps := make([]int, len(ps), len(ps))
	copy(cps, ps)
	sort.Sort(sort.IntSlice(cps))
	c := 0
	for i := range cps {
		if cps[i] != ps[i] {
			c++
		}
	}
	return c <= 2
}

func solve2(ps []int) bool {
	k := 0
	for i, p := range ps {
		if i != p-1 {
			k++
		}
	}
	return k <= 2
}

func main() {
	N := scan.Int()
	ps := scan.Ints(N)
	if solve2(ps) {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

type scanner struct {
	*bufio.Scanner
}

func newScanner(r io.Reader) *scanner {
	s := bufio.NewScanner(r)
	s.Split(bufio.ScanWords)
	s.Buffer(nil, 100000000)
	return &scanner{s}
}

func (s *scanner) String() string {
	s.Scan()
	return s.Text()
}

func (s *scanner) Strings(l int) []string {
	if l == 0 {
		return []string{}
	}
	sl := make([]string, l, l)
	for i := range sl {
		sl[i] = s.String()
	}
	return sl
}

func (s *scanner) Int() int {
	n, _ := strconv.Atoi(s.String())
	return n
}

func (s *scanner) Ints(l int) []int {
	if l == 0 {
		return []int{}
	}
	sl := make([]int, l, l)
	for i := range sl {
		sl[i] = s.Int()
	}
	return sl
}

func (s *scanner) Float64() float64 {
	f, _ := strconv.ParseFloat(s.String(), 64)
	return f
}

func (s *scanner) Float64s(l int) []float64 {
	if l == 0 {
		return []float64{}
	}
	sl := make([]float64, l, l)
	for i := range sl {
		sl[i] = s.Float64()
	}
	return sl
}

func (s *scanner) BigInt() *big.Int {
	n, _ := strconv.ParseInt(s.String(), 10, 64)
	return big.NewInt(n)
}

func (s *scanner) BigInts(l int) []*big.Int {
	if l == 0 {
		return []*big.Int{}
	}
	sl := make([]*big.Int, l, l)
	for i := range sl {
		sl[i] = s.BigInt()
	}
	return sl
}

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

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

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

func ipow(x, n int) int {
	if n == 0 {
		return 1
	}
	a := ipow(x, n>>1)
	a *= a
	if n&1 != 0 {
		a *= x
	}
	return a
}

func isum(X []int) int {
	s := 0
	for _, x := range X {
		s += x
	}
	return s
}

func chmax(x *int, v int) {
	if *x < v {
		*x = v
	}
}

func chmin(x *int, v int) {
	if *x > v {
		*x = v
	}
}

func factor(n int) map[int]int {
	m := map[int]int{}
	for i := 2; i*i <= n; i++ {
		for n%i == 0 {
			n /= i
			m[i]++
		}
	}
	if n != 1 {
		m[n]++
	}
	return m
}

var mod = 1000000007

func setMintMod(x int) {
	mod = x
}

type mint int

func newMint(v int) mint {
	return mint((v%mod + mod) % mod)
}

func (x mint) Add(y mint) mint {
	v := x + y
	if v >= mint(mod) {
		return v - mint(mod)
	}
	return v
}

func (x mint) Sub(y mint) mint {
	v := x + mint(mod) - y
	if v >= mint(mod) {
		return v - mint(mod)
	}
	return v
}

func (x mint) Mul(y mint) mint {
	return (x * y) % mint(mod)
}

func (x mint) pow(n int) mint {
	if n == 0 {
		return mint(1)
	}
	a := x.pow(n >> 1)
	a = a.Mul(a)
	if n&1 != 0 {
		a = a.Mul(x)
	}
	return a
}

func (x mint) Inverse() mint {
	return x.pow(mod - 2)
}

func (x mint) Div(y mint) mint {
	return x * y.Inverse()
}

func (x mint) Neg() mint {
	return newMint(int(-x))
}

type factorial struct {
	fact        []mint
	factInverse []mint
}

func newFactorial(n int) *factorial {
	f := new(factorial)
	f.init(n)
	return f
}

func (f *factorial) init(n int) {
	fact := make([]mint, n+1, n+1)
	fact[0] = newMint(1)
	for i := 1; i <= n; i++ {
		fact[i] = fact[i-1].Mul(newMint(i))
	}

	inv := make([]mint, n+1, n+1)
	inv[n] = fact[n].Inverse()
	for i := n; i >= 1; i-- {
		inv[i-1] = inv[i].Mul(newMint(i))
	}

	f.fact = fact
	f.factInverse = inv
}

func (f *factorial) Get(n int) mint {
	return f.fact[n]
}

func (f *factorial) GetInverse(n int) mint {
	return f.factInverse[n]
}

func (f *factorial) Permutation(n, k int) mint {
	if k < 0 || n < k {
		return 0
	}
	return f.fact[n].Mul(f.factInverse[n-k])
}

func (f *factorial) Combination(n, k int) mint {
	if k < 0 || n < k {
		return 0
	}
	return f.fact[n].Mul(f.factInverse[k]).Mul(f.factInverse[n-k])
}

type sieve struct {
	n          int
	primes     []int
	maxFactors []int
}

func newSieve(n int) *sieve {
	s := &sieve{
		n:          n,
		primes:     []int{},
		maxFactors: make([]int, n+1, n+1),
	}
	s.init()
	return s
}

func (s *sieve) init() {
	s.maxFactors[0] = -1
	s.maxFactors[1] = -1
	for i := 2; i <= s.n; i++ {
		if s.maxFactors[i] != 0 {
			continue
		}
		s.primes = append(s.primes, i)
		s.maxFactors[i] = i
		for j := i * i; j <= s.n; j += i {
			if s.maxFactors[j] == 0 {
				s.maxFactors[j] = i
			}
		}
	}
}

func (s *sieve) IsPrime(x int) bool {
	return s.maxFactors[x] == x
}

func (s *sieve) Factor(x int) map[int]int {
	m := map[int]int{}
	for x != 1 {
		m[s.maxFactors[x]]++
		x /= s.maxFactors[x]
	}
	return m
}

Score : 200 points

Problem Statement

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

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

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

Constraints

All values in input are integers.

2 \leq N \leq 50

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

Input

Input is given from Standard Input in the following format:

N
p_1 p_2 ... p_N

Output

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

Sample Input 1

5
5 2 3 4 1

Sample Output 1

YES

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

Sample Input 2

5
2 4 3 5 1

Sample Output 2

NO

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

Sample Input 3

7
1 2 3 4 5 6 7

Sample Output 3

YES

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


package main

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

type Scanner struct {
	sc *bufio.Scanner
}

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

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

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

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

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

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

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

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

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

func main() {
	sc := NewScanner()
	N := sc.nextInt()
	P := sc.nextIntSlice(N)
	count := 0
	for i, n := range P {
		if n != i+1 {
			count++
		}
	}
	if count <= 2 {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

func lineToInts(line string) []int {
	var array []int
	for _, s := range strings.Split(line, " ") {
		i, _ := strconv.Atoi(s)
		array = append(array, i)
	}
	return array
}

func main() {
	var n int
	fmt.Scan(&n)
	p := lineToInts(readLine())
	counter := 0
	for i := 0; i < len(p); i++ {
		if p[i] != i + 1 {
			counter++
			if counter > 2 {
				break
			}
		}
	}
	if counter > 2 {
		fmt.Println("NO")
	} else {
		fmt.Println("YES")
	}
}


package main

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

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

	var N int
	fmt.Fscanf(input, "%d\n", &N)
	var count int
	for i := 0; i < N; i++ {
		var pi int
		fmt.Fscanf(input, "%d", &pi)
		if pi != i+1 {
			count++
		}
	}
	if count > 2 {
		fmt.Println("NO")
	} else {
		fmt.Println("YES")
	}
}


package main

import "fmt"

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

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

	cnt := 0
	for i := range p {
		v := p[i]
		if v == i+1 {
			continue
		}
		cnt++
	}
	if cnt == 0 || cnt == 2 {
		fmt.Println("YES")
		return
	}
	fmt.Println("NO")
}


package main

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

const pi = math.Pi

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

func main() {
	reader.Split(bufio.ScanWords)
	N, _ := strconv.Atoi(read())
	p := make([]int, N)
	p_bef := make([]int, N)
	for i := 0; i < N; i++ {
		t, _ := strconv.Atoi(read())
		p[i] = t
		p_bef[i] = t
	}
	sort.Ints(p_bef)

	for i := 1; i < N; i++ {
		if p[i] != p_bef[i] {
			cnt++
			if 2 <= cnt {
				fmt.Println("NO")
				return
			}
		}
	}
	fmt.Println("YES")
}

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

var reader = bufio.NewScanner(os.Stdin)

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

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

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

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

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

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

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

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

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

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

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

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

type SortBy [][]int

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

type PriorityQueue []int

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


package main

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

const pi = math.Pi

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

func main() {
	reader.Split(bufio.ScanWords)
	N, _ := strconv.Atoi(read())
	p := make([]int, N)
	p_bef := make([]int, N)
	for i := 0; i < N; i++ {
		t, _ := strconv.Atoi(read())
		p[i] = t
		p_bef[i] = t
	}

	var value, key int
	var flag bool
	for i := 1; i < N; i++ {
		if p[i-1] > p[i] && flag == false {
			value = p[i-1]
			key = i - 1
			flag = true
		}
		if flag == true && value < p[i] {
			p[i], p[key] = p[key], p[i]
			break
		}
		if i == N-1 {
			p[i], p[key] = p[key], p[i]
		}
	}

	sort.Ints(p_bef)

	for i := 0; i < N; i++ {
		if p[i] != p_bef[i] {
			fmt.Println("NO")
			return
		}
	}
	fmt.Println("YES")
}

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

var reader = bufio.NewScanner(os.Stdin)

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

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

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

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

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

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

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

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

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

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

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

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

type SortBy [][]int

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

type PriorityQueue []int

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


package main

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

func main() {
	n := readi()
	a := make([]int64, n+1)
	for i := 0; i < n+1; i++ {
		a[i] = readi64()
	}
	b := make([]int64, n)
	for i := 0; i < n; i++ {
		b[i] = readi64()
	}

	var ans int64
	for i := 0; i < n; i++ {
		if a[i] <= b[i] {
			ans = ans + a[i]
			tmp := (b[i] - a[i])
			if a[i]+1 <= tmp {
				ans = ans + a[i+1]
				a[i+1] = 0
			} else {
				ans = ans + tmp
				a[i+1] = a[i+1] - tmp
			}
		} else {
			ans = ans + b[i]
		}
	}

	fmt.Println(ans)
}

/*-------------------utilities-------------------*/

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

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

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

func chmin(x *int, y int) bool {
	if *x > y {
		*x = y
		return true
	}
	return false
}

func chmax(x *int, y int) bool {
	if *x < y {
		*x = y
		return true
	}
	return false
}

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

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

func comb(n, k int) int {
	if n < k {
		return 0
	}
	if n < 0 || k < 0 {
		return 0
	}
	return fac[n] * (finv[k] * finv[n-k] % MOD) % MOD
}

func permutations(arr []int) [][]int {
	var helper func([]int, int)
	res := [][]int{}

	helper = func(arr []int, n int) {
		if n == 1 {
			tmp := make([]int, len(arr))
			copy(tmp, arr)
			res = append(res, tmp)
		} else {
			for i := 0; i < n; i++ {
				helper(arr, n-1)
				if n%2 == 1 {
					tmp := arr[i]
					arr[i] = arr[n-1]
					arr[n-1] = tmp
				} else {
					tmp := arr[0]
					arr[0] = arr[n-1]
					arr[n-1] = tmp
				}
			}
		}
	}
	helper(arr, len(arr))
	return res
}

func isPrime(n int) bool {
	if n == 1 {
		return false
	}
	for i := 2; i*i <= n; i++ {
		if n%i == 0 {
			return false
		}
	}
	return true
}

func divisor(n int) (res []int) {
	for i := 1; i*i <= n; i++ {
		if n%i == 0 {
			res = append(res, i)
			if i*i != n {
				res = append(res, n/i)
			}
		}
	}
	sort.Ints(res)
	return
}

/*-------------------init-------------------*/

const (
	INF = 1000000000000000000
	MOD = 1e9 + 7

	COMB_MAX = 510000
)

var (
	readString func() string
)

var (
	fac  = [COMB_MAX]int{}
	finv = [COMB_MAX]int{}
	inv  = [COMB_MAX]int{}
)

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

func combInit() {
	fac[0] = 1
	fac[1] = 1
	finv[0] = 1
	finv[1] = 1
	inv[1] = 1
	for i := 2; i < COMB_MAX; i++ {
		fac[i] = fac[i-1] * i % MOD
		inv[i] = MOD - inv[MOD%i]*(MOD/i)%MOD
		finv[i] = finv[i-1] * inv[i] % MOD
	}
}

/*-------------------inputs-------------------*/

func readi() int {
	return int(readi64())
}

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

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

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

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

Score : 300 points

Problem Statement

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

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

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

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

2
3 5 2
4 5

Sample Output 1

9

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

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

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

Sample Input 2

3
5 6 3 8
5 100 8

Sample Output 2

22

Sample Input 3

2
100 1 1
1 100

Sample Output 3

3


package main

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

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

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

func nextInt() uint64 {
	sc.Scan()
	i, e := strconv.ParseUint(sc.Text(), 10, 64)
	if e != nil {
		panic(e)
	}
	return i
}

func intArray(n []string) []int {
	var m []int
	for i, _ := range n {
		v, _ := strconv.Atoi(n[i])
		m = append(m, v)
	}
	return m
}

func int64Array(n []string) []int64 {
	var m []int64
	for i, _ := range n {
		v, _ := strconv.ParseInt(n[i], 10, 64)
		m = append(m, v)
	}
	return m
}

func uint64Array(n []string) []uint64 {
	var m []uint64
	for i, _ := range n {
		v, _ := strconv.ParseUint(n[i], 10, 64)
		m = append(m, v)
	}
	return m
}

func intExistIn(v int, arr []int) bool {
	for _, a := range arr {
		if a == v {
			return true
		}
	}

	return false
}

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

	return false
}

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 uintArrayToStr(a []uint64) string {
	var S string

	for _, v := range a {
		S += strconv.Itoa(int(v))
	}
	return S
}

func remove(x []uint64, y int) []uint64 {
	var newArray []uint64
	for i, _ := range x {
		if i != y {
			newArray = append(newArray, x[i])
		}
	}
	return newArray
}

func ascendSort(a []uint64) []uint64 {
	for i := 0; i < len(a); i++ {
		for i := 0; i < len(a)-1; i++ {
			if a[i] > a[i+1] {
				tmp := a[i+1]
				a[i+1] = a[i]
				a[i] = tmp
			}
		}
	}
	return a
}

func descendSort(a []uint64) []uint64 {
	for i := 0; i < len(a); i++ {
		for i := 0; i < len(a)-1; i++ {
			if a[i] < a[i+1] {
				tmp := a[i+1]
				a[i+1] = a[i]
				a[i] = tmp
			}
		}
	}
	return a
}

func maxAndIndex(a []uint64) (uint64, int) {
	max := uint64(0)
	index := 0
	for i, v := range a {
		if v > max {
			max = v
			index = i
		}
	}
	return max, index
}

func sum(a []uint64) uint64 {
	sum := uint64(0)
	for _, v := range a {
		sum += v
	}
	return sum
}

func defeat(count *int64, hero *int64, monster *int64) {
	if *hero >= *monster {
		*count, *hero, *monster = *count + *monster, *hero - *monster, int64(0)
	} else {
		*count, *hero, *monster = *count + *hero, int64(0), *monster - *hero
	}
}

func main() {
	// sc.Split(bufio.ScanWords)
	N := int(nextInt())
	monsters := int64Array(strings.Split(nextLine(), " "))
	heroes := int64Array(strings.Split(nextLine(), " "))

	var count int64

	for i := 0; i < N; i++ {
		defeat(&count, &heroes[i], &monsters[i])
		defeat(&count, &heroes[i], &monsters[i+1])
	}

	fmt.Println(count)
}


package main

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

func main() {
	sc := bufio.NewScanner(os.Stdin)
	var n int

	if sc.Scan() {
		line := sc.Text()
		n, _ = strconv.Atoi(line)
	}

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

	if sc.Scan() {
		line := sc.Text()
		for i, data := range strings.Split(line, " ") {
			dataInt, _ := strconv.Atoi(data)
			a[i] = dataInt
		}
	}

	if sc.Scan() {
		line := sc.Text()
		for i, data := range strings.Split(line, " ") {
			dataInt, _ := strconv.Atoi(data)
			b[i] = dataInt
		}
	}

	cnt := 0
	for i := 0; i < n; i++ {
		rest := a[i] - b[i]
		if rest < 0 {
			rest *= -1

			cnt += a[i]
			a[i] = 0

			rest2 := a[i+1] - rest
			if rest2 < 0 {
				cnt += a[i+1]
				a[i+1] = 0
			} else {
				cnt += rest
				a[i+1] = -rest2
			}
		} else {
			cnt += b[i]
			a[i] = -rest
		}
	}

	fmt.Println(cnt)
}


package main

import (
	"fmt"
	"strconv"
)

const MOD = 1000000007

func ModAdd(a, b int64) int64 {
	return (a + b) % MOD
}

func ModMul(a, b int64) int64 {
	return a * b % MOD
}

func ModSub(a, b int64) int64 {
	r := (a%MOD - b%MOD) % MOD
	if r < 0 {
		r += MOD
	}
	return r
}

func ModDiv(a, b int64) int64 {
	return a % MOD * ModInv(b) % MOD
}

func ModPow(a, n int64) int64 {
	var r int64 = 1
	for n > 0 {
		if n&1 == 1 {
			r = r * a % MOD
		}
		a = a * a % MOD
		n >>= 1
	}
	return r
}

func ModInv(a int64) int64 {
	var b, u, v int64 = MOD, 1, 0
	for b > 0 {
		t := a / b
		a -= t * b
		a, b = b, a
		u -= t * v
		u, v = v, u
	}
	u %= MOD
	if u < 0 {
		u += MOD
	}
	return u
}

type Q struct {
	idx, value int
	a, b       int
	index      int
}

type QS []*Q

func (p QS) Len() int           { return len(p) }
func (p QS) Less(i, j int) bool { return p[i].value > p[j].value }
func (pq QS) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

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

func (pq *QS) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	old[n-1] = nil  // avoid memory leak
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

func main() {
	var S string
	fmt.Scanf("%s\n", &S)
	RS := []rune(S)
	Reverse(RS)

	dp := [100010][14]int{}
	pow := 1
	for i := 0; i < len(RS); i++ {
		r := RS[i]
		if i == 0 {
			if string(r) == "?" {
				for j := 0; j < 10; j++ {
					value := j
					dp[i][value] += 1
					dp[i][(value*pow)%13] %= MOD

				}
			} else {
				value, _ := strconv.Atoi(string(r))
				dp[i][value*pow] += 1
				dp[i][(value*pow)%13] %= MOD

			}
		} else {
			if string(r) == "?" {
				for j := 0; j < 10; j++ {
					for k := 0; k < 13; k++ {
						value := j
						dp[i][(k+value*pow)%13] += dp[i-1][k]
						dp[i][(k+value*pow)%13] %= MOD
					}
				}
			} else {
				for k := 0; k < 13; k++ {
					value, _ := strconv.Atoi(string(r))
					dp[i][(k+value*pow)%13] += dp[i-1][k]
					dp[i][(k+value*pow)%13] %= MOD
				}
			}
		}

		pow = pow * 10 % 13
	}
	fmt.Println(dp[len(RS)-1][5])
}

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

Score : 400 points

Problem Statement

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

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

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

Constraints

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

1 \leq |S| \leq 10^5

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

??2??5

Sample Output 1

768

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

Sample Input 2

?44

Sample Output 2

1

Only 044 satisfies the condition.

Sample Input 3

7?4

Sample Output 3

0

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

Sample Input 4

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

Sample Output 4

153716888


package main

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

type int64Array []int64

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

type xxx struct {
	x int
}

type sortArray []xxx

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

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

const mod int = 1e9 + 7

func main() {
	s := readString()
	n := len(s)

	dp := make([][]int, n+1)
	for i := range dp {
		dp[i] = make([]int, 13)
	}
	dp[0][0] = 1

	for i := 1; i < n+1; i++ {
		c := s[i-1 : i]
		cnum, _ := strconv.Atoi(c)
		for j := 0; j < 10; j++ {
			if c != "?" && j != cnum {
				continue
			}
			for k := 0; k < 13; k++ {
				dp[i][(k*10+j)%13] = (dp[i][(k*10+j)%13] + dp[i-1][k]) % mod
			}
		}
	}

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


package main

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

// input に使うやつ
var rdr = bufio.NewReaderSize(os.Stdin, 10000)

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

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

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

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

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

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

func main() {
	s := strings.Split(readLine(), "")
	n := 13
	dp := make([]int, n)
	dp[0] = 1

	mod := 1000000007
	mul := 1
	for i := len(s) - 1; i >= 0; i-- {
		nextDP := make([]int, n)

		if s[i] == "?" {
			for k := 0; k < 10; k++ {
				for j := 0; j < n; j++ {
					nextDP[(k*mul+j)%n] += dp[j]
					nextDP[(k*mul+j)%n] %= mod
				}
			}
		} else {
			k, _ := strconv.Atoi(s[i])
			for j := 0; j < n; j++ {
				nextDP[(k*mul+j)%n] += dp[j]
				nextDP[(k*mul+j)%n] %= mod
			}
		}

		mul *= 10
		mul %= n
		dp = nextDP
	}
	fmt.Println(dp[5])
}


// https://atcoder.jp/contests/abc135/tasks/abc135_d

package main

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

func pairsToKey(n, k int) string {
	return fmt.Sprintf("%d_%d", n, k)
}

// 下から n (1, .., len(chars)) 桁以上で見て 13 で割って k 余らせることができる個数
func rec(n, k int, chars []rune, memo [][]int) int {
	if n == len(chars) {
		if chars[0] == '?' {
			if k <= 9 {
				return 1
			}

			return 0
		}

		num := int(chars[0] - '0')

		if num == k {
			return 1
		}

		return 0
	}

	// 10a + b ≡ k ⇔ 40a + 4b ≡ a + 4b ≡ 4k
	// よって 1 の位と 10 の位以上に分けて、 a ≡ 4k - 4b となる個数を再帰で求めれば良い
	if memo[n][k] != -1 {
		return memo[n][k]
	}

	c := chars[len(chars)-n]

	res := 0

	if c == '?' {
		for i := 0; i < 10; i++ {
			rest := (4*k - i*4 + 13*3) % 13
			res += rec(n+1, rest, chars, memo)
		}
	} else {
		num := int(c - '0')
		rest := (4*k - num*4 + 13*3) % 13
		res = rec(n+1, rest, chars, memo)
	}

	res %= MOD

	memo[n][k] = res
	return res
}

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

	chars := []rune(S)
	memo := make([][]int, len(chars))

	for i := range memo {
		memo[i] = make([]int, 13)

		for j := 0; j < 13; j++ {
			memo[i][j] = -1
		}
	}

	res := rec(1, 5, chars, memo)
	io.Println(res)
}

// d: debug IO. it can print debug in test.
func solve2(io *Io, d *Io) {
	S := io.Next()

	chars := []rune(S)
	// dp[i][j] 先頭 i 文字目（1 <= i <= len(chs)）までで余りが j になる個数
	dp := make([][]int, len(chars)+1)

	for i := range dp {
		dp[i] = make([]int, 13)
	}

	// 一文字目を取った時の mod はその文字自体で決定されるため、 0 文字目相当のものの mod は 0 のものが 1 つあるとする必要がある
	dp[0][0] = 1

	for i := 0; i < len(chars); i++ {
		for j := 0; j < 10; j++ {
			if !(chars[i] == '?' || int(chars[i]-'0') == j) {
				continue
			}

			// i+1 桁目が j で i 桁目までの余りが k であれば i+1 桁目までの余りは 10k + j % 13
			for k := 0; k < 13; k++ {
				dp[i+1][(10*k+j)%13] += dp[i][k]
			}

			for k := 0; k < 13; k++ {
				dp[i+1][k] %= MOD
			}
		}
	}

	res := dp[len(chars)][5]
	io.Println(res)
}

func main() {
	io := NewIo()
	defer io.Flush()
	solve2(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
}

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

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

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

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

/* 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 {
	max := numbers[0]
	for i, number := range numbers {
		if i == 0 {
			continue
		}
		if max > number {
			max = number
		}
	}
	return max
}

// DigitSum returns sum of the int's digits
func DigitSum(n int) int {
	if n < 0 {
		return -1
	}

	res := 0

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

	return res
}

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

// MinCalculator is helper to get min value
type MinCalculator struct {
	current int
}

// NewMinCalculator returns new MinCalculator with initial value
func NewMinCalculator(initial int) *MinCalculator {
	return &MinCalculator{
		current: initial,
	}
}

// Check compares the value with current and update current if necessary
func (mc *MinCalculator) Check(val int) {
	if val < mc.current {
		mc.current = val
	}
}

// MaxCalculator is helper to get max value
type MaxCalculator struct {
	current int
}

// NewMaxCalculator returns new MaxCalculator with initial value
func NewMaxCalculator(initial int) *MaxCalculator {
	return &MaxCalculator{
		current: initial,
	}
}

// Check compares the value with current and update current if necessary
func (mc *MaxCalculator) Check(val int) {
	if val > mc.current {
		mc.current = val
	}
}

/* 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 main() {
	var s int
	fmt.Scan(&s)

	v := 1000000000
	x := v - s%v
	y := (s + x) / v
	fmt.Println(0, 0, v, 1, x, y)
}

Score : 400 points

Problem Statement

Given is an integer S.
Find a combination of six integers X_1,Y_1,X_2,Y_2,X_3, and Y_3 that satisfies all of the following conditions:

0 \leq X_1,Y_1,X_2,Y_2,X_3,Y_3 \leq 10^9

The area of the triangle in a two-dimensional plane whose vertices are (X_1,Y_1),(X_2,Y_2), and (X_3,Y_3) is S/2.

We can prove that there always exist six integers that satisfy the conditions under the constraints of this problem.

Constraints

1 \leq S \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

S

Output

Print six integers X_1,Y_1,X_2,Y_2,X_3, and Y_3 that satisfy the conditions, in this order, with spaces in between.
If multiple solutions exist, any of them will be accepted.

Sample Input 1

3

Sample Output 1

1 0 2 2 0 1

The area of the triangle in a two-dimensional plane whose vertices are (1,0),(2,2), and (0,1) is 3/2.
Printing 3 0 3 1 0 1 or 1 0 0 1 2 2 will also be accepted.

Sample Input 2

100

Sample Output 2

0 0 10 0 0 10

Sample Input 3

311114770564041497

Sample Output 3

314159265 358979323 846264338 327950288 419716939 937510582


package main

import (
	"fmt"
)

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

	var x1 = 0
	var y2 = 0
	for i := 1; i < n/2; i++ {
		if n%i == 0 {
			x1 = i
			y2 = n / x1
		}
	}
	fmt.Printf("0 0 %v 0 0 %v", x1, y2)
}


/*
URL:
https://atcoder.jp/contests/agc036/tasks/agc036_b
*/

package main

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

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

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

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

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

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

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

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

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

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

var (
	n, k int
	A    []int

	next [70 + 5][200000 + 50]int
	G    [200000 + 50][]int
)

func main() {
	n, k = ReadInt2()
	A = ReadIntSlice(n)

	for i := 0; i < n; i++ {
		G[A[i]] = append(G[A[i]], i)
	}

	for i := 0; i < 200000+10; i++ {
		if len(G[i]) == 0 {
			continue
		}

		for j := 0; j < len(G[i]); j++ {
			if j+1 < len(G[i]) {
				next[0][G[i][j]] = G[i][j+1] - G[i][j] + 1
			} else {
				next[0][G[i][j]] = n + G[i][0] - G[i][j] + 1
				// next[0][G[i][j]] = INF_BIT60
			}
		}
	}
	// PrintfDebug("%v\n", next[0][:n])

	for d := 0; d+1 < 65; d++ {
		for v := 0; v < n; v++ {
			nid := (next[d][v] + v) % n
			next[d+1][v] = next[d][v] + next[d][nid]

			if next[d+1][v] > INF_BIT60 {
				next[d+1][v] = INF_BIT60
			}
		}
	}
	// for i := 0; i < 3; i++ {
	// 	PrintfDebug("[%d]: %v\n", i, next[i][:n])
	// }

	nokori := n*k - 1
	cid := 0
	for {
		for d := 50; d >= 0; d-- {
			if nokori-next[d][cid] >= 0 {
				nokori -= next[d][cid]
				cid = (next[d][cid] + cid) % n
				// break
			}
		}

		if nokori < n {
			break
		}
	}
	// PrintfDebug("nokori: %v, cid: %v\n", nokori, cid)

	B := []int{}
	for i := cid; i < n; i++ {
		B = append(B, A[i])
	}
	memo := [200000 + 50]int{}
	for i := 0; i < 200000+40; i++ {
		memo[i] = -1
	}

	C := [200000 + 50]int{}
	cur := 0
	for i := 0; i < len(B); i++ {
		b := B[i]

		if memo[b] == -1 {
			C[cur] = b
			memo[b] = cur
			cur++
		} else {
			cur = memo[b]
			memo[b] = -1
		}
	}
	fmt.Println(PrintIntsLine(C[:cur]...))

	// ans := []int{}
	// for i := 0; i < len(B); i++ {
	// 	if memo[B[i]] == -1 {
	// 		ans = append(ans, B[i])
	// 		memo[B[i]] = len(ans) - 1
	// 	} else {
	// 		// ans = ans[:memo[B[i]]]

	// 		tmp := []int{}
	// 		for j := 0; j < memo[B[i]]; j++ {
	// 			tmp = append(tmp, ans[j])
	// 		}
	// 		ans = tmp

	// 		memo[B[i]] = -1
	// 	}
	// }
	// fmt.Println(PrintIntsLine(ans...))
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

	return string(res)
}

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

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

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

	return string(res)
}

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

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

Score : 700 points

Problem Statement

We have a sequence of N \times K integers: X=(X_0,X_1,\cdots,X_{N \times K-1}).
Its elements are represented by another sequence of N integers: A=(A_0,A_1,\cdots,A_{N-1}). For each pair i, j (0 \leq i \leq K-1,\ 0 \leq j \leq N-1), X_{i \times N + j}=A_j holds.

Snuke has an integer sequence s, which is initially empty.
For each i=0,1,2,\cdots,N \times K-1, in this order, he will perform the following operation:

If s does not contain X_i: add X_i to the end of s.

If s does contain X_i: repeatedly delete the element at the end of s until s no longer contains X_i. Note that, in this case, we do not add X_i to the end of s.

Find the elements of s after Snuke finished the operations.

Constraints

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

1 \leq K \leq 10^{12}

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_0 A_1 \cdots A_{N-1}

Output

Print the elements of s after Snuke finished the operations, in order from beginning to end, with spaces in between.

Sample Input 1

3 2
1 2 3

Sample Output 1

2 3

In this case, X=(1,2,3,1,2,3).
We will perform the operations as follows:

i=0: s does not contain 1, so we add 1 to the end of s, resulting in s=(1).

i=1: s does not contain 2, so we add 2 to the end of s, resulting in s=(1,2).

i=2: s does not contain 3, so we add 3 to the end of s, resulting in s=(1,2,3).

i=3: s does contain 1, so we repeatedly delete the element at the end of s as long as s contains 1, which causes the following changes to s: (1,2,3)→(1,2)→(1)→().

i=4: s does not contain 2, so we add 2 to the end of s, resulting in s=(2).

i=5: s does not contain 3, so we add 3 to the end of s, resulting in s=(2,3).

Sample Input 2

5 10
1 2 3 2 3

Sample Output 2

3

Sample Input 3

6 1000000000000
1 1 2 2 3 3

Sample Output 3

s may be empty in the end.

Sample Input 4

11 97
3 1 4 1 5 9 2 6 5 3 5

Sample Output 4

9 2 6


/*
URL:
https://atcoder.jp/contests/agc036/tasks/agc036_b
*/

package main

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

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

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

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

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

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

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

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

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

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

var (
	n, k int
	A    []int

	next [70 + 5][200000 + 50]int
	G    [200000 + 50][]int
)

func main() {
	n, k = ReadInt2()
	A = ReadIntSlice(n)

	for i := 0; i < n; i++ {
		G[A[i]] = append(G[A[i]], i)
	}

	for i := 0; i < 200000+10; i++ {
		if len(G[i]) == 0 {
			continue
		}

		for j := 0; j < len(G[i]); j++ {
			if j+1 < len(G[i]) {
				next[0][G[i][j]] = G[i][j+1] - G[i][j] + 1
			} else {
				next[0][G[i][j]] = n + G[i][0] - G[i][j] + 1
			}
		}
	}
	PrintfDebug("%v\n", next[0][:n])

	for d := 0; d+1 < 60; d++ {
		for v := 0; v < n; v++ {
			nid := (next[d][v] + v) % n
			// next[d+1][v] = next[d][v] + next[d][nid] - v
			next[d+1][v] = next[d][v] + next[d][nid]
		}
	}

	nokori := n*k - 1
	cid := 0
	for {
		for d := 55; d >= 0; d-- {
			if nokori-next[d][cid] >= 0 {
				nokori -= next[d][cid]
				cid = (next[d][cid] + cid) % n
				break
			}
		}

		if nokori < n {
			break
		}
	}
	PrintfDebug("nokori: %v, cid: %v\n", nokori, cid)

	B := []int{}
	for i := cid; i < n; i++ {
		B = append(B, A[i])
	}
	memo := [200000 + 50]int{}
	for i := 0; i < 200000+40; i++ {
		memo[i] = -1
	}

	// ans := []int{}
	// for i := 0; i < len(B); i++ {
	// 	if memo[B[i]] == -1 {
	// 		ans = append(ans, B[i])
	// 		memo[B[i]] = len(ans) - 1
	// 	} else {
	// 		ans = ans[:memo[B[i]]]
	// 		memo[B[i]] = -1
	// 	}
	// }
	// fmt.Println(PrintIntsLine(ans...))
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

	return string(res)
}

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

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

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

	return string(res)
}

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

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


package main

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

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

	as := make([]int, n)
	var sc = bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	for i := range as {
		sc.Scan()
		as[i], _ = strconv.Atoi(sc.Text())
	}

	m := make(map[int]int)
	to := make([]int, n*2)
	for i := 0; i < n*2; i++ {
		v := as[i%n]
		if b, ok := m[v]; ok && b > -1 {
			to[b] = i - b
			m[v] = i
		} else {
			m[v] = i
		}
	}
	//fmt.Println("to: ", to)

	var i, j int
	//fmt.Println("i,j: ", i, j)
	for i := 0; i != k-1 || j+to[j]+1 < n; {
		j += (to[j] + 1)
		if j >= n {
			i++
			j %= n
		}
		//fmt.Println("i,j: ", i, j)
		if j == 0 {
			k = k % i
			i = 0
		}
	}

	var s []int
	m = make(map[int]int)
	for ; i < k; i++ {
		for ; j < n; j++ {
			if b, ok := m[as[j]]; ok && b > -1 {
				for l := len(s) - 1; s[l] != as[j]; l-- {
					m[s[l]] = -1
				}
				m[as[j]] = -1
				s = s[0:b]
			} else {
				s = append(s, as[j])
				m[as[j]] = len(s) - 1
			}
		}
	}

	for i := range s {
		if i == len(s)-1 {
			fmt.Println(s[i])
		} else {
			fmt.Printf("%d ", s[i])
		}
	}
}


package main

import (
	"fmt"
	"math"
)

func main() {
	var r float64
	fmt.Scan(&r)
	fmt.Println(int(3 * math.Pow(r, 2)))
}

Score : 100 points

Problem Statement

It is known that the area of a regular dodecagon inscribed in a circle of radius a is 3a^2.

Given an integer r, find the area of a regular dodecagon inscribed in a circle of radius r.

Constraints

1 \leq r \leq 100

r is an integer.

Input

Input is given from Standard Input in the following format:

r

Output

Print an integer representing the area of the regular dodecagon.

Sample Input 1

4

Sample Output 1

48

The area of the regular dodecagon is 3 \times 4^2 = 48.

Sample Input 2

15

Sample Output 2

675

Sample Input 3

80

Sample Output 3

19200


package main

import (
	"fmt"
)

type ll int64

func main() {

	var N int
	fmt.Scan(&N)

	a := make([]int, N+1)
	ans := 0
	ans_slice := make([]int,N+1)

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

	ans_flag := 0
	for i:= N; i > 0 ; i--  {//Nから1まで

		k:= i
		j := 1
		ans_flag = 0

		for k <= N  {
			ans_flag += a[k]
			j++
			k = i * j
		}

		if ans_flag % 2 != 0 {//2で割り切れない
			ans++
			ans_slice[i] = 1
		}

	}

	fmt.Println(ans)
	for i:=1;i <=N ;i++  {
		if ans_slice[i] == 1 {
			fmt.Print(i)
			//fmt.Print(" ")
		}
	}
	//fmt.Println("")

}


package main

import "fmt"

func main() {
	var r int
	fmt.Scan(&r)
	fmt.Println(3 * r * r)
}


package main

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

var sc *bufio.Scanner

const BufferSize = 1024

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

var production bool

func debugf(format string, v ...interface{}) {
	if !production {
		fmt.Printf(format, v...)
	}
}

func answer(reader io.Reader, writer io.Writer) {
	sc = bufio.NewScanner(reader)
	buf := make([]byte, BufferSize)
	sc.Buffer(buf, 1e+6)
	sc.Split(bufio.ScanWords)
	n := nextInt()
	ans := 3 * n * n

	_, _ = fmt.Fprintf(writer, "%d", ans)
}

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