Let's define the following recurrence: $$$$$$a_{n+1} = a_{n} + minDigit(a_{n}) \cdot maxDigit(a_{n}).$$$$$$Here $$$minDigit(x)$$$ and $$$maxDigit(x)$$$ are the minimal and maximal digits in the decimal representation of $$$x$$$ without leading zeroes. For examples refer to notes.Your task is calculate $$$a_{K}$$$ for given $$$a_{1}$$$ and $$$K$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of independent test cases. Each test case consists of a single line containing two integers $$$a_{1}$$$ and $$$K$$$ ($$$1 \le a_{1} \le 10^{18}$$$, $$$1 \le K \le 10^{16}$$$) separated by a space.

For each test case print one integer $$$a_{K}$$$ on a separate line.

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

var (
	wg sync.WaitGroup
	res map[int]int64
	mut sync.Mutex
)

func mul_has0(v int64) (int64, bool) {
	_min, _max := int64(9), int64(0)
	for v != 0 {
		dig := v % 10
		if dig == 0 {
			return 0, true
		}
		if dig < _min {
			_min = dig
		}
		if dig > _max {
			_max = dig
		}
		v = (v-dig)/10
	}
	return _min*_max, false
}

func Algo(a, n int64, id int) {
	for i := int64(1); i < n; i++ {
		addV, has0 := mul_has0(a)
		if (has0) {
			break
		}
		a = a + addV
	}
	mut.Lock()
	res[id] = a
	wg.Done()
	mut.Unlock()
}

func main() {
	sc.Split(bufio.ScanWords)
	// code
	var (
		a, n int64
	)
	t := nextInt()
	res = make(map[int]int64)
	//loop
	for i := 0; i < t; i++ {
		wg.Add(1)
		a, n = nextInt64(), nextInt64()
		go Algo(a, n, i)
	}
	wg.Wait()
	for i := 0; i < t; i++ {
		fmt.Println(res[i])
	}
}

// -*-*-*-*-*-*-*-*-
// * I/O utilities *
// -*-*-*-*-*-*-*-*-
var sc = bufio.NewScanner(os.Stdin)

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

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

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

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

func nextInts(n int) []int {
	ret := make([]int, n)
	for i := 0; i < n; i++ {
		ret[i] = nextInt()
	}
	return ret
}
func nextFloats(n int) []float64 {
	ret := make([]float64, n)
	for i := 0; i < n; i++ {
		ret[i] = nextFloat64()
	}
	return ret
}
func nextStrings(n int) []string {
	ret := make([]string, n)
	for i := 0; i < n; i++ {
		ret[i] = next()
	}
	return ret
}

func split(s string) []string {
	ret := make([]string, len([]rune(s)))
	for i, v := range []rune(s) {
		ret[i] = string(v)
	}
	return ret
}

package main
import (
	"fmt"
	"sync"
)

var (
	wg sync.WaitGroup
	res map[int]int64
	mut sync.Mutex
)

func min_c(v int64) int64 {
	var res int64 = 9
	for v != 0 {
		dig := v % 10
		if res > dig {
			res = dig
		}
		v = (v-dig)/10
	}
	return res
}
func max_c(v int64) int64 {
	var res int64 = 0
	for v != 0 {
		dig := v % 10
		if res < dig {
			res = dig
		}
		v = (v-dig)/10
	}
	return res
}
func has_0(v int64) bool {
	for v != 0 {
		dig := v % 10
		if dig == 0 {
			return true
		}
		v = (v-dig)/10
	}
	return false
}

func Algo(a, n int64, id int) {
	for i := int64(1); i < n; i++ {
		if has_0(a) {
			break
		}
		a = a + min_c(a)*max_c(a)
	}
	mut.Lock()
	res[id] = a
	wg.Done()
	mut.Unlock()
}

func main() {
	var (
		a, n int64
		t int
	)
	fmt.Scanf("%d\n", &t)
	res = make(map[int]int64)
	//loop
	for i := 0; i < t; i++ {
		wg.Add(1)
		fmt.Scanf("%d %d\n", &a, &n)
		go Algo(a, n, i)
	}
	wg.Wait()
	for i := 0; i < t; i++ {
		fmt.Println(res[i])
	}
}

package main
import (
	"fmt"
)

func min_c(v int64) int64 {
	var res int64 = 9
	for v != 0 {
		dig := v % 10
		if res > dig {
			res = dig
		}
		v = (v-dig)/10
	}
	return res
}
func max_c(v int64) int64 {
	var res int64 = 0
	for v != 0 {
		dig := v % 10
		if res < dig {
			res = dig
		}
		v = (v-dig)/10
	}
	return res
}
func has_0(v int64) bool {
	for v != 0 {
		dig := v % 10
		if dig == 0 {
			return true
		}
		v = (v-dig)/10
	}
	return false
}

func main() {
	var (
		a, n int64
		t int
	)
	fmt.Scanf("%d\n", &t)
	for i := 0; i < t; i++ {
		fmt.Scanf("%d %d\n", &a, &n)
		for i := int64(1); i < n; i++ {
			if has_0(a) {
				break
			}
			a = a + min_c(a)*max_c(a)
		}
		fmt.Println(a)
	}
}

package main
import (
	"fmt"
	"sync"
)

var (
	wg sync.WaitGroup
	res map[int]int64
	mut sync.Mutex
)

func mul_has0(v int64) (int64, bool) {
	_min, _max := int64(9), int64(0)
	for v != 0 {
		dig := v % 10
		if dig == 0 {
			return 0, true
		}
		if dig < _min {
			_min = dig
		}
		if dig > _max {
			_max = dig
		}
		v = (v-dig)/10
	}
	return _min*_max, false
}

func Algo(a, n int64, id int) {
	for i := int64(1); i < n; i++ {
		addV, has0 := mul_has0(a)
		if (has0) {
			break
		}
		a = a + addV
	}
	mut.Lock()
	res[id] = a
	wg.Done()
	mut.Unlock()
}

func main() {
	var (
		a, n int64
		t int
	)
	fmt.Scanf("%d\n", &t)
	res = make(map[int]int64)
	//loop
	for i := 0; i < t; i++ {
		wg.Add(1)
		fmt.Scanf("%d %d\n", &a, &n)
		go Algo(a, n, i)
	}
	wg.Wait()
	for i := 0; i < t; i++ {
		fmt.Println(res[i])
	}
}

package main

import (
	"fmt"
)

func MinMax(number int64) (int64, int64) {
	var minNum, maxNum = number % 10, number % 10
	var ost int64
	for number > 0 {
		ost = number % 10
		if ost > maxNum {
			maxNum = ost
		}
		if ost < minNum {
			minNum = ost
		}
		number /= 10
	}
	return minNum, maxNum
}

func main() {
	var t int
	_, _ = fmt.Scan(&t)
	for ; t > 0; t-- {
		var a1, K int64
		_, _ = fmt.Scan(&a1, &K)
		K--
	outer:
		for ; K > 0; K-- {
			min, max := MinMax(a1)
			a1 += min * max
			checkNum := a1
			for checkNum > 0 {
				if checkNum%10 == 0 {
					break outer
				}
				checkNum /= 10
			}
		}
		fmt.Println(a1)
	}
}

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++ {
		a1, k := int64(0), int64(0)
		fmt.Fscanf(in, "%d %d\n", &a1, &k)
		final := false
		for !final && k > 1 {
			o := minDigit(a1)
			p := maxDigit(a1)
			if o*p == 0 {
				final = true
			}
			a1 += o * p
			k--
		}
		fmt.Fprintf(out, "%d\n", a1)
	}
	return
}

func minDigit(a int64) int64 {
	ans := a % 10
	for a > 0 {
		ans = min(ans, a%10)
		a /= 10
	}
	return ans
}

func maxDigit(a int64) int64 {
	ans := a % 10
	for a > 0 {
		ans = max(ans, a%10)
		a /= 10
	}
	return ans
}

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

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

package main

import (
	"fmt"
)

func minD(x int64) int64 {
	var ans int64 = 9
	for x > 0 {
		if ans > x % 10 {
			ans = x % 10
		}
		x /= 10
	}
	return ans
}

func maxD(x int64) int64 {
	var ans int64
	for x > 0 {
		if ans < x % 10 {
			ans = x % 10
		}
		x /= 10
	}
	return ans
}

func solve() int64 {
	var a, k int64
	fmt.Scan(&a, &k)
	for i := int64(1); i < k; i++ {
		if minD(a) == 0 {
			return a
		}
		a += minD(a) * maxD(a)
	}
	return a
}

func main() {
	var t int
	fmt.Scan(&t)
	for i := 1; i <= t; i++ {
		fmt.Println(solve())
	}
}

// https://codeforces.com/contest/1353/problem/A
package main

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
var input io.Reader

func main() {
	var (
		T int
	)

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &T)
	for i := 0; i < T; i++ {
		solver()
	}
}

func solver() {
	var n, k int64
	fmt.Fscan(input, &n, &k)
	ans := n
	for k > 1 {
		v := ans
		dx := int64(10)
		dm := int64(0)
		for v > 0 {
			d := v - (v/10)*10
			dm = max(dm, d)
			dx = min(dx, d)
			v/=10
		}
		if dx*dm == 0 {
			break
		}
		ans += dx*dm
		k--
	}
	fmt.Println(ans)
}

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

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 i := int64(0); i < t; i++ {
		a, k := int64(0), int64(0)
		fmt.Fscanf(in, "%d %d\n", &a, &k)
		final := false
		for !final && k > 1 {
			min, max := findMinMax(a)
			a += min * max
			if min * max == 0 {
				final = true
			}
			k--
		}
		fmt.Fprintf(out, "%d\n", a)
	}
}

func findMinMax(i int64) (int64, int64) {
	min, max := int64(-1), int64(-1)
	for i > 0 {
		v := i % 10
		if min == -1 || min > v {
			min = v
		}
		if max == -1 || max < v {
			max = v
		}
		i /= 10
	}

	return min, max
}

/*
URL:
https://codeforces.com/problemset/problem/1355/A
*/

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, k int64
)

func main() {
	t = ReadInt()
	for i := 0; i < t; i++ {
		a, k = ReadInt64_2()

		solve()
	}
}

func solve() {
	cur := a
	for i := int64(0); i < k-1; i++ {
		mini, maxi := sub(cur)
		if mini == 0 {
			fmt.Println(cur)
			return
		}

		cur = cur + mini*maxi
	}
	fmt.Println(cur)
}

func sub(a int64) (mini, maxi int64) {
	S := []rune(strconv.FormatInt(a, 10))
	A := []int64{}
	for _, r := range S {
		A = append(A, int64(r-'0'))
	}

	mini, maxi = Min(A...), Max(A...)

	return mini, maxi
}

// Min returns the min integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Min(integers ...int64) int64 {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

// Max returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Max(integers ...int64) int64 {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

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

/*********** 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"
	"math"
	"os"
	"sort"
	"strconv"
	"strings"
	"sync"
)

func main() {
	for t := ScanInt(); t > 0; t-- {
		a1, k := ScanInt64(), ScanInt64()

		for k > 1 {
			k--
			diff := sum(a1)
			if diff == 0 {
				break
			}
			a1 += diff
		}
		P(a1)
	}

	close(O)
	oWg.Wait()
}
func sum(n int64) int64 {
	digits := []int64{}
	for n > 0 {
		digits = append(digits, n%10)
		n /= 10
	}
	mn, mx := MnMx(digits...)

	return mn * mx
}

/*********************** 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 ...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 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"
	"math"
	"os"
	"sort"
	"strconv"
)

func main() {
	for t := ScanInt(); t > 0; t-- {
		a1, k := ScanInt64(), ScanInt64()

		for k > 1 {
			k--
			diff := sum(a1)
			if diff == 0 {
				break
			}
			a1 += diff
		}
		P(a1)
	}

	out.Flush()
}
func sum(n int64) int64 {
	digits := []int{}
	for n > 0 {
		digits = append(digits, int(n%10))
		n /= 10
	}
	mn, mx := MnMx(digits...)

	return int64(mn * mx)
}

/*********************** I/O ***********************/
var in *bufio.Scanner
var out *bufio.Writer

func init() {
	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(1e+9))
	in.Split(bufio.ScanWords)
	out = bufio.NewWriter(os.Stdout)
}

func P(args ...interface{}) {
	print("\n", args...)
}

func PS(args ...interface{}) {
	print(" ", args...)
	out.WriteByte('\n')
}

func print(seperator string, args ...interface{}) {
	for _, arg := range args {
		str := ""
		switch v := arg.(type) {
		case byte:
			str = string(v)
		case rune:
			str = string(v)
		case int:
			str = strconv.Itoa(v)
		case int64:
			str = strconv.FormatInt(v, 10)
		case string:
			str = v
		}
		out.WriteString(str + seperator)
	}
}

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

