package main

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

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

	n, m := io.NextInt(), io.NextInt()

	brokens := []int{}
	for i := 0; i < m; i++ {
		brokens = append(brokens, io.NextInt())
	}

	ans := calc(n, brokens)

	io.PrintLn(ans)
}

func calc(n int, brokens []int) int64 {
	if n == 1 {
		return int64(1)
	}

	dp := make([]int64, n+1)
	dp[0] = 1

	for _, b := range brokens {
		dp[b] = -1
	}

	if dp[1] == -1 {
		dp[1] = 0
	} else {
		dp[1] = 1
	}

	if n <= 1 {
		return dp[n]
	}

	for i := 2; i < n+1; i++ {
		if dp[i] == -1 {
			dp[i] = 0
		} else {
			dp[i] = dp[i-1] + dp[i-2]
			//dp[i] %= (1e9 + 7)
		}
		//fmt.Printf("%#v\n", dp)
	}

	return dp[n] % int64(1e9+7)
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


package main

import (
	"fmt"
)

const MOD = 1000000007

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

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

	res := 1
	for i := 0; i < M; i++ {
		n := 0
		if i == 0 {
			n = as[i] - 1
		} else {
			n =  as[i] - as[i - 1] - 2
		}

		if n < 0 {
			fmt.Println(0)
			return
		}

		res *= fib(n) % MOD
		res = res % MOD
	}

	if M > 0 {
		res *= fib(N-as[M-1]-1) % MOD
		res = res % MOD
	} else {
		res *= fib(N) % MOD
	}

	fmt.Println(res)
}

func fib(N int) int {
	if N < 2 {
		return 1
	}

	n1, n2, f := 1, 1, 1

	for i := 0; i < N - 1; i++ {
		f = n1 + n2
		n1 = n2
		n2 = f
	}

	return f
}

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

Score : 300 points

Problem Statement

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

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

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

Constraints

1 \leq N \leq 10^5

0 \leq M \leq N-1

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

Input

Input is given from Standard Input in the following format:

N M
a_1
a_2
.
.
.
a_M

Output

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

Sample Input 1

6 1
3

Sample Output 1

4

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

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

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

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

0 \to 2 \to 4 \to 6

Sample Input 2

10 2
4
5

Sample Output 2

0

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

Sample Input 3

100 5
1
23
45
67
89

Sample Output 3

608200469

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

Submitted source-code file size, in bytes.

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

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


package main

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

func main() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, initialBufSize), maxBufSize)
	defer wt.Flush()

	_, a, b, c, d := nextInt(), nextInt()-1, nextInt()-1, nextInt()-1, nextInt()-1
	s := next()

	// 連続する岩がないか
	for i := a + 1; i < max(c, d); i++ {
		if s[i] == '#' && s[i+1] == '#' {
			YesOrNo(false)
			return
		}
	}

	if c < d {
		YesOrNo(true)
		return
	}

	// 3連続の空白があるか
	ok := false
	for i := b; i <= d; i++ {
		if s[i-1] == '.' && s[i] == '.' && s[i+1] == '.' {
			ok = true
			break
		}
	}
	YesOrNo(ok)
}

const (
	initialBufSize = 100000
	maxBufSize     = 10000000
)

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

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

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

func puts(a ...interface{}) {
	fmt.Fprintln(wt, a...)
}

func YesOrNo(ok bool) {
	if ok {
		puts("Yes")
	} else {
		puts("No")
	}
}

func max(nums ...int) int {
	ret := nums[0]
	for _, v := range nums {
		if v > ret {
			ret = v
		}
	}
	return ret
}

Score : 400 points

Problem Statement

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

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

You can repeat the following operation any number of times:

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

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

Determine whether this is possible.

Constraints

4 \leq N \leq 200\ 000

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

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

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

A, B, C and D are all different.

A < B

A < C

B < D

Input

Input is given from Standard Input in the following format:

N A B C D
S

Output

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

Sample Input 1

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

Sample Output 1

Yes

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

A#B.#..

A#.B#..

.#AB#..

.#A.#B.

.#.A#B.

.#.A#.B

.#..#AB

Sample Input 2

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

Sample Output 2

No

Sample Input 3

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

Sample Output 3

Yes


package main

import "fmt"

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


package main

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

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

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

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

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

/* sort */
type Int64Slice []int64

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

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

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

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

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

