package main

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

func main() {
	defer writer.Flush() // Use printf, scanf

	// CODE
	var N int
	var S []byte
	scanf("%d\n", &N)
	scanf("%s\n", &S)

	// #.##.
	// 232343

	// startBlack = 0
	v := make([]int, N+1)
	for i := 0; i < N; i++ {
		if S[i] == '.' {
			v[0]++
		}
	}

	for startBlack := 1; startBlack < N; startBlack++ {
		v[startBlack] = v[startBlack-1]
		if S[startBlack-1] == '.' {
			v[startBlack]--
		} else {
			v[startBlack]++
		}
	}

	// startBlack = N
	for i := 0; i < N; i++ {
		if S[i] == '#' {
			v[N]++
		}
	}

	ans := int(1e10)
	for _, t := range v {
		ans = minInt(ans, t)
	}

	printf("%d\n", ans)
}

// I/O {{{
var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)

func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }
func scanInts(n int) []int {
	res := make([]int, n)
	for i := 0; i < n-1; i++ {
		scanf("%d ", &res[i])
	}
	scanf("%d\n", &res[n-1])
	return res
}

// }}}
// {{{ dummy
func dummy() {
	fmt.Printf("Hello, World\n")
	fmt.Printf("%v", reflect.TypeOf(0))

	arr := []int{10, 9, 8, 7, 1}
	sort.Ints(arr)
	fmt.Println(arr)
}

// }}}
// Set {{{
// s := NewSet()
// s.Add("a")
// s.Add("b")

// for i, v := range s.GetSlice() {
// 	// 0 a
// 	// 1 b
// 	printf("%d %s\n", i, v.(string))
// }

// printf("%v\n", s.Contains("a")) // true
// printf("%v\n", s.Contains("x")) // false
type Set map[interface{}]struct{}

func NewSet() Set {
	return Set{}
}

func (s *Set) Add(x interface{}) {
	(*s)[x] = struct{}{}
}

func (s Set) Contains(x interface{}) bool {
	_, ok := s[x]
	return ok
}

func (s Set) GetSlice() []interface{} {
	rc := []interface{}{}
	for key, _ := range s {
		rc = append(rc, key)
	}
	return rc
}

// }}}
// Math {{{
func maxInt(x int, y int) int {
	if x > y {
		return x
	}
	return y
}

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

// }}}
// PriorityQueue {{{
// Usage:
// type Person struct {
// 	name string
// 	age  int
// }
//
// func (p1 Person) Less(p2 interface{}) bool {
// 	return p1.age < p2.(Person).age
// }
//
// func main() {
// 	sc.Split(bufio.ScanWords)
// 	defer out.Flush() // Use printf
//
// 	// CODE
// 	q := NewPriorityQueue()
// 	q.Push(Person{name: "B", age: 11})
// 	q.Push(Person{name: "A", age: 10})
// 	q.Push(Person{name: "C", age: 12})
//
// 	for q.Len() > 0 {
// 		p := q.Pop().(Person)
// 		printf("%s %d\n", p.name, p.age)
// 	}
// }
func NewPriorityQueue() *PriorityQueue {
	q := &PriorityQueue{s: new(sorter)}
	heap.Init(q.s)
	return q
}

func (q *PriorityQueue) Pop() Comparable {
	return heap.Pop(q.s).(Comparable)
}

func (q *PriorityQueue) Top() Comparable {
	if len(*q.s) > 0 {
		return (*q.s)[0].(Comparable)
	}
	return nil
}

func (q *PriorityQueue) Fix(x Comparable, i int) {
	(*q.s)[i] = x
	heap.Fix(q.s, i)
}

func (q *PriorityQueue) Remove(i int) Comparable {
	return heap.Remove(q.s, i).(Comparable)
}

func (q *PriorityQueue) Len() int {
	return q.s.Len()
}

type Comparable interface {
	Less(other interface{}) bool
}

type sorter []Comparable

func (s *sorter) Push(x interface{}) {
	*s = append(*s, x.(Comparable))
}

func (s *sorter) Pop() interface{} {
	n := len(*s)
	if n > 0 {
		x := (*s)[n-1]
		*s = (*s)[0 : n-1]
		return x
	}
	return nil
}

func (s *sorter) Len() int {
	return len(*s)
}

func (s *sorter) Less(i, j int) bool {
	return (*s)[i].Less((*s)[j])
}

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

// Define priority queue struct
type PriorityQueue struct {
	s *sorter
}

func (q *PriorityQueue) Push(x Comparable) {
	heap.Push(q.s, x)
}

// }}}
// Sort {{{
// sort.Stable(IntSlice(a))
type IntSlice []int

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

// }}}
// SegmentTree {{{
// segInt := InitSegmentTree(
// 	[]int{1, 9, 5, 3, 7, 2, 4, 6, 8},
// 	int(1e9),
// 	IntMergerMin,
// )
// fmt.Println(segInt.GetRange(1, 2)) // 9 = min(9)
// fmt.Println(segInt.GetRange(3, 5)) // 3 = min(3, 7)
type SegmentTree struct {
	offset int
	inf    interface{}
	data   []interface{}
	merge  interface{}
}

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

func FloatMergerMin(a, b float64) float64 {
	if a < b {
		return a
	}
	return b
}

func StringMergerMin(a, b string) string {
	strSlice := sort.StringSlice([]string{a, b})
	strSlice.Sort()
	if a == strSlice[0] {
		return a
	}
	return b
}

func InitSegmentTree(a, inf, merge interface{}) *SegmentTree {
	av := reflect.ValueOf(a)
	n := av.Len()
	size := 1
	for size < n {
		size *= 2
	}
	data := make([]interface{}, size*2)
	for j, i := 0, size-1; i < size+n-1; i++ {
		data[i] = av.Index(j).Interface()
		j++
	}
	for i := size + n - 1; i < size*2; i++ {
		data[i] = inf
	}

	for i := size - 2; i >= 0; i-- {
		data[i] = reflect.ValueOf(merge).
			Call([]reflect.Value{reflect.ValueOf(data[i*2+1]), reflect.ValueOf(data[i*2+2])})[0].
			Interface()
	}

	return &SegmentTree{
		inf:    inf,
		offset: size,
		data:   data,
		merge:  merge,
	}
}

func (tree *SegmentTree) GetRange(from, to int) interface{} {
	return tree.getRange(from, to, 0, 0, tree.offset)
}

func (tree *SegmentTree) getRange(from, to, index, left, right int) interface{} {
	if to <= left || right <= from {
		return tree.inf
	}
	if from <= left && right <= to {
		return tree.data[index]
	}
	med := (left + right) / 2
	lvalue := tree.getRange(from, to, index*2+1, left, med)
	rvalue := tree.getRange(from, to, index*2+2, med, right)

	return reflect.ValueOf(tree.merge).
		Call([]reflect.Value{reflect.ValueOf(lvalue), reflect.ValueOf(rvalue)})[0].
		Interface()
}

func (tree *SegmentTree) UpdateAt(index int, value interface{}) {
	idx := tree.offset - 1 + index
	tree.data[idx] = value
	for idx >= 1 {
		parent := idx / 2
		left := parent * 2
		right := parent*2 + 1
		tree.data[parent] = reflect.ValueOf(tree.merge).
			Call([]reflect.Value{reflect.ValueOf(tree.data[left]), reflect.ValueOf(tree.data[right])})[0].
			Interface()
		idx = parent
	}
}

// }}}
// UnionFind {{{
// u := NewUnionFind(3)
// u.Unit(0, 1)
// printf("%v\n", u.Same(0, 1)) // true
// printf("%v\n", u.Same(0, 2)) // false
type UnionFind struct {
	par   []int // 親
	rank  []int // 木の深さ
	count int   // 要素数
}

func NewUnionFind(count int) *UnionFind {
	par := make([]int, count)
	rank := make([]int, count)
	for i := 0; i < count; i++ {
		par[i] = i
		rank[i] = 0
	}
	return &UnionFind{par: par, rank: rank, count: count}
}

func (uf UnionFind) Find(x int) int {
	if uf.par[x] == x {
		return x
	} else {
		uf.par[x] = uf.par[uf.par[x]]
		return uf.Find(uf.par[x])
	}
}

func (uf *UnionFind) Unit(x, y int) {
	x = uf.Find(x)
	y = uf.Find(y)
	if x == y {
		return
	} else if uf.rank[x] < uf.rank[y] {
		uf.par[x] = y
	} else {
		uf.par[y] = x
		if uf.rank[x] == uf.rank[y] {
			uf.rank[x]++
		}
	}
}

func (uf UnionFind) Same(x, y int) bool {
	return uf.Find(x) == uf.Find(y)
}

//}}}
// Prime {{{
const Q int = 10010

var isPrime [Q]bool
var primeList []int

func initPrime() {
	for i := 0; i < Q; i++ {
		isPrime[i] = true
	}
	isPrime[0], isPrime[1] = false, false
	for i := 2; i < Q; i++ {
		if !isPrime[i] {
			continue
		}
		primeList = append(primeList, i)
		for k := i * 2; k < Q; k += i {
			isPrime[k] = false
		}
	}
}

// }}}
// Combination {{{
var memo [1000][1000]int

func c(n, k, m int) int {
	if memo[n][k] != 0 {
		return memo[n][k]
	}

	if n == k {
		memo[n][k] = 1
	} else if k == 0 {
		memo[n][k] = 1
	} else {
		memo[n][k] = (c(n-1, k-1, m) + c(n-1, k, m)) % m
	}
	return memo[n][k]
}

// 重複組合せ O(n+k)
func hcomp(n, k, m int) int {
	return c(k+n-1, k, m)
}

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

// }}}


package main

import (
	"fmt"
)

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

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

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

Score : 100 points

Problem Statement

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

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

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

At most how many coins can you get?

Constraints

All values in input are integers.

3 \leq A, B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of coins you can get.

Sample Input 1

5 3

Sample Output 1

9

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

Sample Input 2

3 4

Sample Output 2

7

Sample Input 3

6 6

Sample Output 3

12

Submitted source-code file size, in bytes.

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

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


package main

import "fmt"

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

	for i:=0; i<2; i++ {
		if X >= Y {
			r += X
			X--
		} else {
			r += Y
			Y--
		}
	}
	fmt.Println(r)
}


package main

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

func main() {
	stdin := bufio.NewScanner(os.Stdin)
	stdin.Scan()
	text := stdin.Text()
	strs := strings.Split(text, " ")

	A, _ := strconv.Atoi(strs[0])
	B, _ := strconv.Atoi(strs[1])

	ret := max(max(2*A-1, A+B), 2*B-1)
	fmt.Println(ret)

}

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


package main
import "fmt"
func main() {
  var a,b,m int
  fmt.Scan(&a,&b)
  m = 0
  if a < b {
    m += b
    b--
  } else {
    m += a
    a--
  }
  if a < b {
    m += b
    b--
  } else {
    m += a
    a--
  }
  fmt.Println(m)
}


package main

import (
	"fmt"
)

func main() {
	var n int

	fmt.Scan(&n)

	var m int = 0
	var cnt int = 0

	for i := 0; i < n; i++ {
		var x int
		fmt.Scan(&x)
		if x >= m {
			cnt++
			m = x
		}
	}

	fmt.Print(cnt)
}

