You are given the array $$$a$$$ consisting of $$$n$$$ elements and the integer $$$k \le n$$$.You want to obtain at least $$$k$$$ equal elements in the array $$$a$$$. In one move, you can make one of the following two operations:  Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of $$$a$$$ is $$$mn$$$ then you choose such index $$$i$$$ that $$$a_i = mn$$$ and set $$$a_i := a_i + 1$$$);  take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of $$$a$$$ is $$$mx$$$ then you choose such index $$$i$$$ that $$$a_i = mx$$$ and set $$$a_i := a_i - 1$$$). Your task is to calculate the minimum number of moves required to obtain at least $$$k$$$ equal elements in the array.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$ and the required number of equal elements. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

Print one integer — the minimum number of moves required to obtain at least $$$k$$$ equal elements in the array.

package main

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

var reader io.Reader
var scanner *bufio.Scanner

func Init(io io.Reader, max_token_size int) {
	reader = bufio.NewReader(io)
	scanner = bufio.NewScanner(reader)
	// max token size
	scanner.Split(bufio.ScanWords)
	scanner.Buffer([]byte{}, max_token_size)
}

func stderr(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
}

func die(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
	os.Exit(1)
}

func NextInt() int {
	bytes := NextBytes()
	i, err := Atoi(bytes)
	if err != nil {
		die(err)
	}
	return i
}
func NextInt64() int64 {
	bytes := NextBytes()
	i, err := Atoi64(bytes)
	if err != nil {
		die(err)
	}
	return i
}

func NextBytes() []byte {
	if !scanner.Scan() {
		die(scanner.Err())
	}
	bytes := scanner.Bytes()
	copied := make([]byte, len(bytes))
	copy(copied, bytes)
	return copied
}

func Atoi(b []byte) (int, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	n := 0
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func Atoi64(b []byte) (int64, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	var n int64
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int64(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func ExtendByteArray(a []byte, size int) []byte {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]byte, size-len(a))...)
	}
}

func ExtendIntArray(a []int, size int) []int {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]int, size-len(a))...)
	}
}

func reverseInts(a []int) {
	for l, r := 0, len(a)-1; l < r; l, r = l+1, r-1 {
		a[l], a[r] = a[r], a[l]
	}
}

func unique(a []int) int {
	newLen := 0
	n := len(a)
	for i := 0; i < n; i++ {
		if newLen == 0 || a[i] != a[newLen-1] {
			a[newLen] = a[i]
			newLen++
		}
	}
	return newLen
}

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

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

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

func main() {
	inf := os.Stdin
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	// inf, err := os.Open("a.in")
	// if err != nil {
	// 	die(err)
	// }
	// out, err := os.Create("a.out")
	// if err != nil {
	// 	die(err)
	// }
	// defer out.Close()
	Init(inf, 1000010)
	n, k := NextInt(), NextInt()
	a := make([]int, n)
	cnt := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = NextInt()
	}
	sort.Ints(a)

	nl := 0
	for i := 0; i < n; i++ {
		if i == 0 || a[i] != a[i-1] {
			a[nl] = a[i]
			cnt[nl] = 0
			nl++
		}
		cnt[nl-1]++
		if cnt[nl-1] >= k {
			fmt.Fprintln(out, 0)
			return
		}
	}
	n = nl

	leftSum, rightSum := make([]int64, n), make([]int64, n)
	leftCnt, rightCnt := make([]int, n), make([]int, n)
	for i := 0; i < n; i++ {
		if i == 0 {
			leftSum[i] = 0
			leftCnt[i] = cnt[i]
			rightSum[n-i-1] = 0
			rightCnt[n-i-1] = cnt[n-i-1]
		} else {
			leftSum[i] = leftSum[i-1] + int64(a[i]-a[i-1])*int64(leftCnt[i-1])
			leftCnt[i] = leftCnt[i-1] + cnt[i]
			rightSum[n-i-1] = rightSum[n-i] + int64(a[n-i]-a[n-i-1])*int64(rightCnt[n-i])
			rightCnt[n-i-1] = rightCnt[n-i] + cnt[n-i-1]
		}
	}

	var res int64
	res = 1000000000000000000
	// stderr(leftSum)
	// stderr(leftCnt)
	// stderr(rightSum)
	// stderr(rightCnt)
	for i := 0; i < n; i++ {
		var leftsum int64
		leftcount := 0
		dl := 0
		if i > 0 {
			dl = a[i] - a[i-1]
			leftsum = leftSum[i-1]
			leftcount = leftCnt[i-1]
		}
		var rightsum int64
		rightcount := 0
		dr := 0
		if i+1 < n {
			dr = a[i+1] - a[i]
			rightsum = rightSum[i+1]
			rightcount = rightCnt[i+1]
		}
		// stderr("i = ", i, "left", leftcount, leftsum, dl, "right", rightcount, rightsum, dr)
		// stderr(cnt[i])
		if rightcount >= k {
			res = mini64(res, rightsum)
		}
		if leftcount >= k {
			res = mini64(res, leftsum)
		}
		if leftcount+cnt[i] >= k {
			cur := leftsum + int64(k-cnt[i]) + int64(leftcount)*int64(dl-1)
			res = mini64(res, cur)
		}
		if rightcount+cnt[i] >= k {
			cur := rightsum + int64(k-cnt[i]) + int64(rightcount)*int64(dr-1)
			res = mini64(res, cur)
		}
		if leftCnt[i] < k && rightcount >= k-leftCnt[i] {
			cur := leftSum[i] + int64(k-leftCnt[i]) + int64(rightcount)*int64(dr-1) + rightsum
			res = mini64(res, cur)
		}
		if rightCnt[i] < k && leftcount >= k-rightCnt[i] {
			cur := rightSum[i] + int64(k-rightCnt[i]) + int64(leftcount)*int64(dl-1) + leftsum
			res = mini64(res, cur)
		}
	}
	fmt.Fprintln(out, res)
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1328F(_r io.Reader, out io.Writer) {
	min := func(a, b int64) int64 {
		if a < b {
			return a
		}
		return b
	}
	in := bufio.NewReader(_r)
	var n, k int
	Fscan(in, &n, &k)
	a := make([]int, n)
	for i := range a {
		Fscan(in, &a[i])
	}
	sort.Ints(a)
	s := make([]int64, n+1)
	for i, v := range a {
		s[i+1] = s[i] + int64(v)
	}
	ans := int64(1e18)
	for i := 0; i < n; {
		st, v := i, a[i]
		for i++; i < n && a[i] == v; i++ {
		}
		if i-st >= k {
			ans = 0
			break
		}
		if i >= k {
			ss := int64(v-1)*int64(st) - s[st]
			ss += int64(k - i + st)
			ans = min(ans, ss)
		}
		if n-st >= k {
			ss := s[n] - s[i] - int64(v+1)*int64(n-i)
			ss += int64(k - i + st)
			ans = min(ans, ss)
		}
		ss := int64(v-1)*int64(st) - s[st]
		ss += s[n] - s[i] - int64(v+1)*int64(n-i)
		ss += int64(k - i + st)
		ans = min(ans, ss)
	}
	Fprint(out, ans)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1328F(_r io.Reader, out io.Writer) {
	min := func(a, b int64) int64 {
		if a < b {
			return a
		}
		return b
	}
	in := bufio.NewReader(_r)
	var n, k int64
	Fscan(in, &n, &k)
	a := make([]int, n)
	for i := range a {
		Fscan(in, &a[i])
	}
	sort.Ints(a)
	s := make([]int64, n+1)
	for i, v := range a {
		s[i+1] = s[i] + int64(v)
	}
	ans := int64(1e18)
	for i := int64(0); i < n; {
		st := i
		for i++; i < n && a[i] == a[st]; i++ {
		}
		d := k - i + st
		if d <= 0 {
			ans = 0
			break
		}
		v := int64(a[st])
		s1, s2 := (v-1)*st-s[st], s[n]-s[i]-(v+1)*(n-i)
		if i >= k {
			ans = min(ans, s1+d)
		}
		if n-st >= k {
			ans = min(ans, s2+d)
		}
		ans = min(ans, s1+s2+d)
	}
	Fprint(out, ans)
}

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

package main

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

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt() int
	NextInt64() int64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	return &wordScannerImpl{Scanner: s}
}