func main() {
	buf := make([]byte, initialBufSize)
	scanner.Buffer(buf, maxBufSize)
	scanner.Split(bufio.ScanWords)
	S := readString()
	var ans int
	for i := 0; i < len(S); i++ {
		if S[i] == 'o' {
			ans++
		}
	}
	if 15-len(S)+ans >= 8 {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

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

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

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

func print() {
	writer.Flush()
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Score : 200 points

Problem Statement

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

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

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

Constraints

1 \leq k \leq 15

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

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

oxoxoxoxoxoxox

Sample Output 1

YES

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

Sample Input 2

xxxxxxxx

Sample Output 2

NO


package main

import (
	"fmt"
	"strings"
)

func main() {
	var s string
	fmt.Scan(&s)
	for i := len(s); i < 15; i++ {
		s = s + "o"
	}
	fmt.Println(s)
	fmt.Println(strings.Count(s, "o"))
	if strings.Count(s, "o") >= 8 {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

func main() {
	torikumi := nextLine()
	if strings.Count(torikumi, "o")+15-len(torikumi) >= 8 {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}


package main

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

const (
	mod = int64(1000003)
)

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

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

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

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

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

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

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

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

Score : 600 points

Problem Statement

Consider the following arithmetic progression with n terms:

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

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

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

Constraints

1 \leq Q \leq 10^5

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

1 \leq n_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

Q
x_1 d_1 n_1
:
x_Q d_Q n_Q

Output

Print Q lines.

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

Sample Input 1

2
7 2 4
12345 67890 2019

Sample Output 1

9009
916936

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


package main

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

var sc = bufio.NewScanner(os.Stdin)

func main() {
	buf := make([]byte, 0)
	sc.Buffer(buf, 1000000009)
	sc.Split(bufio.ScanWords)

	a, p := oneInt(), oneInt()

	fragment := a * 3
	fmt.Println((fragment + p) / 2)
}

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

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

func scanNums(len int) (nums []int) {
	for i := 0; i < len; i++ {
		nums = append(nums, oneInt())
	}
	return nums
}

func scanStrings(len int) (strs []string) {
	for i := 0; i < len; i++ {
		strs = append(strs, oneStr())
	}
	return strs
}

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

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

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

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

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

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

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

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

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

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

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

Score : 100 points

Problem Statement

We have A apples and P pieces of apple.

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

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

Constraints

All values in input are integers.

0 \leq A, P \leq 100

Input

Input is given from Standard Input in the following format:

A P

Output

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

Sample Input 1

1 3

Sample Output 1

3

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

Sample Input 2

0 1

Sample Output 2

0

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

Sample Input 3

32 21

Sample Output 3

58


package main

import (
	"fmt"
	"sort"
)

type restaurant struct {
	id    int
	city  string
	point int
}

type restaurants []restaurant

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

func (r restaurants) Less(i, j int) bool {
	if r[i].city == r[j].city {
		return r[i].point > r[j].point
	}
	return r[i].city < r[j].city
}

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

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

	rs := make([]restaurant, n)
	for i := range rs {
		rs[i].id = i + 1
		fmt.Scan(&rs[i].city, &rs[i].point)
	}

	sort.Sort(restaurants(rs))

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

Score : 200 points

Problem Statement

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

You want to introduce the restaurants in the following order:

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

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

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

Constraints

1 ≤ N ≤ 100

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

0 ≤ P_i ≤ 100

P_i is an integer.

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

Input

Input is given from Standard Input in the following format:

N
S_1 P_1
:
S_N P_N

Output

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

Sample Input 1

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

Sample Output 1

3
4
6
1
5
2

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

Sample Input 2

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

Sample Output 2

10
9
8
7
6
5
4
3
2
1


package main

import (
	"fmt"
	"sort"
)

type restaurant struct {
	s     string
	p     int
	index int
}

type lessFunc func(r1, r2 *restaurant) bool

type multiSorter struct {
	restaurants []restaurant
	less        []lessFunc
}

func (ms *multiSorter) Sort(restaurants []restaurant) {
	ms.restaurants = restaurants
	sort.Sort(ms)
}

func orderedBy(less ...lessFunc) *multiSorter {
	return &multiSorter{
		less: less,
	}
}

func (ms *multiSorter) Len() int { return len(ms.restaurants) }
func (ms *multiSorter) Swap(i, j int) {
	ms.restaurants[i], ms.restaurants[j] = ms.restaurants[j], ms.restaurants[i]
}
func (ms *multiSorter) Less(i, j int) bool {
	p, q := &ms.restaurants[i], &ms.restaurants[j]
	var k int
	for k = 0; k < len(ms.less)-1; k++ {
		less := ms.less[k]
		switch {
		case less(p, q):
			return true
		case less(q, p):
			return false
		}
	}
	return ms.less[k](p, q)
}

func main() {
	city := func(r1, r2 *restaurant) bool {
		return r1.s < r2.s
	}
	point := func(r1, r2 *restaurant) bool {
		return r2.p < r1.p
	}

	var n int
	fmt.Scan(&n)

	restaurants := make([]restaurant, n)
	for i := range restaurants {
		fmt.Scan(&restaurants[i].s, &restaurants[i].p)
		restaurants[i].index = i + 1
	}

	orderedBy(city, point).Sort(restaurants)

	for _, r := range restaurants {
		fmt.Println(r.index)
	}
}


package main

import (
	"fmt"
	"sort"
)

type Restaurant struct {
	Index int
	City  string
	Point int
}

type Restaurants []Restaurant

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

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

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

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

	restaurants := make([]Restaurant, n)

	for i := 0; i < n; i++ {
		restaurant := Restaurant{}
		restaurant.Index = i + 1
		fmt.Scan(&restaurant.City, &restaurant.Point)
		restaurants[i] = restaurant
	}

	sort.Sort(Restaurants(restaurants))

	for _, restaurant := range restaurants {
		fmt.Println(restaurant.Index)
	}
}


package main

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

type Restaurants [][]int

func (r Restaurants) Len() int {
	return len(r)
}
func (r Restaurants) Less(i, j int) bool {
	return r[i][1] > r[j][1]
}
func (r Restaurants) Swap(i, j int) {
	r[i], r[j] = r[j], r[i]
}

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

	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	var cities []string
	restaurantsMap := make(map[string]Restaurants)
	for i := 0; i < n; i++ {
		scanner.Scan()
		s := scanner.Text()
		scanner.Scan()
		p, _ := strconv.Atoi(scanner.Text())
		if _, ok := restaurantsMap[s]; !ok {
			cities = append(cities, s)
			restaurantsMap[s] = [][]int{}
		}
		restaurantsMap[s] = append(restaurantsMap[s], []int{i + 1, p})
	}

	sort.Strings(cities)
	for i := 0; i < len(cities); i++ {
		restaurants := restaurantsMap[cities[i]]
		sort.Sort(restaurants)
		for j := 0; j < len(restaurants); j++ {
			fmt.Println(restaurants[j][0])
		}
	}
}


package main

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

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

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

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

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

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

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

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

	if os.Getenv("MASPY") == "ますピ" {
		fp, _ = os.Open(os.Getenv("BEET_THE_HARMONY_OF_PERFECT"))
		cnt = 2
	}
	if os.Getenv("MASPYPY") == "ますピッピ" {
		wfp, _ = os.Create(os.Getenv("NGTKANA_IS_GENIUS10"))
	}

	scanner := getScanner(fp)
	writer := bufio.NewWriter(wfp)
	solve(scanner, writer)
	for i := 0; i < cnt; i++ {
		fmt.Fprintln(writer, "-----------------------------------")
		solve(scanner, writer)
	}
	writer.Flush()
}

func solve(scanner *bufio.Scanner, writer *bufio.Writer) {
	n := getNextInt(scanner)
	m := getNextInt(scanner)
	ss := make([]int, m)
	for i := 0; i < m; i++ {
		k := getNextInt(scanner)
		for j := 0; j < k; j++ {
			s := getNextInt(scanner) - 1
			ss[i] |= 1 << uint(s)
		}
	}

	pp := make([]int, m)
	for i := 0; i < m; i++ {
		pp[i] = getNextInt(scanner)
	}
	ans := 0
	for b := 0; b < 1<<uint(n); b++ {
		sum := 0
		for i := 0; i < m; i++ {
			target := b & ss[i]
			on := 0
			for j := 0; j < n; j++ {
				on += target >> uint(j) & 1
			}
			if on%2 == pp[i] {
				sum++
			}
		}
		if sum == m {
			ans++
		}
	}

	fmt.Fprintln(writer, ans)
}

Score : 300 points

Problem Statement

We have N switches with "on" and "off" state, and M bulbs. The switches are numbered 1 to N, and the bulbs are numbered 1 to M.

Bulb i is connected to k_i switches: Switch s_{i1}, s_{i2}, ..., and s_{ik_i}. It is lighted when the number of switches that are "on" among these switches is congruent to p_i modulo 2.

How many combinations of "on" and "off" states of the switches light all the bulbs?

Constraints

1 \leq N, M \leq 10

1 \leq k_i \leq N

1 \leq s_{ij} \leq N

s_{ia} \neq s_{ib} (a \neq b)

p_i is 0 or 1.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
k_1 s_{11} s_{12} ... s_{1k_1}
:
k_M s_{M1} s_{M2} ... s_{Mk_M}
p_1 p_2 ... p_M

Output

Print the number of combinations of "on" and "off" states of the switches that light all the bulbs.

Sample Input 1

2 2
2 1 2
1 2
0 1

Sample Output 1

1

Bulb 1 is lighted when there is an even number of switches that are "on" among the following: Switch 1 and 2.

Bulb 2 is lighted when there is an odd number of switches that are "on" among the following: Switch 2.

There are four possible combinations of states of (Switch 1, Switch 2): (on, on), (on, off), (off, on) and (off, off). Among them, only (on, on) lights all the bulbs, so we should print 1.

Sample Input 2

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

Sample Output 2

0

Bulb 1 is lighted when there is an even number of switches that are "on" among the following: Switch 1 and 2.

Bulb 2 is lighted when there is an even number of switches that are "on" among the following: Switch 1.

Bulb 3 is lighted when there is an odd number of switches that are "on" among the following: Switch 2.

Switch 1 has to be "off" to light Bulb 2 and Switch 2 has to be "on" to light Bulb 3, but then Bulb 1 will not be lighted. Thus, there are no combinations of states of the switches that light all the bulbs, so we should print 0.

Sample Input 3

5 2
3 1 2 5
2 2 3
1 0

Sample Output 3

8


package main

import (
    "fmt"
)

func main() {
    var n, m int
    fmt.Scan(&n, &m)
    ls := make([]int, m)
    for i := 0; i < m; i++ {
        var k int
        fmt.Scan(&k)
        var sb int
        for j := 0; j < k; j++ {
            var s uint
            fmt.Scan(&s)
            s--
            sb |= 1 << s
        }
        ls[i] = sb
    }
    ps := make([]int, m)
    for i := 0; i < m; i++ {
        var p int
        fmt.Scan(&p)
        ps[i] = p
    }
    var sc int
    for i := 0; i < 1<<uint(n); i++ {
        var ng bool
        for j := 0; j < m; j++ {
            so := ls[j] & i
            var cnt int
            for l := 0; l < n; l++ {
                if so&(1<<uint(l)) > 0 {
                    cnt++
                }
            }
            if cnt%2 != ps[j] {
                ng = true
            }
        }
        if !ng {
            sc++
        }
    }
    fmt.Println(sc)
}


package main

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

func main() {
	scan_init()
	a := scanInt()
	b := scanInt()
	if 6 <= a &&  a <= 12 {
		fmt.Println(b/2)
	} else {
		if a <= 5 {
			fmt.Println(0)
		} else {
			fmt.Println(b)
		}
	}
}

var sc = bufio.NewScanner(os.Stdin)

func scan_init() {
	sc.Split(bufio.ScanWords)
}
func scanInt() int {
	sc.Scan()
	i, _ := strconv.Atoi(sc.Text())
	return i
}
func scan() string {
	sc.Scan()
	return sc.Text()
}

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

func readLine() string {
	buf := make([]byte, 0, 200000)
	for {
		l, p, e := rdr.ReadLine()
		if e != nil {
			panic(e)
		}
		buf = append(buf, l...)
		if !p {
			break
		}
	}
	return string(buf)
}
func readLineToNumber() int {
	S := readLine()
	number, _ := strconv.Atoi(S)
	return number
}
func readLineToSlice() []string {
	S := readLine()
	list := strings.Split(S, "")
	return list
}
func readLineToNumberSlice(memo map[string]int) []int {
	// err時は-1を代入
	S := readLine()
	intList := make([]int, len(S))
	for i := 0; i < len(S); i++ {
		if val, ok := memo[string(S[i])]; ok {
			intList[i] = val
		} else {
			intList[i] = -1
		}
	}
	return intList
}

Score : 100 points

Problem Statement

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

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

Find the cost of the Ferris wheel for Takahashi.

Constraints

0 ≤ A ≤ 100

2 ≤ B ≤ 1000

B is an even number.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the cost of the Ferris wheel for Takahashi.

Sample Input 1

30 100

Sample Output 1

100

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

Sample Input 2

12 100

Sample Output 2

50

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

Sample Input 3

0 100

Sample Output 3

0

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


package main

import (
	"fmt"
)

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

	var ans int
	if 6 <= A && A <= 12 {
		ans = B / 2
	} else if 12 < A {
		ans = B
	}
	fmt.Println(ans)
}


package main

import (
  "fmt"
)

func main() {

  var a, b int

  fmt.Scan(&a, &b)

  if a > 12 {
    fmt.Println(b)
  } else if a >= 6  {
    fmt.Println(b / 2)
  } else {
    fmt.Println(0)
  }

}


package main

import "fmt"

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

	if a >= 13 {
		fmt.Println(b)
	} else if a >= 6 && a <= 12 {
		fmt.Println(b / 2)
	} else {
		fmt.Println(0)
	}
}


package main

import (
	"fmt"
)

func main() {
	var r,d,x2000 int
	fmt.Scan(&r,&d,&x2000)

	x := make([]int, 11)
	x[0] = r*x2000 - d
	fmt.Println(x[0])
	for i:=1; i<10; i++ {
		x[i] = r*x[i-1] - d
		fmt.Println(x[i])
	}
}

Score : 200 points

Problem Statement

The development of algae in a pond is as follows.

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

x_{i+1} = rx_i - D

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

Constraints

2 ≤ r ≤ 5

1 ≤ D ≤ 100

D < x_{2000} ≤ 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r D x_{2000}

Output

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

Sample Input 1

2 10 20

Sample Output 1

30
50
90
170
330
650
1290
2570
5130
10250

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

Sample Input 2

4 40 60

Sample Output 2

200
760
3000
11960
47800
191160
764600
3058360
12233400
48933560


package main

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

const (
	initialBufSize = 100000
	maxBufSize     = 1000000
)

var sc *bufio.Scanner

func initScanner(r io.Reader) *bufio.Scanner {
	buf := make([]byte, initialBufSize)

	sc := bufio.NewScanner(r)
	sc.Buffer(buf, maxBufSize)
	sc.Split(bufio.ScanWords) // bufio.ScanLines
	return sc
}

func main() {
	sc = initScanner(os.Stdin)
	fmt.Println(resolve(parseProblem()))
}

func parseProblem() int {
	n, m := scanInt(sc), scanInt(sc)
	lmax, rmin := 1, math.MaxInt32
	for i := 0; i < m; i++ {
		l, r := scanInt(sc), scanInt(sc)
		if lmax < l {
			lmax = l
		}
		if r < rmin {
			rmin = r
		}
	}
	return max(0, min(n, rmin)-lmax+1)
}
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

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

func resolve(n int) int {
	return n
}

// snip-scan-funcs
func scanInt(sc *bufio.Scanner) int {
	sc.Scan()
	i, _ := strconv.Atoi(sc.Text())
	return int(i)
}
func scanString(sc *bufio.Scanner) string {
	sc.Scan()
	return sc.Text()
}

Score : 300 points

Problem Statement

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

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

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

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq L_i \leq R_i \leq N

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1
L_2 R_2
\vdots
L_M R_M

Output

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

Sample Input 1

4 2
1 3
2 4

Sample Output 1

2

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

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

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

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

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

Sample Input 2

10 3
3 6
5 7
6 9

Sample Output 2

1

Sample Input 3

100000 1
1 100000

Sample Output 3

100000


package main

import (
	"fmt"
)

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

	left := 1
	right := N
	var L, R int
	for i := 0; i < M; i++ {
		fmt.Scan(&L, &R)
		if left < L {
			left = L
		}
		if R < right {
			right = R
		}
	}

	ans := 0
	if left <= right {
		ans = right - left + 1
	}
	fmt.Println(ans, left, right)
}

