package main

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

func solution(a, b int) int {
	ab := make([]int, b)
	ba := make([]int, a)

	// aをb回
	for i := 0; i < b; i++ {
		ab[i] = a
	}
	// bをa回
	for i := 0; i < a; i++ {
		ba[i] = b
	}

	if dictionaryOrder(ab) < dictionaryOrder(ba) {
		return ints2int(ab)
	}
	return ints2int(ba)
}

func ints2int(nums []int) int {
	strs := make([]string, len(nums))

	for i := range nums {
		strs[i] = strconv.Itoa(nums[i])
	}
	ans, _ := strconv.Atoi(strings.Join(strs, ""))
	return ans
}

func dictionaryOrder(nums []int) int {
	var ans int
	l := len(nums)
	for i := 0; i < l; i++ {
		n := nums[i]
		arr := make([]int, len(nums)-i)
		copy(arr, nums[i:])
		a := ascNumber(arr, n) - 1
		if a == 0 {
			ans += 0
		} else {
			ans += a * factorical(l-i-1)
		}
	}
	ans++
	return ans
}

func ascNumber(nums []int, n int) int {
	sort.Ints(nums)
	var i int = 1
	for _, v := range nums {
		if v == n {
			break
		}
		i++
	}
	return i
}

func factorical(n int) int {
	if n == 0 || n == 1 {
		return 1
	}
	return n * factorical(n-1)
}

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


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
}

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

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

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

func main(){
	var N int
	var res,min int
	var P []int
	fmt.Scan(&N)
	for i:=0;i<N;i++{
		t:=0
		fmt.Scan(&t)
		P = append(P,t)
	}
	min=P[0]
	res=1

	for i:=1;i<N;i++{
		if P[i]<min {
			res++
			min=P[i]
		}
	}

	fmt.Println(res)
}

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

Score : 300 points

Problem Statement

Given is a permutation P_1, \ldots, P_N of 1, \ldots, N.
Find the number of integers i (1 \leq i \leq N) that satisfy the following condition:

For any integer j (1 \leq j \leq i), P_i \leq P_j.

Constraints

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

P_1, \ldots, P_N is a permutation of 1, \ldots, N.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1 ... P_N

Output

Print the number of integers i that satisfy the condition.

Sample Input 1

5
4 2 5 1 3

Sample Output 1

3

i=1, 2, and 4 satisfy the condition, but i=3 does not - for example, P_i > P_j holds for j = 1.

Similarly, i=5 does not satisfy the condition, either. Thus, there are three integers that satisfy the condition.

Sample Input 2

4
4 3 2 1

Sample Output 2

4

All integers i (1 \leq i \leq N) satisfy the condition.

Sample Input 3

6
1 2 3 4 5 6

Sample Output 3

1

Only i=1 satisfies the condition.

Sample Input 4

8
5 7 4 2 6 8 1 3

Sample Output 4

4

Sample Input 5

1
1

Sample Output 5

1

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

const MOD = 1000000007

var sc = bufio.NewScanner(os.Stdin)

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

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

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

func Min(x ...int) int {
	min := x[0]
	for _, v := range x {
		if v < min {
			min = v
		}
	}
	return min
}

func GCD(a, b int) int {
	x := Min(a, b)
	y := Max(a, b)
	for {
		t := y % x
		if t == 0 {
			return x
		}
		y = x
		x = t
	}
}

func LCM(a, b int) int {
	// return (a % MOD * b % MOD) % MOD * ModInv(GCD(a, b), MOD) % MOD
	gcd := GCD(a, b)
	return a * b / gcd
}

func ModInv(a, m int) int {
	b := m
	u := 1
	v := 0
	for b != 0 {
		t := a / b
		a -= t * b
		a, b = b, a
		u -= t * v
		u, v = v, u
	}

	u %= m
	if (u < 0) {
		u += m
	}

	return u
}

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

	lcm := a[0]
	for i := 1; i < n; i++ {
		lcm = LCM(lcm, a[i])
	}

	total := 0
	for i := 0; i < n; i++ {
		b := lcm % MOD * ModInv(a[i], MOD)
		total = (total % MOD + b % MOD) % MOD
	}

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

Score : 500 points

Problem Statement

Given are N positive integers A_1,...,A_N.

Consider positive integers B_1, ..., B_N that satisfy the following condition.

Condition: For any i, j such that 1 \leq i < j \leq N, A_i B_i = A_j B_j holds.

Find the minimum possible value of B_1 + ... + B_N for such B_1,...,B_N.

Since the answer can be enormous, print the sum modulo (10^9 +7).

Constraints

1 \leq N \leq 10^4

1 \leq A_i \leq 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 ... A_N

Output

Print the minimum possible value of B_1 + ... + B_N for B_1,...,B_N that satisfy the condition, modulo (10^9 +7).

Sample Input 1

3
2 3 4

Sample Output 1

13

Let B_1=6, B_2=4, and B_3=3, and the condition will be satisfied.

Sample Input 2

5
12 12 12 12 12

Sample Output 2

5

We can let all B_i be 1.

Sample Input 3

3
1000000 999999 999998

Sample Output 3

996989508

Print the sum modulo (10^9+7).


package main

import "fmt"

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

func main() {

	mod := 1000000007

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

	lcm := A[0]
	for i := 1; i < N; i++ {
		lcm = lcm * A[i] / gcd(lcm, A[i])
	}

	ans := 0
	for _, a := range A {
		ans += lcm / a
		ans %= mod
	}
	fmt.Println(ans)
}


package main

import (
	"fmt"
)

func solution(h, w, n int) int {
	max := max(h, w)
	var ans int = 1
	for max*ans < n {
		ans++
	}
	return ans
}

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

func main() {
	var h, w, n int
	fmt.Scan(&h, &w, n)
	fmt.Println(solution(h, w, n))
}

Score : 100 points

Problem Statement

We have a grid with H rows and W columns, where all the squares are initially white.

You will perform some number of painting operations on the grid.
In one operation, you can do one of the following two actions:

Choose one row, then paint all the squares in that row black.

Choose one column, then paint all the squares in that column black.

At least how many operations do you need in order to have N or more black squares in the grid?
It is guaranteed that, under the conditions in Constraints, having N or more black squares is always possible by performing some number of operations.

Constraints

1 \leq H \leq 100

1 \leq W \leq 100

1 \leq N \leq H \times W

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H
W
N

Output

Print the minimum number of operations needed.

Sample Input 1

3
7
10

Sample Output 1

2

You can have 14 black squares in the grid by performing the "row" operation twice, on different rows.

Sample Input 2

14
12
112

Sample Output 2

8

Sample Input 3

2
100
200

Sample Output 3

2


package main

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

// Robot is a struct.
type Robot struct {
	X   int64
	L   int64
	Min int64
	Max int64
}

// Robots is robots.
type Robots []Robot

// Less .
func (r Robots) Less(i, j int) bool {
	return r[i].Max < r[j].Max
}

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

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

func main() {
	var N int
	fmt.Scanf("%d", &N)
	robots := make(Robots, 0, N)
	for i := 0; i < N; i++ {
		r := Robot{}
		fmt.Scanf("%d %d", &r.X, &r.L)
		r.Min = r.X - r.L + 1
		r.Max = r.X + r.L - 1
		robots = append(robots, r)
	}
	sort.Sort(robots)
	count := 0
	flags := make([]bool, N)
	var max int64
	max = math.MinInt64
	for i, r := range robots {
		if max >= r.Min {
			flags[i] = false
			continue
		}
		flags[i] = true
		if max < r.Max {
			max = r.Max
		}
	}
	for _, v := range flags {
		if v {
			count++
		}
	}
	fmt.Println(count)
}

Score : 200 points

Problem Statement

In a factory, there are N robots placed on a number line.
Robot i is placed at coordinate X_i and can extend its arms of length L_i in both directions, positive and negative.

We want to remove zero or more robots so that the movable ranges of arms of no two remaining robots intersect.
Here, for each i (1 \leq i \leq N), the movable range of arms of Robot i is the part of the number line between the coordinates X_i - L_i and X_i + L_i, excluding the endpoints.

Find the maximum number of robots that we can keep.

Constraints

1 \leq N \leq 100,000

0 \leq X_i \leq 10^9 (1 \leq i \leq N)

1 \leq L_i \leq 10^9 (1 \leq i \leq N)

If i \neq j, X_i \neq X_j.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 L_1
X_2 L_2
\vdots
X_N L_N

Output

Print the maximum number of robots that we can keep.

Sample Input 1

4
2 4
4 3
9 3
100 5

Sample Output 1

3

By removing Robot 2, we can keep the other three robots.

Sample Input 2

2
8 20
1 10

Sample Output 2

1

Sample Input 3

5
10 1
2 1
4 1
6 1
8 1

Sample Output 3

5


package main

import (
	"fmt"
	"sort"
)

type Data struct {
	X   int
	L   int
	Min int
	Max int
}

type Datas []Data

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

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

func (p Datas) Less(i, j int) bool {
	return p[i].X < p[j].X
}

func main() {
	//	fmt.Println("start")
	var N int

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

	d := make(Datas, N)
	for i := 0; i < N; i++ {
		fmt.Scanf("%d %d", &d[i].X, &d[i].L)
		d[i].Min = d[i].X - d[i].L // + 1
		d[i].Max = d[i].X + d[i].L //- 1
	}

	sort.Sort(d)

	for {
		flag := make([]int, N)
		for i := 1; i < N; i++ {
			if d[i-1].Max > d[i].Min {
				flag[i-1]++
				flag[i]++
			}
		}
		max := flag[0]
		pos := 0
		for i := 1; i < N; i++ {
			if flag[i] > max {
				max = flag[i]
				pos = i
			}
		}
		//		fmt.Println(N, d[:N])

		if max == 0 {
			break
		}
		// remove
		for i := 0; i < N-1; i++ {
			if i >= pos {
				d[i] = d[i+1]
			}
		}
		N--
		//		fmt.Println(N, d[:N])
	}
	fmt.Println(N)
}


package main

import "fmt"

func main() {
	var n, m int
	fmt.Scan(&n, &m)
	p := make([]int, m)
	s := make([]string, m)
	ac := make(map[int]struct{})
	wa := make(map[int]struct{})
	for i, _ := range p {
		fmt.Scan(&p[i], &s[i])
		if s[i] == "AC" {
			ac[p[i]] = struct{}{}
		} else {
			wa[p[i]] = struct{}{}
		}
	}
	fmt.Println(len(ac), len(wa))
}

Score : 300 points

Problem Statement

Takahashi participated in a contest on AtCoder.