func (impl *wordScannerImpl) NextInt() int {
	impl.Scan()
	bb := impl.Bytes()
	i := 0
	for _, b := range bb {
		i *= 10
		i += int(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextInt64() int64 {
	impl.Scan()
	bb := impl.Bytes()
	i := int64(0)
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}

var stdin = NewWordScanner(os.Stdin)
var stdout = NewBufferedWriter(os.Stdout)

type Int64Sorter []int64

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

func main() {
	defer stdout.Flush()
	n, k := stdin.NextInt64(), stdin.NextInt64()
	m := map[int64]int64{}
	for i := int64(0); i < n; i++ {
		a := stdin.NextInt64()
		m[a]++
		if m[a] == k {
			stdout.Printf("0\n")
			return
		}
	}
	u := []int64{}
	for v := range m {
		u = append(u, v)
	}
	sort.Sort(Int64Sorter(u))

	solver := &Solver{
		counts: m,
		vals:   u,
		n:      n,
		k:      k,
	}

	stdout.Printf("%d\n", solver.Solve())
}

type Solver struct {
	counts map[int64]int64
	vals   []int64
	n      int64
	k      int64
}

func (s *Solver) Solve() int64 {
	ln := make([]int64, len(s.vals))
	lc := make([]int64, len(s.vals))
	rn := make([]int64, len(s.vals))
	rc := make([]int64, len(s.vals))
	ln[0] = 0
	lc[0] = 0
	rn[len(s.vals)-1] = 0
	rc[len(s.vals)-1] = 0
	for i := 1; i < len(s.vals); i++ {
		ln[i] = ln[i-1] + s.counts[s.vals[i-1]]
		lc[i] = lc[i-1] + (ln[i] * (s.vals[i]-s.vals[i-1]))
	}
	for i := len(s.vals) - 2; i > -1; i-- {
		rn[i] = rn[i+1] + s.counts[s.vals[i+1]]
		rc[i] = rc[i+1] + (rn[i] * (s.vals[i+1]-s.vals[i]))
	}

    minSoFar := lc[0] + rc[0]
    for i := 1; i < len(s.vals); i++ {
        cost := lc[i] + rc[i]
        minSoFar = min(minSoFar, cost)
    }
    if s.n == s.k {
        return minSoFar
    } else {
        minSoFar -= (s.n - s.k)
    }

    var leftRes int64
    for i := 0; i < len(lc); i++ {
        totalSame := ln[i] + s.counts[s.vals[i]]
        if totalSame >= s.k {
            diff := totalSame - s.k
            cost := lc[i]
            leftRes = cost - diff
            break
        }
    }

    var rightRes int64
    for i := len(rc)-1; i > -1; i-- {
        totalSame := rn[i] + s.counts[s.vals[i]]
        if totalSame >= s.k {
            diff := totalSame - s.k
            cost := rc[i]
            rightRes = cost - diff
            break
        }
    }

    return min(minSoFar, leftRes, rightRes)
}

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

package main

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

var reader io.Reader
var scanner *bufio.Scanner

func Init(io io.Reader, max_token_size int) {
	reader = bufio.NewReader(io)
	scanner = bufio.NewScanner(reader)
	// max token size
	scanner.Split(bufio.ScanWords)
	scanner.Buffer([]byte{}, max_token_size)
}

func stderr(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
}

func die(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
	os.Exit(1)
}

func NextInt() int {
	bytes := NextBytes()
	i, err := Atoi(bytes)
	if err != nil {
		die(err)
	}
	return i
}
func NextInt64() int64 {
	bytes := NextBytes()
	i, err := Atoi64(bytes)
	if err != nil {
		die(err)
	}
	return i
}

func NextBytes() []byte {
	if !scanner.Scan() {
		die(scanner.Err())
	}
	bytes := scanner.Bytes()
	copied := make([]byte, len(bytes))
	copy(copied, bytes)
	return copied
}

func Atoi(b []byte) (int, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	n := 0
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func Atoi64(b []byte) (int64, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	var n int64
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int64(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func ExtendByteArray(a []byte, size int) []byte {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]byte, size-len(a))...)
	}
}

func ExtendIntArray(a []int, size int) []int {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]int, size-len(a))...)
	}
}

func reverseInts(a []int) {
	for l, r := 0, len(a)-1; l < r; l, r = l+1, r-1 {
		a[l], a[r] = a[r], a[l]
	}
}

func unique(a []int) int {
	newLen := 0
	n := len(a)
	for i := 0; i < n; i++ {
		if newLen == 0 || a[i] != a[newLen-1] {
			a[newLen] = a[i]
			newLen++
		}
	}
	return newLen
}

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

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

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

func main() {
	inf := os.Stdin
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	// inf, err := os.Open("a.in")
	// if err != nil {
	// 	die(err)
	// }
	// out, err := os.Create("a.out")
	// if err != nil {
	// 	die(err)
	// }
	// defer out.Close()
	Init(inf, 1000010)
	n, k := NextInt(), NextInt()
	a := make([]int, n)
	cnt := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = NextInt()
	}
	sort.Ints(a)

	nl := 0
	for i := 0; i < n; i++ {
		if i == 0 || a[i] != a[i-1] {
			a[nl] = a[i]
			cnt[nl] = 0
			nl++
		}
		cnt[nl-1]++
		if cnt[nl-1] >= k {
			fmt.Fprintln(out, 0)
			return
		}
	}
	n = nl

	leftSum, rightSum := make([]int64, n), make([]int64, n)
	leftCnt, rightCnt := make([]int, n), make([]int, n)
	for i := 0; i < n; i++ {
		if i == 0 {
			leftSum[i] = 0
			leftCnt[i] = cnt[i]
			rightSum[n-i-1] = 0
			rightCnt[n-i-1] = cnt[n-i-1]
		} else {
			leftSum[i] = leftSum[i-1] + int64(a[i]-a[i-1])*int64(leftCnt[i-1])
			leftCnt[i] = leftCnt[i-1] + cnt[i]
			rightSum[n-i-1] = rightSum[n-i] + int64(a[n-i]-a[n-i-1])*int64(rightCnt[n-i])
			rightCnt[n-i-1] = rightCnt[n-i] + cnt[n-i-1]
		}
	}

	var res int64
	res = 1000000000000000000
	// stderr(leftSum)
	// stderr(leftCnt)
	// stderr(rightSum)
	// stderr(rightCnt)
	for i := 0; i < n; i++ {
		var leftsum int64
		leftcount := 0
		dl := 0
		if i > 0 {
			dl = a[i] - a[i-1]
			leftsum = leftSum[i-1]
			leftcount = leftCnt[i-1]
		}
		var rightsum int64
		rightcount := 0
		dr := 0
		if i+1 < n {
			dr = a[i+1] - a[i]
			rightsum = rightSum[i+1]
			rightcount = rightCnt[i+1]
		}
		// stderr("i = ", i, "left", leftcount, leftsum, dl, "right", rightcount, rightsum, dr)
		// stderr(cnt[i])
		if rightcount >= k {
			res = mini64(res, rightsum)
		}
		if leftcount >= k {
			res = mini64(res, leftsum)
		}
		if leftcount+cnt[i] >= k {
			cur := leftsum + int64(k-cnt[i])*int64(dl)
			res = mini64(res, cur)
		}
		if rightcount+cnt[i] >= k {
			cur := rightsum + int64(k-cnt[i])*int64(dr)
			res = mini64(res, cur)
		}
		if leftCnt[i] < k && rightcount >= k-leftCnt[i] {
			cur := leftSum[i] + int64(k-leftCnt[i])*int64(dr) + rightsum
			res = mini64(res, cur)
		}
		if rightCnt[i] < k && leftcount >= k-rightCnt[i] {
			cur := rightSum[i] + int64(k-rightCnt[i])*int64(dl) + leftsum
			res = mini64(res, cur)
		}
	}
	fmt.Fprintln(out, res)
}

package main

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

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt() int
	NextInt64() int64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	return &wordScannerImpl{Scanner: s}
}

