The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$).

For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...".

NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG".

package main

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

/* solution */

func solve() {
	q := readInt()
	for i := 0; i < q; i++ {
		solveOne()
	}
}

func solveOne() {

	n, k := readInt(), readInt()

	arr1 := make([]int, n)
	arr2 := make([]int, n)
	arr3 := make([]int, n)

	s := read()

	for i := 0; i < n; i++ {
		var e1, e2, e3 byte
		switch i % 3 {
		case 0:
			e1, e2, e3 = 'R', 'G', 'B'
		case 1:
			e1, e2, e3 = 'G', 'B', 'R'
		case 2:
			e1, e2, e3 = 'B', 'R', 'G'
		}
		if e1 == s[i] {
			arr1[i] = 1
		}
		if e2 == s[i] {
			arr2[i] = 1
		}
		if e3 == s[i] {
			arr3[i] = 1
		}
	}

	min := check(arr1, k, n)
	cand := check(arr2, k, n)
	if cand < min {
		min = cand
	}
	cand = check(arr3, k, n)
	if cand < min {
		min = cand
	}

	printInt(min)

}

func check(arr []int, k int, n int) int {
	cur := 0
	for i := 0; i < k; i++ {
		cur += arr[i]
	}
	max := cur
	for i := 0; i < n-k; i++ {
		cur += arr[i+k] - arr[i]
		if cur > max {
			max = cur
		}
	}
	return k - max
}

/* stubs */

func main() {

	var f *os.File
	if runtime.GOROOT() == "C:\\Soft\\Go" {
		f, _ = os.Open("input.txt")
		defer f.Close()
	} else {
		f = os.Stdin
	}

	writer = bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	reader = bufio.NewScanner(f)

	const maxCapacity = 1024 * 1024
	buf := make([]byte, maxCapacity)
	reader.Buffer(buf, maxCapacity)

	reader.Split(bufio.ScanWords)

	solve()

}

var reader *bufio.Scanner
var writer *bufio.Writer

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

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

func print(s string) {
	writer.WriteString(s)
	writer.WriteString("\n")
}

func printInt(i int) {
	print(strconv.Itoa(i))
}

func readInt64() int64 {
	reader.Scan()
	ret, _ := strconv.ParseInt(reader.Text(), 10, 64)
	return ret
}

package main

import (
	"fmt"
)

const (
	MAXN = int(2000 + 7)
)

func Min(x int, y ...int) int {
	minVal := x
	for _, v := range y {
		if v < minVal {
			minVal = v
		}
	}
	return minVal
}

func solve(s string) int {
	toNum := func(x byte) (result int) {
		switch x {
		case 'R':
			result = 0
		case 'G':
			result = 1
		case 'B':
			result = 2
		}
		return
	}

	var dp [MAXN][3] int
	dp[0][0], dp[0][1], dp[0][2] = 1, 1, 1
	dp[0][toNum(s[0])] = 0
	//fmt.Println(dp[0])
	for i:=1;i<len(s);i++{
		for j:=0;j<3;j++{
			if j==toNum(s[i]){
				dp[i][j]=dp[i-1][(j+2)%3]
			}else {
				dp[i][j]=dp[i-1][(j+2)%3]+1
			}
		}
		//fmt.Println(dp[i])
	}
	return Min(dp[len(s)-1][0], dp[len(s)-1][1], dp[len(s)-1][2])
}

func main() {
	var N int
	_, _ = fmt.Scanf("%d\n", &N)
	for test := 1; test <= N; test++ {
		var n, k int
		_, _ = fmt.Scanf("%d %d\n", &n, &k)
		var s string
		_, _ = fmt.Scanf("%s\n", &s)
		ans := n
		for i := 0; i <= n-k; i++ {
			ans = Min(solve(s[i:i+k]), ans)
		}
		fmt.Println(ans)
	}
}

package main

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