/*
1234
ooox
xooo
ooxx

xxoo
ooxx

oooo
*/


package main

import "fmt"

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

	var re int
	gate := map[int]int{}

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

	for j := 1; j <= n; j++ {
		var valid bool
		for l, r := range gate {
			if l > j || r < j {
				valid = true
				break
			}
		}
		if !valid {
			re++
		}
	}
	fmt.Println(re)
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

func main() {
	sc.Split(bufio.ScanWords)
	sc.Scan()
	S := sc.Text()
	head, _ := strconv.Atoi(S[:2])
	tail, _ := strconv.Atoi(S[2:])
	if head > 12 {
		if tail > 12 {
			fmt.Printf("NA")
		} else {
			fmt.Printf("YYMM")
		}
	} else {
		if tail > 12 {
			fmt.Printf("MMYY")
		} else {
			fmt.Printf("AMBIGUOUS")
		}
	}
}

Score : 200 points

Problem Statement

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

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

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

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

Constraints

S is a digit sequence of length 4.

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

1905

Sample Output 1

YYMM

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

Sample Input 2

0112

Sample Output 2

AMBIGUOUS

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

Sample Input 3

1700

Sample Output 3

NA

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


package main

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

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

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

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

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


package main

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

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

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

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

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


package main

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

func isMonth(n int) bool {
	return 1 <= n && n <= 12
}