func (impl *wordScannerImpl) NextInt() int {
	impl.Scan()
	bb := impl.Bytes()
	i := 0
	for _, b := range bb {
		i *= 10
		i += int(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextInt64() int64 {
	impl.Scan()
	bb := impl.Bytes()
	i := int64(0)
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}

var stdin = NewWordScanner(os.Stdin)
var stdout = NewBufferedWriter(os.Stdout)

type Int64Sorter []int64

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

func main() {
	defer stdout.Flush()
	n, k := stdin.NextInt64(), stdin.NextInt64()
	m := map[int64]int64{}
	for i := int64(0); i < n; i++ {
		a := stdin.NextInt64()
		m[a]++
		if m[a] == k {
			stdout.Printf("0\n")
			return
		}
	}
	u := []int64{}
	for v := range m {
		u = append(u, v)
	}
	sort.Sort(Int64Sorter(u))

	solver := &Solver{
		counts: m,
		vals:   u,
		n:      n,
		k:      k,
	}

	stdout.Printf("%d\n", solver.Solve())
}

type Solver struct {
	counts map[int64]int64
	vals   []int64
	n      int64
	k      int64
}

func (s *Solver) Solve() int64 {
	ln := make([]int64, len(s.vals))
	lc := make([]int64, len(s.vals))
	rn := make([]int64, len(s.vals))
	rc := make([]int64, len(s.vals))
	ln[0] = 0
	lc[0] = 0
	rn[len(s.vals)-1] = 0
	rc[len(s.vals)-1] = 0
	for i := 1; i < len(s.vals); i++ {
		ln[i] = ln[i-1] + s.counts[s.vals[i-1]]
		lc[i] = lc[i-1] + (ln[i] * (s.vals[i]-s.vals[i-1]))
	}
	for i := len(s.vals) - 2; i > -1; i-- {
		rn[i] = rn[i+1] + s.counts[s.vals[i+1]]
		rc[i] = rc[i+1] + (rn[i] * (s.vals[i+1]-s.vals[i]))
	}
	minSoFar := lc[0] + rc[0]
	for i := 1; i < len(s.vals); i++ {
		cost := lc[i] + rc[i]
		minSoFar = min(minSoFar, cost)
	}
	return minSoFar - (s.n-s.k)
}

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

package main

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

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt() int
	NextInt64() int64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	return &wordScannerImpl{Scanner: s}
}

func (impl *wordScannerImpl) NextInt() int {
	impl.Scan()
	bb := impl.Bytes()
	i := 0
	for _, b := range bb {
		i *= 10
		i += int(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextInt64() int64 {
	impl.Scan()
	bb := impl.Bytes()
	i := int64(0)
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}

var stdin = NewWordScanner(os.Stdin)
var stdout = NewBufferedWriter(os.Stdout)

type Int64Sorter []int64

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

func main() {
	defer stdout.Flush()
	n, k := stdin.NextInt64(), stdin.NextInt64()
	m := map[int64]int64{}
	for i := int64(0); i < n; i++ {
		a := stdin.NextInt64()
		m[a]++
		if m[a] == k {
			stdout.Printf("0\n")
			return
		}
	}
	u := []int64{}
	for v := range m {
		u = append(u, v)
	}
	sort.Sort(Int64Sorter(u))

	solver := &Solver{
		counts: m,
		vals:   u,
		n:      n,
		k:      k,
	}

	stdout.Printf("%d\n", solver.Solve())
}

type Solver struct {
	counts map[int64]int64
	vals   []int64
	n      int64
	k      int64
}

func (s *Solver) Solve() int64 {
	ln := make([]int64, len(s.vals))
	lc := make([]int64, len(s.vals))
	rn := make([]int64, len(s.vals))
	rc := make([]int64, len(s.vals))
	ln[0] = 0
	lc[0] = 0
	rn[len(s.vals)-1] = 0
	rc[len(s.vals)-1] = 0
	for i := 1; i < len(s.vals); i++ {
		ln[i] = ln[i-1] + s.counts[s.vals[i-1]]
		lc[i] = lc[i-1] + ln[i]
	}
	for i := len(s.vals) - 2; i > -1; i-- {
		rn[i] = rn[i+1] + s.counts[s.vals[i+1]]
		rc[i] = rc[i+1] + rn[i]
	}
	minSoFar := lc[0] + rc[0]
	for i := 1; i < len(s.vals); i++ {
		cost := lc[i] + rc[i]
		minSoFar = min(minSoFar, cost)
	}
	return minSoFar - (s.n-s.k)
}

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


You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.

The first line contains two integers n, m (1 ≤ n, m ≤ 2·105) — the sizes of arrays a and b. The second line contains n integers — the elements of array a ( - 109 ≤ ai ≤ 109). The third line contains m integers — the elements of array b ( - 109 ≤ bj ≤ 109).

Print m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value bj.

package main

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

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

func Print(args ...interface{})                 { out.WriteString(fmt.Sprint(args...)) }
func Printf(format string, args ...interface{}) { out.WriteString(fmt.Sprintf(format, args...)) }
func Println(args ...interface{})               { out.WriteString(fmt.Sprintln(args...)) }

func Scan(args ...interface{})   { fmt.Fscan(in, args...) }
func Scanln(args ...interface{}) { fmt.Fscanln(in, args...) }

func main() {
	defer out.Flush()

	var n, m int
	Scan(&n, &m)
	arr := make([]int, n)
	brr := make([]int, m)
	for i := 0; i < n; i++ {
		Scan(&arr[i])
	}
	for i := 0; i < m; i++ {
		Scan(&brr[i])
	}
	sort.Ints(arr)
	for i, s := range brr {
		left := 0
		right := n - 1
		for {
			if left >= n {
				break
			}
			if arr[left] > s {
				break
			}
			mid := (left + right) / 2
			if arr[mid] <= s {
				left = mid + 1
				continue
			}
			right = mid
		}

		Print(left)
		if i != m-1 {
			Print(" ")
		}
	}
	Print("\n")
}

package main

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

func main() {
	var n, m int
	fmt.Scanf("%d %d\n", &n, &m)
	sc := bufio.NewScanner(os.Stdin)
	sc.Buffer(make([]byte, 1024), 12*2*10e5)
	a := scanArray(sc, n)
	b := scanArray(sc, m)
	sort.Sort(sort.IntSlice(a))
	for j, v := range b {
		i := sort.Search(len(a), func(i int) bool {
			if a[i] > v {
				return true
			}
			return false
		})
		b[j] = i
	}
	for _, i := range b {
		fmt.Print(i, " ")
	}
}

func scanArray(sc *bufio.Scanner, n int) []int {
	a := make([]int, n)
	if sc.Scan() {
		tmp := sc.Text()
		for i, s := range strings.Fields(tmp) {
			in, err := strconv.Atoi(s)
			if err != nil {
				fmt.Println(err)
			}
			a[i] = in
		}
	}
	if err := sc.Err(); err != nil {
		fmt.Println(err)
	}
	return a
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Buffer(make([]byte, int(math.Pow(10,8))), int(math.Pow(10, 8)))

	scanner.Scan()
	nmStr := scanner.Text()
	nmArr := strings.Split(nmStr, " ")
	n, _ := strconv.Atoi(nmArr[0])
	m, _ := strconv.Atoi(nmArr[1])

	scanner.Scan()
	aStr := scanner.Text()
	aStrArr := strings.Split(aStr, " ")
	aArr := make([]int, len(aStrArr))
	for idx := 0; idx < n; idx++ {
		aArr[idx], _ = strconv.Atoi(aStrArr[idx])
	}
	sort.Ints(aArr)

	scanner.Scan()
	bStr := scanner.Text()
	bStrArr := strings.Split(bStr, " ")
	bArrIdx := make([][]int, len(bStrArr))
	for idx := 0; idx < m; idx++ {
		b, _ := strconv.Atoi(bStrArr[idx])
		bArrIdx[idx] = []int{b, idx}
	}
	sort.Slice(bArrIdx, func(i, j int) bool {
		return bArrIdx[i][0] < bArrIdx[j][0]
	})

	resp := make([]int, m)

	if len(bArrIdx) == 0 {
		fmt.Println()
	}
	currIdx := sort.SearchInts(aArr, bArrIdx[0][0])
	for currIdx < n && bArrIdx[0][0] == aArr[currIdx] {
		currIdx++
	}
	resp[bArrIdx[0][1]] = currIdx

	for idx := 1; idx < len(bArrIdx); idx++ {
		for currIdx < n && bArrIdx[idx][0] >= aArr[currIdx] {
			currIdx++
		}
		resp[bArrIdx[idx][1]] = currIdx
	}

	for idx := range resp {
		fmt.Printf("%v ", resp[idx])
	}
	fmt.Println()
}

package main

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

//N _
const (
	N = 2*1e5 + 5
)

func upperBound(array []int, target int) int {
	low, high, mid := 0, len(array)-1, 0

	for low <= high {
		mid = (low + high) / 2
		if array[mid] > target {
			high = mid - 1
		} else {
			low = mid + 1
		}
	}
	return low
}

func inputter(inputReader *bufio.Reader,strs chan *string){
	for {
		input , _ := inputReader.ReadString('\n')
		input = strings.TrimSpace(input)
		if len(input) > 0 {
			inputs := strings.Split(input, " ")
			for i := range inputs{
				strs <- &inputs[i]
			}
		}
	}
}

func main(){
	rs := bufio.NewReader(os.Stdin)
	ws := bufio.NewWriter(os.Stdout)

	strs := make(chan *string, 100)

	go inputter(rs, strs)

	n , _ := strconv.ParseInt(*<-strs, 10, 32)
	m , _ := strconv.ParseInt(*<-strs, 10, 32)

	a := make([]int, 0, N)

	for i := 0; i < int(n); i++ {
		x, _ := strconv.ParseInt(*<-strs, 10, 32)
		a = append(a, int(x))
	}

	sort.Ints(a)

	for i := 0; i < int(m); i++ {
		x, _ := strconv.ParseInt(*<-strs, 10, 32)
		ws.WriteString(fmt.Sprint(upperBound(a, int(x))) + " ")
	}

	ws.Flush()
}

package main

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

func main() {
	var n, m int
	fmt.Scanf("%d %d\n", &n, &m)
	sc := bufio.NewScanner(os.Stdin)
	a := scanArray(sc, n)
	b := scanArray(sc, m)
	sort.Sort(sort.IntSlice(a))
	for j, v := range b {
		i := sort.Search(len(a), func(i int) bool {
			if a[i] > v {
				return true
			}
			return false
		})
		b[j] = i
	}
	for _, i := range b {
		fmt.Print(i, " ")
	}
}

func scanArray(sc *bufio.Scanner, n int) []int {
	a := make([]int, n)
	if sc.Scan() {
		tmp := sc.Text()
		for i, s := range strings.Fields(tmp) {
			in, err := strconv.Atoi(s)
			if err != nil {
				fmt.Println(err)
			}
			a[i] = in
		}
	}
	if err := sc.Err(); err != nil {
		fmt.Println(err)
	}
	return a
}

package main

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

func main() {
	var n, m int
	fmt.Scanf("%d %d\n", &n, &m)
	sc := bufio.NewScanner(os.Stdin)
	sc.Buffer(make([]byte, 4096), 100*2*10^5)
	a := scanArray(sc, n)
	b := scanArray(sc, m)
	sort.Sort(sort.IntSlice(a))
	for j, v := range b {
		i := sort.Search(len(a), func(i int) bool {
			if a[i] > v {
				return true
			}
			return false
		})
		b[j] = i
	}
	for _, i := range b {
		fmt.Print(i, " ")
	}
}

func scanArray(sc *bufio.Scanner, n int) []int {
	a := make([]int, n)
	if sc.Scan() {
		tmp := sc.Text()
		for i, s := range strings.Fields(tmp) {
			in, err := strconv.Atoi(s)
			if err != nil {
				fmt.Println(err)
			}
			a[i] = in
		}
	}
	if err := sc.Err(); err != nil {
		fmt.Println(err)
	}
	return a
}

package main

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

func main() {
	var n, m int
	fmt.Scanf("%d %d\n", &n, &m)
	sc := bufio.NewScanner(os.Stdin)
	sc.Buffer(make([]byte, 4096), 2*10^5*4)
	a := scanArray(sc, n)
	b := scanArray(sc, m)
	sort.Sort(sort.IntSlice(a))
	for j, v := range b {
		i := sort.Search(len(a), func(i int) bool {
			if a[i] > v {
				return true
			}
			return false
		})
		b[j] = i
	}
	for _, i := range b {
		fmt.Print(i, " ")
	}
}

func scanArray(sc *bufio.Scanner, n int) []int {
	a := make([]int, n)
	if sc.Scan() {
		tmp := sc.Text()
		for i, s := range strings.Fields(tmp) {
			in, err := strconv.Atoi(s)
			if err != nil {
				fmt.Println(err)
			}
			a[i] = in
		}
	}
	if err := sc.Err(); err != nil {
		fmt.Println(err)
	}
	return a
}

package main

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

func main() {
	var n, m int
	fmt.Scanf("%d %d\n", &n, &m)
	sc := bufio.NewScanner(os.Stdin)
	sc.Buffer(make([]byte, 4096), 2*10^5*12)
	a := scanArray(sc, n)
	b := scanArray(sc, m)
	sort.Sort(sort.IntSlice(a))
	for j, v := range b {
		i := sort.Search(len(a), func(i int) bool {
			if a[i] > v {
				return true
			}
			return false
		})
		b[j] = i
	}
	for _, i := range b {
		fmt.Print(i, " ")
	}
}

func scanArray(sc *bufio.Scanner, n int) []int {
	a := make([]int, n)
	if sc.Scan() {
		tmp := sc.Text()
		for i, s := range strings.Fields(tmp) {
			in, err := strconv.Atoi(s)
			if err != nil {
				fmt.Println(err)
			}
			a[i] = in
		}
	}
	if err := sc.Err(); err != nil {
		fmt.Println(err)
	}
	return a
}

package main

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

func main() {
	var n, m int
	fmt.Scanf("%d %d\n", &n, &m)
	sc := bufio.NewScanner(os.Stdin)
	c := 2*10 ^ 5*12
	sc.Buffer(make([]byte, c), c)
	a := scanArray(sc, n)
	b := scanArray(sc, m)
	sort.Sort(sort.IntSlice(a))
	for j, v := range b {
		i := sort.Search(len(a), func(i int) bool {
			if a[i] > v {
				return true
			}
			return false
		})
		b[j] = i
	}
	for _, i := range b {
		fmt.Print(i, " ")
	}
}

func scanArray(sc *bufio.Scanner, n int) []int {
	a := make([]int, n)
	if sc.Scan() {
		tmp := sc.Text()
		for i, s := range strings.Fields(tmp) {
			in, err := strconv.Atoi(s)
			if err != nil {
				fmt.Println(err)
			}
			a[i] = in
		}
	}
	if err := sc.Err(); err != nil {
		fmt.Println(err)
	}
	return a
}

package main

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

func main() {
	var n, m int
	fmt.Scanf("%d %d\n", &n, &m)
	sc := bufio.NewScanner(os.Stdin)
	sc.Buffer(make([]byte, 4096), 2*10^5*11)
	a := scanArray(sc, n)
	b := scanArray(sc, m)
	sort.Sort(sort.IntSlice(a))
	for j, v := range b {
		i := sort.Search(len(a), func(i int) bool {
			if a[i] > v {
				return true
			}
			return false
		})
		b[j] = i
	}
	for _, i := range b {
		fmt.Print(i, " ")
	}
}

func scanArray(sc *bufio.Scanner, n int) []int {
	a := make([]int, n)
	if sc.Scan() {
		tmp := sc.Text()
		for i, s := range strings.Fields(tmp) {
			in, err := strconv.Atoi(s)
			if err != nil {
				fmt.Println(err)
			}
			a[i] = in
		}
	}
	if err := sc.Err(); err != nil {
		fmt.Println(err)
	}
	return a
}

package main

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

func main() {
	var n, m int
	fmt.Scanf("%d %d\n", &n, &m)
	sc := bufio.NewScanner(os.Stdin)
	sc.Buffer(make([]byte, 4096), 12*2*10^5)
	a := scanArray(sc, n)
	b := scanArray(sc, m)
	sort.Sort(sort.IntSlice(a))
	for j, v := range b {
		i := sort.Search(len(a), func(i int) bool {
			if a[i] > v {
				return true
			}
			return false
		})
		b[j] = i
	}
	for _, i := range b {
		fmt.Print(i, " ")
	}
}

func scanArray(sc *bufio.Scanner, n int) []int {
	a := make([]int, n)
	if sc.Scan() {
		tmp := sc.Text()
		for i, s := range strings.Fields(tmp) {
			in, err := strconv.Atoi(s)
			if err != nil {
				fmt.Println(err)
			}
			a[i] = in
		}
	}
	if err := sc.Err(); err != nil {
		fmt.Println(err)
	}
	return a
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Buffer([]byte{}, int(math.Pow(10, 6)))

	scanner.Scan()
	nmStr := scanner.Text()
	nmArr := strings.Split(nmStr, " ")
	n, _ := strconv.Atoi(nmArr[0])
	m, _ := strconv.Atoi(nmArr[1])

	scanner.Scan()
	aStr := scanner.Text()
	aStrArr := strings.Split(aStr, " ")
	aArr := make([]int, len(aStrArr))
	for idx := 0; idx < n; idx++ {
		aArr[idx], _ = strconv.Atoi(aStrArr[idx])
	}
	sort.Ints(aArr)

	scanner.Scan()
	bStr := scanner.Text()
	bStrArr := strings.Split(bStr, " ")
	bArrIdx := make([][]int, len(bStrArr))
	for idx := 0; idx < m; idx++ {
		b, _ := strconv.Atoi(bStrArr[idx])
		bArrIdx[idx] = []int{b, idx}
	}
	sort.Slice(bArrIdx, func(i, j int) bool {
		return bArrIdx[i][0] < bArrIdx[j][0]
	})

	resp := make([]int, m)

	if len(bArrIdx) == 0 {
		fmt.Println()
	}
	currIdx := sort.SearchInts(aArr, bArrIdx[0][0])
	for currIdx < n && bArrIdx[0][0] == aArr[currIdx] {
		currIdx++
	}
	resp[bArrIdx[0][1]] = currIdx

	for idx := 1; idx < len(bArrIdx); idx++ {
		for currIdx < n && bArrIdx[idx][0] >= aArr[currIdx] {
			currIdx++
		}
		resp[bArrIdx[idx][1]] = currIdx
	}

	var respBuilder strings.Builder
	for idx := range resp {
		respBuilder.WriteByte(byte(resp[idx]+48))
		respBuilder.WriteString(" ")
	}
	respStr := respBuilder.String()
	fmt.Println(respStr[:len(respStr)-1])
}

package main

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

//N _
const (
	N = 2*1e5 + 5
)

func readOneLineInts(inputreader *bufio.Reader, n int) (res chan int) {
	res = make(chan int, N)
	go func() {
		input, _ :=	inputreader.ReadString('\n')
		ints := strings.Split(strings.TrimSpace(input), " ")
		for i := range ints{
			x, _ := strconv.ParseInt(ints[i],10,32)
			res <- int(x)
		}
		close(res)
	}()

	return
}

func upperBound(array []int, target int) int {
	low, high, mid := 0, len(array)-1, 0

	for low <= high {
		mid = (low + high) / 2
		if array[mid] > target {
			high = mid - 1
		} else {
			low = mid + 1
		}
	}
	return low
}

func main(){
	rs := bufio.NewReader(os.Stdin)
	ws := bufio.NewWriter(os.Stdout)

	ch := readOneLineInts(rs, 2);

	n := <- ch
	m := <- ch

	ch1 := readOneLineInts(rs, int(n));
	ch2 := readOneLineInts(rs, int(m));

	a := make([]int, 0, N)

	for x := range ch1{
		a = append(a, x)
	}

	sort.Ints(a)

	for x := range ch2{
		ws.WriteString(fmt.Sprint(upperBound(a, x)) + " ")
	}

	ws.Flush()
}

package main

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

//N _
const (
	N = 2*1e5 + 5
)

func upperBound(array []int, target int) int {
	low, high, mid := 0, len(array)-1, 0

	for low <= high {
		mid = (low + high) / 2
		if array[mid] > target {
			high = mid - 1
		} else {
			low = mid + 1
		}
	}
	return low
}

func inputter(inputReader *bufio.Reader,strs chan *string){
	for {
		input , _ := inputReader.ReadString('\n')
		input = strings.TrimSpace(input)
		if len(input) > 0 {
			inputs := strings.Split(input, " ")
			for i := range inputs{
				strs <- &inputs[i]
			}
		}
	}
}

func main(){
	rs := bufio.NewReader(os.Stdin)
	ws := bufio.NewWriter(os.Stdout)

	strs := make(chan *string, 100)

	go inputter(rs, strs)

	n , _ := strconv.ParseInt(*<-strs, 10, 32)
	m , _ := strconv.ParseInt(*<-strs, 10, 32)

	a := make([]int, 0, N)

	for i := 0; i < int(n); i++ {
		x, _ := strconv.ParseInt(*<-strs, 10, 32)
		a = append(a, int(x))
	}

	sort.Ints(a)

	fmt.Println("sorted:", a)

	for i := 0; i < int(m); i++ {
		x, _ := strconv.ParseInt(*<-strs, 10, 32)
		ws.WriteString(fmt.Sprint(upperBound(a, int(x))) + " ")
	}

	ws.Flush()
}


Vasya has a string $$$s$$$ of length $$$n$$$. He decides to make the following modification to the string:   Pick an integer $$$k$$$, ($$$1 \leq k \leq n$$$).  For $$$i$$$ from $$$1$$$ to $$$n-k+1$$$, reverse the substring $$$s[i:i+k-1]$$$ of $$$s$$$. For example, if string $$$s$$$ is qwer and $$$k = 2$$$, below is the series of transformations the string goes through:   qwer (original string)  wqer (after reversing the first substring of length $$$2$$$)  weqr (after reversing the second substring of length $$$2$$$)  werq (after reversing the last substring of length $$$2$$$)  Hence, the resulting string after modifying $$$s$$$ with $$$k = 2$$$ is werq. Vasya wants to choose a $$$k$$$ such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of $$$k$$$. Among all such $$$k$$$, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds:   $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$;  in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

Each test contains multiple test cases.  The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 5000$$$). The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the length of the string $$$s$$$. The second line of each test case contains the string $$$s$$$ of $$$n$$$ lowercase latin letters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$.

For each testcase output two lines: In the first line output the lexicographically smallest string $$$s'$$$ achievable after the above-mentioned modification.  In the second line output the appropriate value of $$$k$$$ ($$$1 \leq k \leq n$$$) that you chose for performing the modification. If there are multiple values of $$$k$$$ that give the lexicographically smallest string, output the smallest value of $$$k$$$ among them.

6
4
abab
6
qwerty
5
aaaaa
6
alaska
9
lfpbavjsm
1
p

abab
1
ertyqw
3
aaaaa
1
aksala
6
avjsmbpfl
5
p
1

NoteIn the first testcase of the first sample, the string modification results for the sample abab are as follows :   for $$$k = 1$$$ : abab  for $$$k = 2$$$ : baba  for $$$k = 3$$$ : abab  for $$$k = 4$$$ : babaThe lexicographically smallest string achievable through modification is abab for $$$k = 1$$$ and $$$3$$$. Smallest value of $$$k$$$ needed to achieve is hence $$$1$$$.

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := int64(1)
	fmt.Fscanf(in, "%d\n", &t)
	for tt := int64(0); tt < t; tt++ {
		n := 0
		fmt.Fscanf(in, "%d\n", &n)
		s := ""
		fmt.Fscanf(in, "%s\n", &s)
		ans := s
		best := 1
		for i := 1; i < n; i++ {
			newS := []byte(s[i:])
			for j := 0; j < i; j++ {
				k := j
				if (n-i)%2 == 0 {
					k = j
				} else {
					k = i - k - 1
				}
				newS = append(newS, s[k])
			}
			if string(newS) < ans {
				ans = string(newS)
				best = i + 1
			}
		}
		fmt.Fprintf(out, "%s\n", ans)
		fmt.Fprintf(out, "%d\n", best)

	}
	return
}

func getAns1(n, x, y int) int {
	p := x - 1
	q := n - y - 1
	if q > 0 {
		p -= q
		if p < 0 {
			p = 0
		}
		return p + 1
	} else if q == 0 {
		return x
	} else {
		ans1 := x + 1
		if ans1 > n {
			ans1 = n
		}
		return ans1
	}

}

func getAns2(n, x, y int) int {
	q := y - 1
	ans2 := x + q
	if ans2 > n {
		ans2 = n
	}
	return ans2
}

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
}

// yun xu you better ge geng haode ren
func ok1(n, x, y, better int) bool {
	if better < (x - 1) {
		return can1(n-better, x-better, y-better)
	} else {
		return true
	}
}

// can be no1
func can1(n, x, y int) bool {
	if (x + y) < 1+n {
		return true
	}
	return false
}

package main

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

var reader io.Reader
var scanner *bufio.Scanner

func Init(io io.Reader, max_token_size int) {
	reader = bufio.NewReader(io)
	scanner = bufio.NewScanner(reader)
	// max token size
	scanner.Split(bufio.ScanWords)
	scanner.Buffer([]byte{}, max_token_size)
}

func stderr(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
}

func die(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
	os.Exit(1)
}

func NextInt() int {
	bytes := NextBytes()
	i, err := Atoi(bytes)
	if err != nil {
		die(err)
	}
	return i
}
func NextInt64() int64 {
	bytes := NextBytes()
	i, err := Atoi64(bytes)
	if err != nil {
		die(err)
	}
	return i
}

func NextBytes() []byte {
	if !scanner.Scan() {
		die(scanner.Err())
	}
	bytes := scanner.Bytes()
	copied := make([]byte, len(bytes))
	copy(copied, bytes)
	return copied
}

func Atoi(b []byte) (int, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	n := 0
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func Atoi64(b []byte) (int64, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	var n int64
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int64(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func ExtendByteArray(a []byte, size int) []byte {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]byte, size-len(a))...)
	}
}

func ExtendIntArray(a []int, size int) []int {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]int, size-len(a))...)
	}
}

