package main

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

var sc = bufio.NewScanner(os.Stdin)

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

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

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

func main() {
	sc.Split(bufio.ScanWords)
	n, a, b := nextInt(), nextInt(), nextInt()
	if a > b {
		fmt.Println(0)
		return
	}
	if n-2 < 0 && a == b {
		fmt.Println(1)
		return
	}

	ans := int64(n-2)*(int64(b-a)) + 1
	fmt.Println(ans)
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

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

	N, A, B := nextInt(), nextInt(), nextInt()
	if A > B {
		fmt.Println(0)
	} else if N == 1 {
		if A == B {
			fmt.Println(1)
		} else {
			fmt.Println(0)
		}
	} else {
		fmt.Println((N-2)*(B-A) + 1)
	}

}

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

Score : 200 points

Problem Statement

Snuke has N integers. Among them, the smallest is A, and the largest is B.
We are interested in the sum of those N integers. How many different possible sums there are?

Constraints

1 ≤ N,A,B ≤ 10^9

A and B are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print the number of the different possible sums.

Sample Input 1

4 4 6

Sample Output 1

5

There are five possible sums: 18=4+4+4+6, 19=4+4+5+6, 20=4+5+5+6, 21=4+5+6+6 and 22=4+6+6+6.

Sample Input 2

5 4 3

Sample Output 2

0

Sample Input 3

1 7 10

Sample Output 3

0

Sample Input 4

1 3 3

Sample Output 4

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.


/*
URL:
https://atcoder.jp/contests/abc062/tasks/arc074_b
*/

package main

import (
	"bufio"
	"container/heap"
	"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
	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
	A []int

	used    [300000 + 50]bool
	befSums [300000 + 50]int
	aftSums [300000 + 50]int
)

func main() {
	n = ReadInt()
	A = ReadIntSlice(n * 3)

	befPQ, aftPQ := NewBeforePQ(), NewAfterPQ()

	befSum, aftSum := 0, 0

	for i := 0; i < n; i++ {
		befPQ.push(&Before{pri: A[i]})
		befSum += A[i]
		used[i] = true
	}
	befSums[n-1] = befSum
	for i := n; i < 2*n; i++ {
		bp := befPQ.pop()
		if bp.pri < A[i] {
			// 交換
			befSum -= bp.pri
			befSum += A[i]
			befPQ.push(&Before{pri: A[i]})
		} else {
			// もとに戻す
			befPQ.push(bp)
		}

		befSums[i] = befSum
	}

	for i := 2 * n; i < 3*n; i++ {
		aftPQ.push(&After{pri: A[i]})
		aftSum += A[i]
		used[i] = true
	}
	aftSums[2*n-1] = aftSum
	for i := 2*n - 1; i >= n; i-- {
		ap := aftPQ.pop()
		if ap.pri > A[i] {
			// 交換
			aftSum -= ap.pri
			aftSum += A[i]
			aftPQ.push(&After{pri: A[i]})
		} else {
			// もとに戻す
			aftPQ.push(ap)
		}

		aftSums[i-1] = aftSum
	}

	ans := -INF_BIT60
	for i := n - 1; i < 2*n; i++ {
		ChMax(&ans, befSums[i]-aftSums[i])
	}
	fmt.Println(ans)
}

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

type After struct {
	pri int
}
type AfterPQ []*After

// Interfaces
func NewAfterPQ() *AfterPQ {
	temp := make(AfterPQ, 0)
	pq := &temp
	heap.Init(pq)

	return pq
}
func (pq *AfterPQ) push(target *After) {
	heap.Push(pq, target)
}
func (pq *AfterPQ) pop() *After {
	return heap.Pop(pq).(*After)
}

func (pq AfterPQ) Len() int           { return len(pq) }
func (pq AfterPQ) Less(i, j int) bool { return pq[i].pri > pq[j].pri } // <: ASC, >: DESC
func (pq AfterPQ) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
}
func (pq *AfterPQ) Push(x interface{}) {
	item := x.(*After)
	*pq = append(*pq, item)
}
func (pq *AfterPQ) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	*pq = old[0 : n-1]
	return item
}

type Before struct {
	pri int
}
type BeforePQ []*Before

// Interfaces
func NewBeforePQ() *BeforePQ {
	temp := make(BeforePQ, 0)
	pq := &temp
	heap.Init(pq)

	return pq
}
func (pq *BeforePQ) push(target *Before) {
	heap.Push(pq, target)
}
func (pq *BeforePQ) pop() *Before {
	return heap.Pop(pq).(*Before)
}

func (pq BeforePQ) Len() int           { return len(pq) }
func (pq BeforePQ) Less(i, j int) bool { return pq[i].pri < pq[j].pri } // <: ASC, >: DESC
func (pq BeforePQ) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
}
func (pq *BeforePQ) Push(x interface{}) {
	item := x.(*Before)
	*pq = append(*pq, item)
}
func (pq *BeforePQ) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	*pq = old[0 : n-1]
	return item
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

	return string(res)
}

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

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

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

	return string(res)
}

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

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

Score : 500 points

Problem Statement

Let N be a positive integer.

There is a numerical sequence of length 3N, a = (a_1, a_2, ..., a_{3N}).
Snuke is constructing a new sequence of length 2N, a', by removing exactly N elements from a without changing the order of the remaining elements.
Here, the score of a' is defined as follows: (the sum of the elements in the first half of a') - (the sum of the elements in the second half of a').

Find the maximum possible score of a'.

Constraints

1 ≤ N ≤ 10^5

a_i is an integer.

1 ≤ a_i ≤ 10^9

Partial Score

In the test set worth 300 points, N ≤ 1000.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{3N}

Output

Print the maximum possible score of a'.

Sample Input 1

2
3 1 4 1 5 9

Sample Output 1

1

When a_2 and a_6 are removed, a' will be (3, 4, 1, 5), which has a score of (3 + 4) - (1 + 5) = 1.

Sample Input 2

1
1 2 3

Sample Output 2

-1

For example, when a_1 are removed, a' will be (2, 3), which has a score of 2 - 3 = -1.

Sample Input 3

3
8 2 2 7 4 6 5 3 8

Sample Output 3

5

For example, when a_2, a_3 and a_9 are removed, a' will be (8, 7, 4, 6, 5, 3), which has a score of (8 + 7 + 4) - (6 + 5 + 3) = 5.


package main

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

)

/*********** PriorityQueue ***********/
type PriorityQueue struct {
    arr []interface{}
    comps []CompFunc
}