Score : 200 points

Problem Statement

There are N mountains ranging from east to west, and an ocean to the west.

At the top of each mountain, there is an inn. You have decided to choose where to stay from these inns.

The height of the i-th mountain from the west is H_i.

You can certainly see the ocean from the inn at the top of the westmost mountain.

For the inn at the top of the i-th mountain from the west (i = 2, 3, ..., N), you can see the ocean if and only if H_1 \leq H_i, H_2 \leq H_i, ..., and H_{i-1} \leq H_i.

From how many of these N inns can you see the ocean?

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq H_i \leq 100

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

Print the number of inns from which you can see the ocean.

Sample Input 1

4
6 5 6 8

Sample Output 1

3

You can see the ocean from the first, third and fourth inns from the west.

Sample Input 2

5
4 5 3 5 4

Sample Output 2

3

Sample Input 3

5
9 5 6 8 4

Sample Output 3

1


package main

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

func main() {
	stdin := bufio.NewScanner(os.Stdin)
	stdin.Scan()
	text := stdin.Text()
	ret1 := 0
	/* 0101 */
	for i, t := range text {
	    if i % 2 == 0 {
	        if t != '0' {
	            ret1++
	        }
	    }else {
	        if t != '1' {
	            ret1++
	        }
	    }
	}
	ret2 := 0
	/* 1010 */
	for i, t := range text {
	    if i % 2 == 0 {
	        if t != '1' {
	            ret2++
	        }
	    }else {
	        if t != '0' {
	            ret2++
	        }
	    }
	}
	fmt.Println(min(ret1,ret2))
}

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

Score : 300 points

Problem Statement

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

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

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

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

Constraints

1 \leq |S| \leq 10^5

S_i is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

000

Sample Output 1

1

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

Sample Input 2

10010010

Sample Output 2

3

Sample Input 3

0

Sample Output 3

0


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

var stdin = bufio.NewScanner(os.Stdin)
var rdr = bufio.NewReaderSize(os.Stdin,1000000)
func readLine() string{
	//長いトークンを読み込みたい場合
	buf := make([]byte,0,1000000)
	for {
		read,isPrefix,error := rdr.ReadLine()
		if error!= nil{
			panic(error)
		}
		buf = append(buf,read...)
		if !isPrefix{
			break
		}
	}
	return string(buf)
}

func Input_Str() string {
	//かんたんに読み込みたい場合
	stdin.Scan()
	stringInput := stdin.Text()
	out := strings.TrimSpace(stringInput)
	return out
}

func main(){
	stdin.Split(bufio.ScanWords)
	s := readLine()
	count_W:=0
	count_B:=0

	for i:=0;i<len(s);i++{
		if i%2==0{
			if s[i]=='0'{
				count_W++
			}else{
				count_B++
			}
		}else{
			if s[i]=='1'{
				count_W++
			}else{
				count_B++
			}
		}
	}

	if count_W < count_B{
		fmt.Println(count_W)
	}else{
		fmt.Println(count_B)
	}
}


package main
import (
    "fmt"
    "math"
)

var memo = make(map[int]int)

func main(){
    var N, K int
    var s string
    fmt.Scan(&N, &K, &s)
    fmt.Println(search(s, K))
}

func search(s string, K int) float64{
    ans, co := 0.0, 0.0
    for i:=0;i<len(s);i++{
        if s[i] == 48 {
            count := padding(s, K, i, co)
            ans = math.Max(count, ans)
            co, i = 0, i+memo[i]-1

        }else{
            co ++
        }
    }
    return math.Max(ans, co)
}

func padding(s string, K, index int, co float64) (float64){
    n :=  index
    // fmt.Println(index)
    for i, flag:= index, false; i < len(s) &&!(K == 0 &&s[i]== 48);i++{
        if memo[i] != 0{
            co +=float64(memo[i])
            K--
            continue
        }
        if s[i] == 49 && !flag{
            K--
            flag = true
            memo[n] = i - n
        }else if s[i] == 48 && flag{
            flag = false
            n = i
        }
        co ++
    }
    if s[len(s) -1] == 48{
        memo[n] = len(s) - n
    }
    return co
}

Score : 400 points

Problem Statement

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

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

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

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

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

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

Constraints

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

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

The length of the string S is N.

Each character of the string S is 0 or 1.

Input

Input is given from Standard Input in the following format:

N K
S

Output

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

Sample Input 1

5 1
00010

Sample Output 1

4

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

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

Sample Input 2

14 2
11101010110011

Sample Output 2

8

Sample Input 3

1 1
1

Sample Output 3

1

No directions are necessary.


package main

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

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

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

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

	return i
}

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

	return sc.Text()
}

func getRev(before byte) byte {
	if before == '0' {
		return '1'
	}
	return '0'
}

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

	n := scanInt(sc)
	k := scanInt(sc)
	s := scanStr(sc)

	// fmt.Printf("n = %+v\n", n)
	// fmt.Printf("k = %+v\n", k)
	// fmt.Printf("s = %+v\n", s)

	csum := make([]int, 0, len(s)+10)

	before := s[0]
	csum = append(csum, 1)
	for i := 1; i < n; i++ {
		if s[i] != before {
			csum = append(csum, csum[len(csum)-1]+1)
		} else {
			csum[len(csum)-1]++
		}
		before = s[i]
	}

	// fmt.Printf("csum = %+v\n", csum)

	max := 0
	rightIndexFunc := zeroRightIndex
	if s[0] != '0' {
		rightIndexFunc = oneRightIndex
	}
	leftIndexFunc := zeroLeftIndex
	if s[0] != '0' {
		leftIndexFunc = oneLeftIndex
	}
	for i := 0; i < len(csum); i += 2 {
		rightIndex := rightIndexFunc(i, k)
		var right int
		if rightIndex > len(csum)-1 {
			rightIndex = len(csum) - 1
		}
		right = csum[rightIndex]

		leftIndex := leftIndexFunc(i)
		var left int
		if leftIndex < 0 {
			leftIndex = -1
			left = 0
		} else {
			left = csum[leftIndex]
		}
		length := right - left
		// fmt.Printf("[%d](%d) - [%d](%d): %d\n", leftIndex, left, rightIndex, right, length)
		if length > max {
			max = length
		}
	}

	fmt.Printf("%d\n", max)
}

func zeroLeftIndex(i int) int {
	return i - 2
}

func oneLeftIndex(i int) int {
	return i - 1
}

func zeroRightIndex(i int, k int) int {
	return i + 2*k - 1
}

func oneRightIndex(i int, k int) int {
	return i + 2*k
}

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

	n := scanInt(sc)
	k := scanInt(sc)
	s := scanStr(sc)

	// fmt.Printf("n = %+v\n", n)
	// fmt.Printf("k = %+v\n", k)
	// fmt.Printf("s = %+v\n", s)

	flipCount := 0
	prev := s[0]
	max := 0
	length := 0
	left := 0
	right := 1

	// left move loop
	for left < n {
		// right move lop
		for right < n {
			// count 0 -> 1 or 1 -> 0
			if s[right] != prev {
				flipCount++
			}

			// memory prev
			prev = s[right]

			if s[left] == '0' {
				// right limit if 0 start
				if flipCount > 2*k-1 {
					break
				}
			} else {
				// right limit if 1 start
				if flipCount > 2*k {
					break
				}
			}
			right++
			// fmt.Printf("right++: left = %+v, right = %+v, length = %+v\n", left, right, right-left)
		}

		// update max
		length = right - left
		if length > max {
			max = length
			// fmt.Printf("  max changed: left = %+v, right = %+v, length = %+v\n", left, right, right-left)
		}
		// fmt.Printf("  left = %+v, right = %+v, length = %+v, flipCount = %+v\n", left, right, right-left, flipCount)

		// no more max length
		if right >= n {
			break
		}

		index := left
		left++
		// left move
		for left < right {
			if s[left] != s[index] {
				flipCount--
				break
			}
			left++
		}
		// fmt.Printf("  left++: left = %+v, right = %+v, length = %+v, flipCount = %+v\n", left, right, right-left, flipCount)
	}

	fmt.Printf("%d\n", max)
}

func main() {
	// cSum()
	scaleUp()
}


package main
import (
  "container/list"
  "fmt"
  "os"
)
func main() {
  var n,k,r,m int
  var s string
  var a []int
  fmt.Scan(&n,&k)
  fmt.Scan(&s)
  a = make([]int,n)
  r = 1
  if s[0:1] == "0" { r = -1 }
  a[0] = r
  p2n := list.New()
  n2p := list.New()
  for i:=1;i<n;i++ {
    if s[i:i+1] == s[i-1:i] {
      a[i] = a[i-1] + r
    } else {
      if r > 0 {
        p2n.PushBack(i-1)
      } else {
        n2p.PushBack(i-1)
      }
      r = -r
      a[i] = r
    }
  }
  if a[n-1] > 0 {
    p2n.PushBack(n-1)
  } else {
    n2p.PushBack(n-1)
  }
  if p2n.Len() == 0 || n2p.Len() == 0 {
    fmt.Println(abs(a[n-1]))
    os.Exit(0)
  }
  used_p2n := list.New()
  used_n2p := list.New()
  m = 0
  if p2n.Len() == n2p.Len() && a[n-1] > 0 ||
  p2n.Len() != n2p.Len() && a[n-1] < 0 {
    j,_ := n2p.Remove(n2p.Front()).(int)
    m -= a[j]
    k--
    used_n2p.PushBack(j)
  }
  j,_ := p2n.Remove(p2n.Front()).(int)
  m += a[j]
  used_p2n.PushBack(j)
  for c:=0;c<k;c++ {
    if p2n.Len() == 0 { break }
    x,_ := p2n.Remove(p2n.Front()).(int)
    m += a[x]
    used_p2n.PushBack(x)
    if n2p.Len() == 0 { break }
    y,_ := n2p.Remove(n2p.Front()).(int)
    m -= a[y]
    used_n2p.PushBack(y)
  }
  for {
    if p2n.Len() == 0 { break }
    x,_ := p2n.Remove(p2n.Front()).(int)
    m += a[x]
    used_p2n.PushBack(x)
    if n2p.Len() == 0 { break }
    y,_ := n2p.Remove(n2p.Front()).(int)
    m -= a[y]
    used_n2p.PushBack(y)
    p,_ := used_p2n.Remove(used_p2n.Front()).(int)
    q,_ := used_n2p.Remove(used_n2p.Front()).(int)
    m += -a[p]+a[q]
  }
  fmt.Println(m)
}
func abs(n int) int {
  if n < 0 { return -n }
  return n
}


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) nextFloat() float64 {
	f, e := strconv.ParseFloat(s.nextStr(), 64)
	if e != nil {
		panic(e)
	}
	return f
}

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()
	A := sc.nextIntSlice(5)
	k := sc.nextInt()
	ok := true
	for i := 0; i < 5; i++ {
		for j := i + 1; j < 5; j++ {
			if abs(A[i]-A[j]) > k {
				ok = false
			}
		}
	}
	if ok {
		fmt.Println("Yay!")
	} else {
		fmt.Println(":(")
	}
}

Score: 100 points

Problem Statement

