Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$.  For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \leq x \leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty.

The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n \leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \ldots, ca_n$$$ ($$$1 \leq ca_i \leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \ldots, cb_n$$$ ($$$1 \leq cb_i \leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^{5}$$$.

For each test case, print a single integer — the highest possible beauty.

NoteAn optimal solution for the first test case is shown in the following figure:  The beauty is $$$\left|4-3 \right|+\left|3-5 \right|+\left|2-4 \right|+\left|5-2 \right|+\left|1-6 \right|+\left|6-1 \right|=18$$$.An optimal solution for the second test case is shown in the following figure:  The beauty is $$$\left|2-2 \right|+\left|1-6 \right|+\left|3-3 \right|+\left|6-1 \right|+\left|4-4 \right|+\left|5-5 \right|=10$$$.

package main

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

func solve(in io.Reader, out io.Writer) {
	var n int
	Fscan(in, &n)
	a := make([]int, n)
	b := map[int]int{}
	vis := make([]bool, n)

	for i := range a {
		Fscan(in, &a[i])
		a[i]--
	}
	for i := 0; i < n; i++ {
		var x int
		Fscan(in, &x)
		b[x-1] = i
	}
	cnt := 0
	for i := range a {
		if vis[i] {
			continue
		}
		vis[i] = true
		k := 1
		cur := a[i]
		for b[cur] != i {
			vis[b[cur]] = true
			cur = a[b[cur]]
			k++
		}
		cnt += k / 2
	}

	Fprintln(out, int64(n-cnt)*int64(cnt)*2)

}

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var T int
	for Fscan(in, &T); T > 0; T-- {
		solve(in, out)
	}
}

package main

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

const eof = 0

type any = interface{}

type MyIO struct {
	in  *os.File
	out *bufio.Writer
	_i  int
	_n  int
	buf []byte
}

func NewIO(in *os.File, out *os.File) *MyIO {
	return &MyIO{
		in,
		bufio.NewWriter(out),
		0, 0, make([]byte, 1<<12),
	}
}

func (myio *MyIO) rc() byte {
	if myio._i == myio._n {
		myio._n, _ = myio.in.Read(myio.buf)
		if myio._n == 0 { // EOF
			return eof
		}
		myio._i = 0
	}
	b := myio.buf[myio._i]
	myio._i++
	return b
}

func (myio *MyIO) ReadInt() (x int) {
	rc := myio.rc
	b := rc()
	neg := false

	for ; '0' > b || b > '9'; b = rc() {
		if b == eof {
			return
		}
		if b == '-' {
			neg = true
		}
	}
	for ; '0' <= b && b <= '9'; b = rc() {
		x = x*10 + int(b&15)
	}
	if neg {
		return -x
	}
	return x
}

func (myio *MyIO) ReadBytes() (s []byte) {
	rc := myio.rc
	b := rc()
	for ; b <= ' '; b = rc() {
	}
	for ; b > ' '; b = rc() {
		s = append(s, b)
	}
	return
}

func (myio *MyIO) ReadStr() (s string) {
	return string(myio.ReadBytes())
}

func (myio *MyIO) Flush() {
	myio.out.Flush()
}

func (myio *MyIO) Printf(format string, a ...any) (n int, err error) {
	return fmt.Fprintf(myio.out, format, a...)
}

func (myio *MyIO) Println(a ...any) (n int, err error) {
	return fmt.Fprintln(myio.out, a...)
}

func (myio *MyIO) Print(a ...any) (n int, err error) {
	return fmt.Fprint(myio.out, a...)
}

func main() {
	myio := NewIO(os.Stdin, os.Stdout)
	defer myio.Flush()

	t := myio.ReadInt()
	sol := func() {
		n := myio.ReadInt()
		p := make([]int, n)
		v := make([]int, n)
		vis := make([]bool, n)
		for i := 0; i < n; i++ {
			t := myio.ReadInt() - 1
			p[i] = t
		}
		for i := 0; i < n; i++ {
			t := myio.ReadInt() - 1
			v[p[i]] = t
		}
		color := 0
		var sum int64 = 0
		for i := 0; i < n; i++ {
			if vis[i] {
				continue
			}
			c := 1
			for t := v[i]; !vis[t]; t = v[t] {
				vis[t] = true
				c++
			}
			sum += calcSum(color, c/2, n)
			color += c / 2
		}
		myio.Println(sum)
	}
	for ; t > 0; t-- {
		sol()
	}
}

func calcSum(color, c, n int) (sum int64) {
	for i := 0; i < c; i++ {
		sum += (int64)(n - 1 - color - i - color - i)
		sum += (int64)(n - 1 - color - i - (color + (i+1)%c))
	}
	return
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)
var wrtr = bufio.NewWriterSize(os.Stdout, 10_000_000)
var rdr = bufio.NewScanner(os.Stdin)
func gs() string  { rdr.Scan(); return rdr.Text() }
func gi() int     { i,e := strconv.Atoi(gs()); if e != nil {panic(e)}; return i }
func gis(n int) []int  { res := make([]int,n); for i:=0;i<n;i++ { res[i] = gi() }; return res }
func abs(a int) int { if a < 0 { return -a }; return a }
func main() {
	//f1, _ := os.Create("cpu.prof"); pprof.StartCPUProfile(f1); defer pprof.StopCPUProfile()
	defer wrtr.Flush()
	infn := ""; if infn == "" && len(os.Args) > 1 {	infn = os.Args[1] }
	if infn != "" {	f, e := os.Open(infn); if e != nil { panic(e) }; rdr = bufio.NewScanner(f) }
	rdr.Split(bufio.ScanWords); rdr.Buffer(make([]byte,1024),1_000_000_000)
	// PROGRAM STARTS HERE
	T := gi()
	for tt:=1;tt<=T;tt++ {
		N := gi()
		CA := gis(N); CB := gis(N); for i:=0;i<N;i++ { CA[i]--; CB[i]-- }
		CAinv := make([]int,N); for i,c := range CA { CAinv[c] = i }
		perms := make([][]int,0)
		sb := make([]bool,N)
		for i:=0;i<N;i++ {
			v := CA[i]; if sb[v] { continue }
			p := []int{v}; idx := i; sb[v] = true;
			for CB[idx] != v { p = append(p,CB[idx]); sb[CB[idx]] = true; idx = CAinv[CB[idx]] }
			perms = append(perms,p)
		}
		permlt := func (a,b []int) bool {
			if len(a)%2 != len(b)%2 {
				if len(a)%2 == 0 { return true } else { return false }
			}
			return len(a) > len(b)
		}
		sort.Slice(perms,func(i,j int) bool { return permlt(perms[i],perms[j]) } )
		cc := make([]int,N); order := make([]int,0,N)
		top,bot := N-1,0; for top >= bot { order = append(order,top); top--; if top>=bot { order = append(order,bot); bot++ } }
		curs := 0
		for _,p := range perms {
			lp := len(p)
			if lp % 2 == 0 {
				for _,x := range p { cc[x] = order[curs]; curs++ }
			} else {
				for i:=0;i<lp-1;i++ { x := p[i]; cc[x] = order[curs]; curs++ }
			}
		}
		for _,p := range perms {
			lp := len(p)
			if lp % 2 == 1 { x := p[lp-1]; cc[x] = order[curs]; curs++ }
		}
		ans := int64(0);
		for i:=0;i<N;i++ { ans += int64(abs(cc[CA[i]]-cc[CB[i]])) }
		fmt.Fprintln(wrtr,ans)
	}
}

package main

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

func solve(in io.Reader, out io.Writer) {
	var n int
	Fscan(in, &n)
	a := make([]int, n)
	b := map[int]int{}
	vis := make([]bool, n)

	for i := range a {
		Fscan(in, &a[i])
		a[i]--
	}
	for i := 0; i < n; i++ {
		var x int
		Fscan(in, &x)
		b[x-1] = i
	}
	cnt := 0
	for i := range a {
		if vis[i] {
			continue
		}
		vis[i] = true
		k := 1
		cur := a[i]
		for b[cur] != i {
			vis[b[cur]] = true
			cur = a[b[cur]]
			k++
		}
		cnt += k / 2
	}

	Fprintln(out, (n-cnt)*cnt*2)

}

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var T int
	for Fscan(in, &T); T > 0; T-- {
		solve(in, out)
	}
}

package main

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

const eof = 0

type any = interface{}

type MyIO struct {
	in  *os.File
	out *bufio.Writer
	_i  int
	_n  int
	buf []byte
}

func NewIO(in *os.File, out *os.File) *MyIO {
	return &MyIO{
		in,
		bufio.NewWriter(out),
		0, 0, make([]byte, 1<<12),
	}
}

func (myio *MyIO) rc() byte {
	if myio._i == myio._n {
		myio._n, _ = myio.in.Read(myio.buf)
		if myio._n == 0 { // EOF
			return eof
		}
		myio._i = 0
	}
	b := myio.buf[myio._i]
	myio._i++
	return b
}

func (myio *MyIO) ReadInt() (x int) {
	rc := myio.rc
	b := rc()
	neg := false

	for ; '0' > b || b > '9'; b = rc() {
		if b == eof {
			return
		}
		if b == '-' {
			neg = true
		}
	}
	for ; '0' <= b && b <= '9'; b = rc() {
		x = x*10 + int(b&15)
	}
	if neg {
		return -x
	}
	return x
}

func (myio *MyIO) ReadBytes() (s []byte) {
	rc := myio.rc
	b := rc()
	for ; b <= ' '; b = rc() {
	}
	for ; b > ' '; b = rc() {
		s = append(s, b)
	}
	return
}

func (myio *MyIO) ReadStr() (s string) {
	return string(myio.ReadBytes())
}

func (myio *MyIO) Flush() {
	myio.out.Flush()
}

func (myio *MyIO) Printf(format string, a ...any) (n int, err error) {
	return fmt.Fprintf(myio.out, format, a...)
}

func (myio *MyIO) Println(a ...any) (n int, err error) {
	return fmt.Fprintln(myio.out, a...)
}

func (myio *MyIO) Print(a ...any) (n int, err error) {
	return fmt.Fprint(myio.out, a...)
}

