You are given a rooted tree of $$$2^n - 1$$$ vertices. Every vertex of this tree has either $$$0$$$ children, or $$$2$$$ children. All leaves of this tree have the same distance from the root, and for every non-leaf vertex, one of its children is the left one, and the other child is the right one. Formally, you are given a perfect binary tree.The vertices of the tree are numbered in the following order:  the root has index $$$1$$$;  if a vertex has index $$$x$$$, then its left child has index $$$2x$$$, and its right child has index $$$2x+1$$$. Every vertex of the tree has a letter written on it, either A or B. Let's define the character on the vertex $$$x$$$ as $$$s_x$$$.Let the preorder string of some vertex $$$x$$$ be defined in the following way:  if the vertex $$$x$$$ is a leaf, then the preorder string of $$$x$$$ be consisting of only one character $$$s_x$$$;  otherwise, the preorder string of $$$x$$$ is $$$s_x + f(l_x) + f(r_x)$$$, where $$$+$$$ operator defines concatenation of strings, $$$f(l_x)$$$ is the preorder string of the left child of $$$x$$$, and $$$f(r_x)$$$ is the preorder string of the right child of $$$x$$$. The preorder string of the tree is the preorder string of its root.Now, for the problem itself...You have to calculate the number of different strings that can be obtained as the preorder string of the given tree, if you are allowed to perform the following operation any number of times before constructing the preorder string of the tree:  choose any non-leaf vertex $$$x$$$, and swap its children (so, the left child becomes the right one, and vice versa).

The first line contains one integer $$$n$$$ ($$$2 \le n \le 18$$$). The second line contains a sequence of $$$2^n-1$$$ characters $$$s_1, s_2, \dots, s_{2^n-1}$$$. Each character is either A or B. The characters are not separated by spaces or anything else.

Print one integer — the number of different strings that can be obtained as the preorder string of the given tree, if you can apply any number of operations described in the statement. Since it can be very large, print it modulo $$$998244353$$$.

package main

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

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

func main() {
	defer out.Flush()
	const mod = 998244353
	var n int
	fmt.Fscan(in, &n)
	var str string
	fmt.Fscan(in, &str)
	str = " " + str

	arr := make([]string, 2<<19)
	res := 1
	var dfs func(rt, length int)
	dfs = func(rt, length int) {
		if length == 1 {
			arr[rt] = string(str[rt])
			return
		}

		dfs(rt<<1, length>>1)
		dfs(rt<<1|1, length>>1)
		a := arr[rt<<1]
		b := arr[rt<<1|1]
		if a != b {
			res = (res + res) % mod
		}
		if a > b {
			arr[rt<<1], arr[rt<<1|1] = arr[rt<<1|1], arr[rt<<1]
		}
		arr[rt] = string(str[rt]) + arr[rt<<1] + arr[rt<<1|1]
	}
	dfs(1, 1<<n-1)
	fmt.Fprintln(out, res%mod)
}

package main

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

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

const mod = 998244353

type node struct {
	cnt int64
	s   string
}

func main() {
	defer out.Flush()

	var n int
	var s string
	fmt.Fscan(in, &n, &s)

	nodes := make([]node, 1<<n+1)
	for i := 1 << (n - 1); i < 1<<n; i++ {
		nodes[i].cnt = 1
		nodes[i].s = s[i-1 : i]
	}
	for i := 1<<(n-1) - 1; i >= 1; i-- {
		lt, rt := nodes[i*2], nodes[i*2+1]
		if lt.s == rt.s {
			nodes[i].cnt = (lt.cnt * rt.cnt) % mod
			nodes[i].s = s[i-1:i] + lt.s + rt.s
		} else {
			nodes[i].cnt = (2 * lt.cnt * rt.cnt) % mod
			if lt.s < rt.s {
				nodes[i].s = s[i-1:i] + lt.s + rt.s
			} else {
				nodes[i].s = s[i-1:i] + rt.s + lt.s
			}
		}
	}
	fmt.Fprintln(out, nodes[1].cnt)
}

package main

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

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

const mod = 998244353

type node struct {
	cnt int64
	s   string
}

func main() {
	defer out.Flush()

	var n int
	var s string
	fmt.Fscan(in, &n, &s)

	nodes := make([]node, 1<<n+1)
	for i := 1 << (n - 1); i < 1<<n; i++ {
		nodes[i].cnt = 1
		nodes[i].s = s[i-1 : i]
	}
	for i := 1<<(n-1) - 1; i >= 1; i-- {
		lt, rt := nodes[i*2], nodes[i*2+1]
		if lt.s == rt.s {
			nodes[i].cnt = (lt.cnt * rt.cnt) % mod
			nodes[i].s = lt.s + rt.s
		} else {
			nodes[i].cnt = (2 * lt.cnt * rt.cnt) % mod
			if lt.s < rt.s {
				nodes[i].s = lt.s + rt.s
			} else {
				nodes[i].s = rt.s + lt.s
			}
		}
	}
	fmt.Fprintln(out, nodes[1].cnt)
}


INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.2. The i-th element of the array is subtracted from the result of the previous step modulo 256.3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.You are given the text printed using this method. Restore the array used to produce this text.

The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.

Output the initial array, which was used to produce text, one integer per line.

NoteLet's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b.

// 132A
package main

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

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

func Btoi(n int) int {
	var ans string
	for n/2 != 1 {
		ans += string(n%2 + 48)
		n /= 2
	}
	ans += string(n%2 + 48)
	ans += string('1')
	for len(ans) != 8 {
		ans += string('0')
	}
	res := 0.0
	for i := 0; i < 8; i++ {
		if ans[8-i-1]-48 != 0 {
			res += math.Pow(2.0, float64(i))
		}
	}
	return int(res)
}

func main() {
	var s string
	in.Split(bufio.ScanLines)
	in.Scan()
	s = in.Text()
	last := 0
	for i := 0; i < len(s); i++ {
		a := Btoi(int(s[i]))
		res := last - a
		if res < 0 {
			res *= -1
			fmt.Fprintln(out, 256-(res%256))
		} else {
			fmt.Fprintln(out, res%256)
		}
		last = a
	}
	out.Flush()
}

// 132A
package main

import (
	"fmt"
	"math"
)

func Btoi(n int) int {
	var ans string
	for n/2 != 1 {
		ans += string(n%2 + 48)
		n /= 2
	}
	ans += string(n%2 + 48)
	ans += string('1')
	for len(ans) != 8 {
		ans += string('0')
	}
	res := 0.0
	for i := 0; i < 8; i++ {
		if ans[8-i-1]-48 != 0 {
			res += math.Pow(2.0, float64(i))
		}
	}
	return int(res)
}

func main() {
	var s string
	fmt.Scanln(&s)
	length := len(s)
	last := 0
	for i := 0; i < length; i++ {
		a := Btoi(int(s[i]))
		res := last - a
		if res < 0 {
			res *= -1
			fmt.Println(256 - (res % 256))
		} else {
			fmt.Println(res % 256)
		}
		last = a
	}
}


A dragon symbolizes wisdom, power and wealth. On Lunar New Year's Day, people model a dragon with bamboo strips and clothes, raise them with rods, and hold the rods high and low to resemble a flying dragon.A performer holding the rod low is represented by a 1, while one holding it high is represented by a 2. Thus, the line of performers can be represented by a sequence a1, a2, ..., an.Little Tommy is among them. He would like to choose an interval [l, r] (1 ≤ l ≤ r ≤ n), then reverse al, al + 1, ..., ar so that the length of the longest non-decreasing subsequence of the new sequence is maximum.A non-decreasing subsequence is a sequence of indices p1, p2, ..., pk, such that p1 < p2 < ... < pk and ap1 ≤ ap2 ≤ ... ≤ apk. The length of the subsequence is k.

The first line contains an integer n (1 ≤ n ≤ 2000), denoting the length of the original sequence. The second line contains n space-separated integers, describing the original sequence a1, a2, ..., an (1 ≤ ai ≤ 2, i = 1, 2, ..., n).

Print a single integer, which means the maximum possible length of the longest non-decreasing subsequence of the new sequence.

NoteIn the first example, after reversing [2, 3], the array will become [1, 1, 2, 2], where the length of the longest non-decreasing subsequence is 4.In the second example, after reversing [3, 7], the array will become [1, 1, 1, 1, 2, 2, 2, 2, 2, 1], where the length of the longest non-decreasing subsequence is 9.

package main

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