/*
p < q ... -1
p == q ... 0
p > q ... 1
*/
type CompFunc func(p, q interface{}) int

func NewPriorityQueue() *PriorityQueue {
    return new(PriorityQueue)
}

func (pq PriorityQueue) Len() int {
    return len(pq.arr)
}

func (pq PriorityQueue) Swap(i, j int) {
    pq.arr[i], pq.arr[j] = pq.arr[j], pq.arr[i]
}

func (pq PriorityQueue) Less(i, j int) bool{
    for _, comp := range pq.comps {
        result := comp(pq.arr[i], pq.arr[j])
        switch result {
            case -1: return true
            case 1:  return false
            case 0:  continue
        }
    }
    return true
}

func (pq *PriorityQueue) Push(x interface{}) {
    pq.arr = append(pq.arr, x)
}

func (pq *PriorityQueue) Pop() interface{} {
    n := pq.Len()
    item := pq.arr[n - 1]
    pq.arr = pq.arr[:n - 1]
    return item
}

func (pq *PriorityQueue) IsEmpty() bool {
    return pq.Len() == 0
}

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

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

func main() {
    sc.Split(bufio.ScanWords)
    comp := func(p, q interface{}) int {
        if p.(int) < q.(int) {
            return -1
        } else if p.(int) == q.(int) {
            return 0
        } else {
            return 1
        }
    }
    n := readInt()
    preQue := new(PriorityQueue)
    preQue.comps = append(preQue.comps, comp)
    sufQue := new(PriorityQueue)
    sufQue.comps = append(sufQue.comps, comp)
    mid := make([]int, n)
    var preScore, sufScore int
    preScores := make([]int, n + 1)
    sufScores := make([]int, n + 1)
    for i := 0; i < n; i++ {
        v := readInt()
        preScore += v
        heap.Push(preQue, v)
    }
    for i := 0; i < n; i++ {
        mid[i] = readInt()
    }
    for i := 0; i < n; i++ {
        v := -readInt()
        sufScore += v
        heap.Push(sufQue, v)
    }

    preScores[0] = preScore
    for i, m := range mid {
        v := heap.Pop(preQue).(int)
        if v < m {
            preScore += (m - v)
            heap.Push(preQue, m)
        } else {
            heap.Push(preQue, v)
        }
        preScores[i + 1] = preScore
    }

    sufScores[0] = sufScore
    for i := n - 1; i >= 0; i-- {
        m := mid[i]
        v := heap.Pop(sufQue).(int)
        if -v > m {
            sufScore += -v - m
            heap.Push(sufQue, -m)
        } else {
            heap.Push(sufQue, v)
        }
        sufScores[n - i] = sufScore
    }
    ans := -10000000000000000
    for i := 0; i <= n; i++ {
        score := preScores[i] + sufScores[n - i]
        if ans < score {
            ans = score
        }
    }
    fmt.Println(ans)
}


package main

import (
	"fmt"
	"strings"
)

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

  	head := strings.Index(s, "A")
  	end  := strings.LastIndex(s, "Z")

  	ans := end - head + 1
	fmt.Printf("%d\n", ans)
}

Score : 200 points

Problem Statement

Snuke has decided to construct a string that starts with A and ends with Z, by taking out a substring of a string s (that is, a consecutive part of s).

Find the greatest length of the string Snuke can construct. Here, the test set guarantees that there always exists a substring of s that starts with A and ends with Z.

Constraints

1 ≦ |s| ≦ 200{,}000

s consists of uppercase English letters.

There exists a substring of s that starts with A and ends with Z.

Input

The input is given from Standard Input in the following format:

s

Output

Print the answer.

Sample Input 1

QWERTYASDFZXCV

Sample Output 1

5

By taking out the seventh through eleventh characters, it is possible to construct ASDFZ, which starts with A and ends with Z.

Sample Input 2

ZABCZ

Sample Output 2

4

Sample Input 3

HASFJGHOGAKZZFEGA

Sample Output 3

12


package main

import (
  "fmt"
  "strings"
)

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

  findA := strings.Index(s, "A")
  findZ := strings.LastIndex(s, "Z")

  fmt.Println(findZ - findA + 1)
}


package main

import (
	"fmt"
	"strings"
)

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

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

	fmt.Println(strings.LastIndex(s, "Z") - strings.Index(s, "A") + 1)
}


package main

import (
	"fmt"
	"regexp"
)

func main() {
	var s string
	fmt.Scan(&s)
	re := regexp.MustCompile("A.+Z")
	ss := re.FindString(s)
	fmt.Println(len(ss))
}


package main

import (
	"fmt"
)

func main() {
	var s string
	var si, ei int = -1, -1
	fmt.Scan(&s)

	for i :=0; i<len(s); i++ {
		sc := string(s[i])
		if si < 0 && sc == "A" {
			si = i
		}
		if sc == "Z" {
			ei = i
		}
	}

	fmt.Println(ei - si + 1)
}


package main

import (
	"fmt"
	"strings"
)

func main() {
	var s string
	fmt.Scan(&s)
	fmt.Println(strings.LastIndex(s, "Z") - strings.Index(s, "A") + 1)
}


package main

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

func main() {
	var S string
	r := bufio.NewScanner(os.Stdin)
	b := make([]byte, 10000000)
	r.Buffer(b, 10000000)
	r.Scan()
	S = r.Text()

	a := -1
	z := -1
	for i := 0; i < len(S); i++ {
		if S[i:i+1] == "A" && a < 0 {
			a = i
		}
		if S[len(S)-1-i:len(S)-i] == "Z" && z < 0 {
			z = len(S) - 1 - i
		}
	}
	fmt.Println(z - a + 1)
}


package main
import . "fmt"
import "strings"
func main() {
  var s string
  Scan(&s)
  Println(strings.LastIndex(s,"Z")-strings.Index(s,"A")+1)
}


package main

import (
  "fmt"
  "strings"
)

func Reverse(s string) (result string) {
  for _, v := range s {
    result = string(v) + result
  }
  return
}

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

  fmt.Println((len(s) - strings.Index(Reverse(s), "Z")) - strings.Index(s, "A"))

}


package main

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

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

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

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

func main() {
	sc.Split(bufio.ScanWords)
	K, S := nextInt(), nextInt()

	fmt.Printf("%d\n", ABC051B(K, S))
}

// ABC051B ...
func ABC051B(K, S int) (res int) {
	for x := 0; x <= K; x++ {
		for y := 0; y <= K; y++ {
			z := S - x - y
			if 0 <= z && z <= K {
				res++
			}
		}
	}

	return
}