/*********************** Utils int64 ***********************/
func MnMx64(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 Mn64(args ...int64) int64 { mn, _ := MnMx64(args...); return mn }
func Mx64(args ...int64) int64 { _, mx := MnMx64(args...); return mx }
func LCM64(a, b int64) int64   { return a / GCD64(a, b) * b }
func GCD64(a, b int64) int64 {
	if a == 0 {
		return b
	}
	return GCD64(b%a, a)
}
func SortInt64Slice(a []int64) { sort.Slice(a, func(i, j int) bool { return a[i] < a[j] }) }
func Abs64(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

/*********************** Utils int ***********************/
func MnMx(args ...int) (int, int) {
	minVal, maxVal := math.MaxInt32, math.MinInt32
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
		if v > maxVal {
			maxVal = v
		}
	}
	return minVal, maxVal
}
func Mn(args ...int) int { mn, _ := MnMx(args...); return mn }
func Mx(args ...int) int { _, mx := MnMx(args...); return mx }
func LCM(a, b int) int   { return a / GCD(a, b) * b }
func GCD(a, b int) int {
	if a == 0 {
		return b
	}
	return GCD(b%a, a)
}
func Abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

package main

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

func minDigit(x int64) int64{
	var min = x%10
	x=x/10
	for x>0{
		min= int64(math.Min(float64(min), float64(x%10)))
		x=x/10
	}
	return min
}

func maxDigit(x int64) int64{
	var max = x%10
	x=x/10
	for x>0{
		max = int64(math.Max(float64(max), float64(x%10)))
		x=x/10
	}
	return max
}

func main() {
	var t,a,k int64;
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	fmt.Fscan(in,&t)
	for cas := int64(1); cas <= t; cas++ {
		fmt.Fscan(in,&a,&k)
		var res = int64(a)
		for i := int64(1); i < k; i++ {
			min := minDigit(res)
			max := maxDigit(res)
			res = res + (min*max)
			if min==0 {
				break
			}
		}
		fmt.Fprintln(out,res)
		out.Flush()
	}
}

package main

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

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

func main() {
	sc.Split(bufio.ScanWords)
	defer out.Flush() // !!!!coution!!!! you must use Fprint(out, ) not Print()
	/* --- code --- */
	t := nextInt()
	// t := 1
	for i := 0; i < t; i++ {
		a, k := nextInt64(), nextInt64()
		// a, k := int64(487), int64(100)
		aMemo := map[int64]int64{}
		revMemo := map[int64]int64{}
		aMemo[a] = 1
		revMemo[1] = a
		for j := int64(2); j <= k; j++ {
			// max, min := splitNum(a)
			max, min := minmax(a)
			a = a + min*max
			// fmt.Println(a)
			_, exists := aMemo[a]
			if exists {
				// looped
				looping := j - aMemo[a]
				// fmt.Println("test, ", aMemo[a]+(k-aMemo[a])%looping)
				a = revMemo[aMemo[a]+(k-aMemo[a])%looping]
				break
			} else {
				aMemo[a] = j
				revMemo[j] = a
			}
		}

		fmt.Println(a)
	}

}

func minmax(a int64) (int64, int64) {
	aStr := strconv.FormatInt(a, 10)
	minKey := int64(10)
	maxKey := int64(0)
	for i := 0; i < len(aStr); i++ {
		s := aStr[i] - '0'
		minKey = min64(minKey, int64(s))
		maxKey = max64(maxKey, int64(s))
	}
	return maxKey, minKey
}

// -*-*-*-*-*-*-*-*-
// * I/O utilities *
// -*-*-*-*-*-*-*-*-

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

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

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

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

func nextInts(n int) []int {
	ret := make([]int, n)
	for i := 0; i < n; i++ {
		ret[i] = nextInt()
	}
	return ret
}
func nextFloats(n int) []float64 {
	ret := make([]float64, n)
	for i := 0; i < n; i++ {
		ret[i] = nextFloat64()
	}
	return ret
}
func nextStrings(n int) []string {
	ret := make([]string, n)
	for i := 0; i < n; i++ {
		ret[i] = next()
	}
	return ret
}

func split(s string) []string {
	ret := make([]string, len([]rune(s)))
	for i, v := range []rune(s) {
		ret[i] = string(v)
	}
	return ret
}

// -*-*-*-*-*-*-*-*-
// * tool snippets *
// -*-*-*-*-*-*-*-*-
func duplicate2Int(base [][]int) (ret [][]int) {
	ret = make([][]int, len(base))
	for i, v := range base {
		ret[i] = append([]int{}, v...)
	}
	return
}

func max(a, b int) int {
	return int(max64(int64(a), int64(b)))
}

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

func min(a, b int) int {
	return int(min64(int64(a), int64(b)))
}

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

// *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
// * math flavor typical theories *
// *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
func gcd(a, b int) int {
	if a > b {
		return gcd(b, a)
	}
	for a != 0 {
		a, b = b%a, a
	}
	return b
}

func pow(a, b int) (ret int) {
	ret = a
	// 10^2 = 100ってことは10に10を1回掛けることだね
	// なので初期値を含めると上限b-1未満
	for i := 0; i < b-1; i++ {
		ret *= a
	}
	return
}

func powMod(n, m, mod int) (ret int) {
	ret = 1
	for m > 0 {
		if m&1 == 1 {
			ret *= n
			ret %= mod
		}
		n *= n
		n %= mod
		m >>= 1
	}
	return ret
}

package main

import "fmt"

func minmax(a int64) (int64, int64) {
	r := a % 10
	min, max := r, r
	for a > 0 {
		r = a % 10
		if min > r {
			min = r
		}
		if max < r {
			max = r
		}
		a /= 10
	}
	return min, max
}

func main() {
	var t int
	fmt.Scan(&t)
	for ; t > 0; t-- {
		var a, k int64
		fmt.Scan(&a, &k)
		k--
	outer:
		for ; k > 0; k-- {
			min, max := minmax(a)
			a += min * max
			tmp := a
			for tmp > 0 {
				if tmp%10 == 0 {
					break outer
				}
				tmp /= 10
			}
		}
		fmt.Println(a)
	}
}

package main

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

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 {
	NextInt64() int64
	NextUInt64() uint64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	// adjust the following size as needed
	// 2 << 17 is good enough to scan strings of len 2*10^5
	// it could go as high as 2 << 26 before cf judge breaks
	size := 2 << 20
	buf := make([]byte, size)
	s.Buffer(buf, size)
	return &wordScannerImpl{Scanner: s}
}

func (impl *wordScannerImpl) NextInt64() int64 {
	impl.Scan()
	bb := impl.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 (impl *wordScannerImpl) NextUInt64() uint64 {
	impl.Scan()
	bb := impl.Bytes()
	i := uint64(0)
	for _, b := range bb {
		i *= 10
		i += uint64(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.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
}

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

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

func main() {
	defer writer.Flush()
	t := reader.NextInt64()
	for ; t > 0; t-- {
		a1, K := reader.NextInt64(), reader.NextInt64()
		writer.Printf("%d\n", sol(a1, K))
	}
}

func sol(a, k int64) int64 {
	for ; k > 1; k-- {
		minD, maxD := getMinMaxD(a)
		if minD == 0 || maxD == 0 {
			break
		}
		a += minD * maxD
	}
	return a
}

func getMinMaxD(a int64) (int64, int64) {
	minD := int64(9)
	maxD := int64(0)
	for a > 0 {
		d := a % 10
		if d < minD {
			minD = d
		}
		if d > maxD {
			maxD = d
		}
		a /= 10
	}
	return minD, maxD
}

package main
import (
	"fmt"
	"sync"
)

var (
	wg sync.WaitGroup
	res map[int]int64
	mut sync.Mutex
)

func min_c(v int64) int64 {
	var res int64 = 9
	for v != 0 {
		dig := v % 10
		if res > dig {
			res = dig
		}
		v = (v-dig)/10
	}
	return res
}
func max_c(v int64) int64 {
	var res int64 = 0
	for v != 0 {
		dig := v % 10
		if res < dig {
			res = dig
		}
		v = (v-dig)/10
	}
	return res
}
func has_0(v int64) bool {
	for v != 0 {
		dig := v % 10
		if dig == 0 {
			return true
		}
		v = (v-dig)/10
	}
	return false
}

func Algo(a, n int64, id int) {
	wg.Add(1)
	for i := int64(1); i < n; i++ {
		if has_0(a) {
			break
		}
		a = a + min_c(a)*max_c(a)
	}
	mut.Lock()
	res[id] = a
	mut.Unlock()
	wg.Done()
}

func main() {
	var (
		a, n int64
		t int
	)
	fmt.Scanf("%d\n", &t)
	res = make(map[int]int64)
	//loop
	for i := 0; i < t; i++ {
		fmt.Scanf("%d %d\n", &a, &n)
		go Algo(a, n, i)
	}
	wg.Wait()
	for i := 0; i < t; i++ {
		fmt.Println(res[i])
	}
}

package main
import (
	"fmt"
)

func min_c(v int64) int64 {
	var res int64 = 9
	for v != 0 {
		dig := v % 10
		if res > dig {
			res = dig
		}
		v = (v-dig)/10
	}
	return res
}
func max_c(v int64) int64 {
	var res int64 = 0
	for v != 0 {
		dig := v % 10
		if res < dig {
			res = dig
		}
		v = (v-dig)/10
	}
	return res
}

func main() {
	var (
		a, n int64
		t int
	)
	fmt.Scanf("%d\n", &t)
	for i := 0; i < t; i++ {
		fmt.Scanf("%d %d\n", &a, &n)
		for i := int64(1); i < n; i++ {
			a = a + min_c(a)*max_c(a)
		}
		println(a)
	}
}

// https://codeforces.com/contest/1353/problem/A
package main

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
var input io.Reader

func main() {
	var (
		T int
	)

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &T)
	for i := 0; i < T; i++ {
		solver()
	}
}

func solver() {
	var n, k int
	fmt.Fscan(input, &n, &k)
	ans := n
	for k > 1 {
		v := ans
		dx := 10
		dm := 0
		for v > 0 {
			d := v - (v/10)*10
			dm = max(dm, d)
			dx = min(dx, d)
			v/=10
		}
		if dx*dm == 0 {
			break
		}
		ans += dx*dm
		k--
	}
	fmt.Println(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
}

package main

import (
	"fmt"
	"math"
)

func minDigit(x int64) int64{
	var min = x%10
	x=x/10
	for x>0{
		min= int64(math.Min(float64(min), float64(x%10)))
		x=x/10
	}
	return min
}

func maxDigit(x int64) int64{
	var max = x%10
	x=x/10
	for x>0{
		max = int64(math.Max(float64(max), float64(x%10)))
		x=x/10
	}
	return max
}

func main() {
	var t,a,k int;
	fmt.Scanf("%d",&t)
	for cas := 1; cas <= t; cas++ {
		fmt.Scanf("%d %d",&a,&k)
		var res = int64(a)
		for i := 1; i < k; i++ {
			res = res + (maxDigit(res)*minDigit(res))
		}
	}
}

package main

import (
	"fmt"
	"math"
)

func minDigit(x int64) int64{
	var min = x%10
	x=x/10
	for x>0{
		min= int64(math.Min(float64(min), float64(x%10)))
		x=x/10
	}
	return min
}

func maxDigit(x int64) int64{
	var max = x%10
	x=x/10
	for x>0{
		max = int64(math.Max(float64(max), float64(x%10)))
		x=x/10
	}
	return max
}

func main() {
	var t,a,k int;
	fmt.Scanf("%d",&t)
	for cas := 1; cas <= t; cas++ {
		fmt.Scanf("%d %d",&a,&k)
		var res = int64(a)
		fmt.Printf("res = %d", res)
		for i := 1; i < k; i++ {
			res = res + (maxDigit(res)*minDigit(res))
		}
		fmt.Printf("%d\n",res)
	}
}

package main

import (
	"fmt"
	"math"
)

func minDigit(x int64) int64{
	var min = x%10
	x=x/10
	for x>0{
		min= int64(math.Min(float64(min), float64(x%10)))
		x=x/10
	}
	return min
}

func maxDigit(x int64) int64{
	var max = x%10
	x=x/10
	for x>0{
		max = int64(math.Max(float64(max), float64(x%10)))
		x=x/10
	}
	return max
}

func main() {
	var t,a,k int;
	fmt.Scanf("%d",&t)
	for cas := 1; cas <= t; cas++ {
		fmt.Scanf("%d %d",&a,&k)
		var res = int64(a)
		for i := 1; i < k; i++ {
			//fmt.Printf("res = %d ",res )
			res = res + (maxDigit(res)*minDigit(res))
		}
		fmt.Printf("%d",res)
	}
}

package main

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

func minDigit(x int64) int64{
	var min = x%10
	x=x/10
	for x>0{
		min= int64(math.Min(float64(min), float64(x%10)))
		x=x/10
	}
	return min
}

func maxDigit(x int64) int64{
	var max = x%10
	x=x/10
	for x>0{
		max = int64(math.Max(float64(max), float64(x%10)))
		x=x/10
	}
	return max
}

func main() {
	var t,a,k int;
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	fmt.Fscan(in,&t)
	for cas := 1; cas <= t; cas++ {
		fmt.Fscan(in,&a,&k)
		var res = int64(a)
		for i := 1; i < k; i++ {
			res = res + (maxDigit(res)*minDigit(res))
		}
		fmt.Fprintln(out,res)
	}
}

package main

import (
	"fmt"
	"math"
)

func minDigit(x int64) int64{
	var min = x%10
	x=x/10
	for x>0{
		min= int64(math.Min(float64(min), float64(x%10)))
		x=x/10
	}
	return min
}

func maxDigit(x int64) int64{
	var max = x%10
	x=x/10
	for x>0{
		max = int64(math.Max(float64(max), float64(x%10)))
		x=x/10
	}
	return max
}

func main() {
	var t,a,k int;
	fmt.Scanf("%d",&t)
	for cas := 1; cas <= t; cas++ {
		fmt.Scanf("%d %d",&a,&k)
		var res = int64(a)
		fmt.Printf("a = %d", a)
		fmt.Printf("k = %d", k)
		fmt.Printf("res = %d", res)
		for i := 1; i < k; i++ {
			res = res + (maxDigit(res)*minDigit(res))
		}
		fmt.Printf("%d\n",res)
	}
}

package main

import (
	"fmt"
	"math"
)

func minDigit(x int64) int64{
	var min = x%10
	x=x/10
	for x>0{
		min= int64(math.Min(float64(min), float64(x%10)))
		x=x/10
	}
	return min
}

func maxDigit(x int64) int64{
	var max = x%10
	x=x/10
	for x>0{
		max = int64(math.Max(float64(max), float64(x%10)))
		x=x/10
	}
	return max
}

func main() {
	var t,a,k int;
	fmt.Scanf("%d",&t)
	for cas := 1; cas <= t; cas++ {
		fmt.Scanf("%d %d",&a,&k)
		var res = int64(a)
		for i := 1; i < k; i++ {
			//fmt.Printf("res = %d ",res )
			res = res + (maxDigit(res)*minDigit(res))
		}
		println(res)
	}
}

package main

import (
	"fmt"
	"math"
)

func minDigit(x int64) int64{
	var min = x%10
	x=x/10
	for x>0{
		min= int64(math.Min(float64(min), float64(x%10)))
		x=x/10
	}
	return min
}

func maxDigit(x int64) int64{
	var max = x%10
	x=x/10
	for x>0{
		max = int64(math.Max(float64(max), float64(x%10)))
		x=x/10
	}
	return max
}

func main() {
	var t,a,k int;
	fmt.Scanf("%d",&t)
	for cas := 1; cas <= t; cas++ {
		fmt.Scanf("%d %d",&a,&k)
		var res = int64(a)
		for i := 1; i < k; i++ {
			res = res + (maxDigit(res)*minDigit(res))
		}
		fmt.Printf("%d \n",res)
	}
}

package main

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

func minDigit(x int64) int64{
	var min = x%10
	x=x/10
	for x>0{
		min= int64(math.Min(float64(min), float64(x%10)))
		x=x/10
	}
	return min
}

func maxDigit(x int64) int64{
	var max = x%10
	x=x/10
	for x>0{
		max = int64(math.Max(float64(max), float64(x%10)))
		x=x/10
	}
	return max
}

func main() {
	var t,a,k int;
	in := bufio.NewReader(os.Stdin)
	fmt.Fscan(in,&t)
	for cas := 1; cas <= t; cas++ {
		fmt.Fscan(in,&a,&k)
		var res = int64(a)
		for i := 1; i < k; i++ {
			res = res + (maxDigit(res)*minDigit(res))
		}
		fmt.Printf("%d\n",res)
	}
}

package main

import (
	"fmt"
	"math"
)

func minDigit(x int64) int64{
	var min = x%10
	x=x/10
	for x>0{
		min= int64(math.Min(float64(min), float64(x%10)))
		x=x/10
	}
	return min
}

func maxDigit(x int64) int64{
	var max = x%10
	x=x/10
	for x>0{
		max = int64(math.Max(float64(max), float64(x%10)))
		x=x/10
	}
	return max
}

func main() {
	var t,a,k int;
	fmt.Scanf("%d",&t)
	for cas := 1; cas <= t; cas++ {
		fmt.Scanf("%d %d",&a,&k)
		var res = int64(a)
		for i := 1; i < k; i++ {
			res = res + (maxDigit(res)*minDigit(res))
		}
		fmt.Printf("hello\n")
	}
}

package main

import (
	"fmt"
	"math"
)

func minDigit(x int64) int64{
	var min = x%10
	x=x/10
	for x>0{
		min= int64(math.Min(float64(min), float64(x%10)))
		x=x/10
	}
	return min
}

func maxDigit(x int64) int64{
	var max = x%10
	x=x/10
	for x>0{
		max = int64(math.Max(float64(max), float64(x%10)))
		x=x/10
	}
	return max
}

func main() {
	var t,a,k int;
	fmt.Scanf("%d",&t)
	for cas := 1; cas <= t; cas++ {
		fmt.Scanf("%d %d",&a,&k)
		var res = int64(a)
		for i := 1; i < k; i++ {
			//fmt.Printf("res = %d ",res )
			res = res + (maxDigit(res)*minDigit(res))
		}
		fmt.Printf("%d\n",res)
	}
}

 package main

import (
	"fmt"
	"math"
)

func minDigit(x int64) int64{
	var min = x%10
	x=x/10
	for x>0{
		min= int64(math.Min(float64(min), float64(x%10)))
		x=x/10
	}
	return min
}

func maxDigit(x int64) int64{
	var max = x%10
	x=x/10
	for x>0{
		max = int64(math.Max(float64(max), float64(x%10)))
		x=x/10
	}
	return max
}

func main() {
	var t,a,k int;
	fmt.Scanf("%d",&t)
	for cas := 1; cas <= t; cas++ {
		fmt.Scanf("%d %d",&a,&k)
		var res = int64(a)
		for i := 1; i < k; i++ {
			res = res + (maxDigit(res)*minDigit(res))
		}
		fmt.Printf("hello")
	}
}

package main

import (
	"fmt"
	"math"
)

func minDigit(x int64) int64{
	var min = x%10
	x=x/10
	for x>0{
		min= int64(math.Min(float64(min), float64(x%10)))
		x=x/10
	}
	return min
}

func maxDigit(x int64) int64{
	var max = x%10
	x=x/10
	for x>0{
		max = int64(math.Max(float64(max), float64(x%10)))
		x=x/10
	}
	return max
}

func main() {
	var t,a,k int;
	fmt.Scanf("%d",&t)
	for cas := 1; cas <= t; cas++ {
		fmt.Scanf("%d %d",&a,&k)
		var res = int64(a)
		for i := 1; i < k; i++ {
			res = res + (maxDigit(res)*minDigit(res))
		}
		fmt.Printf("%d\n",res)
	}
}

package main

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

func minDigit(x int64) int64{
	var min = x%10
	x=x/10
	for x>0{
		min= int64(math.Min(float64(min), float64(x%10)))
		x=x/10
	}
	return min
}

func maxDigit(x int64) int64{
	var max = x%10
	x=x/10
	for x>0{
		max = int64(math.Max(float64(max), float64(x%10)))
		x=x/10
	}
	return max
}

func main() {
	var t,a,k int;
	in := bufio.NewReader(os.Stdin)
	fmt.Fscan(in,&t)
	for cas := 1; cas <= t; cas++ {
		fmt.Fscan(in,&a,&k)
		var res = int64(a)
		fmt.Printf("a = %d", a)
		fmt.Printf("k = %d", k)
		fmt.Printf("res = %d", res)
		for i := 1; i < k; i++ {
			res = res + (maxDigit(res)*minDigit(res))
		}
		fmt.Printf("%d\n",res)
	}
}

package main

import (
	"fmt"
	"math"
)

func minDigit(x int64) int64{
	var min = x%10
	x=x/10
	for x>0{
		min= int64(math.Min(float64(min), float64(x%10)))
		x=x/10
	}
	return min
}

func maxDigit(x int64) int64{
	var max = x%10
	x=x/10
	for x>0{
		max = int64(math.Max(float64(max), float64(x%10)))
		x=x/10
	}
	return max
}

func main() {
	var t,a,k int;
	fmt.Scanf("%d",&t)
	for cas := 1; cas <= t; cas++ {
		fmt.Scanf("%d %d",&a,&k)
		var res = int64(a)
		for i := 1; i <= k; i++ {
			res = res + (maxDigit(res)*minDigit(res))
		}
		fmt.Printf("%d\n",res)
	}
}

package main

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

func minDigit(x int64) int64{
	var min = x%10
	x=x/10
	for x>0{
		min= int64(math.Min(float64(min), float64(x%10)))
		x=x/10
	}
	return min
}

func maxDigit(x int64) int64{
	var max = x%10
	x=x/10
	for x>0{
		max = int64(math.Max(float64(max), float64(x%10)))
		x=x/10
	}
	return max
}

func main() {
	var t,a,k int;
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	fmt.Fscan(in,&t)
	for cas := 1; cas <= t; cas++ {
		fmt.Fscan(in,&a,&k)
		var res = int64(a)
		for i := 1; i < k; i++ {
			res = res + (maxDigit(res)*minDigit(res))
		}
		fmt.Fprintln(out,res)
		out.Flush()
	}
}

package main

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

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

func main() {
	sc.Split(bufio.ScanWords)
	defer out.Flush() // !!!!coution!!!! you must use Fprint(out, ) not Print()
	/* --- code --- */
	t := nextInt()
	for i := 0; i < t; i++ {
		a, k := nextInt64(), nextInt64()
		aMemo := map[int64]int64{}
		revMemo := map[int64]int64{}
		aMemo[a] = 1
		revMemo[1] = a
		for j := int64(2); j <= k; j++ {
			// max, min := splitNum(a)
			max, min := minmax(a)
			a = a + min*max
			_, exists := aMemo[a]
			if exists {
				// looped
				looping := j - aMemo[a]
				a = revMemo[(k-aMemo[a])+(k-aMemo[a])%looping]
				break
			} else {
				aMemo[a] = j
				revMemo[j] = a
			}
		}

		fmt.Println(a)
	}

}

func minmax(a int64) (int64, int64) {
	aStr := strconv.FormatInt(a, 10)
	minKey := int64(10)
	maxKey := int64(0)
	for i := 0; i < len(aStr); i++ {
		s := aStr[i] - '0'
		minKey = min64(minKey, int64(s))
		maxKey = max64(maxKey, int64(s))
	}
	return maxKey, minKey
}

// -*-*-*-*-*-*-*-*-
// * I/O utilities *
// -*-*-*-*-*-*-*-*-

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

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

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

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

func nextInts(n int) []int {
	ret := make([]int, n)
	for i := 0; i < n; i++ {
		ret[i] = nextInt()
	}
	return ret
}
func nextFloats(n int) []float64 {
	ret := make([]float64, n)
	for i := 0; i < n; i++ {
		ret[i] = nextFloat64()
	}
	return ret
}
func nextStrings(n int) []string {
	ret := make([]string, n)
	for i := 0; i < n; i++ {
		ret[i] = next()
	}
	return ret
}

func split(s string) []string {
	ret := make([]string, len([]rune(s)))
	for i, v := range []rune(s) {
		ret[i] = string(v)
	}
	return ret
}

// -*-*-*-*-*-*-*-*-
// * tool snippets *
// -*-*-*-*-*-*-*-*-
func duplicate2Int(base [][]int) (ret [][]int) {
	ret = make([][]int, len(base))
	for i, v := range base {
		ret[i] = append([]int{}, v...)
	}
	return
}

func max(a, b int) int {
	return int(max64(int64(a), int64(b)))
}

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

func min(a, b int) int {
	return int(min64(int64(a), int64(b)))
}

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

// *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
// * math flavor typical theories *
// *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
func gcd(a, b int) int {
	if a > b {
		return gcd(b, a)
	}
	for a != 0 {
		a, b = b%a, a
	}
	return b
}

func pow(a, b int) (ret int) {
	ret = a
	// 10^2 = 100ってことは10に10を1回掛けることだね
	// なので初期値を含めると上限b-1未満
	for i := 0; i < b-1; i++ {
		ret *= a
	}
	return
}

func powMod(n, m, mod int) (ret int) {
	ret = 1
	for m > 0 {
		if m&1 == 1 {
			ret *= n
			ret %= mod
		}
		n *= n
		n %= mod
		m >>= 1
	}
	return ret
}


You have a stripe of checkered paper of length $$$n$$$. Each cell is either white or black.What is the minimum number of cells that must be recolored from white to black in order to have a segment of $$$k$$$ consecutive black cells on the stripe?If the input data is such that a segment of $$$k$$$ consecutive black cells already exists, then print 0.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Next, descriptions of $$$t$$$ test cases follow. The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2\cdot10^5$$$). The second line consists of the letters 'W' (white) and 'B' (black). The line length is $$$n$$$. It is guaranteed that the sum of values $$$n$$$ does not exceed $$$2\cdot10^5$$$.

For each of $$$t$$$ test cases print an integer — the minimum number of cells that need to be repainted from white to black in order to have a segment of $$$k$$$ consecutive black cells.

4

5 3

BBWBW

5 5

BBWBW

5 1

BBWBW

1 1

W

NoteIn the first test case, $$$s$$$="BBWBW" and $$$k=3$$$. It is enough to recolor $$$s_3$$$ and get $$$s$$$="BBBBW". This string contains a segment of length $$$k=3$$$ consisting of the letters 'B'.In the second test case of the example $$$s$$$="BBWBW" and $$$k=5$$$. It is enough to recolor $$$s_3$$$ and $$$s_5$$$ and get $$$s$$$="BBBBB". This string contains a segment of length $$$k=5$$$ consisting of the letters 'B'.In the third test case of the example $$$s$$$="BBWBW" and $$$k=1$$$. The string $$$s$$$ already contains a segment of length $$$k=1$$$ consisting of the letters 'B'.

// 00
package main

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

func write_int(f *bufio.Writer, a int) {
	f.Write([]byte(strconv.Itoa(a)))
}
func write_string(f *bufio.Writer, a string) {
	f.Write([]byte(a))
}

func main() {
	var T int
	reader := bufio.NewReader(os.Stdin)
	f := bufio.NewWriter(os.Stdout)
	defer f.Flush()
	fmt.Fscan(reader, &T)
	for t := 1; t <= T; t++ {
		var n, k int
		var s string
		fmt.Fscan(reader, &n, &k, &s)
		ans := k
		white := 0
		black := 0
		for i := 0; i < k; i++ {
			if s[i] == 'B' {
				black++
			} else {
				white++
			}
		}
		if white < ans {
			ans = white
		}
		for i := k; i < n; i++ {
			if s[i-k] == 'B' {
				black--
			} else {
				white--
			}
			if s[i] == 'B' {
				black++
			} else {
				white++
			}
			if white < ans {
				ans = white
			}
		}

		fmt.Println(ans)

	}
}

// 00
package main

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

func write_int(f *bufio.Writer, a int) {
	f.Write([]byte(strconv.Itoa(a)))
}
func write_string(f *bufio.Writer, a string) {
	f.Write([]byte(a))
}

func main() {
	var T int
	reader := bufio.NewReader(os.Stdin)
	f := bufio.NewWriter(os.Stdout)
	defer f.Flush()
	fmt.Fscan(reader, &T)
	for t := 1; t <= T; t++ {
		var n, k int
		var s string
		fmt.Fscan(reader, &n, &k, &s)
		ans := k
		white := 0
		black := 0
		for i := 0; i < n; i++ {
			if i >= k {
				if white < ans {
					ans = white
				}
				if s[i-k] == 'B' {
					black--
				} else {
					white--
				}

			}
			if s[i] == 'B' {
				black++
			} else {
				white++
			}
		}
		if white < ans {
			ans = white
		}
		fmt.Println(ans)

	}
}

// 00
package main

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

func write_int(f *bufio.Writer, a int) {
	f.Write([]byte(strconv.Itoa(a)))
}
func write_string(f *bufio.Writer, a string) {
	f.Write([]byte(a))
}

func main() {
	var T int
	reader := bufio.NewReader(os.Stdin)
	f := bufio.NewWriter(os.Stdout)
	defer f.Flush()
	fmt.Fscan(reader, &T)
	for t := 1; t <= T; t++ {
		var n, k int
		var s string
		fmt.Fscan(reader, &n, &k, &s)
		ans := k
		white := 0
		black := 0
		for i := 0; i < n; i++ {
			if i < k {
				if s[i] == 'B' {
					black++
				} else {
					white++
				}
			} else {
				if white < ans {
					ans = white
				}
				if s[i] == 'B' {
					black++
				} else {
					white++
				}
				if s[i-k] == 'B' {
					black--
				} else {
					white--
				}
			}
		}
		if white < ans {
			ans = white
		}
		fmt.Println(ans)

	}
}

package main

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

var (
	a [2e5 + 5]int
)

func run(_r io.Reader, _w io.Writer) {
	const eof = 0
	out := bufio.NewWriter(_w)
	defer out.Flush()
	_i, _n, buf := 0, 0, make([]byte, 1<<12)
	rc := func() byte {
		if _i == _n {
			_n, _ = _r.Read(buf)
			if _n == 0 {
				return eof
			}
			_i = 0
		}
		b := buf[_i]
		_i++
		return b
	}

	r := func() (x int) {
		b := rc()
		for ; '0' > b || b > '9'; b = rc() {
			if b == eof {
				return
			}
		}
		for ; '0' <= b && b <= '9'; b = rc() {
			x = x*10 + int(b&15)
		}
		return
	}
	for t := r(); t > 0; t-- {
		n, k := r(), r()
		b := rc()
		for ; b == '\n' || b == '\r'; b = rc() {
			if b == eof {
				return
			}
		}
		for i := 1; i <= n; i++ {
			if b == 'W' {
				a[i] = a[i-1] + 1
			} else {
				a[i] = a[i-1]
			}
			b = rc()
		}
		res := 1<<31 - 1
		for i := 1; i+k-1 <= n; i++ {
			r := i + k - 1
			if t := a[r] - a[i-1]; t < res {
				res = t
			}
		}
		Fprintln(out, res)
	}
}

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

package main

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

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

// source: https://codeforces.com/contest/1690/problem/D
func solve() {
	n, k := _readInt(), _readInt()
	a := _readStr()
	ps := make([]int, n+1)
	for i := 1; i <= n; i++ {
		ps[i] = ps[i-1]
		if a[i-1] == 'W' {
			ps[i]++
		}
	}

	res := n
	for i := 0; i+k <= n; i++ {
		res = _min(res, ps[i+k]-ps[i])
	}

	_print(res)
	return
}

func main() {
	defer out.Flush()
	var t int
	for fmt.Fscanln(in, &t); t > 0; t-- {
		solve()
	}
}

// ====
func _readInt() int {
	var x int
	fmt.Fscan(in, &x)
	return x
}
func _readStr() string {
	var x string
	fmt.Fscan(in, &x)
	return x
}
func _readArr(x ...int) (int, []int) {
	var n int
	if len(x) == 0 {
		fmt.Fscan(in, &n)
	} else {
		n = x[0]
	}
	var v = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &v[i])
	}
	return n, v
}
func _print(x ...any) {
	fmt.Fprintln(out, x...)
}
func _max(x ...int) int {
	mi := 0
	for i := 1; i < len(x); i++ {
		if x[i] > x[mi] {
			mi = i
		}
	}
	return x[mi]
}
func _min(x ...int) int {
	mi := 0
	for i := 1; i < len(x); i++ {
		if x[i] < x[mi] {
			mi = i
		}
	}
	return x[mi]
}
func _sum(x ...int) int {
	res := 0
	for _, i := range x {
		res += i
	}
	return res
}
func _abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}
func _sortStr(x string) string {
	r := []rune(x)
	sort.Slice(r, func(i, j int) bool {
		return r[i] < r[j]
	})
	return string(r)
}
func _reverseInts(x []int) {
	n := len(x)
	for i := 0; i < n/2; i++ {
		x[i], x[n-1-i] = x[n-1-i], x[i]
	}
}
func _reverseStr(s string) string {
	x := []rune(s)
	n := len(x)
	for i := 0; i < n/2; i++ {
		x[i], x[n-1-i] = x[n-1-i], x[i]
	}
	return string(x)
}
func _makeMatrix(n, m int) [][]int {
	x := make([][]int, n)
	for i := range x {
		x[i] = make([]int, m)
	}
	return x
}