// github.com/EndlessCheng/codeforces-go
func CF933A(_r io.Reader, _w io.Writer) {
	max := func(a, b int) int {
		if a > b {
			return a
		}
		return b
	}
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var n int
	Fscan(in, &n)
	a := make([]int, n)
	sum := make([][2]int, n+1)
	for i := range a {
		Fscan(in, &a[i])
		sum[i+1][0] = sum[i][0]
		sum[i+1][1] = sum[i][1]
		sum[i+1][a[i]-1]++
	}
	ans := 0
	for _, s := range sum {
		ans = max(ans, s[0]+sum[n][1]-s[1])
	}
	for i := 1; i <= n; i++ {
		maxL := 0
		for _, s := range sum[:i] {
			maxL = max(maxL, s[0]+sum[i-1][1]-s[1])
		}
		maxR := 0
		for _, s := range sum[i:] {
			maxR = max(maxR, s[0]-sum[i-1][0]+sum[n][1]-s[1])
		}
		ans = max(ans, maxL+maxR)
	}
	Fprint(out, ans)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF933A(_r io.Reader, _w io.Writer) {
	max := func(a, b int) int {
		if a > b {
			return a
		}
		return b
	}
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var n int
	Fscan(in, &n)
	a := make([]int, n)
	sum := make([][2]int, n+1)
	for i := range a {
		Fscan(in, &a[i])
		sum[i+1][0] = sum[i][0]
		sum[i+1][1] = sum[i][1]
		sum[i+1][a[i]-1]++
	}
	ans := 0
	for i := range a {
		maxL := 0
		for _, s := range sum[:i+1] {
			maxL = max(maxL, s[0]+sum[i][1]-s[1])
		}
		maxR := 0
		for _, s := range sum[i:] {
			maxR = max(maxR, s[0]-sum[i][0]+sum[n][1]-s[1])
		}
		ans = max(ans, maxL+maxR)
	}
	Fprint(out, ans)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF933A(_r io.Reader, _w io.Writer) {
	max := func(a, b int) int {
		if a > b {
			return a
		}
		return b
	}
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var n int
	Fscan(in, &n)
	a := make([]int, n)
	sum := make([][2]int, n+1)
	for i := range a {
		Fscan(in, &a[i])
		sum[i+1][0] = sum[i][0]
		sum[i+1][1] = sum[i][1]
		sum[i+1][a[i]-1]++
	}
	ans := 0
	for i := 1; i <= n; i++ {
		maxL := 0
		for _, s := range sum[:i] {
			maxL = max(maxL, s[0]+sum[i-1][1]-s[1])
		}
		maxR := 0
		for _, s := range sum[i:] {
			maxR = max(maxR, s[0]-sum[i-1][0]+sum[n][1]-s[1])
		}
		ans = max(ans, maxL+maxR)
	}
	Fprint(out, ans)
}

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


You are given two arrays $$$a$$$ and $$$b$$$, each contains $$$n$$$ integers.You want to create a new array $$$c$$$ as follows: choose some real (i.e. not necessarily integer) number $$$d$$$, and then for every $$$i \in [1, n]$$$ let $$$c_i := d \cdot a_i + b_i$$$.Your goal is to maximize the number of zeroes in array $$$c$$$. What is the largest possible answer, if you choose $$$d$$$ optimally?

The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in both arrays. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$). The third line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$-10^9 \le b_i \le 10^9$$$).

Print one integer — the maximum number of zeroes in array $$$c$$$, if you choose $$$d$$$ optimally.

NoteIn the first example, we may choose $$$d = -2$$$.In the second example, we may choose $$$d = -\frac{1}{13}$$$.In the third example, we cannot obtain any zero in array $$$c$$$, no matter which $$$d$$$ we choose.In the fourth example, we may choose $$$d = 6$$$.

package main

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

type Num struct {
	f int
	u int64
	d int64
}

type Nums []*Num

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

func (s Nums) Swap(a, b int) {
	tmp := s[a]
	s[a] = s[b]
	s[b] = tmp
}
func (s Nums) Less(i, j int) bool {
	if s[i].f == 0 && s[j].f == 1 {
		return false
	}
	if s[i].f == 1 && s[j].f == 0 {
		return true
	}
	if s[i].f == 0 && s[j].f == 0 {
		if s[i].u*s[j].d < s[i].d*s[j].u {
			return true
		}
		return false
	} else {
		if s[i].u*s[j].d < s[i].d*s[j].u {
			return false
		}
		return true
	}
}
func nof(n int64) int64 {
	if n < 0 {
		return 0 - n
	}
	return n
}
func getf(u, d int64) int {
	if u == 0 {
		return 0
	}
	if (u > 0 && d > 0) || (u < 0 && d < 0) {
		return 0
	}
	return 1
}
func eq(a, b *Num) bool {
	if a.f != b.f {
		return false
	}
	if a.u*b.d != a.d*b.u {
		return false
	}
	return true
}
func main() {
	buf := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscanf(buf, "%d\n", &n)
	a := make([]int64, n)
	var v int64
	mat := make(Nums, 0)
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d", &a[i])
	}
	fmt.Fscanf(buf, "\n")
	tmp := 0
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d", &v)
		num := &Num{
		}
		if a[i] == 0 && v != 0 {
			continue
		}
		if v == 0 && a[i] == 0 {
			tmp++
			continue
		}
		v = 0 - v
		num.f = getf(v, a[i])
		num.u = nof(v)
		num.d = nof(a[i])
		mat = append(mat, num)
	}
	fmt.Fscanf(buf, "\n")
	sort.Sort(mat)
	ln := len(mat)
	ans := 0
	f := 0
	r := 0
//	fmt.Printf("ln=%d\n", ln)
	for f < ln {
		r = f
		for r < ln && eq(mat[f], mat[r]) {
			r++
		}
		if ans < r-f {
			ans = r - f
		}
		f = r
	}
	fmt.Printf("%d\n", ans+tmp)
}

package main

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

type Prob struct {
    in *bufio.Reader
}

func (prob *Prob) NextLine() string {
    line, _, _ := prob.in.ReadLine()
    return string(line[:])
}

func (prob *Prob) NextByte() byte {
    bt, _ := prob.in.ReadByte()
    return bt
}

func (prob *Prob) Next() string {
    var buff bytes.Buffer
    bt := prob.NextByte()
    for bt == '\n' || bt == ' ' {
        bt = prob.NextByte()
    }
    for bt != '\n' && bt != ' ' {
        buff.WriteByte(bt)
        bt = prob.NextByte()
    }
    return buff.String()
}

func (prob *Prob) NextInt() int {
    var x int
    bt := prob.NextByte()
    for bt > '9' || bt < '0' {
        if bt == '-' {
            return -prob.NextInt()
        }
        bt = prob.NextByte()
    }
    for bt >= '0' && bt <= '9' {
        x = x * 10 + int(bt - '0')
        bt = prob.NextByte()
    }
    return x
}

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

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

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

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

type P struct {
    a int
    b int
}

func (a *P) Sp() {
    if a.b < 0 {
        a.a *= -1
        a.b *= -1
    }
    gcd := Gcd(Abs(a.a), Abs(a.b))
    if gcd != 0 {
        a.a /= gcd
        a.b /= gcd
    }
    if a.b == 0 && a.a != 0 {
        a.a = 1
    }
}

type PS []P

func (a PS) Len() int {
    return len(a)
}

func (a PS) Swap(i int, j int) {
    a[i], a[j] = a[j], a[i]
}

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

func (prob Prob) Solve() {
    n := prob.NextInt()
    ps := make([]P, n, n)
    for i := 0; i < n; i++ {
        ps[i].a = prob.NextInt()
    }
    for i := 0; i < n; i++ {
        ps[i].b = prob.NextInt()
        ps[i].Sp()
    }
    sort.Sort(PS(ps))
    res := 0
    zero := 0
    for i := 0; i < n; {
        if ps[i].a == 0 {
            if ps[i].b == 0 {
                zero++
            }
            i++
            continue
        }
        j := i
        for ; j < n && ps[i].a == ps[j].a && ps[i].b == ps[j].b; j++ {}
        res = Max(res, j - i)
        i = j
    }
    fmt.Println(res + zero)
}

func main() {
    Prob{in: bufio.NewReader(os.Stdin)}.Solve()
}

/*
URL:
https://codeforces.com/problemset/problem/1133/D
*/

package main

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

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

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

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

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

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

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

const (
	// General purpose
	MOD          = 1000000000 + 7
	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, B []int
	C, D []int
)

func main() {
	n = ReadInt()
	A, B = ReadIntSlice(n), ReadIntSlice(n)

	C, D = []int{}, []int{}
	ans := 0
	for i := 0; i < n; i++ {
		a, b := A[i], B[i]
		if a == 0 {
			if b == 0 {
				ans++
			}
		} else {
			C = append(C, a)
			D = append(D, b)
		}
	}

	memo := make(map[Value]int)
	for i := 0; i < len(C); i++ {
		a, b := C[i], D[i]
		g := Gcd(AbsInt(a), AbsInt(b))
		a /= g
		b /= g

		if a < 0 {
			a *= -1
			b *= -1
		}

		v := Value{bunbo: a, bunshi: -b}
		memo[v]++
	}

	num := 0
	for _, v := range memo {
		ChMax(&num, v)
	}
	fmt.Println(ans + num)
}

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

// 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 Value struct {
	bunbo, bunshi int
}

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

	if a == 0 {
		return b
	}
	if b == 0 {
		return a
	}

	if a < b {
		a, b = b, a
	}

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

	return a
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

	return string(res)
}

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

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

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

	return string(res)
}

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

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

package main

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

type Prob struct {
    in *bufio.Reader
}

func (prob *Prob) NextLine() string {
    line, _, _ := prob.in.ReadLine()
    return string(line[:])
}

func (prob *Prob) NextByte() byte {
    bt, _ := prob.in.ReadByte()
    return bt
}

func (prob *Prob) Next() string {
    var buff bytes.Buffer
    bt := prob.NextByte()
    for bt == '\n' || bt == ' ' {
        bt = prob.NextByte()
    }
    for bt != '\n' && bt != ' ' {
        buff.WriteByte(bt)
        bt = prob.NextByte()
    }
    return buff.String()
}

func (prob *Prob) NextInt() int {
    var x int
    bt := prob.NextByte()
    for bt > '9' || bt < '0' {
        if bt == '-' {
            return -prob.NextInt()
        }
        bt = prob.NextByte()
    }
    for bt >= '0' && bt <= '9' {
        x = x * 10 + int(bt - '0')
        bt = prob.NextByte()
    }
    return x
}

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

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

type P struct {
    a int
    b int
}

type PS []P

func (a PS) Len() int {
    return len(a)
}

func (a PS) Swap(i int, j int) {
    a[i], a[j] = a[j], a[i]
}

func (a PS) Less(i int, j int) bool {
    sa := a[i].a * a[i].b
    sb := a[j].a * a[j].b
    if sa < 0 && sb > 0 {
        return true
    } else if sa > 0 && sb < 0 {
        return false
    } else if sa > 0 {
        return a[i].a * a[j].b < a[i].b * a[j].a
    } else {
        return a[i].a * a[j].b > a[i].b * a[j].a
    }
}