Score : 200 points

Problem Statement

You are given two integers K and S.

Three variable X, Y and Z takes integer values satisfying 0≤X,Y,Z≤K.

How many different assignments of values to X, Y and Z are there such that X + Y + Z = S?

Constraints

2≤K≤2500

0≤S≤3K

K and S are integers.

Input

The input is given from Standard Input in the following format:

K S

Output

Print the number of the triples of X, Y and Z that satisfy the condition.

Sample Input 1

2 2

Sample Output 1

6

There are six triples of X, Y and Z that satisfy the condition:

X = 0, Y = 0, Z = 2

X = 0, Y = 2, Z = 0

X = 2, Y = 0, Z = 0

X = 0, Y = 1, Z = 1

X = 1, Y = 0, Z = 1

X = 1, Y = 1, Z = 0

Sample Input 2

5 15

Sample Output 2

1

The maximum value of X + Y + Z is 15, achieved by one triple of X, Y and Z.


package main

import "fmt"

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

	var cnt int
	for x := 0; x <= k; x++ {
		for y := 0; y <= k; y++ {
			z := s - x - y
			if 0 <= z && z <= k {
				cnt++
			}
		}
	}

	fmt.Println(cnt)
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

func init() {
	sc.Split(bufio.ScanWords)
	sc.Buffer([]byte{}, math.MaxInt64)
}

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

func main() {
	var K, S int
	K, S = readInt(), readInt()
	cnt := 0
	if K > S {
		K = S
	}
	for i := 0; i <= K; i++ {
		for j := 0; j <= K; j++ {
			if k := S - (i + j); 0 <= k && k <= K {
				cnt++
			}
		}
	}
	fmt.Println(cnt)
}


package main

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

type contest struct {
	in  io.Reader
	out io.Writer
}

func (con *contest) Scan(a ...interface{}) (int, error) {
	return fmt.Fscan(con.in, a...)
}
func (con *contest) Scanln(a ...interface{}) (int, error) {
	return fmt.Fscanln(con.in, a...)
}
func (con *contest) Scanf(f string, a ...interface{}) (int, error) {
	return fmt.Fscanf(con.in, f, a...)
}
func (con *contest) Print(a ...interface{}) (int, error) {
	return fmt.Fprint(con.out, a...)
}
func (con *contest) Println(a ...interface{}) (int, error) {
	return fmt.Fprintln(con.out, a...)
}
func (con *contest) Printf(f string, a ...interface{}) (int, error) {
	return fmt.Fprintf(con.out, f, a...)
}
func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	con := &contest{in: in, out: out}
	con.main()
}

func (con *contest) main() error {
	var K, S int
	con.Scan(&K, &S)
	if K > S {
		K = S
	}
	C := 0
	for X := 0; X <= K; X++ {
		for Y := 0; Y <= S-X && Y <= K; Y++ {
			if S-X-Y <= K {
				C++
			}
		}
	}
	con.Println(C)
	return nil
}


package main

import (
	"fmt"

)

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

	count := 0

	for x := 0; x <= k; x++ {
		for y := x; y <= k; y++ {
			for z := y; z <= k; z++ {
				if s == x + y + z {
					switch compare(x, y, z) {
					case "three":
						count++
					case "two":
						count += 3
					case "diff":
						count += 6
					}
				}
			}
		}
	}
}

func compare(x, y, z int) string {
	if z == y || y == x {
		if z == x {
			return "three"
		}
		return "two"
	}
	return "diff"
}


package main

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

func solve() {
	k, s := getInt(), getInt()
	m := min(k, s)

	ans := 0
	for x := 0; x <= m; x++ {
		for y := 0; y <= m; y++ {
			z := s - (x + y)
			if (z >= 0) && (z <= k) {
				ans++
			}
		}
	}

	fmt.Fprintln(wr, ans)
}

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

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

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

const (
	inf = 1 << 60
	// mod = 1000000007
)

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

func main() {
	// buf := 200001
	// sc.Buffer(make([]byte, buf), buf)
	sc.Split(bufio.ScanWords)
	solve()
	wr.Flush()
}

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

func getIntSlice(n int) []int {
	is := make([]int, n)
	for i := range is {
		is[i] = getInt()
	}
	return is
}

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

func getRunes() []rune {
	return []rune(getString())
}


package main

import "fmt"

func main(){
	var K, S int
	fmt.Scan(&K, &S)
	var count int
	for i := 0; i <= K; i++ {
		if K > S || K * 3 < S {
			break
		}
		for j := 0; j <= K; j++ {
			if i + j + S == S {
				count++
			}
		}

	}
	fmt.Println(count)
}


package main

import (
        "fmt"
)

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

        var cnt int

        for i := 0; i <= k; i++ {
                for j := 0; j <= k && i+j <= s; j++ {
                        for l := 0; l <= k; l++ {
                                if i+j+l == s {
                                        cnt++
                                }
                        }
                }
        }
        fmt.Println(cnt)

}


package main

import "fmt"