func reverseInts(a []int) {
	for l, r := 0, len(a)-1; l < r; l, r = l+1, r-1 {
		a[l], a[r] = a[r], a[l]
	}
}

func unique(a []int) int {
	newLen := 0
	n := len(a)
	for i := 0; i < n; i++ {
		if newLen == 0 || a[i] != a[newLen-1] {
			a[newLen] = a[i]
			newLen++
		}
	}
	return newLen
}

// var fst, last int
// var nxt, prev []int
// var ch []byte

// func pushBack(i int, char byte) {
// 	prv[i] = last
// 	ch[i] = char
// 	nxt[i] = -1
// 	if last >= 0 {
// 		nxt[last] = i
// 	}
// 	last = i
// }

func main() {
	inf := os.Stdin
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	// inf, err := os.Open("a.in")
	// if err != nil {
	// 	die(err)
	// }
	// out, err := os.Create("a.out")
	// if err != nil {
	// 	die(err)
	// }
	// defer out.Close()
	Init(inf, 1000010)

	T := NextInt()
	// nxt = make([]int, 5000)
	// prv = make([]int, 5000)
	// ch = make([]byte, 5000)
	res := make([]byte, 5001)
	curr := make([]byte, 5001)

	for t := 0; t < T; t++ {
		n := NextInt()
		s := NextBytes()
		var resK int
		for k := 1; k <= n; k++ {
			for i := k - 1; i < n; i++ {
				curr[i-k+1] = s[i]
			}

			rotated := (n-(k-1))%2 == 1
			if rotated {
				for i := 0; i < k-1; i++ {
					// stderr("ass")
					curr[n-(k-1)+i] = s[k-1-i-1]
				}
			} else {
				for i := 0; i < k-1; i++ {
					// stderr("ass")
					curr[n-(k-1)+i] = s[i]
				}
			}
			// stderr("check", string(curr))
			if k == 1 || string(curr[:n]) < string(res[:n]) {
				// stderr("yeah!")
				copy(res[:n], curr[:n])
				resK = k
			}
		}

		fmt.Fprintln(out, string(res[:n]))
		fmt.Fprintln(out, resK)
	}
}