func (prob Prob) Solve() {
    n := prob.NextInt()
    ps := make([]P, n, n)
    for i := 0; i < n; i++ {
        ps[i].a = prob.NextInt()
    }
    for i := 0; i < n; i++ {
        ps[i].b = prob.NextInt()
    }
    sort.Sort(PS(ps))
    res := 0
    zero := 0
    i := 0
    j := 0
    for ; i < n; i++ {
        if ps[i].a == 0 {
            if ps[i].b == 0 {
                zero++
            }
            continue
        }
        j = Max(i, j)
        for ; j < n && ps[i].a * ps[j].b == ps[i].b * ps[j].a; j++ {}
        res = Max(res, j - i)
    }
    fmt.Println(res + zero)
}

func main() {
    Prob{in: bufio.NewReader(os.Stdin)}.Solve()
}

package main

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

type Prob struct {
    in *bufio.Reader
}

func (prob *Prob) NextLine() string {
    line, _, _ := prob.in.ReadLine()
    return string(line[:])
}

func (prob *Prob) NextByte() byte {
    bt, _ := prob.in.ReadByte()
    return bt
}

func (prob *Prob) Next() string {
    var buff bytes.Buffer
    bt := prob.NextByte()
    for bt == '\n' || bt == ' ' {
        bt = prob.NextByte()
    }
    for bt != '\n' && bt != ' ' {
        buff.WriteByte(bt)
        bt = prob.NextByte()
    }
    return buff.String()
}

func (prob *Prob) NextInt() int {
    var x int
    bt := prob.NextByte()
    for bt > '9' || bt < '0' {
        if bt == '-' {
            return -prob.NextInt()
        }
        bt = prob.NextByte()
    }
    for bt >= '0' && bt <= '9' {
        x = x * 10 + int(bt - '0')
        bt = prob.NextByte()
    }
    return x
}

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

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

type P struct {
    a int
    b int
}

type PS []P

func (a PS) Len() int {
    return len(a)
}

func (a PS) Swap(i int, j int) {
    a[i], a[j] = a[j], a[i]
}

func (a PS) Less(i int, j int) bool {
    return a[i].a * a[j].b < a[i].b * a[j].a
}

func (prob Prob) Solve() {
    n := prob.NextInt()
    ps := make([]P, n, n)
    for i := 0; i < n; i++ {
        ps[i].a = prob.NextInt()
    }
    for i := 0; i < n; i++ {
        ps[i].b = prob.NextInt()
    }
    sort.Sort(PS(ps))
    res := 0
    i := 0
    j := 0
    for ; i < n; i++ {
        for ; j < n && ps[i].a * ps[j].b >= ps[i].b * ps[j].a; j++ {}
        res = Max(res, j - i)
    }
    fmt.Println(res)
}

func main() {
    Prob{in: bufio.NewReader(os.Stdin)}.Solve()
}

package main

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

type Prob struct {
    in *bufio.Reader
}

func (prob *Prob) NextLine() string {
    line, _, _ := prob.in.ReadLine()
    return string(line[:])
}

func (prob *Prob) NextByte() byte {
    bt, _ := prob.in.ReadByte()
    return bt
}

func (prob *Prob) Next() string {
    var buff bytes.Buffer
    bt := prob.NextByte()
    for bt == '\n' || bt == ' ' {
        bt = prob.NextByte()
    }
    for bt != '\n' && bt != ' ' {
        buff.WriteByte(bt)
        bt = prob.NextByte()
    }
    return buff.String()
}

func (prob *Prob) NextInt() int {
    var x int
    bt := prob.NextByte()
    for bt > '9' || bt < '0' {
        if bt == '-' {
            return -prob.NextInt()
        }
        bt = prob.NextByte()
    }
    for bt >= '0' && bt <= '9' {
        x = x * 10 + int(bt - '0')
        bt = prob.NextByte()
    }
    return x
}

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

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

type P struct {
    a int
    b int
}

type PS []P

func (a PS) Len() int {
    return len(a)
}

func (a PS) Swap(i int, j int) {
    a[i], a[j] = a[j], a[i]
}

func (a PS) Less(i int, j int) bool {
    return a[i].a * a[j].b < a[i].b * a[j].a
}

func (prob Prob) Solve() {
    n := prob.NextInt()
    ps := make([]P, n, n)
    for i := 0; i < n; i++ {
        ps[i].a = prob.NextInt()
    }
    for i := 0; i < n; i++ {
        ps[i].b = prob.NextInt()
    }
    sort.Sort(PS(ps))
    res := 0
    zero := 0
    i := 0
    j := 0
    for ; i < n; i++ {
        if ps[i].a == 0 {
            if ps[i].b == 0 {
                zero++
            }
            continue
        }
        j = Max(i, j)
        for ; j < n && ps[i].a * ps[j].b >= ps[i].b * ps[j].a; j++ {}
        res = Max(res, j - i)
    }
    fmt.Println(res + zero)
}

func main() {
    Prob{in: bufio.NewReader(os.Stdin)}.Solve()
}

package main

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

type Prob struct {
    in *bufio.Reader
}

func (prob *Prob) NextLine() string {
    line, _, _ := prob.in.ReadLine()
    return string(line[:])
}

func (prob *Prob) NextByte() byte {
    bt, _ := prob.in.ReadByte()
    return bt
}

func (prob *Prob) Next() string {
    var buff bytes.Buffer
    bt := prob.NextByte()
    for bt == '\n' || bt == ' ' {
        bt = prob.NextByte()
    }
    for bt != '\n' && bt != ' ' {
        buff.WriteByte(bt)
        bt = prob.NextByte()
    }
    return buff.String()
}

func (prob *Prob) NextInt() int {
    var x int
    bt := prob.NextByte()
    for bt > '9' || bt < '0' {
        if bt == '-' {
            return -prob.NextInt()
        }
        bt = prob.NextByte()
    }
    for bt >= '0' && bt <= '9' {
        x = x * 10 + int(bt - '0')
        bt = prob.NextByte()
    }
    return x
}

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

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

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

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

type P struct {
    a int
    b int
}

func (a *P) Sp() {
    if a.b < 0 {
        a.a *= -1
        a.b *= -1
    }
    gcd := Gcd(Abs(a.a), Abs(a.b))
    if gcd != 0 {
        a.a /= gcd
        a.b /= gcd
    }
    if a.b == 0 {
        a.a = 1
    }
}

type PS []P

func (a PS) Len() int {
    return len(a)
}

func (a PS) Swap(i int, j int) {
    a[i], a[j] = a[j], a[i]
}

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

func (prob Prob) Solve() {
    n := prob.NextInt()
    ps := make([]P, n, n)
    for i := 0; i < n; i++ {
        ps[i].a = prob.NextInt()
    }
    for i := 0; i < n; i++ {
        ps[i].b = prob.NextInt()
        ps[i].Sp()
    }
    sort.Sort(PS(ps))
    res := 0
    zero := 0
    for i := 0; i < n; {
        if ps[i].a == 0 {
            if ps[i].b == 0 {
                zero++
            }
            i++
            continue
        }
        j := i
        for ; j < n && ps[i].a == ps[j].a && ps[i].b == ps[j].b; j++ {}
        res = Max(res, j - i)
        i = j
    }
    fmt.Println(res + zero)
}

func main() {
    Prob{in: bufio.NewReader(os.Stdin)}.Solve()
}

package main

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

type Prob struct {
    in *bufio.Reader
}

func (prob *Prob) NextLine() string {
    line, _, _ := prob.in.ReadLine()
    return string(line[:])
}

func (prob *Prob) NextByte() byte {
    bt, _ := prob.in.ReadByte()
    return bt
}

func (prob *Prob) Next() string {
    var buff bytes.Buffer
    bt := prob.NextByte()
    for bt == '\n' || bt == ' ' {
        bt = prob.NextByte()
    }
    for bt != '\n' && bt != ' ' {
        buff.WriteByte(bt)
        bt = prob.NextByte()
    }
    return buff.String()
}

func (prob *Prob) NextInt() int {
    var x int
    bt := prob.NextByte()
    for bt > '9' || bt < '0' {
        if bt == '-' {
            return -prob.NextInt()
        }
        bt = prob.NextByte()
    }
    for bt >= '0' && bt <= '9' {
        x = x * 10 + int(bt - '0')
        bt = prob.NextByte()
    }
    return x
}

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

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

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

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

type P struct {
    a int
    b int
}

func (a *P) Sp() {
    if a.b < 0 {
        a.a *= -1
        a.b *= -1
    }
    gcd := Gcd(Abs(a.a), Abs(a.b))
    if gcd != 0 {
        a.a /= gcd
        a.b /= gcd
    }
}

type PS []P

func (a PS) Len() int {
    return len(a)
}

func (a PS) Swap(i int, j int) {
    a[i], a[j] = a[j], a[i]
}

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

func (prob Prob) Solve() {
    n := prob.NextInt()
    ps := make([]P, n, n)
    for i := 0; i < n; i++ {
        ps[i].a = prob.NextInt()
    }
    for i := 0; i < n; i++ {
        ps[i].b = prob.NextInt()
        ps[i].Sp()
    }
    sort.Sort(PS(ps))
    res := 0
    zero := 0
    i := 0
    j := 0
    for ; i < n; i++ {
        if ps[i].a == 0 {
            if ps[i].b == 0 {
                zero++
            }
            continue
        }
        j = Max(i, j)
        for ; j < n && ps[i].a == ps[j].a && ps[i].b == ps[j].b; j++ {}
        res = Max(res, j - i)
    }
    fmt.Println(res + zero)
}

func main() {
    Prob{in: bufio.NewReader(os.Stdin)}.Solve()
}