func main() {

	//stdin, err := os.Open("test.txt")
	//if err != nil {
	//	panic(err)
	//}
	//defer stdin.Close()
	stdin := os.Stdin
	reader := bufio.NewReaderSize(stdin, 1024*1024)

	//stdout, err := os.Create("test.txt")
	//if err != nil {
	//	panic(err)
	//}
	//defer stdout.Close()
	stdout := os.Stdout
	writer := bufio.NewWriterSize(stdout, 1024*1024)

	var q int
	fmt.Fscanf(reader, "%d\n", &q)

	for i := 0; i < q; i++ {
		var n, k int
		r, g, b := make([]int, 0), make([]int, 0), make([]int, 0)
		fmt.Fscanf(reader, "%d %d\n", &n, &k)

		var s string
		fmt.Fscanf(reader, "%s\n", &s)

		for j := 0; j < n; j++ {

			if j%3 == 0 {
				if s[j] == 'R' {
					r = append(r, 0)
				} else {
					r = append(r, 1)
				}

				if s[j] == 'G' {
					g = append(g, 0)
				} else {
					g = append(g, 1)
				}

				if s[j] == 'B' {
					b = append(b, 0)
				} else {
					b = append(b, 1)
				}

			} else if j%3 == 1 {
				if s[j] == 'G' {
					r = append(r, 0)
				} else {
					r = append(r, 1)
				}

				if s[j] == 'B' {
					g = append(g, 0)
				} else {
					g = append(g, 1)
				}

				if s[j] == 'R' {
					b = append(b, 0)
				} else {
					b = append(b, 1)
				}

			} else if j%3 == 2 {
				if s[j] == 'B' {
					r = append(r, 0)
				} else {
					r = append(r, 1)
				}

				if s[j] == 'R' {
					g = append(g, 0)
				} else {
					g = append(g, 1)
				}

				if s[j] == 'G' {
					b = append(b, 0)
				} else {
					b = append(b, 1)
				}
			}
		}

		for j := 1; j < n; j++ {
			r[j] += r[j-1]
			g[j] += g[j-1]
			b[j] += b[j-1]
		}

		var min int = 2e3 + 1
		min = int(math.Min(float64(min), float64(r[k-1])))
		min = int(math.Min(float64(min), float64(g[k-1])))
		min = int(math.Min(float64(min), float64(b[k-1])))
		//fmt.Println(min)
		for j := k; j < n; j++ {
			min = int(math.Min(float64(min), float64(r[j])-float64(r[j-k])))
			min = int(math.Min(float64(min), float64(g[j])-float64(g[j-k])))
			min = int(math.Min(float64(min), float64(b[j])-float64(b[j-k])))
		}

		//fmt.Println(r)
		//fmt.Println(g)
		//fmt.Println(b)

		fmt.Println(min)

	}

	writer.Flush()
}

// Author: sighduck
// URL: https://codeforces.com/contest/1196/problem/D1, https://codeforces.com/contest/1196/problem/D2

package main

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

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

func Solve(n int, k int, s string) int {
	rotations := []string{"RGB", "GBR", "BRG"}
	dp := make([]int, n+1)
	solution := n + 1
	for _, rotation := range rotations {
		wrong := 0
		for i := 0; i < n; i++ {
			if rotation[i%3] != s[i] {
				wrong += 1
			}
			dp[i+1] = wrong
			if i+1 >= k {
				solution = min(solution, dp[i+1]-dp[i+1-k])
			}
		}
	}
	return solution
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var q int
	fmt.Fscanf(reader, "%d\n", &q)
	for i := 0; i < q; i++ {
		var n, k int
		fmt.Fscanf(reader, "%d %d\n", &n, &k)
		var s string
		fmt.Fscanf(reader, "%s\n", &s)
		fmt.Fprintf(writer, "%d\n", Solve(n, k, s))
	}
}

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
)

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)

	var q int
	rgb := "RGB"
	fmt.Fscanf(reader, "%d\n", &q)
	for i := 0;i < q;i ++ {
		var n, k int
		var s string
		fmt.Fscanf(reader, "%d %d\n", &n, &k)
		fmt.Fscanf(reader, "%s\n", &s)
		min := k + 1
		for j := 0;j < 3;j ++ {
			diff := 0
			for left, right := 0,0;right < n;right ++ {
				if s[right] != rgb[(right + j) % 3] {
					diff ++
				}
				if right - left + 1 == k {
					if diff < min {
						min = diff
					}
					if s[left] != rgb[(left + j) % 3] {
						diff --
					}
					left ++
				}
			}
		}
		fmt.Printf("%d\n", min)
	}
}

package main

import (
	"fmt"
)

const (
	MAXN = int(2000 + 7)
)

func Min(x int, y ...int) int {
	minVal := x
	for _, v := range y {
		if v < minVal {
			minVal = v
		}
	}
	return minVal
}

func solve(s string) int {
	toNum := func(x byte) (result int) {
		switch x {
		case 'R':
			result = 0
		case 'G':
			result = 1
		case 'B':
			result = 2
		}
		return
	}

	var dp [MAXN][3] int
	dp[0][1], dp[0][1], dp[0][2] = 1, 1, 1
	dp[0][toNum(s[0])] = 0

	for id, _ := range s {
		now := toNum(s[id])
		next := (now + 1) % 3
		//fmt.Println(id, next)
		for j := 0; j < 3; j++ {
			dp[id+1][j] = dp[id][(j+2)%3]+1
			if j==next{
				dp[id+1][j]=Min(dp[id+1][j],dp[id][now])
			}
		}
		//fmt.Println(dp[id+1])
	}
	return Min(dp[len(s)][0], dp[len(s)][1], dp[len(s)][2])
}