package main

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

const (
	MaxInt32 = 1 << 31 - 1
)

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
}

func main(){
	cin := bufio.NewReader(os.Stdin)
	var t int
	fmt.Fscan(cin, &t)
	for tc := 0; tc < t; tc++ {
		var n, k int
		fmt.Fscan(cin, &n, &k)
		var s string
		fmt.Fscan(cin, &s)

		w_prefix_sum := make([]int, n + 1)
		for i := 1; i <= n; i++ {
			cnt := 0
			if string(s[i - 1]) == "W" {
				cnt += 1
			}
			w_prefix_sum[i] = w_prefix_sum[i - 1] + cnt
		}

		ans := MaxInt32
		for i := k; i <= n; i++ {
			ans = Min(ans, w_prefix_sum[i] - w_prefix_sum[i - k])
		}
		fmt.Println(ans)
	}
}

package main

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

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

	var tt int
	fmt.Fscan(in, &tt)
	for tc := 0; tc < tt; tc++ {
		var (
			n int
			k int
			s string
		)
		fmt.Fscan(in, &n, &k, &s)
		cnt := 0
		ans := math.MaxInt
		for i := 0; i < n; i++ {
			if i >= k && s[i-k] == 'B' {
				cnt--
			}
			if s[i] == 'B' {
				cnt++
			}
			if k <= i+1 {
				ans = Min(ans, k-cnt)
			}
		}
		fmt.Fprintln(out, ans)
	}
}