In AtCoder city, there are five antennas standing in a straight line. They are called Antenna A, B, C, D and E from west to east, and their coordinates are a, b, c, d and e, respectively.

Two antennas can communicate directly if the distance between them is k or less, and they cannot if the distance is greater than k.

Determine if there exists a pair of antennas that cannot communicate directly.

Here, assume that the distance between two antennas at coordinates p and q (p < q) is q - p.

Constraints

a, b, c, d, e and k are integers between 0 and 123 (inclusive).

a < b < c < d < e

Input

Input is given from Standard Input in the following format:

a
b
c
d
e
k

Output

Print :( if there exists a pair of antennas that cannot communicate directly, and print Yay! if there is no such pair.

Sample Input 1

1
2
4
8
9
15

Sample Output 1

Yay!

In this case, there is no pair of antennas that cannot communicate directly, because:

the distance between A and B is 2 - 1 = 1

the distance between A and C is 4 - 1 = 3

the distance between A and D is 8 - 1 = 7

the distance between A and E is 9 - 1 = 8

the distance between B and C is 4 - 2 = 2

the distance between B and D is 8 - 2 = 6

the distance between B and E is 9 - 2 = 7

the distance between C and D is 8 - 4 = 4

the distance between C and E is 9 - 4 = 5

the distance between D and E is 9 - 8 = 1

and none of them is greater than 15. Thus, the correct output is Yay!.

Sample Input 2

15
18
26
35
36
18

Sample Output 2

:(

In this case, the distance between antennas A and D is 35 - 15 = 20 and exceeds 18, so they cannot communicate directly.
Thus, the correct output is :(.


package main

import (
  "fmt"
)

func main() {
  var a, b, c, d, e, k int
  fmt.Scan(&a, &b, &c, &d, &e, &k)
  if e-a > k {
    fmt.Println(":(")
    return
  }
  fmt.Println("Yay!")
}


package main

import (
	"fmt"
	"sort"
)

var (
	a []int
	k int
)

func main() {
	a = make([]int, 5)
	fmt.Scan(&a[0])
	fmt.Scan(&a[1])
	fmt.Scan(&a[2])
	fmt.Scan(&a[3])
	fmt.Scan(&a[4])
	fmt.Scan(&k)

	sort.Ints(a)
	if a[4] - a[0] > k {
		fmt.Println(":(")
	} else {
		fmt.Println("Yay!")
	}
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

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

func getRuneAt(s string, i int) rune {
	rs := []rune(s)
	return rs[i]
}

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

	var val []int
	val = make([]int, 5)
	for index := 0; index < 5; index++ {
		val[index] = nextInt()
	}
	k := nextInt()

	for i := 0; i < 4; i++ {
		for j := i + 1; j < 5; j++ {
			if !canCommunicate(val[i], val[j], k) {
				fmt.Print(":(")
				return
			}
		}
	}
	fmt.Print("Yay!")
}

func canCommunicate(a int, b int, waveRange int) bool {
	return (b - a) <= waveRange
}


package main

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

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

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

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

func debug(a ...interface{}) { fmt.Fprintln(os.Stderr, a...) }

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

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

func main() {
	defer wr.Flush()
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 10000), 1001001)

	a := scanInt()-1
	b := scanInt()-1
	c := scanInt()-1
	d := scanInt()-1
	e := scanInt()-1

	t := min(a%10,min(b%10,min(c%10,min(d%10,e%10))))+1

	a += 10
	b += 10
	c += 10
	d += 10
	e += 10

	a /= 10
	b /= 10
	c /= 10
	d /= 10
	e /= 10

	fmt.Fprintln(wr, (a+b+c+d+e)*10-10+t)
}

Score: 200 points

Problem Statement

The restaurant AtCoder serves the following five dishes:

ABC Don (rice bowl): takes A minutes to serve.

ARC Curry: takes B minutes to serve.

AGC Pasta: takes C minutes to serve.

APC Ramen: takes D minutes to serve.

ATC Hanbagu (hamburger patty): takes E minutes to serve.

Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.

This restaurant has the following rules on orders:

An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).

Only one dish can be ordered at a time.

No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.

E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.

Here, he can order the dishes in any order he likes, and he can place an order already at time 0.

Constraints

A, B, C, D and E are integers between 1 and 123 (inclusive).

Input

Input is given from Standard Input in the following format:

A
B
C
D
E

Output

Print the earliest possible time for the last dish to be delivered, as an integer.

Sample Input 1

29
20
7
35
120

Sample Output 1

215

If we decide to order the dishes in the order ABC Don, ARC Curry, AGC Pasta, ATC Hanbagu, APC Ramen, the earliest possible time for each order is as follows:

Order ABC Don at time 0, which will be delivered at time 29.

Order ARC Curry at time 30, which will be delivered at time 50.

Order AGC Pasta at time 50, which will be delivered at time 57.

Order ATC Hanbagu at time 60, which will be delivered at time 180.

Order APC Ramen at time 180, which will be delivered at time 215.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 2

101
86
119
108
57

Sample Output 2

481

If we decide to order the dishes in the order AGC Pasta, ARC Curry, ATC Hanbagu, APC Ramen, ABC Don, the earliest possible time for each order is as follows:

Order AGC Pasta at time 0, which will be delivered at time 119.

Order ARC Curry at time 120, which will be delivered at time 206.

Order ATC Hanbagu at time 210, which will be delivered at time 267.

Order APC Ramen at time 270, which will be delivered at time 378.

Order ABC Don at time 380, which will be delivered at time 481.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 3

123
123
123
123
123

Sample Output 3

643

This is the largest valid case.


package main

import (
	"fmt"
	"strconv"
)

func main() {
	var dishes = [5]string{}
	fmt.Scan(&dishes[0])
	fmt.Scan(&dishes[1])
	fmt.Scan(&dishes[2])
	fmt.Scan(&dishes[3])
	fmt.Scan(&dishes[4])

	res := 0
	for _, dish := range dishes {
		dishNum, err := strconv.Atoi(dish)
		if err != nil {
			return
		}
		res = res + dishNum
	}

	fmt.Println(strconv.Itoa(res))
	return
}


package main

import "fmt"

func main() {
	var n, a, b, c, d, e int
	result := 0
	fmt.Scanf("%d", &n)
	fmt.Scanf("%d", &a)
	fmt.Scanf("%d", &b)
	fmt.Scanf("%d", &c)
	fmt.Scanf("%d", &d)
	fmt.Scanf("%d", &e)
  	basic := a
	canTrasnportNum := &[5]int{a, b, c, d, e}
	for _, current := range canTrasnportNum {
		if current < basic {
			basic = current
		}
	}
    if basic >= n {
		result = 5
    }else{
  	  result = len(canTrasnportNum)
      if (n - basic) / basic == 0 {
        result = result + 1
      }else{
        result = result + (n - basic) / basic
      }
      if (n-basic)/basic != 0 {
          result = result + 1
      }
    }
    fmt.Printf("%d", result)
}

Score: 300 points

Problem Statement

In 2028 and after a continuous growth, AtCoder Inc. finally built an empire with six cities (City 1, 2, 3, 4, 5, 6)!

There are five means of transport in this empire:

Train: travels from City 1 to 2 in one minute. A train can occupy at most A people.

Bus: travels from City 2 to 3 in one minute. A bus can occupy at most B people.

Taxi: travels from City 3 to 4 in one minute. A taxi can occupy at most C people.

Airplane: travels from City 4 to 5 in one minute. An airplane can occupy at most D people.

Ship: travels from City 5 to 6 in one minute. A ship can occupy at most E people.

For each of them, one vehicle leaves the city at each integer time (time 0, 1, 2, ...).

There is a group of N people at City 1, and they all want to go to City 6.

At least how long does it take for all of them to reach there?
You can ignore the time needed to transfer.

Constraints

1 \leq N, A, B, C, D, E \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A
B
C
D
E

Output

Print the minimum time required for all of the people to reach City 6, in minutes.

Sample Input 1

5
3
2
4
3
5

Sample Output 1

7

One possible way to travel is as follows.
First, there are N = 5 people at City 1, as shown in the following image:

In the first minute, three people travels from City 1 to City 2 by train. Note that a train can only occupy at most three people.

In the second minute, the remaining two people travels from City 1 to City 2 by train, and two of the three people who were already at City 2 travels to City 3 by bus. Note that a bus can only occupy at most two people.

In the third minute, two people travels from City 2 to City 3 by train, and another two people travels from City 3 to City 4 by taxi.

From then on, if they continue traveling without stopping until they reach City 6, all of them can reach there in seven minutes.

There is no way for them to reach City 6 in 6 minutes or less.

Sample Input 2

10
123
123
123
123
123

Sample Output 2

5

All kinds of vehicles can occupy N = 10 people at a time.
Thus, if they continue traveling without stopping until they reach City 6, all of them can reach there in five minutes.

Sample Input 3

10000000007
2
3
5
7
11

Sample Output 3

5000000008

Note that the input or output may not fit into a 32-bit integer type.


package main

import (
	"fmt"
	"math"
)

func main() {
	var n, min, x int
	fmt.Scan(&n, &min)
	for i := 1; i < 5; i++ {
		fmt.Scan(&x)
		if x < min {
			min = x
		}
	}
	fmt.Println(int(math.Ceil(float64(n)/float64(min))) + 4)
}


package main

import (
	"fmt"
	"math"
)

func read() []int64 {
	var tmp int64
	list := make([]int64, 6)
	for i := 0; i < 6; i++ {
		fmt.Scan(&tmp)
		list[i] = tmp
	}
	return list
}

func fetchMinval(list []int64) (min int64, idx int) {
	min = math.MaxInt64
	for i := 0; i < len(list)-1; i++ {
		if min > list[i] {
			min = list[i]
			idx = i
		}
	}
	return
}

func main() {
	list := read()
	min, idx := fetchMinval(list[1:])
	if idx == 0 {
		div := float64(list[0]) / float64(min)
		colSize := int64(div)
		lineSize := int64(len(list[1:]))
		fmt.Println(colSize + lineSize - 1)
	} else {
		colSize := int64(math.Ceil(float64(list[0]) / float64(min)))
		lineSize := int64(len(list[1:]) - idx)
		fmt.Println(colSize + lineSize)
	}
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

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

func getRuneAt(s string, i int) rune {
	rs := []rune(s)
	return rs[i]
}

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

	n := nextInt()

	var val []int
	val = make([]int, 5)
	for index := 0; index < 5; index++ {
		val[index] = nextInt()
	}
	val = sort.IntSlice(val)
	if val[0] >= n {
		fmt.Print(5)
		return
	}

	if n%val[0] == 0 {
		fmt.Print(n/val[0] + 5)
	} else {
		fmt.Print(n/val[0] + 6)
	}

}


package main

import (
    "fmt"
)

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

    min := int(1e15)
    for i := 0; i < 5; i++ {
        var t int
        fmt.Scan(&t)
        if t < min {
            min = t
        }
    }
    r := int(n / min)
    if n%min > 0 {
        r += 1
    }
    r += 4

    fmt.Println(r)
}


package main

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