func main() {
	var N int
	_, _ = fmt.Scanf("%d\n", &N)
	for test := 1; test <= N; test++ {
		var n, k int
		_, _ = fmt.Scanf("%d %d\n", &n, &k)
		var s string
		_, _ = fmt.Scanf("%s\n", &s)
		ans := n
		for i := 0; i <= n-k; i++ {
			ans = Min(solve(s[i:i+k]), ans)
		}
		fmt.Println(ans)
	}
}

package main

import (
	"fmt"
)

const (
	MAXN = int(2000 + 7)
)

func Min(x int, y ...int) int {
	minVal := x
	for _, v := range y {
		if v < minVal {
			minVal = v
		}
	}
	return minVal
}

func solve(s string) int {
	toNum := func(x byte) (result int) {
		switch x {
		case 'R':
			result = 0
		case 'G':
			result = 1
		case 'B':
			result = 2
		}
		return
	}

	var dp [MAXN][3] int
	dp[0][0], dp[0][1], dp[0][2] = 1, 1, 1
	dp[0][toNum(s[0])] = 0

	for id, _ := range s {
		now := toNum(s[id])
		next := (now + 1) % 3
		//fmt.Println(id, next)
		for j := 0; j < 3; j++ {
			dp[id+1][j] = dp[id][(j+2)%3] + 1
			if j == next {
				dp[id+1][j] = Min(dp[id+1][j], dp[id][now])
			}
		}
		//fmt.Println(dp[id+1])
	}
	return Min(dp[len(s)][0], dp[len(s)][1], dp[len(s)][2])
}

func main() {
	var N int
	_, _ = fmt.Scanf("%d\n", &N)
	for test := 1; test <= N; test++ {
		var n, k int
		_, _ = fmt.Scanf("%d %d\n", &n, &k)
		var s string
		_, _ = fmt.Scanf("%s\n", &s)
		ans := n
		for i := 0; i <= n-k; i++ {
			ans = Min(solve(s[i:i+k]), ans)
		}
		fmt.Println(ans)
	}
}


You are given two strings $$$x$$$ and $$$y$$$, both consist only of lowercase Latin letters. Let $$$|s|$$$ be the length of string $$$s$$$.Let's call a sequence $$$a$$$ a merging sequence if it consists of exactly $$$|x|$$$ zeros and exactly $$$|y|$$$ ones in some order.A merge $$$z$$$ is produced from a sequence $$$a$$$ by the following rules:   if $$$a_i=0$$$, then remove a letter from the beginning of $$$x$$$ and append it to the end of $$$z$$$;  if $$$a_i=1$$$, then remove a letter from the beginning of $$$y$$$ and append it to the end of $$$z$$$. Two merging sequences $$$a$$$ and $$$b$$$ are different if there is some position $$$i$$$ such that $$$a_i \neq b_i$$$.Let's call a string $$$z$$$ chaotic if for all $$$i$$$ from $$$2$$$ to $$$|z|$$$ $$$z_{i-1} \neq z_i$$$.Let $$$s[l,r]$$$ for some $$$1 \le l \le r \le |s|$$$ be a substring of consecutive letters of $$$s$$$, starting from position $$$l$$$ and ending at position $$$r$$$ inclusive.Let $$$f(l_1, r_1, l_2, r_2)$$$ be the number of different merging sequences of $$$x[l_1,r_1]$$$ and $$$y[l_2,r_2]$$$ that produce chaotic merges. Note that only non-empty substrings of $$$x$$$ and $$$y$$$ are considered.Calculate $$$\sum \limits_{1 \le l_1 \le r_1 \le |x| \\ 1 \le l_2 \le r_2 \le |y|} f(l_1, r_1, l_2, r_2)$$$. Output the answer modulo $$$998\,244\,353$$$.

The first line contains a string $$$x$$$ ($$$1 \le |x| \le 1000$$$). The second line contains a string $$$y$$$ ($$$1 \le |y| \le 1000$$$). Both strings consist only of lowercase Latin letters.

NoteIn the first example there are:   $$$6$$$ pairs of substrings "a" and "b", each with valid merging sequences "01" and "10";  $$$3$$$ pairs of substrings "a" and "bb", each with a valid merging sequence "101";  $$$4$$$ pairs of substrings "aa" and "b", each with a valid merging sequence "010";  $$$2$$$ pairs of substrings "aa" and "bb", each with valid merging sequences "0101" and "1010";  $$$2$$$ pairs of substrings "aaa" and "b", each with no valid merging sequences;  $$$1$$$ pair of substrings "aaa" and "bb" with a valid merging sequence "01010"; Thus, the answer is $$$6 \cdot 2 + 3 \cdot 1 + 4 \cdot 1 + 2 \cdot 2 + 2 \cdot 0 + 1 \cdot 1 = 24$$$.