func Min(xs ...int) int {
	m := math.MaxInt
	for _, i := range xs {
		if i < m {
			m = i
		}
	}
	return m
}

package main

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

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

	var T int
	fmt.Fscan(in, &T)
	for t := 0; t < T; t++ {
		var n, k int
		var s string
		fmt.Fscan(in, &n, &k, &s)

		var tot int
		for i := 0; i < k; i++ {
			if s[i] == 'W' {
				tot++
			}
		}

		min := tot
		for i := k; i < n; i++ {
			if s[i-k] == 'W' {
				tot--
			}
			if s[i] == 'W' {
				tot++
			}
			if tot < min {
				min = tot
			}
		}

		fmt.Fprintln(out, min)
	}
}

package main

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

/*
7
1 1
W
1 1
B
4 3
BWBW
5 4
BWBWW
6 3
BWBBBW
7 4
BWBWBWW
8 4
BWBWBWWB
---
1
0
1
2
0
2
2
*/

//goland:noinspection GoUnhandledErrorResult
func solve() {
	var n, k int
	var s string
	scanf("%d %d\n%s\n", &n, &k, &s)

	cnt := 0

	for i := 0; i < k; i++ {
		if s[i] == 'W' {
			cnt++
		}
	}

	minCnt := cnt

	for i, j := 0, k; j < n; i, j = i+1, j+1 {
		if s[i] == 'W' {
			cnt--
		}
		if s[j] == 'W' {
			cnt++
		}

		minCnt = min(minCnt, cnt)
	}

	fmt.Fprintln(writer, minCnt)
}

//goland:noinspection GoUnhandledErrorResult
func main() {
	defer writer.Flush()

	t := 1
	scanf("%d\n", &t)

	for ; t > 0; t-- {
		solve()
	}
}

const maxUint = ^uint(0)

//goland:noinspection GoUnusedConst
const minUint = 0
const maxInt = int(maxUint >> 1)

//goland:noinspection GoUnusedConst
const minInt = -maxInt - 1

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

func scanf(f string, a ...interface{}) {
	if _, err := fmt.Fscanf(reader, f, a...); err != nil {
		panic(err)
	}
}

//goland:noinspection GoUnusedFunction
func reversed(s string) string {
	input := []rune(s)
	li := len(input)
	ret := make([]rune, li)
	for i, r := range input {
		ret[li-i-1] = r
	}
	return string(ret)
}

//goland:noinspection GoUnusedFunction
func divCeil(num, div int64) int64 {
	quot := num / div
	if num%div > 0 {
		quot++
	} else if num%div < 0 {
		quot--
	}
	return quot
}