func main() {
	var x, y, z, k int
	fmt.Scan(&x, &y, &z, &k)

	scanner := bufio.NewScanner(os.Stdin)
	as := strToInt64Slice(scanLine(scanner))
	bs := strToInt64Slice(scanLine(scanner))
	cs := strToInt64Slice(scanLine(scanner))

	sumList := calcEachSum(as, bs, cs, x, y, z)
	sortDescInt64Slice(sumList)

	for i := 0; i < k; i++ {
		fmt.Printf("%d\n", sumList[i]);
	}
}

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

func strToInt64Slice(line string) []int64 {
	strSlice := strings.Split(line, " ")

	var intSlice []int64
	for _, str := range strSlice {
		intValue, _ := strconv.ParseInt(str, 10, 64)
		intSlice = append(intSlice, intValue)
	}

	return intSlice
}

func sortDescInt64Slice(ints []int64) {
	sort.Sort(sort.Reverse(Int64Slice(ints)))
}

func calcEachSum(as, bs, cs []int64, x, y, z int) []int64 {
	var sumList []int64
	for i := 0; i < x; i++ {
		for j := 0; j < y; j++ {
			for k := 0; k < z; k++ {
				sumList = append(sumList, as[i] + bs[j] + cs[k])
			}
		}
	}
	return sumList
}

type Int64Slice []int64

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

Score: 400 points

Problem Statement

The Patisserie AtCoder sells cakes with number-shaped candles.
There are X, Y and Z kinds of cakes with 1-shaped, 2-shaped and 3-shaped candles, respectively.
Each cake has an integer value called deliciousness, as follows:

The deliciousness of the cakes with 1-shaped candles are A_1, A_2, ..., A_X.

The deliciousness of the cakes with 2-shaped candles are B_1, B_2, ..., B_Y.

The deliciousness of the cakes with 3-shaped candles are C_1, C_2, ..., C_Z.

Takahashi decides to buy three cakes, one for each of the three shapes of the candles, to celebrate ABC 123.

There are X \times Y \times Z such ways to choose three cakes.

We will arrange these X \times Y \times Z ways in descending order of the sum of the deliciousness of the cakes.

Print the sums of the deliciousness of the cakes for the first, second, ..., K-th ways in this list.

Constraints

1 \leq X \leq 1 \ 000

1 \leq Y \leq 1 \ 000

1 \leq Z \leq 1 \ 000

1 \leq K \leq \min(3 \ 000, X \times Y \times Z)

1 \leq A_i \leq 10 \ 000 \ 000 \ 000

1 \leq B_i \leq 10 \ 000 \ 000 \ 000

1 \leq C_i \leq 10 \ 000 \ 000 \ 000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y Z K
A_1 \ A_2 \ A_3 \ ... \ A_X
B_1 \ B_2 \ B_3 \ ... \ B_Y
C_1 \ C_2 \ C_3 \ ... \ C_Z

Output

Print K lines. The i-th line should contain the i-th value stated in the problem statement.

Sample Input 1

2 2 2 8
4 6
1 5
3 8

Sample Output 1

19
17
15
14
13
12
10
8

There are 2 \times 2 \times 2 = 8 ways to choose three cakes, as shown below in descending order of the sum of the deliciousness of the cakes:

(A_2, B_2, C_2): 6 + 5 + 8 = 19

(A_1, B_2, C_2): 4 + 5 + 8 = 17

(A_2, B_1, C_2): 6 + 1 + 8 = 15

(A_2, B_2, C_1): 6 + 5 + 3 = 14

(A_1, B_1, C_2): 4 + 1 + 8 = 13

(A_1, B_2, C_1): 4 + 5 + 3 = 12

(A_2, B_1, C_1): 6 + 1 + 3 = 10

(A_1, B_1, C_1): 4 + 1 + 3 = 8

Sample Input 2

3 3 3 5
1 10 100
2 20 200
1 10 100

Sample Output 2

400
310
310
301
301

There may be multiple combinations of cakes with the same sum of the deliciousness. For example, in this test case, the sum of A_1, B_3, C_3 and the sum of A_3, B_3, C_1 are both 301.
However, they are different ways of choosing cakes, so 301 occurs twice in the output.

Sample Input 3

10 10 10 20
7467038376 5724769290 292794712 2843504496 3381970101 8402252870 249131806 6310293640 6690322794 6082257488
1873977926 2576529623 1144842195 1379118507 6003234687 4925540914 3902539811 3326692703 484657758 2877436338
4975681328 8974383988 2882263257 7690203955 514305523 6679823484 4263279310 585966808 3752282379 620585736

Sample Output 3

23379871545
22444657051
22302177772
22095691512
21667941469
21366963278
21287912315
21279176669
21160477018
21085311041
21059876163
21017997739
20703329561
20702387965
20590247696
20383761436
20343962175
20254073196
20210218542
20150096547

Note that the input or output may not fit into a 32-bit integer type.


package main

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

func main() {
	_ = nextInt()
	s := nextLine()
	r, b := 0, 0
	for _, v := range s {
		if v == 'R' {
			r++
		} else {
			b++
		}
	}
	if r > b {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
}

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

func gcd(a, b int64) int64 {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

const size = 1000000

var reader = bufio.NewReaderSize(os.Stdin, size)

func nextLine() string {
	var line, buffer []byte
	isPrefix := true
	var err error
	for isPrefix {
		line, isPrefix, err = reader.ReadLine()
		if err != nil {
			panic(err)
		}
		buffer = append(buffer, line...)
	}
	return string(buffer)
}
func nextStringArray() []string {
	return strings.Split(nextLine(), " ")
}
func nextInt() int {
	n, _ := strconv.Atoi(nextLine())
	return n
}

func nextIntArray() []int {
	s := strings.Split(nextLine(), " ")
	n := len(s)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i], _ = strconv.Atoi(s[i])
	}
	return a
}

func min(i, j int) int {
	if i > j {
		return j
	}
	return i
}

func max(i, j int) int {
	if i < j {
		return j
	}
	return i
}

Score : 200 points

Problem Statement

There are N people numbered 1 to N. Each person wears a red hat or a blue hat.

You are given a string s representing the colors of the people. Person i wears a red hat if s_i is R, and a blue hat if s_i is B.

Determine if there are more people wearing a red hat than people wearing a blue hat.

Constraints

1 \leq N \leq 100

|s| = N

s_i is R or B.

Input

Input is given from Standard Input in the following format:

N
s

Output

If there are more people wearing a red hat than there are people wearing a blue hat, print Yes; otherwise, print No.

Sample Input 1

4
RRBR

Sample Output 1

Yes

There are three people wearing a red hat, and one person wearing a blue hat.

Since there are more people wearing a red hat than people wearing a blue hat, the answer is Yes.

Sample Input 2

4
BRBR

Sample Output 2

No

There are two people wearing a red hat, and two people wearing a blue hat.

Since there are as many people wearing a red hat as people wearing a blue hat, the answer is No.


package main

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

// {{{
// source: https://github.com/raahii/algo
func MaxInts(nums ...int) int {
	var maxVal int
	for i, e := range nums {
		if i == 0 || e > maxVal {
			maxVal = e
		}
	}
	return maxVal
}

func MaxIntsWithIdx(nums ...int) (int, int) {
	var maxIdx, maxVal int
	for i, e := range nums {
		if i == 0 || e > maxVal {
			maxIdx = i
			maxVal = e
		}
	}
	return maxVal, maxIdx
}

func MinInts(nums ...int) int {
	var minVal int
	for i, e := range nums {
		if i == 0 || e < minVal {
			minVal = e
		}
	}
	return minVal
}

func MinIntsWithIdx(nums ...int) (int, int) {
	var minIdx, minVal int
	for i, e := range nums {
		if i == 0 || e < minVal {
			minIdx = i
			minVal = e
		}
	}
	return minVal, minIdx
}

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

func SumInts2d(mat [][]int) int {
	s := 0
	for _, nums := range mat {
		for _, v := range nums {
			s += v
		}
	}
	return s
}

func ReverseInts(nums []int) []int {
	rnums := make([]int, len(nums))
	for i := 0; i < len(nums); i++ {
		rnums[len(nums)-1-i] = nums[i]
	}
	return rnums
}

func ExtendInts(nums1 []int, nums2 []int) []int {
	for _, v := range nums2 {
		nums1 = append(nums1, v)
	}
	return nums1
}

func Ints2d(n_rows, n_cols int) [][]int {
	ints := make([][]int, n_rows)
	for i := 0; i < n_rows; i++ {
		ints[i] = make([]int, n_cols)
	}
	return ints
}

func StrInts2d(mat [][]int) string {
	str := ""
	for i := 0; i < len(mat); i++ {
		str += fmt.Sprintf("[%d", mat[i][0])
		for j := 1; j < len(mat[0]); j++ {
			str += fmt.Sprintf(" %d", mat[i][j])
		}
		str += "]"
		if i != len(mat)-1 {
			str += "\n"
		}
	}
	return str
}

func MemsetInts1d(nums []int, val int) {
	for i := range nums {
		nums[i] = val
	}
}

func MemsetInts2d(nums [][]int, val int) {
	for i := range nums {
		for j := range nums[i] {
			nums[i][j] = val
		}
	}
}

func ContainsInt(nums []int, num int) bool {
	sort.Ints(nums)

	s, e := 0, len(nums)
	for {
		if s >= e {
			break
		}

		m := (e + s) / 2
		if nums[m] == num {
			return true
		} else if num > nums[m] {
			s = m + 1
		} else {
			e = m
		}
	}

	return false
}

func UniqInts(nums []int) []int {
	m := make(map[int]struct{}, len(nums))
	for _, n := range nums {
		m[n] = struct{}{}
	}

	unums := make([]int, 0, len(nums))
	for k, _ := range m {
		unums = append(unums, k)
	}

	return unums
}

func ReadInt(f *os.File) int {
	var n int
	fmt.Fscanf(f, "%d", &n)
	return n
}

func ReadInts(f *os.File, n int) []int {
	nums := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(f, "%d", &nums[i])
	}
	return nums
}

func ScanInts(f *os.File, vars ...*int) {
	for i := 0; i < len(vars); i++ {
		fmt.Fscanf(f, "%d", vars[i])
	}
}

func ReadLine(f *os.File) string {
	var str string
	fmt.Fscanf(f, "%s", &str)

	return str
}

func ReadLines(f *os.File, n int) []string {
	lines := make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(f, "%s", &lines[i])
	}

	return lines
}

func ReadWords(f *os.File, n int) []string {
	strs := make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(f, "%s", &strs[i])
	}
	return strs
}

func Pow(a, n int) int {
	c := 1
	for i := 0; i < n; i++ {
		c *= a
	}
	return c
}

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

	return n
}

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

func BinComb(n int, c chan []int) {
	n2 := 1 << uint(n)

	for i := 0; i < n2; i++ {
		pat := make([]int, n)
		for j := 0; j < n; j++ {
			pat[j] = i >> uint(j) & 1
		}
		c <- pat
	}
	close(c)
}

// }}}

type Pair struct {
	first  string
	second string
}

func simulate(s string, qs []Pair, pos int) int {
	for _, query := range qs {
		if query.first != string(s[pos]) {
			continue
		}
		if query.second == "R" {
			pos++
		} else {
			pos--
		}

		if pos == -1 {
			return -1
		} else if pos == len(s) {
			return 1
		}
	}
	return 0
}