The contest had N problems.

Takahashi made M submissions during the contest.

The i-th submission was made for the p_i-th problem and received the verdict S_i (AC or WA).

The number of Takahashi's correct answers is the number of problems on which he received an AC once or more.

The number of Takahashi's penalties is the sum of the following count for the problems on which he received an AC once or more: the number of WAs received before receiving an AC for the first time on that problem.

Find the numbers of Takahashi's correct answers and penalties.

Constraints

N, M, and p_i are integers.

1 \leq N \leq 10^5

0 \leq M \leq 10^5

1 \leq p_i \leq N

S_i is AC or WA.

Input

Input is given from Standard Input in the following format:

N M
p_1 S_1
:
p_M S_M

Output

Print the number of Takahashi's correct answers and the number of Takahashi's penalties.

Sample Input 1

2 5
1 WA
1 AC
2 WA
2 AC
2 WA

Sample Output 1

2 2

In his second submission, he received an AC on the first problem for the first time. Before this, he received one WA on this problem.

In his fourth submission, he received an AC on the second problem for the first time. Before this, he received one WA on this problem.

Thus, he has two correct answers and two penalties.

Sample Input 2

100000 3
7777 AC
7777 AC
7777 AC

Sample Output 2

1 0

Note that it is pointless to get an AC more than once on the same problem.

Sample Input 3

6 0

Sample Output 3

0 0


package main

import (
	"fmt"
)

func main() {
	var n, m, p int
	var s string
	fmt.Scanf("%d %d", &n, &m)

	acflag := map[int]bool{}
	var ac, wa int
	wabuf := map[int]int{}

	for i := 0; i < m; i++ {
		fmt.Scan(&p)
		fmt.Scan(&s)
		if !acflag[p] {
			switch s {
			case "AC":
				ac++
				acflag[p] = true
				wa += wabuf[p]
			case "WA":
				wabuf[p]++
			}
		}
	}

	fmt.Print(ac)
	fmt.Print(" ")
	fmt.Println(wa)
}


package main
import (
	"fmt"
)
func main()  {
	var N,K int
	fmt.Scan(&N,&K)
	pena,acc:=0,0
	plob :=map[int]int{}

	for i := 0; i < K; i++ {
		var p int
		var s string
		fmt.Scan(&p,&s)
		a,b:=plob[p]
		if !b {
			if s=="WA" {
				plob[p]=1
			}else{
				plob[p]=0
				acc++
			}
		}else{
			if a>0 &&  s=="WA" {
				plob[p]++;
			}else if a>0 &&  s=="AC" {
				acc++
				pena+=a
				plob[p]=0
			}
		}

	}

	fmt.Println(acc,pena)

}


package main

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

func main() {
	NM := sc.nextInts()
	// N := NM[0]
	M := NM[1]
	mAc := make(map[string]int)
	mWa := make(map[string]int)
	for i := 0; i < M; i++ {
		prob := sc.nexts()
		nth := prob[0]
		result := prob[1]
		if result == "AC" {
			mAc[nth] = 1
		} else {
			if mAc[nth] == 0 {
				mWa[nth]++
			}
		}
	}
	var sumAc int
	var sunWa int

	for _, v := range mAc {
		sumAc += v
	}

	for i, v := range mWa {
		if mAc[i] == 1 {
			sunWa += v
		}
	}

	fmt.Println(sumAc, sunWa)
}

/* template functions */
var (
	sc scanner
)

func init() {
	sc = scanner{
		buf: make([]string, 0, 0),
		cur: 0,
		r:   bufio.NewReader(os.Stdin),
	}
}

type scanner struct {
	buf []string
	cur int
	r   *bufio.Reader
}

func (s *scanner) readln() {
	rbuf := make([]byte, 0, 0)
	for {
		line, prefix, err := s.r.ReadLine()
		if err != nil {
			panic(err)
		}
		rbuf = append(rbuf, line...)
		if prefix == false {
			break
		}
	}
	s.cur = 0
	s.buf = strings.Split(*(*string)(unsafe.Pointer(&rbuf)), " ")
}

func (s *scanner) isFull() bool {
	if s.cur == len(s.buf) {
		return true
	}
	return false
}

func (s *scanner) resetCur() {
	s.cur = 0
}

func (s *scanner) next() string {
	if s.cur == 0 {
		s.readln()
	}
	res := s.buf[s.cur]
	s.cur++
	if s.isFull() {
		s.resetCur()
	}
	return res
}

func (s *scanner) nexts() []string {
	s.readln()
	s.resetCur()
	return s.buf
}

func (s *scanner) nextInt() int {
	if s.cur == 0 {
		s.readln()
	}
	res, _ := strconv.Atoi(s.buf[s.cur])
	s.cur++
	if s.isFull() {
		s.resetCur()
	}
	return res
}

func (s *scanner) nextInts() []int {
	s.readln()
	res := make([]int, len(s.buf))
	for i := range s.buf {
		res[i], _ = strconv.Atoi(s.buf[i])
	}
	s.resetCur()
	return res
}

func (s *scanner) nextFloat() float64 {
	if s.cur == 0 {
		s.readln()
	}
	res, _ := strconv.ParseFloat(s.buf[s.cur], 64)
	s.cur++
	if s.isFull() {
		s.resetCur()
	}
	return res
}

func (s *scanner) nextFloats() []float64 {
	s.readln()
	res := make([]float64, len(s.buf))
	for i := range s.buf {
		res[i], _ = strconv.ParseFloat(s.buf[i], 64)
	}
	s.resetCur()
	return res
}

func digits(x int) int {
	return len(strconv.Itoa(x))
}

func powInt(x, p int) (result int) {
	result = 1
	for i := 0; i < p; i++ {
		result *= x
	}
	return
}

func max(x, y int) int {
	return int(math.Max(float64(x), float64(y)))
}

func min(x, y int) int {
	return int(math.Min(float64(x), float64(y)))
}

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

func varDump(value ...interface{}) {
	for _, v := range value {
		fmt.Fprintf(os.Stderr, "%#v\n", v)
	}
}

func yes() {
	fmt.Println("Yes")
}

func no() {
	fmt.Println("No")
}


package main

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

type PS struct {
	p int
	s string
}

var buf = bufio.NewScanner(os.Stdin)

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

func scanInts(n int) []int {
	a := make([]int, n)
	for k, _ := range a {
		a[k] = scanInt()
	}
	return a
}

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

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

	n := scanInt()
	m := scanInt()
	ps := make([]PS, m)
	for k, _ := range ps {
		ps[k].p = scanInt()
		ps[k].s = scanString()
	}

	acknowledged := make([]int, n)

	correctAnswers := 0
	penalties := 0
	for _, v := range ps {
		if acknowledged[v.p-1] == 0 {
			if v.s == "AC" {
				acknowledged[v.p-1] = 1
				correctAnswers++
			} else {
				penalties++
			}
		}
	}

	fmt.Printf("%d %d", correctAnswers, penalties)
}


package main

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

func main() {
	sc := NewScanner()

	_ = sc.NextInt()
	m := sc.NextInt()

	ac := 0
	wa := 0

	ignore := 0
	for i := 0; i < m; i++ {
		p := sc.NextInt()
		s := sc.NextLine()
		if ignore == p {
			continue
		}
		if s == "WA" {
			wa++
		}
		if s == "AC" {
			ac++
			ignore = p
		}
	}
	fmt.Printf("%v %v\n", ac, wa)

}

type Scanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewScanner() *Scanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1000)
	return &Scanner{r: rdr}
}
func (s *Scanner) Next() string {
	s.pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	result := string(s.buf[start:s.p])
	s.p++
	return result
}
func (s *Scanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *Scanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}

func (s *Scanner) NextIntArray() []int {
	s.pre()
	start := s.p
	result := []int{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			result = append(result, v)
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	result = append(result, v)

	return result
}

func (s *Scanner) NextMap() map[int]bool {
	s.pre()
	start := s.p
	mp := map[int]bool{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			mp[v] = true
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	mp[v] = true

	return mp
}

func (s *Scanner) pre() {
	if s.p >= len(s.buf) {
		s.readLine()
		s.p = 0
	}
}
func (s *Scanner) readLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, e := s.r.ReadLine()
		if e != nil {
			panic(e)
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

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

func scanInt64() int64 {
	sc.Scan()
	a, err := strconv.Atoi(sc.Text())
	if err != nil {
		fmt.Println(err)
	}
	return int64(a)
}

func scanFloat() float64 {
	sc.Scan()
	a, err := strconv.ParseFloat(sc.Text(), 64)
	if err != nil {
		fmt.Println(err)
	}
	return a
}

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

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

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

func scanInt64Slice(n int64) []int64 {
	a := make([]int64, n)
	for i := int64(0); i < n; i++ {
		a[i] = scanInt64()
	}
	return a
}

// var sc = bufio.NewScanner(os.Stdin)

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

	input := scanSlice(2)
	n := input[0]
	m := input[1]

	_ = n

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

	for i := 0; i < m; i++ {
		tmp := scanTextSlice(2)
		p, _ := strconv.Atoi(tmp[0])
		s := tmp[1]

		if val, ok := memo[p]; ok {
			ac := val[0]
			// penalty := val[1]
			if ac > 0 {
				continue
			} else if ac <= 0 && s == "WA" {
				memo[p][1] = memo[p][1] + 1
			} else if ac <= 0 && s == "AC" {
				memo[p][0] = 1
			}
		} else {
			memo[p] = make([]int, 2)
			if s == "AC" {
				memo[p][0] = 1

			} else {
				memo[p][1] = 1

			}
		}
	}

	ansAC := 0
	ansWA := 0
	for _, val := range memo {
		ac := val[0]
		penalty := val[1]
		if ac > 0 {
			ansAC++
		}
		ansWA += penalty
	}

	fmt.Println(ansAC, ansWA)

}

func binarySearch(arr []int, number int) int {

	l := -1
	r := len(arr)
	index := 0
	for {
		mid := l + (r-l)/2
		tmp := arr[mid]

		if r-l <= 1 || tmp == number {
			index = mid
			break
		} else if tmp < number {
			l = mid
		} else {
			r = mid
		}
	}
	return index
}

func factorial(n int) int64 {
	sum := int64(1)
	for i := 2; i <= n; i++ {
		sum *= int64(i)
	}
	return sum
}

func deleteNumOfArray(arr []int, position int) []int {
	left := arr[:position]
	r := arr[position+1:]
	appendArr := append(left, r...)
	return appendArr
}


package main

import "fmt"

func main() {
	var n, m int
	pmap := map[int]bool{}
	fmt.Scan(&n)
	fmt.Scan(&m)
	var num, ac, wa int
	var ans string
	for i := 0; i < m; i++ {
		fmt.Scan(&num)
		fmt.Scan(&ans)
		val, ok := pmap[num]
		// まだ AC も WA もしてないとき
		if !ok {
			if ans == "AC" {
				pmap[num] = true
				ac++
			} else {
				pmap[num] = false
				wa++
			}
			continue
		}
		// 既に AC または WA してるとき
		if val {
			// AC 済み
			continue
		}
		// WA
		if ans == "AC" {
			// 正解した
			pmap[num] = true
			ac++
		} else {
			// ひきつづき不正解
			wa++
		}
	}
	fmt.Printf("%d %d\n", ac, wa)
}


package main

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

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

func warshallFloyd(n int, d [][]int) {
	for k := 0; k < n; k++ {
		for i := 0; i < n; i++ {
			for j := 0; j < n; j++ {
				d[i][j] = min(d[i][j], d[i][k] + d[k][j])
			}
		}
	}
}

func main() {
	H := readInt()
	W := readInt()

	S := make([]string, H)
	for i := 0; i < H; i++ {
		S[i] = readString()
	}

	n := H * W
	d := make([][]int, n)
	for i := 0; i < n; i++ {
		d[i] = make([]int, n)
		fillInts(d[i], math.MaxInt32)
		d[i][i] = 0
	}

	for y := 0; y < H; y++ {
		for x := 0; x < W; x++ {
			if S[y][x] == '#' {
				continue
			}
			if y-1 >= 0 && S[y-1][x] != '#' {
				d[y*W+x][(y-1)*W+x] = 1
			}
			if y+1 < H && S[y+1][x] != '#' {
				d[y*W+x][(y+1)*W+x] = 1
			}
			if x-1 >= 0 && S[y][x-1] != '#' {
				d[y*W+x][y*W+x-1] = 1
			}
			if x+1 < W && S[y][x+1] != '#' {
				d[y*W+x][y*W+x+1] = 1
			}
		}
	}

	warshallFloyd(n, d)

	result := 0
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if d[i][j] < math.MaxInt32 && d[i][j] > result {
				result = d[i][j]
			}
		}
	}

	fmt.Println(result)
}