This is a simplified version of the task Toy Train. These two versions differ only in the constraints. Hacks for this version are disabled.Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of $$$n$$$ stations, enumerated from $$$1$$$ through $$$n$$$. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station $$$i$$$ is station $$$i+1$$$ if $$$1 \leq i < n$$$ or station $$$1$$$ if $$$i = n$$$. It takes the train $$$1$$$ second to travel to its next station as described.Bob gave Alice a fun task before he left: to deliver $$$m$$$ candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from $$$1$$$ through $$$m$$$. Candy $$$i$$$ ($$$1 \leq i \leq m$$$), now at station $$$a_i$$$, should be delivered to station $$$b_i$$$ ($$$a_i \neq b_i$$$).    The blue numbers on the candies correspond to $$$b_i$$$ values. The image corresponds to the $$$1$$$-st example. The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.

The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 100$$$; $$$1 \leq m \leq 200$$$) — the number of stations and the number of candies, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$; $$$a_i \neq b_i$$$) — the station that initially contains candy $$$i$$$ and the destination station of the candy, respectively.

In the first and only line, print $$$n$$$ space-separated integers, the $$$i$$$-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station $$$i$$$.

NoteConsider the second sample.If the train started at station $$$1$$$, the optimal strategy is as follows.  Load the first candy onto the train.  Proceed to station $$$2$$$. This step takes $$$1$$$ second.  Deliver the first candy.  Proceed to station $$$1$$$. This step takes $$$1$$$ second.  Load the second candy onto the train.  Proceed to station $$$2$$$. This step takes $$$1$$$ second.  Deliver the second candy.  Proceed to station $$$1$$$. This step takes $$$1$$$ second.  Load the third candy onto the train.  Proceed to station $$$2$$$. This step takes $$$1$$$ second.  Deliver the third candy. Hence, the train needs $$$5$$$ seconds to complete the tasks.If the train were to start at station $$$2$$$, however, it would need to move to station $$$1$$$ before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is $$$5+1 = 6$$$ seconds.

package main

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

func dist(a, b, n int) int {
	return (b + n - a) % n
}

func getNumsFromOneLine(ir *bufio.Reader) []int {
	stream, _ := ir.ReadString('\n')
	// Trims the stream and then splits
	trimmedStream := strings.TrimSpace(stream)
	splitArr := strings.Split(trimmedStream, " ")
	// convert strings to integers and store them in a slice
	nums := make([]int, len(splitArr))
	for index, val := range splitArr {
		nums[index], _ = strconv.Atoi(val)
	}
	return nums
}

func main() {
	ir := bufio.NewReader(os.Stdin)
	nm := getNumsFromOneLine(ir)
	n, m := nm[0], nm[1]
	des := make([]int, 5004) // station i 的 destination 是des[i]
	cnt := make([]int, 5004) // station i 里面共有 candy cnt[1]个
	for i := 0; i < m; i += 1 {
		ab := getNumsFromOneLine(ir)
		a, b := ab[0], ab[1]
		if des[a] == 0 {
			des[a] = b
		} else {
			if dist(a, b, n) < dist(a, des[a], n) {
				des[a] = b // 永远使得最后一轮距离最短
			}
		}
		cnt[a] += 1
	}

	res := make([]string, 0)
	for i := 1; i < n+1; i++ { // 起点是 station i
		curRes := 0
		for j := 1; j < n+1; j++ {
			if des[j] > 0 {
				// curRes 永远取最大那个
				// 对于某个 station j 来说，所需要走的距离为从起点 station i 到 station j 的距离       +
				//                                    (candy 数 - 1) * n                       +
				//                                     从 station j 到达最终的 destination des[j]
				curRes = int(math.Max(float64(curRes), float64(dist(i, j, n) + (cnt[j] - 1) * n + dist(j, des[j], n))))
			}
		}
		res = append(res, strconv.Itoa(curRes))
	}
	fmt.Println(strings.Join(res, " "))
}

package main

import (
	"fmt"
	"math"
	"strconv"
)

func dist(a, b, n int) int {
	return (b + n - a) % n
}

func main() {
	var nn, mm string
	fmt.Scanf("%s %s\n", &nn, &mm)
	n, _ := strconv.Atoi(nn)
	m, _ := strconv.Atoi(mm)
	//fmt.Println(n, m)
	nums, cnt := [5004]int{}, [5004]int{}
	for i := 0; i < m; i++ {
		var aa, bb string
		fmt.Scanf("%s %s\n", &aa, &bb)
		a, _ := strconv.Atoi(aa)
		b, _ := strconv.Atoi(bb)
		//fmt.Println(aa, bb)
		if nums[a] == 0 {
			nums[a] = b
		} else {
			cnt[a] += 1
			if dist(a, b, n) < dist(a, nums[a], n) {
				nums[a] = b
			}

		}
	}
	res := ""
	for i := 1; i < n+1; i++ {
		ans := 0
		for j := 1; j < n+1; j++ {
			if nums[j] > 0 {
				ans = int(math.Max(float64(ans), float64(dist(i, j, n) + cnt[j] * n + dist(j, nums[j], n))))
			}
		}
		res += strconv.Itoa(ans) + " "
	}
	fmt.Println(res[:len(res)-1])
}

package main

import (
	"fmt"
	"math"
	"strconv"
)

func dist(a, b, n int) int {
	return (b + n - a) % n
}

func main() {
	var nn, mm string
	fmt.Scanf("%s %s", &nn, &mm)
	n, _ := strconv.Atoi(nn)
	m, _ := strconv.Atoi(mm)
	nums, cnt := [5004]int{}, [5004]int{}
	for i := 0; i < m; i++ {
		var aa, bb string
		fmt.Scanf("%s %s", &aa, &bb)
		a, _ := strconv.Atoi(aa)
		b, _ := strconv.Atoi(bb)
		if nums[a] == 0 {
			nums[a] = b
		} else {
			cnt[a] += 1
			if dist(a, b, n) < dist(a, nums[a], n) {
				nums[a] = b
			}

		}
	}
	res := ""
	for i := 1; i < n+1; i++ {
		ans := 0
		for j := 1; j < n+1; j++ {
			if nums[j] > 0 {
				ans = int(math.Max(float64(ans), float64(dist(i, j, n) + cnt[j] * n + dist(j, nums[j], n))))
			}
		}
		res += strconv.Itoa(ans) + " "
	}
	fmt.Println(res[:len(res)-1])
}


You are given two strings $$$s$$$ and $$$t$$$. Both strings have length $$$n$$$ and consist of lowercase Latin letters. The characters in the strings are numbered from $$$1$$$ to $$$n$$$.You can successively perform the following move any number of times (possibly, zero):  swap any two adjacent (neighboring) characters of $$$s$$$ (i.e. for any $$$i = \{1, 2, \dots, n - 1\}$$$ you can swap $$$s_i$$$ and $$$s_{i + 1})$$$. You can't apply a move to the string $$$t$$$. The moves are applied to the string $$$s$$$ one after another.Your task is to obtain the string $$$t$$$ from the string $$$s$$$. Find any way to do it with at most $$$10^4$$$ such moves.You do not have to minimize the number of moves, just find any sequence of moves of length $$$10^4$$$ or less to transform $$$s$$$ into $$$t$$$.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the length of strings $$$s$$$ and $$$t$$$. The second line of the input contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. The third line of the input contains the string $$$t$$$ consisting of $$$n$$$ lowercase Latin letters.

If it is impossible to obtain the string $$$t$$$ using moves, print "-1". Otherwise in the first line print one integer $$$k$$$ — the number of moves to transform $$$s$$$ to $$$t$$$. Note that $$$k$$$ must be an integer number between $$$0$$$ and $$$10^4$$$ inclusive. In the second line print $$$k$$$ integers $$$c_j$$$ ($$$1 \le c_j < n$$$), where $$$c_j$$$ means that on the $$$j$$$-th move you swap characters $$$s_{c_j}$$$ and $$$s_{c_j + 1}$$$. If you do not need to apply any moves, print a single integer $$$0$$$ in the first line and either leave the second line empty or do not print it at all.

NoteIn the first example the string $$$s$$$ changes as follows: "abcdef" $$$\rightarrow$$$ "abdcef" $$$\rightarrow$$$ "abdcfe" $$$\rightarrow$$$ "abdfce" $$$\rightarrow$$$ "abdfec".In the second example there is no way to transform the string $$$s$$$ into the string $$$t$$$ through any allowed moves.

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	var ss, tt string
	fmt.Scan(&ss)
	fmt.Scan(&tt)
	s:=make([]uint8,n)
	t:=make([]uint8,n)
	for i:=0;i<n;i++ {
		s[i]=ss[i]
		t[i]=tt[i]
	}
	a := make([]int, 400)
	b := make([]int, 400)
	for i := 0; i < n; i++ {
		a[s[i]]++
	}
	for i := 0; i < n; i++ {
		b[t[i]]++
	}
	for i := 'a'; i <= 'z'; i++ {
		if a[i] != b[i] {
			fmt.Println(-1);
			return
		}
	}
	ind:=0
	res:=make([]int,10000)
	for i := 0; i < n; i++ {
		//fmt.Printf("! %d\n",i)
		j := i
		for j = i; s[j] != t[i]; j++ {
			//fmt.Println(j)
		}
		for j>i {
			res[ind]=j
			j--
			ind++
			c:=s[j]
			s[j]=s[j+1]
			s[j+1]=c
		}
	}
	fmt.Println(ind)
	for i:=0;i<ind;i++ {
		fmt.Printf("%d ",res[i])
	}
}

package main

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