func solve(s string, qs []Pair) int {
	l := sort.Search(len(s), func(i int) bool { return simulate(s, qs, i) == 0 })
	r := sort.Search(len(s), func(i int) bool { return simulate(s, qs, i) == 1 })

	return r - l
}

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

	var s string
	fmt.Scan(&s)

	qs := make([]Pair, q)
	for i := 0; i < q; i++ {
		fmt.Scan(&qs[i].first, &qs[i].second)
	}

	fmt.Println(solve(s, qs))
}

Score : 500 points

Problem Statement

There are N squares numbered 1 to N from left to right.
Each square has a character written on it, and Square i has a letter s_i. Besides, there is initially one golem on each square.

Snuke cast Q spells to move the golems.

The i-th spell consisted of two characters t_i and d_i, where d_i is L or R.
When Snuke cast this spell, for each square with the character t_i, all golems on that square moved to the square adjacent to the left if d_i is L, and moved to the square adjacent to the right if d_i is R.

However, when a golem tried to move left from Square 1 or move right from Square N, it disappeared.

Find the number of golems remaining after Snuke cast the Q spells.

Constraints

1 \leq N,Q \leq 2 \times 10^{5}

|s| = N

s_i and t_i are uppercase English letters.

d_i is L or R.

Input

Input is given from Standard Input in the following format:

N Q
s
t_1 d_1
\vdots
t_{Q} d_Q

Output

Print the answer.

Sample Input 1

3 4
ABC
A L
B L
B R
A R

Sample Output 1

2

Initially, there is one golem on each square.

In the first spell, the golem on Square 1 tries to move left and disappears.

In the second spell, the golem on Square 2 moves left.

In the third spell, no golem moves.

In the fourth spell, the golem on Square 1 moves right.

After the four spells are cast, there is one golem on Square 2 and one golem on Square 3, for a total of two golems remaining.

Sample Input 2

8 3
AABCBDBA
A L
B R
A R

Sample Output 2

5

After the three spells are cast, there is one golem on Square 2, two golems on Square 4 and two golems on Square 6, for a total of five golems remaining.

Note that a single spell may move multiple golems.

Sample Input 3

10 15
SNCZWRCEWB
B R
R R
E R
W R
Z L
S R
Q L
W L
B R
C L
A L
N L
E R
Z L
S L

Sample Output 3

3


package main

import (
	"fmt"
)

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

	switch b {
	case "A":
		fmt.Println("T")
	case "T":
		fmt.Println("A")
	case "C":
		fmt.Println("G")
	case "G":
		fmt.Println("C")
	default:
	}
}

Score : 100 points

Problem Statement

On the Planet AtCoder, there are four types of bases: A, C, G and T. A bonds with T, and C bonds with G.

You are given a letter b as input, which is A, C, G or T. Write a program that prints the letter representing the base that bonds with the base b.

Constraints

b is one of the letters A, C, G and T.

Input

Input is given from Standard Input in the following format:

b

Output

Print the letter representing the base that bonds with the base b.

Sample Input 1

A

Sample Output 1

T

Sample Input 2

G

Sample Output 2

C


package main

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

var (
	b string
)

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	b = scanner.Text()
	cur := ""
	buff := bytes.NewBufferString(cur)
	max := 0

	for i := 0; i < len(b); i++ {
		if b[i] == 'A' || b[i] == 'C' || b[i] == 'G' || b[i] == 'T' {
			buff.WriteByte(b[i])
		} else {
			if max < buff.Len() {
				max = buff.Len()
			}
		}
	}

	fmt.Println(max)
}

Score : 200 points

Problem Statement

You are given a string S consisting of uppercase English letters. Find the length of the longest ACGT string that is a substring (see Notes) of S.

Here, a ACGT string is a string that contains no characters other than A, C, G and T.

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

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

Each character in S is an uppercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

Print the length of the longest ACGT string that is a substring of S.

Sample Input 1

ATCODER

Sample Output 1

3

Among the ACGT strings that are substrings of ATCODER, the longest one is ATC.

Sample Input 2

HATAGAYA

Sample Output 2

5

Among the ACGT strings that are substrings of HATAGAYA, the longest one is ATAGA.

Sample Input 3

SHINJUKU

Sample Output 3

0

Among the ACGT strings that are substrings of SHINJUKU, the longest one is (the empty string).


package main

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

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

func nextLine() []string {
	line := readLine()
	return strings.Split(line, " ")
}

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

func main() {
	//sc.Split(bufio.ScanLines)
	tmp := nextLine()
	Q, _ := strconv.Atoi(tmp[1])

	S := readLine()

	fmt.Println(Q)
	fmt.Println(S)
	for i := 0; i < Q; i++ {
		tmp = nextLine()
		fmt.Println(tmp)
		// l, _ := strconv.Atoi(tmp[0])
		// r, _ := strconv.Atoi(tmp[1])
		// subS := S[l-1 : r]
		// fmt.Println(strings.Count(subS, "AC"))
	}
}

Score : 300 points

Problem Statement

You are given a string S of length N consisting of A, C, G and T. Answer the following Q queries:

Query i (1 \leq i \leq Q): You will be given integers l_i and r_i (1 \leq l_i < r_i \leq N). Consider the substring of S starting at index l_i and ending at index r_i (both inclusive). In this string, how many times does AC occurs as a substring?

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

2 \leq N \leq 10^5

1 \leq Q \leq 10^5

S is a string of length N.

Each character in S is A, C, G or T.

1 \leq l_i < r_i \leq N

Input

Input is given from Standard Input in the following format:

N Q
S
l_1 r_1
:
l_Q r_Q

Output

Print Q lines. The i-th line should contain the answer to the i-th query.

Sample Input 1

8 3
ACACTACG
3 7
2 3
1 8

Sample Output 1

2
0
3

Query 1: the substring of S starting at index 3 and ending at index 7 is ACTAC. In this string, AC occurs twice as a substring.

Query 2: the substring of S starting at index 2 and ending at index 3 is CA. In this string, AC occurs zero times as a substring.

Query 3: the substring of S starting at index 1 and ending at index 8 is ACACTACG. In this string, AC occurs three times as a substring.


package main

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

var sc = bufio.NewScanner(os.Stdin)

func nextLine() []string {
	sc.Scan()
	tmp := strings.Split(sc.Text(), " ")
	if len(tmp) < 2 {
		tmp = strings.Split(sc.Text(), "	")
	}
	return tmp
}

func main() {
	sc.Split(bufio.ScanLines)
	tmp := nextLine()
	Q, _ := strconv.ParseInt(tmp[1], 10, 64)

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

	for i := int64(0); i < Q; i++ {
		subS := ""
		tmp = nextLine()
		if len(tmp) < 1 {
			panic("none")
		} else if len(tmp) < 2 {
			subS = S
		} else {
			l, _ := strconv.ParseInt(tmp[0], 10, 64)
			r, _ := strconv.ParseInt(tmp[1], 10, 64)
			subS = S[l-1 : r]
		}
		fmt.Println(strings.Count(subS, "AC"))
	}
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

func nextLine() []string {
	sc.Scan()
	tmp := strings.Split(sc.Text(), " ")
	if len(tmp) < 2 {
		tmp = strings.Split(sc.Text(), "	")
	}
	return tmp
}

func main() {
	tmp := nextLine()
	Q, _ := strconv.ParseInt(tmp[1], 10, 64)

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

	for i := int64(0); i < Q; i++ {
		subS := ""
		tmp = nextLine()
		if len(tmp) < 1 {
			panic("none")
		} else if len(tmp) < 2 {
			subS = S
		} else {
			l, _ := strconv.ParseInt(tmp[0], 10, 64)
			r, _ := strconv.ParseInt(tmp[1], 10, 64)
			subS = S[l-1 : r]
		}
		fmt.Println(strings.Count(subS, "AC"))
	}
}


package main

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

var (
	BufferSize = 7 + 100000 + (7+1+7)*100000 + 1
	Pattern    = "AC"
)

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

	return sc.Text()
}

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

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

	return i
}

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

	n := scanInt(sc)
	q := scanInt(sc)
	s := scanStr(sc)

	targetIndex := make([]int, 100001)
	for i := 0; i < n; i++ {
		target := string(s[i])
		if target == "A" {
			if i+1 > n {
				break
			}
			if next := string(s[i+1]); next == "C" {
				targetIndex[i] = 1
				i++
			}
		}
	}

	for i := 0; i < q; i++ {
		count := 0
		l := scanInt(sc)
		r := scanInt(sc)
		if r-l < 2 {
			// fmt.Printf("%d\n", 0)
		}
		for j := 0; j < len(targetIndex); j++ {
			count += targetIndex[j]
		}
		// fmt.Printf("%d\n", count)
	}
}

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

	n := scanInt(sc)
	q := scanInt(sc)
	s := scanStr(sc)

	targetIndex := make([]int, 0, 500001)
	for i := 0; i < n; i++ {
		target := string(s[i])
		if target == "A" {
			if i+1 > n {
				break
			}
			if next := string(s[i+1]); next == "C" {
				targetIndex = append(targetIndex, i)
				i++
			}
		}
	}

	for i := 0; i < q; i++ {
		count := 0
		l := scanInt(sc)
		r := scanInt(sc)
		if r-l < 2 {
			// fmt.Printf("%d\n", 0)
		}
		for j := 0; j < len(targetIndex); j++ {
			if l-1 <= targetIndex[j] && targetIndex[j]+1 <= r-1 {
				count++
			}
		}
		// fmt.Printf("%d\n", count)
	}
}

func main() {
	// compare()
	count()
}


package main

import (
	"fmt"
)

func main() {

	var H, W, h, w int
	fmt.Scan(&H, &W, &h, &w)
	fmt.Println((H - h) * (W - w))
}

Score : 100 points

Problem Statement

There are H rows and W columns of white square cells.

You will choose h of the rows and w of the columns, and paint all of the cells contained in those rows or columns.

How many white cells will remain?

It can be proved that this count does not depend on what rows and columns are chosen.

Constraints

All values in input are integers.

1 \leq H, W \leq 20

1 \leq h \leq H

1 \leq w \leq W

Input

Input is given from Standard Input in the following format:

H W
h w

Output

Print the number of white cells that will remain.

Sample Input 1

3 2
2 1

Sample Output 1

1

There are 3 rows and 2 columns of cells. When two rows and one column are chosen and painted in black, there is always one white cell that remains.

Sample Input 2

5 5
2 3

Sample Output 2

6

Sample Input 3

2 4
2 4

Sample Output 3

0


package main

import "fmt"

func main() {
	var H, W, h, w int
	fmt.Scan(&H, &W, &h, &w)

	white := H * W
	black := h * W
	black += w*H - (h * w)

	fmt.Println(white - black)
}


package main

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

)

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

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

func NewScannerEx(stdin io.Reader) *ReaderEx {
	var this ReaderEx
	var idx int
	this.baseScanner = bufio.NewScanner(stdin)
	this.baseScanner.Buffer(make([]byte, 0), 1E+11)
	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) Scan() (ok bool) {
	ok = me.baseScanner.Scan()
	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 {
			panic(err)
		}
	}()

	return n
}

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

type StringArray []string

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

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

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

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

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

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