func main() {

	stdin := bufio.NewScanner(os.Stdin)

	// 一行目
	stdin.Scan()
	line1 := stdin.Text()
	head, _ := strconv.Atoi(line1[0:2])
	tail, _ := strconv.Atoi(line1[2:4])

	if isMonth(head) && isMonth(tail) {
		fmt.Println("AMBIGUOUS")
	} else if isMonth(head) {
		fmt.Println("MMYY")
	} else if isMonth(tail) {
		fmt.Println("YYMM")
	} else {
		fmt.Println("NA")
	}
}


package main

import (
	"fmt"
	"strconv"
)

func main() {
	var S string
	fmt.Scan(&S)
	Fint, _ := strconv.Atoi(S[0:2])
	Sint, _ := strconv.Atoi(S[2:4])
	if Fint == 0 && Sint == 0 {
		fmt.Println("NA")
		return
	}
	if Fint > 12 && Sint > 12 {
		fmt.Println("NA")
		return
	}
	if Fint <= 12 && Sint <= 12 {
		if Fint == 0 {
			fmt.Println("YYMM")
			return
		}
		if Sint == 0 {
			fmt.Println("MMYY")
			return
		}
		fmt.Println("AMBIGUOUS")
	} else if Fint <= 12 && Sint > 12 {
		fmt.Println("MMYY")
	} else if Fint > 12 && Sint <= 12 {
		fmt.Println("YYMM")
	}
}


package main

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

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

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

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

	scanner := bufio.NewReader(fp)

	s := getNextLine(scanner)
	part1, _ := strconv.Atoi(s[0:2])
	part2, _ := strconv.Atoi(s[2:])
	if part1 == 0 || part2 == 0 {
		fmt.Println("NA")
		return
	}
	if part1 > 12 && part2 > 12 {
		fmt.Println("NA")
		return
	}
	if part1 > 12 && part2 <= 12 {
		fmt.Println("YYMM")
		return
	}
	if part2 > 12 && part1 <= 12 {
		fmt.Println("MMYY")
		return
	}
	fmt.Println("AMBIGUOUS")
}


package main

import (
	"fmt"
)

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

	ans := 0.0
	for i := 1; i <= n; i++ {
		score := i
		cal := 1.0 / float64(n)
		for score < k {
			score *= 2
			cal *= 0.5
		}
		ans += cal
	}
	fmt.Print(ans)
}

Score : 300 points

Problem Statement

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

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

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

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

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

Constraints

1 ≤ N ≤ 10^5

1 ≤ K ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

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

Sample Input 1

3 10

Sample Output 1

0.145833333333

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

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

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

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

Sample Input 2

100000 5

Sample Output 2

0.999973749998


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

func main() {
	N := oneInt()
	K := oneInt()
	var temp = asK(K) - 1
	var result float64
	result = 0.5
	for index := 0; index < temp - 1; index++ {
		result += 0.5 * result
	}
	result = float64(1/N) * result
	fmt.Printf("%f",result)
}

func asK(val int) int {
	var count int
	var kaijo int
	kaijo = 1
	count = 0
	for {
		if kaijo > val {
			return count
		}
		kaijo = kaijo * 2
		count++
	}
}


package main

import "fmt"

func main() {
	var n, k int
	fmt.Scan(&n, &k)
	ans := float64(0)
	for i := 1; i <= n; i++ {
		bnb := n
		sum := i
		for sum < k {
			bnb *= 2
			sum *= 2
		}
		ans += float64(1) / float64(bnb)
	}
	fmt.Println(ans)
}


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 dfs(v, c int) bool {
	colors[v] = c
	for _, nextv := range G[v] {
		if colors[nextv.to] != -1 {
			if colors[nextv.to] == c {
				if nextv.cost%2 == 0 {
					return true
				}
				return false
			}

			continue
		}

		if !dfs(nextv.to, 1-c) {
			return false
		}
	}
	return true
}

type edge struct {
	to   int
	cost int
}

var G [][]edge
var N int
var colors []int

func main() {
	sc.Split(bufio.ScanWords)
	N = nextInt()
	G = make([][]edge, N)
	for i := 0; i < N; i++ {
		G[i] = make([]edge, 0)
	}
	colors = make([]int, N)
	for i := 0; i < N; i++ {
		colors[i] = -1
	}

	for i := 0; i < N-1; i++ {
		u, v, w := nextInt()-1, nextInt()-1, nextInt()
		G[u] = append(G[u], edge{to: v, cost: w})
		G[v] = append(G[v], edge{to: u, cost: w})
	}

	for i := 0; i < N; i++ {
		if colors[i] != -1 {
			continue
		}
		dfs(i, 0)
	}

	for _, c := range colors {
		fmt.Println(c)
	}
}

Score : 400 points

Problem Statement

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

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

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

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq u_i < v_i \leq N

1 \leq w_i \leq 10^9

Input

Input is given from Standard Input in the following format:

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

Output

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

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

Sample Input 1

3
1 2 2
2 3 1

Sample Output 1

0
0
1

Sample Input 2

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

Sample Output 2

1
0
1
0
1


package main

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

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

// IO helper functions

// Returns next token from input.  It must be initialized by SetInput()
// before the first call.
var nextToken func() ([]byte, error)
var nextLine func() ([]byte, error)

// Holds a buffer for output.  It must be initialized by SetOutput().
// All IO fucntions (read*() and [e]print*()) should write to OutputWriter
// instead of this.
var OutputBuffer *bufio.Writer

// Holds an io.Writer.  It must be initialized by SetOutput()
var OutputWriter io.Writer

// Set IO functions for interactive input/output.
func SetInteractive(w io.Writer, r io.Reader) {
	SetUnbefferedInput(r)
	OutputBuffer = nil
	OutputWriter = w
}

// Setup OutputBuffer and OutputWriter.
func SetOutput(w io.Writer) {
	OutputBuffer = bufio.NewWriter(w)
	OutputWriter = OutputBuffer
}

// Flushes OutputBuffer
func Flush() {
	if OutputBuffer != nil {
		OutputBuffer.Flush()
	}
}

// Returns true if c is a white space
func IsSpace(c byte) bool {
	switch c {
	case '\t', '\n', '\v', '\f', '\r', ' ':
		return true
	}
	return false
}

func IsNewLine(c byte) bool {
	switch c {
	case '\n', '\r':
		return true
	}
	return false
}

// Setup nextToken with input buffer.
func SetInput(r io.Reader) {
	buf := new(bytes.Buffer)
	var b []byte

	var i int
	rest := func() ([]byte, error) {
		for i < len(b) && IsSpace(b[i]) {
			i++
		}
		if i == len(b) {
			return nil, io.ErrUnexpectedEOF
		}
		j := i
		for i < len(b) && !IsSpace(b[i]) {
			i++
		}
		return b[j:i], nil
	}
	initial := func() ([]byte, error) {
		io.Copy(buf, r)
		b = buf.Bytes()
		nextToken = rest
		return rest()
	}
	nextToken = initial

	restLn := func() ([]byte, error) {
		for i < len(b) && IsNewLine(b[i]) {
			i++
		}
		if i == len(b) {
			return nil, io.ErrUnexpectedEOF
		}
		j := i
		for i < len(b) && !IsNewLine(b[i]) {
			i++
		}
		return b[j:i], nil
	}

	initialLn := func() ([]byte, error) {
		io.Copy(buf, r)
		b = buf.Bytes()
		nextLine = restLn
		return restLn()
	}
	nextLine = initialLn
}