//goland:noinspection GoUnusedFunction
func min(nums ...int) int {
	return nums[minIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func minIdx(nums ...int) int {
	minNumIdx := 0
	for i, num := range nums {
		if num < nums[minNumIdx] {
			minNumIdx = i
		}
	}

	return minNumIdx
}

//goland:noinspection GoUnusedFunction
func max(nums ...int) int {
	return nums[maxIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func maxIdx(nums ...int) int {
	maxNumIdx := 0
	for i, num := range nums {
		if num > nums[maxNumIdx] {
			maxNumIdx = i
		}
	}

	return maxNumIdx
}

//goland:noinspection GoUnusedFunction
func sum(nums ...int) (sum int) {
	for _, num := range nums {
		sum += num
	}
	return
}

//goland:noinspection GoUnusedFunction
func abs(num int) int {
	if num < 0 {
		return -num
	}
	return num
}

//goland:noinspection GoUnusedFunction
func isPrime(num int64) bool {
	if num == 2 || num == 3 {
		return true
	}

	if num <= 1 || num%2 == 0 || num%3 == 0 {
		return false
	}

	for i := int64(5); i*i <= num; i += 6 {
		if num%i == 0 || num%(i+2) == 0 {
			return false
		}
	}

	return true
}

//goland:noinspection GoUnusedFunction
func gcd(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

//goland:noinspection GoUnusedFunction
func lcm(a, b int) int {
	return abs(a) / gcd(a, b) * abs(b)
}

// Examples:
//	digitAt(1234, -1) -> panic!
//	digitAt(1234, 0) -> 4
//	digitAt(1234, 1) -> 3
//	digitAt(1234, 2) -> 2
//	digitAt(1234, 3) -> 1
//	digitAt(1234, 4) -> panic!
//goland:noinspection GoUnusedFunction
func digitAt(num, pos int) int {
	if num == 0 {
		return 0
	}

	num = abs(num)

	lenNum := int(math.Log10(float64(num))) + 1
	if pos < 0 || pos >= lenNum {
		err := fmt.Sprintf("Out of bound access for digit. Position passed %d, number %d", pos, num)
		panic(err)
	}

	rem := num % int(math.Pow10(pos+1))
	return rem / int(math.Pow10(pos))
}

//goland:noinspection GoUnusedFunction
func factorize(num int64) []int64 {
	factors := make([]int64, 0)

	for ftr := int64(2); ftr*ftr <= num; ftr++ {
		for num%ftr == 0 {
			num /= ftr
			factors = append(factors, ftr)
		}
	}

	if num > 1 {
		factors = append(factors, num)
	}

	return factors
}

package main

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

func A4() {
	_in, _out := os.Stdin, os.Stdout
	in, out := bufio.NewReader(_in), bufio.NewWriter(_out)
	defer out.Flush()
	var cas int = 1
	Fscan(in, &cas)
	var sol func()
	// Coding...beg!
	sol = func() {
		var n, k int
		Fscan(in, &n, &k)
		var s string
		Fscan(in, &s)
		// for i:=1;i<=n;i++{
		// 	sum[i] = sum[i-1]
		// 	if s[i-1] == 'B'{
		// 		sum[i]++
		// 	}
		// }
		ans := int(1e9)
		var cnt int
		for i, j := 0, 0; i < n; i++ {
			if s[i] == 'B' {
				cnt++
			}
			for i-j+1 > k {
				if s[j] == 'B' {
					cnt--
				}
				j++
			}
			if i-j+1 == k {
				if k-cnt < ans {
					ans = k - cnt
				}
			}
		}
		Fprintln(out, ans)
	}
	// Coding...ove!
	for i := 0; i < cas; i++ {
		sol()
	}
}

func main() { A4() }

package main

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

var r = bufio.NewReader(os.Stdin)
var w = bufio.NewWriter(os.Stdout)

func slove() {
	var n, k int
	fmt.Fscan(r, &n, &k)
	var s string
	fmt.Fscan(r, &s)
	dp := make([]int, n)
	for i:=0;i<k;i++ {
		if s[i] == 'W' {
			dp[k-1]++
		}
	}
	ans := dp[k-1]
	for i:=k;i<n;i++ {
		if s[i-k] == 'W' {
			dp[i] = dp[i-1] - 1
		} else {
			dp[i] = dp[i-1]
		}
		if s[i] == 'W' {
			dp[i]++
		}
		ans = min(ans, dp[i])
	}
	fmt.Fprintln(w, ans)
}

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

func main() {
	defer w.Flush()
	var n int
	fmt.Fscan(r, &n)
	for i:=1;i<=n;i++ {
		slove()
	}
}

package main

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

var (
	a [2e5 + 5]bool
)

func run(_r io.Reader, _w io.Writer) {
	const eof = 0
	out := bufio.NewWriter(_w)
	defer out.Flush()
	_i, _n, buf := 0, 0, make([]byte, 1<<12)
	rc := func() byte {
		if _i == _n {
			_n, _ = _r.Read(buf)
			if _n == 0 {
				return eof
			}
			_i = 0
		}
		b := buf[_i]
		_i++
		return b
	}

	r := func() (x int) {
		b := rc()
		for ; '0' > b || b > '9'; b = rc() {
			if b == eof {
				return
			}
		}
		for ; '0' <= b && b <= '9'; b = rc() {
			x = x*10 + int(b&15)
		}
		return
	}
	for t := r(); t > 0; t-- {
		n, k := r(), r()
		b := rc()
		for ; b == '\n' || b == '\r'; b = rc() {
			if b == eof {
				return
			}
		}
		for i := 1; i <= n; i++ {
			if b == 'W' {
				a[i] = true
			}
			b = rc()
		}
		res := 0
		for i := 1; i <= n && i <= k; i++ {
			if a[i] {
				res++
			}
		}
		tmp := res
		l, r := 2, k+1
		for r <= n {
			if a[l-1] {
				tmp--
			}
			if a[r] {
				tmp++
			}
			if tmp < res {
				res = tmp
			}
			l++
			r++
		}
		Fprintln(out, res)
	}
}

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

package main

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

var (
	a [2e5 + 5]bool
)

func run(_r io.Reader, _w io.Writer) {
	const eof = 0
	out := bufio.NewWriter(_w)
	defer out.Flush()
	_i, _n, buf := 0, 0, make([]byte, 1<<12)
	rc := func() byte {
		if _i == _n {
			_n, _ = _r.Read(buf)
			if _n == 0 {
				return eof
			}
			_i = 0
		}
		b := buf[_i]
		_i++
		return b
	}

	r := func() (x int) {
		b := rc()
		for ; '0' > b || b > '9'; b = rc() {
			if b == eof {
				return
			}
		}
		for ; '0' <= b && b <= '9'; b = rc() {
			x = x*10 + int(b&15)
		}
		return
	}
	for t := r(); t > 0; t-- {
		n, k := r(), r()
		b := rc()
		for ; b == '\n' || b == '\r'; b = rc() {
			if b == eof {
				return
			}
		}
		for i := 1; i <= n; i++ {
			if b == 'W' {
				a[i] = true
			}
			b = rc()
		}
		res := 0
		for i := 1; i <= n && i <= k; i++ {
			if a[i] {
				res++
			}
		}
		tmp := res
		l, r := 2, k+1
		for r <= n {
			if a[l] != a[l-1] {
				if a[l] {
					tmp++
				} else {
					tmp--
				}
			}
			if a[r] {
				tmp++
			}
			if tmp < res {
				res = tmp
			}
			l++
			r++
		}
		Fprintln(out, res)
	}
}

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


There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

The first line contains integer n (1 ≤ n ≤ 3·105) — the number of pearls in a row. The second line contains n integers ai (1 ≤ ai ≤ 109) – the type of the i-th pearl.

On the first line print integer k — the maximal number of segments in a partition of the row. Each of the next k lines should contain two integers lj, rj (1 ≤ lj ≤ rj ≤ n) — the number of the leftmost and the rightmost pearls in the j-th segment. Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type. If there are several optimal solutions print any of them. You can print the segments in any order. If there are no correct partitions of the row print the number "-1".

package main

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

type segment struct {
    start int
    end int
}

func main() {
    var a [300000]int
    var segments []segment
    stin := bufio.NewReader(os.Stdin)
    ns,_ := stin.ReadBytes('\n')
    n,_ := strconv.Atoi(string(bytes.Trim(ns,"\n\r ")))
//    fmt.Printf("%d\n\r", n)
    var tmp []byte
    for i := 0; i < n-1; i++ {
        tmp,_ = stin.ReadBytes(' ')
        a[i],_ = strconv.Atoi(string(bytes.Trim(tmp," ")))
    }
    tmp,_ = stin.ReadBytes('\n')
//    fmt.Printf("last: %v\n", bytes.Trim(tmp,"\n\r"))
    a[n-1],_ = strconv.Atoi(string(bytes.Trim(tmp,"\n\r")))
//    for k := 0; k < n; k++ {
//        fmt.Printf("%d ", a[k])
//    }
//    fmt.Println()

    var g map[int]int = make(map[int]int)
    var left int = 0
    var right int = 0
    for i := 0; i < n; i++ {
        right = i
        if g[a[i]] == 1 { //already in map
            for k := range g {
                delete(g, k)
            }
            segments = append(segments, segment{start: left, end: right})
            left = i+1
        } else {
            g[a[i]] = 1
        }
    }
    kkl := len(segments)
    if kkl == 0 {
        fmt.Println("-1")
        return
    }
    segments[kkl-1].end = n-1
    fmt.Printf("%d\n", kkl)
    for k := 0; k < kkl; k++ {
        fmt.Printf("%d %d\n", segments[k].start+1, segments[k].end+1)
    }
}

package main

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

type ii struct {
	start, end int
}

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

// func ReadInt64() int64 {
//     scanner.Scan()
//     ans, _ := strconv.ParseInt(scanner.Text(),10,64)
//     return ans
// }

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

// writer.WriteString(strconv.FormatInt(value, 10))
// writer.WriteByte(' ')

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

	n := ReadInt32()

	mapa := make(map[int]int)

	ini := 1

	var resp []ii

	for i := 1; i <= n; i++ {
		val := ReadInt32()
		if _, ok := mapa[val]; ok {
			resp = append(resp, ii{ini, i})
			ini = i+1
			mapa = make(map[int]int)
		} else {
			mapa[val]++
		}
	}

	if len(resp) == 0 {
		writer.WriteString("-1\n")
		return
	}

	if ini != n+1 {
		resp[len(resp) - 1].end = n
	}

	writer.WriteString(strconv.Itoa(len(resp)))
	writer.WriteString("\n")

	for _,elem := range resp {
		writer.WriteString(strconv.Itoa(elem.start))
		writer.WriteByte(' ')
		writer.WriteString(strconv.Itoa(elem.end))
		writer.WriteString("\n")
	}

}

// Codeforces problem 620C Shemchug
package main

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

type slr struct {
    l int
    r int
}

func main() {
    reader := bufio.NewReader(os.Stdin)
    // read n
    s, _ := reader.ReadString('\n')
    ss := strings.Split(strings.TrimSpace(s), " ")
    n,_ := strconv.Atoi(ss[0])
    // read a
    s, _ = reader.ReadString('\n')
    ss = strings.Split(strings.TrimSpace(s), " ")
    a := make([]int, n)
    for i:=0; i<n; i++ {
        a[i],_ = strconv.Atoi(ss[i])
    }

    mp := make(map[int]int,0)
    var olr []slr

    // calculate olr
    for i:=0; i<n; i++ {
        c := a[i]
        l,was := mp[c]
        if !was {
            // no match
            mp[c] = i
        } else {
            lr := slr{l:l+1, r:i+1}
            olr = append(olr, lr)
            mp = make(map[int]int,0) // clear mp
        }
    }

    // prepare and print answer
    m := len(olr)
    if m==0 {
        fmt.Println("-1")
        return
    }
    // making all list belong to some lr
    olr[0].l = 1
    olr[m-1].r = n
    for i:=1; i<m; i++ {
        olr[i].l = olr[i-1].r+1
    }
    fmt.Println(m)
    for i:=0; i<m; i++ {
        fmt.Println(olr[i].l, olr[i].r)
    }
}

package main

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

type pair struct {
	left, right int
}

type set map[interface{}]struct{}

func newSet() set {
	return make(set)
}

func (set *set) Contains(item interface{}) bool {
	_, ok := (*set)[item]
	return ok
}

func (set *set) Add(item interface{}) {
	(*set)[item] = struct{}{}
}

func solve(a []int) []pair {
	var segments []pair
	set := newSet()
	left := 1
	for i, x := range a {
		if set.Contains(x) {
			set = newSet()
			segments = append(segments, pair{left: left, right: i + 1})
			left = i + 2
		} else {
			set.Add(x)
		}
	}
	return segments
}

func main() {
	// buffered I/O
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)

	var n int

	//	fmt.Scan(&n)
	scanner.Scan()
	n, _ = strconv.Atoi(scanner.Text())

	a := make([]int, n)
	for i := 0; i < n; i++ {
		//		fmt.Scan(&a[i])
		scanner.Scan()
		a[i], _ = strconv.Atoi(scanner.Text())
	}

	segments := solve(a)
	length := len(segments)
	var left, right int

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

	if length == 0 {
		// fmt.Println(-1)
		fmt.Fprintln(writer, -1)
		return
	} else {
		// fmt.Println(length)
		fmt.Fprintln(writer, length)
		for i, x := range segments {
			left = x.left
			right = x.right
			if i == length - 1 {
				right = n
			}
			// fmt.Println(left, right)
			fmt.Fprintln(writer, left, right)
		}
	}
}

package main

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

type segment struct {
    start int
    end int
}

func main() {
    var a [300000]int
    var segments []segment
    stin := bufio.NewReader(os.Stdin)
    ns,_ := stin.ReadBytes('\n')
    n,_ := strconv.Atoi(string(bytes.Trim(ns,"\n\r ")))
//    fmt.Printf("%d\n\r", n)
    for i := 0; i < n; i++ {
        tmp,_ := stin.ReadBytes(' ')
        a[i],_ = strconv.Atoi(string(bytes.Trim(tmp," ")))
    }
    var g map[int]int = make(map[int]int)
    var left int = 0
    var right int = 0
    for i := 0; i < n; i++ {
        right = i
        if g[a[i]] == 1 { //already in map
            for k := range g {
                delete(g, k)
            }
            segments = append(segments, segment{start: left, end: right})
            left = i+1
        } else {
            g[a[i]] = 1
        }
    }
    kkl := len(segments)
    if kkl == 0 {
        fmt.Println("-1")
        return
    }
    segments[kkl-1].end = n-1
    fmt.Printf("%d\n", kkl)
    for k := 0; k < kkl; k++ {
        fmt.Printf("%d %d\n", segments[k].start+1, segments[k].end+1)
    }
}

package main

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

type pair struct {
	left, right int
}

type set map[interface{}]struct{}

func newSet() set {
	return make(set)
}

func (set *set) Contains(item interface{}) bool {
	_, ok := (*set)[item]
	return ok
}

func (set *set) Add(item interface{}) {
	(*set)[item] = struct{}{}
}

func solve(a []int) []pair {
	var segments []pair
	set := newSet()
	left := 1
	for i, x := range a {
		if set.Contains(x) {
			set = newSet()
			segments = append(segments, pair{left: left, right: i + 1})
			left = i + 2
		} else {
			set.Add(x)
		}
	}
	return segments
}

func main() {
	// buffered I/O
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)

	var n int

//	fmt.Scan(&n)
	scanner.Scan()
	n, _ = strconv.Atoi(scanner.Text())

	a := make([]int, n)
	for i := 0; i < n; i++ {
//		fmt.Scan(&a[i])
		scanner.Scan()
		a[i], _ = strconv.Atoi(scanner.Text())
	}

	segments := solve(a)
	length := len(segments)
	var left, right int

	writer := bufio.NewWriter(os.Stdout)

	if length == 0 {
//		fmt.Println(-1)
		fmt.Fprintln(writer, -1)
		return
	}

//	fmt.Println(length)
	fmt.Fprintln(writer, length)
	for i, x := range segments {
		left = x.left
		right = x.right
		if i == length-1 {
			right = n
		}
//		fmt.Println(left, right)
		fmt.Fprintln(writer, left, right)
	}
	writer.Flush()
}


A matrix of size $$$n \times m$$$ is called nice, if all rows and columns of the matrix are palindromes. A sequence of integers $$$(a_1, a_2, \dots , a_k)$$$ is a palindrome, if for any integer $$$i$$$ ($$$1 \le i \le k$$$) the equality $$$a_i = a_{k - i + 1}$$$ holds.Sasha owns a matrix $$$a$$$ of size $$$n \times m$$$. In one operation he can increase or decrease any number in the matrix by one. Sasha wants to make the matrix nice. He is interested what is the minimum number of operations he needs.Help him!

The first line contains a single integer $$$t$$$ — the number of test cases ($$$1 \le t \le 10$$$). The $$$t$$$ tests follow. The first line of each test contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 100$$$) — the size of the matrix. Each of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i, j}$$$ ($$$0 \le a_{i, j} \le 10^9$$$) — the elements of the matrix.