type factType struct {
	prime int
	count int
}

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

	for i := 2; i*i <= n; i++ {
		if n%i == 0 {
			fa := factType{prime: i}
			for n%fa.prime == 0 {
				n /= fa.prime
				fa.count++
			}
			facts = append(facts, fa)
		}
	}
	if n > 1 {
		facts = append(facts, factType{prime: n, count: 1})
	}
	return facts
}

type line struct {
	aYen int
	bHon int
}

func min(v int, vs ...int) int {
	for _, vi := range vs {
		if vi < v {
			v = vi
		}
	}
	return v
}

type lineSorter []*line

func (a lineSorter) Len() int           { return len(a) }
func (a lineSorter) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a lineSorter) Less(i, j int) bool { return a[i].aYen < a[j].aYen }
func solve(stdin io.Reader, stdout io.Writer) {
	r := NewScannerEx(stdin)
	r.ScanAndSplit()
	n, m := r.nextInt(), r.nextInt()

	lines := make([]*line, n)
	for i := 0; i < n; i++ {
		r.ScanAndSplit()
		lines[i] = &line{aYen: r.nextInt(), bHon: r.nextInt()}
	}

	sort.Sort(lineSorter(lines))

	ans := 0
	for _, l := range lines {
		if m <= 0 {
			break
		}
		w := min(m, l.bHon)
		m -= w
		ans += w * l.aYen
	}
	fmt.Fprintln(stdout, ans)
}

Score : 300 points

Problem Statement

Hearing that energy drinks increase rating in those sites, Takahashi decides to buy up M cans of energy drinks.

There are N stores that sell energy drinks. In the i-th store, he can buy at most B_i cans of energy drinks for A_i yen (the currency of Japan) each.

What is the minimum amount of money with which he can buy M cans of energy drinks?

It is guaranteed that, in the given inputs, a sufficient amount of money can always buy M cans of energy drinks.

Constraints

All values in input are integers.

1 \leq N, M \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^5

B_1 + ... + B_N \geq M

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 minimum amount of money with which Takahashi can buy M cans of energy drinks.

Sample Input 1

2 5
4 9
2 4

Sample Output 1

12

With 12 yen, we can buy one drink at the first store and four drinks at the second store, for the total of five drinks. However, we cannot buy 5 drinks with 11 yen or less.

Sample Input 2

4 30
6 18
2 5
3 10
7 9

Sample Output 2

130

Sample Input 3

1 100000
1000000000 100000

Sample Output 3

100000000000000

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


package main

import (
	"fmt"
	"sort"
)

type shop struct {
	a, b int
}

type byPrice []shop

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

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

	sort.Sort(byPrice(s))

	c := 0
	for i := 0; i < n; i++ {
		if s[i].b >= m {
			c += s[i].a * m
			fmt.Println(c)
			return
		}
		m -= s[i].b
		c += s[i].a * s[i].b
	}
}


// https://atcoder.jp/contests/abc120/tasks/abc120_c

package main

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

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

	return x
}

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

	chars := []rune(S)

	zeroCt := 0
	for _, ch := range chars {
		if ch == '0' {
			zeroCt++
		}
	}

	res := len(chars) - abs(len(chars)-2*zeroCt)
	io.Println(res)
}

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

/* IO Helpers */

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

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

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

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

	var buffer bytes.Buffer

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

	return buffer.String()
}

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

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

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

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

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

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

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

Score : 300 points

Problem Statement

There are N cubes stacked vertically on a desk.

You are given a string S of length N. The color of the i-th cube from the bottom is red if the i-th character in S is 0, and blue if that character is 1.

You can perform the following operation any number of times: choose a red cube and a blue cube that are adjacent, and remove them. Here, the cubes that were stacked on the removed cubes will fall down onto the object below them.

At most how many cubes can be removed?

Constraints

1 \leq N \leq 10^5

|S| = N

Each character in S is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum number of cubes that can be removed.

Sample Input 1

0011

Sample Output 1

4

All four cubes can be removed, by performing the operation as follows:

Remove the second and third cubes from the bottom. Then, the fourth cube drops onto the first cube.

Remove the first and second cubes from the bottom.

Sample Input 2

11011010001011

Sample Output 2

12

Sample Input 3

0

Sample Output 3

0


package main

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

// {{{
// source: https://github.com/raahii/algo
func MaxInts(nums ...int) int {
	var maxVal int
	for i, e := range nums {
		if i == 0 || e > maxVal {
			maxVal = e
		}
	}
	return maxVal
}

func MaxIntsWithIdx(nums ...int) (int, int) {
	var maxIdx, maxVal int
	for i, e := range nums {
		if i == 0 || e > maxVal {
			maxIdx = i
			maxVal = e
		}
	}
	return maxVal, maxIdx
}

func MinInts(nums ...int) int {
	var minVal int
	for i, e := range nums {
		if i == 0 || e < minVal {
			minVal = e
		}
	}
	return minVal
}

func MinIntsWithIdx(nums ...int) (int, int) {
	var minIdx, minVal int
	for i, e := range nums {
		if i == 0 || e < minVal {
			minIdx = i
			minVal = e
		}
	}
	return minVal, minIdx
}

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

func ReverseInts(nums []int) []int {
	rnums := make([]int, len(nums))
	for i := 0; i < len(nums); i++ {
		rnums[len(nums)-1-i] = nums[i]
	}
	return rnums
}

func ExtendInts(nums1 []int, nums2 []int) []int {
	for _, v := range nums2 {
		nums1 = append(nums1, v)
	}
	return nums1
}

func Ints2d(n_rows, n_cols int) [][]int {
	ints := make([][]int, n_rows)
	for i := 0; i < n_rows; i++ {
		ints[i] = make([]int, n_cols)
	}
	return ints
}

func MemsetInts1d(nums []int, val int) {
	for i := range nums {
		nums[i] = val
	}
}

func MemsetInts2d(nums [][]int, val int) {
	for i := range nums {
		for j := range nums[i] {
			nums[i][j] = val
		}
	}
}

func ContainsInt(nums []int, num int) bool {
	sort.Ints(nums)

	s, e := 0, len(nums)
	for {
		if s >= e {
			break
		}

		m := (e + s) / 2
		if nums[m] == num {
			return true
		} else if num > nums[m] {
			s = m + 1
		} else {
			e = m
		}
	}

	return false
}

func ReadInt(f *os.File) int {
	var n int
	fmt.Fscanf(f, "%d", &n)
	return n
}

func ReadInts(f *os.File, n int) []int {
	nums := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(f, "%d", &nums[i])
	}
	return nums
}

func ScanInts(f *os.File, vars ...*int) {
	for i := 0; i < len(vars); i++ {
		fmt.Fscanf(f, "%d", vars[i])
	}
}

func ReadLines(f *os.File, n int) []string {
	var lines []string
	reader := bufio.NewReader(f)
	for i := 0; i < n; i++ {
		bytes, _, err := reader.ReadLine()
		if err != nil {
			break
		}
		lines = append(lines, string(bytes))
	}

	return lines
}

func ReadWords(f *os.File, n int) []string {
	strs := make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(f, "%s", &strs[i])
	}
	return strs
}

func Pow(a, n int) int {
	c := 1
	for i := 0; i < n; i++ {
		c *= a
	}
	return c
}

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

	return n
}

// }}}

func ReadLine(f *os.File) string {
	reader := bufio.NewReader(f)
	bytes, _, _ := reader.ReadLine()

	return string(bytes)
}

func remove(str *string, char string) bool {
	if !strings.Contains(*str, char) {
		return false
	} else {
		strings.Replace(*str, char+char, "", -1)
		return true
	}
}

func solve(str string) string {
	for {
		i0 := strings.Index(str, "01")
		i1 := strings.Index(str, "10")
		if i0 == -1 && i1 == -1 {
			break
		} else if i0 == -1 || (i1 != -1 && i1 < i0) {
			str = strings.Replace(str, "10", "", 1)
		} else {
			str = strings.Replace(str, "01", "", 1)
		}
	}
	return str
}

func main() {
	str := ReadLine(os.Stdin)
	fmt.Println(len(str) - len(solve(str)))
}


package main

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

var (
	uft []int
	ch  []int
	ans []int64
)

func find(x int) int {
	if uft[x] == x {
		return x
	}

	uft[x] = find(uft[x])
	return uft[x]
}

func union(a, b, i int) {
	ans[i-1] = ans[i]
	ar, br := find(a), find(b)
	if ar == br {
		return
	}

	ans[i-1] -= int64(ch[ar] * ch[br])
	uft[ar] = uft[br]
	ch[br] += ch[ar]
}

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

	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	as := make([]int, m)
	bs := make([]int, m)
	for i := 0; i < m; i++ {
		sc.Scan()
		as[i], _ = strconv.Atoi(sc.Text())
		sc.Scan()
		bs[i], _ = strconv.Atoi(sc.Text())
	}

	uft = make([]int, n+1)
	ch = make([]int, n+1)
	for i := range uft {
		uft[i] = i
		ch[i]++
	}

	ans = make([]int64, m)
	ans[m-1] = int64(n * (n - 1) / 2)
	for i := m - 1; i >= 1; i-- {
		union(as[i], bs[i], i)
	}

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

Score : 400 points

Problem Statement

There are N islands and M bridges.

The i-th bridge connects the A_i-th and B_i-th islands bidirectionally.

Initially, we can travel between any two islands using some of these bridges.

However, the results of a survey show that these bridges will all collapse because of aging, in the order from the first bridge to the M-th bridge.

Let the inconvenience be the number of pairs of islands (a, b) (a < b) such that we are no longer able to travel between the a-th and b-th islands using some of the bridges remaining.

For each i (1 \leq i \leq M), find the inconvenience just after the i-th bridge collapses.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i < B_i \leq N

All pairs (A_i, B_i) are distinct.

The inconvenience is initially 0.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_M B_M

Output

In the order i = 1, 2, ..., M, print the inconvenience just after the i-th bridge collapses.
Note that the answer may not fit into a 32-bit integer type.

Sample Input 1

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

Sample Output 1

0
0
4
5
6

For example, when the first to third bridges have collapsed, the inconvenience is 4 since we can no longer travel between the pairs (1, 2), (1, 3), (2, 4) and (3, 4).

Sample Input 2

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

Sample Output 2

8
9
12
14
15

Sample Input 3

2 1
1 2

Sample Output 3

1


package main

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

var (
	uft      []int
	children map[int]int64
)

func find(x int) int {
	if uft[x] == x {
		return x
	}

	uft[x] = find(uft[x])
	return uft[x]
}

func union(a, b int) {
	uft[a] = uft[b]
	children[b] += children[a]
}

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

	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	as := make([]int, m)
	bs := make([]int, m)
	for i := 0; i < m; i++ {
		sc.Scan()
		as[i], _ = strconv.Atoi(sc.Text())
		sc.Scan()
		bs[i], _ = strconv.Atoi(sc.Text())
	}

	uft = make([]int, n+1)
	children = make(map[int]int64)
	for i := range uft {
		uft[i] = i
		children[i]++
	}

	ans := make([]int64, m)
	ans[m-1] = int64(n * (n - 1) / 2)
	for i := m - 1; i >= 1; i-- {
		ar := find(as[i])
		br := find(bs[i])

		if ar != br {
			ans[i-1] = ans[i] - children[ar]*children[br]
			union(ar, br)
			continue
		}
		ans[i-1] = ans[i]
	}

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