var allAns []int

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n := 0
	fmt.Fscanf(in, "%d\n", &n)
	s1 := ""
	s2 := ""
	fmt.Fscanf(in, "%s\n", &s1)
	fmt.Fscanf(in, "%s\n", &s2)
	allAns = make([]int, 0)
	ok := move([]byte(s1), []byte(s2), 1)
	if !ok {
		fmt.Fprintf(out, "%d\n", -1)
		return
	}
	fmt.Fprintf(out, "%d\n", len(allAns))
	if len(allAns) > 0 {
		fmt.Fprintf(out, "%d", allAns[0])
		for i := 1; i < len(allAns); i++ {
			fmt.Fprintf(out, " %d", allAns[i])
		}
		fmt.Fprintf(out, "\n")
	}

	return
}

func move(s1, s2 []byte, offset int) bool {
	n := len(s1)
	if n == 0 {
		return true
	}
	found := -1
	for i := 0; i < n; i++ {
		if s1[i] == s2[0] {
			found = i
			break
		}
	}
	if found == -1 {
		return false
	}
	for i := found - 1; i >= 0; i-- {
		allAns = append(allAns, i+offset)
		s1[i], s1[i+1] = s1[i+1], s1[i]
	}
	return move(s1[1:], s2[1:], offset+1)
}

package main

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

func main()  {

	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	var n int
	fmt.Fscan(in, &n)

	var s, t string
	fmt.Fscan(in, &s, &t)

	result := make([]int, 0)

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

		pos := -1
		for j := i; j < n; j++ {
			if t[i] == s[j] {
				pos = j
				break
			}
		}

		if pos == -1 {
			fmt.Fprintln(out, "-1")
			return
		}

		for j := pos - 1; j >= i; j-- {
			result = append(
				result,
				j + 1,
			)
		}

		s = s[:i] + s[pos:pos+1] + s[i:pos] + s[pos+1:]

	}

	fmt.Fprintln(out, len(result))
	for i := 0; i < len(result); i++ {
		fmt.Fprint(out, result[i], " ")
	}

}

package main

import (
	"fmt"
	"os"
)

var n int

func main() {
	fmt.Scanf("%d\n", &n)
	var st, ed string
	fmt.Scanf("%s\n%s\n", &st, &ed)
	step := 0
	steps := make([]int, 0)
	for step < n {
		if st[step] != ed[step] {
			f := false
			for i := step + 1; i < n; i++ {
				if st[i] == ed[step] {
					f = true
					for j := i - 1; j >= step; j-- {
						steps = append(steps, j)
					}
					st = swap(st, step, i)
					break
				}
			}
			if !f {
				fmt.Println(-1)
				os.Exit(0)
			}
		}
		step++
	}
	fmt.Println(len(steps))
	if len(steps) != 0 {
		fmt.Print(steps[0] + 1)
		for i := 1; i < len(steps); i++ {
			fmt.Print(" ", steps[i]+1)
		}
		fmt.Println()
	}
}
func swap(s string, st int, ed int) string {
	bytes := []byte(s)
	t := bytes[ed]
	for i := ed; i > st; i-- {
		bytes[i] = bytes[i-1]
	}
	bytes[st] = t
	return string(bytes)
}

package main

import (
	. "fmt"
)

func swapBytes(bs []byte, p1, p2 int) {
	tmp := bs[p2]
	bs[p2] = bs[p1]
	bs[p1] = tmp
}

func main() {
	var n int
	var s1, s2 string
	Scan(&n, &s1, &s2)

	cnt1 := make([]int, 26)
	cnt2 := make([]int, 26)
	for _, c := range s1 {
		cnt1[c-'a']++
	}
	for _, c := range s2 {
		cnt2[c-'a']++
	}

	if Sprint(cnt1) != Sprint(cnt2) {
		Println(-1)
	} else {
		b1 := []byte(s1)
		b2 := []byte(s2)

		cnt:=0
		var ans []interface{}

		for i, b := range b2 {
			if b != b1[i] {
				for j := i; j < n; j++ {
					if b == b1[j] {
						for k := j-1; k >=i; k-- {
							swapBytes(b1, k, k+1)

							cnt++
							ans = append(ans,k+1)
						}
						break
					}
				}
			}
		}

		Println(cnt)
		Print(ans...)
	}

}

package main

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

func SortString(s string) string {
	sa := strings.Split(s, "")
	sort.Strings(sa)
	return strings.Join(sa, "")
}

func SwapItem(stringArray []string, i int) []string {
	tmp := stringArray[i]
	stringArray[i] = stringArray[i-1]
	stringArray[i-1] = tmp
	return stringArray
}

func SearchItemIndex(stringArray []string, s string, startIndex int) int {
	l := len(stringArray)
	for i := startIndex; i < l; i++ {
		if stringArray[i] == s {
			return i
		}
	}
	return -1
}

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

	if s == t {
		fmt.Println("0")
		return
	}

	sortedS := SortString(s)
	sortedT := SortString(t)

	if sortedS != sortedT {
		fmt.Println("-1")
		return
	}

	sArray := strings.Split(s, "")
	tArray := strings.Split(t, "")

	var result []int

	for k, v := range tArray {
		if sArray[k] == v {
			continue
		}

		index := SearchItemIndex(sArray, v, k+1)
		for i := index; i > k; i-- {
			sArray = SwapItem(sArray, i)
			result = append(result, i)
		}
	}

	output := fmt.Sprint(result)
	output = strings.Replace(output, "[", "", -1)
	output = strings.Replace(output, "]", "", -1)

	fmt.Println(len(result))
	fmt.Println(output)
}

package main

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

func main()  {

	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	var n int
	fmt.Fscan(in, &n)

	var s, t string
	fmt.Fscan(in, &s, &t)

	result := make([]int, 0)

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

		pos := -1
		for j := i; j < n; j++ {
			if t[i] == s[j] {
				pos = j
				break
			}
		}

		if pos == -1 {
			fmt.Fprintln(out, "-1")
			break
		}

		for j := pos - 1; j >= i; j-- {
			result = append(
				result,
				j + 1,
			)
		}

		s = s[:i] + s[pos:pos+1] + s[i:pos] + s[pos+1:]

	}

	fmt.Fprintln(out, len(result))
	for i := 0; i < len(result); i++ {
		fmt.Fprint(out, result[i], " ")
	}

}

package main

import (
	"fmt"
	"os"
)

var n int

func main() {
	fmt.Scanf("%d\n", &n)
	var st, ed string
	fmt.Scanf("%s\n%s\n", &st, &ed)
	step := 0
	steps := make([]int, 0)
	for step < n {
		if st[step] != ed[step] {
			f := false
			for i := step + 1; i < n; i++ {
				if st[i] == ed[step] {
					f = true
					for j := i - 1; j >= step; j-- {
						steps = append(steps, j)
					}
					st = swap(st, step, i)
					break
				}
			}
			if !f {
				fmt.Println(-1)
				os.Exit(0)
			}
		}
		step++
	}
	fmt.Println(len(steps))
	if len(steps) == 0 {
		fmt.Print(steps[0] + 1)
		for i := 1; i < len(steps); i++ {
			fmt.Print(" ", steps[i]+1)
		}
		fmt.Println()
	}
}
func swap(s string, st int, ed int) string {
	bytes := []byte(s)
	t := bytes[ed]
	for i := ed; i > st; i-- {
		bytes[i] = bytes[i-1]
	}
	bytes[st] = t
	return string(bytes)
}

package main

import (
	. "fmt"
)

func swapBytes(bs []byte, p1, p2 int) {
	tmp := bs[p2]
	bs[p2] = bs[p1]
	bs[p1] = tmp
}

func main() {
	var n int
	var s1, s2 string
	Scan(&n, &s1, &s2)

	cnt1 := make([]int, 26)
	cnt2 := make([]int, 26)
	for _, c := range s1 {
		cnt1[c-'a']++
	}
	for _, c := range s2 {
		cnt2[c-'a']++
	}

	if Sprint(cnt1) != Sprint(cnt2) {
		Println(-1)
	} else {
		b1 := []byte(s1)
		b2 := []byte(s2)

		for i, b := range b2 {
			if b != b1[i] {
				for j := i; j < n; j++ {
					if b == b1[j] {
						for k := j-1; k >=i; k-- {
							swapBytes(b1, k, k+1)
							Printf("%d ", k+1)
						}
						break
					}
				}
			}
		}
	}

}

package main

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

func SortString(s string) string {
	sa := strings.Split(s, "")
	sort.Strings(sa)
	return strings.Join(sa, "")
}

func SwapItem(stringArray []string, i int) []string {
	tmp := stringArray[i]
	stringArray[i] = stringArray[i-1]
	stringArray[i-1] = tmp
	return stringArray
}

func SearchItemIndex(stringArray []string, s string) int {
	for k, v := range stringArray {
		if v == s {
			return k
		}
	}
	return -1
}

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

	sortedS := SortString(s)
	sortedT := SortString(t)

	if sortedS != sortedT {
		fmt.Println("-1")
		return
	}

	sArray := strings.Split(s, "")
	tArray := strings.Split(t, "")

	var result []int

	for k, v := range tArray {
		if sArray[k] == v {
			continue
		}

		index := SearchItemIndex(sArray, v)
		for i := index; i > k; i-- {
			sArray = SwapItem(sArray, i)
			result = append(result, i)
		}
	}

	output := fmt.Sprint(result)
	output = strings.Replace(output, "[", "", -1)
	output = strings.Replace(output, "]", "", -1)

	fmt.Println(len(result))
	fmt.Println(output)
}


One day, liouzhou_101 got a chat record of Freda and Rainbow. Out of curiosity, he wanted to know which sentences were said by Freda, and which were said by Rainbow. According to his experience, he thought that Freda always said "lala." at the end of her sentences, while Rainbow always said "miao." at the beginning of his sentences. For each sentence in the chat record, help liouzhou_101 find whose sentence it is.

The first line of the input contains an integer n (1 ≤ n ≤ 10), number of sentences in the chat record. Each of the next n lines contains a sentence. A sentence is a string that contains only Latin letters (A-Z, a-z), underline (_), comma (,), point (.) and space ( ). Its length doesn’t exceed 100.