package main

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

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

	var buf bytes.Buffer

	x, _ := reader.ReadString('\n')
	y, _ := reader.ReadString('\n')

	res := solve(normalize(x), normalize(y))
	buf.WriteString(fmt.Sprintf("%d\n", res))
	fmt.Print(buf.String())
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func normalize(s string) string {
	for i := 0; i < len(s); i++ {
		if s[i] < 'a' || s[i] > 'z' {
			return s[:i]
		}
	}
	return s
}

const MOD = 998244353

func solve(x, y string) int {
	m := len(x)
	n := len(y)
	dp := make([][][][]int64, m+1)
	for i := 0; i <= m; i++ {
		dp[i] = make([][][]int64, n+1)
		for j := 0; j <= n; j++ {
			dp[i][j] = make([][]int64, 2)
			for k := 0; k < 2; k++ {
				dp[i][j][k] = make([]int64, 4)
			}
		}
	}
	var res int64
	for i := 0; i <= m; i++ {
		for j := 0; j <= n; j++ {
			if i < m {
				modAdd(&dp[i+1][j][0][1], 1)
			}
			if j < n {
				modAdd(&dp[i][j+1][1][2], 1)
			}
			for mask := 0; mask < 4; mask++ {
				if 0 < i && i < m && x[i-1] != x[i] {
					modAdd(&dp[i+1][j][0][mask|1], dp[i][j][0][mask])
				}
				if i < m && 0 < j && y[j-1] != x[i] {
					modAdd(&dp[i+1][j][0][mask|1], dp[i][j][1][mask])
				}

				if 0 < j && j < n && y[j-1] != y[j] {
					modAdd(&dp[i][j+1][1][mask|2], dp[i][j][1][mask])
				}

				if 0 < i && j < n && x[i-1] != y[j] {
					modAdd(&dp[i][j+1][1][mask|2], dp[i][j][0][mask])
				}
			}
			modAdd(&res, dp[i][j][0][3])
			modAdd(&res, dp[i][j][1][3])
		}
	}

	return int(res)
}