package main

import "fmt"

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

	if s <= "2019/04/30" {
		fmt.Println("Heisei")
	} else {
		fmt.Println("TBD")
	}

}

Score : 100 points

Problem Statement

You are given a string S as input. This represents a valid date in the year 2019 in the yyyy/mm/dd format. (For example, April 30, 2019 is represented as 2019/04/30.)

Write a program that prints Heisei if the date represented by S is not later than April 30, 2019, and prints TBD otherwise.

Constraints

S is a string that represents a valid date in the year 2019 in the yyyy/mm/dd format.

Input

Input is given from Standard Input in the following format:

S

Output

Print Heisei if the date represented by S is not later than April 30, 2019, and print TBD otherwise.

Sample Input 1

2019/04/30

Sample Output 1

Heisei

Sample Input 2

2019/11/01

Sample Output 2

TBD


package main

import "fmt"

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

	if s <= "2019/04/30" {
		fmt.Println("Heisei")
	} else {
		fmt.Println("TBD")
	}
}


package main

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

func main() {
	sc.Split(bufio.ScanWords)
	// sc.Split(bufio.ScanLines)
	n := readInt()
	var sum float64
	for i := 0; i < n; i++ {
		x := readFloat()
		u := read()
		if u == "BTC" {
			sum += 380000 * x
		} else {
			sum += x
		}
	}
	fmt.Println(sum)
}

//便利関数群
var sc = bufio.NewScanner(os.Stdin)

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

func readInt() int {
	i, _ := strconv.Atoi(read())
	return i
}

func readFloat() float64 {
	i, _ := strconv.ParseFloat(read(), 64)
	return i
}

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

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

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

type XY struct {
	x, y int
}

type Points []XY

func (p Points) Len() int {
	return len(p)
}
func (p Points) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}
func (p Points) Less(i, j int) bool {
	return p[i].x < p[j].x
}
func (p Points) remove(i int) Points {
	if i >= len(p) {
		return p
	}
	return append(p[:i], p[i+1:]...)
}

Score : 200 points

Problem Statement

Takahashi received otoshidama (New Year's money gifts) from N of his relatives.

You are given N values x_1, x_2, ..., x_N and N strings u_1, u_2, ..., u_N as input. Each string u_i is either JPY or BTC, and x_i and u_i represent the content of the otoshidama from the i-th relative.

For example, if x_1 = 10000 and u_1 = JPY, the otoshidama from the first relative is 10000 Japanese yen; if x_2 = 0.10000000 and u_2 = BTC, the otoshidama from the second relative is 0.1 bitcoins.

If we convert the bitcoins into yen at the rate of 380000.0 JPY per 1.0 BTC, how much are the gifts worth in total?

Constraints

2 \leq N \leq 10

u_i = JPY or BTC.

If u_i = JPY, x_i is an integer such that 1 \leq x_i \leq 10^8.

If u_i = BTC, x_i is a decimal with 8 decimal digits, such that 0.00000001 \leq x_i \leq 100.00000000.

Input

Input is given from Standard Input in the following format:

N
x_1 u_1
x_2 u_2
:
x_N u_N

Output

If the gifts are worth Y yen in total, print the value Y (not necessarily an integer).

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

Sample Input 1

2
10000 JPY
0.10000000 BTC

Sample Output 1

48000.0

The otoshidama from the first relative is 10000 yen. The otoshidama from the second relative is 0.1 bitcoins, which is worth 38000.0 yen if converted at the rate of 380000.0 JPY per 1.0 BTC. The sum of these is 48000.0 yen.

Outputs such as 48000 and 48000.1 will also be judged correct.

Sample Input 2

3
100000000 JPY
100.00000000 BTC
0.00000001 BTC

Sample Output 2

138000000.0038

In this case, outputs such as 138001000 and 1.38e8 will also be judged correct.


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

func main() {
	buf := make([]byte, 0)
	sc.Buffer(buf, 1000000007)
	sc.Split(bufio.ScanWords)
	a, _ := strconv.Atoi(Scanner())
	b, _ := strconv.Atoi(Scanner())
	q, _ := strconv.Atoi(Scanner())
	s := make([]int, a)
	t := make([]int, b)
	for i := 0; i < a; i++ {
		s[i], _ = strconv.Atoi(Scanner())
	}
	for i := 0; i < b; i++ {
		t[i], _ = strconv.Atoi(Scanner())
	}
	for i := 0; i < q; i++ {
		x, _ := strconv.Atoi(Scanner())
		sidx := sort.SearchInts(s, x)
		tidx := sort.SearchInts(t, x)
		ans := 1000000000000
		if sidx > 0 && tidx > 0 {
			ans = smaller(larger(x-s[sidx-1], x-t[tidx-1]), ans)
		}
		if sidx < a && tidx > 0 {
			ans = smaller(larger(s[sidx]-x, x-t[tidx-1])+smaller(s[sidx]-x, x-t[tidx-1])*2, ans)
		}
		if sidx > 0 && tidx < b {
			ans = smaller(larger(x-s[sidx-1], t[tidx]-x)+smaller(x-s[sidx-1], t[tidx]-x)*2, ans)
		}
		if sidx < a && tidx < b {
			ans = smaller(larger(s[sidx]-x, t[tidx]-x), ans)
		}
		fmt.Println(ans)
	}
}
func smaller(x, y int) int {
	if x < y {
		return x
	} else {
		return y
	}
}
func larger(x, y int) int {
	if x < y {
		return y
	} else {
		return x
	}
}

Score : 400 points

Problem Statement

Along a road running in an east-west direction, there are A shrines and B temples.
The i-th shrine from the west is located at a distance of s_i meters from the west end of the road, and the i-th temple from the west is located at a distance of t_i meters from the west end of the road.

Answer the following Q queries:

Query i (1 \leq i \leq Q): If we start from a point at a distance of x_i meters from the west end of the road and freely travel along the road, what is the minimum distance that needs to be traveled in order to visit one shrine and one temple? (It is allowed to pass by more shrines and temples than required.)

Constraints

1 \leq A, B \leq 10^5

1 \leq Q \leq 10^5

1 \leq s_1 < s_2 < ... < s_A \leq 10^{10}

1 \leq t_1 < t_2 < ... < t_B \leq 10^{10}

1 \leq x_i \leq 10^{10}

s_1, ..., s_A, t_1, ..., t_B, x_1, ..., x_Q are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B Q
s_1
:
s_A
t_1
:
t_B
x_1
:
x_Q

Output

Print Q lines. The i-th line should contain the answer to the i-th query.

Sample Input 1

2 3 4
100
600
400
900
1000
150
2000
899
799

Sample Output 1

350
1400
301
399

There are two shrines and three temples. The shrines are located at distances of 100, 600 meters from the west end of the road, and the temples are located at distances of 400, 900, 1000 meters from the west end of the road.

Query 1: If we start from a point at a distance of 150 meters from the west end of the road, the optimal move is first to walk 50 meters west to visit a shrine, then to walk 300 meters east to visit a temple.

Query 2: If we start from a point at a distance of 2000 meters from the west end of the road, the optimal move is first to walk 1000 meters west to visit a temple, then to walk 400 meters west to visit a shrine. We will pass by another temple on the way, but it is fine.

Query 3: If we start from a point at a distance of 899 meters from the west end of the road, the optimal move is first to walk 1 meter east to visit a temple, then to walk 300 meters west to visit a shrine.

Query 4: If we start from a point at a distance of 799 meters from the west end of the road, the optimal move is first to walk 199 meters west to visit a shrine, then to walk 200 meters west to visit a temple.

Sample Input 2

1 1 3
1
10000000000
2
9999999999
5000000000

Sample Output 2

10000000000
10000000000
14999999998

The road is quite long, and we may need to travel a distance that does not fit into a 32-bit integer.


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

func main() {
	sc.Split(bufio.ScanWords)
	var n, m, ans int
	var k [30]int
	var array [30]int
	fmt.Scanf("%d %d", &n, &m)
	for i := 0; i < n; i++ {
		k[i] = nextInt()
		for j := 0; j < k[i]; j++ {
			a := nextInt()
			a--
			array[a]++
		}
	}

	for _, a := range array {
		if a == n {
			ans++
		}
	}

	fmt.Println(ans)

}

Score : 200 points

Problem Statement

Katsusando loves omelette rice.

Besides, he loves crème brûlée, tenderloin steak and so on, and believes that these foods are all loved by everyone.

To prove that hypothesis, he conducted a survey on M kinds of foods and asked N people whether they like these foods or not.

The i-th person answered that he/she only likes the A_{i1}-th, A_{i2}-th, ..., A_{iK_i}-th food.

Find the number of the foods liked by all the N people.

Constraints

All values in input are integers.

1 \leq N, M \leq 30

1 \leq K_i \leq M

1 \leq A_{ij} \leq M

For each i (1 \leq i \leq N), A_{i1}, A_{i2}, ..., A_{iK_i} are distinct.

Constraints

Input is given from Standard Input in the following format:

N M
K_1 A_{11} A_{12} ... A_{1K_1}
K_2 A_{21} A_{22} ... A_{2K_2}
:
K_N A_{N1} A_{N2} ... A_{NK_N}

Output

Print the number of the foods liked by all the N people.

Sample Input 1

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

Sample Output 1

1

As only the third food is liked by all the three people, 1 should be printed.

Sample Input 2

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

Sample Output 2

0

Katsusando's hypothesis turned out to be wrong.

Sample Input 3

1 30
3 5 10 30

Sample Output 3

3


package main

import (
	"fmt"
)

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

	foods := make(map[int]int)

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

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

		for _, v := range lst {
			foods[v]++
		}
	}

	count := 0
	for _, v := range foods {
		if v == n {
			count++
		}
	}
	fmt.Println(count)
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

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

func nextFloat() float64 {
	sc.Scan()
	f, e := strconv.ParseFloat(sc.Text(), 64)
	if e != nil {
		panic(e)
	}
	return f
}

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

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

func main() {
	N := nextInt()
	IS := scanInts(N)
	sort.Sort(sort.IntSlice(IS))
	if len(IS) > 10 {
		IS = IS[0:9]
	}
	for {
		if len(IS) == 1 {
			fmt.Println(IS[0])
			return
		}
		if IS[0] == IS[1] {
			IS = IS[1:]
			continue
		} else if IS[0] == 1 {
			fmt.Println(1)
			return
		}
		a := IS[1] - IS[0]
		b := IS[0]
		IS[1] = max(a, b)
		IS[0] = min(a, b)
	}
}

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

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

Score : 300 points

Problem Statement

There are N monsters, numbered 1, 2, ..., N.

Initially, the health of Monster i is A_i.

Below, a monster with at least 1 health is called alive.

Until there is only one alive monster, the following is repeated:

A random alive monster attacks another random alive monster.

As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.

Find the minimum possible final health of the last monster alive.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible final health of the last monster alive.

Sample Input 1

4
2 10 8 40

Sample Output 1

2

When only the first monster keeps on attacking, the final health of the last monster will be 2, which is minimum.