package main

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

func main() {
	var cases int
	fmt.Scanf("%d\n", &cases)
	reader := bufio.NewReader(os.Stdin)
	for i := 0; i < cases; i++ {
		line := readLine(reader)
		n, _ := strconv.Atoi(string(line))
		str := readLine(reader)
		// fmt.Println(cases, n, str)
		k, s := 1, string(str)
		for j := 2; j <= n; j++ {
			sss := make([]byte, n)
			copy(sss, str)
			temp := reverseS(sss, j)
			if temp < s {
				k = j
				s = temp
			}
		}
		fmt.Println(s)
		fmt.Println(k)
	}
}

func reverseS(str []byte, k int) string {
	// if k == len(str) {
	// 	s := make([]byte, 0)
	// 	for i:=len(str)-1;i>=0;i-- {
	// 		s = append(s, str[i])
	// 	}
	// 	return string(s)
	// }
	first := str[k-1:]
	second := make([]byte, 0)
	if (len(str)-k+1) % 2 == 1 { // 奇数反转
		for i:=k-2;i>=0;i--{
			second = append(second, str[i])
		}
		return string(first) + string(second)
	}
	return string(first) + string(str[:k-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 {
			break
		}
	}
	return result
}

/*
URL:
https://codeforces.com/problemset/problem/1316/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
	n int
	S []rune
)

func main() {
	t = ReadInt()
	for i := 0; i < t; i++ {
		n = ReadInt()
		S = ReadRuneSlice()

		solve()
	}
}

func solve() {
	// C := []Candidate{}

	mini := "{{{{{{}}}}}}"
	ans := 0

	for k := 1; k <= n; k++ {
		bef := []rune{}
		for i := k - 1; i < n; i++ {
			bef = append(bef, S[i])
		}
		aft := []rune{}
		for i := 0; i < k-1; i++ {
			aft = append(aft, S[i])
		}

		if (n-k+1)%2 == 1 {
			aft = Reverse(aft)
		}

		tmp := []rune{}
		tmp = append(tmp, bef...)
		tmp = append(tmp, aft...)

		// obj := Candidate{S: tmp, k: k}
		// C = append(C, obj)

		if mini > string(tmp) {
			mini = string(tmp)
			ans = k
		}
	}

	// sort.SliceStable(C, func(i, j int) bool {
	// 	if string(C[i].S) < string(C[j].S) {
	// 		return true
	// 	} else if string(C[i].S) > string(C[j].S) {
	// 		return false
	// 	} else {
	// 		return C[i].k < C[j].k
	// 	}
	// })
	// fmt.Println(string(C[0].S))
	// fmt.Println(C[0].k)

	fmt.Println(mini)
	fmt.Println(ans)
}

type Candidate struct {
	S []rune
	k int
}

func Reverse(A []rune) []rune {
	res := []rune{}

	n := len(A)
	for i := n - 1; i >= 0; i-- {
		res = append(res, A[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 (
	"bufio"
	. "fmt"
	"io"
	"os"
)

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

	var t, n int
	var s, ss string
	Fscan(in, &t)
	for ; t > 0; t-- {
		Fscan(in, &n, &s)
		minS := s
		k := 1
		for i := 1; i < n; i++ {
			if (n-i)%2 == 1 {
				ss = s[i:] + reverse(s[:i])
			} else {
				ss = s[i:] + s[:i]
			}
			if ss < minS {
				minS = ss
				k = i + 1
			}
		}
		Fprintln(out, minS)
		Fprintln(out, k)
	}
}

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

package main

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

func main() {

	for t := ScanInt(); t > 0; t-- {
		n := ScanInt()
		s := ScanWord()

		c := []class{}
		for k := 1; k <= n; k++ {
			c = append(c, class{Str: krev(s, k), K: k})
		}
		sort.Slice(c, func(i, j int) bool {
			if c[i].Str < c[j].Str {
				return true
			} else if c[i].Str > c[j].Str {
				return false
			} else {
				return c[i].K < c[j].K
			}
		})
		P(c[0].Str)
		P(c[0].K)
	}

	close(O)
	oWg.Wait()
}

type class struct {
	Str string
	K   int
}

func krev(s string, k int) string {
	right := s[k-1:]
	left := s[:k-1]

	r := right
	if len(s)%2 == k%2 {
		r = r + rev(left)
	} else {
		r = r + left
	}
	return r
}
func rev(str string) string {
	s := []byte(str)
	n := len(s)
	for i := 0; i < n/2; i++ {
		s[i], s[n-i-1] = s[n-i-1], s[i]
	}
	return string(s)
}

/*********************** 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(1e+9))
	in.Split(bufio.ScanWords)

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

	writer := bufio.NewWriter(os.Stdout)
	go func() {
		defer oWg.Done()
		defer writer.Flush()

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

func ScanWord() string { in.Scan(); return in.Text() }
func ScanInt() int     { i, _ := strconv.Atoi(ScanWord()); return i }
func ScanInt64() int64 { i, _ := strconv.ParseInt(ScanWord(), 10, 64); return i }
func ScanStringSlice(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ScanWord()
	}
	return s
}
func ScanIntSlice(n int) []int {
	arr := make([]int, n)
	for i := 0; i < n; i++ {
		arr[i] = ScanInt()
	}
	return arr
}
func ScanInt64Slice(n int) []int64 {
	arr := make([]int64, n)
	for i := 0; i < n; i++ {
		arr[i] = ScanInt64()
	}
	return arr
}

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

func S(v interface{}) string { return fmt.Sprintf("%v", v) }
func SArr(a []int) string {
	sb := strings.Builder{}
	sb.Grow(len(a) * 9)
	for i := range a {
		sb.WriteString(strconv.Itoa(a[i]) + " ")
	}
	return sb.String()
}
func SArr64(a []int64) string {
	sb := strings.Builder{}
	sb.Grow(len(a) * 9)
	for i := range a {
		sb.WriteString(strconv.FormatInt(a[i], 10) + " ")
	}
	return sb.String()
}
func MnMx(args ...byte) (byte, byte) {
	minVal, maxVal := args[0], args[0]
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
		if v > maxVal {
			maxVal = v
		}
	}
	return minVal, maxVal
}
func Mn(args ...byte) byte { mn, _ := MnMx(args...); return mn }
func Mx(args ...byte) byte { _, mx := MnMx(args...); return mx }
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 sortInt64Slice(a []int64) { sort.Slice(a, func(i, j int) bool { return a[i] < a[j] }) }
func abs(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

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 main() {
  defer writer.Flush()
  var n, t int
  scanf("%d\n", &n)
  var s string
  for i := 0; i < n; i++ {
    scanf("%d\n", &t)
    scanf("%s\n", &s)
    solve(s)
  }
}

func solve(s string) {
  var min byte = 'z'
  start := []int{}
  resS, resK := s, 1
  for i := range s {
    if s[i] < min {
      min = s[i]
      start = []int{i}
    } else if s[i] == min {
      start = append(start, i)
    }
  }
  for _, i := range start {
    res := flip(s, i)
    if res < resS {
      resS, resK = res, i+1
    }
  }
  printf("%s\n%d\n", resS, resK)
}

func flip(s string, i int) string {
  res := s[i:] + s[:i]

  if (len(s)-i)%2 == 1 {
    l, r := len(s)-i, len(s)-1
    b := []byte(res)
    for l < r {
      b[l], b[r] = b[r], b[l]
      l++
      r--
    }
    return string(b)
  } else {
    return res
  }
}

package main

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

func main() {

	for t := scanInt(); t > 0; t-- {
		lengthOfString := scanInt()
		actualString := scanString()
		answerInt := 1
		answerString := actualString
		for i := 2; i <= lengthOfString; i++ {
			subString := actualString[0 : i-1]
			if (lengthOfString-i)%2 == 0 {
				subString = reverseString(subString)
			}

			if actualString[i-1 : lengthOfString] +  subString < answerString {
				answerString = actualString[i-1 : lengthOfString] +  subString
				answerInt = i
			}

		}
		fmt.Println(answerString)
		fmt.Println(answerInt)
	}

	close(channelType)
	oWg.Wait()
}

func reverseString(str string) string {
	s := []byte(str)
	n := len(s)
	for i := 0; i < n/2; i++ {
		s[i], s[n-i-1] = s[n-i-1], s[i]
	}
	return string(s)
}

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

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

func init() {
	printFmt = fmt.Println

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

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

	writer := bufio.NewWriter(os.Stdout)
	go func() {
		defer oWg.Done()
		defer writer.Flush()

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

func scanString() string {in.Scan(); return in.Text() }
func scanInt() int {i, _ := strconv.Atoi(scanString()); return i}
func scanInt64() int64 {i, _ := strconv.ParseInt(scanString(), 10, 64); return i}
func scanStringSlice(n int) []string {s := make([]string, n); for i := 0; i < n; i++ {s[i] = scanString()}; return s}
func scanIntSlice(n int) []int {arr := make([]int, n); for i := 0; i < n; i++ {arr[i] = scanInt()}; return arr}
func scanInt64Slice(n int) []int64 {arr := make([]int64, n); for i := 0; i < n; i++ {arr[i] = scanInt64()}; return arr}

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

func stringEquivalent(v interface{}) string {return fmt.Sprintf("%v", v)}
func spaceSeperatedStringFromArray(a []int) string {sb := strings.Builder{}; sb.Grow(len(a) * 9); for i := range a {sb.WriteString(strconv.Itoa(a[i]) + " ")}; return sb.String()}
func spaceSeperatedStringFromArray64(a []int64) string {sb := strings.Builder{}; sb.Grow(len(a) * 9); for i := range a {sb.WriteString(strconv.FormatInt(a[i], 10) + " ")}; return sb.String()}
func minMaxFromArray(args ...int64) (int64, int64) {minVal, maxVal := int64(math.MaxInt64), int64(math.MinInt64); for _, v := range args {if v < minVal {minVal = v}; if v > maxVal {maxVal = v}}; return minVal, maxVal}
func minElementFromArray(args ...int64) int64 { mn, _ := minMaxFromArray(args...); return mn }
func maxElementFromArray(args ...int64) int64 { _, mx := minMaxFromArray(args...); return mx }
func lcmCalculation(a, b int64) int64 {return a / gcdCalculation(a, b) * b}
func gcdCalculation(a, b int64) int64 {if (a == 0) {return b}; return gcdCalculation(b%a, a)}
func sortInt64Slice(a []int64) {sort.Slice(a, func(i, j int) bool { return a[i] < a[j] })}
func absoluteValue(x int64) int64 {if x < 0 {return -x}; return x}

package main

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

func main() {

	for t := scanInt(); t > 0; t-- {
		lengthOfString := scanInt()
		actualString := scanString()
		answerInt := 1
		answerString := actualString
		for i := 2; i <= lengthOfString; i++ {
			firstSubString := actualString[i-1 : lengthOfString]
			secondSubString := actualString[0 : i-1]

			if (lengthOfString-i)%2 == 0 {
				secondSubString = reverseString(secondSubString)
			}
			//
			firstSubString += secondSubString

			if firstSubString < answerString {
				answerString = firstSubString
				answerInt = i
			}

		}
		fmt.Println(answerString)
		fmt.Println(answerInt)
	}

	close(channelType)
	oWg.Wait()
}

func reverseString(str string) string {
	s := []byte(str)
	n := len(s)
	for i := 0; i < n/2; i++ {
		s[i], s[n-i-1] = s[n-i-1], s[i]
	}
	return string(s)
}

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

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

func init() {
	printFmt = fmt.Println

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

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

	writer := bufio.NewWriter(os.Stdout)
	go func() {
		defer oWg.Done()
		defer writer.Flush()

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

func scanString() string {in.Scan(); return in.Text() }
func scanInt() int {i, _ := strconv.Atoi(scanString()); return i}
func scanInt64() int64 {i, _ := strconv.ParseInt(scanString(), 10, 64); return i}
func scanStringSlice(n int) []string {s := make([]string, n); for i := 0; i < n; i++ {s[i] = scanString()}; return s}
func scanIntSlice(n int) []int {arr := make([]int, n); for i := 0; i < n; i++ {arr[i] = scanInt()}; return arr}
func scanInt64Slice(n int) []int64 {arr := make([]int64, n); for i := 0; i < n; i++ {arr[i] = scanInt64()}; return arr}

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

func stringEquivalent(v interface{}) string {return fmt.Sprintf("%v", v)}
func spaceSeperatedStringFromArray(a []int) string {sb := strings.Builder{}; sb.Grow(len(a) * 9); for i := range a {sb.WriteString(strconv.Itoa(a[i]) + " ")}; return sb.String()}
func spaceSeperatedStringFromArray64(a []int64) string {sb := strings.Builder{}; sb.Grow(len(a) * 9); for i := range a {sb.WriteString(strconv.FormatInt(a[i], 10) + " ")}; return sb.String()}
func minMaxFromArray(args ...int64) (int64, int64) {minVal, maxVal := int64(math.MaxInt64), int64(math.MinInt64); for _, v := range args {if v < minVal {minVal = v}; if v > maxVal {maxVal = v}}; return minVal, maxVal}
func minElementFromArray(args ...int64) int64 { mn, _ := minMaxFromArray(args...); return mn }
func maxElementFromArray(args ...int64) int64 { _, mx := minMaxFromArray(args...); return mx }
func lcmCalculation(a, b int64) int64 {return a / gcdCalculation(a, b) * b}
func gcdCalculation(a, b int64) int64 {if (a == 0) {return b}; return gcdCalculation(b%a, a)}
func sortInt64Slice(a []int64) {sort.Slice(a, func(i, j int) bool { return a[i] < a[j] })}
func absoluteValue(x int64) int64 {if x < 0 {return -x}; return x}

package main

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

func main() {

	for t := scanInt(); t > 0; t-- {
		lengthOfString := scanInt()
		actualString := scanString()
		answerInt := 1
		answerString := actualString
		for i := 2; i <= lengthOfString; i++ {
			firstSubString := actualString[i-1 : lengthOfString]
			secondSubString := actualString[0 : i-1]

			if (lengthOfString-i)%2 == 0 {
				secondSubString = reverseString(secondSubString)
			}
			//
			firstSubString += secondSubString

			if firstSubString < answerString {
				answerString = firstSubString
				answerInt = i
			}

		}
		fmt.Println(answerString)
		fmt.Println(answerInt)
	}

	close(channelType)
	oWg.Wait()
}

func reverseString(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)
}

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

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

func init() {
	printFmt = fmt.Println

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

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

	writer := bufio.NewWriter(os.Stdout)
	go func() {
		defer oWg.Done()
		defer writer.Flush()

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

func scanString() string {in.Scan(); return in.Text() }
func scanInt() int {i, _ := strconv.Atoi(scanString()); return i}
func scanInt64() int64 {i, _ := strconv.ParseInt(scanString(), 10, 64); return i}
func scanStringSlice(n int) []string {s := make([]string, n); for i := 0; i < n; i++ {s[i] = scanString()}; return s}
func scanIntSlice(n int) []int {arr := make([]int, n); for i := 0; i < n; i++ {arr[i] = scanInt()}; return arr}
func scanInt64Slice(n int) []int64 {arr := make([]int64, n); for i := 0; i < n; i++ {arr[i] = scanInt64()}; return arr}

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

func stringEquivalent(v interface{}) string {return fmt.Sprintf("%v", v)}
func spaceSeperatedStringFromArray(a []int) string {sb := strings.Builder{}; sb.Grow(len(a) * 9); for i := range a {sb.WriteString(strconv.Itoa(a[i]) + " ")}; return sb.String()}
func spaceSeperatedStringFromArray64(a []int64) string {sb := strings.Builder{}; sb.Grow(len(a) * 9); for i := range a {sb.WriteString(strconv.FormatInt(a[i], 10) + " ")}; return sb.String()}
func minMaxFromArray(args ...int64) (int64, int64) {minVal, maxVal := int64(math.MaxInt64), int64(math.MinInt64); for _, v := range args {if v < minVal {minVal = v}; if v > maxVal {maxVal = v}}; return minVal, maxVal}
func minElementFromArray(args ...int64) int64 { mn, _ := minMaxFromArray(args...); return mn }
func maxElementFromArray(args ...int64) int64 { _, mx := minMaxFromArray(args...); return mx }
func lcmCalculation(a, b int64) int64 {return a / gcdCalculation(a, b) * b}
func gcdCalculation(a, b int64) int64 {if (a == 0) {return b}; return gcdCalculation(b%a, a)}
func sortInt64Slice(a []int64) {sort.Slice(a, func(i, j int) bool { return a[i] < a[j] })}
func absoluteValue(x int64) int64 {if x < 0 {return -x}; return x}

package main

import (
	"fmt"
)
func reversestring(s string) string{
	chars := []rune(s)
	for i, j :=0, len(s)-1; i < j; i, j = i + 1, j - 1{
		chars[i], chars[j] = chars[j], chars[i]
	}
	return string(chars)
}

func remake(s string, j int) string{
	chars := []rune(s)
	charFirst := chars[:j]
	charSecond := chars[j:]
	if len(charSecond) % 2 != 0{
		return string(charSecond) + reversestring(string(charFirst))
	} else {
		return string(charSecond) + string(charFirst)
	}
}

func main() {
	var n, ansk int
	fmt.Scanf("%d\n", &n)
	for i:=0 ; i < n; i++{
		var l int
		fmt.Scanf("%d\n", &l)
		var s string
		fmt.Scanf("%s\n", &s)
		var ans = s
		ansk = 1
		for j := 1; j < l; j++{
			var tmp = remake(s, j)
			if (tmp < ans) {
				ans = tmp
				ansk = j + 1
			}
		}
		fmt.Println(ans)
		fmt.Println(ansk)
	}
	//var s string = "qwerty"
	//var ans = s
	//ansk := 1
	//l := 5
	//for j := 2; j < l; j++{
	//	var tmp = remake(s, j)
	//	if (tmp < ans) {
	//		ans = tmp
	//		ansk = j + 1
	//	}
	//}
	//fmt.Println(ans)
	//fmt.Println(ansk)
}

package main

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

func reverseString(s string) string {
	runes := []rune(s)
	for from, to := 0, len(runes)-1; from < to; from, to = from+1, to-1 {
		runes[from], runes[to] = runes[to], runes[from]
	}
	return string(runes)
}

func main() {
	for t := ReadInt(); t > 0; t-- {
		n := ReadInt()
		s := ReadString()
		ans := s
		var k int =0
		for i := 0; i < n; i++ {
			tmp1 := s[i:n]
			tmp2 := s[0:i]
			if (n-i)%2 == 1 {
				tmp2=reverseString(tmp2)
			}
			tmp1 += tmp2
			if tmp1 < ans {
				ans = tmp1
				k = i
			}
		}
		fmt.Println(ans)
		fmt.Println(k + 1)
	}
}

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

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

var out chan string
var in *bufio.Scanner
var outWg *sync.WaitGroup

func ReadString() string {
	in.Scan()
	return in.Text()
}
func ReadStringSlice(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ReadString()
	}
	return s
}
func ReadInt() int {
	intStr := ReadString()
	i, _ := strconv.ParseInt(intStr, 10, 32)
	return int(i)
}
func ReadIntSlice(n int) []int {
	arr := make([]int, n)
	for i := 0; i < n; i++ {
		arr[i] = ReadInt()
	}
	return arr
}
func init() {
	//set input
	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(2e+5))
	in.Split(bufio.ScanWords)

	//set output
	out = make(chan string, 16)
	outWg = &sync.WaitGroup{}
	outWg.Add(1)

	writer := bufio.NewWriterSize(os.Stdout, int(2e+5))
	go func(write *bufio.Writer) {
		defer outWg.Done()
		defer write.Flush()

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

package main

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

func main() {
	var cases int
	fmt.Scanf("%d\n", &cases)
	reader := bufio.NewReader(os.Stdin)
	for i := 0; i < cases; i++ {
		line := readLine(reader)
		n, _ := strconv.Atoi(string(line))
		str := readLine(reader)
		// fmt.Println(cases, n, str)
		k, s := 1, string(str)
		for j := 2; j <= n; j++ {
			sss := make([]byte, n)
			copy(sss, str)
			temp := reverseS(sss, j)
			if temp < s {
				k = j
				s = temp
			}
		}
		fmt.Println(s)
		fmt.Println(k)
	}
}

func reverseS(str []byte, k int) string {
	first := str[k-1:]
	second := make([]byte, 0)
	if (len(str)-k+1) % 2 == 1 { // 奇数反转
		for i:=k-1;i>=0;i--{
			second = append(second, str[i])
		}
		return string(first) + string(second)
	}
	return string(first) + string(str[0:k-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 {
			break
		}
	}
	return result
}

package main

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

func main() {

	for t := ScanInt(); t > 0; t-- {
		n := ScanInt()
		s := ScanWord()

		c := []class{}
		for k := 1; k <= n; k++ {
			c = append(c, class{Str: krev(s, k), K: k})
		}
		sort.Slice(c, func(i, j int) bool {
			if c[i].Str < c[j].Str {
				return true
			} else if c[i].Str > c[j].Str {
				return false
			} else {
				return c[i].K < c[j].K
			}
		})
		P(c[0].K)
		P(c[0].Str)
	}

	close(O)
	oWg.Wait()
}

type class struct {
	Str string
	K   int
}

func krev(s string, k int) string {
	right := s[k-1:]
	left := s[:k-1]

	r := right
	if len(s)%2 == k%2 {
		r = r + rev(left)
	} else {
		r = r + left
	}
	return r
}
func rev(str string) string {
	s := []byte(str)
	n := len(s)
	for i := 0; i < n/2; i++ {
		s[i], s[n-i-1] = s[n-i-1], s[i]
	}
	return string(s)
}

/*********************** 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(1e+9))
	in.Split(bufio.ScanWords)

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

	writer := bufio.NewWriter(os.Stdout)
	go func() {
		defer oWg.Done()
		defer writer.Flush()

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

func ScanWord() string { in.Scan(); return in.Text() }
func ScanInt() int     { i, _ := strconv.Atoi(ScanWord()); return i }
func ScanInt64() int64 { i, _ := strconv.ParseInt(ScanWord(), 10, 64); return i }
func ScanStringSlice(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ScanWord()
	}
	return s
}
func ScanIntSlice(n int) []int {
	arr := make([]int, n)
	for i := 0; i < n; i++ {
		arr[i] = ScanInt()
	}
	return arr
}
func ScanInt64Slice(n int) []int64 {
	arr := make([]int64, n)
	for i := 0; i < n; i++ {
		arr[i] = ScanInt64()
	}
	return arr
}

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

func S(v interface{}) string { return fmt.Sprintf("%v", v) }
func SArr(a []int) string {
	sb := strings.Builder{}
	sb.Grow(len(a) * 9)
	for i := range a {
		sb.WriteString(strconv.Itoa(a[i]) + " ")
	}
	return sb.String()
}
func SArr64(a []int64) string {
	sb := strings.Builder{}
	sb.Grow(len(a) * 9)
	for i := range a {
		sb.WriteString(strconv.FormatInt(a[i], 10) + " ")
	}
	return sb.String()
}
func MnMx(args ...byte) (byte, byte) {
	minVal, maxVal := args[0], args[0]
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
		if v > maxVal {
			maxVal = v
		}
	}
	return minVal, maxVal
}
func Mn(args ...byte) byte { mn, _ := MnMx(args...); return mn }
func Mx(args ...byte) byte { _, mx := MnMx(args...); return mx }
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 sortInt64Slice(a []int64) { sort.Slice(a, func(i, j int) bool { return a[i] < a[j] }) }
func abs(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

package main

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

func main() {
	for t := ScanInt(); t > 0; t-- {
		n := ScanInt()
		s := []byte(ScanWord())
		sCopy := s
		sarr := make([]string, 0, n)
		for i := 0; i < len(s)-1; i++ {

			sarr = append(sarr, string(s[i:]))
		}

		minI := 0
		minV := strings.Repeat("z", n)
		//P(sarr)
		for i := 0; i < len(s) - 1; i++ {
			if sarr[i] < minV {
				minI = i
				minV = sarr[i]
			}
		}

		// alabka
		// a
		//P("minI:", string(s[minI]), minI)

		right := s[minI:]
		left := []byte{}

		if len(right)%2 == 0 {
			left = s[:minI]
		} else {
			left = rev(s[:minI])
		}

		//P("left", string(left))
		//P("right", string(right))

		result := append(right, left...)

		sb := strings.Builder{}
		for i := 0; i < len(result); i++ {
			sb.WriteByte(result[i])
		}
		resultFInal := sb.String()

		revStrig := string(rev(sCopy))

		if resultFInal < revStrig {
			P(sb.String())
			P(minI + 1)
		} else {
			P(revStrig)
			P(n)
		}

	}

	close(O)
	oWg.Wait()
}

func rev(s []byte) []byte {
	n := len(s)
	for i := 0; i < n/2; i++ {
		s[i], s[n-i-1] = s[n-i-1], s[i]
	}
	return s
}

/*********************** 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(1e+9))
	in.Split(bufio.ScanWords)

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

	writer := bufio.NewWriter(os.Stdout)
	go func() {
		defer oWg.Done()
		defer writer.Flush()

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

func ScanWord() string { in.Scan(); return in.Text() }
func ScanInt() int     { i, _ := strconv.Atoi(ScanWord()); return i }
func ScanInt64() int64 { i, _ := strconv.ParseInt(ScanWord(), 10, 64); return i }
func ScanStringSlice(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ScanWord()
	}
	return s
}
func ScanIntSlice(n int) []int {
	arr := make([]int, n)
	for i := 0; i < n; i++ {
		arr[i] = ScanInt()
	}
	return arr
}
func ScanInt64Slice(n int) []int64 {
	arr := make([]int64, n)
	for i := 0; i < n; i++ {
		arr[i] = ScanInt64()
	}
	return arr
}

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

func S(v interface{}) string { return fmt.Sprintf("%v", v) }
func SArr(a []int) string {
	sb := strings.Builder{}
	sb.Grow(len(a) * 9)
	for i := range a {
		sb.WriteString(strconv.Itoa(a[i]) + " ")
	}
	return sb.String()
}
func SArr64(a []int64) string {
	sb := strings.Builder{}
	sb.Grow(len(a) * 9)
	for i := range a {
		sb.WriteString(strconv.FormatInt(a[i], 10) + " ")
	}
	return sb.String()
}
func MnMx(args ...byte) (byte, byte) {
	minVal, maxVal := args[0], args[0]
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
		if v > maxVal {
			maxVal = v
		}
	}
	return minVal, maxVal
}
func Mn(args ...byte) byte { mn, _ := MnMx(args...); return mn }
func Mx(args ...byte) byte { _, mx := MnMx(args...); return mx }
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 sortInt64Slice(a []int64) { sort.Slice(a, func(i, j int) bool { return a[i] < a[j] }) }
func abs(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

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 main() {
  defer writer.Flush()
  var n, t int
  scanf("%d\n", &n)
  var s string
  for i := 0; i < n; i++ {
    scanf("%d\n", &t)
    scanf("%s\n", &s)
    solve(s)
  }
}

func solve(s string) {
  var min byte = 'z'
  start := []int{}
  resS, resK := s, 1
  for i := range s {
    if s[i] < min {
      min = s[i]
      start = []int{i}
    } else if s[i] == min {
      start = append(start, i)
    }
  }
  for _, i := range start {
    res := flip(s, i)
    if res < resS {
      resS, resK = res, i+1
    }
  }
  printf("%s\n%d\n", resS, resK)
}

func flip(s string, i int) string {
  res := s[i:] + s[:i]
  if (len(s)-i)%2 == 1 {
    l, r := i, len(s)-1
    b := []byte(res)
    for l < r {
      b[l], b[r] = b[r], b[l]
      l++
      r--
    }
    return string(b)
  } else {
    return res
  }
}

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 main() {
  defer writer.Flush()
  var n, t int
  scanf("%d\n", &n)
  var s string
  for i := 0; i < n; i++ {
    scanf("%d\n", &t)
    scanf("%s\n", &s)
    solve(s)
  }
}

func solve(s string) {
  var min byte = 'z'
  start := []int{}
  resS, resK := s, 1
  for i := range s {
    if s[i] < min {
      min = s[i]
      start = []int{i}
    } else if s[i] == min {
      start = append(start, i)
    }
  }
  for _, i := range start {
    res := flip(s, i)
    if res < resS {
      resS, resK = res, i+1
    }
  }
  printf("%s\n%d\n", resS, resK)
}

func flip(s string, i int) string {
  res := s[i:] + s[:i]

  if i%2 == 1 {
    l, r := len(s)-i, len(s)-1
    b := []byte(res)
    for l < r {
      b[l], b[r] = b[r], b[l]
      l++
      r--
    }
    return string(b)
  } else {
    return res
  }
}

package main

import (
	"fmt"
)
func reversestring(s string) string{
	chars := []rune(s)
	for i, j :=0, len(s)-1; i < j; i, j = i + 1, j - 1{
		chars[i], chars[j] = chars[j], chars[i]
	}
	return string(chars)
}

func remake(s string, j int) string{
	chars := []rune(s)
	charFirst := chars[:j]
	charSecond := chars[j:]
	if j % 2 != 0{
		return string(charSecond) + reversestring(string(charFirst))
	} else {
		return string(charSecond) + string(charFirst)
	}
}

func main() {
	var n, ansk int
	fmt.Scanf("%d\n", &n)
	for i:=0 ; i < n; i++{
		var l int
		fmt.Scanf("%d\n", &l)
		var s string
		fmt.Scanf("%s\n", &s)
		var ans = s
		ansk = 1
		for j := 2; j < l; j++{
			var tmp = remake(s, j)
			if (tmp < ans) {
				ans = tmp
				ansk = j + 1
			}
		}
		fmt.Println(ans)
		fmt.Println(ansk)
	}
	//var s string = "qwerty"
	//var ans = s
	//ansk := 1
	//l := 5
	//for j := 2; j < l; j++{
	//	var tmp = remake(s, j)
	//	if (tmp < ans) {
	//		ans = tmp
	//		ansk = j + 1
	//	}
	//}
	//fmt.Println(ans)
	//fmt.Println(ansk)
}

package main

import (
	"fmt"
)
func reversestring(s string) string{
	chars := []rune(s)
	for i, j :=0, len(s)-1; i < j; i, j = i + 1, j - 1{
		chars[i], chars[j] = chars[j], chars[i]
	}
	return string(chars)
}

func remake(s string, j int) string{
	chars := []rune(s)
	charFirst := chars[:j]
	charSecond := chars[j:]
	if len(charSecond) % 2 != 0{
		return string(charSecond) + reversestring(string(charFirst))
	} else {
		return string(charSecond) + string(charFirst)
	}
}

func main() {
	var n, ansk int
	fmt.Scanf("%d\n", &n)
	for i:=0 ; i < n; i++{
		var l int
		fmt.Scanf("%d\n", &l)
		var s string
		fmt.Scanf("%s\n", &s)
		var ans = s
		ansk = 1
		for j := 2; j < l; j++{
			var tmp = remake(s, j)
			if (tmp < ans) {
				ans = tmp
				ansk = j + 1
			}
		}
		fmt.Println(ans)
		fmt.Println(ansk)
	}
	//var s string = "qwerty"
	//var ans = s
	//ansk := 1
	//l := 5
	//for j := 2; j < l; j++{
	//	var tmp = remake(s, j)
	//	if (tmp < ans) {
	//		ans = tmp
	//		ansk = j + 1
	//	}
	//}
	//fmt.Println(ans)
	//fmt.Println(ansk)
}

package main

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

func reverseString(s string) string {
	runes := []rune(s)
	for from, to := 0, len(runes)-1; from < to; from, to = from+1, to-1 {
		runes[from], runes[to] = runes[to], runes[from]
	}
	return string(runes)
}

func main() {
	for t := ReadInt(); t > 0; t-- {
		n := ReadInt()
		s := ReadString()
		ans := s
		var k int
		for i := 0; i < n; i++ {
			tmp1 := s[i:]
			tmp2 := s[0:i]
			if (n-i)&1 == 1 {
				reverseString(tmp2)
			}
			tmp1 += tmp2
			if tmp1 < ans {
				ans = tmp1
				k = i
			}
		}
		fmt.Println(ans)
		fmt.Println(k + 1)
	}
}

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

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

var out chan string
var in *bufio.Scanner
var outWg *sync.WaitGroup

func ReadString() string {
	in.Scan()
	return in.Text()
}
func ReadStringSlice(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ReadString()
	}
	return s
}
func ReadInt() int {
	intStr := ReadString()
	i, _ := strconv.ParseInt(intStr, 10, 32)
	return int(i)
}
func ReadIntSlice(n int) []int {
	arr := make([]int, n)
	for i := 0; i < n; i++ {
		arr[i] = ReadInt()
	}
	return arr
}
func init() {
	//set input
	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(2e+5))
	in.Split(bufio.ScanWords)

	//set output
	out = make(chan string, 16)
	outWg = &sync.WaitGroup{}
	outWg.Add(1)

	writer := bufio.NewWriterSize(os.Stdout, int(2e+5))
	go func(write *bufio.Writer) {
		defer outWg.Done()
		defer write.Flush()

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