For each test output the smallest number of operations required to make the matrix nice.

NoteIn the first test case we can, for example, obtain the following nice matrix in $$$8$$$ operations:2 24 44 42 2In the second test case we can, for example, obtain the following nice matrix in $$$42$$$ operations:5 6 6 56 6 6 65 6 6 5

package main

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

var in *bufio.Reader
var out *bufio.Writer

func printf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(out, x, a...)
}

func scanf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fscanf(in, x, a...)
}

func scan(a ...interface{}) (n int, err error) {
	return fmt.Fscan(in, a...)
}

var err error

func next() (n string) {
	scan(&n)
	return n
}

func nextInt() (n int) {
	scan(&n)
	return n
}

func nextLong() (n int64) {
	scan(&n)
	return n
}

func nextDouble() (n float64) {
	scan(&n)
	return n
}

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

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

func solve() {
	n, m := nextInt(), nextInt()
	arr := make([][]int, n)
	for i := range arr {
		arr[i] = make([]int, m)
		for j := range arr[i] {
			arr[i][j] = nextInt()
		}
	}
	var res int64
	for i := 0; i < n/2; i++ {
		for j := 0; j < m/2; j++ {
			nums := []int{arr[i][j], arr[n-i-1][j], arr[n-i-1][m-j-1], arr[i][m-j-1]}
			sort.Ints(nums)
			res += int64(nums[1] - nums[0] + nums[2] - nums[1] + nums[3] - nums[1])
		}
	}
	if n%2 == 1 {
		for i := 0; i < m/2; i++ {
			res += int64(Abs(arr[n/2][i] - arr[n/2][m-i-1]))
		}
	}

	if m%2 == 1 {
		for i := 0; i < n/2; i++ {
			res += int64(Abs(arr[i][m/2] - arr[n-i-1][m/2]))
		}
	}

	printf("%d\n", res)
}

func main() {
	in = bufio.NewReaderSize(os.Stdin, 8192)
	out = bufio.NewWriterSize(os.Stdout, 8192)
	name := "in"
	file1, err := os.Open(name + ".in")
	if err == nil {
		in = bufio.NewReaderSize(file1, 8192)
	}
	// file2, err := os.Create(name + ".out")
	// if err != nil {
	// 	log.Fatal(err)
	// }
	// out = bufio.NewWriterSize(file2, 8192)
	defer out.Flush()
	// start := time.Now()

	for t, i := nextInt(), 1; t > 0; t, i = t-1, i+1 {
		// printf("Case #%d:\n", i)
		solve()
	}

	// printf("%v\n", time.Now().Sub(start))
}

package main

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

func main() {
	t := ReadInt()
	for i := 0; i < t; i++ {
		n, m := ReadInt(), ReadInt()
		matrix := make([][]int64, n)
		for i := 0; i < n; i++ {
			matrix[i] = ReadInts64(m)
		}
		fmt.Println(solve(n, m, matrix))
	}
}

func solve(n, m int, matrix [][]int64) int64 {
	ans := int64(0)
	for i := 0; i < (n+1)/2; i++ {
		for j := 0; j < (m+1)/2; j++ {
			a, b := n-i-1, m-j-1
			if i == a && j == b {
				continue
			}
			if i == a || j == b {
				ans += Abs(matrix[i][j] - matrix[a][b])
				continue
			}

			ary := []int64{
				matrix[i][j],
				matrix[a][j],
				matrix[i][b],
				matrix[a][b],
			}
			sort.Slice(ary, func(i, j int) bool {
				return ary[i] < ary[j]
			})
			median := ary[len(ary)/2]
			for i := 0; i < len(ary); i++ {
				ans += Abs(ary[i] - median)
			}
		}
	}
	return ans
}

func Abs(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

var reader = bufio.NewReader(os.Stdin)

func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(reader, a...); err != nil {
		panic(err)
	}
}
func ReadString() (s string) { Scan(&s); return }
func ReadInt() (i int)       { Scan(&i); return }
func ReadInts64(n int) []int64 {
	v := make([]int64, n)
	for i := 0; i < n; i++ {
		Scan(&v[i])
	}
	return v
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1422B(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	abs := func(x int) int {
		if x < 0 {
			return -x
		}
		return x
	}
	var T, n, m int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &m)
		a := make([][]int, n)
		for i := range a {
			a[i] = make([]int, m)
			for j := range a[i] {
				Fscan(in, &a[i][j])
			}
		}
		s := int64(0)
		for i := 0; 2*i < n; i++ {
			if 2*i+1 == n {
				for j, v := range a[i][:m/2] {
					s += int64(abs(v - a[i][m-1-j]))
				}
				continue
			}
			for j := 0; 2*j < m; j++ {
				b := []int{a[i][j], a[n-1-i][j]}
				if 2*j+1 == m {
					s += int64(abs(b[0] - b[1]))
					continue
				}
				b = append(b, a[i][m-1-j], a[n-1-i][m-1-j])
				sort.Ints(b)
				s += int64(b[3]-b[1]) + int64(b[2]-b[0])
			}
		}
		Fprintln(out, s)
	}
}

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

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var t int
	fmt.Fscan(reader, &t)

	for i := 0; i < t; i++ {
		var n, m int
		fmt.Fscan(reader, &n, &m)

		matrix := make([][]int, n)
		used := make([][]bool, n)

		for j := 0; j < n; j++ {
			for k := 0; k < m; k++ {
				var x int
				fmt.Fscan(reader, &x)
				matrix[j] = append(matrix[j], x)
				used[j] = append(used[j], false)
			}
		}

		var cost int64 = 0
		for j := 0; j < n; j++ {
			for k := 0; k < m; k++ {
				if used[j][k] {
					continue
				}

				parts := []int{}
				xs := []int{j, j, n - j - 1, n - j - 1}
				ys := []int{k, m - k - 1, k, m - k - 1}

				for l := 0; l < 4; l++ {
					if used[xs[l]][ys[l]] {
						continue
					}

					parts = append(parts, matrix[xs[l]][ys[l]])
					used[xs[l]][ys[l]] = true
				}

				sort.Ints(parts)
				median := parts[len(parts)/2]
				for _, p := range parts {
					cost += int64(abs(p - median))
				}

				// fmt.Println(parts)
			}
		}

		fmt.Println(cost)
	}
}

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

	return a
}

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

	return b
}

func second_largest(a, b, c, d int) int {
	arr := []int{a, b, c, d}

	sort.Ints(arr)

	return arr[1]
}

package main

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

func main() {
	t := ReadInt()
	for i := 0; i < t; i++ {
		n, m := ReadInt(), ReadInt()
		matrix := make([][]int, n)
		for i := 0; i < n; i++ {
			matrix[i] = ReadInts(m)
		}
		fmt.Println(solve(n, m, matrix))
	}
}

func solve(n, m int, matrix [][]int) int {
	ans := 0
	for i := 0; i < (n+1)/2; i++ {
		for j := 0; j < (m+1)/2; j++ {
			a, b := n-i-1, m-j-1
			if i == a && j == b {
				continue
			}
			if i == a || j == b {
				ans += Abs(matrix[i][j] - matrix[a][b])
				continue
			}

			ary := []int{
				matrix[i][j],
				matrix[a][j],
				matrix[i][b],
				matrix[a][b],
			}
			sort.Ints(ary)
			median := ary[len(ary)/2]
			for i := 0; i < len(ary); i++ {
				ans += Abs(ary[i] - median)
			}
		}
	}
	return ans
}

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

var reader = bufio.NewReader(os.Stdin)

func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(reader, a...); err != nil {
		panic(err)
	}
}
func ReadString() (s string) { Scan(&s); return }
func ReadInt() (i int)       { Scan(&i); return }
func ReadInts(n int) []int {
	v := make([]int, n)
	for i := 0; i < n; i++ {
		Scan(&v[i])
	}
	return v
}

package main

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

func main() {
	t := ReadInt()
	for i := 0; i < t; i++ {
		n, m := ReadInt(), ReadInt()
		matrix := make([][]int, n)
		for i := 0; i < n; i++ {
			matrix[i] = ReadInts(m)
		}
		fmt.Println(solve(n, m, matrix))
	}
}

func solve(n, m int, matrix [][]int) int {
	ans := 0
	for i := 0; i < (n+1)/2; i++ {
		for j := 0; j < (m+1)/2; j++ {
			a, b := n-i-1, m-j-1
			ary := []int{
				matrix[i][j],
				matrix[a][j],
				matrix[i][b],
				matrix[a][b],
			}
			sort.Ints(ary)
			median := ary[len(ary)/2]
			c := 0
			for i := 0; i < len(ary); i++ {
				c += Abs(ary[i] - median)
			}
			if i == a || j == b {
				c /= 2
			}
			ans += c
		}
	}
	return ans
}

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