func main() {
	myio := NewIO(os.Stdin, os.Stdout)
	defer myio.Flush()

	t := myio.ReadInt()
	sol := func() {
		n := myio.ReadInt()
		p := make([]int, n)
		v := make([]int, n)
		vis := make([]bool, n)
		for i := 0; i < n; i++ {
			t := myio.ReadInt() - 1
			p[i] = t
		}
		for i := 0; i < n; i++ {
			t := myio.ReadInt() - 1
			v[p[i]] = t
		}
		color := 0
		sum := 0
		for i := 0; i < n; i++ {
			if vis[i] {
				continue
			}
			c := 1
			for t := v[i]; !vis[t]; t = v[t] {
				vis[t] = true
				c++
			}
			sum += calcSum(color, c/2, n)
			color += c / 2
		}
		myio.Println(sum)
	}
	for ; t > 0; t-- {
		sol()
	}
}

func calcSum(color, c, n int) (sum int) {
	for i := 0; i < c; i++ {
		sum += (n - 1 - color - i - color - i)
		sum += (n - 1 - color - i - (color + (i+1)%c))
	}
	return
}


Bankopolis is an incredible city in which all the n crossroads are located on a straight line and numbered from 1 to n along it. On each crossroad there is a bank office.The crossroads are connected with m oriented bicycle lanes (the i-th lane goes from crossroad ui to crossroad vi), the difficulty of each of the lanes is known.Oleg the bank client wants to gift happiness and joy to the bank employees. He wants to visit exactly k offices, in each of them he wants to gift presents to the employees.The problem is that Oleg don't want to see the reaction on his gifts, so he can't use a bicycle lane which passes near the office in which he has already presented his gifts (formally, the i-th lane passes near the office on the x-th crossroad if and only if min(ui, vi) < x < max(ui, vi))). Of course, in each of the offices Oleg can present gifts exactly once. Oleg is going to use exactly k - 1 bicycle lane to move between offices. Oleg can start his path from any office and finish it in any office.Oleg wants to choose such a path among possible ones that the total difficulty of the lanes he will use is minimum possible. Find this minimum possible total difficulty.

The first line contains two integers n and k (1 ≤ n, k ≤ 80) — the number of crossroads (and offices) and the number of offices Oleg wants to visit. The second line contains single integer m (0 ≤ m ≤ 2000) — the number of bicycle lanes in Bankopolis. The next m lines contain information about the lanes. The i-th of these lines contains three integers ui, vi and ci (1 ≤ ui, vi ≤ n, 1 ≤ ci ≤ 1000), denoting the crossroads connected by the i-th road and its difficulty.

In the only line print the minimum possible total difficulty of the lanes in a valid path, or -1 if there are no valid paths.

NoteIn the first example Oleg visiting banks by path 1 → 6 → 2 → 4.Path 1 → 6 → 2 → 7 with smaller difficulity is incorrect because crossroad 2 → 7 passes near already visited office on the crossroad 6.In the second example Oleg can visit banks by path 4 → 1 → 3.

package main

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

var in = bufio.NewScanner(os.Stdin)

func readInt() int {
	if !in.Scan() {
		panic(in.Err())
	}
	res := 0
	for _, b := range in.Bytes() {
		res = res*10 + int(b-'0')
	}
	return res
}

const inf int = 1e9

type lane struct {
	to, d int
}

var lanes [][]lane

var mem [80][80][80][80]int

func difficulty(bank, mi, ma, left int) (res int) {
	if left == 0 {
		return 0
	}
	res = mem[bank][mi][ma][left]
	if res > 0 {
		return res
	}
	defer func() { mem[bank][mi][ma][left] = res }()
	res = inf
	for _, l := range lanes[bank] {
		if l.to >= mi && l.to <= ma {
			nmi := mi
			nma := ma
			if l.to > bank {
				nmi = bank + 1
			} else {
				nma = bank - 1
			}
			if x := l.d + difficulty(l.to, nmi, nma, left-1); res > x {
				res = x
			}
		}
	}
	return res
}

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

	n := readInt()
	k := readInt()
	m := readInt()
	lanes = make([][]lane, n)
	for i := 0; i < m; i++ {
		u := readInt() - 1
		lanes[u] = append(lanes[u], lane{readInt() - 1, readInt()})
	}
	ans := inf
	for i := range lanes {
		if x := difficulty(i, 0, n-1, k-1); ans > x {
			ans = x
		}
	}
	if ans == inf {
		fmt.Println(-1)
	} else {
		fmt.Println(ans)
	}
}


After a long party Petya decided to return home, but he turned out to be at the opposite end of the town from his home. There are $$$n$$$ crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string $$$s$$$ of length $$$n$$$, where $$$s_i = \texttt{A}$$$, if there is a bus station at $$$i$$$-th crossroad, and $$$s_i = \texttt{B}$$$, if there is a tram station at $$$i$$$-th crossroad. Currently Petya is at the first crossroad (which corresponds to $$$s_1$$$) and his goal is to get to the last crossroad (which corresponds to $$$s_n$$$).If for two crossroads $$$i$$$ and $$$j$$$ for all crossroads $$$i, i+1, \ldots, j-1$$$ there is a bus station, one can pay $$$a$$$ roubles for the bus ticket, and go from $$$i$$$-th crossroad to the $$$j$$$-th crossroad by the bus (it is not necessary to have a bus station at the $$$j$$$-th crossroad). Formally, paying $$$a$$$ roubles Petya can go from $$$i$$$ to $$$j$$$ if $$$s_t = \texttt{A}$$$ for all $$$i \le t < j$$$. If for two crossroads $$$i$$$ and $$$j$$$ for all crossroads $$$i, i+1, \ldots, j-1$$$ there is a tram station, one can pay $$$b$$$ roubles for the tram ticket, and go from $$$i$$$-th crossroad to the $$$j$$$-th crossroad by the tram (it is not necessary to have a tram station at the $$$j$$$-th crossroad). Formally, paying $$$b$$$ roubles Petya can go from $$$i$$$ to $$$j$$$ if $$$s_t = \texttt{B}$$$ for all $$$i \le t < j$$$.For example, if $$$s$$$="AABBBAB", $$$a=4$$$ and $$$b=3$$$ then Petya needs:  buy one bus ticket to get from $$$1$$$ to $$$3$$$,  buy one tram ticket to get from $$$3$$$ to $$$6$$$,  buy one bus ticket to get from $$$6$$$ to $$$7$$$. Thus, in total he needs to spend $$$4+3+4=11$$$ roubles. Please note that the type of the stop at the last crossroad (i.e. the character $$$s_n$$$) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the $$$n$$$-th crossroad. After the party he has left with $$$p$$$ roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad $$$i$$$ to go on foot the first, so he has enough money to get from the $$$i$$$-th crossroad to the $$$n$$$-th, using only tram and bus tickets.

Each test contains one or more test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The first line of each test case consists of three integers $$$a, b, p$$$ ($$$1 \le a, b, p \le 10^5$$$) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has. The second line of each test case consists of one string $$$s$$$, where $$$s_i = \texttt{A}$$$, if there is a bus station at $$$i$$$-th crossroad, and $$$s_i = \texttt{B}$$$, if there is a tram station at $$$i$$$-th crossroad ($$$2 \le |s| \le 10^5$$$). It is guaranteed, that the sum of the length of strings $$$s$$$ by all test cases in one test doesn't exceed $$$10^5$$$.

For each test case print one number — the minimal index $$$i$$$ of a crossroad Petya should go on foot. The rest of the path (i.e. from $$$i$$$ to $$$n$$$ he should use public transport).

5
2 2 1
BB
1 1 1
AB
3 2 8
AABBBBAABB
5 3 4
BBBBB
2 1 1
ABABAB

package main

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

func main() {
	var cases int
	fmt.Scanf("%d\n", &cases)
	reader := bufio.NewReader(os.Stdin)
	for i := 0; i < cases; i++ {
		// var a, b, p int
		// fmt.Scanf("%d %d %d", &a, &b, &p)
		ns := readLine(reader)
		arrs := strings.Split(string(ns), " ")
		a, _ := strconv.Atoi(arrs[0])
		b, _ := strconv.Atoi(arrs[1])
		p, _ := strconv.Atoi(arrs[2])
		s := readLine(reader)
		// fmt.Println(a,b,p,s)
		current := s[len(s)-2] // for last doesn't matter
		cost := a
		if current == 'B' {
			cost = b
		}
		if cost > p {
			fmt.Println(len(s))
			continue
		}
		j := len(s) - 3
		for ; j >= 0; j-- {
			if s[j] == current {
				continue
			}
			if s[j] == 'A' {
				cost += a
			} else {
				cost += b
			}
			current = s[j]
			if cost > p {
				break
			}
		}
		if cost > p {
			fmt.Println(j+2)
		} else {
			fmt.Println(1)
		}
	}
}

func readLine(reader *bufio.Reader) []byte {
	result := make([]byte, 0)
	for {
		s, isPrefix, err := reader.ReadLine()
		if err != nil {
			fmt.Printf("error=%+v\n", err)
			break
		}
		result = append(result, s...)
		if !isPrefix {
			// fmt.Println(string(result))
			break
		}
	}
	return result
}

/*
URL:
https://codeforces.com/problemset/problem/1315/B
*/

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 (
	t       int
	a, b, p int
	S       []rune
)

func main() {
	t = ReadInt()

	for i := 0; i < t; i++ {
		a, b, p = ReadInt3()
		S = ReadRuneSlice()

		solve()
	}
}

func solve() {
	comp, cnts := RunLengthEncoding(S)

	num := 0
	for i := len(cnts) - 1; i >= 0; i-- {
		if i == len(cnts)-1 && cnts[i] == 1 {
			num++
			continue
		}

		val := 0
		if comp[i] == 'A' {
			val = a
		} else {
			val = b
		}

		if p-val >= 0 {
			p -= val
			num += cnts[i]
		} else {
			break
		}
	}

	if num > 0 {
		fmt.Println(len(S) - num + 1)
	} else {
		fmt.Println(len(S))
	}
}