For each sentence, output "Freda's" if the sentence was said by Freda, "Rainbow's" if the sentence was said by Rainbow, or "OMG>.< I don't know!" if liouzhou_101 can’t recognize whose sentence it is. He can’t recognize a sentence if it begins with "miao." and ends with "lala.", or satisfies neither of the conditions.

5
I will go to play with you lala.
wow, welcome.
miao.lala.
miao.
miao .

Freda's
OMG>.< I don't know!
OMG>.< I don't know!
Rainbow's
OMG>.< I don't know!

package main

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

var w *bufio.Writer = bufio.NewWriter(os.Stdout)
var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)

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

func main() {
	scanner.Split(bufio.ScanLines)
	n := NextInt()
	for i := 0; i < n; i++ {
		scanner.Scan()
		miao, lala := strings.HasPrefix(scanner.Text(), "miao."),
			strings.HasSuffix(scanner.Text(), "lala.")
		if miao && !lala {
			w.WriteString("Rainbow's\n")
		} else if !miao && lala {
			w.WriteString("Freda's\n")
		} else {
			w.WriteString("OMG>.< I don't know!\n")
		}
	}
	w.Flush()
}

package main

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

func main() {
	var n int
	var a,b,c string
	b="miao."
	c="lala."
	input := bufio.NewScanner(os.Stdin)
	input.Split(bufio.ScanLines)
	input.Scan()
	bb,_:=strconv.Atoi(input.Text())
	n=bb
	for  k:=0;k<n;k++{
		input.Scan()
		a = input.Text()
		cek1 := strings.HasPrefix(a,b)
		cek2 := strings.HasSuffix(a,c)
		if cek1==false && cek2==true  {
			fmt.Println("Freda's")
		} else if cek1==true && cek2==false {
			fmt.Println("Rainbow's")
		} else {
			fmt.Println("OMG>.< I don't know!")
		}
	}
}

package main

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

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Scan()
    count, _ := strconv.Atoi(scanner.Text())

    for i := 0; i < count; i++ {
        scanner.Scan()
        text := scanner.Text()

        const miao = "miao."
        isRainbow := text == miao || strings.HasPrefix(text, miao)
        const lala = "lala."
        isFreda := text == lala || strings.HasSuffix(text, lala)

        if isFreda && isRainbow == false {
            fmt.Println("Freda's")
        } else
        if isRainbow && isFreda == false {
            fmt.Println("Rainbow's")
        } else {
            fmt.Println("OMG>.< I don't know!")
        }
    }
}

package main

import "os"
import "bufio"
import "strconv"
import "strings"

func main(){
	var n int
	r := bufio.NewScanner(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	r.Scan()
	n, _ = strconv.Atoi(r.Text())
	f := "lala."
	ra := "miao."
	for i:=0; i<n; i++ {
		r.Scan()
		if strings.HasSuffix(r.Text(), f) && !strings.HasPrefix(r.Text(), ra) {
			w.WriteString("Freda's\n")
		} else if strings.HasPrefix(r.Text(), ra) && !strings.HasSuffix(r.Text(), f) {
			w.WriteString("Rainbow's\n")
		} else {
			w.WriteString("OMG>.< I don't know!\n")
		}
		w.Flush()
	}
}

package main

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

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Scan()
    n, _ := strconv.Atoi(scanner.Text())
    for i := 0; i < n; i++ {
        scanner.Scan()
        if len(scanner.Text()) < 5 {
            fmt.Println("OMG>.< I don't know!")
        } else {
            begin, end := scanner.Text()[:5], scanner.Text()[len(scanner.Text())-5:]
            if (begin == "miao.") && (end != "lala.") {
                fmt.Println("Rainbow's")
            } else if (begin != "miao.") && (end == "lala.") {
                fmt.Println("Freda's")
            } else {
                fmt.Println("OMG>.< I don't know!")
            }
        }
    }
}

//312A

package main

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

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

func NextInt() int {
	in.Scan()
	ans, _ := strconv.Atoi(in.Text())
	return ans
}

func main() {
	in.Split(bufio.ScanLines)
	n := NextInt()
	for i := 0; i < n; i++ {
		in.Scan()
		x := strings.HasPrefix(in.Text(), "miao.")
		y := strings.HasSuffix(in.Text(), "lala.")
		if x && !y {
			out.WriteString("Rainbow's\n")
		} else if !x && y {
			out.WriteString("Freda's\n")
		} else {
			out.WriteString("OMG>.< I don't know!\n")
		}
	}
	out.Flush()
}

package main

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

func main() {
	var n,i,s,t,j int
	i,s,j =0,0,0
	var a,b,c string
	b="miao."
	c="lala."
	input := bufio.NewScanner(os.Stdin)
	fmt.Scan(&n)
	for  k:=0;k<=n;k++{
		input.Scan()
		a = input.Text()
		t=len(a)
		if t==0 || a==""{
			fmt.Println("OMG>.< I don't know!")
			continue
		} else {
			for k:=0;k<5;k++ {
				if a[k]==b[k] {
					s++
				}
			}
		}
		for k:=t-5;k<t;k++ {
			if a[k]==c[i] {
				j++
				i++
			}
		}
		if s==j || s!=5 && j!=5 {
			fmt.Println("OMG>.< I don't know!")
		} else if s==5 && j!=5 {
			fmt.Println("Rainbow's")
		} else {
			fmt.Println("Freda's")
		}
		i=0
		s=0
		j=0
	}
}

package main

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

func main() {
    var count int

    fmt.Fscanln(os.Stdin, &count)

    var results = make([]string, count)

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

        reader := bufio.NewReader(os.Stdin)
        text, _ := reader.ReadString('\n')
        text = strings.ReplaceAll(text, "\n", "")
        text = strings.ReplaceAll(text, "\r", "")

        const miao = "miao."
        isRainbow := text == miao || strings.HasPrefix(text, miao)
        const lala = "lala."
        isFreda := text == lala || strings.HasSuffix(text, lala)

        const s = "OMG>.< I don't know!"

        if isFreda && isRainbow {
           results[i] = s
        } else
        if isFreda {
           results[i] = "Freda's"
        } else
        if isRainbow {
           results[i] = "Rainbow's"
        } else {
           results[i] = s
        }
    }

    for _, line := range results {
       fmt.Println(line)
    }
}

package main

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

func main() {
    var count int

    fmt.Fscan(os.Stdin, &count)

    var results = make([]string, count)

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

        reader := bufio.NewReader(os.Stdin)
        text, _ := reader.ReadString('\n')
        text = strings.ReplaceAll(text, "\n", "")

        const miao = "miao."
        isRainbow := text == miao || strings.HasPrefix(text, miao)
        const lala = "lala."
        isFreda := text == lala || strings.HasSuffix(text, lala)

        const s = "OMG>.< I don't know!"

        if isFreda && isRainbow {
           results[i] = s
        } else
        if isFreda {
           results[i] = "Freda's"
        } else
        if isRainbow {
           results[i] = "Rainbow's"
        } else {
           results[i] = s
        }
    }

    for _, line := range results {
       fmt.Println(line)
    }
}

package main

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

func main() {
    var count int

    fmt.Fscan(os.Stdin, &count)

    var results = make([]string, count)

    var text string
    for i := 0; i < count; i++ {
        fmt.Fscan(os.Stdin, &text)

        const miao = "miao."
        isRainbow := text == miao || strings.HasPrefix(text, miao)
        const lala = "lala."
        isFreda := text == lala || strings.HasSuffix(text, lala)

        const s = "OMG>.< I don't know!"

        if isFreda && isRainbow {
            results[i] = s
        } else
        if isFreda {
            results[i] = "Freda's"
        } else
        if isRainbow {
            results[i] = "Rainbow's"
        } else {
            results[i] = s
        }
    }

    for _, line := range results {
        fmt.Println(line)
    }
}

package main

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

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    var n int
    fmt.Scan(&n)
    for i := 0; i < n; i++ {
        scanner.Scan()
        if len(scanner.Text()) < 5 {
            fmt.Println("OMG>.< I don't know!")
        } else {
            begin, end := scanner.Text()[:5], scanner.Text()[len(scanner.Text())-5:]
            if (begin == "miao.") && (end != "lala.") {
                fmt.Println("Rainbow's")
            } else if (begin != "miao.") && (end == "lala.") {
                fmt.Println("Freda's")
            } else {
                fmt.Println("OMG>.< I don't know!")
            }
        }
    }
}

//312A

package main

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

func NextInt() int {
	in := bufio.NewScanner(os.Stdin)
	in.Scan()
	ans, _ := strconv.Atoi(in.Text())
	return ans
}