func modAdd(a *int64, b int64) {
	*a += b
	if *a >= MOD {
		*a -= MOD
	}
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1499E(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	const mod = 998244353
	f := func(s []byte) []uint {
		n := len(s)
		df := make([]uint, n)
		df[0] = 1
		for i := 1; i < n; i++ {
			if s[i] != s[i-1] {
				df[i] = df[i-1] + 1
			} else {
				df[i] = 1
			}
		}
		return df
	}

	var s, t []byte
	Fscan(in, &s, &t)
	diffS, diffT := f(s), f(t)
	dp := make([][][2]uint, len(s))
	for i := range dp {
		dp[i] = make([][2]uint, len(t))
	}
	ans := uint(0)
	for i, v := range s {
		for j, w := range t {
			if v != w {
				dp[i][j][0] = diffT[j]
				dp[i][j][1] = diffS[i]
			}
			if i > 0 {
				if v != w {
					dp[i][j][0] = (dp[i][j][0] + dp[i-1][j][1]) % mod
				}
				if v != s[i-1] {
					dp[i][j][0] = (dp[i][j][0] + dp[i-1][j][0]) % mod
				}
			}
			if j > 0 {
				if w != v {
					dp[i][j][1] = (dp[i][j][1] + dp[i][j-1][0]) % mod
				}
				if w != t[j-1] {
					dp[i][j][1] = (dp[i][j][1] + dp[i][j-1][1]) % mod
				}
			}
			ans = (ans + dp[i][j][0] + dp[i][j][1]) % mod
		}
	}
	Fprint(out, ans)
}
func main() { CF1499E(os.Stdin, os.Stdout) }

package main

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

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

	var buf bytes.Buffer

	var x, y string
	fmt.Scanf("%s", &x)
	fmt.Scanf("%s", &y)
	res := solve(x, y)
	buf.WriteString(fmt.Sprintf("%d\n", res))
	fmt.Print(buf.String())
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

const MOD = 998244353

func solve(x, y string) int {
	m := len(x)
	n := len(y)
	dp := make([][][][]int64, m+1)
	for i := 0; i <= m; i++ {
		dp[i] = make([][][]int64, n+1)
		for j := 0; j <= n; j++ {
			dp[i][j] = make([][]int64, 2)
			for k := 0; k < 2; k++ {
				dp[i][j][k] = make([]int64, 4)
			}
		}
	}
	var res int64
	for i := 0; i <= m; i++ {
		for j := 0; j <= n; j++ {
			if i < m {
				modAdd(&dp[i+1][j][0][1], 1)
			}
			if j < n {
				modAdd(&dp[i][j+1][1][2], 1)
			}
			for mask := 0; mask < 4; mask++ {
				if 0 < i && i < m && x[i-1] != x[i] {
					modAdd(&dp[i+1][j][0][mask|1], dp[i][j][0][mask])
				}
				if i < m && 0 < j && y[j-1] != x[i] {
					modAdd(&dp[i+1][j][0][mask|1], dp[i][j][1][mask])
				}

				if 0 < j && j < n && y[j-1] != y[j] {
					modAdd(&dp[i][j+1][1][mask|2], dp[i][j][1][mask])
				}

				if 0 < i && j < n && x[i-1] != y[j] {
					modAdd(&dp[i][j+1][1][mask|2], dp[i][j][0][mask])
				}
			}
			modAdd(&res, dp[i][j][0][3])
			modAdd(&res, dp[i][j][1][3])
		}
	}

	return int(res)
}

func modAdd(a *int64, b int64) {
	*a += b
	if *a >= MOD {
		*a -= MOD
	}
}

package main

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

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

	var buf bytes.Buffer

	x, _ := reader.ReadString('\n')
	y, _ := reader.ReadString('\n')
	x = x[:len(x)-1]
	y = y[:len(y)-1]
	res := solve(x, y)
	buf.WriteString(fmt.Sprintf("%d\n", res))
	fmt.Print(buf.String())
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

const MOD = 998244353

func solve(x, y string) int {
	m := len(x)
	n := len(y)
	dp := make([][][][]int64, m+1)
	for i := 0; i <= m; i++ {
		dp[i] = make([][][]int64, n+1)
		for j := 0; j <= n; j++ {
			dp[i][j] = make([][]int64, 2)
			for k := 0; k < 2; k++ {
				dp[i][j][k] = make([]int64, 4)
			}
		}
	}
	var res int64
	for i := 0; i <= m; i++ {
		for j := 0; j <= n; j++ {
			if i < m {
				modAdd(&dp[i+1][j][0][1], 1)
			}
			if j < n {
				modAdd(&dp[i][j+1][1][2], 1)
			}
			for mask := 0; mask < 4; mask++ {
				if 0 < i && i < m && x[i-1] != x[i] {
					modAdd(&dp[i+1][j][0][mask|1], dp[i][j][0][mask])
				}
				if i < m && 0 < j && y[j-1] != x[i] {
					modAdd(&dp[i+1][j][0][mask|1], dp[i][j][1][mask])
				}

				if 0 < j && j < n && y[j-1] != y[j] {
					modAdd(&dp[i][j+1][1][mask|2], dp[i][j][1][mask])
				}

				if 0 < i && j < n && x[i-1] != y[j] {
					modAdd(&dp[i][j+1][1][mask|2], dp[i][j][0][mask])
				}
			}
			modAdd(&res, dp[i][j][0][3])
			modAdd(&res, dp[i][j][1][3])
		}
	}

	return int(res)
}

func modAdd(a *int64, b int64) {
	*a += b
	if *a >= MOD {
		*a -= MOD
	}
}


Andrewid the Android is a galaxy-famous detective. He is now investigating the case of vandalism at the exhibition of contemporary art.The main exhibit is a construction of n matryoshka dolls that can be nested one into another. The matryoshka dolls are numbered from 1 to n. A matryoshka with a smaller number can be nested in a matryoshka with a higher number, two matryoshkas can not be directly nested in the same doll, but there may be chain nestings, for example, 1 → 2 → 4 → 5. In one second, you can perform one of the two following operations:  Having a matryoshka a that isn't nested in any other matryoshka and a matryoshka b, such that b doesn't contain any other matryoshka and is not nested in any other matryoshka, you may put a in b;  Having a matryoshka a directly contained in matryoshka b, such that b is not nested in any other matryoshka, you may get a out of b. According to the modern aesthetic norms the matryoshka dolls on display were assembled in a specific configuration, i.e. as several separate chains of nested matryoshkas, but the criminal, following the mysterious plan, took out all the dolls and assembled them into a single large chain (1 → 2 → ... → n). In order to continue the investigation Andrewid needs to know in what minimum time it is possible to perform this action.

The first line contains integers n (1 ≤ n ≤ 105) and k (1 ≤ k ≤ 105) — the number of matryoshkas and matryoshka chains in the initial configuration. The next k lines contain the descriptions of the chains: the i-th line first contains number mi (1 ≤ mi ≤ n), and then mi numbers ai1, ai2, ..., aimi — the numbers of matryoshkas in the chain (matryoshka ai1 is nested into matryoshka ai2, that is nested into matryoshka ai3, and so on till the matryoshka aimi that isn't nested into any other matryoshka). It is guaranteed that m1 + m2 + ... + mk = n, the numbers of matryoshkas in all the chains are distinct, in each chain the numbers of matryoshkas follow in the ascending order.

In the single line print the minimum number of seconds needed to assemble one large chain from the initial configuration.

NoteIn the first sample test there are two chains: 1 → 2 and 3. In one second you can nest the first chain into the second one and get 1 → 2 → 3.In the second sample test you need to disassemble all the three chains into individual matryoshkas in 2 + 1 + 1 = 4 seconds and then assemble one big chain in 6 seconds.

package main

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

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

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

	l := 0
	for i := 0; i < k; i++ {
		bs.Scan()
		m, _ := strconv.Atoi(bs.Text())

		first := 1
		for ; m > 0; m-- {
			bs.Scan()
			a, _ := strconv.Atoi(bs.Text())

			if a == first {
				first++
				l++
			}
		}
	}

	fmt.Println(2*n - k + 1 - 2*l)
}

package main

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

func main() {
        r := bufio.NewReader(os.Stdin)
        ch := 0
        var n, k int
        fmt.Fscanf(r, "%d %d\n", &n, &k)
        for z := 0; z < k; z++ {
                m, x, t := 1, 1, 1
                fmt.Fscanf(r, "%d", &m)
                for ; m > 0; m-- {
                        fmt.Fscanf(r, "%d", &x)
                        if x == t {
                                ch++
                                t++
                        }
                }
                fmt.Fscanf(r, "\n")
        }
        fmt.Printf("%d\n", n-ch+1-k+n-ch)
}

package main

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

var (
	reader  = bufio.NewReader(os.Stdin)
	writer  = bufio.NewWriter(os.Stdout)
	scanner = bufio.NewScanner(os.Stdin)
)

//Wrong
func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	_, k := nextInt(), nextInt()
	m, ops := 0, 0
	a := make([]int, 100000)

	for ; k > 0; k-- {
		m = nextInt()

		for i := 0; i < m; i++ {
			a[i] = nextInt()
		}

		if a[0] == 1 {
			i := 1

			for i < m && a[i] == a[i-1]+1 {
				i++
			}

			m -= i
			ops += 2
		}

		ops += m*2 - 1
	}

	println(ops - 1)
}