// RunLengthEncoding returns encoded slice of an input.
func RunLengthEncoding(S []rune) ([]rune, []int) {
	runes := []rune{}
	lengths := []int{}

	l := 0
	for i := 0; i < len(S); i++ {
		// 1文字目の場合保持
		if i == 0 {
			l = 1
			continue
		}

		if S[i-1] == S[i] {
			// 直前の文字と一致していればインクリメント
			l++
		} else {
			// 不一致のタイミングで追加し、長さをリセットする
			runes = append(runes, S[i-1])
			lengths = append(lengths, l)
			l = 1
		}
	}
	runes = append(runes, S[len(S)-1])
	lengths = append(lengths, l)

	return runes, lengths
}

// RunLengthDecoding decodes RLE results.
func RunLengthDecoding(S []rune, L []int) []rune {
	if len(S) != len(L) {
		panic("S, L are not RunLengthEncoding results")
	}

	res := []rune{}

	for i := 0; i < len(S); i++ {
		for j := 0; j < L[i]; j++ {
			res = append(res, S[i])
		}
	}

	return res
}

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

/*********** 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 "fmt"
import "os"
import "bufio"
import "strings"
import "strconv"

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    capacity := 5000 * 1024
    scanner.Buffer(make([]byte, capacity), capacity)
    scanner.Scan()
    line := scanner.Text()
    t, _ := strconv.ParseInt(line, 10, 64)
    for i := int64(0); i < t; i++ {
        scanner.Scan()
        line = scanner.Text()
        parts := strings.Split(line, " ")
        a, _ := strconv.ParseInt(parts[0], 10, 64)
        b, _ := strconv.ParseInt(parts[1], 10, 64)
        r, _ := strconv.ParseInt(parts[2], 10, 64)
        scanner.Scan()
        s := scanner.Text()

        //~ fmt.Println(a, b, r, s)
        costs := make([]int64, len(s))

        costs[len(s) - 1] = 0
        if s[len(s) - 2] == 'A' {
            costs[len(s) - 2] = a
        } else {
            costs[len(s) - 2] = b
        }

        for i := int64(len(s) - 3); i >= 0; i-- {
            if s[i] == s[i + 1] {
                costs[i] = costs[i + 1]
            } else if s[i] == 'A' {
                costs[i] = costs[i + 1] + a
            } else {
                costs[i] = costs[i + 1] + b
            }
        }

        //~ fmt.Println(costs)

        min_i := 0
        for costs[min_i] > r {
            min_i++
        }

        fmt.Println(min_i + 1)
    }
}

package main

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

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

	var tc int
	fmt.Fscanf(r, "%d\n", &tc)

	for t := 0; t < tc; t++ {
		var a, b, p int
		var s string
		fmt.Fscanf(r, "%d %d %d\n%s\n", &a, &b, &p, &s)
		fmt.Fprintf(w, "%d\n", findClosest(a, b, p, s))
	}
}

func findClosest(a, b, p int, s string) int {
	n := len(s)
	dp := make([]int64, n)

	dp[n-1] = 0
	for i := n - 2; i >= 0; {
		j := i
		for j >= 0 && s[j] == s[i] {
			dp[j] = dp[i+1]
			if s[j] == 'A' {
				dp[j] += int64(a)
			} else {
				dp[j] += int64(b)
			}
			j--
		}
		i = j
	}

	for i := 0; i < n; i++ {
		if dp[i] <= int64(p) {
			return i + 1
		}
	}

	return n
}

package main

import "fmt"

func solve(a, b, p int64, s string) int {
	n := len(s)
	dp := make([]int64, n)
	dp[n-1] = 0
	if s[n-2] == 'A' {
		dp[n-2] = a
	} else {
		dp[n-2] = b
	}
	for i := n - 3; i >= 0; i-- {
		if s[i] == s[i+1] {
			dp[i] = dp[i+1]
		} else if s[i] == 'A' {
			dp[i] = dp[i+1] + a
		} else {
			dp[i] = dp[i+1] + b
		}
	}
	for i := 0; i < n; i++ {
		if dp[i] <= int64(p) {
			return i + 1
		}
	}
	return n
}

func main() {
	var t int
	fmt.Scan(&t)
	for tc := 0; tc < t; tc++ {
		var a, b, p int64
		var s string
		fmt.Scan(&a, &b, &p, &s)
		rls := solve(a, b, p, s)
		fmt.Println(rls)
	}
}

package main

import "fmt"

func solve(a, b, p int, s string) int {
	n := len(s)
	dp := make([]int64, n)
	for i := n - 2; i >= 0; {
		j := i
		for j >= 0 && s[j] == s[i] {
			dp[j] = dp[i+1]
			if s[j] == 'A' {
				dp[j] += int64(a)
			} else {
				dp[j] += int64(b)
			}
			j -= 1
		}
		i = j
	}
	for i := 0; i < n; i++ {
		if dp[i] <= int64(p) {
			return i + 1
		}
	}
	return n
}

func main() {
	var t int
	fmt.Scan(&t)
	for tc := 0; tc < t; tc++ {
		var a, b, p int
		var s string
		fmt.Scan(&a, &b, &p, &s)
		rls := solve(a, b, p, s)
		fmt.Println(rls)
	}
}

package main

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

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

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

func main() {
	defer out.Flush()
	inn.Split(bufio.ScanWords)
	var tt int
	Fscan(in, &tt)
	for ; tt > 0; tt-- {
		// a, b, p := rd(), rd(), rd()
		var a, b, p int
		var st string
		Fscan(in, &a, &b, &p, &st)
		tot, ans := 0, 1
		for i, j := len(st)-2, len(st)-2; i >= 0; i = j {
			for j >= 0 && st[i] == st[j] {
				j--
			}
			if st[i] == 'A' {
				tot += a
			} else {
				tot += b
			}
			if tot > p {
				ans = i + 2
				break
			}
		}
		Fprintln(out, ans)
	}
}

func rd() (x int) {
	inn.Scan()
	data := inn.Bytes()
	f := 1
	if data[0] == '-' {
		f = -1
		data = data[1:]
	}
	for _, b := range data {
		x = x*10 + int(b&15)
	}
	return f * x
}
func rdll() (x int64) {
	inn.Scan()
	data := inn.Bytes()
	f := int64(1)
	if data[0] == '-' {
		f = -1
		data = data[1:]
	}
	for _, b := range data {
		x = x*10 + int64(b&15)
	}
	return f * x
}
func rds() string {
	inn.Scan()
	data := inn.Bytes()
	return string(data)
}

package main

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

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

func main() {
	defer out.Flush()
	inn.Buffer([]byte{}, 1000000)
	inn.Split(bufio.ScanWords)
	for tt := rd(); tt > 0; tt-- {
		a, b, p := rd(), rd(), rd()
		st := rds()
		tot, ans := 0, 1
		for i, j := len(st)-2, len(st)-2; i >= 0; i = j {
			for j >= 0 && st[i] == st[j] {
				j--
			}
			if st[i] == 'A' {
				tot += a
			} else {
				tot += b
			}
			if tot > p {
				ans = i + 2
				break
			}
		}
		Fprintln(out, ans)
	}
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func rd() (x int) {
	inn.Scan()
	data := inn.Bytes()
	x, _ = strconv.Atoi(string(data))
	return x
}
func rds() string {
	inn.Scan()
	return string(inn.Bytes())
}

package main

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

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

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

func main() {
	defer out.Flush()
	inn.Split(bufio.ScanWords)

	for tt := rd(); tt > 0; tt-- {
		a, b, p := rd(), rd(), rd()
		var st string
		Fscan(in, &st)
		tot, ans := 0, 1
		for i, j := len(st)-2, len(st)-2; i >= 0; i = j {
			for j >= 0 && st[i] == st[j] {
				j--
			}
			if st[i] == 'A' {
				tot += a
			} else {
				tot += b
			}
			if tot > p {
				ans = i + 2
				break
			}
		}
		Fprintln(out, ans)
	}
}

func rd() (x int) {
	inn.Scan()
	data := inn.Bytes()
	f := 1
	if data[0] == '-' {
		f = -1
		data = data[1:]
	}
	for _, b := range data {
		x = x*10 + int(b&15)
	}
	return f * x
}
func rdll() (x int64) {
	inn.Scan()
	data := inn.Bytes()
	f := int64(1)
	if data[0] == '-' {
		f = -1
		data = data[1:]
	}
	for _, b := range data {
		x = x*10 + int64(b&15)
	}
	return f * x
}
func rds() (x string) {
	inn.Scan()
	data := inn.Bytes()
	return string(data)
}

package main

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

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

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

func main() {
	defer out.Flush()
	inn.Split(bufio.ScanWords)

	for tt := rd(); tt > 0; tt-- {
		a, b, p := rd(), rd(), rd()
		st := rds()
		tot, ans := 0, 1
		for i, j := len(st)-2, len(st)-2; i >= 0; i = j {
			for j >= 0 && st[i] == st[j] {
				j--
			}
			if st[i] == 'A' {
				tot += a
			} else {
				tot += b
			}
			if tot > p {
				ans = i + 2
				break
			}
		}
		Fprintln(out, ans)
	}
}

func rd() (x int) {
	inn.Scan()
	data := inn.Bytes()
	f := 1
	if data[0] == '-' {
		f = -1
		data = data[1:]
	}
	for _, b := range data {
		x = x*10 + int(b&15)
	}
	return f * x
}
func rdll() (x int64) {
	inn.Scan()
	data := inn.Bytes()
	f := int64(1)
	if data[0] == '-' {
		f = -1
		data = data[1:]
	}
	for _, b := range data {
		x = x*10 + int64(b&15)
	}
	return f * x
}
func rds() (x string) {
	inn.Scan()
	return inn.Text()
}

package main

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

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

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

func main() {
	defer out.Flush()
	inn.Split(bufio.ScanWords)

	for tt := rd(); tt > 0; tt-- {
		a, b, p := rd(), rd(), rd()
		st := rds()
		tot, ans := 0, 1
		for i, j := len(st)-2, len(st)-2; i >= 0; i = j {
			for j >= 0 && st[i] == st[j] {
				j--
			}
			if st[i] == 'A' {
				tot += a
			} else {
				tot += b
			}
			if tot > p {
				ans = i + 2
				break
			}
		}
		Fprintln(out, ans)
	}
}

func rd() (x int) {
	inn.Scan()
	data := inn.Bytes()
	f := 1
	if data[0] == '-' {
		f = -1
		data = data[1:]
	}
	for _, b := range data {
		x = x*10 + int(b&15)
	}
	return f * x
}
func rdll() (x int64) {
	inn.Scan()
	data := inn.Bytes()
	f := int64(1)
	if data[0] == '-' {
		f = -1
		data = data[1:]
	}
	for _, b := range data {
		x = x*10 + int64(b&15)
	}
	return f * x
}
func rds() (x string) {
	inn.Scan()
	data := inn.Bytes()
	return string(data)
}


Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has $$$n$$$ distinct strings of equal length $$$m$$$. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$1 \le m \le 50$$$) — the number of strings and the length of each string. Next $$$n$$$ lines contain a string of length $$$m$$$ each, consisting of lowercase Latin letters only. All strings are distinct.

In the first line, print the length of the longest palindrome string you made. In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.

9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji

NoteIn the first example, "battab" is also a valid answer.In the second example, there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example, the empty string is the only valid palindrome string.

package main

import "fmt"

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

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

func isPalindrome(str string) bool {
	if str == Reverse(str) {
		return true
	}
	return false
}

func LongestPalindrome(sList []string) (int, string) {
	rsc := ""
	rsl := ""
	dc := ""
	var tempReverse []string
	for i := 0; i < len(sList); i++ {
		for j := i + 1; j < len(sList); j++ {
			if sList[i] == reverse(sList[j]) {
				tempReverse = append(tempReverse, sList[i], sList[j])
				sList[i] = ""
				sList[j] = ""
			}
		}
		if len(sList[i]) > 0 {
			if isPalindrome(sList[i]) {
				dc = sList[i]
			}
		}
	}
	for i :=0; i < len(tempReverse); i++ {
		if i % 2 == 0 {
			rsc += tempReverse[i]
		} else {
			rsl = tempReverse[i] + rsl
		}
	}
	rs := rsc + dc + rsl
	return len(rs), rs
}

func main() {
	var n, m int
	var sList []string
	fmt.Scanf("%d %d\n", &n, &m)
	for i := 0; i < n; i++ {
		var s string
		fmt.Scanf("%s\n", &s)
		sList = append(sList, s)
	}
	num, str := LongestPalindrome(sList)
	fmt.Println(num)
	fmt.Println(str)
}

/**
 * Copyright shopee
 * @Author : Yuxiang.Lei
 * @MailBox: Yuxiang.Lei@shopee.com
 * @Date : 2020-02-15
 * @Version: v2.4
 **/

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	firstLine := scanner.Text()
	arrs := strings.Split(firstLine, " ")
	num, _ := strconv.ParseInt(arrs[0], 10, 64)
	// length, _ := strconv.ParseInt(arrs[1], 10, 64)
	m := make(map[string]bool)
	result := ""
	hasZhou := false
	for i := int64(0); i < num; i++ {
		scanner.Scan()
		str := scanner.Text()
		strReverse := reverseStr(str)
		// fmt.Println(str, strReverse, result)
		if _, ok := m[strReverse]; ok {
			result = str + result + strReverse
		} else if str == strReverse && hasZhou == false {
			if len(result) == 0 {
				result = str
				hasZhou = true
			} else {
				result = result[:len(result)/2] + str + result[len(result)/2:]
				hasZhou = true
			}
		} else {
			m[str] = false
		}
	}
	fmt.Println(len(result))
	fmt.Println(result)
}