// Setup nextToken without input buffer.
func SetUnbefferedInput(r io.Reader) {
	buf := bufio.NewReader(r)
	var b []byte

	var i int
	nextToken = func() ([]byte, error) {
		var err error
		if i == len(b) {
			b, err = buf.ReadBytes('\n')
			if err != nil {
				return nil, err
			}
			i = 0
			j := len(b) - 1
			for 0 <= j && IsSpace(b[j]) {
				j--
			}
			b = b[0 : j+1]
		}
		for i < len(b) && IsSpace(b[i]) {
			i++
		}
		j := i
		for i < len(b) && !IsSpace(b[i]) {
			i++
		}
		if i == j {
			return nil, io.ErrUnexpectedEOF
		}
		return b[j:i], nil
	}
}

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

// IO functions

// Reads next token and return it as []byte
func readb() []byte {
	b, err := nextToken()
	if err != nil {
		panic(err)
	}
	return b
}

// Reads next token and return it as string
func reads() string {
	return string(readb())
}

// Read next line as []byte
func readbln() []byte {
	b, err := nextLine()
	if err != nil {
		panic(err)
	}
	return b
}

// Read next line as string
func readsln() string {
	return string(readbln())
}

// Reads next token and return it as int64
func readll() int64 {
	i, err := strconv.ParseInt(reads(), 10, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// Reads next token and return it as int
func readi() int {
	return int(readll())
}

// Reads next token and return it as float64
func readf() float64 {
	f, err := strconv.ParseFloat(reads(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// Write args to OutputWriter with the format f
func printf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(OutputWriter, f, args...)
}

// Write args to OutputWriter without format
func println(args ...interface{}) (int, error) {
	return fmt.Fprintln(OutputWriter, args...)
}

// Write args to stderr with the format f
func eprintf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(os.Stderr, f, args...)
}

// Write args to stderr without format
func eprintln(args ...interface{}) (int, error) {
	return fmt.Fprintln(os.Stderr, args...)
}

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

// Simple math functions

const (
	// big prime
	INF  = 1000000007
	INF2 = 1000000009
	INF3 = 998244353
)

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

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

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

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

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

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

// egcd(a, b) returns d, x, y:
//   d is gcd(a,b)
//   x, y are  integers that satisfy ax + by = d
func egcd(a, b int) (int, int, int) {
	if b == 0 {
		return a, 1, 0
	}
	d, x, y := egcd(b, a%b)
	return d, y, x - a/b*y
}

func egcdll(a, b int64) (int64, int64, int64) {
	if b == 0 {
		return a, 1, 0
	}
	d, x, y := egcdll(b, a%b)
	return d, y, x - a/b*y
}

func gcd(a, b int) int {
	d, _, _ := egcd(a, b)
	return d
}

func gcdll(a, b int64) int64 {
	d, _, _ := egcdll(a, b)
	return d
}

// set up IO functions
func init() {
	// for non-interactive
	SetInput(os.Stdin)
	SetOutput(os.Stdout)

	// Enable below when interactive.  Its ok to leave above intact.
	// SetInteractive(os.Stdout, os.Stdin)
}

func main() {
	defer Flush()

	N := readi()
	M := readi()

	uf := NewUnionFind(N)
	for i := 0; i < M; i++ {
		x := readi() - 1
		y := readi() - 1
		_ = readi()
		uf.Union(x, y)
	}
	var ans int
	counted := make([]bool, N)
	for i := range counted {
		p := uf.Find(i)
		if !counted[p] {
			counted[p] = true
			ans++
		}
	}
	println(ans)
}

type UnionFind struct {
	parent []int
	rank   []int
	size   []int
}

// Initialize UnionFind for [0, n) elements.
// If you need [1, n] items, use NewUnionFind(n+1) then ignore 0.
func NewUnionFind(n int) *UnionFind {
	u := &UnionFind{
		parent: make([]int, n),
		rank:   make([]int, n),
		size:   make([]int, n),
	}

	for i := range u.parent {
		u.parent[i] = i
		u.rank[i] = 0
		u.size[i] = 1
	}

	return u
}

func (u *UnionFind) Find(i int) int {
	if u.parent[i] == i {
		return i
	}
	p := u.Find(u.parent[i])
	u.parent[i] = p
	return p
}

func (u *UnionFind) Union(i, j int) {
	p := u.Find(i)
	q := u.Find(j)

	if p == q {
		return
	}

	if u.rank[p] < u.rank[q] {
		p, q = q, p
	}
	u.parent[p] = q
	if u.rank[p] == u.rank[q] {
		u.rank[q]++
	}
	u.size[q] += u.size[p]
}

func (u *UnionFind) Size(i int) int {
	p := u.Find(i)
	return u.size[p]
}

Score : 500 points

Problem Statement

There are N cards placed face down in a row. On each card, an integer 1 or 2 is written.

Let A_i be the integer written on the i-th card.

Your objective is to guess A_1, A_2, ..., A_N correctly.

You know the following facts:

For each i = 1, 2, ..., M, the value A_{X_i} + A_{Y_i} + Z_i is an even number.

You are a magician and can use the following magic any number of times:

Magic: Choose one card and know the integer A_i written on it. The cost of using this magic is 1.

What is the minimum cost required to determine all of A_1, A_2, ..., A_N?

It is guaranteed that there is no contradiction in given input.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq X_i < Y_i \leq N

1 \leq Z_i \leq 100

The pairs (X_i, Y_i) are distinct.

There is no contradiction in input. (That is, there exist integers A_1, A_2, ..., A_N that satisfy the conditions.)

Input

Input is given from Standard Input in the following format:

N M
X_1 Y_1 Z_1
X_2 Y_2 Z_2
\vdots
X_M Y_M Z_M

Output

Print the minimum total cost required to determine all of A_1, A_2, ..., A_N.

Sample Input 1

3 1
1 2 1

Sample Output 1

2

You can determine all of A_1, A_2, A_3 by using the magic for the first and third cards.

Sample Input 2

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

Sample Output 2

2

Sample Input 3

100000 1
1 100000 100

Sample Output 3

99999


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

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

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

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

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

func main() {
	n := scanInt()
	ans := 0
	cab, ca, cb := 0, 0, 0
	for i := 0; i < n; i++ {
		s := scanString()
		ans += strings.Count(s, "AB")
		if s[0] == 'B' && s[len(s)-1] == 'A' {
			cab++
		} else if s[0] == 'B' {
			cb++
		} else if s[len(s)-1] == 'A' {
			ca++
		}
	}
	if ca > 0 && cab > 0 {
		ca--
		ans++
	}
	if cb > 0 && cab > 0 {
		cb--
		ans++
	}
	if cab > 0 {
		ans += cab - 1
	}
	ans += min(ca, cb)
	fmt.Println(ans)
}

Score : 400 points

Problem Statement

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

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

Constraints

1 \leq N \leq 10^{4}

2 \leq |s_i| \leq 10

s_i consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
s_1
\vdots
s_N

Output

Print the answer.

Sample Input 1

3
ABCA
XBAZ
BAD

Sample Output 1

2

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

Sample Input 2

9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA

Sample Output 2

4

Sample Input 3

7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA

Sample Output 3

4


package main

import (
	"fmt"
	"strings"
)

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

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

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


package main

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

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

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

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

	scanner := bufio.NewReader(fp)

	var n int

	fmt.Sscan(getNextLine(scanner), &n)
	bstart := 0
	aend := 0
	both := 0
	ans := 0
	for i := 0; i < n; i++ {
		s := getNextLine(scanner)
		if s[0] == 'B' {
			bstart++
		}
		if s[len(s)-1] == 'A' {
			aend++
		}
		if s[0] == 'B' && s[len(s)-1] == 'A' {
			both++
		}
		for j := 1; j < len(s); j++ {
			if s[j-1] == 'A' && s[j] == 'B' {
				ans++
			}
		}
	}
	ans += minint(minint(bstart, aend), n-1)
	if bstart == aend && bstart == both && n > both {
		ans--
	}
	fmt.Println(ans)
}
func minint(a int, b int) int {
	if a < b {
		return a
	}
	return b
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

const inf = 1 << 60

func ri() (n int) {
	sc.Scan()
	for _, v := range sc.Bytes() {
		n = n*10 + int(v-48)
	}
	return
}

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

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

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

	var s string
	ctAB, ctTailA, ctHeadB, ctTailAHeadB := 0, 0, 0, 0
	for i := 0; i < n; i++ {
		s = rs()
		for j := 0; j < len(s)-1; j++ {
			if s[j] == 'A' && s[j+1] == 'B' {
				ctAB++
			}
		}
		if s[len(s)-1] == 'A' {
			ctTailA++
		}
		if s[0] == 'B' {
			ctHeadB++
		}
		if s[len(s)-1] == 'A' && s[0] == 'B' {
			ctTailAHeadB++
		}
	}

	ans := -1
	ans = ctAB + smaller(ctTailA, ctHeadB)
	if ctTailAHeadB != 0 && ctTailAHeadB == ctTailA && ctTailAHeadB == ctHeadB {
		ans--
	}
	fmt.Println(ans)
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	var result int
	if sumOfAB > 0 {
		result = result - 1
	}

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

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

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

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

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


package main

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

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

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

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

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

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

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

	n := scanInt()
	ans := 0
	for i := 1; i*i <= n; i++ {
		if n%i == 0 && i < n/i-1{
			ans += n/i-1
		}
	}

	fmt.Fprintln(wr, ans)
}

Score : 500 points

Problem Statement

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

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

Find all favorite numbers and print the sum of those.

Constraints

All values in input are integers.

1 \leq N \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

8

Sample Output 1

10

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

Sample Input 2

1000000000000

Sample Output 2

2499686339916

Watch out for overflow.


package main

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

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

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

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

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

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

// ReadInt returns an integer.
func ReadInt() int {
	return int(readInt64())
}

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

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

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

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

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

	res := 0

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

	return res
}

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

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

	return s
}