const (
	ioBufferSize = 1 * 1024 * 1024 // 1 MB
)

var stdinScanner = func() *bufio.Scanner {
	result := bufio.NewScanner(os.Stdin)
	result.Buffer(make([]byte, ioBufferSize), ioBufferSize)
	result.Split(bufio.ScanWords)
	return result
}()

func readString() string {
	stdinScanner.Scan()
	return stdinScanner.Text()
}

func readInt() int {
	result, err := strconv.Atoi(readString())
	if err != nil {
		panic(err)
	}
	return result
}

func fillInts(a []int, x int) {
	for i := 0; i < len(a); i++ {
		a[i] = x
	}
}

Score : 400 points

Problem Statement

Takahashi has a maze, which is a grid of H \times W squares with H horizontal rows and W vertical columns.

The square at the i-th row from the top and the j-th column is a "wall" square if S_{ij} is #, and a "road" square if S_{ij} is ..

From a road square, you can move to a horizontally or vertically adjacent road square.

You cannot move out of the maze, move to a wall square, or move diagonally.

Takahashi will choose a starting square and a goal square, which can be any road squares, and give the maze to Aoki.

Aoki will then travel from the starting square to the goal square, in the minimum number of moves required.

In this situation, find the maximum possible number of moves Aoki has to make.

Constraints

1 \leq H,W \leq 20

S_{ij} is . or #.

S contains at least two occurrences of ..

Any road square can be reached from any road square in zero or more moves.

Input

Input is given from Standard Input in the following format:

H W
S_{11}...S_{1W}
:
S_{H1}...S_{HW}

Output

Print the maximum possible number of moves Aoki has to make.

Sample Input 1

3 3
...
...
...

Sample Output 1

4

If Takahashi chooses the top-left square as the starting square and the bottom-right square as the goal square, Aoki has to make four moves.

Sample Input 2

3 5
...#.
.#.#.
.#...

Sample Output 2

10

If Takahashi chooses the bottom-left square as the starting square and the top-right square as the goal square, Aoki has to make ten moves.


// フェルマーの小定理
package main

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

const (
	m = 1000000007
)

var (
	fac []int
)

func mpow(x int, n int) int {
	result := 1
	for n != 0 {
		if n&1 == 1 {
			result *= x
			result %= m
		}
		x *= x
		x %= m
		n >>= 1
	}
	return result
}

func mcomb(n int, k int) int {
	if n == 0 && k == 0 {
		return 1
	}
	if n < k || k < 0 {
		return 0
	}
	return (fac[n] * mpow(fac[n-k], m-2) % m) * mpow(fac[k], m-2) % m
}

func main() {
	N := readInt()
	K := readInt()
	A := make([]int, N)
	for i := 0; i < N; i++ {
		A[i] = readInt()
	}

	fac = make([]int, N+1)
	fac[0] = 1
	for i := 0; i < N; i++ {
		fac[i+1] = fac[i] * (i + 1) % m
	}

	sort.Sort(sort.Reverse(sort.IntSlice(A)))
	result := 0
	for i := 0; i < N-K+1; i++ {
		result += A[i] * mcomb(N-(i+1), K-1)
		result %= m
	}

	sort.Ints(A)
	t := 0
	for i := 0; i < N-K+1; i++ {
		t += A[i] * mcomb(N-(i+1), K-1)
		t %= m
	}

	result += m - t
	result %= m
	fmt.Println(result)
}

const (
	ioBufferSize = 1 * 1024 * 1024 // 1 MB
)

var stdinScanner = func() *bufio.Scanner {
	result := bufio.NewScanner(os.Stdin)
	result.Buffer(make([]byte, ioBufferSize), ioBufferSize)
	result.Split(bufio.ScanWords)
	return result
}()

func readString() string {
	stdinScanner.Scan()
	return stdinScanner.Text()
}

func readInt() int {
	result, err := strconv.Atoi(readString())
	if err != nil {
		panic(err)
	}
	return result
}

Score : 500 points

Problem Statement

For a finite set of integers X, let f(X)=\max X - \min X.

Given are N integers A_1,...,A_N.

We will choose K of them and let S be the set of the integers chosen. If we distinguish elements with different indices even when their values are the same, there are {}_N C_K ways to make this choice. Find the sum of f(S) over all those ways.

Since the answer can be enormous, print it \bmod (10^9+7).

Constraints

1 \leq N \leq 10^5

1 \leq K \leq N

|A_i| \leq 10^9

Input

Input is given from Standard Input in the following format:

N K
A_1 ... A_N

Output

Print the answer \bmod (10^9+7).

Sample Input 1

4 2
1 1 3 4

Sample Output 1

11

There are six ways to choose S: \{1,1\},\{1,3\},\{1,4\},\{1,3\},\{1,4\}, \{3,4\} (we distinguish the two 1s). The value of f(S) for these choices are 0,2,3,2,3,1, respectively, for the total of 11.

Sample Input 2

6 3
10 10 10 -10 -10 -10

Sample Output 2

360

There are 20 ways to choose S. In 18 of them, f(S)=20, and in 2 of them, f(S)=0.

Sample Input 3

3 1
1 1 1

Sample Output 3

0

Sample Input 4

10 6
1000000000 1000000000 1000000000 1000000000 1000000000 0 0 0 0 0

Sample Output 4

999998537

Print the sum \bmod (10^9+7).


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

var mod int = 1000000007

func main() {
	buf := make([]byte, 0)
	sc.Buffer(buf, mod)
	sc.Split(bufio.ScanWords)
	n := iScan()
	x := make([]int, n)
	y := make([]int, n)
	for i := 0; i < n; i++ {
		x[i] = iScan()
		y[i] = iScan()
	}
	ng, ok := 0., 1000000.
	for ok-ng > 1e-16 {
		med := (ok + ng) / 2.
		f := true
		for i := 0; i < n; i++ {
			for j := i; j < n; j++ {
				z := math.Pow(float64((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j])), 0.5)
				if z > med {
					f = false
				}
			}
		}
		if f {
			ok = med
		} else {
			ng = med
		}
	}
	fmt.Println(ok / 2)
}

Score : 600 points

Problem Statement

Given are N points (x_i, y_i) in a two-dimensional plane.

Find the minimum radius of a circle such that all the points are inside or on it.

Constraints

2 \leq N \leq 50

0 \leq x_i \leq 1000

0 \leq y_i \leq 1000

The given N points are all different.

The values in input are all integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the minimum radius of a circle such that all the N points are inside or on it.

Your output will be considered correct if the absolute or relative error from our answer is at most 10^{-6}.

Sample Input 1

2
0 0
1 0

Sample Output 1

0.500000000000000000

Both points are contained in the circle centered at (0.5,0) with a radius of 0.5.

Sample Input 2

3
0 0
0 1
1 0

Sample Output 2

0.707106781186497524

Sample Input 3

10
10 9
5 9
2 0
0 0
2 7
3 3
2 5
10 0
3 7
1 9

Sample Output 3

6.726812023536805158

If the absolute or relative error from our answer is at most 10^{-6}, the output will be considered correct.


/*
URL:
https://atcoder.jp/contests/abc151/tasks/abc151_f
*/

package main

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

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

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

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

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

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

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

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

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

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

var (
	n    int
	X, Y []float64
)