func reverseStr(str1 string) string {
	str2 := strings.Builder{}
	for i:=len(str1)-1;i>=0;i-- {
		str2.WriteByte(str1[i])
	}
	return str2.String()
}

package main

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

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

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

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

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

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

func main() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 10000), 1000000)

	n := scanInt()
	m := scanInt()
	s := make([]string, n)

	for i := 0; i < n; i++ {
		s[i] = scanString()
	}

	a,b := []string{},[]string{}
	isUsed := make([]bool, n)

	for i := 0; i < n; i++ {
		if isUsed[i] {
			continue
		}
		for j := i+1; j < n; j++ {
			if isUsed[j] {
				continue
			}
			f := true
			for k := 0; k < m; k++ {
				if s[i][k] != s[j][m-1-k] {
					f = false
				}
			}

			if f {
				a = append(a, s[i])
				b = append(b, s[j])
				isUsed[i] = true
				isUsed[j] = true
			}
		}
	}

	c := []string{}
	for i := 0; i < n; i++ {
		if isUsed[i] {
			continue
		}
		f := true
		for j := 0; j < m; j++ {
			if s[i][j] != s[i][m-1-j] {
				f = false
			}
		}

		if f {
			c = append(c,s[i])
			break
		}
	}

	l := len(a)
	fmt.Println(l*m*2+len(c)*m)
	for i := 0; i < l; i++ {
		fmt.Print(a[i])
	}
	if len(c) != 0 {
		fmt.Print(c[0])
	}
	for i := 0; i < l; i++ {
		fmt.Print(b[l-1-i])
	}
	fmt.Println()
}

package main

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

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)

func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }

func rev(s string) string {
	arr := []byte(s)
	for i := 0; i < len(s)/2; i++ {
		arr[i], arr[len(arr)-i-1] = arr[len(arr)-1-i], arr[i]
	}
	return string(arr)
}
func remove(arr []string, a, b int) []string {
	ret := []string{}
	for i := 0; i < len(arr); i++ {
		if i == a || i == b {
			continue
		}
		ret = append(ret, arr[i])
	}
	return ret
}

func main() {
	defer writer.Flush()
	var n, m int
	scanf("%d %d\n", &n, &m)
	ans := ""
	arr := []string{}
	for i := 0; i < n; i++ {
		var s string
		scanf("%s\n", &s)
		arr = append(arr, s)
	}
	flag := true
	for flag {
		f := false
		flag = false
		for i := 0; i < len(arr); i++ {
			// fmt.Println(i)
			for j := i + 1; j < len(arr); j++ {
				// if i == 0 && j == 1 {
				// 	fmt.Println(rev(arr[j]), arr[i])
				// }
				if rev(arr[j]) == arr[i] {
					f = true
					ans = ans + arr[i]
					arr = remove(arr, i, j)
					break
				}
			}
			if f {
				flag = true
				break
			}
		}
	}
	rans := rev(ans)

	md := ""

	for i := 0; i < len(arr); i++ {
		if rev(arr[i]) == arr[i] {
			md = arr[i]
		}
	}
	ans = ans + md + rans

	printf("%d\n%s\n", len(ans), ans)
}

package main

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

func reverse(s string) string {
    rev := ""
    for i := len(s) - 1; i >= 0; i-- {
        rev += string(s[i])
    }
    return rev
}

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Scan()
    line := scanner.Text()
    parts := strings.Split(line, " ")
    n, _ := strconv.Atoi(parts[0])
    //~ m, _ := strconv.Atoi(parts[1])
    strings := make([]string, n)
    for i, _ := range strings {
        scanner.Scan()
        strings[i] = scanner.Text()
    }
    //~ fmt.Println(n, m, strings)
    var s_palindrome *string
    pairs_first := make([]string, 0)
    pairs_second := make([]string, 0)

    for len(strings) > 0 {
        s := strings[len(strings) - 1]
        strings = strings[:len(strings) - 1]
        s_reversed := reverse(s)
        //~ fmt.Println("ssr", s, s_reversed)
        //~ fmt.Println(strings)
        var s_partner *string
        for i, sp := range strings {
            if s_reversed == sp {
                s_partner = &sp
                new_strings := make([]string, len(strings) - 1)
                copy(new_strings[:i], strings[:i])
                copy(new_strings[i:], strings[i + 1:])
                strings = new_strings
                break
            }
        }
        //~ fmt.Println(strings, s_partner)

        if s_partner != nil {
            pairs_first = append(pairs_first, s)
            pairs_second = append(pairs_second, *s_partner)
        } else if s == s_reversed {
            s_palindrome = &s
        }
    }

    //~ fmt.Println("pff", pairs_first, pairs_second, s_palindrome)

    palindrome := ""
    for i := 0; i < len(pairs_first); i++ {
        palindrome += pairs_first[i]
    }
    if s_palindrome != nil {
        palindrome += *s_palindrome
    }
    for i := len(pairs_first) - 1; i >= 0; i-- {
        palindrome += pairs_second[i]
    }

    fmt.Println(len(palindrome))
    fmt.Println(palindrome)
}

package main

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

func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var n, m int
	Fscan(in, &n, &m)
	a := make([]string, n)
	pa := ""
	pos := map[string]int{}
	//matchTo := make([]int, n)
	ans := []string{}
	for i := range a {
		Fscan(in, &a[i])
		ok := true
		for j, b := range a[i] {
			if a[i][m-1-j] != byte(b) {
				ok  = false
				break
			}
		}
		if ok {
			pa = a[i]
		} else {
			s := a[i]
			sRB := make([]byte, len(s))
			for i := range s {
				sRB[i] = s[len(s)-1-i]
			}
			if _, ok := pos[string(sRB)]; ok {
				ans = append(ans, a[i])
			}

		}
		pos[a[i]] = i
	}

	aa := []byte{}
	for _, s := range ans {
		aa = append(aa, s...)
	}
	aa = append(aa, pa...)
	for i := len(ans) - 1; i >= 0; i-- {
		v := ans[i]
		for j := range v {
			aa = append(aa, v[m-1-j])
		}
	}
	Fprintln(out, len(aa))
	Fprintln(out, string(aa))
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	reverse := func(a []byte) []byte {
		n := len(a)
		r := make([]byte, n)
		for i, v := range a {
			r[n-1-i] = v
		}
		return r
	}

	ss := [][]byte{}
	pa := []byte{}
	has := map[string]bool{}
	var n, m int
	var s []byte
	Fscan(in, &n, &m)
	for i := 0; i < n; i++ {
		Fscan(in, &s)
		if rs := reverse(s); bytes.Equal(s, rs) {
			pa = s
		} else if has[string(rs)] {
			ss = append(ss, s)
		} else {
			has[string(s)] = true
		}
	}

	ans := []byte{}
	for _, s := range ss {
		ans = append(ans, s...)
	}
	ans = append(ans, pa...)
	for i := len(ss) - 1; i >= 0; i-- {
		ans = append(ans, reverse(ss[i])...)
	}
	Fprintln(out, len(ans))
	Fprintln(out, string(ans))
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	reverse := func(a []byte) []byte {
		n := len(a)
		r := make([]byte, n)
		for i, v := range a {
			r[n-1-i] = v
		}
		return r
	}

	ss := [][]byte{}
	pa := []byte{}
	has := map[string]bool{}
	var n, m int
	var s []byte
	Fscan(in, &n, &m)
	for i := 0; i < n; i++ {
		Fscan(in, &s)
		if rs := reverse(s); bytes.Equal(s, rs) {
			pa = s
		} else if has[string(rs)] {
			ss = append(ss, s)
		} else {
			has[string(s)] = true
		}
	}

	ans := []byte{}
	for _, s := range ss {
		ans = append(ans, s...)
	}
	rAns := reverse(ans)
	ans = append(ans, pa...)
	ans = append(ans, rAns...)
	Fprintln(out, len(ans))
	Fprintln(out, string(ans))
}

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