func scan(a ...interface{}) {
	fmt.Fscan(reader, a...)
}

func next() string {
	if !scanner.Scan() {
		panic(scanner.Err())
	}
	return scanner.Text()
}

func nextInt64() int64 {
	n, _ := strconv.ParseInt(next(), 0, 64)
	return n
}

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

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

func println(a ...interface{})               { fmt.Fprintln(writer, a...) }
func print(a ...interface{})                 { fmt.Fprint(writer, a...) }
func printf(format string, a ...interface{}) { fmt.Fprintf(writer, format, a...) }

package main

import "fmt"

func main() {
        ch := 0
        var n, k int
        fmt.Scanf("%d%d", &n, &k)
        for z := 0; z < k; z++ {
                m, x, t := 1, 1, 1
                fmt.Scanf("%d", &m)
                for ; m > 0; m-- {
                        fmt.Scanf("%d", &x)
                        if x == t {
                                ch++
                                t++
                        }
                }
        }
        fmt.Printf("%d\n", n-ch+1-k+n-ch)
}

package main

import "fmt"

func main() {
        ch := 0
        var n, k int
        fmt.Scanf("%d%d", &n, &k)
        for z := 0; z < k; z++ {
                m, x, t := 1, 1, 1
                fmt.Scanf("%d", &m)
                for ; m > 0; m-- {
                        fmt.Scanf("%d", &x)
                        if x == t {
                                ch++
                                t++
                        }
                }
        }
        fmt.Printf("%d", n-ch+1-k+n-ch)
}

package main

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

var r = bufio.NewReader(os.Stdin)

func main() {
        ch := 0
        var n, k int
        fmt.Fscanf(r, "%d%d", &n, &k)
        for z := 0; z < k; z++ {
                m, x, t := 1, 1, 1
                fmt.Fscanf(r, "%d", &m)
                for ; m > 0; m-- {
                        fmt.Fscanf(r, "%d", &x)
                        if x == t {
                                ch++
                                t++
                        }
                }
        }
        fmt.Printf("%d\n", n-ch+1-k+n-ch)
}

package main

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

var (
	reader  = bufio.NewReader(os.Stdin)
	writer  = bufio.NewWriter(os.Stdout)
	scanner = bufio.NewScanner(os.Stdin)
)

//Wrong
func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	_, k := nextInt(), nextInt()
	m, ops := 0, 0
	a := make([]int, 100000)
	ops += k

	for ; k > 0; k-- {
		m = nextInt()

		for i := 0; i < m; i++ {
			a[i] = nextInt()
		}

		for i := 1; i < m; i++ {
			if a[i] != a[i-1]+1 {
				ops += 2
			}
		}
	}

	println(ops - 1)
}

func scan(a ...interface{}) {
	fmt.Fscan(reader, a...)
}

func next() string {
	if !scanner.Scan() {
		panic(scanner.Err())
	}
	return scanner.Text()
}