var reader = bufio.NewReader(os.Stdin)

func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(reader, a...); err != nil {
		panic(err)
	}
}
func ReadString() (s string) { Scan(&s); return }
func ReadInt() (i int)       { Scan(&i); return }
func ReadInts(n int) []int {
	v := make([]int, n)
	for i := 0; i < n; i++ {
		Scan(&v[i])
	}
	return v
}

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var t int
	fmt.Fscan(reader, &t)

	for i := 0; i < t; i++ {
		var n, m int
		fmt.Fscan(reader, &n, &m)

		matrix := make([][]int, n)

		for j := 0; j < n; j++ {
			for k := 0; k < m; k++ {
				var x int
				fmt.Fscan(reader, &x)

				matrix[j] = append(matrix[j], x)
			}
		}

		moves := 0
		for j := 0; j < (n+1)/2; j++ {
			for k := 0; k < (m+1)/2; k++ {
				curr := matrix[j][k]
				right := matrix[j][m-k-1]
				down := matrix[n-j-1][k]
				right_down := matrix[n-j-1][m-k-1]

				val := second_largest(curr, right, down, right_down)

				if (n - j - 1) == j {
					moves += abs(val-curr) + abs(val-right)
				} else {
					moves += abs(val-curr) + abs(val-right) + abs(val-down) + abs(val-right_down)
				}
			}
		}

		fmt.Println(moves)
	}
}

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

	return a
}

func second_largest(a, b, c, d int) int {
	arr := []int{a, b, c, d}

	sort.Ints(arr)

	fmt.Println(arr)

	return arr[2]
}

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var t int
	fmt.Fscan(reader, &t)

	for i := 0; i < t; i++ {
		var n, m int
		fmt.Fscan(reader, &n, &m)

		matrix := make([][]int, n)

		for j := 0; j < n; j++ {
			for k := 0; k < m; k++ {
				var x int
				fmt.Fscan(reader, &x)

				matrix[j] = append(matrix[j], x)
			}
		}

		moves := 0
		for j := 0; j < (n+1)/2; j++ {
			for k := 0; k < (m+1)/2; k++ {
				curr := matrix[j][k]
				right := matrix[j][m-k-1]
				down := matrix[n-j-1][k]
				right_down := matrix[n-j-1][m-k-1]

				val := second_largest(curr, right, down, right_down)

				if (n - j - 1) == j {
					moves += abs(val-curr) + abs(val-right)
				} else {
					moves += abs(val-curr) + abs(val-right) + abs(val-down) + abs(val-right_down)
				}
			}
		}

		fmt.Println(moves)
	}
}

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

	return a
}

func second_largest(a, b, c, d int) int {
	arr := []int{a, b, c, d}

	sort.Ints(arr)

	return arr[2]
}

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var t int
	fmt.Fscan(reader, &t)

	for i := 0; i < t; i++ {
		var n, m int
		fmt.Fscan(reader, &n, &m)

		matrix := make([][]int, n)

		for j := 0; j < n; j++ {
			for k := 0; k < m; k++ {
				var x int
				fmt.Fscan(reader, &x)
				matrix[j] = append(matrix[j], x)
			}
		}

		var cost int64 = 0

		for j := 0; j < (n+1)/2; j++ {
			for k := 0; k < (m+1)/2; k++ {
				curr := matrix[j][k]
				right := matrix[j][m-k-1]
				down := matrix[n-j-1][k]
				right_down := matrix[n-j-1][m-k-1]

				val := second_largest(curr, right, down, right_down)

				if (n - j - 1) == j {
					cost += int64(abs(val-curr) + abs(val-right))
				} else {
					cost += int64(abs(val-curr) + abs(val-right) + abs(val-down) + abs(val-right_down))
				}
			}
		}

		fmt.Println(cost)
	}
}

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

	return a
}

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

	return b
}

func second_largest(a, b, c, d int) int {
	arr := []int{a, b, c, d}

	sort.Ints(arr)

	return arr[1]
}

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var t int
	fmt.Fscan(reader, &t)

	for i := 0; i < t; i++ {
		var n, m int
		fmt.Fscan(reader, &n, &m)

		matrix := make([][]int, n)

		for j := 0; j < n; j++ {
			for k := 0; k < m; k++ {
				var x int
				fmt.Fscan(reader, &x)

				matrix[j] = append(matrix[j], x)
			}
		}

		moves := 0
		for j := 0; j < (n+1)/2; j++ {
			for k := 0; k < (m+1)/2; k++ {
				curr := matrix[j][k]
				right := matrix[j][m-k-1]
				down := matrix[n-j-1][k]
				right_down := matrix[n-j-1][m-k-1]

				val := second_largest(curr, right, down, right_down)

				if (n - j - 1) == j {
					moves += abs(val-curr) + abs(val-right)
				} else {
					moves += abs(val-curr) + abs(val-right) + abs(val-down) + abs(val-right_down)
				}
			}
		}

		fmt.Println(moves)
	}
}

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 second_largest(a, b, c, d int) int {
	arr := []int{a, b, c, d}

	sort.Ints(arr)

	return arr[1]
}

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var t int
	fmt.Fscan(reader, &t)

	for i := 0; i < t; i++ {
		var n, m int
		fmt.Fscan(reader, &n, &m)

		matrix := make([][]int, n)

		for j := 0; j < n; j++ {
			for k := 0; k < m; k++ {
				var x int
				fmt.Fscan(reader, &x)

				matrix[j] = append(matrix[j], x)
			}
		}

		moves := 0
		for j := 0; j < (n+1)/2; j++ {
			for k := 0; k < (m+1)/2; k++ {
				if (n - j - 1) == j {
					curr := matrix[j][k]
					right := matrix[j][m-k-1]

					val := min(curr, right)

					moves += abs(val-curr) + abs(val-right)
				} else {
					curr := matrix[j][k]
					right := matrix[j][m-k-1]
					down := matrix[n-j-1][k]
					right_down := matrix[n-j-1][m-k-1]

					val := second_largest(curr, right, down, right_down)

					moves += abs(val-curr) + abs(val-right) + abs(val-down) + abs(val-right_down)
				}
			}
		}

		fmt.Println(moves)
	}
}

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 second_largest(a, b, c, d int) int {
	arr := []int{a, b, c, d}

	sort.Ints(arr)

	return arr[2]
}

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var t int
	fmt.Fscan(reader, &t)

	for i := 0; i < t; i++ {
		var n, m int
		fmt.Fscan(reader, &n, &m)

		matrix := make([][]int, n)

		for j := 0; j < n; j++ {
			for k := 0; k < m; k++ {
				var x int
				fmt.Fscan(reader, &x)
				matrix[j] = append(matrix[j], x)
			}
		}

		moves := 0
		for j := 0; j < n/2; j++ {
			for k := 0; k < m/2; k++ {
				curr := matrix[j][k]
				right := matrix[j][m-k-1]
				down := matrix[n-j-1][k]
				right_down := matrix[n-j-1][m-k-1]

				val := second_largest(curr, right, down, right_down)

				moves += abs(val-curr) + abs(val-right) + abs(val-down) + abs(val-right_down)
			}
		}

		if n%2 == 1 {
			row := n / 2
			for j := 0; j < m/2; j++ {
				moves += abs(matrix[row][j] - matrix[row][m-j-1])
			}
		}

		fmt.Println(moves)
	}
}

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

	return a
}

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

	return b
}

func second_largest(a, b, c, d int) int {
	arr := []int{a, b, c, d}

	sort.Ints(arr)

	return arr[1]
}

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var t int
	fmt.Fscan(reader, &t)

	for i := 0; i < t; i++ {
		var n, m int
		fmt.Fscan(reader, &n, &m)

		matrix := make([][]int, n)
		used := make([][]bool, n)

		for j := 0; j < n; j++ {
			for k := 0; k < m; k++ {
				var x int
				fmt.Fscan(reader, &x)
				matrix[j] = append(matrix[j], x)
				used[j] = append(used[j], false)
			}
		}

		cost := 0
		for j := 0; j < n; j++ {
			for k := 0; k < m; k++ {
				if used[j][k] {
					continue
				}

				parts := []int{}
				xs := []int{j, j, n - j - 1, n - j - 1}
				ys := []int{k, m - k - 1, k, m - k - 1}

				for l := 0; l < 4; l++ {
					if used[xs[l]][ys[l]] {
						continue
					}

					parts = append(parts, matrix[xs[l]][ys[l]])
					used[xs[l]][ys[l]] = true
				}

				sort.Ints(parts)
				median := parts[len(parts)/2]

				for _, p := range parts {
					cost += abs(p - median)
				}

				// fmt.Println(parts)
			}
		}

		fmt.Println(cost)
	}
}

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

	return a
}

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

	return b
}

func second_largest(a, b, c, d int) int {
	arr := []int{a, b, c, d}

	sort.Ints(arr)

	return arr[1]
}

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var t int
	fmt.Fscan(reader, &t)

	for i := 0; i < t; i++ {
		var n, m int
		fmt.Fscan(reader, &n, &m)

		matrix := make([][]int, n)

		for j := 0; j < n; j++ {
			for k := 0; k < m; k++ {
				var x int
				fmt.Fscan(reader, &x)
				matrix[j] = append(matrix[j], x)
			}
		}

		var cost int64 = 0

		for j := 0; j < n/2; j++ {
			for k := 0; k < m/2; k++ {
				curr := matrix[j][k]
				right := matrix[j][m-k-1]
				down := matrix[n-j-1][k]
				right_down := matrix[n-j-1][m-k-1]

				val := second_largest(curr, right, down, right_down)

				cost += int64(abs(val-curr) + abs(val-right) + abs(val-down) + abs(val-right_down))
			}
		}

		if n%2 == 1 {
			row := n / 2
			for j := 0; j < m/2; j++ {
				cost += int64(abs(matrix[row][j] - matrix[row][m-j-1]))
			}
		}

		fmt.Println(cost)
	}
}

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

	return a
}

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

	return b
}

func second_largest(a, b, c, d int) int {
	arr := []int{a, b, c, d}

	sort.Ints(arr)

	return arr[1]
}


LiLand is a country, consisting of n cities. The cities are numbered from 1 to n. The country is well known because it has a very strange transportation system. There are many one-way flights that make it possible to travel between the cities, but the flights are arranged in a way that once you leave a city you will never be able to return to that city again.Previously each flight took exactly one hour, but recently Lily has become the new manager of transportation system and she wants to change the duration of some flights. Specifically, she wants to change the duration of some flights to exactly 2 hours in such a way that all trips from city 1 to city n take the same time regardless of their path.Your task is to help Lily to change the duration of flights.

First line of the input contains two integer numbers n and m (2 ≤ n ≤ 1000; 1 ≤ m ≤ 5000) specifying the number of cities and the number of flights. Each of the next m lines contains two integers ai and bi (1 ≤ ai < bi ≤ n) specifying a one-directional flight from city ai to city bi. It is guaranteed that there exists a way to travel from city number 1 to city number n using the given flights. It is guaranteed that there is no sequence of flights that forms a cyclical path and no two flights are between the same pair of cities.

If it is impossible for Lily to do her task, print "No" (without quotes) on the only line of the output.  Otherwise print "Yes" (without quotes) on the first line of output, then print an integer ansi (1 ≤ ansi ≤ 2) to each of the next m lines being the duration of flights in new transportation system. You should print these numbers in the order that flights are given in the input. If there are multiple solutions for the input, output any of them.

package main

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

type edge struct {
	to, id int
}