package main

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

func main() {
	n := int(ReadInt64())
	ReadInt64()
	s := ReadStringSlice(int(n))
	centerString := ""

	firstHalf := ""
	secondHalf := ""
	forward := make(map[string]int)
	backward := make(map[string]int)

	for i := 0; i < n; i++ {
		rev := revStr(s[i])
		if rev == s[i] {
			centerString = rev
		} else {
			forward[s[i]] = i
			backward[rev] = i
		}
	}

	for k := range forward {
		kRev := revStr(k)
		if _, ok := backward[k]; ok {
			firstHalf += k
			secondHalf = kRev + secondHalf
			delete(forward, k)
			delete(backward, k)
			delete(forward, kRev)
			delete(backward, kRev)
		}
	}
	finalStr := firstHalf + centerString + secondHalf
	fmt.Println(len(finalStr))
	fmt.Println(finalStr)
}

var scanner *bufio.Scanner

func init() {
	scanner = bufio.NewScanner(os.Stdin)
	scanner.Buffer(make([]byte, 1024), int(1e8))
	scanner.Split(bufio.ScanWords)
}

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

func ReadStringSlice(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ReadString()
	}
	return s
}

func ReadInt64() int64 {
	intStr := ReadString()
	i, err := strconv.ParseInt(intStr, 10, 64)
	if err != nil {
		panic(err)
	}
	return i
}

func ReadInt64Slice(n int) []int64 {
	arr := make([]int64, n)
	for i := 0; i < n; i++ {
		arr[i] = ReadInt64()
	}
	return arr
}

func revStr(inputString string) string {
	stringBuilder := strings.Builder{}
	stringBuilder.Grow(len(inputString))
	for i := len(inputString) - 1; i >= 0; i-- {
		stringBuilder.WriteString(string(inputString[i]))
	}
	return stringBuilder.String()
}

package main

import (
	"fmt"
)

func isPals(s1 string, s2 string) bool {
	return isPalindrome(s1 + s2)
}

func isPalindrome(s string) bool {
	i := 0
	j := len(s) - 1
	for i < j {
		if s[i] != s[j] {
			return false
		}
		i++
		j--
	}
	return true
}

func reverse(in string) string {
	var out []byte
	for i := len(in) - 1; i >= 0; i-- {
		out = append(out, in[i])
	}
	return string(out)
}

func del(m map[string][]int, k string) {
	m[k] = m[k][:len(m[k])-1]
	if len(m[k]) == 0 {
		delete(m, k)
	}
}

func main() {
	n := 0
	m := 0
	fmt.Scanln(&n, &m)
	used := map[int]struct{}{}
	var ss []string
	seen := make(map[string]int)
	pals := make([][]string, 0)
	for i := 0; i < n; i++ {
		s := ""
		fmt.Scanln(&s)
		ss = append(ss, s)
		r := reverse(s)
		if p, ok := seen[r]; ok {
			pals = append(pals, []string{s, r})
			delete(seen, r)
			used[p] = struct{}{}
			used[i] = struct{}{}
		} else {
			seen[s] = i
		}
	}

	res := ""
	for i := 0; i < len(ss); i++ {
		if _, ok := used[i]; ok {
			continue
		}
		if isPalindrome(ss[i]) && len(ss[i]) > len(res) {
			res = ss[i]
		}
	}
	for i := 0; i < len(pals);i++ {
		res = pals[i][0] + res + pals[i][1]
	}

	fmt.Println(len(res))
	fmt.Println(res)

}

package main

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

const (
	MX_INT int64 = math.MaxInt64
	MN_INT int64 = math.MinInt64
)

func main() {
	n, _ := ScanInt(), ScanInt()
	s := ScanStringSlice(n)

	left, right := "", ""
	straightM := make(map[string]int)
	reverseM := make(map[string]int)

	palindrom := ""

	for i := 0; i < n; i++ {
		rev := reverseString(s[i])

		if rev == s[i] {
			palindrom = rev
		} else {
			straightM[s[i]] = i
			reverseM[rev] = i
		}
	}

	for k := range straightM {
		kRev := reverseString(k)
		if _, ok := reverseM[k]; ok {
			left += k
			right = kRev + right

			delete(straightM, k)
			delete(straightM, kRev)
			delete(reverseM, k)
			delete(reverseM, kRev)
		}
	}

	finalStr := left + palindrom + right
	fmt.Println(len(finalStr))
	fmt.Println(finalStr)

	close(O)
	oWg.Wait()
}
func reverseString(s string) string {
	sb := strings.Builder{}
	sb.Grow(len(s))

	for i := len(s) - 1; i >= 0; i-- {
		sb.WriteString(string(s[i]))
	}
	return sb.String()
}

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

var O chan string
var in *bufio.Scanner
var oWg *sync.WaitGroup
var P func(a ...interface{}) (n int, err error)

func init() {
	P = fmt.Println

	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(1e7))
	in.Split(bufio.ScanWords)

	O = make(chan string, 16)
	oWg = &sync.WaitGroup{}
	oWg.Add(1)

	writer := bufio.NewWriterSize(os.Stdout, int(1e7))
	go func(writer *bufio.Writer) {
		defer oWg.Done()
		defer writer.Flush()

		for line := range O {
			writer.WriteString(line + "\n")
		}
	}(writer)
}

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

func ScanStringSlice(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ScanWord()
	}
	return s
}

func ScanInt64() int64 {
	intStr := ScanWord()
	i, err := strconv.ParseInt(intStr, 10, 64)
	if err != nil {
		panic(err)
	}
	return i
}

func ScanInt() int {
	intStr := ScanWord()
	i, err := strconv.Atoi(intStr)
	if err != nil {
		panic(err)
	}
	return i
}

func ScanInt64Slice(n int) []int64 {
	arr := make([]int64, n)
	for i := 0; i < n; i++ {
		arr[i] = ScanInt64()
	}
	return arr
}

/*********************** Utils ***********************/

func MnMx(args ...int64) (int64, int64) {
	minVal, maxVal := MX_INT, MN_INT

	for _, v := range args {
		if v < minVal {
			minVal = v
		}
		if v > maxVal {
			maxVal = v
		}
	}
	return minVal, maxVal
}

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

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

func S(v interface{}) string {
	return fmt.Sprintf("%v", v)
}

func SArr(a []int64) string {
	sb := strings.Builder{}
	sb.Grow(len(a) * 9)

	for i := range a {
		numStr := strconv.FormatInt(a[i], 10)
		sb.WriteString(numStr + " ")
	}
	return sb.String()
}

package main

import (
	"fmt"
)

func checkReversiveStr(a, b string) bool  {
	if a == "" || b == "" {
		return false
	}
	for i := 0; i < len(a); i++ {
		if a[i] != b[len(b) - 1 - i] {
			return false
		}
	}
	return true
}

func checkPalindrome(s string) bool  {
	for i := 0; i < len(s) / 2; i++ {
		if s[i] != s[len(s) - 1 - i] {
			return false
		}
	}
	return true
}

func process(arrStr []string, n int, m int) (int, string)  {
	resultLeft := ""
	resultRight := ""
	for i := 0; i < n; i++ {
		for j := i + 1; j < n; j++ {
			if checkReversiveStr(arrStr[i], arrStr[j]) {
				resultLeft = arrStr[i] + resultLeft
				resultRight = resultRight + arrStr[j]
				arrStr[i] = ""
				arrStr[j] = ""
			}
		}
	}
	resultMid := ""
	for i := 0; i < len(arrStr); i++ {
		if len(arrStr[i])  > 0 && checkPalindrome(arrStr[i]) {
			resultMid = arrStr[i]
			break
		}
	}
	result := resultLeft + resultMid + resultRight
	return len(result), result
}

func main()  {
	var n, m int
	fmt.Scan(&n, &m)
	arrStr := make([]string, n)

	for i := 0; i < n; i++ {
		fmt.Scan(&arrStr[i])
	}

	len, result := process(arrStr, n, m)
	fmt.Println(len)
	fmt.Println(result)
}


As you know, every birthday party has a cake! This time, Babaei is going to prepare the very special birthday party's cake.Simple cake is a cylinder of some radius and height. The volume of the simple cake is equal to the volume of corresponding cylinder. Babaei has n simple cakes and he is going to make a special cake placing some cylinders on each other.However, there are some additional culinary restrictions. The cakes are numbered in such a way that the cake number i can be placed only on the table or on some cake number j where j < i. Moreover, in order to impress friends Babaei will put the cake i on top of the cake j only if the volume of the cake i is strictly greater than the volume of the cake j.Babaei wants to prepare a birthday cake that has a maximum possible total volume. Help him find this value.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of simple cakes Babaei has. Each of the following n lines contains two integers ri and hi (1 ≤ ri, hi ≤ 10 000), giving the radius and height of the i-th cake.

Print the maximum volume of the cake that Babaei can make. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