func nextInt64() int64 {
	n, _ := strconv.ParseInt(next(), 0, 64)
	return n
}

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

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

func println(a ...interface{})               { fmt.Fprintln(writer, a...) }
func print(a ...interface{})                 { fmt.Fprint(writer, a...) }
func printf(format string, a ...interface{}) { fmt.Fprintf(writer, format, a...) }


Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.

The first line of the input data contains an integer number n (3 ≤ n ≤ 106), n — the amount of hills around the capital. The second line contains n numbers — heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109.

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"sort"
)

type Node struct {
	value int
	count int64
}

func reverse(a []int) {
	for i := 0; ; i++ {
		j := len(a) - i - 1
		if i >= j {
			return
		}
		a[i], a[j] = a[j], a[i]
	}
}

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)
	var n int

	fmt.Fscanf(reader, "%d\n", &n)
	number := make([]int, 0, 1000000)
	sorted := make([]int, 0, 1000000)
	stack := make([]*Node, 1000000, 1000000)
	var pointer int
	for i := 0; i < n; i++ {
		var hill int
		fmt.Fscanf(reader, "%d ", &hill)
		number = append(number, hill)
		sorted = append(sorted, hill)
	}

	sort.Ints(sorted)
	max := sorted[n-1]
	prev, pos := max, n

	result := int64(0)
	maxPos := 0
	for i := n - 1; i >= 0; i-- {
		if sorted[i] != prev {
			pos = i + 1
			prev = sorted[i]
		}
		inc := n - pos
		if inc >= 2 {
			result += 2
		} else {
			result += int64(inc)
		}
		if number[i] == max {
			maxPos = i
		}
	}
	reverse(number[:maxPos+1])
	reverse(number[maxPos+1:])
	reverse(number)

	for i := 0; i < len(number); i++ {
		for pointer != 0 {
			if stack[pointer-1].value == number[i] {
				stack[pointer-1].count++
				break
			} else if stack[pointer-1].value > number[i] {
				stack[pointer] = &Node{number[i], 1}
				pointer++
				break
			} else {
				count := stack[pointer-1].count
				result = result + (count * (count - 1) / 2)
				pointer--
			}
		}
		if pointer == 0 {
			stack[pointer] = &Node{number[i], 1}
			pointer++
		}
	}

	for pointer != 0 {
		count := stack[pointer-1].count
		result = result + (count * (count - 1) / 2)
		pointer--
	}

	fmt.Printf("%d", result)

}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	n := readNum(reader)
	H := readNNums(reader, n)
	fmt.Println(solve(n, H))
}

func solve(n int, H []int) int64 {
	hills := make([]int, n+1)

	var pivot int
	for i := 1; i < n; i++ {
		if H[i] > H[pivot] {
			pivot = i
		}
	}

	copy(hills, H[pivot:])
	copy(hills[n-pivot:], H[0:])
	hills[n] = H[pivot]
	//n++

	C := make([]int, n+1)
	R := make([]int, n+1)

	for i := n - 1; i >= 0; i-- {
		R[i] = i + 1
		for R[i] < n && hills[i] > hills[R[i]] {
			R[i] = R[R[i]]
		}
		if R[i] < n && hills[i] == hills[R[i]] {
			C[i] = C[R[i]] + 1
			R[i] = R[R[i]]
		}
	}

	L := make([]int, n+1)
	for i := 1; i <= n; i++ {
		L[i] = i - 1
		for L[i] > 0 && hills[i] >= hills[L[i]] {
			L[i] = L[L[i]]
		}
	}

	var res int64

	for i := 0; i < n; i++ {
		res += int64(C[i])
		if hills[i] < hills[0] {
			if L[i] == 0 && R[i] == n {
				res++
			} else {
				res += 2
			}
		}
	}

	return res
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"sort"
)

type Node struct {
	value int
	count int64
}