// CeilInt returns the minimum integer larger than or equal to float(a/b).
func CeilInt(a, b int) int {
	res := a / b
	if a%b > 0 {
		res++
	}
	return res
}

// FloorInt returns the maximum integer smaller than or equal to float(a/b)
func FloorInt(a, b int) int {
	res := a / b
	return res
}

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

	if e == 0 {
		return 1
	}

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

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

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

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

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

	return a
}

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

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

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

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

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

//str := ReadString()
//i := ReadInt()
//X := ReadIntSlice(n)
//S := ReadRuneSlice()

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

const MOD = 1000000000 + 7
const ALPHABET_NUM = 26

var n int

func main() {
	n = ReadInt()

	ans := 0
	for a := 1; a*a+a < n; a++ {
		m := n/a - 1
		if n%a == 0 {
			ans += m
		}
	}

	fmt.Println(ans)
}

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

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


package main

import "fmt"

func main() {
	var h, w, n, sr, sc int
	var s, t string
	fmt.Scan(&h, &w, &n, &sr, &sc, &s, &t)

	ans := "YES"

	ri := w
	li := 1
	for i := n - 1; i >= 0; i-- {
		if t[i] == 'L' && ri < w {
			ri++
		} else if t[i] == 'R' && li > 1 {
			li--
		}
		if s[i] == 'L' {
			li++
		} else if s[i] == 'R' {
			ri--
		}
		if li > ri {
			ans = "NO"
			break
		}
	}
	if sc < li || ri < sc {
		ans = "NO"
	}

	di := h
	ui := 1
	for i := n - 1; i >= 0; i-- {
		if t[i] == 'U' && di < h {
			di++
		} else if t[i] == 'D' && ui > 1 {
			ui--
		}
		if s[i] == 'U' {
			ui++
		} else if s[i] == 'D' {
			di--
		}
		if ui > di {
			ans = "NO"
			break
		}
	}
	if sr < ui || di < sr {
		ans = "NO"
	}

	fmt.Println(ans)
}

Score : 600 points

Problem Statement

We have a rectangular grid of squares with H horizontal rows and W vertical columns. Let (i,j) denote the square at the i-th row from the top and the j-th column from the left.
On this grid, there is a piece, which is initially placed at square (s_r,s_c).

Takahashi and Aoki will play a game, where each player has a string of length N.
Takahashi's string is S, and Aoki's string is T. S and T both consist of four kinds of letters: L, R, U and D.

The game consists of N steps. The i-th step proceeds as follows:

First, Takahashi performs a move. He either moves the piece in the direction of S_i, or does not move the piece.

Second, Aoki performs a move. He either moves the piece in the direction of T_i, or does not move the piece.

Here, to move the piece in the direction of L, R, U and D, is to move the piece from square (r,c) to square (r,c-1), (r,c+1), (r-1,c) and (r+1,c), respectively. If the destination square does not exist, the piece is removed from the grid, and the game ends, even if less than N steps are done.

Takahashi wants to remove the piece from the grid in one of the N steps.
Aoki, on the other hand, wants to finish the N steps with the piece remaining on the grid.
Determine if the piece will remain on the grid at the end of the game when both players play optimally.

Constraints

2 \leq H,W \leq 2 \times 10^5

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

1 \leq s_r \leq H

1 \leq s_c \leq W

|S|=|T|=N

S and T consists of the four kinds of letters L, R, U and D.

Input

Input is given from Standard Input in the following format:

H W N
s_r s_c
S
T

Output

If the piece will remain on the grid at the end of the game, print YES; otherwise, print NO.

Sample Input 1

2 3 3
2 2
RRL
LUD

Sample Output 1

YES

Here is one possible progress of the game:

Takahashi moves the piece right. The piece is now at (2,3).

Aoki moves the piece left. The piece is now at (2,2).

Takahashi does not move the piece. The piece remains at (2,2).

Aoki moves the piece up. The piece is now at (1,2).

Takahashi moves the piece left. The piece is now at (1,1).

Aoki does not move the piece. The piece remains at (1,1).

Sample Input 2

4 3 5
2 2
UDRRR
LLDUD

Sample Output 2

NO

Sample Input 3

5 6 11
2 1
RLDRRUDDLRL
URRDRLLDLRD

Sample Output 3

NO


package main

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