func main() {
	n = ReadInt()
	for i := 0; i < n; i++ {
		x, y := ReadInt2()
		xf, yf := float64(x), float64(y)
		X = append(X, xf)
		Y = append(Y, yf)
	}

	// res := calcTwoIntersections(0.0, 0.0, 4.0, 0.0, 1.0)
	// PrintfDebug("%v\n", res)
	// res = calcTwoIntersections(0.0, 0.0, 2.0, 2.0, 1.414)
	// PrintfDebug("%v\n", res)

	ans := BinarySearch(10000000.0, 0.0, func(r float64) bool {
		A := [][2]float64{}
		for i := 0; i < n; i++ {
			for j := i + 1; j < n; j++ {
				x1, y1, x2, y2 := X[i], Y[i], X[j], Y[j]

				// 2点間の距離
				// d := math.Sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2))
				d := Distance(x1, y1, x2, y2)
				if d > 2.0*r {
					// 2円は交点を生じない
					continue
				}

				// 2点の中点と、交点との距離
				h := calcH(d, r)

				// 2点間のベクトル
				dx := x1 - x2
				dy := y1 - y2

				// 単位ベクトル化
				// dist := math.Sqrt(dx*dx + dy*dy)
				// dx /= dist
				// dy /= dist
				dx, dy = UnitVector(dx, dy)

				// 90度回転
				// dx, dy = -dy, dx
				// 手法1
				// dx, dy = Rotate90(dx, dy)
				// 手法2
				// dx, dy = RotateN(dx, dy, math.Pi/2.0)
				// 手法3
				dx, dy = RotateN(dx, dy, math.Pi/4.0)
				dx, dy = RotateN(dx, dy, math.Pi/4.0)

				// 中点の座標
				mx, my := (x1+x2)/2.0, (y1+y2)/2.0

				// 交点を2つ求める
				x3, y3 := mx+h*dx, my+h*dy
				x4, y4 := mx-h*dx, my-h*dy

				// Aに追加
				A = append(A, [2]float64{x3, y3})
				A = append(A, [2]float64{x4, y4})
			}
		}

		for _, P := range A {
			cx, cy := P[0], P[1]
			num := 0
			for i := 0; i < n; i++ {
				x, y := X[i], Y[i]
				dist := math.Sqrt((cx-x)*(cx-x) + (cy-y)*(cy-y))
				// 交点を作る2円を確実に含めるように微小値を加える
				if dist <= (r + 0.0000001) {
					num++
				}
			}

			if num >= n {
				return true
			}
		}
		return false
	})

	fmt.Println(ans)
}

func Distance(x1, y1, x2, y2 float64) float64 {
	return math.Sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2))
}

func UnitVector(dx, dy float64) (ex, ey float64) {
	dist := math.Sqrt(dx*dx + dy*dy)
	return dx / dist, dy / dist
}

func Rotate90(cx, cy float64) (nx, ny float64) {
	return -cy, cx
}

func RotateN(cx, cy, radi float64) (nx, ny float64) {
	nx = math.Cos(radi)*cx - math.Sin(radi)*cy
	ny = math.Sin(radi)*cx + math.Cos(radi)*cy
	return nx, ny
}

func calcH(d, r float64) float64 {
	return math.Sqrt(r*r - (d/2.0)*(d/2.0))
}

// func calcTwoIntersections(x1, y1, x2, y2, h float64) [][2]float64 {
// 	// 2点間のベクトル
// 	dx := x1 - x2
// 	dy := y1 - y2
// 	// 単位ベクトル化
// 	dist := math.Sqrt(dx*dx + dy*dy)
// 	dx /= dist
// 	dy /= dist
// 	// 90度回転
// 	dx, dy = -dy, dx
// 	// 中点の座標
// 	mx, my := (x1+x2)/2.0, (y1+y2)/2.0
// 	// 交点を2つ求める
// 	x3, y3 := mx+h*dx, my+h*dy
// 	x4, y4 := mx-h*dx, my-h*dy

// 	return [][2]float64{
// 		[2]float64{x3, y3}, [2]float64{x4, y4},
// 	}
// }

func BinarySearch(initOK, initNG float64, isOK func(mid float64) bool) (ok float64) {
	ng := initNG
	ok = initOK
	// for int(math.Abs(float64(ok-ng))) > 1 {
	for i := 0; i < 50; i++ {
		mid := (ok + ng) / 2
		if isOK(mid) {
			ok = mid
		} else {
			ng = mid
		}
	}

	return ok
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

	return string(res)
}

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

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

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

	return string(res)
}

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

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


/*
URL:
https://atcoder.jp/contests/abc151/tasks/abc151_f
*/

package main

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

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

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

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

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

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

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

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

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

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

var (
	n    int
	X, Y []float64
)

func main() {
	n = ReadInt()
	for i := 0; i < n; i++ {
		x, y := ReadInt2()
		xf, yf := float64(x), float64(y)
		X = append(X, xf)
		Y = append(Y, yf)
	}

	// res := calcTwoIntersections(0.0, 0.0, 4.0, 0.0, 1.0)
	// PrintfDebug("%v\n", res)
	// res = calcTwoIntersections(0.0, 0.0, 2.0, 2.0, 1.414)
	// PrintfDebug("%v\n", res)

	ans := BinarySearch(10000000.0, 0.0, func(r float64) bool {
		A := [][2]float64{}
		for i := 0; i < n; i++ {
			for j := i + 1; j < n; j++ {
				x1, y1, x2, y2 := X[i], Y[i], X[j], Y[j]

				// 2点間の距離
				// d := math.Sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2))
				d := Distance(x1, y1, x2, y2)
				if d > 2.0*r {
					// 2円は交点を生じない
					continue
				}

				// 2点の中点と、交点との距離
				h := calcH(d, r)

				// 2点間のベクトル
				dx := x1 - x2
				dy := y1 - y2
				// 単位ベクトル化
				dist := math.Sqrt(dx*dx + dy*dy)
				dx /= dist
				dy /= dist
				// 90度回転
				dx, dy = -dy, dx
				// 中点の座標
				mx, my := (x1+x2)/2.0, (y1+y2)/2.0
				// 交点を2つ求める
				x3, y3 := mx+h*dx, my+h*dy
				x4, y4 := mx-h*dx, my-h*dy
				// Aに追加
				A = append(A, [2]float64{x3, y3})
				A = append(A, [2]float64{x4, y4})
			}
		}

		for _, P := range A {
			cx, cy := P[0], P[1]
			num := 0
			for i := 0; i < n; i++ {
				x, y := X[i], Y[i]
				dist := math.Sqrt((cx-x)*(cx-x) + (cy-y)*(cy-y))
				// 交点を作る2円を確実に含めるように微小値を加える
				if dist <= (r + 0.0000001) {
					num++
				}
			}

			if num >= n {
				return true
			}
		}
		return false
	})

	fmt.Println(ans)
}

func Distance(x1, y1, x2, y2 float64) float64 {
	return math.Sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2))
}

func calcH(d, r float64) float64 {
	return math.Sqrt(r*r - (d/2.0)*(d/2.0))
}

// func calcTwoIntersections(x1, y1, x2, y2, h float64) [][2]float64 {
// 	// 2点間のベクトル
// 	dx := x1 - x2
// 	dy := y1 - y2
// 	// 単位ベクトル化
// 	dist := math.Sqrt(dx*dx + dy*dy)
// 	dx /= dist
// 	dy /= dist
// 	// 90度回転
// 	dx, dy = -dy, dx
// 	// 中点の座標
// 	mx, my := (x1+x2)/2.0, (y1+y2)/2.0
// 	// 交点を2つ求める
// 	x3, y3 := mx+h*dx, my+h*dy
// 	x4, y4 := mx-h*dx, my-h*dy

// 	return [][2]float64{
// 		[2]float64{x3, y3}, [2]float64{x4, y4},
// 	}
// }

func BinarySearch(initOK, initNG float64, isOK func(mid float64) bool) (ok float64) {
	ng := initNG
	ok = initOK
	// for int(math.Abs(float64(ok-ng))) > 1 {
	for i := 0; i < 50; i++ {
		mid := (ok + ng) / 2
		if isOK(mid) {
			ok = mid
		} else {
			ng = mid
		}
	}

	return ok
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

	return string(res)
}

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

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

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

	return string(res)
}

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

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


package main

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

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

func Dist(A, B *[]float64) float64 {
  D := 0.0
  for i, a := range (*A) {
    x := (*B)[i] - a
    D += x * x
  }
  return math.Sqrt(D)
}
func CrossPoint(A, B *[]float64, R float64) []*[]float64 {
  AB := Dist(A, B)
  C := math.Sqrt(4.0 * R * R / (AB * AB) - 1)
  x1 := (((*A)[0] + (*B)[0]) + ((*A)[1] - (*B)[1]) * C) / 2.0
  y1 := (((*A)[1] + (*B)[1]) - ((*A)[0] - (*B)[0]) * C) / 2.0
  x2 := (((*A)[0] + (*B)[0]) - ((*A)[1] - (*B)[1]) * C) / 2.0
  y2 := (((*A)[1] + (*B)[1]) + ((*A)[0] - (*B)[0]) * C) / 2.0
  p1 := []float64{x1, y1}
  p2 := []float64{x2, y2}
  return []*[]float64{&p1, &p2}
}

func main() {
  N := NextInt()
  P := make([]*[]float64, N)
  for i := range P {
    p := NextFloatVec()
    P[i] = &p
  }
  D := make([][]float64, N)
  for i := range D {
    D[i] = make([]float64, N)
    for j := range D[i] {
      D[i][j] = Dist(P[i], P[j])
    }
  }
  R := math.Sqrt(2.0 * 500.0 * 500.0)
  r := 0.0
  diff := float64(1e-7)
  for diff < R - r {
    _r := (R + r) / 2.0
    Include := 0
    for i := 0; i < N - 1 && Include == 0; i++ {
      for j := i + 1; j < N && Include == 0 ; j++ {
        if 2.0 * _r < D[i][j] {
          Include = -1
          break
        }
        CP := CrossPoint(P[i], P[j], _r)
        if D[i][j] < _r {
          CP = append(CP, []*[]float64{P[i], P[j]}...)
        }
        for _, cp := range CP {
          inc := true
          for _, p := range P {
            if _r + diff < Dist(p, cp) {
              inc = false
              break
            }
          }
          if inc {
            Include = 1
            break
          }
        }
      }
    }
    if Include < 1 {
      r = _r
    } else {
      R = _r
    }
  }
  Write(R)
  Output()
}


package main

import "fmt"

type music struct {
	Name string
	Time int
}

func (m music) Is(s string) bool {
	return s == m.Name
}

func main() {
	var (
		playlist []music
	)
	var n int
	fmt.Scan(&n)
	playlist = make([]music, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&playlist[i].Name)
		fmt.Scan(&playlist[i].Time)
	}
	var x string
	fmt.Scan(&x)
	var flag bool
	all := 0
	for i := 0; i < n; i++ {
		if flag {
			all += playlist[i].Time
			continue
		}
		flag = playlist[i].Is(x)
	}
	fmt.Println(all)
}

Score : 200 points

Problem Statement

Niwango created a playlist of N songs.
The title and the duration of the i-th song are s_i and t_i seconds, respectively.
It is guaranteed that s_1,\ldots,s_N are all distinct.

Niwango was doing some work while playing this playlist. (That is, all the songs were played once, in the order they appear in the playlist, without any pause in between.)
However, he fell asleep during his work, and he woke up after all the songs were played.
According to his record, it turned out that he fell asleep at the very end of the song titled X.

Find the duration of time when some song was played while Niwango was asleep.

Constraints

1 \leq N \leq 50

s_i and X are strings of length between 1 and 100 (inclusive) consisting of lowercase English letters.