func reverse(a []int) {
	for i := 0; ; i++ {
		j := len(a) - i - 1
		if i >= j {
			return
		}
		a[i], a[j] = a[j], a[i]
	}
}

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)
	var n int

	fmt.Fscanf(reader, "%d\n", &n)
	number := make([]int, 0, 1000000)
	sorted := make([]int, 0, 1000000)
	stack := make([]*Node, 1000000, 1000000)
	var pointer int
	for i := 0; i < n; i++ {
		var hill int
		fmt.Fscanf(reader, "%d ", &hill)
		number = append(number, hill)
		sorted = append(sorted, hill)
	}

	sort.Ints(sorted)
	max := sorted[n-1]
	prev, pos := max, n

	result := int64(0)
	maxPos := 0
	for i := n - 1; i >= 0; i-- {
		if sorted[i] != prev {
			pos = i + 1
			max = sorted[i]
		}
		inc := n - pos
		if inc >= 2 {
			result += 2
		} else {
			result += int64(inc)
		}
		if number[i] == max {
			maxPos = i
		}
	}
	reverse(number[:maxPos])
	reverse(number[maxPos:])
	reverse(number)

	for i := 0; i < len(number); i++ {
		for pointer != 0 {
			if stack[pointer-1].value == number[i] {
				stack[pointer-1].count++
				break
			} else if stack[pointer-1].value > number[i] {
				stack[pointer] = &Node{number[i], 1}
				pointer++
				break
			} else {
				count := stack[pointer-1].count
				result = result + (count * (count - 1) / 2)
				pointer--
			}
		}
		if pointer == 0 {
			stack[pointer] = &Node{number[i], 1}
			pointer++
		}
	}

	for pointer != 0 {
		count := stack[pointer-1].count
		result = result + (count * (count - 1) / 2)
		pointer--
	}

	fmt.Printf("%d", result)

}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	n := readNum(reader)
	H := readNNums(reader, n)
	fmt.Println(solve(n, H))
}

func solve(n int, H []int) int64 {
	HH := make([]int, 2*n)
	copy(HH, H)
	copy(HH[n:], H)

	stack := make([]int, 2*n)
	var head, tail int
	var res int64
	for i := 0; i < n; i++ {
		for tail > head && H[stack[tail-1]] < H[i] {
			res++
			if tail > head+1 && H[stack[tail-1]] == H[stack[tail-2]] {
				res++
			}
			tail--
		}
		//res += int64(tail - head)
		stack[tail] = i
		tail++
	}

	for i := n; i < 2*n; i++ {
		for head < tail && stack[head] <= i-n {
			head++
		}
		for tail > head && HH[stack[tail-1]] < HH[i] {
			res++
			if tail > head+1 && HH[stack[tail-1]] == HH[stack[tail-2]] {
				res++
			}
			tail--
		}
		//res += int64(tail - head)
		stack[tail] = i
		tail++
	}
	// the only issue here is the same height hills

	if tail-2 > head && HH[stack[tail-1]] == HH[stack[head]] {
		res++
	}

	for tail-1 > head {
		if HH[stack[tail-1]] == HH[stack[tail-2]] {
			res++
		}
		tail--
	}

	return res
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	n := readNum(reader)
	H := readNNums(reader, n)
	fmt.Println(solve(n, H))
}

func solve(n int, H []int) int64 {
	HH := make([]int, 2*n)
	copy(HH, H)
	copy(HH[n:], H)

	stack := make([]int, 2*n)
	var head, tail int
	var res int64
	for i := 0; i < n; i++ {
		for tail > head && H[stack[tail-1]] < H[i] {
			res++
			if tail > head+1 && H[stack[tail-1]] == H[stack[tail-2]] {
				res++
			}
			tail--
		}
		//res += int64(tail - head)
		stack[tail] = i
		tail++
	}

	for i := n; i < 2*n; i++ {
		for head < tail && stack[head] <= i-n {
			head++
		}
		for tail > head && HH[stack[tail-1]] < HH[i] {
			res++
			if tail > head+1 && HH[stack[tail-1]] == HH[stack[tail-2]] {
				res++
			}
			tail--
		}
		//res += int64(tail - head)
		stack[tail] = i
		tail++
	}
	// the only issue here is the same height hills

	if tail-1 > head && HH[stack[tail-1]] == HH[stack[head]] {
		res++
	}

	for tail-1 > head {
		if HH[stack[tail-1]] == HH[stack[tail-2]] {
			res++
		}
		tail--
	}

	return res
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	n := readNum(reader)
	H := readNNums(reader, n)
	fmt.Println(solve(n, H))
}

func solve(n int, H []int) int64 {
	HH := make([]int, 2*n)
	copy(HH, H)
	copy(HH[n:], H)

	stack := make([]int, 2*n)
	var head, tail int
	var res int64
	for i := 0; i < n; i++ {
		for tail > head && H[stack[tail-1]] < H[i] {
			res++
			if tail > head+1 && H[stack[tail-1]] == H[stack[tail-2]] {
				res++
			}
			tail--
		}
		//res += int64(tail - head)
		stack[tail] = i
		tail++
	}

	for i := n; i < 2*n; i++ {
		for head < tail && stack[head] <= i-n {
			head++
		}
		for tail > head && HH[stack[tail-1]] < HH[i] {
			res++
			if tail > head+1 && HH[stack[tail-1]] == HH[stack[tail-2]] {
				res++
			}
			tail--
		}
		//res += int64(tail - head)
		stack[tail] = i
		tail++
	}
	// the only issue here is the same height hills

	for tail-1 > head {
		if HH[stack[tail-1]] == HH[stack[tail-2]] {
			res++
		}
		tail--
	}

	return res
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}