func main() {
	in := bufio.NewScanner(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	in.Split(bufio.ScanLines)
	n := NextInt()
	for i := 0; i < n; i++ {
		in.Scan()
		miao, lala := strings.HasPrefix(in.Text(), "miao."),
			strings.HasSuffix(in.Text(), "lala.")
		if miao && !lala {
			out.WriteString("Rainbow's\n")
		} else if !miao && lala {
			out.WriteString("Freda's\n")
		} else {
			out.WriteString("OMG>.< I don't know!\n")
		}
	}
	out.Flush()
}


Appleman has a very big sheet of paper. This sheet has a form of rectangle with dimensions 1 × n. Your task is help Appleman with folding of such a sheet. Actually, you need to perform q queries. Each query will have one of the following types:  Fold the sheet of paper at position pi. After this query the leftmost part of the paper with dimensions 1 × pi must be above the rightmost part of the paper with dimensions 1 × ([current width of sheet] - pi).  Count what is the total width of the paper pieces, if we will make two described later cuts and consider only the pieces between the cuts. We will make one cut at distance li from the left border of the current sheet of paper and the other at distance ri from the left border of the current sheet of paper. Please look at the explanation of the first test example for better understanding of the problem.

The first line contains two integers: n and q (1  ≤ n ≤ 105; 1 ≤ q ≤ 105) — the width of the paper and the number of queries. Each of the following q lines contains one of the described queries in the following format:   "1 pi" (1 ≤ pi < [current width of sheet]) — the first type query.  "2 li ri" (0 ≤ li < ri ≤ [current width of sheet]) — the second type query.

For each query of the second type, output the answer.

NoteThe pictures below show the shapes of the paper during the queries of the first example:  After the first fold operation the sheet has width equal to 4, after the second one the width of the sheet equals to 2.

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var n, q int
	fmt.Fscan(reader, &n, &q)
	a := make([]int, n+10)
	for i := 0; i <= n; i++ {
		a[i] = i
	}
	var cmd int
	var is_rev int = 0
	var head, tail int = 1, n + 1 // [head, tail) is current interval.

	for i := 0; i < q; i++ {
		fmt.Fscan(reader, &cmd)
		if cmd == 1 {
			var p int
			fmt.Fscan(reader, &p)
			if p*2 > tail-head {
				is_rev ^= 1
				p = tail - head - p
			}
			if is_rev == 1 {
				for i, j := tail-2*p, 1; i < tail-p; i++ {
					a[i] += a[tail-1] - a[tail-1-j]
					j++
				}
				tail -= p
			} else {
				for i, j := head+p, 1; i < head+p*2; i++ {
					j++
					a[i] -= a[head+p-j]
				}
				a[head+p-1] = 0
				head += p
			}
		} else {
			var l, r int
			fmt.Fscan(reader, &l, &r)
			if is_rev == 0 {
				fmt.Println(a[r+head-1] - a[l+head-1])
			} else {
				fmt.Println(a[tail-1-l] - a[tail-r-1])
			}
		}
	}
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var n, q int
	fmt.Fscan(reader, &n, &q)
	a := make([]int, n+10)
	for i := 0; i <= n; i++ {
		a[i] = i
	}
	var cmd int
	var is_rev int = 0
	var head, tail int = 1, n + 1 // [head, tail) is current interval.

	for i := 0; i < q; i++ {
		fmt.Fscan(reader, &cmd)
		if cmd == 1 {
			var p int
			fmt.Fscan(reader, &p)
			if p*2 > tail-head {
				is_rev ^= 1
				p = tail - head - p
			}
			if is_rev == 1 {
				for i, j := tail-2*p, 1; i < tail-p; i++ {
					a[i] += a[tail-1] - a[tail-1-j]
					j++
				}
				for i := tail - p; i < tail; i++ {
					a[i] = 0
				}
				tail -= p
			} else {
				for i, j := head+p, 1; i < head+p*2; i++ {
					j++
					a[i] -= a[head+p-j]
					a[head+p-j] = 0
				}
				a[head+p-1] = 0
				head += p
			}
		} else {
			var l, r int
			fmt.Fscan(reader, &l, &r)
			if is_rev == 0 {
				fmt.Println(a[r+head-1] - a[l+head-1])
			} else {
				fmt.Println(a[tail-1-l] - a[tail-r-1])
			}
		}
	}
}

package main

import (
	"fmt"
)

func main() {
	var n, q int
	fmt.Scan(&n, &q)
	a := make([]int, n+10)
	for i := 0; i <= n; i++ {
		a[i] = i
	}
	var cmd int
	var is_rev int = 0
	var head, tail int = 1, n + 1 // [head, tail) is current interval.

	for i := 0; i < q; i++ {
		fmt.Scan(&cmd)
		if cmd == 1 {
			var p int
			fmt.Scan(&p)
			if p*2 > tail-head {
				is_rev ^= 1
				p = tail - head - p
			}
			if is_rev == 1 {
				fmt.Println("rev", tail-2*p, tail-p-1)
				for i, j := tail-2*p, 1; i < tail-p; i++ {
					a[i] += a[tail-1] - a[tail-1-j]
					j++
				}
				for i := tail - p; i < tail; i++ {
					a[i] = 0
				}
				tail -= p
			} else {
				for i, j := head+p, 1; i < head+p*2; i++ {
					j++
					a[i] -= a[head+p-j]
					a[head+p-j] = 0
				}
				a[head+p-1] = 0
				head += p
			}
		} else {
			var l, r int
			fmt.Scan(&l, &r)
			if is_rev == 0 {
				fmt.Println(a[r+head-1] - a[l+head-1])
			} else {
				fmt.Println(a[tail-1-l] - a[tail-r-1])
			}
		}
	}
}


Even the most successful company can go through a crisis period when you have to make a hard decision — to restructure, discard and merge departments, fire employees and do other unpleasant stuff. Let's consider the following model of a company.There are n people working for the Large Software Company. Each person belongs to some department. Initially, each person works on his own project in his own department (thus, each company initially consists of n departments, one person in each).However, harsh times have come to the company and the management had to hire a crisis manager who would rebuild the working process in order to boost efficiency. Let's use team(person) to represent a team where person person works. A crisis manager can make decisions of two types:  Merge departments team(x) and team(y) into one large department containing all the employees of team(x) and team(y), where x and y (1 ≤ x, y ≤ n) — are numbers of two of some company employees. If team(x) matches team(y), then nothing happens.  Merge departments team(x), team(x + 1), ..., team(y), where x and y (1 ≤ x ≤ y ≤ n) — the numbers of some two employees of the company. At that the crisis manager can sometimes wonder whether employees x and y (1 ≤ x, y ≤ n) work at the same department.Help the crisis manager and answer all of his queries.

The first line of the input contains two integers n and q (1 ≤ n ≤ 200 000, 1 ≤ q ≤ 500 000) — the number of the employees of the company and the number of queries the crisis manager has. Next q lines contain the queries of the crisis manager. Each query looks like type x y, where . If type = 1 or type = 2, then the query represents the decision of a crisis manager about merging departments of the first and second types respectively. If type = 3, then your task is to determine whether employees x and y work at the same department. Note that x can be equal to y in the query of any type.

For each question of type 3 print "YES" or "NO" (without the quotes), depending on whether the corresponding people work in the same department.

package main

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

// github.com/EndlessCheng/codeforces-go
func CF566D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var n, q, op, x, y int
	Fscan(in, &n, &q)
	fa := make([]int, n+1)
	next := make([]int, n+1)
	for i := range fa {
		fa[i] = i
		next[i] = i + 1
	}
	var f func(int) int
	f = func(x int) int {
		if fa[x] != x {
			fa[x] = f(fa[x])
		}
		return fa[x]
	}
	merge := func(from, to int) { fa[f(from)] = f(to) }
	for ; q > 0; q-- {
		Fscan(in, &op, &x, &y)
		if op == 1 {
			merge(x, y)
		} else if op == 2 {
			for i := x + 1; i <= y; {
				merge(i-1, i)
				i, next[i] = next[i], next[y]
			}
		} else if f(x) == f(y) {
			Fprintln(out, "YES")
		} else {
			Fprintln(out, "NO")
		}
	}
}

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

package main

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

var scanner = bufio.NewScanner(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)
//defer writer.Flush()

const (
	//MaxScanTokenSize = 64 * 1024 // package default
	MaxScanTokenSize = 8 * 1024 * 1024 // 8M
)

func init() {
	scanner.Buffer(make([]byte, 0, MaxScanTokenSize), MaxScanTokenSize)
	scanner.Split(bufio.ScanWords)
}

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

func readInt() int {
	val, _ := strconv.Atoi(readString())
	return val
}

func readInt64() int64 {
	v, _ := strconv.ParseInt(readString(), 10, 64)
	return v
}

func readIntArray(size int) []int {
	a := make([]int, size)
	for i := 0; i < size; i++ {
		a[i] = readInt()
	}
	return a
}

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

func readFloat64() float64 {
	v, _ := strconv.ParseFloat(readString(), 64)
	return v
}

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

type UnionFindSet struct {
	N int
	Parent []int
}

func NewUnionFindSet(n int) *UnionFindSet {
	ufs := &UnionFindSet{
		N: n,
		Parent: make([]int, n, n),
	}
	for i := range ufs.Parent {
		ufs.Parent[i] = i;
	}
	return ufs
}

func (ufs *UnionFindSet) find(x int) int {
	parent := &ufs.Parent[x]
	if *parent != x {
		*parent = ufs.find(*parent)
	}
	return *parent
}

func (ufs *UnionFindSet) union(x, y int) {
	ufs.Parent[ufs.find(x)] = ufs.find(y)
}

func (ufs *UnionFindSet) show() {
	return
	for i, p := range ufs.Parent {
		fmt.Fprintf(writer, "[%2d]%2d ", i, p)
	}
	fmt.Fprintln(writer)
}

func main() {
	defer writer.Flush()

	n, q := readInt(), readInt()
	ufs := NewUnionFindSet(n + 1)
	next := make([]int, n + 1, n + 1)
	for i := range next {
		next[i] = i + 1
	}
	ufs.show()
	for i := 0; i < q; i++ {
		c, x, y := readInt(), readInt(), readInt()
		//fmt.Fprintf(writer, "c = %d, x = %d, y = %d\n", c, x, y)
		switch c {
		case 1:
			ufs.union(x, y)

			ufs.show()
		case 2:
			if x > y {
				x, y = y, x
			}
			for j := x; j < y; {
				nxt := next[j]
				if y > next[j] {
					next[j] = y
				}
				ufs.union(j, nxt)
				j = nxt
			}

			ufs.show()
		case 3:
			ans := "YES"
			if ufs.find(x) != ufs.find(y) {
				ans = "NO"
			}
			fmt.Fprintln(writer, ans)

			ufs.show()
		}
	}

}