s_1,\ldots,s_N are distinct.

There exists an integer i such that s_i = X.

1 \leq t_i \leq 1000

t_i is an integer.

Input

Input is given from Standard Input in the following format:

N
s_1 t_1
\vdots
s_{N} t_N
X

Output

Print the answer.

Sample Input 1

3
dwango 2
sixth 5
prelims 25
dwango

Sample Output 1

30

While Niwango was asleep, two songs were played: sixth and prelims.

The answer is the total duration of these songs, 30.

Sample Input 2

1
abcde 1000
abcde

Sample Output 2

0

No songs were played while Niwango was asleep.

In such a case, the total duration of songs is 0.

Sample Input 3

15
ypnxn 279
kgjgwx 464
qquhuwq 327
rxing 549
pmuduhznoaqu 832
dagktgdarveusju 595
wunfagppcoi 200
dhavrncwfw 720
jpcmigg 658
wrczqxycivdqn 639
mcmkkbnjfeod 992
htqvkgkbhtytsz 130
twflegsjz 467
dswxxrxuzzfhkp 989
szfwtzfpnscgue 958
pmuduhznoaqu

Sample Output 3

6348


package main

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

func main() {
	sc.nextInt()
	S := sc.next()

	aflag := false
	bflag := false
	cflag := false
	var cnt int
	for _, v := range strings.Split(S, "") {
		if v == "A" && !aflag && !bflag && !cflag {
			aflag = true
		} else if v == "B" && aflag {
			bflag = true
			aflag = false
		} else if v == "C" && bflag {
			cflag = true
			bflag = false
		} else {
			aflag = false
			bflag = false
			cflag = false
		}
		if cflag {
			cnt++
			aflag = false
			bflag = false
			cflag = false
		}
	}
	fmt.Println(cnt)
}

/* template functions */
var (
	sc scanner
)

func init() {
	sc = scanner{
		buf: make([]string, 0, 0),
		cur: 0,
		r:   bufio.NewReader(os.Stdin),
	}
}

type scanner struct {
	buf []string
	cur int
	r   *bufio.Reader
}

func (s *scanner) readln() {
	rbuf := make([]byte, 0, 0)
	for {
		line, prefix, err := s.r.ReadLine()
		if err != nil {
			panic(err)
		}
		rbuf = append(rbuf, line...)
		if prefix == false {
			break
		}
	}
	s.cur = 0
	s.buf = strings.Split(*(*string)(unsafe.Pointer(&rbuf)), " ")
}
func (s *scanner) isFull() bool {
	if s.cur == len(s.buf) {
		return true
	}
	return false
}
func (s *scanner) resetCur() {
	s.cur = 0
}
func (s *scanner) next() string {
	if s.cur == 0 {
		s.readln()
	}
	res := s.buf[s.cur]
	s.cur++
	if s.isFull() {
		s.resetCur()
	}
	return res
}
func (s *scanner) nexts() []string {
	s.readln()
	s.resetCur()
	return s.buf
}
func (s *scanner) nextInt() int {
	if s.cur == 0 {
		s.readln()
	}
	res, _ := strconv.Atoi(s.buf[s.cur])
	s.cur++
	if s.isFull() {
		s.resetCur()
	}
	return res
}
func (s *scanner) nextInts() []int {
	s.readln()
	res := make([]int, len(s.buf))
	for i := range s.buf {
		res[i], _ = strconv.Atoi(s.buf[i])
	}
	s.resetCur()
	return res
}
func (s *scanner) nextFloat() float64 {
	if s.cur == 0 {
		s.readln()
	}
	res, _ := strconv.ParseFloat(s.buf[s.cur],
		64)
	s.cur++
	if s.isFull() {
		s.resetCur()
	}
	return res
}
func (s *scanner) nextFloats() []float64 {
	s.readln()
	res := make([]float64, len(s.buf))
	for i := range s.buf {
		res[i], _ = strconv.ParseFloat(s.buf[i],
			64)
	}
	s.resetCur()
	return res
}
func digits(x int) int {
	return len(strconv.Itoa(x))
}
func powInt(x, p int) (result int) {
	result = 1
	for i := 0; i < p; i++ {
		result *= x
	}
	return
}
func max(x, y int) int {
	return int(math.Max(float64(x), float64(y)))
}
func min(x, y int) int {
	return int(math.Min(float64(x), float64(y)))
}
func abs(x int) int {
	return int(math.Abs(float64(x)))
}
func varDump(value ...interface{}) {
	for _, v := range value {
		fmt.Fprintf(os.Stderr, "%#v\n", v)
	}
}
func yes() {
	fmt.Println("Yes")
}
func no() {
	fmt.Println("No")
}

Score : 200 points

Problem Statement

We have a string S of length N consisting of uppercase English letters.

How many times does ABC occur in S as contiguous subsequences (see Sample Inputs and Outputs)?

Constraints

3 \leq N \leq 50

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print number of occurrences of ABC in S as contiguous subsequences.

Sample Input 1

10
ZABCDBABCQ

Sample Output 1

2

Two contiguous subsequences of S are equal to ABC: the 2-nd through 4-th characters, and the 7-th through 9-th characters.

Sample Input 2

19
THREEONEFOURONEFIVE

Sample Output 2

0

No contiguous subsequences of S are equal to ABC.

Sample Input 3

33
ABCCABCBABCCABACBCBBABCBCBCBCABCB

Sample Output 3

5


package main

import (
	"fmt"
	"regexp"
)

func main() {
	var wordCount int
    var abcTestStr string
	fmt.Scanf("%d", &wordCount)
	fmt.Scanf("%s", &abcTestStr)

	var sLength = len([]byte(abcTestStr))
	if(sLength < 3 || 50 < sLength) {
        panic("allow length 1 to 50")
    }
	if(sLength != wordCount) {
        panic("allow length wordCount")
    }
	upperCaseAtoZRep := regexp.MustCompile(`^[A-Z]*`)
	if(!upperCaseAtoZRep.MatchString(abcTestStr)) {
		panic("allow AtoZ only")
	}
    splitAtoZRep := regexp.MustCompile(`ABC`)
    result := splitAtoZRep.FindAllStringSubmatch(abcTestStr, -1)
	fmt.Printf("%d", len(result))
}


package main

import (
	"fmt"
)

func main() {

	// 読み込み数取得
	var n int
	var s string
	fmt.Scan(&n, &s)

	count := 0

	for i := 0; i < (n - 2); i++ {
		if s[i:(i+3)] == "ABC" {
			count++
		}
	}
	fmt.Printf("%d\n", count)

}


package main

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

func main() {
	n := readI()
	P, Q := make([]int, n), make([]int, n)
	for i := 0; i < n; i++ {
		P[i] = readI()
	}
	for i := 0; i < n; i++ {
		Q[i] = readI()
	}

	if isLager(P, Q) {
		P, Q = Q, P
	}

	i := 0
	for ; !isSame(P, Q); i++ {
		nextPermutation(P)
	}

	fmt.Println(i)
}

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

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

func nextPermutation(p []int) bool {
	swap := func(a []int, b, c int) {
		a[b], a[c] = a[c], a[b]
	}
	rev := func(s []int) {
		for i := 0; i < len(s)/2; i++ {
			swap(s, i, len(s)-1-i)
		}
	}

	l, r := len(p)-2, len(p)-1

	for p[l] >= p[l+1] {
		if l == 0 {
			rev(p)
			return false
		}
		l--
	}
	for p[l] >= p[r] {
		r--
	}

	swap(p, l, r)
	rev(p[l+1:])
	return true
}

/*-----------Input utils-----------*/

var sc = bufio.NewScanner(os.Stdin)

func init() {
	if len(os.Args) >= 2 {
		if os.Args[1] == "debug" {
			debug()
		}
	}
	const buf = 200100
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, buf), buf)
}

func debug() {
	testFile, err := os.Open("./test/sample-2.in")
	if err != nil {
		fmt.Fprintln(os.Stderr, "There is no testfile.")
		os.Exit(1)
	}
	sc = bufio.NewScanner(testFile)
}

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

func readR() []rune {
	return []rune(readS())
}

func readI() int {
	i, _ := strconv.Atoi(readS())
	return i
}

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

Score : 300 points

Problem Statement

We have two permutations P and Q of size N (that is, P and Q are both rearrangements of (1,~2,~...,~N)).

There are N! possible permutations of size N. Among them, let P and Q be the a-th and b-th lexicographically smallest permutations, respectively. Find |a - b|.

Notes

For two sequences X and Y, X is said to be lexicographically smaller than Y if and only if there exists an integer k such that X_i = Y_i~(1 \leq i < k) and X_k < Y_k.

Constraints

2 \leq N \leq 8

P and Q are permutations of size N.

Input

Input is given from Standard Input in the following format:

N
P_1 P_2 ... P_N
Q_1 Q_2 ... Q_N

Output

Print |a - b|.

Sample Input 1

3
1 3 2
3 1 2

Sample Output 1

3

There are 6 permutations of size 3: (1,~2,~3), (1,~3,~2), (2,~1,~3), (2,~3,~1), (3,~1,~2), and (3,~2,~1). Among them, (1,~3,~2) and (3,~1,~2) come 2-nd and 5-th in lexicographical order, so the answer is |2 - 5| = 3.

Sample Input 2

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

Sample Output 2

17517

Sample Input 3

3
1 2 3
1 2 3

Sample Output 3

0


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

var perms [][]int

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

	rest := make([]int, n)
	p := make([]int, n)
	for i := 0; i < n; i++ {
		p[i] = readInt()
		rest[i] = i + 1
	}
	q := make([]int, n)
	for i := 0; i < n; i++ {
		q[i] = readInt()
	}

	perms = make([][]int, 0)
	perm([]int{}, rest)

	pi, pq := 0, 0
	for i := 0; i < len(perms); i++ {
		if equal(perms[i], p) {
			pi = i
		}
		if equal(perms[i], q) {
			pq = i
		}
	}
	fmt.Println(abs(pi - pq))
}

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

func equal(x, y []int) bool {
	if len(x) != len(y) {
		return false
	}
	n := len(x)
	for i := 0; i < n; i++ {
		if x[i] != y[i] {
			return false
		}
	}
	return true
}

func perm(head, rest []int) []int {
	if len(rest) == 0 {
		perms = append(perms, head)
		return head
	}
	res := make([]int, 0)
	for i := 0; i < len(rest); i++ {
		restx := make([]int, len(rest))
		copy(restx, rest)

		headx := make([]int, len(head))
		copy(headx, head)

		headx = append(headx, restx[i])
		restx = append(restx[:i], restx[i+1:]...)
		res = perm(headx, restx)
	}
	return res
}