NoteIn first sample, the optimal way is to choose the cake number 1.In second sample, the way to get the maximum volume is to use cakes with indices 1, 2 and 4.

package main

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

// github.com/EndlessCheng/codeforces-go
func CF629D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	type pair struct {
		v int64
		i int
	}

	var n int
	var r, h, ans int64
	Fscan(in, &n)
	a := make([]pair, n)
	for i := range a {
		Fscan(in, &r, &h)
		a[i] = pair{r * r * h, i}
	}
	sort.Slice(a, func(i, j int) bool { a, b := a[i], a[j]; return a.v < b.v || a.v == b.v && a.i > b.i })

	max := func(a, b int64) int64 {
		if a > b {
			return a
		}
		return b
	}
	tree := make([]int64, n+1)
	add := func(i int, val int64) {
		for ; i <= n; i += i & -i {
			tree[i] = max(tree[i], val)
		}
	}
	query := func(i int) (res int64) {
		for ; i > 0; i &= i - 1 {
			res = max(res, tree[i])
		}
		return
	}
	for _, p := range a {
		v := p.v + query(p.i)
		ans = max(ans, v)
		add(p.i+1, v)
	}
	Fprintf(_w, "%.9f", float64(ans)*math.Pi)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF629D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	type pair struct {
		v int64
		i int
	}

	var n int
	var r, h, ans int64
	Fscan(in, &n)
	a := make([]pair, n)
	for i := range a {
		Fscan(in, &r, &h)
		a[i] = pair{r * r * h, i}
	}
	sort.Slice(a, func(i, j int) bool { a, b := a[i], a[j]; return a.v < b.v || a.v == b.v && a.i < b.i })

	max := func(a, b int64) int64 {
		if a > b {
			return a
		}
		return b
	}
	tree := make([]int64, n+1)
	add := func(i int, val int64) {
		for ; i <= n; i += i & -i {
			tree[i] = max(tree[i], val)
		}
	}
	query := func(i int) (res int64) {
		for ; i > 0; i &= i - 1 {
			res = max(res, tree[i])
		}
		return
	}
	for _, p := range a {
		v := p.v + query(p.i)
		ans = max(ans, v)
		add(p.i+1, v)
	}
	Fprintf(_w, "%.9f", float64(ans)*math.Pi)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF629D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	type pair struct {
		v int64
		i int
	}

	var n int
	var r, h, ans int64
	Fscan(in, &n)
	a := make([]pair, n)
	for i := range a {
		Fscan(in, &r, &h)
		a[i] = pair{r * r * h, i}
	}
	sort.Slice(a, func(i, j int) bool { a, b := a[i], a[j]; return a.v < b.v })

	max := func(a, b int64) int64 {
		if a > b {
			return a
		}
		return b
	}
	tree := make([]int64, n+1)
	add := func(i int, val int64) {
		for ; i <= n; i += i & -i {
			tree[i] = max(tree[i], val)
		}
	}
	query := func(i int) (res int64) {
		for ; i > 0; i &= i - 1 {
			res = max(res, tree[i])
		}
		return
	}
	for _, p := range a {
		v := p.v + query(p.i)
		ans = max(ans, v)
		add(p.i+1, v)
	}
	Fprintf(_w, "%.9f", float64(ans)*math.Pi)
}

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


You are given a rectangular grid with $$$n$$$ rows and $$$m$$$ columns. The cell located on the $$$i$$$-th row from the top and the $$$j$$$-th column from the left has a value $$$a_{ij}$$$ written in it.You can perform the following operation any number of times (possibly zero):  Choose any two adjacent cells and multiply the values in them by $$$-1$$$. Two cells are called adjacent if they share a side. Note that you can use a cell more than once in different operations.You are interested in $$$X$$$, the sum of all the numbers in the grid. What is the maximum $$$X$$$ you can achieve with these operations?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$,$$$m$$$ ($$$2 \le n$$$, $$$m \le 10$$$).  The following $$$n$$$ lines contain $$$m$$$ integers each, the $$$j$$$-th element in the $$$i$$$-th line is $$$a_{ij}$$$ ($$$-100\leq a_{ij}\le 100$$$).

For each testcase, print one integer $$$X$$$, the maximum possible sum of all the values in the grid after applying the operation as many times as you want.

NoteIn the first test case, there will always be at least one $$$-1$$$, so the answer is $$$2$$$. In the second test case, we can use the operation six times to elements adjacent horizontally and get all numbers to be non-negative. So the answer is: $$$2\times 1 + 3\times2 + 3\times 3 + 2\times 4 + 1\times 5 = 30$$$.

package main

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

const (
	SCANNER_BUF_SIZE = 2 << 20

	INF = int64(math.MaxInt64)
	MOD = 1e9 + 7
)

var (
	writer  *bufio.Writer
	scanner *bufio.Scanner
)

func init() {
	writer = bufio.NewWriter(os.Stdout)
	scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, SCANNER_BUF_SIZE), SCANNER_BUF_SIZE)
}

func printf(f string, a ...interface{}) {
	fmt.Fprintf(writer, f, a...)
}

func sint64() int64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := int64(0)
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int64(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func suint64() uint64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := uint64(0)
	for _, b := range bb {
		i *= 10
		i += uint64(b - '0')
	}
	return i
}

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

func gcd(a, b int64) int64 {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

func lcm(a, b int64) int64 {
	return a * b / gcd(a, b)
}

func abs(a int64) int64 {
	if a < 0 {
		return a * -1
	}
	return a
}

func min(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r < a {
			a = r
		}
	}
	return a
}

func max(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r > a {
			a = r
		}
	}
	return a
}

func main() {
	defer writer.Flush()
	t := sint64()
	for ; t > 0; t-- {
		n, m := sint64(), sint64()
		nums := []int64{}
		for i := int64(0); i < n; i++ {
			for j := int64(0); j < m; j++ {
				nums = append(nums, sint64())
			}
		}
		printf("%d\n", sol(nums))
	}
}

func sol(nums []int64) int64 {
	sort.Slice(nums, func(a, b int) bool {
		return nums[a] < nums[b]
	})
	negCount := 0
	for _, n := range nums {
		if n <= 0 {
			negCount++
		}
	}
	res := int64(0)
	if negCount&1 == 1 {
		// maybe make a positive number negative
		if negCount < len(nums) && nums[negCount] < -nums[negCount-1] {
			res += -sum(nums[:negCount+1])
			res += sum(nums[negCount+1:])
			return res
		}

		// only make negative numbers negative
		res += -sum(nums[:negCount-1])
		res += sum(nums[negCount-1:])
		return res
	}

	// even number of negative numbers
	res += -sum(nums[:negCount])
	res += sum(nums[negCount:])
	return res
}

func sum(nums []int64) int64 {
	res := int64(0)
	for _, n := range nums {
		res += n
	}
	return res
}

package main

import (
	"fmt"
	"math"
)

var t,n,m,f,ff,s,mi int

func main()  {
	fmt.Scan(&t)
	for i:=1;i<=t;i++{
		f,ff,s,mi=0,0,0,100
		fmt.Scan(&n,&m)
		a:=make([][]int,n+1)
		for j:=range a{
			a[j]=make([]int,m+1)
		}
		for j:=1;j<=n;j++{
			for k:=1;k<=m;k++{
				fmt.Scan(&a[j][k])
				if a[j][k]==0{
					f=1
				}else if a[j][k]<0{
					ff++

				}
				mi=int(math.Min(float64(mi),math.Abs(float64(a[j][k]))))
				s+=int(math.Abs(float64(a[j][k])))
			}
		}
		if f==1{
			fmt.Println(s)
		}else if ff%2==0{
			fmt.Println(s)
		}else{
			fmt.Println(s-2*mi)
		}
	}
}

package main

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

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

	var T, n, m int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &m)
		a := make([]int, n*m)
		c, s := 0, 0
		for i := range a {
			Fscan(in, &a[i])
			if a[i] < 0 {
				c++
				a[i] = -a[i]
			}
			s += a[i]
		}
		sort.Ints(a)
		if a[0] > 0 && c&1 > 0 {
			s -= 2 * a[0]
		}
		Fprintln(out, s)
	}
}

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

package main

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

func main() {
	//rd, _ := os.Open("input")
	//in := bufio.NewReader(rd)
	in := bufio.NewReader(os.Stdin)

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

	for ; t > 0; t-- {
		fmt.Fscan(in, &n, &m)
		a := make([]int, n*m)
		hasZero := false
		negatives := 0
		for i := 0; i < n; i++ {
			for j := 0; j < m; j++ {
				fmt.Fscan(in, &a[i*m+j])
				if a[i*m+j] == 0 {
					hasZero = true
				} else if a[i*m+j] < 0 {
					negatives++
					a[i*m+j] *= -1
				}
			}
		}
		sort.Ints(a)
		sum := 0
		for i := range a {
			sum += a[i]
		}
		if negatives%2 == 1 && !hasZero {
			sum -= 2 * a[0]
		}
		fmt.Println(sum)
	}

}

package main

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

const (
	SCANNER_BUF_SIZE = 2 << 20

	INF = int64(math.MaxInt64)
	MOD = 1e9 + 7
)

var (
	writer  *bufio.Writer
	scanner *bufio.Scanner
)

func init() {
	writer = bufio.NewWriter(os.Stdout)
	scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, SCANNER_BUF_SIZE), SCANNER_BUF_SIZE)
}

func printf(f string, a ...interface{}) {
	fmt.Fprintf(writer, f, a...)
}

func sint64() int64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := int64(0)
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int64(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func suint64() uint64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := uint64(0)
	for _, b := range bb {
		i *= 10
		i += uint64(b - '0')
	}
	return i
}

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

func gcd(a, b int64) int64 {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

func lcm(a, b int64) int64 {
	return a * b / gcd(a, b)
}

func abs(a int64) int64 {
	if a < 0 {
		return a * -1
	}
	return a
}

func min(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r < a {
			a = r
		}
	}
	return a
}

func max(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r > a {
			a = r
		}
	}
	return a
}