Nezzar has a binary string $$$s$$$ of length $$$n$$$ that he wants to share with his best friend, Nanako. Nanako will spend $$$q$$$ days inspecting the binary string. At the same time, Nezzar wants to change the string $$$s$$$ into string $$$f$$$ during these $$$q$$$ days, because it looks better.It is known that Nanako loves consistency so much. On the $$$i$$$-th day, Nanako will inspect a segment of string $$$s$$$ from position $$$l_i$$$ to position $$$r_i$$$ inclusive. If the segment contains both characters '0' and '1', Nanako becomes unhappy and throws away the string.After this inspection, at the $$$i$$$-th night, Nezzar can secretly change strictly less than half of the characters in the segment from $$$l_i$$$ to $$$r_i$$$ inclusive, otherwise the change will be too obvious.Now Nezzar wonders, if it is possible to avoid Nanako being unhappy and at the same time have the string become equal to the string $$$f$$$ at the end of these $$$q$$$ days and nights.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of test cases. The first line of each test case contains two integers $$$n,q$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le q \le 2 \cdot 10^5$$$). The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$. The third line of each test case contains a binary string $$$f$$$ of length $$$n$$$. Then $$$q$$$ lines follow, $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le n$$$)  — bounds of the segment, that Nanako will inspect on the $$$i$$$-th day. It is guaranteed that the sum of $$$n$$$ for all test cases doesn't exceed $$$2 \cdot 10^5$$$, and the sum of $$$q$$$ for all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print "YES" on the single line if it is possible to avoid Nanako being unhappy and have the string $$$f$$$ at the end of $$$q$$$ days and nights. Otherwise, print "NO". You can print each letter in any case (upper or lower).

NoteIn the first test case, $$$\underline{00000} \rightarrow \underline{000}11 \rightarrow 00111$$$ is one of the possible sequences of string changes.In the second test case, it can be shown that it is impossible to have the string $$$f$$$ at the end.

package main

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

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

	tc := readNum(reader)

	var buf bytes.Buffer

	for tc > 0 {
		tc--
		n, m := readTwoNums(reader)
		s, _ := reader.ReadString('\n')
		f, _ := reader.ReadString('\n')
		L, R := make([]int, m), make([]int, m)
		for i := 0; i < m; i++ {
			L[i], R[i] = readTwoNums(reader)
		}
		res := solve(n, s, f, L, R)
		if res {
			buf.WriteString("YES\n")
		} else {
			buf.WriteString("NO\n")
		}
	}
	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 solve(n int, s, f string, L, R []int) bool {
	arr := make([]int, n)
	for i := 0; i < n; i++ {
		arr[i] = int(f[i] - '0')
	}
	tree := NewSegTree(n, arr)

	for i := len(L) - 1; i >= 0; i-- {
		l, r := L[i], R[i]
		cnt := tree.Query(l-1, r-1)
		ll := r - l + 1
		if cnt*2 == ll {
			// half 0/1
			return false
		}
		if cnt*2 < ll {
			// before should be all zeros in range [l, r], some changed to 1
			tree.Update(l-1, r-1, 0)
		} else {
			tree.Update(l-1, r-1, 1)
		}
	}
	for i := 0; i < n; i++ {
		x := tree.Query(i, i)
		if x != int(s[i]-'0') {
			return false
		}
	}
	return true
}

type SegTree struct {
	lazy []int
	sum  []int
	n    int
}

func NewSegTree(n int, arr []int) *SegTree {
	m := 1
	for m < n {
		m <<= 1
	}
	lazy := make([]int, m<<1)
	sum := make([]int, m<<1)

	var build func(i int, l, r int)
	build = func(i int, l, r int) {
		if l == r {
			sum[i] = arr[l]
			return
		}
		mid := (l + r) >> 1
		build(i<<1, l, mid)
		build((i<<1)|1, mid+1, r)
		sum[i] = sum[i<<1] + sum[(i<<1)|1]
	}

	build(1, 0, n-1)

	return &SegTree{lazy, sum, n}
}

func (tree *SegTree) push(i int, l, r int) {
	if tree.lazy[i] != 0 {
		if tree.lazy[i] == 1 {
			// all change to 1
			tree.sum[i] = r - l + 1
		} else {
			// all change to 0
			tree.sum[i] = 0
		}
		if l < r {
			tree.lazy[i<<1] = tree.lazy[i]
			tree.lazy[(i<<1)|1] = tree.lazy[i]
		}
		tree.lazy[i] = 0
	}

}

// set all values between l, r to v
func (tree *SegTree) Update(l, r int, v int) {
	var loop func(i int, ll, rr int)
	loop = func(i int, ll, rr int) {
		tree.push(i, ll, rr)
		if r < ll || rr < l {
			return
		}
		if l <= ll && rr <= r {
			if v == 1 {
				tree.sum[i] = rr - ll + 1
				if ll < rr {
					tree.lazy[i<<1] = 1
					tree.lazy[(i<<1)|1] = 1
				}
			} else {
				tree.sum[i] = 0
				if ll < rr {
					tree.lazy[i<<1] = -1
					tree.lazy[(i<<1)|1] = -1
				}
			}
			return
		}
		mid := (ll + rr) >> 1
		loop(i<<1, ll, mid)
		loop((i<<1)|1, mid+1, rr)
		tree.sum[i] = tree.sum[i<<1] + tree.sum[(i<<1)|1]
	}

	loop(1, 0, tree.n-1)
}

func (tree *SegTree) Query(l, r int) int {
	var loop func(i int, ll, rr int) int

	loop = func(i int, ll, rr int) int {
		tree.push(i, ll, rr)
		if rr < l || r < ll {
			return 0
		}
		if l <= ll && rr <= r {
			return tree.sum[i]
		}
		mid := (ll + rr) >> 1
		a := loop(i<<1, ll, mid)
		b := loop((i<<1)|1, mid+1, rr)
		return a + b
	}
	return loop(1, 0, tree.n-1)
}

package main

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

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

	tc := readNum(reader)

	var buf bytes.Buffer

	for tc > 0 {
		tc--
		n, m := readTwoNums(reader)
		s, _ := reader.ReadString('\n')
		f, _ := reader.ReadString('\n')
		L, R := make([]int, m), make([]int, m)
		for i := 0; i < m; i++ {
			L[i], R[i] = readTwoNums(reader)
		}
		res := solve(n, s, f, L, R)
		if res {
			buf.WriteString("YES\n")
		} else {
			buf.WriteString("NO\n")
		}
	}
	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 solve(n int, s, f string, L, R []int) bool {
	arr := make([]int, n)
	for i := 0; i < n; i++ {
		arr[i] = int(f[i] - '0')
	}
	tree := NewSegTree(n, arr)

	for i := len(L) - 1; i >= 0; i-- {
		l, r := L[i], R[i]
		cnt := tree.Query(l-1, r-1)
		ll := r - l + 1
		if cnt*2 == ll {
			// half 0/1
			return false
		}
		if cnt*2 < ll {
			// before should be all zeros in range [l, r], some changed to 1
			tree.Update(l-1, r-1, 0)
		} else {
			tree.Update(l-1, r-1, 1)
		}
	}
	for i := 0; i < n; i++ {
		x := tree.Query(i, i)
		if x != int(s[i]-'0') {
			return false
		}
	}
	return true
}

type SegTree struct {
	lazy []int
	sum  []int
	n    int
}

func NewSegTree(n int, arr []int) *SegTree {
	m := 1
	for m < n {
		m <<= 1
	}
	lazy := make([]int, m<<1)
	sum := make([]int, m<<1)

	var build func(i int, l, r int)
	build = func(i int, l, r int) {
		if l == r {
			sum[i] = arr[l]
			return
		}
		mid := (l + r) >> 1
		build(i<<1, l, mid)
		build((i<<1)|1, mid+1, r)
		sum[i] = sum[i<<1] + sum[(i<<1)|1]
	}

	build(1, 0, n-1)

	return &SegTree{lazy, sum, n}
}

func (tree *SegTree) push(i int, l, r int) {
	if tree.lazy[i] != 0 {
		if tree.lazy[i] == 1 {
			// all change to 1
			tree.sum[i] = r - l + 1
		} else {
			// all change to 0
			tree.sum[i] = 0
		}
		if l < r {
			tree.lazy[i<<1] = tree.lazy[i]
			tree.lazy[(i<<1)|1] = tree.lazy[i]
		}
		tree.lazy[i] = 0
	}

}

// set all values between l, r to v
func (tree *SegTree) Update(l, r int, v int) {
	var loop func(i int, ll, rr int)
	loop = func(i int, ll, rr int) {
		if r < ll || rr < l {
			return
		}
		tree.push(i, ll, rr)
		if l <= ll && rr <= r {
			if v == 1 {
				tree.sum[i] = rr - ll + 1
				if ll < rr {
					tree.lazy[i<<1] = 1
					tree.lazy[(i<<1)|1] = 1
				}
			} else {
				tree.sum[i] = 0
				if ll < rr {
					tree.lazy[i<<1] = -1
					tree.lazy[(i<<1)|1] = -1
				}
			}
			return
		}
		mid := (ll + rr) >> 1
		loop(i<<1, ll, mid)
		loop((i<<1)|1, mid+1, rr)
		tree.sum[i] = tree.sum[i<<1] + tree.sum[(i<<1)|1]
	}

	loop(1, 0, tree.n-1)
}

func (tree *SegTree) Query(l, r int) int {
	var loop func(i int, ll, rr int) int

	loop = func(i int, ll, rr int) int {
		if rr < l || r < ll {
			return 0
		}
		tree.push(i, ll, rr)
		if l <= ll && rr <= r {
			return tree.sum[i]
		}
		mid := (ll + rr) >> 1
		a := loop(i<<1, ll, mid)
		b := loop((i<<1)|1, mid+1, rr)
		return a + b
	}
	return loop(1, 0, tree.n-1)
}