func main() {
	var k, s int
	fmt.Scanf("%d %d\n", &k, &s)
	cnt := 0
	for x := 0; x <= k; x++ {
		for y := 0; y <= k-x; y++ {
			cnt++
			//for z := 0; z <= k; z++ {
			//	if x+y+z == s {
			//		cnt++
			//	}
			//}
		}
	}
	fmt.Println(cnt)
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

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

func main() {
	s := scanStr()
	var n string
	n = strings.Replace(s, "drea", ",drea", -1)
	n = strings.Replace(n, "eras", ",eras", -1)

	if n[0:1] == "," {
		n = strings.TrimLeft(n, ",")
	}
	/*
		if n[len(n)-1:len(n)] == "," {
			n = strings.TrimRight(n, ",")
		}
	*/

	l := strings.Split(n, ",")
	fmt.Println(l)

	ok := true
	for _, i := range l {
		if i == "eraser" || i == "erase" || i == "dream" || i == "dreamer" {
			continue
		} else {
			ok = false
			break
		}
	}

	if ok {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

Score : 300 points

Problem Statement

You are given a string S consisting of lowercase English letters.
Another string T is initially empty.
Determine whether it is possible to obtain S = T by performing the following operation an arbitrary number of times:

Append one of the following at the end of T: dream, dreamer, erase and eraser.

Constraints

1≦|S|≦10^5

S consists of lowercase English letters.

Input

The input is given from Standard Input in the following format:

S

Output

If it is possible to obtain S = T, print YES. Otherwise, print NO.

Sample Input 1

erasedream

Sample Output 1

YES

Append erase and dream at the end of T in this order, to obtain S = T.

Sample Input 2

dreameraser

Sample Output 2

YES

Append dream and eraser at the end of T in this order, to obtain S = T.

Sample Input 3

dreamerer

Sample Output 3

NO


package main

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

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

	ed := len(text)
	isYes := true
	for ed > 0 {
		if ed-5 >= 0 && (text[ed-5:ed] == "dream" || text[ed-5:ed] == "erase") {
			ed = ed - 5
		} else if ed-6 >= 0 && text[ed-6:ed] == "eraser" {
			ed = ed - 6
		} else if ed-7 >= 0 && text[ed-7:ed] == "dreamer" {
			ed = ed - 7
		} else {
			isYes = false
			break
		}
	}

	if isYes {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}


package main
import (
   "fmt"
   "os"
   "bufio"
   "strconv"
)
var sc = bufio.NewScanner(os.Stdin)

func main() {
  sc.Split(bufio.ScanWords)
  s := nextString()
  str := []string{
	  //"maerd",
	  "dream",
	  //"remaerd",
	  "dreamer",
	  //"esare",
	  "erase",
	  "eraser",
	  //"resare",
  }

  for i := 0; i <len(str); i++{
	  str[i] = reverse(str[i])
  }

  s = reverse(s)

  if isExist(s, str) {
    fmt.Println("YES")
  } else {
    fmt.Println("NO")
  }

}

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

func isExist(s string, strList []string) (bool){
	listLen := len(strList)
	for 0 < len(s){
	  str := ""
      var ok bool
	  for i, v := range s {
	    str = str + string(v)
		for j := 0; j < listLen; j++ {
			if str == strList[j] {
				s = s[i + 1:]
				ok = true
				break
			}
		}
	  }
      if !ok {
        return false
      }

    }
	return true
}

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

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

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

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


package main
import (
   "fmt"
   "os"
   "bufio"
   "strconv"
)
var sc = bufio.NewScanner(os.Stdin)

func main() {
  sc.Split(bufio.ScanWords)
  s := nextString()
  str := []string{
	  "maerd",
	  "remaerd",
	  "esare",
	  "resare",
  }

  s = reverse(s)

  if isExist(s, str) {
    fmt.Println("YES")
  } else {
    fmt.Println("NO")
  }

}

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

func isExist(s string, strList []string) (bool){
	listLen := len(strList)
	for 0 < len(s){
	  str := ""
      var ok bool
	  for i, v := range s {
	    str = str + string(v)
		for j := 0; j < listLen; j++ {
			if str == strList[j] {
				s = s[i + 1:]
				ok = true
				break
			}
		}
	  }
      if !ok {
        return false
      }

    }
	return true
}

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

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

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

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


package main

import "fmt"

func main() {
	var s string
	fmt.Scan(&s)
	var check bool
	for ;; {
		check = true
		if len(s) == 0 {
			fmt.Println("YES")
			break
		}
		if len(s) < 5 || len(s) == 8 || len(s) == 9{
			fmt.Println("NO")
			break
		}
		if s[0:5] == "dream" {
			if len(s) == 5 || s[5:6] == "d" {
				s = s[5:]
				check = false
			} else if len(s) >= 7 && s[5:7] == "er" {
				if len(s) == 7 || s[7:8] == "d" || s[7:8] == "e" {
					s = s[7:]
					check = false
				} else if s[7:8] == "a" {
					s = s[5:]
					check = false
				}
			}
		} else if s[0:5] == "erase" {
			check = false
			if len(s) == 5 {
				s = s[5:]
			}
			if s[5:6] == "r" {
				s = s[6:]
			} else {
				s = s[5:]
			}
		}
		if check {
			fmt.Println("NO")
			break
		}
	}
}


package main

import "fmt"

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

	ss := map[string]bool{"maerd": true, "remaerd": true, "esare": true, "resare": true}

	t := ""
	for i := 0; i < len(s); i++ {
		t += string(s[i])
		if ss[t] {
			t = ""
		}
		if 7 < len(t) {
			break
		}
	}

	if t == "" {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}

}

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


package main

import "fmt"

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

	ss := map[string]bool{"maerd": true, "remaerd": true, "esare": true, "resare": true}
	l := len(s)
	t := ""
	for i := 0; i < l; i++ {
		t += string(s[l-i-1])
		if len(t) == 5 && ss[t] {
			t = ""
		} else if len(t) == 7 && ss[t] {
			t = ""
		} else if 7 < len(t) {
			fmt.Println("NO")
			return
		}
	}

	if t == "" {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}

}


package main

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

var SC = bufio.NewScanner(os.Stdin)

func main(){
  SC.Scan()
  S := SC.Text()
  // fmt.Scan(&S)

  // fmt.Println(S)
  //deramderam
  //dreamdreamer =>dreamdならdream
  //dreamerase
  //dreameraser => dreameraならdream

  //dreamerdream
  //dreamerdreamer => dreamerdならdreamer
  //dreamererase
  //dreamereraser => dreamereならdreamer

  //erasedream
  //erasedreamer => erasedならerase
  //eraseerase
  //eraseeraser => eraseeならerase

  //eraserdream
  //eraserdreamer => eraserdならeraser
  //erasererase
  //erasereraser => erasereならeraser

  var result string
  n := 0
  for {
    if len(S[n:]) == 5 && (S[n:] == "dream" || S[n:] == "erase") {
      result = "YES"
      break
    }else if len(S[n:]) == 6 && S[n:] == "eraser"{
      result = "YES"
      break
    }else if len(S[n:]) == 7 && S[n:] == "dreamer"{
      result = "YES"
      break
    }else if len(S[n:]) <= 8{
      result = "NO"
      break
    }else if S[n:n+7] == "dreamer" && S[n:n+8] != "dreamera"{
      n+=7 //dreamer
    }else if S[n:n+5] == "dream"{
      n+=5 //dream
    }else if S[n:n+5] == "erase" && S[n:n+6]!= "eraser"{
      n+=5 //erase
    }else if S[n:n+6] ==  "eraser"{
      n+=6
    }else{
      result = "NO"
      break
    }
    // fmt.Println(n)
  }
  fmt.Println(result)
}

// func saiki(S string){
//   if S[:5] == "dreamd"{ //dream
//     return saiki(S[5:])
//     }else if S[:7] == "dreamera"{ //dream
//       return saiki(S[5:])
//     }else if S[:7] == "dreamerd"{
//       return saiki(S[7:])
//     }else if S[:7] == "dreamere"{
//       return saiki(S[7:])
//     }else if S == ""{
//       return 'YES'
//     }else{
//       return 'NO'
//     }
// }


package main

import (
	"fmt"
)

func check(s string, d []string) bool {
	for i := 0; i < len(d); i++ {
		if len(s) < len(d[i]) {
			continue
		}

		if s[0:len(d[i])] == d[i] {
			if s == d[i] {
				return true
			}
			return check(s[len(d[i]):], d)
		}
	}
	return false
}

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

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

	d := []string{"esare", "resare", "maerd", "remaerd"}

	if check(s, d) {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}


package main

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

func solve() {
	s := next()
	// phrases := []string{"dream", "dreamer", "erase", "eraser"}
	r := regexp.MustCompile(`^(dream(er)?|eraser?)*$`)

	if r.MatchString(s) {
		println("YES")
	} else {
		println("NO")
	}
	return
}

func main() {
	defer out.Flush()
	in.Buffer(make([]byte, scBufSize), scBufSize)
	in.Split(bufio.ScanWords)

	solve()
}

// --- template ---

const scBufSize = 1e6

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

func println(a ...interface{}) {
	fmt.Fprintln(out, a...)
}

func printf(format string, a ...interface{}) {
	fmt.Fprintf(out, format, a...)
}

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

func nextInt() int {
	s := next()
	i, e := strconv.Atoi(s)
	if e != nil {
		fmt.Println(e)
	}
	return i
}

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

func unique(list []int) []int {
	m := make(map[int]bool)
	uniq := make([]int, 0)
	for _, e := range list {
		if !m[e] {
			m[e] = true
			uniq = append(uniq, e)
		}
	}
	return uniq
}


package main

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

func solve() {
	s := next()
	r := regexp.MustCompile(`^(eraser|erase|dreamer|dream)+$`)
	if r.MatchString(s) {
		println("YES")
	} else {
		println("NO")
	}
	return
}

func main() {
	defer out.Flush()
	in.Split(bufio.ScanLines)

	solve()
}

// --- template ---

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

func println(a ...interface{}) {
	fmt.Fprintln(out, a...)
}

func printf(format string, a ...interface{}) {
	fmt.Fprintf(out, format, a...)
}

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

func nextInt() int {
	s := next()
	i, e := strconv.Atoi(s)
	if e != nil {
		fmt.Println(e)
	}
	return i
}

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

func unique(list []int) []int {
	m := make(map[int]bool)
	uniq := make([]int, 0)
	for _, e := range list {
		if !m[e] {
			m[e] = true
			uniq = append(uniq, e)
		}
	}
	return uniq
}


// ABC 049 C - Daydream
package main

import (
    "fmt"
    "strings"
)

func main() {

    var s string
    fmt.Scan(&s)

    s = reverse(s)
    s = strings.Replace(s, "resare", "", -1)
    s = strings.Replace(s, "esare", "", -1)
    s = strings.Replace(s, "remaerd", "", -1)
    s = strings.Replace(s, "maerd", "", -1)

    var res string
    if len(s) == 0 {
        res = "YES"
    } else {
        res = "NO"
    }
    fmt.Println(res)
}

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


package main

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

var (
	stdin = bufio.NewScanner(os.Stdin)
	t     = []string{"dream", "dreamer", "erase", "eraser"}
)

func main() {
	stdin.Scan()
	s := stdin.Text()
	s = strings.Replace(s, t[0], "D", -1)
	s = strings.Replace(s, t[2], "E", -1)
	s = strings.Replace(s, "Der", "", -1)
	s = strings.Replace(s, "Er", "", -1)
	s = strings.Replace(s, "D", "", -1)
	s = strings.Replace(s, "E", "", -1)
	var o = "NO"
	if s == "" {
		o = "YES"
	}
	fmt.Println(o)
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

func main() {

	sc.Scan()
	S := sc.Bytes()
	if back(S) {
		fmt.Println("YES")
		return
	}

	fmt.Println("NO")
	return

	i := 0
	for i < len(S) {
		b, c := confirm(S[i:])
		if !b {
			fmt.Println("NO")
			return
		}

		i += c
	}

	fmt.Println("YES")

}

func back(b []byte) bool {
	S := reverse(b)
	divide := []([]byte){
		reverse([]byte("dream")), reverse([]byte("dreamer")), reverse([]byte("erase")), reverse([]byte("eraser")),
	}

	can := true
	for i := 0; i < len(S); {
		can2 := false
		for j := range divide {
			if bytes.HasPrefix(S[i:], divide[j]) {
				can2 = true
				i += len(divide[j])
				break
			}
		}
		if !can2 {
			return false
		}
	}
	return can
}

func reverse(b []byte) []byte {
	if len(b) == 1 {
		return b
	}
	for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
		b[i], b[j] = b[j], b[i]
	}

	return b
}

func try2(b []byte) bool {
	fmt.Println(string(b))
	if len(b) == 0 {
		return true
	}

	if len(b) < 5 {
		return false
	}

	if bytes.HasSuffix(b, []byte{'d', 'r', 'e', 'a', 'm'}) {
		return try2(b[:len(b)-5])
	} else if bytes.HasSuffix(b, []byte{'d', 'r', 'e', 'a', 'm', 'e', 'r'}) {
		return try2(b[:len(b)-7])
	} else if bytes.HasSuffix(b, []byte{'e', 'r', 'a', 's', 'e'}) {
		return try2(b[:len(b)-5])
	} else if bytes.HasSuffix(b, []byte{'e', 'r', 'a', 's', 'e', 'r'}) {
		return try2(b[:len(b)-6])
	}
	return false
}

func confirm(b []byte) (bool, int) {
	if has(b, []byte("dreamer")) {
		if len(b) == 7 {
			return true, 7
		}

		if b[7] == 'a' {
			return true, 5
		}

		return true, 7
	}

	if has(b, []byte("dream")) {
		return true, 5
	}

	if has(b, []byte("eraser")) {
		return true, 6
	}

	if has(b, []byte("erase")) {
		return true, 5
	}

	return false, -1
}

// b の先頭が t かどうか
func has(b []byte, t []byte) bool {
	if len(b) < len(t) {
		return false
	}

	for i := range t {
		if b[i] != t[i] {
			return false
		}
	}
	return true
}


package main

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

var sc = bufio.NewScanner(os.Stdin)

func main() {

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

	for i := 0; i < len(S); {
		b, c := confirm(S[i:])
		if !b {
			fmt.Println("NO")
			return
		}

		i += c
	}

	fmt.Println("YES")

}

func confirm(b []byte) (bool, int) {
	if has(b, []byte("dream")) {
		if len(b) == 5 {
			return true, 5
		}

		if has(b[5:], []byte("d")) {
			return true, 5
		}

		if !has(b[5:], []byte("er")) {
			return false, -1
		}

		if !has(b[5:], []byte("era")) {
			return true, 7
		}
		return true, 5
	}

	if has(b, []byte("eraser")) {
		return true, 6
	}

	if has(b, []byte("erase")) {
		return true, 5
	}

	return false, -1
}

// b の先頭が t かどうか
func has(b []byte, t []byte) bool {
	if len(b) < len(t) {
		return false
	}

	for i := range t {
		if b[i] != t[i] {
			return false
		}
	}
	return true
}


package main

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

func getScanner(fp *os.File) *bufio.Scanner {
	scanner := bufio.NewScanner(fp)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 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 main() {
	fp := os.Stdin
	if len(os.Args) > 1 {
		fp, _ = os.Open(os.Args[1])
	}

	scanner := getScanner(fp)
	writer := bufio.NewWriter(os.Stdout)

	s := getNextString(scanner)
	ans := "NO"
	if able(s) {
		ans = "YES"
	}
	fmt.Fprintln(writer, ans)
	writer.Flush()
}

func able(s string) bool {
	if s == "" {
		return true
	}

	ss := map[string]int{
		"dream":   5,
		"dreamer": 7,
		"erase":   5,
		"eraser":  6,
	}

	for sss, l := range ss {
		if len(s) < l {
			continue
		}
		if s[0:l] == sss {
			if able(s[l:]) {
				return true
			}
		}
	}

	return false
}


package main

import (
	"errors"
	"fmt"
	"os"
	"strings"
)

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

	if s[:1] != "d" && s[:1] != "e" {
		fmt.Println("NO")
		os.Exit(0)
	}

	for {
		var err error
		s, err = removeMatchedStr(s)
		if err != nil {
			fmt.Println("NO")
			os.Exit(0)
		}
		if len(s) == 0 {
			break
		}
	}
	fmt.Println("YES")
}

func removeMatchedStr(s string) (string, error) {
	if s == "dreamer" || s == "dream" || s == "eraser" || s == "erase" {
		return "", nil
	}

	if strings.HasSuffix(s, "dreamer") {
		return strings.TrimSuffix(s, "dreamer"), nil
	}

	if strings.HasSuffix(s, "dream") {
		return strings.TrimSuffix(s, "dream"), nil
	}

	if strings.HasSuffix(s, "eraser") {
		return strings.TrimSuffix(s, "eraser"), nil
	}

	if strings.HasSuffix(s, "erase") {
		return strings.TrimSuffix(s, "erase"), nil
	}

	return "", errors.New("string is not found")
}


package main

import (
	"fmt"
	"math"
	"regexp"
)

var S string

func main() {
	fmt.Scan(&S)
	r := regexp.MustCompile(`^(eraser|erase|dreamer|dream)`)
	if r.MatchString(S) {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

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

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

func combination(x, y int) int {
	return permutation(x, y) / permutation(y, y)
}

func permutation(x, y int) int {
	var ans int = 1
	for i := x - y; 0 < i; i-- {
		ans *= i
	}
	return ans
}

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

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

type XY struct {
	x int
	y int
}

type SortBy [][]int

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


package main

import (
	"fmt"
	"regexp"
)

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

	for 0 < len(str) {
		before := len(str)

		rep := regexp.MustCompile(`eraser$|erase$|dreamer$|dream$`)
		str = rep.ReplaceAllString(str, "")

		after := len(str)
		if before == after {
			fmt.Println("NO")
			return
		}
	}
	fmt.Println("YES")
}


package main

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

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Scan()
	s := sc.Text()
	if eraser(s, 0) {
		fmt.Println("YES")
		return
	}
	fmt.Println("NO")
}

func eraser(s string, i int) bool {
	if i == len(s) {
		return true
	}
	switch s[i] {
	case 'd':
		return eraseDream(s, i)
	case 'e':
		return eraseErase(s, i)
	default:
		return false
	}
	return false
}

func eraseDream(s string, i int) bool {
	i5 := i + 5
	if i5 < len(s) {
		i7 := i + 7
		if i7 < len(s) {
			if s[i7] == 'a' {
				return eraseErase(s, i5)
			}
			if s[i:i7] == "dreamer" {
				return eraser(s, i7)
			}
			return s[i:i5] == "dream" && eraser(s, i5)
		}
	}
	return i5 == len(s) && s[i:i5] == "dream"
}

func eraseErase(s string, i int) bool {
	i5 := i + 5
	if i5 < len(s) {
		if s[i5] == 'r' {
			if i5+1 < len(s) {
				return s[i:i5+1] == "eraser" && eraser(s, i5+1)
			}
			return i5+1 == len(s) && s[i:i5+1] == "eraser"
		}
		return s[i:i5] == "erase" && eraser(s, i5)
	}
	return i5 == len(s) && s[i:i5] == "erase"
}


package main

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

func main() {
	r := bufio.NewReaderSize(os.Stdin, 200000)
	s, _, _ := r.ReadLine()

	if daydream(string(s)) {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

func daydream(s string) bool {
	if s == "" {
		return true
	}

	if strings.HasPrefix(s, "dreamer") {
		return daydream(s[7:]) || daydream(s[5:])
	} else if strings.HasPrefix(s, "dream") {
		return daydream(s[5:])
	} else if strings.HasPrefix(s, "eraser") {
		return daydream(s[6:])
	} else if strings.HasPrefix(s, "erase") {
		return daydream(s[5:])
	}

	return false
}


package main

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

func main() {
	log.SetFlags(log.Lshortfile)
	nextReader = NewScanner()
	str := nextString()[0]
	words := []string{
		"eraser",
		"erase",
		"dreamer",
		"dream",
	}

	for {
		idx := -1
		for _, w := range words {
			idx = strings.LastIndex(str, w)
			//fmt.Printf("index: %d\n", idx)
			//fmt.Printf("len(w): %d\n", len(w))
			//fmt.Printf("len(str): %d\n", len(str))
			if idx == -1 {
				continue
			}
			if idx+len(w) != len(str) {
				fmt.Println("No")
				return
			} else {
				break
			}
		}
		if idx == -1 {
			fmt.Println("No")
			return
		}
		str = str[:idx]
		if len(str) == 0 {
			fmt.Println("Yes")
			return
		}
	}
}

// ------ Mathライブラリ ---------------------------------//
func max(a ...int) int {
	r := a[0]
	for i := 0; i < len(a); i++ {
		if r < a[i] {
			r = a[i]
		}
	}
	return r
}

func maxIdx(a ...int) int {
	r := a[0]
	index := 0
	for i := 0; i < len(a); i++ {
		if r < a[i] {
			r = a[i]
			index = i
		}
	}
	return index
}

func min(a ...int) int {
	r := a[0]
	for i := 0; i < len(a); i++ {
		if r > a[i] {
			r = a[i]
		}
	}
	return r
}

func minIdx(a ...int) int {
	r := a[0]
	index := 0
	for i := 0; i < len(a); i++ {
		if r > a[i] {
			r = a[i]
			index = i
		}
	}
	return index
}

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

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

// ------ Mathライブラリ ---------------------------------//

// ----- 標準入力用の関数 ----------------------------------//
var nextReader func() []string

func NewScanner() func() []string {
	r := bufio.NewScanner(os.Stdin)
	r.Buffer(make([]byte, 1024), int(1e+11))
	return func() []string {
		r.Scan()
		return strings.Fields(r.Text())
	}
}

func nextString() []string {
	return nextReader()
}

func nextInt() []int {
	var intArray []int
	strArray := nextReader()
	for _, v := range strArray {
		i, _ := strconv.Atoi(v)
		intArray = append(intArray, i)
	}
	return intArray
}

func nextFloat64() []float64 {
	var floatArray []float64
	strArray := nextReader()
	for _, v := range strArray {
		f, _ := strconv.ParseFloat(v, 64)
		floatArray = append(floatArray, f)
	}
	return floatArray
}

// ------ 標準入力用の関数 ---------------------------------//

// ------ あまり使わない -----------------------------------//
func nextInt64() []int64 {
	var int64Array []int64
	strArray := nextReader()
	for _, v := range strArray {
		i, _ := strconv.ParseInt(v, 10, 64)
		int64Array = append(int64Array, i)
	}
	return int64Array
}

// ------ あまり使わない -----------------------------------//


package main

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

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

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

type TBytes []byte

func (obj TBytes) HasSuffix(keys []TBytes) int {
	for _, k := range keys {
		if bytes.HasSuffix(obj, k) {
			return len(k)
		}
	}
	return -1
}

func main() {
	s := TBytes(readLine())
	keys := []TBytes{TBytes("dreamer"), TBytes("eraser"), TBytes("dream"), TBytes("erase")}
	for klen := 0; klen >= 0; klen = s.HasSuffix(keys) {
		s = s[0 : len(s)-klen]
	}
	if len(s) == 0 {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}


package main

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

type TBytes []byte

func (obj TBytes) HasSuffix(keys []TBytes) int {
	for _, k := range keys {
		if bytes.HasSuffix(obj, k) {
			return len(k)
		}
	}
	return -1
}

var sc = bufio.NewScanner(os.Stdin)

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

func main() {
	s := TBytes(nextLine())
	keys := []TBytes{TBytes("dreamer"), TBytes("eraser"), TBytes("dream"), TBytes("erase")}
	for klen := 0; klen >= 0; klen = s.HasSuffix(keys) {
		s = s[0 : len(s)-klen]
	}
	if len(s) == 0 {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}


package main

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

var bufin *bufio.Reader
var bufout *bufio.Writer

func reverse(S string) string {
	runes := []rune(S)
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	return string(runes)
}
func solve(S string) int {
	c := S[0]
	ret := 0
	for i := 1; i < len(S); i++ {
		if c != S[i] {
			ret += 1
			c = S[i]
		}
	}
	return ret
}

func main() {
	bufin = bufio.NewReader(os.Stdin)
	bufout = bufio.NewWriter(os.Stdout)
	defer bufout.Flush()
	var S string
	fmt.Fscanf(bufin, "%s\n", &S)
	a := solve(S)
	T := reverse(S)
	b := solve(T)
	if a > b {
		a = b
	}
	fmt.Fprintf(bufout, "%d\n", a)
}

Score : 300 points

Problem Statement

Two foxes Jiro and Saburo are playing a game called 1D Reversi. This game is played on a board, using black and white stones. On the board, stones are placed in a row, and each player places a new stone to either end of the row. Similarly to the original game of Reversi, when a white stone is placed, all black stones between the new white stone and another white stone, turn into white stones, and vice versa.

In the middle of a game, something came up and Saburo has to leave the game. The state of the board at this point is described by a string S. There are |S| (the length of S) stones on the board, and each character in S represents the color of the i-th (1 ≦ i ≦ |S|) stone from the left. If the i-th character in S is B, it means that the color of the corresponding stone on the board is black. Similarly, if the i-th character in S is W, it means that the color of the corresponding stone is white.

Jiro wants all stones on the board to be of the same color. For this purpose, he will place new stones on the board according to the rules. Find the minimum number of new stones that he needs to place.

Constraints

1 ≦ |S| ≦ 10^5

Each character in S is B or W.

Input

The input is given from Standard Input in the following format:

S

Output

Print the minimum number of new stones that Jiro needs to place for his purpose.

Sample Input 1

BBBWW

Sample Output 1

1

By placing a new black stone to the right end of the row of stones, all white stones will become black. Also, by placing a new white stone to the left end of the row of stones, all black stones will become white.

In either way, Jiro's purpose can be achieved by placing one stone.

Sample Input 2

WWWWWW

Sample Output 2

0

If all stones are already of the same color, no new stone is necessary.

Sample Input 3

WBWBWBWBWB

Sample Output 3

9


package main

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

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

var fp *os.File

func input() *os.File {
	var err error
	fp, err = os.Open("input.txt")
	if err != nil {
		panic(err)
	}
	return fp
}

func rmConseq(S string, p string) string {
	var pp = p + p
	var tmp = ""

	for strings.Compare(S, tmp) != 0 {
		tmp = S
		S = strings.Replace(S, pp, p, -1)
	}
	return S
}

// main

func main() {

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

	var S = nextLine(sc)
	S = rmConseq(S, "B")
	S = rmConseq(S, "W")

	fmt.Println(len(S) - 1)

	defer fp.Close()

}


package main

import (
	"fmt"
	"sort"
)

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

	var ans string
	for _, key := range	 s{
		ans += key
	}
	fmt.Print(ans)
}

Score : 200 points

Problem Statement

Iroha has a sequence of N strings S_1, S_2, ..., S_N. The length of each string is L.

She will concatenate all of the strings in some order, to produce a long string.

Among all strings that she can produce in this way, find the lexicographically smallest one.

Here, a string s=s_1s_2s_3...s_n is lexicographically smaller than another string t=t_1t_2t_3...t_m if and only if one of the following holds:

There exists an index i(1≦i≦min(n,m)), such that s_j = t_j for all indices j(1≦j<i), and s_i<t_i.

s_i = t_i for all integers i(1≦i≦min(n,m)), and n<m.

Constraints

1 ≦ N, L ≦ 100

For each i, the length of S_i equals L.

For each i, S_i consists of lowercase letters.

Input

The input is given from Standard Input in the following format:

N L
S_1
S_2
:
S_N

Output

Print the lexicographically smallest string that Iroha can produce.

Sample Input 1

3 3
dxx
axx
cxx

Sample Output 1

axxcxxdxx

The following order should be used: axx, cxx, dxx.


package main

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

func main() {
	N, _ := ReadInt(), ReadInt()
	S := make([]string, N)
	for i := 0; i < N; i++ {
		S[i] = ReadString()
	}
	sort.Strings(S)
	for _, s := range S {
		fmt.Printf(s)
	}
	fmt.Println()
}

var reader = bufio.NewReader(os.Stdin)

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


package main

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

var (
	finv, inv, fac [MAX]int
)

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

func init() {
	fac[0] = 1
	fac[1] = 1
	finv[0] = 1
	finv[1] = 1
	inv[1] = 1
	for i := 2; i < MAX; i++ {
		fac[i] = fac[i-1] * i % MOD
		inv[i] = MOD - inv[MOD%i]*(MOD/i)%MOD
		finv[i] = finv[i-1] * inv[i] % MOD
	}
	//sc.Split(bufio.ScanLines)
	sc.Split(bufio.ScanWords)
	sc.Buffer([]byte{}, 500100)
}

const (
	MOD = 1000000007
	MAX = 510000
)

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

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

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

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

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

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

type Q struct {
	value int
	index int
	A, B  int
}

type QS []*Q

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

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

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

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

func LCM(a, b int64) int64 {
	return a * b / GCD(a, b)
}

type UnionFind struct {
	par  []int
	size []int
}

func NewUnionFind(size int) *UnionFind {
	return new(UnionFind).init(size)
}

func (uf *UnionFind) init(size int) *UnionFind {
	uf.par = make([]int, size)
	uf.size = make([]int, size)

	for i := 0; i < size; i++ {
		uf.par[i] = i
		uf.size[i] = 1
	}
	return uf
}

func (uf *UnionFind) Unite(p int, q int) {
	rp := uf.Root(p)
	rq := uf.Root(q)
	if rp == rq {
		return
	}
	if uf.size[rp] < uf.size[rq] {
		uf.par[rp] = uf.par[rq]
		uf.size[rq] += uf.size[rp]
	} else {
		uf.par[rq] = uf.par[rp]
		uf.size[rp] += uf.size[rq]
	}
}

func (uf *UnionFind) Root(p int) int {
	for uf.par[p] == p {
		return p
	}
	uf.par[p] = uf.Root(uf.par[p])
	return uf.par[p]
}

func (uf *UnionFind) Size(p int) int {
	return uf.size[uf.Root(p)]
}

func (uf *UnionFind) Same(p int, q int) bool {
	return uf.Root(p) == uf.Root(q)
}

var sc = bufio.NewScanner(os.Stdin)

func getInt() int {
	n, _ := strconv.Atoi(getStr())
	return n
}

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

func factor(result map[int]int, num, pnum int) map[int]int {
	if pnum*pnum > num {
		if num != 1 {
			result[num] += 1
		}
		return result
	}

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

func main() {
	N, _ := getInt(), getInt()
	S := make([]string, N)
	for i := 0; i < N; i++ {
		S[i] = getStr()
	}
	sort.Strings(S)
	for i := 0; i < N; i++ {
		fmt.Print(S[i])
	}
	fmt.Println()
}

type IntHeap []int

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

func (h *IntHeap) Push(x interface{}) {
	// Push and Pop use pointer receivers because they modify the slice's length,
	// not just its contents.
	*h = append(*h, x.(int))
}

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


package main

import (
	"fmt"
	"sort"
)

func main() {
	var n, l int
	fmt.Scan(&n, &l)
	s := make([]string, n)
	for i := range s {
		fmt.Scan(&s[i])
	}

	sort.Sort(sort.StringSlice(s))

	var ans string
	for _, si := range s {
		ans += si
	}

	fmt.Println(ans)
}


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

func main() {
  solve()
}

func solve() {
  input := bufio.NewScanner(os.Stdin)
  input.Scan()

  var re []string
  for input.Scan() {
    re = append(re, input.Text())
  }
  sort.Strings(re)

  var s string
  for _, v := range re {
    s += v
  }
  fmt.Println(s)
}


package main

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

func main() {

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

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

	sort.Strings(s)

	fmt.Print(strings.Join(s, ""))
	fmt.Println()

}


package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"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
}

func ceil(a, b int) int {
	if a%b == 0 {
		return a / b
	} else {
		return a/b + 1
	}
}

// Sort
type RuneSlice []rune

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

// Main
func main() {
	sc := NewScanner()
	wtr := bufio.NewWriter(os.Stdout)
	N, _ := sc.nextInt(), sc.nextInt()
	S := make([]string, N)
	for i := 0; i < N; i++ {
		S[i] = sc.nextStr()
	}
	sort.Strings(S)

	for i := 0; i < N; i++ {
		fmt.Fprint(wtr, S[i])
	}
	fmt.Fprintln(wtr)
	wtr.Flush()
}


package main

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

func main() {
	var n, l int
	var s string

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

	//process
	sort.Strings(strArr)
	s = strings.Join(strArr, "")
	fmt.Println(s)
}


package main

import (
	"fmt"
	"sort"
)

func main() {
	var n, l int
	fmt.Scan(&n, &l)
	strs := make([]string, n)
	for i := range strs {
		fmt.Scan(&strs[i])
	}
	sort.Strings(strs)
	for i := range strs {
		fmt.Print(strs[i])
	}
	fmt.Println()
}