func main() {
	defer writer.Flush()
	t := sint64()
	for ; t > 0; t-- {
		n, m := sint64(), sint64()
		nums := []int64{}
		for i := int64(0); i < n; i++ {
			for j := int64(0); j < m; j++ {
				nums = append(nums, sint64())
			}
		}
		printf("%d\n", sol(nums))
	}
}

func sol(nums []int64) int64 {
	sort.Slice(nums, func(a, b int) bool {
		return nums[a] < nums[b]
	})
	negCount := 0
	for _, n := range nums {
		if n <= 0 {
			negCount++
		}
	}
	res := int64(0)
	if negCount & 1 == 1 {
		res += -sum(nums[:negCount-1])
		res += nums[negCount-1]
	} else {
		res += -sum(nums[:negCount])
	}
	res += sum(nums[negCount:])
	return res
}

func sum(nums []int64) int64 {
	res := int64(0)
	for _, n := range nums {
		res += n
	}
	return res
}

package main

import (
	"fmt"
	"math"
)

var t,n,m,f,ff,s,ma int

func main()  {
	fmt.Scan(&t)
	for i:=1;i<=t;i++{
		f,ff,s,ma=0,0,0,-100
		fmt.Scan(&n,&m)
		a:=make([][]int,n+1)
		for j:=range a{
			a[j]=make([]int,m+1)
		}
		for j:=1;j<=n;j++{
			for k:=1;k<=m;k++{
				fmt.Scan(&a[j][k])
				if a[j][k]==0{
					f=1
				}else if a[j][k]<0{
					ff++
					ma=int(math.Max(float64(ma),float64(a[j][k])))
				}
				s+=int(math.Abs(float64(a[j][k])))
			}
		}
		if f==1{
			fmt.Println(s)
		}else if ff%2==0{
			fmt.Println(s)
		}else{
			fmt.Println(s+2*ma)
		}
	}
}


You are given a rooted tree with vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.Ancestors of the vertex $$$i$$$ are all vertices on the path from the root to the vertex $$$i$$$, except the vertex $$$i$$$ itself. The parent of the vertex $$$i$$$ is the nearest to the vertex $$$i$$$ ancestor of $$$i$$$. Each vertex is a child of its parent. In the given tree the parent of the vertex $$$i$$$ is the vertex $$$p_i$$$. For the root, the value $$$p_i$$$ is $$$-1$$$.    An example of a tree with $$$n=8$$$, the root is vertex $$$5$$$. The parent of the vertex $$$2$$$ is vertex $$$3$$$, the parent of the vertex $$$1$$$ is vertex $$$5$$$. The ancestors of the vertex $$$6$$$ are vertices $$$4$$$ and $$$5$$$, the ancestors of the vertex $$$7$$$ are vertices $$$8$$$, $$$3$$$ and $$$5$$$ You noticed that some vertices do not respect others. In particular, if $$$c_i = 1$$$, then the vertex $$$i$$$ does not respect any of its ancestors, and if $$$c_i = 0$$$, it respects all of them.You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex $$$v$$$, all children of $$$v$$$ become connected with the parent of $$$v$$$.    An example of deletion of the vertex $$$7$$$. Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of vertices in the tree. The next $$$n$$$ lines describe the tree: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le n$$$, $$$0 \le c_i \le 1$$$), where $$$p_i$$$ is the parent of the vertex $$$i$$$, and $$$c_i = 0$$$, if the vertex $$$i$$$ respects its parents, and $$$c_i = 1$$$, if the vertex $$$i$$$ does not respect any of its parents. The root of the tree has $$$-1$$$ instead of the parent index, also, $$$c_i=0$$$ for the root. It is guaranteed that the values $$$p_i$$$ define a rooted tree with $$$n$$$ vertices.

In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer $$$-1$$$.

NoteThe deletion process in the first example is as follows (see the picture below, the vertices with $$$c_i=1$$$ are in yellow):  first you will delete the vertex $$$1$$$, because it does not respect ancestors and all its children (the vertex $$$2$$$) do not respect it, and $$$1$$$ is the smallest index among such vertices;  the vertex $$$2$$$ will be connected with the vertex $$$3$$$ after deletion;  then you will delete the vertex $$$2$$$, because it does not respect ancestors and all its children (the only vertex $$$4$$$) do not respect it;  the vertex $$$4$$$ will be connected with the vertex $$$3$$$;  then you will delete the vertex $$$4$$$, because it does not respect ancestors and all its children (there are none) do not respect it (vacuous truth);  you will just delete the vertex $$$4$$$;  there are no more vertices to delete.   In the second example you don't need to delete any vertex:  vertices $$$2$$$ and $$$3$$$ have children that respect them;  vertices $$$4$$$ and $$$5$$$ respect ancestors.   In the third example the tree will change this way:

package main

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

type Songs []int

func (s Songs) Less(i, j int) bool {
	if s[i] < s[j] {
		return true
	}
	return false
}
func (s Songs) Len() int {
	return len(s)
}
func (s Songs) Swap(i, j int) {
	tmp := s[i]
	s[i] = s[j]
	s[j] = tmp
}

func addC(u, v int, edge [][]int) {
	if len(edge[u]) == 0 {
		edge[u] = make([]int, 0)
	}
	edge[u] = append(edge[u], v)
}
func main() {
	buf := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscanf(buf, "%d\n", &n)
	edge := make([][]int, n+1)
	s := make(Songs, 0)
	per := make([]int, n+1)
	col := make([]int, n+1)
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d %d\n", &per[i+1], &col[i+1])
		if per[i+1] == -1 {
			continue
		}
		addC(i+1, per[i+1], edge)
		addC(per[i+1], i+1, edge)
	}
	for i:= 1;i <= n;i++{
		if per[i]==-1||col[i]==0{
			continue
		}
		flag := true
		for _,v := range edge[i]{
			if per[i] != v&&col[v]==0{
				flag=false
			}
		}
		if flag{
			s=append(s,i)
		}
	}
	ls := len(s)
	if ls==0{
		fmt.Printf("-1\n")
		return
	}
	sort.Sort(s)

	for i := 0; i < ls; i++ {
		fmt.Printf("%d ", s[i])
	}

}

/**
0 0
0 1
3
UDD
 */

package main

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

const (
	mod = int(1e9 + 7)
)

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n := 0
	fmt.Fscanf(in, "%d\n", &n)
	p, c := make([]int, n), make([]int, n)
	stable := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(in, "%d %d\n", &p[i], &c[i])
		p[i]--
		if p[i] != -2 {
			if c[i] == 0 {
				stable[i] = 1
				//fmt.Println(p[i])
				stable[p[i]] = 1
			}
		} else {
			if c[i] == 0 {
				stable[i] = 1
			}
		}
	}
	ans := make([]int, 0)
	for i := 0; i < n; i++ {
		if stable[i] == 0 {
			ans = append(ans, i+1)
		}
	}
	if len(ans) > 0 {
		for i := 0; i < len(ans)-1; i++ {
			fmt.Fprintf(out, "%d ", ans[i])
		}
		fmt.Fprintf(out, "%d\n", ans[len(ans)-1])
	} else {
		fmt.Fprintf(out, "%d\n", -1)
	}
	return
}

package main

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

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)

func p(a ...interface{})                { fmt.Fprint(writer, a...) }
func pln(a ...interface{})              { fmt.Fprintln(writer, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }

func scan(a ...interface{})            { fmt.Fscan(reader, a...) }
func scanf(f string, a ...interface{}) { fmt.Fscanf(reader, f, a...) }

func main() {
	defer writer.Flush()

	var n, par, c int
	scan(&n)

	var tree = make([]bool, n+1)

	for i, _ := range tree {
		tree[i] = true
	}

	for i := 1; i <= n; i++ {
		scan(&par, &c)
		if par == -1 {
			tree[i] = false
			continue
		}
		if c == 0 {
			tree[par] = false
			tree[i] = false
		}
	}
	count := 0
	for i := 1; i <= n; i++ {
		if tree[i] {
			count++
			printf("%d ", i)
		}
	}
	if count == 0 {
		p(-1)
	}
	pln()
	return
}

// Author: sighduck
// URL: https://codeforces.com/contest/1143/problem/C

package main

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

type Node struct {
	Parent         int
	Value          int
	RespectsParent bool
}

func Solve(n int, nodes []Node) []int {
	nodesToDelete := make([]bool, n+1)
	for i := 0; i < n+1; i++ {
		nodesToDelete[i] = true
	}
	for _, node := range nodes {
		if node.Parent == -1 {
			nodesToDelete[node.Value] = false
		} else if node.RespectsParent {
			nodesToDelete[node.Parent] = false
			nodesToDelete[node.Value] = false
		}
	}
	output := []int{}
	for i := 1; i < n+1; i++ {
		if nodesToDelete[i] {
			output = append(output, i)
		}
	}
	return output
}

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

	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	nodes := make([]Node, n)
	for i := 0; i < n; i++ {
		nodes[i].Value = i + 1
		var respectsParent int
		fmt.Fscanf(reader, "%d %d\n", &nodes[i].Parent, &respectsParent)
		nodes[i].RespectsParent = (respectsParent == 0)
	}

	output := Solve(n, nodes)
	if len(output) == 0 {
		fmt.Fprintf(writer, "-1\n")
	} else {
		for _, node := range output {
			fmt.Fprintf(writer, "%d ", node)
		}
		fmt.Fprintf(writer, "\n")
	}
}


The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other — the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).

The first line of the input contains a single number n (1 ≤ n ≤ 105) — the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1 ≤ hi ≤ 109), where hi equals the number of floors in the i-th house.

Print n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.

package main

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

func main() {

	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	n := readInt(scanner)
	values := readArray(scanner, n)
	maxi := make([]int, n)
	biggest := -1
	for i:=n-1;i>=0;i-- {
		biggest = max(biggest, values[i])
		maxi[i] = biggest
	}
	for i:=0;i<n;i++ {
		val := maxi[i] - values[i]
		if val == 0 {
			if i+1 < n && maxi[i+1] == values[i] {
				fmt.Print(1, " ")
			} else {
				fmt.Print(0, " ")
			}
		} else {
			fmt.Print(val+1, " ")
		}
	}
}

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