package main

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

func main() {
	readInt()
	S, Result, Checker := readString(), 0, 0

	for _, c := range strings.Split(S, "") {
		switch c {
		case "A":
			Checker = 1

		case "B":
			if Checker == 1 {
				Checker = 2
			} else {
				Checker = 0
			}

		case "C":
			if Checker == 2 {
				Result++
			}
			Checker = 0
		}
	}

	fmt.Println(Result)
}

var scanner = bufio.NewScanner(os.Stdin)

func init() {
	scanner.Split(bufio.ScanWords)
	//scanner.Split(bufio.ScanLines)
}

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

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


package main

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"math"
	"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)) // for AtCoder
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	// Split sets the split function for the Scanner. The default split function is ScanLines.
	// Split panics if it is called after scanning has started.
	r.Split(bufio.ScanWords)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

	return string(res)
}

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

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

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

	return string(res)
}

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

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

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

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

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

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

/*
ASCII code

ASCII   10進数  ASCII   10進数  ASCII   10進数
!       33      "       34      #       35
$       36      %       37      &       38
'       39      (       40      )       41
*       42      +       43      ,       44
-       45      .       46      /       47
0       48      1       49      2       50
3       51      4       52      5       53
6       54      7       55      8       56
9       57      :       58      ;       59
<       60      =       61      >       62
?       63      @       64      A       65
B       66      C       67      D       68
E       69      F       70      G       71
H       72      I       73      J       74
K       75      L       76      M       77
N       78      O       79      P       80
Q       81      R       82      S       83
T       84      U       85      V       86
W       87      X       88      Y       89
Z       90      [       91      \       92
]       93      ^       94      _       95
`       96      a       97      b       98
c       99      d       100     e       101
f       102     g       103     h       104
i       105     j       106     k       107
l       108     m       109     n       110
o       111     p       112     q       113
r       114     s       115     t       116
u       117     v       118     w       119
x       120     y       121     z       122
{       123     |       124     }       125
~       126             127
*/

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

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

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

var n, m int
var A []int

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

	for i := 0; i < n; i++ {
		A[i] /= 2
	}

	var slcm int
	slcm = 1
	if n == 1 {
		slcm = A[0]
	} else {
		slcm = Lcm(A[0], A[1])
		if slcm >= m {
			fmt.Println(0)
			return
		}
		for i := 2; i < n; i++ {
			slcm = Lcm(slcm, A[i])
			if slcm >= m {
				fmt.Println(0)
				return
			}
		}
	}
	// fmt.Println(slcm)

	// if slcm%2 == 0 {
	// 	fmt.Println(0)
	// 	return
	// }

	ans := m / slcm
	if ans%2 == 0 {
		fmt.Println(ans / 2)
	} else {
		fmt.Println((ans + (2 - 1)) / 2)
	}
}

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

/*
- まずは全探索を検討しましょう
- MODは最後にとりましたか？
- ループを抜けた後も処理が必要じゃありませんか？
- 和・積・あまりを求められたらint64が必要ではありませんか？
- いきなりオーバーフローはしていませんか？
	- MOD取る系はint64必須ですよ？
*/

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

Score : 400 points

Problem Statement

Given are a sequence A= {a_1,a_2,......a_N} of N positive even numbers, and an integer M.

Let a semi-common multiple of A be a positive integer X that satisfies the following condition for every k (1 \leq k \leq N):

There exists a non-negative integer p such that X= a_k \times (p+0.5).

Find the number of semi-common multiples of A among the integers between 1 and M (inclusive).

Constraints

1 \leq N \leq 10^5

1 \leq M \leq 10^9

2 \leq a_i \leq 10^9

a_i is an even number.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
a_1 a_2 ... a_N

Output

Print the number of semi-common multiples of A among the integers between 1 and M (inclusive).

Sample Input 1

2 50
6 10

Sample Output 1

2

15 = 6 \times 2.5

15 = 10 \times 1.5

45 = 6 \times 7.5

45 = 10 \times 4.5

Thus, 15 and 45 are semi-common multiples of A. There are no other semi-common multiples of A between 1 and 50, so the answer is 2.

Sample Input 2

3 100
14 22 40

Sample Output 2

0

The answer can be 0.

Sample Input 3

5 1000000000
6 6 2 6 2

Sample Output 3

166666667


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

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

func KMP(A, B []interface{}) []int {
  N := len(B)
  PMT := make([]int, N + 1)
  PMT[0] = -1
  for i, j := 2, 0; i <= N; {
    if B[i - 1] == B[j] {
      PMT[i] = j + 1
      i++
      j++
    } else if 0 < j {
      j = PMT[j]
    } else {
      PMT[i] = 0
      i++
    }
  }
  M := make([]int, 0)
  for i, j := 0, 0; i + j < len(A); {
    if A[i + j] == B[j] {
      j++
      if j == N {
        M = append(M, i)
        i += N - PMT[N]
        j = PMT[j]
      }
    } else {
      i += j - PMT[j]
      if 0 < j { j = PMT[j] }
    }
  }
  return M
}

func main() {
  N := NextInt()
  A := NextIntVec()
  B := NextIntVec()
  XA := make([]interface{}, N)
  XB := make([]interface{}, N)
  for i, a := range A {
    XA[i] = a ^ A[(i + 1) % N]
    XB[i] = B[i] ^ B[(i + 1) % N]
  }
  XA = append(XA, XA...)
  K := KMP(XA, XB)
  for _, k := range K {
    if N <= k { break }
    x := A[k] ^ B[0]
    WriteIntVec([]int{k, x})
  }
  Output()
}

Score : 600 points

Problem Statement

Given are two sequences a=\{a_0,\ldots,a_{N-1}\} and b=\{b_0,\ldots,b_{N-1}\} of N non-negative integers each.

Snuke will choose an integer k such that 0 \leq k < N and an integer x not less than 0, to make a new sequence of length N, a'=\{a_0',\ldots,a_{N-1}'\}, as follows:

a_i'= a_{i+k \mod N}\ XOR \ x

Find all pairs (k,x) such that a' will be equal to b.

What is \mbox{ XOR }?

The XOR of integers A and B, A \mbox{ XOR } B, is defined as follows:

When A \mbox{ XOR } B is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if either A or B, but not both, has 1 in the 2^k's place, and 0 otherwise.

For example, 3 \mbox{ XOR } 5 = 6. (In base two: 011 \mbox{ XOR } 101 = 110.)

Constraints

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

0 \leq a_i,b_i < 2^{30}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_0 a_1 ... a_{N-1}
b_0 b_1 ... b_{N-1}

Output

Print all pairs (k, x) such that a' and b will be equal, using one line for each pair, in ascending order of k (ascending order of x for pairs with the same k).

If there are no such pairs, the output should be empty.

Sample Input 1

3
0 2 1
1 2 3

Sample Output 1

1 3

If (k,x)=(1,3),

a_0'=(a_1\ XOR \ 3)=1

a_1'=(a_2\ XOR \ 3)=2

a_2'=(a_0\ XOR \ 3)=3

and we have a' = b.

Sample Input 2

5
0 0 0 0 0
2 2 2 2 2

Sample Output 2

0 2
1 2
2 2
3 2
4 2

Sample Input 3

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

Sample Output 3

2 2
5 5

Sample Input 4

2
1 2
0 0

Sample Output 4

No pairs may satisfy the condition.


package main

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

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

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