var reader = bufio.NewReaderSize(os.Stdin, 1000000)
func NextLine() string {
  var line, buffer []byte
  var isPrefix bool = true
  var err error
  for isPrefix {
    line, isPrefix, err = reader.ReadLine()
    if err != nil { panic(err) }
    buffer = append(buffer, line...)
  }
  return string(buffer)
}
func NextInt() int {
  var n int
  n, _ = strconv.Atoi(NextLine())
  return n
}
func NextIntVec() []int {
  L := strings.Split(NextLine(), " ")
  N := make([]int, len(L))
  for i := range N {
    N[i], _ = strconv.Atoi(L[i])
  }
  return N
}

func dijkstra(E *[][]int, s int) (D []int) {
  N := len((*E))
  D = make([]int, N)
  for i := 0; i < N; i++ {
    if i != s {
      D[i] = -1
    }
  }
  Q := make([]int, N)
  Q[0] = s
  var v int
  pos := 1
  for i := 0; i < N; i++ {
    v = Q[i]
    for _, adj := range (*E)[v] {
      if D[adj] >= 0 {
        continue
      }
      D[adj] = D[v] + 1
      Q[pos] = adj
      pos += 1
    }
  }
  return
}

func max(A *[]int) (i, a int) {
  i = 0
  a = (*A)[0]
  for _i, _a := range (*A) {
    if _a > a {
      a = _a
      i = _i
    }
  }
  return
}

func main() {
  var N int
  N = NextInt()
  E := make([][]int, N)
  for i := range E {
    E[i] = make([]int, 0)
  }
  var a, b int
  for i := 0; i < N - 1; i++ {
    ab := NextIntVec()
    a = ab[0]
    b = ab[1]
    E[a - 1] = append(E[a - 1], b - 1)
    E[b - 1] = append(E[b - 1], a - 1)
  }
  D0 := dijkstra(&E, 0)
  s, _ := max(&D0)
  D1 := dijkstra(&E, s)
  _, L := max(&D1)
  if L % 3 != 1 {
    fmt.Println("First")
  } else {
    fmt.Println("Second")
  }
}

Score : 800 points

Problem Statement

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

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

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

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

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

Constraints

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

1 \leq a_i, b_i \leq N

a_i \neq b_i

The graph given as input is a tree.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

3
1 2
2 3

Sample Output 1

First

Here is one possible progress of the game:

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

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

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

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

Sample Input 2

6
1 2
2 3
2 4
4 6
5 6

Sample Output 2

Second

Sample Input 3

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

Sample Output 3

First


package main

import "fmt"

// import "fmt"
func readline(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}
	return a
}

func main() {
	v := readline(3)
	a := v[0]
	b := v[1]
	t := v[2]
	res := (t / a) * b
	fmt.Println(res)
}

Score : 100 points

Problem Statement

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

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

Constraints

All values in input are integers.

1 \leq A, B, T \leq 20

Input

Input is given from Standard Input in the following format:

A B T

Output

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

Sample Input 1

3 5 7

Sample Output 1

10

Five biscuits will be produced three seconds after activation.

Another five biscuits will be produced six seconds after activation.

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

Sample Input 2

3 2 9

Sample Output 2

6

Sample Input 3

20 20 19

Sample Output 3

0


package main

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

func stdioText(s *bufio.Scanner) string {
	s.Scan()
	return s.Text()
}

func stdioNum(s *bufio.Scanner) int {
	num, _ := strconv.Atoi(stdioText(s))
	return num
}

func stdioNums(s *bufio.Scanner) []int {
	var nums []int
	for _, v := range strings.Split(stdioText(s), " ") {
		i, _ := strconv.Atoi(v)
		nums = append(nums, i)
	}
	return nums
}

func main()  {
	s := bufio.NewScanner(os.Stdin)
	nums := stdioNums(s)
	fmt.Println(nums[2] / nums[0] * nums[1])
}


package main

import (
	"fmt"
)

func main() {
	var N, r int
	fmt.Scan(&N)
	va := make([]int, N)
	ca := make([]int, N)
	for i := range va {
		fmt.Scan(&va[i])
	}
	for i := range ca {
		fmt.Scan(&ca[i])
	}
	for i := 0; i < N; i++ {
		if va[i] > ca[i] {
			r += va[i] - ca[i]
		}
	}
	fmt.Println(r)
}

Score : 200 points

Problem Statement

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

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

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

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

Find the maximum possible value of X-Y.

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq C_i, V_i \leq 50

Input

Input is given from Standard Input in the following format:

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

Output

Print the maximum possible value of X-Y.

Sample Input 1

3
10 2 5
6 3 4

Sample Output 1

5

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

Sample Input 2

4
13 21 6 19
11 30 6 15

Sample Output 2

6

Sample Input 3

1
1
50

Sample Output 3

0


package main

import "fmt"

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

	sum := 0
	for i := 0; i < n; i++ {
		if v := vs[i] - cs[i]; v > 0 {
			sum += v
		}
	}
	fmt.Println(sum)
}


package main

import "fmt"

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

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

	var ans int
	for i := 0; i < n; i++ {
		if tmp := vs[i] - cs[i]; tmp > 0 {
			ans += tmp
		}
	}

	fmt.Println(ans)
}


package main

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

func makeabs(A []int) []int {
	for i := 0; i < len(A); i++ {
		A[i] = int(math.Abs(float64(A[i])))
	}
	return A
}

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

func minAbs(A []int) int {
	s := math.Abs(float64(A[0]))

	for i := 1; i < len(A); i++ {
		if t := math.Abs(float64(A[i])); t < s {
			s = t
		}
	}

	return int(s)
}

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

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

	sort.Sort(sort.Reverse(sort.IntSlice(A)))

	n_neg := 0
	for _, a := range A {
		if a < 0 {
			n_neg++
		}
	}

	if n_neg % 2 == 0 {
		fmt.Println(sum(makeabs(A)))
	} else {
		fmt.Println(sum(makeabs(A)) - 2 * minAbs(A))
	}
}

Score : 400 points

Problem Statement

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

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

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

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

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

Constraints

All values in input are integers.

2 \leq N \leq 10^5

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

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

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

Sample Input 1

3
-10 5 -4

Sample Output 1

19

If we perform the operation as follows:

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

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

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

Sample Input 2

5
10 -4 -8 -11 3

Sample Output 2

30

Sample Input 3

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

Sample Output 3

10000000000

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


package main

import "fmt"

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

func main() {
    var n int
    fmt.Scan(&n)
    a := make([]int64, n)
    for i := 0; i < n; i++ {
        fmt.Scan(&a[i])
    }
    var ans int64 = 0
    var min_a int64 = 1000000007
    var min_i int
    for i, v := range a {
        v = abs(v)
        if min_a > v {
            min_i = i
            min_a = v
        }
    }
    for i := 0; i < min_i; i++ {
        if a[i] < 0 {
            a[i] *= -1
            a[i + 1] *= -1
        }
    }
    for i := n - 1; i > min_i; i-- {
        if a[i] < 0 {
            a[i] *= -1
            a[i - 1] *= -1
        }
    }
    for _, v := range a {
        ans += v
    }
    fmt.Println(ans)
}


package main

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