func readArray(scanner *bufio.Scanner, n int) []int {
	res := make([]int, n)
	for i:= 0;i<n;i++ {
		res[i] = readInt(scanner)
	}
	return res
}
func readInt(scanner *bufio.Scanner) int {
	scanner.Scan()
	val, _ := strconv.Atoi(scanner.Text())
	return val
}

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)

	n := nextInt()
	a := make([]int, n)

	for i := range a {
		a[i] = nextInt()
	}

	maxFloor := a[len(a)-1]
	a[len(a)-1] = 0

	for i := len(a) - 2; i >= 0; i-- {

		if a[i] > maxFloor {
			maxFloor = a[i]
			a[i] = 0
		} else {
			a[i] = maxFloor + 1 - a[i]
		}
	}

	for i := range a {
		print(a[i], " ")
	}

	println()
}

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 (
    "bufio"
    "fmt"
    "os"
)

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

func main() {
    stdin := bufio.NewReader(os.Stdin)
    var n int
    fmt.Fscanf(stdin, "%d\n", &n)
    h := make([]int, n)
    for i := 0; i < n; i++ {
        fmt.Fscanf(stdin, "%d", &h[i])
    }

    maxh := 0
    r := make([]int, n)
    for i := n-1; i >= 0; i-- {
        r[i] = max(0, maxh - h[i])
        maxh = max(maxh, h[i]+1)

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

package main

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

func main() {
	var n int
	if _, err := fmt.Scanf("%d\n", &n); err != nil {
		return
	}

	houses := make([]int, n)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := 0; scanner.Scan(); i++ {
		a, err := strconv.Atoi(scanner.Text())
		if err != nil {
			return
		}
		houses[i] = a
	}

	needs := make([]int, n)

	var max_right_floors int = houses[n-1]
	for i := n - 2; i >= 0; i-- {
		if houses[i] <= max_right_floors {
			needs[i] = max_right_floors - houses[i] + 1
		} else {
			max_right_floors = houses[i]
		}
	}

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

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	line, _ := reader.ReadString('\n')
	line = strings.TrimSpace(line)
	size, _ := strconv.ParseUint(line, 10, 64)
	line, _ = reader.ReadString('\n')
	line = strings.TrimSpace(line)

	table := make([]uint64, size)
	out := make([]uint64, size)
	for n, i := range strings.Split(line, " ") {
		table[n], _ = strconv.ParseUint(i, 10, 64)
	}

	max := uint64(0)
	for i := len(table) - 1; i >= 0; i-- {
		if table[i] > max {
			max = table[i]
			out[i] = 0
		} else {
			out[i] = max - table[i] + 1
		}
	}
	for _, val := range out {
		fmt.Print(val, " ")
	}
}

package main

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

func main() {
	var n int
	fmt.Scan(&n)
	hn := make([]int, n, n)
	ans := make([]int, n, n)

	bs := bufio.NewScanner(os.Stdin)
	bs.Split(bufio.ScanWords)
	for i := 0; i < n; i++ {
		bs.Scan()
		hn[i], _ = strconv.Atoi(bs.Text())
	}

	h := 0
	for i := n - 1; i >= 0; i-- {
		delta := 0
		if hn[i] <= h {
			delta = h - hn[i] + 1
		}
		ans[i] = delta
		if h < hn[i] {
			h = hn[i]
		}
	}

	s := fmt.Sprint(ans)
	fmt.Println(s[1 : len(s)-1])
}

package main

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

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

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

	buf := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(in, "%d", &(buf[i]))
	}
	for i, max := n-1, 0; i >= 0; i-- {
		if buf[i] > max {
			max = buf[i]
			buf[i] = 0
		} else {
			buf[i] = max + 1 - buf[i]
		}
	}
	fmt.Print(buf[0])
	for i := 1; i < n; i++ {
		fmt.Printf(" %d", buf[i])
	}
	fmt.Println()
}

package main

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

func main() {
	//defer profile.Start(profile.ProfilePath(".")).Stop()
	defer flush()

	n := nextInt()
	h := make([]int, n)
	for i := 0; i < n; i++ {
		h[i] = nextInt()
	}
	for i, max := n-1, 0; i >= 0; i-- {
		if h[i] > max {
			max = h[i]
			h[i] = 0
		} else {
			h[i] = max + 1 - h[i]
		}
	}
	printa(h[0])
	for i := 1; i < n; i++ {
		printa(" ", h[i])
	}
	printn()
}

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

var scanner = bufio.NewScanner(os.Stdin)

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

func nextWord() string {
	return next()
}

func nextLine() string {
	defer scanner.Split(bufio.ScanWords)
	scanner.Split(bufio.ScanLines)
	return strings.TrimSpace(next())
}

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

var stdout = bufio.NewWriter(os.Stdout)

func printa(a ...interface{}) (int, error) {
	return fmt.Fprint(stdout, a...)
}

func printn(a ...interface{}) (int, error) {
	return fmt.Fprintln(stdout, a...)
}

func printf(format string, a ...interface{}) (int, error) {
	return fmt.Fprintf(stdout, format, a...)
}

func flush() error {
	return stdout.Flush()
}

package main

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

func main() {

	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	n := readInt(scanner)
	values := readArray(scanner, n)
	maxi := make([]int, n)
	biggest := -1
	for i:=n-1;i>=0;i-- {
		biggest = max(biggest, values[i])
		maxi[i] = biggest
	}
	for i:=0;i<n;i++ {
		val := maxi[i] - values[i]
		if val == 0 {
			fmt.Print(val, " ")
		} else {
			fmt.Print(val+1, " ")
		}
	}
}

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

func readArray(scanner *bufio.Scanner, n int) []int {
	res := make([]int, n)
	for i:= 0;i<n;i++ {
		res[i] = readInt(scanner)
	}
	return res
}
func readInt(scanner *bufio.Scanner) int {
	scanner.Scan()
	val, _ := strconv.Atoi(scanner.Text())
	return val
}

package main

import "fmt"

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

func main() {
    var n int
    fmt.Scanf("%d\n", &n)
    h := make([]int, n)
    for i := 0; i < n; i++ {
        fmt.Scanf("%d", &h[i])
    }

    maxh := 0
    r := make([]int, n)
    for i := n-1; i >= 0; i-- {
        r[i] = max(0, maxh - h[i])
        maxh = max(maxh, h[i]+1)

    }
    fmt.Println(r)
}


A map of some object is a rectangular field consisting of n rows and n columns. Each cell is initially occupied by the sea but you can cover some some cells of the map with sand so that exactly k islands appear on the map. We will call a set of sand cells to be island if it is possible to get from each of them to each of them by moving only through sand cells and by moving from a cell only to a side-adjacent cell. The cells are called to be side-adjacent if they share a vertical or horizontal side. It is easy to see that islands do not share cells (otherwise they together form a bigger island).Find a way to cover some cells with sand so that exactly k islands appear on the n × n map, or determine that no such way exists.

The single line contains two positive integers n, k (1 ≤ n ≤ 100, 0 ≤ k ≤ n2) — the size of the map and the number of islands you should form.

If the answer doesn't exist, print "NO" (without the quotes) in a single line. Otherwise, print "YES" in the first line. In the next n lines print the description of the map. Each of the lines of the description must consist only of characters 'S' and 'L', where 'S' is a cell that is occupied by the sea and 'L' is the cell covered with sand. The length of each line of the description must equal n. If there are multiple answers, you may print any of them. You should not maximize the sizes of islands.

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)

	n, k := nextInt(), nextInt()
	flag := 0

	if n%2 == 0 {
		if n*n/2 < k {
			println("NO")
			return
		}
	} else if n*n/2+1 < k {
		println("NO")
		return
	}

	println("YES")
	for i := 0; i < n; i++ {
		if i%2 == 0 {
			flag = 1
		} else {
			flag = 0
		}

		for j := 0; j < n; j++ {
			if k > 0 && flag == 1 {
				print("L")
				k--
			} else {
				print("S")
			}
			flag = 1 - flag
		}
		println()
	}
}

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 (
  "os"
  "bufio"
  "strconv"
  "fmt"
)

var scanner *bufio.Scanner
var writer *bufio.Writer

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer = bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  n, k := getI(), getI()
  if k > (n*n+1)/2 {
    writer.WriteString("NO\n")
    return
  }
  writer.WriteString("YES\n")
  for r := 0; r < n; r++ {
    for c := 0; c < n; c++ {
      ch := 'S'
      if k > 0 && r%2 == c%2 {
        ch = 'L'
        k--
      }
      writer.WriteString(fmt.Sprintf("%c", ch))
    }
    writer.WriteString("\n")
  }
}

package main

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

var scanner *bufio.Scanner
var writer *bufio.Writer

func getInt64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getInt() int {
  return int(getInt64())
}
func getFloat() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getString() string {
  scanner.Scan()
  return scanner.Text()
}

func solve() {
  dx := []int {1,-1,0,0}
  dy := []int {0,0,1,-1}
  n, k := getInt(), getInt()
  res := make([]string, n)

  for i:=0; i<n; i++ {
    for j:=0; j<n; j++ {
      var have bool
      for q:=0; q<4; q++ {
        x := i + dx[q]
        y := j + dy[q]
        if x>=0 && y>=0 && x<n && y<n && x<=i && y<=j && res[x][y]=='L' {
          have = true
        }
      }
      if !have && k!=0 {
        res[i] += "L"
        k -= 1
      } else {
        res[i] += "S"
      }
    }
  }

  if k!=0 {
    fmt.Println("NO")
  } else {
    fmt.Println("YES")
    for _, val := range res {
      fmt.Println(val)
    }
  }
}

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer = bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  solve()
}

package main

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

var scanner *bufio.Scanner
var writer *bufio.Writer

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer = bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  n, k := getI(), getI()
  if k > (n*n+1)/2 {
    writer.WriteString("NO\n")
    return
  }
  for r := 0; r < n; r++ {
    for c := 0; c < n; c++ {
      ch := 'S'
      if k > 0 && r%2 == c%2 {
        ch = 'L'
        k--
      }
      writer.WriteString(fmt.Sprintf("%c", ch))
    }
    writer.WriteString("\n")
  }
}