func main() {
	S := getString()
	T := getString()
	fmt.Println(T + S)
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Score : 100 points

Problem Statement

Given are two strings S and T consisting of lowercase English letters. Concatenate T and S in this order, without space in between, and print the resulting string.

Constraints

S and T are strings consisting of lowercase English letters.

The lengths of S and T are between 1 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

S T

Output

Print the resulting string.

Sample Input 1

oder atc

Sample Output 1

atcoder

When S = oder and T = atc, concatenating T and S in this order results in atcoder.

Sample Input 2

humu humu

Sample Output 2

humuhumu


package main

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

func main() {
	S, T := readString(), readString()
	fmt.Println(T + S)
}

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

func init() {
	scanner.Split(bufio.ScanWords)
	//scanner.Split(bufio.ScanLines)
}

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


package main

import "fmt"

func main(){
	var A, B, K int64;

	fmt.Scan(&A, &B, &K);

	if A >=1{
		if A - K <= 0 {
			B += A-K
			if B < 0{
				B = 0;
			}
			A = 0;
		}
	}else if B >= 1 {
		if B - K > 0{
			B -= K
		}else {
			B = 0
		}
	}
	fmt.Println(A, B);
}

Score : 200 points

Problem Statement

Takahashi has A cookies, and Aoki has B cookies.
Takahashi will do the following action K times:

If Takahashi has one or more cookies, eat one of his cookies.

Otherwise, if Aoki has one or more cookies, eat one of Aoki's cookies.

If they both have no cookies, do nothing.

In the end, how many cookies will Takahashi and Aoki have, respectively?

Constraints

0 \leq A \leq 10^{12}

0 \leq B \leq 10^{12}

0 \leq K \leq 10^{12}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B K

Output

Print the numbers of Takahashi's and Aoki's cookies after K actions.

Sample Input 1

2 3 3

Sample Output 1

0 2

Takahashi will do the following:

He has two cookies, so he eats one of them.

Now he has one cookie left, and he eats it.

Now he has no cookies left, but Aoki has three, so Takahashi eats one of them.

Thus, in the end, Takahashi will have 0 cookies, and Aoki will have 2.

Sample Input 2

500000000000 500000000000 1000000000000

Sample Output 2

0 0

Watch out for overflows.


package main

import "fmt"

func main(){
	var A, B, K int64;

	fmt.Scan(&A, &B, &K);

	if A >=1{
		if A - K <= 0 {
			B += A-K
			A = 0;
		}
	}else if B >= 1 {
		if B - K <= 0{
			B = 0
		}else {
			B -= K
		}
	}
	if B < 0 {B=0}
	fmt.Println(A, B);
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

func main() {
	scanInit()

	x := nextInt()

	for i := x; i < 200000; i++ {
		if isPrime(i) == true {
			fmt.Println(i)
			return
		}
	}

}

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

// ---- readfunc
func scanInit() {
	const cap = 64 * 1024
	var buf = make([]byte, cap)
	sc.Buffer(buf, cap)
	sc.Split(bufio.ScanWords)
	return
}
func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}
func nextStr() string {
	sc.Scan()
	return sc.Text()
}

Score: 300 points

Problem Statement

Find the minimum prime number greater than or equal to X.

Notes

A prime number is an integer greater than 1 that cannot be evenly divided by any positive integer except 1 and itself.

For example, 2, 3, and 5 are prime numbers, while 4 and 6 are not.

Constraints

2 \le X \le 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X

Output

Print the minimum prime number greater than or equal to X.

Sample Input 1

20

Sample Output 1

23

The minimum prime number greater than or equal to 20 is 23.

Sample Input 2

2

Sample Output 2

2

X itself can be a prime number.

Sample Input 3

99992

Sample Output 3

100003


package main

import "fmt"

func merge(m1, m2 map[int]int) map[int]int {
	ans := map[int]int{}
	for k, v := range m1 {
		ans[k] += v
	}
	for k, v := range m2 {
		ans[k] += v
	}
	return ans
}

func factor(num, pnum int, v map[int]int) bool {
	if pnum*pnum > num {
		if num != 1 {
			if v[num] > 0 {
				return false
			}
			v[num]++
		}
		return len(v) == 1
	}

	if num%pnum == 0 {
		num /= pnum
		if v[pnum] > 0 {
			return false
		}
		v[pnum]++
	} else {
		pnum++
	}
	return factor(num, pnum, v)
}

func main() {
	var X int
	fmt.Scan(&X)
	r := 0
	for i := X; r == 0; i++ {
		if factor(i, 2, map[int]int{}) {
			r = i
		}
	}
	fmt.Println(r)
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
	"unicode/utf8"
)

const (
	Rock         = "Rock"
	Scissors     = "Scissors"
	Paper        = "Paper"
	FailRock     = "FailRock"
	FailScissors = "FailScissors"
	FailPaper    = "FailPaper"
)

func main() {
	in := readLineInt()
	Count, Dup := in[0], in[1]

	in = readLineInt()
	RockP, ScissorsP, PaperP := in[0], in[1], in[2]

	Machine := readLine()
	ResultArray, Result := make([]string, Count), 0

	fmt.Println(utf8.RuneCountInString(Machine))

	for i, M := range strings.Split(Machine, "") {
		var r string
		switch M {
		case "r":
			r = Paper
		case "s":
			r = Rock
		case "p":
			r = Scissors
		default:
			fmt.Println("fixme: Fail at switch M")
		}

		if i-Dup >= 0 {
			if isFail(ResultArray[i-Dup]) {
				ResultArray[i] = r
			} else if ResultArray[i-Dup] == r {
				ResultArray[i] = getFail(r)
			} else {
				ResultArray[i] = r
			}
		} else {
			fmt.Println("initial")
			ResultArray[i] = r
		}
	}

	fmt.Println(ResultArray)

	for _, v := range ResultArray {
		switch {
		case v == Rock:
			Result += RockP
		case v == Scissors:
			Result += ScissorsP
		case v == Paper:
			Result += PaperP
		case isFail(v):
			Result += 0
		}
	}

	fmt.Println(Result)
}

func isFail(i string) bool {
	return i == FailPaper || i == FailRock || i == FailScissors
}

func getFail(i string) string {
	switch i {
	case Rock:
		return FailRock
	case Scissors:
		return FailScissors
	case Paper:
		return FailPaper
	}
	fmt.Println("fixme: getFail")
	return ""
}

/////////////////////////////////////////

func readLineInt() []int {
	result := make([]int, 0)
	for _, v := range strings.Split(readLine(), " ") {
		i, _ := strconv.Atoi(v)
		result = append(result, i)
	}
	return result
}

var reader = bufio.NewReaderSize(os.Stdin, 1e6)

func readLine() string {
	result := make([]byte, 0, 1e6)
	for {
		line, remains, e := reader.ReadLine()
		if e != nil {
			panic(e)
		}
		result = append(result, line...)
		if !remains {
			break
		}
	}
	return string(result)
}

Score : 400 points

Problem Statement

At an arcade, Takahashi is playing a game called RPS Battle, which is played as follows:

The player plays N rounds of Rock Paper Scissors against the machine. (See Notes for the description of Rock Paper Scissors. A draw also counts as a round.)

Each time the player wins a round, depending on which hand he/she uses, he/she earns the following score (no points for a draw or a loss):

R points for winning with Rock;

S points for winning with Scissors;

P points for winning with Paper.

However, in the i-th round, the player cannot use the hand he/she used in the (i-K)-th round. (In the first K rounds, the player can use any hand.)

Before the start of the game, the machine decides the hand it will play in each round. With supernatural power, Takahashi managed to read all of those hands.

The information Takahashi obtained is given as a string T. If the i-th character of T (1 \leq i \leq N) is r, the machine will play Rock in the i-th round. Similarly, p and s stand for Paper and Scissors, respectively.

What is the maximum total score earned in the game by adequately choosing the hand to play in each round?

Notes

In this problem, Rock Paper Scissors can be thought of as a two-player game, in which each player simultaneously forms Rock, Paper, or Scissors with a hand.

If a player chooses Rock and the other chooses Scissors, the player choosing Rock wins;

if a player chooses Scissors and the other chooses Paper, the player choosing Scissors wins;

if a player chooses Paper and the other chooses Rock, the player choosing Paper wins;

if both players play the same hand, it is a draw.

Constraints

2 \leq N \leq 10^5

1 \leq K \leq N-1

1 \leq R,S,P \leq 10^4

N,K,R,S, and P are all integers.

|T| = N

T consists of r, p, and s.

Input

Input is given from Standard Input in the following format:

N K
R S P
T

Output

Print the maximum total score earned in the game.

Sample Input 1

5 2
8 7 6
rsrpr

Sample Output 1

27

The machine will play {Rock, Scissors, Rock, Paper, Rock}.

We can, for example, play {Paper, Rock, Rock, Scissors, Paper} against it to earn 27 points.
We cannot earn more points, so the answer is 27.

Sample Input 2

7 1
100 10 1
ssssppr

Sample Output 2

211

Sample Input 3

30 5
325 234 123
rspsspspsrpspsppprpsprpssprpsr

Sample Output 3

4996


package main

import (
	"fmt"
	"sort"
)

func main() {
	var n, m int
	var score int64
	var power []int

	fmt.Scanf("%d %d", &n, &m)

	for i := 0; i < n; i++ {
		var tmp int
		fmt.Scanf("%d", &tmp)
		power = append(power, tmp)
	}

	sort.Ints(power)

	min := findByBTree(power, m, numOfElem)

	score, minNum, count := calcTotal(power, min)

	if m < count {
		score -= int64(minNum * (count - m))
	}

	fmt.Print(score)
}

func calcTotal(array []int, min int) (int64, int, int) {
	l := len(array)
	total := int64(0)
	minNum := 200000
	count := 0
	cache := []int64{0}
	cacheBound := make(map[int]int)
	sum := 0
	for _, a := range array {
		cache = append(cache, int64(a+sum))
		sum += a
	}

	max := cache[len(cache) - 1]
	for _, a := range array {
		bound := 0
		if val, ok := cacheBound[a]; ok {
			bound = val
		} else {
			bound = findLowerBound(array, min - a)
			cacheBound[a] = bound
		}
		if bound != -1 {
			count += l - bound
			total += max - cache[bound] + int64(a * (l - bound))
			if minNum > a + array[bound] {
				minNum = a + array[bound]
			}
		}
	}
	return total, minNum, count
}

func findByBTree(array []int, target int, check func(array []int, min int, target int) int) int {
	left := array[0]
	right := array[len(array)-1] * 2
	mid := 0
	count := 0
	var countCache []int
	var midCache []int
	for left <= right {
		mid = (left + right) / 2
		count = check(array, mid, target)
		if count == target {
			return mid
		} else if count > target {
			left = mid + 1
		} else if count < target {
			right = mid - 1
		}
		countCache = append(countCache, count)
		midCache = append(midCache, mid)
	}

	if count >= target {
		return mid
	}
	for i := len(countCache) - 1; i >= 0; i-- {
		if countCache[i] > target {
			return midCache[i]
		}
	}
	return -1
}

func numOfElem(array []int, min int, target int) int {
	len := len(array)
	count := 0
	cacheBound := make(map[int]int)
	for i := len - 1; i >= 0; i-- {
		if target < count {
			break
		}
		index := 0
		if val, ok := cacheBound[min - array[i]]; ok {
			index = val
		} else {
			index = findLowerBound(array, min-array[i])
			cacheBound[min-array[i]] = index
		}
		if index != -1 {
			count += len - index
		}
	}

	return count
}

func findLowerBound(array []int, target int) int {
	l := len(array)
	left := 0
	right := l - 1
	mid := -1
	tmp := 0
	var tmpCache []int
	var midCache []int
	for left <= right {
		mid = (left + right) / 2
		tmp = array[mid]
		if tmp == target {
			for mid > 1 && array[mid] == array[mid-1] {
				mid--
			}
			break
		} else if tmp < target {
			left = mid + 1
		} else if tmp > target {
			right = mid - 1
		}
		tmpCache = append(tmpCache, tmp)
		midCache = append(midCache, mid)
		if left > right {
			if left == l {
				mid = -1
			}
			break
		}
	}

	if tmp >= target {
		return mid
	}
	for i := len(tmpCache) - 1; i >= 0; i-- {
		if tmpCache[i] > target {
			return midCache[i]
		}
	}
	return -1
}

Score : 500 points

Problem Statement

Takahashi has come to a party as a special guest.
There are N ordinary guests at the party. The i-th ordinary guest has a power of A_i.

Takahashi has decided to perform M handshakes to increase the happiness of the party (let the current happiness be 0).
A handshake will be performed as follows:

Takahashi chooses one (ordinary) guest x for his left hand and another guest y for his right hand (x and y can be the same).

Then, he shakes the left hand of Guest x and the right hand of Guest y simultaneously to increase the happiness by A_x+A_y.

However, Takahashi should not perform the same handshake more than once. Formally, the following condition must hold:

Assume that, in the k-th handshake, Takahashi shakes the left hand of Guest x_k and the right hand of Guest y_k. Then, there is no pair p, q (1 \leq p < q \leq M) such that (x_p,y_p)=(x_q,y_q).

What is the maximum possible happiness after M handshakes?

Constraints

1 \leq N \leq 10^5

1 \leq M \leq N^2

1 \leq A_i \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N

Output

Print the maximum possible happiness after M handshakes.

Sample Input 1

5 3
10 14 19 34 33

Sample Output 1

202

Let us say that Takahashi performs the following handshakes:

In the first handshake, Takahashi shakes the left hand of Guest 4 and the right hand of Guest 4.

In the second handshake, Takahashi shakes the left hand of Guest 4 and the right hand of Guest 5.

In the third handshake, Takahashi shakes the left hand of Guest 5 and the right hand of Guest 4.

Then, we will have the happiness of (34+34)+(34+33)+(33+34)=202.

We cannot achieve the happiness of 203 or greater, so the answer is 202.

Sample Input 2

9 14
1 3 5 110 24 21 34 5 3

Sample Output 2

1837

Sample Input 3

9 73
67597 52981 5828 66249 75177 64141 40773 79105 16076

Sample Output 3

8128170


package main

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

func out(x ...interface{}) {
	fmt.Println(x...)
}

var sc = bufio.NewScanner(os.Stdin)

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

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

// min, max, asub, absなど基本関数
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 asub(a, b int) int {
	if a > b {
		return a - b
	}
	return b - a
}

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

func lowerBound(a []int, x int) int {
	l := 0
	r := len(a) - 1
	for l <= r {
		m := (l + r) / 2
		if a[m] >= x {
			r = m - 1
		} else {
			l = m + 1
		}
	}
	return l
}

func calc(a, s []int, x int) (int, int) {
	tot := 0
	num := 0
	n := len(a)
	for i := 0; i < n; i++ {
		j := lowerBound(a, x-a[i])
		num += n - j
		tot += s[n] - s[j]
		tot += a[i] * (n - j)
	}
	return tot, num
}

func main() {
	sc.Split(bufio.ScanWords)
	N, M := getInt(), getInt()
	a := make([]int, N)
	for i := 0; i < N; i++ {
		a[i] = getInt()
	}
	sort.Ints(a)
	b := make([]int, N+1)
	for i := 0; i < N; i++ {
		b[i+1] = b[i] + a[i]
	}

	l := 0
	r := 200005
	for l+1 < r {
		c := (l + r) >> 1
		_, num := calc(a, b, c)
		if num >= M {
			l = c
		} else {
			r = c
		}
	}
	ans, num := calc(a, b, l)
	ans -= (num - M) * l
	out(ans)
}


package main

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

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

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

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

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

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

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

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

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

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

	n := getNextInt(scanner)
	m := getNextInt64(scanner)

	aa := make(I64, n)
	ss := make([]int64, n+1)
	for i := 0; i < n; i++ {
		aa[i] = getNextInt64(scanner)
	}

	sort.Sort(aa)
	for i := 0; i < n; i++ {
		ss[i+1] = ss[i] + aa[i]
	}

	var ans int64
	l := int64(-1)
	r := aa[0]<<1 + 1

	for l+1 < r {
		mid := (l + r) >> 1
		c := m
		for i := 0; i < n; i++ {
			ll := i - 1
			rr := n
			for ll+1 < rr {
				mm := (ll + rr) >> 1
				if aa[mm]+aa[i] < mid {
					rr = mm
					continue
				}
				ll = mm
			}
			if rr-i == 0 {
				continue
			}
			c -= int64(rr-i-1)<<1 + 1
		}
		if c < 0 {
			l = mid
			continue
		}
		r = mid
	}

	c := m
	for i := 0; i < n; i++ {
		ll := i - 1
		rr := n
		for ll+1 < rr {
			mm := (ll + rr) >> 1
			if aa[mm]+aa[i] <= l {
				rr = mm
				continue
			}
			ll = mm
		}
		if rr-i == 0 {
			continue
		}
		ans += (int64(rr-i-1)<<1)*aa[i] + (ss[rr]-ss[i])<<1
		c -= int64(rr-i-1)<<1 + 1
	}
	ans += c * l

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

type I64 []int64

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


package main

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

var sc = bufio.NewScanner(os.Stdin)

func main() {
	scanInit()

	n := nextInt64()
	a := nextInt64()
	b := nextInt64()

	if (b-a-1)%2 == 1 {
		fmt.Println((b - a + 1) / 2)
		return
	}
	fmt.Println(min(b-1, n-a))

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

// ---- readfunc
func scanInit() {
	const cap = 200 * 1024 // Default=64
	var buf = make([]byte, cap)
	sc.Buffer(buf, cap)
	sc.Split(bufio.ScanWords)
	return
}
func nextInt64() int64 {
	sc.Scan()
	i, e := strconv.ParseInt(sc.Text(), 10, 64)
	if e != nil {
		panic(e)
	}
	return i
}
func nextStr() string {
	sc.Scan()
	return sc.Text()
}

Score : 300 points

Problem Statement

2N players are running a competitive table tennis training on N tables numbered from 1 to N.

The training consists of rounds.
In each round, the players form N pairs, one pair per table.
In each pair, competitors play a match against each other.
As a result, one of them wins and the other one loses.

The winner of the match on table X plays on table X-1 in the next round,
except for the winner of the match on table 1 who stays at table 1.

Similarly, the loser of the match on table X plays on table X+1 in the next round,
except for the loser of the match on table N who stays at table N.

Two friends are playing their first round matches on distinct tables A and B.
Let's assume that the friends are strong enough to win or lose any match at will.
What is the smallest number of rounds after which the friends can get to play a match against each other?

Constraints

2 \leq N \leq 10^{18}

1 \leq A < B \leq N

All input values are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print the smallest number of rounds after which the friends can get to play a match against each other.

Sample Input 1

5 2 4

Sample Output 1

1

If the first friend loses their match and the second friend wins their match, they will both move to table 3 and play each other in the next round.

Sample Input 2

5 2 3

Sample Output 2

2

If both friends win two matches in a row, they will both move to table 1.


package main

import "fmt"

func main() {
	var N, A, B int
	fmt.Scan(&N, &A, &B)
	var ans int
	if (B-A)%2 == 0 {
		ans = (B - A) / 2
	} else {
		// 答えは以下の(A)+(B)+(C)になる
		// (A) 片方が1卓あるいはN卓に移動するまでに必要なラウンド - min(A-1, N-B)
		// (B) 偶奇を調整するラウンド - 1ラウンド
        // (C) 双方が出会うためのラウンド - 最初は同じ方向に進むので、距離が縮まらない。偶奇調整後は近くが、調整ラウンド1分だけ距離が縮まっているので、必要なラウンド数は(B-A-1)/2となる
		ans = min(A-1, N-B) + 1 + (B-A-1)/2
	}
	fmt.Println(ans)
}
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}


package main

import "fmt"

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

	if a > b {
		a, b = b, a
	}

	if (b-a)%2 == 0 {
		result = (b - a) / 2
	} else {
		if a < (games - b) {
			result = b - 1
		} else {
			result = games - a - 1
		}
	}
	fmt.Println(result)
}