func main() {
	n := nextInt()
	s := nextString()
	if len(s) != n {
		fmt.Println(s[n-1])
	}
	s1 := []byte(s)
	s2 := []byte(s)
	cnt1 := 0
	cnt2 := 0
	for i := 0; i < n-1; i++ {
		if s1[i] == '#' && s1[i+1] == '.' {
			s1[i] = '.'
			cnt1++
			for j := i - 1; j >= 0; j-- {
				if s1[j] == '#' && s1[j+1] == '.' {
					s1[j] = '.'
					cnt1++
				} else {
					break
				}
			}
		}
	}
	for i := 0; i < n-1; i++ {
		if s2[i] == '#' && s2[i+1] == '.' {
			s2[i+1] = '#'
			cnt2++
		}
	}
	log.Println(cnt1, string(s1))
	log.Println(cnt2, string(s2))
	fmt.Println(min(cnt1, cnt2))
}

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

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

func lcm(a, b int) int {
	return a * b / gcd(a, b)
}
func gcd(a, b int) int {
	if a < b {
		a, b = b, a
	}
	for b != 0 {
		a, b = b, a%b
	}
	return a
}
func max(a ...int) int {
	r := a[0]
	for i := 0; i < len(a); i++ {
		if r < a[i] {
			r = a[i]
		}
	}
	return r
}
func min(a ...int) int {
	r := a[0]
	for i := 0; i < len(a); i++ {
		if r > a[i] {
			r = a[i]
		}
	}
	return r
}
func sum(a []int) (r int) {
	for i := range a {
		r += a[i]
	}
	return r
}
func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

type pair struct {
	a, b int
}

type pairs []pair

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

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

var nextReader func() []byte

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

func newScanner() func() []byte {
	r := bufio.NewScanner(os.Stdin)
	r.Buffer(make([]byte, 10000), int(1000000))
	r.Split(bufio.ScanWords)
	return func() []byte {
		r.Scan()
		return r.Bytes()
	}
}
func nextBytes() []byte {
	return nextReader()
}

func nextString() string {
	return string(nextReader())
}
func nextInt64() int64 {
	v, _ := strconv.ParseInt(string(nextReader()), 10, 64)
	return v
}
func nextInt() int {
	v, _ := strconv.Atoi(string(nextReader()))
	return v
}
func nextInts(n int) []int {
	r := make([]int, n)
	for i := 0; i < n; i++ {
		r[i] = nextInt()
	}
	return r
}
func nextFloat64() float64 {
	f, _ := strconv.ParseFloat(string(nextReader()), 64)
	return f
}

Score : 300 points

Problem Statement

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

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

Constraints

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

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

Input

Input is given from Standard Input in the following format:

N
S

Output

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

Sample Input 1

3
#.#

Sample Output 1

1

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

Sample Input 2

5
#.##.

Sample Output 2

2

Sample Input 3

9
.........

Sample Output 3

0


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

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

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

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

func main() {
	sc.Split(bufio.ScanWords)
	a, b, c := nextInt(), nextInt(), nextInt()
	if (a < c && c < b) || (a > c && c > b) {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
}

Score : 100 points

Problem Statement

There are three houses on a number line: House 1, 2 and 3, with coordinates A, B and C, respectively.
Print Yes if we pass the coordinate of House 3 on the straight way from House 1 to House 2 without making a detour, and print No otherwise.

Constraints

0\leq A,B,C\leq 100

A, B and C are distinct integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print Yes if we pass the coordinate of House 3 on the straight way from House 1 to House 2 without making a detour, and print No otherwise.

Sample Input 1

3 8 5

Sample Output 1

Yes

We pass the coordinate 5 on the straight way from the house at coordinate 3 to the house at coordinate 8.

Sample Input 2

7 3 1

Sample Output 2

No

Sample Input 3

10 2 4

Sample Output 3

Yes

Sample Input 4

31 41 59

Sample Output 4

No


package main

import (
	"bufio"
	"fmt"
	"io"
	"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 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() int {
	var n int
	fmt.Scan(&n)
	return n
}

func ReadIntF(f io.Reader) int {
	var n int
	fmt.Fscanf(f, "%d", &n)
	return n
}

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

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

func ReadWord(f io.Reader) string {
	var str string
	fmt.Scan(&str)
	return str
}

func ReadWordF(f io.Reader) string {
	var str string
	fmt.Fscanf(f, "%s", &str)
	return str
}

func ReadLine() string {
	r := bufio.NewReader(os.Stdin)
	str, _ := r.ReadString('\n')
	str = strings.Trim(str, "\n")
	return str
}

func ReadLineF(f io.Reader) string {
	r := bufio.NewReader(f)
	str, _ := r.ReadString('\n')
	str = strings.Trim(str, "\n")
	return str
}

func ReadLines(n int) []string {
	r := bufio.NewReader(os.Stdin)
	lines := make([]string, n)
	for i := 0; i < n; i++ {
		lines[i], _ = r.ReadString('\n')
		lines[i] = strings.Trim(lines[i], "\n")
	}
	return lines
}

func ReadLinesF(f io.Reader, n int) []string {
	r := bufio.NewReader(f)
	lines := make([]string, n)
	for i := 0; i < n; i++ {
		lines[i], _ = r.ReadString('\n')
		lines[i] = strings.Trim(lines[i], "\n")
	}
	return lines
}

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

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 AllComb(n int) [][]int {
	n2 := 1 << uint(n)
	ret := make([][]int, n2)

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

func AllCombChan(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)
}

func PermuteInts(nums []int) [][]int {
	n := Factorial(len(nums))
	ret := make([][]int, 0, n)
	permuteInts(nums, &ret)
	return ret
}

func permuteInts(nums []int, ret *[][]int) {
	*ret = append(*ret, makeCopy(nums))

	n := len(nums)
	p := make([]int, n+1)
	for i := 0; i < n+1; i++ {
		p[i] = i
	}
	for i := 1; i < n; {
		p[i]--
		j := 0
		if i%2 == 1 {
			j = p[i]
		}

		nums[i], nums[j] = nums[j], nums[i]
		*ret = append(*ret, makeCopy(nums))
		for i = 1; p[i] == 0; i++ {
			p[i] = i
		}
	}
}

func makeCopy(nums []int) []int {
	return append([]int{}, nums...)
}

// }}}

func main() {
	a, b, c := ReadInt(), ReadInt(), ReadInt()
	if (c > a && c < b) || (c > b && c < a) {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
}


package main

import "fmt"

func main() {
	var n, k int
	var s string
	fmt.Scan(&n, &s, &k)
	c := s[k-1 : k]
	ans := ""
	for _, v := range s {
		if string(v) == c {
			ans += string(v)
		} else {
			ans += "*"
		}
	}
	fmt.Println(ans)
}

Score : 200 points

Problem Statement

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

Constraints

1 \leq K \leq N\leq 10

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

N and K are integers.

Input

Input is given from Standard Input in the following format:

N
S
K

Output

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

Sample Input 1

5
error
2

Sample Output 1

*rr*r

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

Sample Input 2

6
eleven
5

Sample Output 2

e*e*e*

Sample Input 3

9
education
7

Sample Output 3

******i**


package main

import (
	"fmt"
)

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

	const white, black = '.', '#'
	beforeColor, toBlackCount, toWhiteCount := '.', 0, 0
	for i := 0; i < n; i++ {
		currentColor := int32(s[i])
		if beforeColor == black && currentColor == white {
			toBlackCount++
			currentColor = black
		} else if currentColor == black && i != n - 1 {
			toWhiteCount++
		}
		beforeColor = currentColor
	}

	var result int
	if toBlackCount < toWhiteCount {
		result = toBlackCount
	} else {
		result = toWhiteCount
	}
	fmt.Print(result);
}