Sample Input 2

4
5 13 8 1000000000

Sample Output 2

1

Sample Input 3

3
1000000000 1000000000 1000000000

Sample Output 3

1000000000


package main

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

var (
	readString func() string
	stdout     *bufio.Writer
)

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

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

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

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

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

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

func readLengthAndSlice() (int, []int) {
	n := readInt()
	return n, readIntSlice(n)
}

func printf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(stdout, f, args...)
}

func println(args ...interface{}) (int, error) {
	return fmt.Fprintln(stdout, args...)
}

func eprintln(args ...interface{}) (int, error) {
	return fmt.Fprintln(os.Stderr, args...)
}

// readString() string
// readInt() int
// readIntSlice(n int) []int
// readLengthAndSlice() []int

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

var score []int = []int{0, 2, 5, 5, 4, 5, 6, 3, 7, 6}

type sortTarget0Slice []int

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

func (s sortTarget0Slice) Less(i, j int) bool {
	if score[s[i]] < score[s[j]] {
		return true
	} else if score[s[i]] > score[s[j]] {
		return false
	}
	return s[i] > s[j]
}

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

func less(a, b string) bool {
	if len(a) < len(b) {
		return true
	} else if len(a) > len(b) {
		return false
	}
	av, _ := strconv.ParseInt(a[:1], 0, 64)
	bv, _ := strconv.ParseInt(b[:1], 0, 64)
	if av < bv {
		return true
	} else if av > bv {
		return false
	}
	return less(a[1:], b[1:])
}

func main() {
	defer stdout.Flush()
	n := readInt()

	m := readInt()
	a := make([]int, m)
	for i := range a {
		a[i] = readInt()
	}
	sort.Sort(sortTarget0Slice(a))

	dp := make([]string, n+1)
	for i := range dp {
		dp[i] = "_"
	}
	dp[0] = ""
	for i := 1; i <= n; i++ {
		for _, x := range a {
			p := i - score[x]
			if p < 0 || dp[p] == "_" {
				continue
			}
			s := fmt.Sprintf("%d%s", x, dp[p])
			if dp[i] == "_" || less(dp[i], s) {
				dp[i] = s
			}
		}
	}
	println(dp[n])
}

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

Score : 400 points

Problem Statement

Find the largest integer that can be formed with exactly N matchsticks, under the following conditions:

Every digit in the integer must be one of the digits A_1, A_2, ..., A_M (1 \leq A_i \leq 9).

The number of matchsticks used to form digits 1, 2, 3, 4, 5, 6, 7, 8, 9 should be 2, 5, 5, 4, 5, 6, 3, 7, 6, respectively.

Constraints

All values in input are integers.

2 \leq N \leq 10^4

1 \leq M \leq 9

1 \leq A_i \leq 9

A_i are all different.

There exists an integer that can be formed by exactly N matchsticks under the conditions.

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_M

Output

Print the largest integer that can be formed with exactly N matchsticks under the conditions in the problem statement.

Sample Input 1

20 4
3 7 8 4

Sample Output 1

777773

The integer 777773 can be formed with 3 + 3 + 3 + 3 + 3 + 5 = 20 matchsticks, and this is the largest integer that can be formed by 20 matchsticks under the conditions.

Sample Input 2

101 9
9 8 7 6 5 4 3 2 1

Sample Output 2

71111111111111111111111111111111111111111111111111

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

Sample Input 3

15 3
5 4 6

Sample Output 3

654


package main

import (
	"fmt"
)

func main() {
	var n, k int
	fmt.Scan(&n, &k)
	m := (n-1)/2 + 1
	if k <= m {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

Score : 100 points

Problem Statement

Determine if we can choose K different integers between 1 and N (inclusive) so that no two of them differ by 1.

Constraints

1\leq N,K\leq 100

N and K are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

If we can choose K integers as above, print YES; otherwise, print NO.

Sample Input 1

3 2

Sample Output 1

YES

We can choose 1 and 3.

Sample Input 2

5 5

Sample Output 2

NO

Sample Input 3

31 10

Sample Output 3

YES

Sample Input 4

10 90

Sample Output 4

NO


package main

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

func main() {
	var n int
	var k int
	var num int
	sc := bufio.NewScanner(os.Stdin)
	sc.Scan()
	fmt.Sscanf(sc.Text(), "%d %d", &n, &k)

	if n%2 == 0{
		num = n/2
	} else {
		num = ((n+1)/2) + 1
	}

	if k <= num{
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}


package main

import (
  "fmt"
)

func main() {
  a := make([]int, 3)
  b := make([]int, 3)
  for i := 0; i < 3; i++ {
    fmt.Scan(&a[i])
    fmt.Scan(&b[i])
  }
  isTwoCount := 0
  isYes := true
  for i := 1; i < 5; i++ {
    count := 0
    for j := 0; j < 3; j++ {
      if a[j] == i || b [j] == i {
        count++
      }
    }
    if count > 2 {
      isYes = false
      break
    }
    if count > 1 {
      isTwoCount++
    }
  }
  if isYes || isTwoCount == 1 {
    fmt.Println("YES")
  } else {
    fmt.Println("NO")
  }
}

Score : 200 points

Problem Statement

There are four towns, numbered 1,2,3 and 4.
Also, there are three roads. The i-th road connects different towns a_i and b_i bidirectionally.
No two roads connect the same pair of towns. Other than these roads, there is no way to travel between these towns, but any town can be reached from any other town using these roads.

Determine if we can visit all the towns by traversing each of the roads exactly once.

Constraints

1 \leq a_i,b_i \leq 4(1\leq i\leq 3)

a_i and b_i are different. (1\leq i\leq 3)

No two roads connect the same pair of towns.

Any town can be reached from any other town using the roads.

Input

Input is given from Standard Input in the following format:

a_1 b_1
a_2 b_2
a_3 b_3

Output

If we can visit all the towns by traversing each of the roads exactly once, print YES; otherwise, print NO.

Sample Input 1

4 2
1 3
2 3

Sample Output 1

YES

We can visit all the towns in the order 1,3,2,4.

Sample Input 2

3 2
2 4
1 2

Sample Output 2

NO

Sample Input 3

2 1
3 2
4 3

Sample Output 3

YES


package main

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

//scanで一行づつ読み込む
var sc = bufio.NewScanner(os.Stdin)
var wtr = bufio.NewWriter(os.Stdout)

//sort
// array := []int{5, 1, 4, 2, 3}
// sort.Sort(sort.IntSlice(array))

func main() {
	// a := make([]int, n)
	// A := strings.Split(nextLine(), " ")

	X := strings.Split(nextLine(), " ")

	// Z := strings.Split(nextLine(), " ")

	// n, _ := strconv.Atoi(input[0])

	// memo = make([]bool, n+1, n+2)

	K, _ := strconv.Atoi(X[0])
	A, _ := strconv.Atoi(X[1])
	B, _ := strconv.Atoi(X[2])

	// ans := K+1
	buiscket := int64(K + 1)
	tmp := int64(1)
	money := int64(0)

	for i := 0; i < K; i++ {

		if money < 1 {

			if i >= K-1 {
				tmp++
			} else if tmp < int64(A) {
				tmp++
			} else {
				tmp, money = exchangeToYen(tmp, int64(A))
			}
		} else {
			tmp, money = exchangeToBuiscket(money, tmp, int64(B))
		}
		// fmt.Printf("tmp: %d , money: %d \n", tmp, money)
	}

	buiscket = max(buiscket, tmp)

	fmt.Fprintln(wtr, buiscket)

	_ = wtr.Flush()
}

func addBuiscket(b int64) int64 {
	return b + 1
}
func exchangeToYen(b int64, rate int64) (rest int64, money int64) {
	return b - rate, 1
}
func exchangeToBuiscket(mone int64, buis int64, rate int64) (b int64, money int64) {
	return buis + rate, mone - 1
}

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

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func max(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}
func com(a, b int) int {

	if a > b {
		return 0
	}
	return abs(a - b)
}

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

type dishh struct {
	first  int
	second int
}

type dish []dishh

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

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

func (p dish) Less(i, j int) bool {

	return p[i].first+p[i].second > p[j].first+p[j].second
}

Score : 400 points

Problem Statement

Snuke has one biscuit and zero Japanese yen (the currency) in his pocket.
He will perform the following operations exactly K times in total, in the order he likes:

Hit his pocket, which magically increases the number of biscuits by one.

Exchange A biscuits to 1 yen.

Exchange 1 yen to B biscuits.

Find the maximum possible number of biscuits in Snuke's pocket after K operations.

Constraints

1 \leq K,A,B \leq 10^9

K,A and B are integers.

Input

Input is given from Standard Input in the following format:

K A B

Output

Print the maximum possible number of biscuits in Snuke's pocket after K operations.

Sample Input 1

4 2 6

Sample Output 1

7

The number of biscuits in Snuke's pocket after K operations is maximized as follows:

Hit his pocket. Now he has 2 biscuits and 0 yen.

Exchange 2 biscuits to 1 yen. his pocket. Now he has 0 biscuits and 1 yen.

Hit his pocket. Now he has 1 biscuits and 1 yen.

Exchange 1 yen to 6 biscuits. his pocket. Now he has 7 biscuits and 0 yen.

Sample Input 2

7 3 4

Sample Output 2

8

Sample Input 3

314159265 35897932 384626433

Sample Output 3

48518828981938099


package main

import (
  "fmt"
)

func maxInt(a ...int) int {m := a[0]; for _, x := range a {if x > m {m = x}}; return m}
func minInt(a ...int) int {m := a[0]; for _, x := range a {if x < m {m = x}}; return m}
func sumInt(a ...int) int {s := 0; for _, v := range a {s += v}; return s}

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

  ans := "No"
  if sumInt(l...) > maxInt(l...) * 2 {
    ans = "Yes"
  }
  fmt.Println(ans)

}

Score : 200 points

Problem Statement

Determine if an N-sided polygon (not necessarily convex) with sides of length L_1, L_2, ..., L_N can be drawn in a two-dimensional plane.

You can use the following theorem:

Theorem: an N-sided polygon satisfying the condition can be drawn if and only if the longest side is strictly shorter than the sum of the lengths of the other N-1 sides.

Constraints

All values in input are integers.

3 \leq N \leq 10

1 \leq L_i \leq 100

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 ... L_N

Output

If an N-sided polygon satisfying the condition can be drawn, print Yes; otherwise, print No.

Sample Input 1

4
3 8 5 1

Sample Output 1

Yes

Since 8 < 9 = 3 + 5 + 1, it follows from the theorem that such a polygon can be drawn on a plane.

Sample Input 2

4
3 8 4 1

Sample Output 2

No

Since 8 \geq 8 = 3 + 4 + 1, it follows from the theorem that such a polygon cannot be drawn on a plane.

Sample Input 3

10
1 8 10 5 8 12 34 100 11 3

Sample Output 3

No


package main

import (
	"fmt"
)

func main() {

	var n int
	var max int
	var sum int

	fmt.Scan(&n)

	for i := 0; i < n; i++ {
		var l int
		fmt.Scan(&l)
		sum += l
		if max < l {
			max = l
		}
	}

	sum -= max

	if max < sum {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}

}