package main

import (
	"fmt"
	"sort"
)

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

	sort.Ints(a)

	for i := 0; i < 2; i++ {
		if a[i] != i+1 {
			fmt.Println(i + 1)
		}
	}

	fmt.Printf("Hello, world\n")
}

Score: 100 points

Problem Statement

Takahashi is solving quizzes. He has easily solved all but the last one.

The last quiz has three choices: 1, 2, and 3.

With his supernatural power, Takahashi has found out that the choices A and B are both wrong.

Print the correct choice for this problem.

Constraints

Each of the numbers A and B is 1, 2, or 3.

A and B are different.

Input

Input is given from Standard Input in the following format:

A
B

Output

Print the correct choice.

Sample Input 1

3
1

Sample Output 1

2

When we know 3 and 1 are both wrong, the correct choice is 2.

Sample Input 2

1
2

Sample Output 2

3


package main

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

// I/O
type Scanner struct {
	sc *bufio.Scanner
}

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

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

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

func (s *Scanner) nextFloat() float64 {
	f, e := strconv.ParseFloat(s.nextStr(), 64)
	if e != nil {
		panic(e)
	}
	return f
}

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

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

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

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

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

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

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

// Sort
type Val struct {
	id, num int
}
type ByNum []Val

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

func main() {
	sc := NewScanner()
	wtr := bufio.NewWriter(os.Stdout)
	A, B := sc.nextInt(), sc.nextInt()

	if A != 1 && B != 1 {
		fmt.Fprintln(wtr, 1)
	} else if A != 2 && B != 2 {
		fmt.Fprintln(wtr, 2)
	} else {
		fmt.Fprintln(wtr, 3)
	}
	wtr.Flush()
}


package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	inputArray, _ := toIntArray(splitInput(scanner, " "))
	n := inputArray[0]
	st := splitInput(scanner, " ")
	s := st[0]
	t := st[1]

	for i := 0; i < n; i++ {
		fmt.Printf("%s", s[i:i+1])
		fmt.Printf("%s", t[i:i+1])
	}
	fmt.Println()
}

func splitInput(scanner *bufio.Scanner, sep string) []string {
	scanner.Scan()
	return strings.Split(scanner.Text(), sep)
}

func toIntArray(str []string) ([]int, error) {
	length := len(str)
	resVal := make([]int, length)
	var err error
	for i := 0; i < length; i++ {
		resVal[i], err = strconv.Atoi(str[i])
		if err != nil {
			return nil, err
		}
	}
	return resVal, nil
}

Score : 200 points

Problem Statement

Given are strings s and t of length N each, both consisting of lowercase English letters.

Let us form a new string by alternating the characters of S and the characters of T, as follows: the first character of S, the first character of T, the second character of S, the second character of T, ..., the N-th character of S, the N-th character of T. Print this new string.

Constraints

1 \leq N \leq 100

|S| = |T| = N

S and T are strings consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S T

Output

Print the string formed.

Sample Input 1

2
ip cc

Sample Output 1

icpc

Sample Input 2

8
hmhmnknk uuuuuuuu

Sample Output 2

humuhumunukunuku

Sample Input 3

5
aaaaa aaaaa

Sample Output 3

aaaaaaaaaa


package main

import (
	"fmt"
)

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

func main() {
	var a, b int
	fmt.Scan(&a, &b)
	cal := a * b / gcd(a, b)

	fmt.Println(cal)
}

Score : 300 points

Problem Statement

Takahashi is organizing a party.

At the party, each guest will receive one or more snack pieces.

Takahashi predicts that the number of guests at this party will be A or B.

Find the minimum number of pieces that can be evenly distributed to the guests in both of the cases predicted.

We assume that a piece cannot be divided and distributed to multiple guests.

Constraints

1 \leq A, B \leq 10^5

A \neq B

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the minimum number of pieces that can be evenly distributed to the guests in both of the cases with A guests and B guests.

Sample Input 1

2 3

Sample Output 1

6

When we have six snack pieces, each guest can take three pieces if we have two guests, and each guest can take two if we have three guests.

Sample Input 2

123 456

Sample Output 2

18696

Sample Input 3

100000 99999

Sample Output 3

9999900000