func main() {
	in := bufio.NewReaderSize(os.Stdin, 2<<16)
	var n, m int
	fmt.Fscan(in, &n, &m)
	edges := make([][]edge, n+1)
	for i := 0; i < m; i++ {
		var from, to int
		fmt.Fscan(in, &from, &to)
		edges[from] = append(edges[from], edge{to, i})
	}

	relevant := make([]int, n+1)
	relevant[n] = 1
	var findRelevant func(v int) bool
	findRelevant = func(v int) (ret bool) {
		if relevant[v] != 0 {
			return relevant[v] == 1
		}
		defer func() {
			if ret {
				relevant[v] = 1
			} else {
				relevant[v] = -1
			}
		}()

		ret = false
		for _, e := range edges[v] {
			if findRelevant(e.to) {
				ret = true
			}
		}
		return ret
	}
	findRelevant(1)

	dist := make([]int, n+1)
	for i := 2; i <= n; i++ {
		dist[i] = 1e9
	}
	ts := 1
	var update func(v int) bool
	update = func(v int) bool {
		relevant[v]++
		ret := false
		for _, e := range edges[v] {
			if relevant[e.to] <= 0 {
				continue
			}
			if dist[v]+2 < dist[e.to] {
				dist[e.to] = dist[v] + 2
				ret = true
			}
			if dist[v] > dist[e.to]-1 {
				dist[v] = dist[e.to] - 1
				ret = true
			}
			if relevant[e.to] == ts {
				if update(e.to) {
					ret = true
				}
			}
		}
		return ret
	}

	for ; ts <= n; ts++ {
		update(1)
	}
	if update(1) {
		fmt.Println("No")
		return
	}
	out := bufio.NewWriterSize(os.Stdout, 2<<16)
	defer out.Flush()
	fmt.Fprintln(out, "Yes")
	ans := make([]int, m)
	for from, es := range edges {
		for _, e := range es {
			if relevant[from] <= 0 || relevant[e.to] <= 0 {
				ans[e.id] = 1
				continue
			}
			ans[e.id] = dist[e.to] - dist[from]
		}
	}
	for _, ans := range ans {
		fmt.Fprintln(out, ans)
	}
}

package main

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

type edge struct {
	to, id, cost int
}

func main() {
	in := bufio.NewReaderSize(os.Stdin, 2<<16)
	var n, m int
	fmt.Fscan(in, &n, &m)
	edges := make([][]edge, n+1)
	for i := 0; i < m; i++ {
		var from, to int
		fmt.Fscan(in, &from, &to)
		edges[from] = append(edges[from], edge{to, i, 1})
	}

	storedMax := make([]int, n+1)
	var maxDist func(v int) (int, bool)
	maxDist = func(v int) (int, bool) {
		if v == n {
			return 0, true
		}
		if len(edges) == 0 {
			return 0, false
		}
		max := 0
		for _, e := range edges[v] {
			if d, ok := maxDist(e.to); ok && max < d+1 {
				max = d + 1
			}
		}
		storedMax[v] = max
		return max, max > 0
	}

	var makeDist func(v, dist int) bool
	makeDist = func(v, dist int) bool {
		if v == n {
			return dist == 0
		}
		if storedMax[v] == 0 {
			return true
		}
		for i, e := range edges[v] {
			if storedMax[e.to]+1 < dist {
				edges[v][i].cost = 2
				if !makeDist(e.to, dist-2) {
					return false
				}
			} else {
				if !makeDist(e.to, dist-1) {
					return false
				}
			}
		}
		return true
	}

	max, ok := maxDist(1)
	if !ok {
		panic("no way")
	}
	if !makeDist(1, max) {
		fmt.Println("No")
		return
	}
	if d, _ := maxDist(1); d != max {
		fmt.Println("No")
		return
	}
	out := bufio.NewWriterSize(os.Stdout, 2<<16)
	defer out.Flush()
	fmt.Fprintln(out, "Yes")
	ans := make([]int, m)
	for _, es := range edges {
		for _, e := range es {
			ans[e.id] = e.cost
		}
	}
	for _, ans := range ans {
		fmt.Fprintln(out, ans)
	}
}

package main

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

type edge struct {
	to, id int
}

func main() {
	in := bufio.NewReaderSize(os.Stdin, 2<<16)
	var n, m int
	fmt.Fscan(in, &n, &m)
	edges := make([][]edge, n+1)
	for i := 0; i < m; i++ {
		var from, to int
		fmt.Fscan(in, &from, &to)
		edges[from] = append(edges[from], edge{to, i})
	}

	relevant := make([]int, n+1)
	relevant[n] = 1
	var findRelevant func(v int) bool
	findRelevant = func(v int) (ret bool) {
		if relevant[v] != 0 {
			return relevant[v] == 1
		}
		defer func() {
			if ret {
				relevant[v] = 1
			} else {
				relevant[v] = -1
			}
		}()

		ret = false
		for _, e := range edges[v] {
			if findRelevant(e.to) {
				ret = true
			}
		}
		return ret
	}
	findRelevant(1)

	dist := make([]int, n+1)
	for i := 2; i <= n; i++ {
		dist[i] = 1e9
	}
	ts := 1
	var update func(v int) bool
	update = func(v int) bool {
		relevant[v]++
		ret := false
		for _, e := range edges[v] {
			if relevant[e.to] == -1 {
				continue
			}
			if dist[v]+2 < dist[e.to] {
				dist[e.to] = dist[v] + 2
				ret = true
			}
			if dist[v] > dist[e.to]-1 {
				dist[v] = dist[e.to] - 1
				ret = true
			}
			if relevant[e.to] == ts {
				if update(e.to) {
					ret = true
				}
			}
		}
		return ret
	}

	for ; ts <= n; ts++ {
		update(1)
	}
	if update(1) {
		fmt.Println("No")
		return
	}
	out := bufio.NewWriterSize(os.Stdout, 2<<16)
	defer out.Flush()
	fmt.Fprintln(out, "Yes")
	ans := make([]int, m)
	for from, es := range edges {
		for _, e := range es {
			if relevant[from] == -1 || relevant[e.to] == -1 {
				ans[e.id] = 1
				continue
			}
			ans[e.id] = dist[e.to] - dist[from]
		}
	}
	for _, ans := range ans {
		fmt.Fprintln(out, ans)
	}
}


Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.You are given a tree with $$$n$$$ nodes. In the beginning, $$$0$$$ is written on all edges. In one operation, you can choose any $$$2$$$ distinct leaves $$$u$$$, $$$v$$$ and any real number $$$x$$$ and add $$$x$$$ to values written on all edges on the simple path between $$$u$$$ and $$$v$$$.For example, on the picture below you can see the result of applying two operations to the graph: adding $$$2$$$ on the path from $$$7$$$ to $$$6$$$, and then adding $$$-0.5$$$ on the path from $$$4$$$ to $$$5$$$.   Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?Leaf is a node of a tree of degree $$$1$$$. Simple path is a path that doesn't contain any node twice.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$), meaning that there is an edge between nodes $$$u$$$ and $$$v$$$. It is guaranteed that these edges form a tree.

If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO".  Otherwise, output "YES".  You can print each letter in any case (upper or lower).

NoteIn the first example, we can add any real $$$x$$$ to the value written on the only edge $$$(1, 2)$$$.  In the second example, one of configurations that we can't reach is $$$0$$$ written on $$$(1, 2)$$$ and $$$1$$$ written on $$$(2, 3)$$$.  Below you can see graphs from examples $$$3$$$, $$$4$$$:

package main

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

func main() {
	//var read, _ = os.Open("dat.txt")
	//var write, _ = os.Create("result.txt")
	var read = bufio.NewReader(os.Stdin)
	var write = bufio.NewWriter(os.Stdout)
	defer write.Flush()
	var n int
	fmt.Fscan(read, &n)
	var a = make([]int, n)
	for i := 0; i < n-1; i++ {
		var u, v int
		fmt.Fscan(read, &u, &v)
		u--
		v--
		a[u]++
		a[v]++
	}
	var res = "YES"
	for i := 0; i < n; i++ {
		if a[i] == 2 {
			res = "NO"
			break
		}
	}
	fmt.Fprint(write, res)
	//read.Close()
	//write.Close()
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n := 0
	fmt.Fscanf(in, "%d\n", &n)
	//	fmt.Println(n)
	edges := make([]int, n)
	for i := 0; i < n-1; i++ {
		a, b := 0, 0
		fmt.Fscanf(in, "%d %d\n", &a, &b)
		a--
		b--
		edges[a]++
		edges[b]++
	}
	ok := true
	for i := 0; i < n; i++ {
		if edges[i] == 2 {
			ok = false
		}
	}
	if ok {
		fmt.Fprintf(out, "YES\n")
		return
	}
	fmt.Fprintf(out, "NO\n")
	return
}
func minstep(a, b byte) int {
	return min(int(a-b+26)%26, int(b-a+26)%26)
}

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

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
)
const (
	MAXN=int(1e5+7)
)
func main(){
	input,err:=ioutil.ReadAll(os.Stdin)
	if err!=nil{
		return
	}
	inputReader:=bytes.NewReader(input)
	var N int
	_,_=fmt.Fscanf(inputReader,"%d\n",&N)
	du:=make([]int,MAXN,MAXN)
	for i:=1;i<N;i++ {
		var x,y int
		_,_=fmt.Fscanf(inputReader,"%d %d\n",&x,&y)
		//fmt.Println(x,y)
		du[x]++
		du[y]++
	}
	hasAns:=true
	for i:=1;i<=N;i++{
		if du[i]==2{
			hasAns=false
		}
	}
	if hasAns{
		fmt.Println("YES")
	}else{
		fmt.Println("NO")
	}
}

package main

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

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

    var n int
    fmt.Fscan(reader, &n)
    deg := make([]int, n)
    for i := 1; i < n; i++ {
        var x,y int
        fmt.Fscan(reader, &x, &y)
        deg[x - 1]++
        deg[y - 1]++
    }
    ans := true
    for i := 0; i < n; i++ {
        if deg[i] == 2 {
            ans = false
        }
    }
    if ans {
        fmt.Println("YES")
    } else {
        fmt.Println("NO")
    }
}

package main

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

func main() {
	//var read, _ = os.Open("dat.txt")
	//var write, _ = os.Create("result.txt")
	var read = bufio.NewReader(os.Stdin)
	var write = bufio.NewWriter(os.Stdout)
	defer write.Flush()
	var n int
	fmt.Fscan(read, &n)
	var a = make([]int, n)
	for i := 0; i < n-1; i++ {
		var u, v int
		fmt.Fscan(read, &u, &v)
		u = u - 1
		v = v - 1
		a[u] = a[u] + 1
		a[v] = a[v] + 1
	}
	var res = "YES"
	for i := 0; i < n-1; i++ {
		if a[i] == 2 {
			res = "NO"
			break
		}
	}
	fmt.Fprint(write, res)
	//read.Close()
	//write.Close()
}


There are $$$n$$$ armchairs, numbered from $$$1$$$ to $$$n$$$ from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than $$$\frac{n}{2}$$$.For some reason, you would like to tell people to move from their armchairs to some other ones. If the $$$i$$$-th armchair is occupied by someone and the $$$j$$$-th armchair is not, you can tell the person sitting in the $$$i$$$-th armchair to move to the $$$j$$$-th armchair. The time it takes a person to move from the $$$i$$$-th armchair to the $$$j$$$-th one is $$$|i - j|$$$ minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?

The first line contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of armchairs. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$). $$$a_i = 1$$$ means that the $$$i$$$-th armchair is initially occupied, $$$a_i = 0$$$ means that it is initially free. The number of occupied armchairs is at most $$$\frac{n}{2}$$$.

Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.

NoteIn the first test, you can perform the following sequence:  ask a person to move from armchair $$$1$$$ to armchair $$$2$$$, it takes $$$1$$$ minute;  ask a person to move from armchair $$$7$$$ to armchair $$$6$$$, it takes $$$1$$$ minute;  ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute. In the second test, you can perform the following sequence:  ask a person to move from armchair $$$1$$$ to armchair $$$4$$$, it takes $$$3$$$ minutes;  ask a person to move from armchair $$$2$$$ to armchair $$$6$$$, it takes $$$4$$$ minutes;  ask a person to move from armchair $$$4$$$ to armchair $$$5$$$, it takes $$$1$$$ minute;  ask a person to move from armchair $$$3$$$ to armchair $$$4$$$, it takes $$$1$$$ minute. In the third test, no seat is occupied so your goal is achieved instantly.

package main

import (
	"bufio"
	. "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()

	var n, v int
	Fscan(in, &n)
	pos := [2][]int{}
	for i := 0; i < n; i++ {
		Fscan(in, &v)
		pos[v] = append(pos[v], i)
	}
	if len(pos[1]) == 0 {
		Fprint(out, 0)
		return
	}

	dp := make([][]int, n+2)
	for i := range dp {
		dp[i] = make([]int, n+2)
		if i > 0 {
			for j := range dp[i] {
				dp[i][j] = 1e9
			}
		}
	}
	mi := make([][]int, n+1)
	for i := range mi {
		mi[i] = make([]int, n+1)
		if i > 0 {
			for j := range mi[i] {
				mi[i][j] = 1e9
			}
		}
	}

	for i, p := range pos[1] {
		i++
		for j := 1; j <= len(pos[0]); j++ {
			dp[i][j] = mi[i-1][j-1] + abs(p-pos[0][j-1])
		}
		for j := 1; j <= len(pos[0]); j++ {
			mi[i][j] = min(mi[i][j-1], dp[i][j])
		}
	}
	ans := int(1e9)
	for _, v := range dp[len(pos[1])] {
		ans = min(ans, v)
	}
	Fprintln(out, ans)
}

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

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

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