Recall that a permutation of length $$$n$$$ is an array where each element from $$$1$$$ to $$$n$$$ occurs exactly once.For a fixed positive integer $$$d$$$, let's define the cost of the permutation $$$p$$$ of length $$$n$$$ as the number of indices $$$i$$$ $$$(1 \le i < n)$$$ such that $$$p_i \cdot d = p_{i + 1}$$$.For example, if $$$d = 3$$$ and $$$p = [5, 2, 6, 7, 1, 3, 4]$$$, then the cost of such a permutation is $$$2$$$, because $$$p_2 \cdot 3 = p_3$$$ and $$$p_5 \cdot 3 = p_6$$$.Your task is the following one: for a given value $$$n$$$, find the permutation of length $$$n$$$ and the value $$$d$$$ with maximum possible cost (over all ways to choose the permutation and $$$d$$$). If there are multiple answers, then print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The single line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print the value $$$d$$$ in the first line, and $$$n$$$ integers in the second line — the permutation itself. If there are multiple answers, then print any of them.

package main
import "fmt"

func main() {
    var testCase int;
    fmt.Scanf("%d ", &testCase);
    for testCase > 0 {
        var n int
        fmt.Scanf("%d ", &n)
        d := 2
        fmt.Println(d)
        mv := make(map[int]bool)
        for i:=1; i<=n; i++ {
            if _, ok := mv[i]; ok{
                continue
            }
            if (i != 1) {
                fmt.Printf(" ")
            }
            fmt.Printf("%d", i)
            mv[i] = true
            for j:=i*d; j<=n; j*=d {
                if _, ok := mv[j]; ok {
                    continue
                }
                fmt.Printf(" %d", j)

                mv[j] = true
            }
        }
        fmt.Printf("\n")
        testCase--;
    }

}

package main
// github.com/jamesgrimard/codeforces
import(
    "fmt"
    "bufio"
    "os"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var n int
		fmt.Fscan(in,&n)
		fmt.Fprintln(out,2)
		p:= make([]int,n)
		tally:=1
		p[0] = 1
		for j:=1;j<n;j++{
			if p[j-1] * 2 <= n {
				p[j] = p[j-1] * 2
				continue
			}
			tally+=2
			p[j] = tally
		}
		for j:=0;j<n;j++{
			fmt.Fprintf(out,"%v ",p[j])
		}
		fmt.Fprintln(out)
	}
}

package main

import (
	"fmt"
	"strings"
)

func solve(n int) []int {
	top := 0
	res := make([]int, n)
	mark := map[int]bool{}

	for i := 1; i <= n; i++ {
		if _, ok := mark[i]; !ok {
			times := i
			for times <= n {
				res[top] = times
				top++
				mark[times] = true
				times *= 2
			}
		}
	}

	return res
}

func main() {
	var test int
	fmt.Scanln(&test)

	for test > 0 {
		test--
		var n int
		fmt.Scanln(&n)

		res := solve(n)

		fmt.Println(2)
		resConv := make([]string, n)
		for i, v := range res {
			resConv[i] = fmt.Sprint(v)
		}
		fmt.Println(strings.Join(resConv, " "))
	}
}

package main

import(
	"fmt"
	"strings"
	"strconv"
)

func solveBOne(n int) (int, []int) {
	var resultD int = 2

	taken := make(map[int]bool)
	taken[1] = true

	left := n - 1
	iter := 1

	var permutation []int
	permutation = append(permutation, 1)
	for left != 0 {
		for i := iter; n + 1 > i; i*=2 {
			_, exists := taken[i]
			if !exists {
				permutation = append(permutation, i)
				taken[i] = true
				left--
			}
		}
		iter += 1
	}

	return resultD, permutation
}

func toString(arr []int) []string {
	var output []string
	for i := 0; len(arr) > i; i++ {
		output = append(output, strconv.Itoa(arr[i]))
	}
	return output
}

func solveB() {
	var t int
	_, err := fmt.Scan(&t)
	if err != nil {
		panic(err)
	}

	for i := 0; t > i; i++ {
		var n int
		_, err := fmt.Scan(&n)
		if err != nil {
			panic(err)
		}

		d, permutations := solveBOne(n)

		permutationsString := strings.Join(toString(permutations), " ")

		fmt.Printf("%d\n", d)
		fmt.Printf("%s\n", permutationsString)

	}
}

func solveA() {
	var t int
	_, err := fmt.Scan(&t)
	if err != nil {
		panic(err)
	}

	for i := 0; t > i; i++ {
		var a []int
		for j := 0; 2 > j; j++ {
			var v1 int
			var v2 int
			_, err := fmt.Scan(&v1)
			if err != nil {
				panic(err)
			}
			_, err2 := fmt.Scan(&v2)
			if err2 != nil {
				panic(err)
			}
			a = append(a, v1, v2)
		}

		if a[0] + a[1] + a[2] + a[3] == 4 {
			fmt.Println("2")
		} else if a[0] + a[1] + a[2] + a[3] == 0 {
			fmt.Println("0")
		} else {
			fmt.Println("1")
		}
	}
}

func main() {
	solveB()
}

package main

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

type CF1701B struct {
	sc        *bufio.Reader
	split     []string
	index     int
	separator string
}

func (in *CF1701B) GetLine() string {
	line, err := in.sc.ReadString('\n')
	if err != nil {
		fmt.Println("error line:", line, " err: ", err)
	}
	in.split = []string{}
	in.index = 0
	return line
}
func (in *CF1701B) load() {
	if len(in.split) <= in.index {
		in.split = strings.Split(in.GetLine(), in.separator)
		in.index = 0
	}
}

func (in *CF1701B) NextInt() int {
	in.load()
	val, _ := strconv.Atoi(strings.TrimSpace(in.split[in.index]))
	in.index++
	return val
}

func (in *CF1701B) NextInt64() int64 {
	in.load()
	val, _ := strconv.ParseInt(strings.TrimSpace(in.split[in.index]), 10, 64)
	in.index++
	return val
}

func (in *CF1701B) NextString() string {
	in.load()
	val := strings.TrimSpace(in.split[in.index])
	in.index++
	return val
}

/**
Run solve the problem CF1701B
Date: 18/07/22
User: pepradere
URL: https://codeforces.com/problemset/problem/1701/B
Problem: CF1701B
**/
func (in *CF1701B) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		var ans strings.Builder

		arr := make([]bool, n+1)
		size := 2

		for i := 1; i <= n; i++ {
			if !arr[i] {
				for j := i; j <= n ; j*=size {
					ans.WriteString(fmt.Sprintf("%d ", j))
					arr[j] = true
				}
			}
		}

		fmt.Println(size)
		fmt.Println(ans.String())

	}
}

func NewCF1701B(r *bufio.Reader) *CF1701B {
	return &CF1701B{
		sc:        r,
		split:     []string{},
		index:     0,
		separator: " ",
	}
}

func main() {
	NewCF1701B(bufio.NewReader(os.Stdin)).Run()
}

package main

import (
	"fmt"
)

func main() {
	var test int
	fmt.Scan(&test)
	for t := 1; t <= test; t++ {
		var n int
		fmt.Scan(&n)
		fmt.Println(2)
		// vector := make([]int, 0)
		for i := 1; i <= n; i += 2 {
			for j := i; j <= n; j *= 2 {
				// vector = append(vector, j)
				fmt.Print(j)
				fmt.Print(" ")
			}
		}
		// fmt.Println(vector)
	}
}

// 1701B. Permutation
package main

import (
	"fmt"
)

func main() {
	var T, n int
	fmt.Scan(&T)
	for t := 0; t < T; t++ {
		fmt.Scan(&n)
		fmt.Println(2)
		m := make(map[int]bool)
		l := []interface{}{}
		for i := 1; i <= n/2; i++ {
			if !m[i] && !m[i*2] {
				curr := i
				for curr <= n {
					m[curr] = true
					l = append(l, curr)
					curr = curr * 2
				}
			}
		}
		for i := 1; i <= n; i++ {
			if !m[i] {
				l = append(l, i)
			}
		}
		fmt.Println(l...)
	}
}

package main

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

var (
	reader = bufio.NewReader(os.Stdin)
	t, a   int
)

func solve(n int) string {
	var c int
	var result = make([]int, n)

	for i := 1; i <= n/2; i += 2 {
		for j := i; j <= n; j *= 2 {
			result[c] = j
			c++
		}
	}

	for i := n/2 + 1; i <= n; i++ {
		if i%2 == 1 {
			result[c] = i
			c++
		}
	}
	return "2\n" + strings.Trim(fmt.Sprint(result), "[]")
}

func main() {
	fmt.Fscan(reader, &t)
	for ; t > 0; t-- {
		fmt.Fscan(reader, &a)
		fmt.Println(solve(a))
	}
}

package main

import (
	"fmt"
	"strconv"
	"strings"
)

func main() {

	var t, a int
	fmt.Scanln(&t)

	for i := 0; i < t; i++ {
		fmt.Scanln(&a)

		fmt.Println("2")

		m := make(map[int]bool)
		s := []string{}

		for j := 1; j <= a; j++ {
			for k := j; k <= a; k *= 2 {
				if m[k] {
					continue
				}

				m[k] = true
				s = append(s, strconv.Itoa(k))
			}
		}

		fmt.Println(strings.Join(s, " "))
	}
}

package main

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

func Solve(testCaseIdx int, reader io.Reader, writer io.Writer) {
	var n int
	fmt.Fscan(reader, &n)
	fmt.Fprintln(writer, 2)
	a := make([]bool, n + 1)
	for start := 1; start <= n; start++ {
		if a[start] {
			continue
		}
		for k := start; k <= n; k *= 2 {
			a[k] = true
			fmt.Fprintf(writer, "%d ", k)
		}
	}
	fmt.Fprintln(writer)
}

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

	var testCaseCount int
	fmt.Fscan(reader, &testCaseCount)
	for t := 0; t < testCaseCount; t++ {
		Solve(t, reader, writer)
	}
}

package main

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

var rr = bufio.NewReader(os.Stdin)
var ww = bufio.NewWriter(os.Stdout)

func slove() {
	var n int
	fmt.Fscan(rr, &n)
	fmt.Fprintln(ww, 2)
	cnt := map[int]bool{}
	ans := make([]int, 0)
	for i:=1;i<=n;i++ {
		if !cnt[i] {
			p := i
			for p <= n {
				cnt[p] = true
				ans = append(ans, p)
				p *= 2
			}
		}
	}
	for i:=1;i<n;i++ {
		if !cnt[i] {
			ans = append(ans, i)
		}
	}
	for i := range ans {
		fmt.Fprint(ww, ans[i], " ")
	}
	fmt.Fprint(ww, "\n")
}

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

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 int
		fmt.Fscan(in, &n)
		aa := make([]int, n)
		d := 1
		var idx int
		for d <= n {
			for i := d; i <= n; i *= 2 {
				aa[idx] = i
				idx++
			}
			d += 2
		}
		fmt.Fprintln(out, 2)
		for _, v := range aa {
			fmt.Fprintf(out, "%d ", v)
		}
		fmt.Fprintln(out)
	}
}

package main

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

var in = bufio.NewReader(os.Stdin)

func readInt() int {
	nStr, _ := in.ReadString('\n')
	nStr = strings.ReplaceAll(nStr, "\r", "")
	nStr = strings.ReplaceAll(nStr, "\n", "")
	n, _ := strconv.Atoi(nStr)
	return n
}

func readLine() []string {
	line, _ := in.ReadString('\n')
	line = strings.ReplaceAll(line, "\r", "")
	line = strings.ReplaceAll(line, "\n", "")
	values := strings.Split(line, " ")
	return values
}

func readArrInt() []int {
	line := readLine()
	res := make([]int, 0, 0)
	for i := range line {
		var x, _ = strconv.Atoi(line[i])
		res = append(res, x)
	}
	return res
}

func main() {
	test := readInt()
	for ; 0 < test; test-- {
		n := readInt()
		hs := make(map[int]int)
		fmt.Println("2")
		for i := 1; i <= n; i++ {
			t := i
			for hs[t] == 0 && t <= n {
				hs[t] = 1
				fmt.Printf("%d ", t)
				t *= 2
			}
		}
		fmt.Println()
	}
}

package main

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

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

func init() {
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 4096), 1e9)
}

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

func _int() int {
	s := _string()
	i := 0
	if s[0] == '-' {
		for _, r := range s[1:] {
			i *= 10
			i -= int(r - '0')
		}
		return i
	}
	for _, r := range s {
		i *= 10
		i += int(r - '0')
	}
	return i
}

func _int64() int64 {
	s := _string()
	i := int64(0)
	if s[0] == '-' {
		for _, r := range s[1:] {
			i *= 10
			i -= int64(r - '0')
		}
		return i
	}
	for _, r := range s {
		i *= 10
		i += int64(r - '0')
	}
	return i
}

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

func main() {
	defer writer.Flush()
	for t := _int(); t > 0; t-- {
		n := _int()
		d, a := sol(n)
		printf("%d\n", d)
		for _, i := range a {
			printf("%d ", i)
		}
		printf("\n")
	}
}

func sol(n int) (int, []int) {
	seen := make([]bool, n+1)
	ret := []int{}
	for i := 1; i <= n; i++ {
		for j := i; j <= n; j *= 2 {
			if seen[j] {
				break
			}
			seen[j] = true
			ret = append(ret, j)
		}
	}
	return 2, ret
}

package main
import "fmt"

func main() {
    var testCase int;
    fmt.Scanf("%d ", &testCase);
    for testCase > 0 {
        var n int
        fmt.Scanf("%d ", &n)
        fmt.Println(2)
        mv := make(map[int]bool)
        for i:=1; i*2<=n; i++ {

            if s, ok := mv[i]; ok && s {
                continue
            }
            if s, ok := mv[i*2]; ok && s {
                continue
            }
            if (i != 1) {
                fmt.Print(" ")
            }
            fmt.Printf("%d %d", i, i * 2)
            mv[i] = true
            mv[i*2] = true
        }
        for i:=1; i<=n; i++ {
            if s, ok := mv[i]; ok && s {
                continue
            }
            fmt.Printf(" %d", i)
        }

        fmt.Printf("\n")
        testCase--;
    }

}

package main
import "fmt"

func main() {
    var testCase int;
    fmt.Scanf("%d ", &testCase);
    for testCase > 0 {
        var n int
        fmt.Scanf("%d ", &n)
        fmt.Println(2)
        mv := make(map[int]bool)
        for i:=1; i*2<=n; i++ {

            if _, ok := mv[i]; ok {
                continue
            }
            if _, ok := mv[i*2]; ok {
                continue
            }
            if (i != 1) {
                fmt.Print(" ")
            }
            fmt.Printf("%d %d", i, i * 2)
            mv[i] = true
            mv[i*2] = true
        }
        for i:=1; i<=n; i++ {
            if _, ok := mv[i]; ok {
                continue
            }
            fmt.Printf(" %d", i)
        }

        fmt.Printf("\n")
        testCase--;
    }

}

package main
import "fmt"

func main() {
    var testCase int;
    fmt.Scanf("%d ", &testCase);
    for testCase > 0 {
        var n int
        fmt.Scanf("%d ", &n)
        fmt.Println(2)
        mv := make(map[int]bool)
        for i:=1; i*2<=n; i++ {
            if (i != 1) {
                fmt.Print(" ")
            }
            if _, ok := mv[i]; ok {
                continue
            }
            if _, ok := mv[i*2]; ok {
                continue
            }
            fmt.Printf("%d %d", i, i * 2)
            mv[i] = true
            mv[i*2] = true
        }
        for i:=1; i<=n; i++ {
            if _, ok := mv[i]; ok {
                continue
            }
            fmt.Printf(" %d", i)
        }

        fmt.Printf("\n")
        testCase--;
    }

}

package main
import "fmt"

func main() {
    var testCase int;
    fmt.Scanf("%d ", &testCase);
    for testCase > 0 {
        var n int
        fmt.Scanf("%d ", &n)
        fmt.Printf("%d\n", n)
        fmt.Printf("1 %d", n)
        for i:=2; i<n; i++ {
            fmt.Printf(" %d", i)
        }
        fmt.Printf("\n")
        testCase--;
    }

}

package main
import "fmt"

func main() {
    var testCase int;
    fmt.Scanf("%d ", &testCase);
    for testCase > 0 {
        var n int
        fmt.Scanf("%d ", &n)
        fmt.Printf("1 %d", n)
        for i:=2; i<n; i++ {
            fmt.Printf(" %d", i)
        }
        fmt.Printf("\n")
        testCase--;
    }

}

package main
// github.com/jamesgrimard/codeforces
import(
    "fmt"
    "bufio"
    "os"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var n int
		fmt.Fscan(in,&n)
		fmt.Fprintln(out,n)
		for j:=1;j<=n;j++{
			fmt.Fprintf(out,"%v ",j)
		}
		fmt.Fprintln(out)
	}
}

package main
// github.com/jamesgrimard/codeforces
import(
    "fmt"
    "bufio"
    "os"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var n int
		fmt.Fscan(in,&n)
		fmt.Fprintln(out,1)
		for j:=1;j<=n;j++{
			fmt.Fprintf(out,"%v ",j)
		}
		fmt.Fprintln(out)
	}
}

package main
// github.com/jamesgrimard/codeforces
import(
    "fmt"
    "bufio"
    "os"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var n int
		fmt.Fscan(in,&n)
		for j:=1;j<=n;j++{
			fmt.Fprintf(out,"%v ",j)
		}
		fmt.Fprintln(out)
	}
}

package main

import (
	"fmt"
	"strings"
)

func solve(n int) []int {
	res := make([]int, n)
	res[0] = 1
	times := 1
	top := 0

	mark := map[int]bool{}

	for times < n {
		times = 2 * times
		if times <= n {
			top += 1
			res[top] = times
			mark[times] = true
		}
	}

	for i := 2; i <= n; i++ {
		if _, ok := mark[i]; !ok {
			top += 1
			res[top] = i
		}
	}

	return res
}

func main() {
	var test int
	fmt.Scanln(&test)

	for test > 0 {
		test--
		var n int
		fmt.Scanln(&n)

		res := solve(n)

		fmt.Println(2)
		resConv := make([]string, n)
		for i, v := range res {
			resConv[i] = fmt.Sprint(v)
		}
		fmt.Println(strings.Join(resConv, " "))
	}
}

package main

import (
	"fmt"
	"strings"
)

func solve(n int) (int, []int) {
	res := make([]int, n)
	res[0] = 1
	times := 1
	top := 0

	mark := map[int]bool{}

	for times < n {
		times = 2 * times
		if times <= n {
			top += 1
			res[top] = times
			mark[times] = true
		}
	}

	tmp := top

	for i := 2; i <= n; i++ {
		if _, ok := mark[i]; !ok {
			tmp += 1
			res[tmp] = i
		}
	}

	return top, res
}

func main() {
	var test int
	fmt.Scanln(&test)

	for test > 0 {
		test--
		var n int
		fmt.Scanln(&n)

		top, res := solve(n)

		fmt.Println(top)
		resConv := make([]string, n)
		for i, v := range res {
			resConv[i] = fmt.Sprint(v)
		}
		fmt.Println(strings.Join(resConv, " "))
	}
}

package main

import (
	"fmt"
	"strings"
)

func solve(n int) []int {
	res := make([]int, n)
	res[0] = 1
	res[1] = n
	for i := 2; i <= n-1; i++ {
		res[i] = i
	}
	return res
}

func main() {
	var test int
	fmt.Scanln(&test)

	for test > 0 {
		test--
		var n int
		fmt.Scanln(&n)

		res := solve(n)

		fmt.Println(n)
		resConv := make([]string, n)
		for i, v := range res {
			resConv[i] = fmt.Sprint(v)
		}
		fmt.Println(strings.Join(resConv, " "))
	}
}

package main

import(
	"fmt"
	"strings"
	"strconv"
)

func solveBOne(n int) (int, []int) {
	var resultD int = 2

	taken := make(map[int]bool)
	var permutation []int
	for i := 1; n + 1 > i; i*=2 {
		if i == 1 || i % 2 == 0 {
			permutation = append(permutation, i)
			taken[i] = true
		}
	}
	for i := 1; n + 1 > i; i++ {
		_, exists := taken[i]

		if !exists {
			permutation = append(permutation, i)
		}
	}

	return resultD, permutation
}

func toString(arr []int) []string {
	var output []string
	for i := 0; len(arr) > i; i++ {
		output = append(output, strconv.Itoa(arr[i]))
	}
	return output
}

func solveB() {
	var t int
	_, err := fmt.Scan(&t)
	if err != nil {
		panic(err)
	}

	for i := 0; t > i; i++ {
		var n int
		_, err := fmt.Scan(&n)
		if err != nil {
			panic(err)
		}

		d, permutations := solveBOne(n)

		permutationsString := strings.Join(toString(permutations), " ")

		fmt.Printf("%d\n", d)
		fmt.Printf("%s\n", permutationsString)

	}
}

func solveA() {
	var t int
	_, err := fmt.Scan(&t)
	if err != nil {
		panic(err)
	}

	for i := 0; t > i; i++ {
		var a []int
		for j := 0; 2 > j; j++ {
			var v1 int
			var v2 int
			_, err := fmt.Scan(&v1)
			if err != nil {
				panic(err)
			}
			_, err2 := fmt.Scan(&v2)
			if err2 != nil {
				panic(err)
			}
			a = append(a, v1, v2)
		}

		if a[0] + a[1] + a[2] + a[3] == 4 {
			fmt.Println("2")
		} else if a[0] + a[1] + a[2] + a[3] == 0 {
			fmt.Println("0")
		} else {
			fmt.Println("1")
		}
	}
}

func main() {
	solveB()
}

package main

import(
	"fmt"
	"strings"
	"strconv"
)

func solveBOne(n int) (int, []int) {
	var resultD int = 2

	var permutation []int
	for i := 1; n + 1 > i; i++ {
		if i == 1 || i % 2 == 0 {
			permutation = append(permutation, i)
		}
	}
	for i := 1; n + 1 > i; i++ {
		if !(i == 1 || i % 2 == 0) {
			permutation = append(permutation, i)
		}
	}

	return resultD, permutation
}

func toString(arr []int) []string {
	var output []string
	for i := 0; len(arr) > i; i++ {
		output = append(output, strconv.Itoa(arr[i]))
	}
	return output
}

func solveB() {
	var t int
	_, err := fmt.Scan(&t)
	if err != nil {
		panic(err)
	}

	for i := 0; t > i; i++ {
		var n int
		_, err := fmt.Scan(&n)
		if err != nil {
			panic(err)
		}

		d, permutations := solveBOne(n)

		permutationsString := strings.Join(toString(permutations), " ")

		fmt.Printf("%d\n", d)
		fmt.Printf("%s\n", permutationsString)

	}
}

func solveA() {
	var t int
	_, err := fmt.Scan(&t)
	if err != nil {
		panic(err)
	}

	for i := 0; t > i; i++ {
		var a []int
		for j := 0; 2 > j; j++ {
			var v1 int
			var v2 int
			_, err := fmt.Scan(&v1)
			if err != nil {
				panic(err)
			}
			_, err2 := fmt.Scan(&v2)
			if err2 != nil {
				panic(err)
			}
			a = append(a, v1, v2)
		}

		if a[0] + a[1] + a[2] + a[3] == 4 {
			fmt.Println("2")
		} else if a[0] + a[1] + a[2] + a[3] == 0 {
			fmt.Println("0")
		} else {
			fmt.Println("1")
		}
	}
}

func main() {
	solveB()
}

package main

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

type CF1701B struct {
	sc        *bufio.Reader
	split     []string
	index     int
	separator string
}

func (in *CF1701B) GetLine() string {
	line, err := in.sc.ReadString('\n')
	if err != nil {
		fmt.Println("error line:", line, " err: ", err)
	}
	in.split = []string{}
	in.index = 0
	return line
}
func (in *CF1701B) load() {
	if len(in.split) <= in.index {
		in.split = strings.Split(in.GetLine(), in.separator)
		in.index = 0
	}
}

func (in *CF1701B) NextInt() int {
	in.load()
	val, _ := strconv.Atoi(strings.TrimSpace(in.split[in.index]))
	in.index++
	return val
}

func (in *CF1701B) NextInt64() int64 {
	in.load()
	val, _ := strconv.ParseInt(strings.TrimSpace(in.split[in.index]), 10, 64)
	in.index++
	return val
}

func (in *CF1701B) NextString() string {
	in.load()
	val := strings.TrimSpace(in.split[in.index])
	in.index++
	return val
}

/**
Run solve the problem CF1701B
Date: 18/07/22
User: pepradere
URL: https://codeforces.com/problemset/problem/1701/B
Problem: CF1701B
**/
func (in *CF1701B) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		var ans strings.Builder
		mapa := make(map[int]bool)
		i := 0
		val := 1
		for ; i < n; i++ {
			if val <= n {
				mapa[val] = true
				ans.WriteString(fmt.Sprintf("%d ", val))
			} else {
				break
			}
			val *= 2
		}

		aux := 3
		for ; i < n; i++ {
			if _, ok := mapa[aux]; ok {
				aux++
			}
			ans.WriteString(fmt.Sprintf("%d ", aux))
			aux++
		}

		fmt.Println(2)
		fmt.Println(ans.String())

	}
}

func NewCF1701B(r *bufio.Reader) *CF1701B {
	return &CF1701B{
		sc:        r,
		split:     []string{},
		index:     0,
		separator: " ",
	}
}

func main() {
	NewCF1701B(bufio.NewReader(os.Stdin)).Run()
}

package main

import (
	"fmt"
)

func main() {
	var test int
	fmt.Scan(&test)
	for t := 1; t <= test; t++ {
		var n int
		fmt.Scan(&n)
		vector := make([]int, 0)
		for i := 1; i <= n; i += 2 {
			for j := i; j <= n; j *= 2 {
				vector = append(vector, j)
			}
		}
		fmt.Println(2)
		fmt.Println(vector)
	}
}

// 1701B. Permutation
package main

import (
	"fmt"
)

func main() {
	var T, n int
	fmt.Scan(&T)
	for t := 0; t < T; t++ {
		fmt.Scan(&n)
		fmt.Println(2)
		m := make(map[int]bool)
		l := []interface{}{}
		for i := 1; i <= n/2; i++ {
			if !m[i] && !m[i*2] {
				m[i] = true
				m[i*2] = true
				l = append(l, i)
				l = append(l, i*2)
			}
		}
		for i := 1; i <= n; i++ {
			if !m[i] {
				l = append(l, i)
			}
		}
		fmt.Println(l...)
	}
}


Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where ε < 10 - 7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help.

First line consists of two space separated integers k, q (1 ≤ k, q ≤ 1000) — number of different kinds of orbs and number of queries respectively. Each of the next q lines contain a single integer pi (1 ≤ pi ≤ 1000) — i-th query.

Output q lines. On i-th of them output single integer — answer for i-th query.

package main

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

func solve(k int) []float64 {
	a := make([]float64, k + 1)
	b := make([]float64, k + 1)
	a[0] = 1
	r := make([]float64, 0)
	for a[k] < 0.5001 {
		r = append(r, a[k])
		for i := 0; i <= k; i++ {
			b[i] = 0
		}
		for i := 0; i <= k; i++ {
			b[i] += a[i] * float64(i) / float64(k)
			if i < k {
				b[i + 1] += a[i] * float64(k - i) / float64(k)
			}
		}
		a, b = b, a
	}
	r = append(r, a[k])
	return r
}

func main() {
	cin := NewParser(bufio.NewReaderSize(os.Stdin, 1<<16))
	k := cin.nextInt()
	q := cin.nextInt()
	r := solve(k)
	for i := 0; i < q; i++ {
		p := cin.nextInt()
		d := 1
		for d < len(r) && r[d] < (float64(p) - 1e-7) / 2000 {
			d += 1
		}
		fmt.Printf("%d\n", d)
	}
}

// some io

type ParserReader struct {
	r   io.ByteReader
	err error
	c   byte
}

func NewParser(r io.ByteReader) *ParserReader {
	return &ParserReader{r, nil, 0}
}

func (p *ParserReader) next() error {
	p.c, p.err = p.r.ReadByte()
	return p.err
}

func isDigit(c byte) bool {
	return '0' <= c && c <= '9'
}

func (p *ParserReader) nextUInt64() uint64 {
	for !isDigit(p.c) && p.err == nil {
		p.next()
	}
	var r uint64
	for isDigit(p.c) && p.err == nil {
		r = r*10 + uint64(p.c - '0')
		p.next()
	}
	return r
}

func (p *ParserReader) nextUInt() uint {
	for !isDigit(p.c) && p.err == nil {
		p.next()
	}
	var r uint
	for isDigit(p.c) && p.err == nil {
		r = r*10 + uint(p.c - '0')
		p.next()
	}
	return r
}

func (p *ParserReader) nextInt64() int64 {
	for p.c != '-' && !isDigit(p.c) && p.err == nil {
		p.next()
	}
	var sign bool
	if p.c == '-' {
		sign = true
	}
	r := int64(p.nextUInt64())
	if sign {
		return -r
	}
	return r
}

func (p *ParserReader) nextInt() int {
	for p.c != '-' && !isDigit(p.c) && p.err == nil {
		p.next()
	}
	var sign bool
	if p.c == '-' {
		sign = true
	}
	r := int(p.nextUInt())
	if sign {
		return -r
	}
	return r
}


Makes solves problems on Decoforces and lots of other different online judges. Each problem is denoted by its difficulty — a positive integer number. Difficulties are measured the same across all the judges (the problem with difficulty d on Decoforces is as hard as the problem with difficulty d on any other judge). Makes has chosen n problems to solve on Decoforces with difficulties a1, a2, ..., an. He can solve these problems in arbitrary order. Though he can solve problem i with difficulty ai only if he had already solved some problem with difficulty  (no matter on what online judge was it).Before starting this chosen list of problems, Makes has already solved problems with maximum difficulty k.With given conditions it's easy to see that Makes sometimes can't solve all the chosen problems, no matter what order he chooses. So he wants to solve some problems on other judges to finish solving problems from his list. For every positive integer y there exist some problem with difficulty y on at least one judge besides Decoforces.Makes can solve problems on any judge at any time, it isn't necessary to do problems from the chosen list one right after another.Makes doesn't have too much free time, so he asked you to calculate the minimum number of problems he should solve on other judges in order to solve all the chosen problems from Decoforces.

The first line contains two integer numbers n, k (1 ≤ n ≤ 103, 1 ≤ k ≤ 109). The second line contains n space-separated integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109).

Print minimum number of problems Makes should solve on other judges in order to solve all chosen problems on Decoforces.

NoteIn the first example Makes at first solves problems 1 and 2. Then in order to solve the problem with difficulty 9, he should solve problem with difficulty no less than 5. The only available are difficulties 5 and 6 on some other judge. Solving any of these will give Makes opportunity to solve problem 3.In the second example he can solve every problem right from the start.

package main

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

func Init() {
}

func Solve(io *FastIO) {
	N := io.NextInt()
	K := io.NextInt()
	A := io.NextIntArray(N)

	sort.Ints(A)

	skill := K
	cnt := 0
	for _, v := range A {
		for (skill << 1) < v {
			skill <<= 1
			cnt++
		}
		skill = Max(skill, v)
	}
	io.Println(cnt)
}

func Max(args ...int) int {
	max := args[0]
	for i := 1; i < len(args); i++ {
		if args[i] > max {
			max = args[i]
		}
	}
	return max
}

type FastIO struct {
	reader *bufio.Reader
	writer *bufio.Writer
}

func (io *FastIO) NextChar() byte {
	c, _ := io.reader.ReadByte()
	return c
}

func (io *FastIO) NextInt() int {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := 1
	if c == '-' {
		sgn = -1
		c = io.NextChar()
	}
	res := 0
	for !IsSpaceChar(c) {
		res = (res * 10) + int(c - '0')
		c = io.NextChar()
	}
	return sgn * res
}

func (io *FastIO) NextLong() int64 {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := int64(1)
	if c == '-' {
		sgn = -1
		c = io.NextChar()
	}
	res := int64(0)
	for !IsSpaceChar(c) {
		res = (res * 10) + int64(c - '0')
		c = io.NextChar()
	}
	return sgn * res
}

func (io *FastIO) NextIntArray(size int) []int {
	return io.NextIntArrayOffset(size, 0)
}

func (io *FastIO) NextIntArrayOffset(size, offset int) []int {
	arr := make([]int, size + offset)
	for i := 0; i < size; i++ {
		arr[i + offset] = io.NextInt()
	}
	return arr
}

func (io *FastIO) NextLongArray(size int) []int64 {
	return io.NextLongArrayOffset(size, 0)
}

func (io *FastIO) NextLongArrayOffset(size, offset int) []int64 {
	arr := make([]int64, size + offset)
	for i := 0; i < size; i++ {
		arr[i + offset] = io.NextLong()
	}
	return arr
}

func (io *FastIO) NextString() string {
	c := io.NextChar()
	for (IsSpaceChar(c)) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsSpaceChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}

func (io *FastIO) NextLine() string {
	c := io.NextChar()
	for (IsSpaceChar(c)) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsLineBreakChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}

func (io *FastIO) Println(args ...interface{}) {
	io.writer.WriteString(fmt.Sprintln(args...))
}

func (io *FastIO) Printf(format string, args ...interface{}) {
	io.writer.WriteString(fmt.Sprintf(format, args...))
}

func (io *FastIO) FlushOutput() {
	io.writer.Flush()
}

func IsSpaceChar(c byte) bool {
	switch c {
	case 0, '\t', '\n', '\r', ' ':
		return true
	default:
		return false
	}
}

func IsLineBreakChar(c byte) bool {
	switch c {
		case 0, '\n', '\r':
			return true
		default:
			return false
	}
}

func main() {
	io := FastIO{reader: bufio.NewReader(os.Stdin), writer: bufio.NewWriter(os.Stdout)}
	Init()
	Solve(&io)
	io.FlushOutput()
}

package main

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

func Init() {
}

func Solve(io *FastIO) {
	N := io.NextInt()
	K := io.NextInt()
	A := io.NextIntArray(N)

	sort.Ints(A)

	skill := K
	cnt := 0
	for _, v := range A {
		for (skill << 1) < v {
			skill <<= 1
			cnt++
		}
	}
	io.Println(cnt)
}

type FastIO struct {
	reader *bufio.Reader
	writer *bufio.Writer
}

func (io *FastIO) NextChar() byte {
	c, _ := io.reader.ReadByte()
	return c
}

func (io *FastIO) NextInt() int {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := 1
	if c == '-' {
		sgn = -1
		c = io.NextChar()
	}
	res := 0
	for !IsSpaceChar(c) {
		res = (res * 10) + int(c - '0')
		c = io.NextChar()
	}
	return sgn * res
}

func (io *FastIO) NextLong() int64 {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := int64(1)
	if c == '-' {
		sgn = -1
		c = io.NextChar()
	}
	res := int64(0)
	for !IsSpaceChar(c) {
		res = (res * 10) + int64(c - '0')
		c = io.NextChar()
	}
	return sgn * res
}

func (io *FastIO) NextIntArray(size int) []int {
	return io.NextIntArrayOffset(size, 0)
}

func (io *FastIO) NextIntArrayOffset(size, offset int) []int {
	arr := make([]int, size + offset)
	for i := 0; i < size; i++ {
		arr[i + offset] = io.NextInt()
	}
	return arr
}

func (io *FastIO) NextLongArray(size int) []int64 {
	return io.NextLongArrayOffset(size, 0)
}

func (io *FastIO) NextLongArrayOffset(size, offset int) []int64 {
	arr := make([]int64, size + offset)
	for i := 0; i < size; i++ {
		arr[i + offset] = io.NextLong()
	}
	return arr
}

func (io *FastIO) NextString() string {
	c := io.NextChar()
	for (IsSpaceChar(c)) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsSpaceChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}

func (io *FastIO) NextLine() string {
	c := io.NextChar()
	for (IsSpaceChar(c)) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsLineBreakChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}

func (io *FastIO) Println(args ...interface{}) {
	io.writer.WriteString(fmt.Sprintln(args...))
}

func (io *FastIO) Printf(format string, args ...interface{}) {
	io.writer.WriteString(fmt.Sprintf(format, args...))
}

func (io *FastIO) FlushOutput() {
	io.writer.Flush()
}

func IsSpaceChar(c byte) bool {
	switch c {
	case 0, '\t', '\n', '\r', ' ':
		return true
	default:
		return false
	}
}

func IsLineBreakChar(c byte) bool {
	switch c {
		case 0, '\n', '\r':
			return true
		default:
			return false
	}
}

func main() {
	io := FastIO{reader: bufio.NewReader(os.Stdin), writer: bufio.NewWriter(os.Stdout)}
	Init()
	Solve(&io)
	io.FlushOutput()
}


Let's call left cyclic shift of some string $$$t_1 t_2 t_3 \dots t_{n - 1} t_n$$$ as string $$$t_2 t_3 \dots t_{n - 1} t_n t_1$$$.Analogically, let's call right cyclic shift of string $$$t$$$ as string $$$t_n t_1 t_2 t_3 \dots t_{n - 1}$$$.Let's say string $$$t$$$ is good if its left cyclic shift is equal to its right cyclic shift.You are given string $$$s$$$ which consists of digits 0–9.What is the minimum number of characters you need to erase from $$$s$$$ to make it good?

The first line contains single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ lines contains test cases — one per line. The first and only line of each test case contains string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$). Each character $$$s_i$$$ is digit 0–9. It's guaranteed that the total length of strings doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print the minimum number of characters you need to erase from $$$s$$$ to make it good.

NoteIn the first test case, you can erase any $$$3$$$ characters, for example, the $$$1$$$-st, the $$$3$$$-rd, and the $$$4$$$-th. You'll get string 51 and it is good.In the second test case, we can erase all characters except 0: the remaining string is 0000 and it's good.In the third test case, the given string $$$s$$$ is already good.

package main

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

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

	T:= 0
	for Fscan(in, &T); T > 0; T-- {
		var s string
		Fscan(in, &s);
		n:=len(s)
		var dp[10][10]int

		for _,x :=range(s){
			cur:=int(x-'0')
			// Fprintln(out,cur)
			for i:=0;i<10;i++{
				if i!=cur && dp[i][cur]%2==1{
					dp[i][cur]++
				}

				if i!=cur && dp[cur][i]%2==0{
					dp[cur][i]++
				}
			}
			dp[cur][cur]++
		}
		ans:=0
		for i:=0;i<10;i++{
			for j:=0;j<10;j++{
				if i!=j && dp[i][j]%2==1{
					dp[i][j]--
				}
				if ans < dp[i][j]{
					ans=dp[i][j]
				}
			}
		}
		Fprintln(out,n-ans)
	}
}

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

package main

import (
    "fmt"
)

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

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

func main() {
    var t int
    fmt.Scan(&t)
    for t > 0 {
        var s string
        fmt.Scan(&s)

        n := len(s)

        count := make([]int, 10)
        for i := 0; i < n; i++ {
            count[int(s[i] - '0')]++
        }

        answer := n

        // odd length
        for i := 0; i < 10; i++ {
            answer = min(answer, n - (count[i] - (1 - count[i] % 2)))
        }

        // even length
        dp := make([][][]int, 10)
        for i := 0; i < 10; i++ {
            dp[i] = make([][]int, 10)
            for j := 0; j < 10; j++ {
                dp[i][j] = make([]int, n + 1)
            }
        }
        for k := n - 1; k >= 0; k-- {
            for i := 0; i < 10; i++ {
                for j := 0; j < 10; j++ {
                    dp[i][j][k] = dp[i][j][k + 1]
                    if int(s[k] - '0') == i {
                        dp[i][j][k] = max(dp[i][j][k], 1 + dp[j][i][k + 1])
                    }
                }
            }
        }

        for i := 0; i < 10; i++ {
            for j := 0; j < 10; j++ {
                answer = min(answer, n - (dp[i][j][0] - dp[i][j][0] % 2))
            }
        }

        fmt.Println(answer)

        t--
    }
}

package main

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

func main() {
	io := newFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	for t := io.nextInt(); t > 0; t-- {
		s := io.next()
		ans := len(s)
		for i := '0'; i <= '9'; i++ {
			for j := '0'; j <= '9'; j++ {
				cur, cnt := i, 0
				for _, c := range s {
					if c == cur {
						if cur == i {
							cur = j
						} else {
							cur = i
						}
					} else {
						cnt++
					}
				}
				if i != j && cur == j {
					cnt++
				}
				if cnt < ans {
					ans = cnt
				}
			}
		}

		io.println(ans)
	}
}

type fastIO struct {
	*bufio.Reader
	*bufio.Writer
	p [1]byte
}

func newFastIO(r io.Reader, w io.Writer) *fastIO {
	return &fastIO{Reader: bufio.NewReader(r), Writer: bufio.NewWriter(w)}
}

func (f *fastIO) nextInt() int {
	f.Read(f.p[:])
	for f.p[0] <= ' ' {
		f.Read(f.p[:])
	}
	neg := false
	if f.p[0] == '-' {
		neg = true
		f.Read(f.p[:])
	}
	n := 0
	for '0' <= f.p[0] && f.p[0] <= '9' {
		n = n*10 + int(f.p[0]) - '0'
		f.Read(f.p[:])
	}
	if neg {
		return -n
	}
	return n
}

func (f *fastIO) nextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.nextInt()
	}
	return a
}

func (f *fastIO) next() string {
	f.Read(f.p[:])
	for f.p[0] <= ' ' {
		f.Read(f.p[:])
	}
	var s []byte
	for f.p[0] > ' ' {
		s = append(s, f.p[0])
		f.Read(f.p[:])
	}
	return string(s)
}

func (f *fastIO) println(a ...interface{}) {
	fmt.Fprintln(f.Writer, a...)
}

func (f *fastIO) print(a ...interface{}) {
	fmt.Fprint(f.Writer, a...)
}

func (f *fastIO) printInts(a ...int) {
	if len(a) > 0 {
		f.print(a[0])
		for _, x := range a[1:] {
			f.print(" ", x)
		}
	}
}

func (f *fastIO) printlnInts(a ...int) {
	f.printInts(a...)
	f.println()
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	buffer := make([]byte, 1024*1024*10)
	scanner.Buffer(buffer, 20*1024*1024)
	scanner.Split(bufio.ScanLines)

	scanner.Scan()
	t, _ := strconv.Atoi(scanner.Text())

	for ; t > 0; t-- {
		scanner.Scan()
		seq := scanner.Text()

		a := make([]int, 100)

		for i := range seq {
			dig := int(seq[i]) - int('0')

			for i := 0; i < 10; i++ {
				num1 := i*10 + dig
				num2 := dig*10 + i
				changed := false
				if a[num1]%2 == 1 {
					a[num1]++
					changed = true
				}

				if a[num2]%2 == 0 {
					a[num2]++
				}

				if num1 == num2 && changed {
					a[num1]--
				}
			}
		}

		max := 2

		for i := range a {
			if max < a[i] {
				if a[i]%2 == 0 || i%11 == 0 {
					max = a[i]
				}
			}
		}

		fmt.Println(len(seq) - max)
	}

}

package main

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

type FastIn struct {
	scanner *bufio.Scanner
}

func MakeFastIn() (obj FastIn)  {
	obj = FastIn{bufio.NewScanner(os.Stdin)}
	obj.scanner.Split(bufio.ScanWords)

	const maxCapacity = 1024*1024
	buf := make([]byte, maxCapacity)
	obj.scanner.Buffer(buf, maxCapacity)
	return
}

func (fi *FastIn) ReadText() string {
	fi.scanner.Scan()
	return fi.scanner.Text()
}

func (fi *FastIn) ReadInt() int {
	ret, err := strconv.Atoi(fi.ReadText())
	if err != nil {
		panic(err)
	}
	return ret
}

func (fi *FastIn) ReadInts(arr []int) {
	for i := 0; i < len(arr); i++ {
		arr[i] = fi.ReadInt()
	}
}
func Min (a int64, b int64) int64 {
	if a < b {
		return a
	}
	return b
}

func (fi *FastIn) ReadInt64() int64 {
	ret, err := strconv.ParseInt(fi.ReadText(), 10, 64)
	if err != nil {
		panic(err)
	}
	return ret
}

func Test(str []rune, c1 int32, c2 int32) int {
	j := 0
	ans := 0
	curr := c1
	for j < len(str) {
		for j < len(str) && str[j] != rune(curr) {
			j++
		}
		if j >= len(str) {
			break
		}
		ans++
		j++
		if curr == c1 {
			curr = c2
		} else {
			curr = c1
		}
	}
	if c1 != c2 && ans % 2 == 1 {
		ans--
	}
	return ans
}

func main() {
	fin := MakeFastIn()
	t := fin.ReadInt()

	for i := 0; i < t; i++ {
		str := fin.ReadText()
		r := []rune(str)
		if len(r) != len(str) {
			panic("")
		}

		max_sz := 0
		for c1 := '0'; c1 <= '9'; c1++ {
			for c2 := '0'; c2 <= '9'; c2++ {
				tmp := Test(r, c1, c2)
				if tmp > max_sz {
					max_sz = tmp
				}
			}
		}
		fmt.Printf("%d\n", len(str)-max_sz)
	}
}

/*
URL:
https://codeforces.com/contest/1389/problem/C
*/

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
	// MOD          = 998244353
	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

	S []rune
	n int
)

func main() {
	t = ReadInt()

	for tc := 0; tc < t; tc++ {
		S = ReadRuneSlice()

		solve()
	}
}

func solve() {
	n = len(S)

	// 2文字以外全部消すときが最悪
	ans := n - 2

	// 全部同じ文字にする
	cnts := make([]int, 15)
	for i := 0; i < 10; i++ {
		cnts[i] = 0
	}
	for _, r := range S {
		cnts[r-'0']++
	}
	for i := 0; i < 10; i++ {
		ChMin(&ans, n-cnts[i])
	}

	for i := '0'; i <= '9'; i++ {
		for j := '0'; j <= '9'; j++ {
			// if n >= 4 {
			// 	val4 := four(i, j)
			// 	ChMin(&ans, val4)
			// }

			// if n >= 6 {
			// 	valOther := other(i, j)
			// 	ChMin(&ans, valOther)
			// }

			ChMin(&ans, find(i, j))
		}
	}

	fmt.Println(ans)
}

func find(s, t rune) int {
	kesu := 0

	cnt := 0
	for i := 0; i < n; i++ {
		if cnt%2 == 0 && S[i] == s {
			cnt++
		} else if cnt%2 == 1 && S[i] == t {
			cnt++
		} else {
			kesu++
		}
	}

	if cnt%2 == 0 {
		return kesu
	} else {
		return INF_BIT30
	}
}

// func other(s, t rune) int {
// 	l := 0

// 	// sts
// 	lcnt := 0
// 	for l < n {
// 		if S[l] == s {
// 			lcnt++
// 			break
// 		}
// 		l++
// 	}
// 	for l < n {
// 		if S[l] == t {
// 			lcnt++
// 			break
// 		}
// 		l++
// 	}
// 	for l < n {
// 		if S[l] == s {
// 			lcnt++
// 			break
// 		}
// 		l++
// 	}

// 	// tst
// 	r := n - 1
// 	rcnt := 0
// 	for r > l {
// 		if S[r] == t {
// 			rcnt++
// 			break
// 		}
// 		r--
// 	}
// 	for r > l {
// 		if S[r] == s {
// 			rcnt++
// 			break
// 		}
// 		r--
// 	}
// 	for r > l {
// 		if S[r] == t {
// 			rcnt++
// 			break
// 		}
// 		r--
// 	}

// 	if lcnt == 3 && rcnt == 3 {
// 		return n - (6 + (r - l - 1))
// 	} else {
// 		return INF_BIT30
// 	}
// }

// func four(s, t rune) int {
// 	l := 0
// 	cnt := 0

// 	for l < n {
// 		if S[l] == s {
// 			cnt++
// 			l++
// 			break
// 		}
// 		l++
// 	}

// 	for l < n {
// 		if S[l] == t {
// 			cnt++
// 			l++
// 			break
// 		}
// 		l++
// 	}

// 	for l < n {
// 		if S[l] == s {
// 			cnt++
// 			l++
// 			break
// 		}
// 		l++
// 	}

// 	for l < n {
// 		if S[l] == t {
// 			cnt++
// 			l++
// 			break
// 		}
// 		l++
// 	}

// 	if cnt == 4 {
// 		return n - cnt
// 	} else {
// 		return INF_BIT30
// 	}
// }

// ChMin accepts a pointer of integer and a target value.
// If target value is SMALLER than the first argument,
//	then the first argument will be updated by the second argument.
func ChMin(updatedValue *int, target int) bool {
	if *updatedValue > target {
		*updatedValue = target
		return true
	}
	return false
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

	return string(res)
}

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

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

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

	return string(res)
}

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

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

package main

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

var numbers = []byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}

func solve() {
	b := readBytes()
	ans := math.MaxInt32
	for _, x := range numbers {
		for _, y := range numbers {
			removed := make([]byte, 0)
			for i := range b {
				if b[i] == x || b[i] == y {
					removed = append(removed, b[i])
				}
			}

			if x == y {
				ans = min(ans, len(b)-len(removed))
				continue
			}

			cnt := 0
			pre := byte(' ')
			for _, x := range removed {
				if x != pre {
					cnt++
					pre = x
				}
			}
			// fmt.Println(x, y, len(b), len(removed), cnt)
			if cnt%2 == 1 {
				cnt--
			}
			ans = min(ans, len(b)-cnt)
		}
	}
	fmt.Println(ans)
}

func main() {
	k := readInt()
	for i := 0; i < k; i++ {
		solve()
	}
}

// sort ------------------------------------------------------------

type xxx struct {
	x int
}

type sortArray []xxx

func (s sortArray) Len() int           { return len(s) }
func (s sortArray) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s sortArray) Less(i, j int) bool { return s[i].x < s[j].x }

// -----------------------------------------------------------------

var (
	readString func() string
	readBytes  func() []byte
)

func init() {
	log.SetFlags(log.Lshortfile)
	readString, readBytes = newReadString(os.Stdin)
}

func newReadString(ior io.Reader) (func() string, func() []byte) {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), math.MaxInt32)
	r.Split(bufio.ScanWords)

	f1 := func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
	f2 := func() []byte {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Bytes()
	}
	return f1, f2
}

func readInt() int {
	return int(readInt64())
}

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

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

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 maxInt64(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}

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

func sum(a []int) int {
	var ret int
	for i := range a {
		ret += a[i]
	}
	return ret
}

func sumFloat64(a []float64) float64 {
	var ret float64
	for i := range a {
		ret += a[i]
	}
	return ret
}

func gcd(m, n int) int {
	for m%n != 0 {
		m, n = n, m%n
	}
	return n
}

func lcm(m, n int) int {
	return m / gcd(m, n) * n
}

package main

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

var rw = newFastIO(os.Stdin, os.Stdout)

func main() {
	defer rw.Flush()
	nTest := rw.nextInt()
	for i := 0; i < nTest; i++ {
		solveCase()
	}
}

func solveCase() {
	s := rw.next()
	n := len(s)
	ans := n
	for x := '0'; x <= '9'; x++ {
		cnt := 0
		for _, c := range s {
			if c == x {
				cnt++
			}
		}
		if n-cnt < ans {
			ans = n - cnt
		}
		prev := '!'
		for y := '0'; y <= '9'; y++ {
			cnt := 0
			for _, c := range s {
				if c != prev && (c == x || c == y) {
					cnt++
					prev = c
				}
			}
			if cnt%2 == 1 {
				cnt--
			}
			if n-cnt < ans {
				ans = n - cnt
			}
		}
	}
	rw.println(ans)
}

// @meooow template uwu
type fastIO struct {
	*bufio.Reader
	*bufio.Writer
	p [1]byte
}

func newFastIO(r io.Reader, w io.Writer) *fastIO {
	return &fastIO{Reader: bufio.NewReader(r), Writer: bufio.NewWriter(w)}
}

func (f *fastIO) nextInt() int {
	f.Read(f.p[:])
	for f.p[0] <= ' ' {
		f.Read(f.p[:])
	}
	neg := false
	if f.p[0] == '-' {
		neg = true
		f.Read(f.p[:])
	}
	n := 0
	for '0' <= f.p[0] && f.p[0] <= '9' {
		n = n*10 + int(f.p[0]) - '0'
		f.Read(f.p[:])
	}
	if neg {
		return -n
	}
	return n
}

func (f *fastIO) nextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.nextInt()
	}
	return a
}

func (f *fastIO) next() string {
	f.Read(f.p[:])
	for f.p[0] <= ' ' {
		f.Read(f.p[:])
	}
	var s []byte
	for f.p[0] > ' ' {
		s = append(s, f.p[0])
		f.Read(f.p[:])
	}
	return string(s)
}

func (f *fastIO) println(a ...interface{}) {
	fmt.Fprintln(f.Writer, a...)
}

func (f *fastIO) print(a ...interface{}) {
	fmt.Fprint(f.Writer, a...)
}

func (f *fastIO) printInts(a ...int) {
	if len(a) > 0 {
		f.print(a[0])
		for _, x := range a[1:] {
			f.print(" ", x)
		}
	}
}

func (f *fastIO) printlnInts(a ...int) {
	f.printInts(a...)
	f.println()
}

package main

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

const (
	SCANNER_BUF_SIZE = 2 << 20

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

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

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

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

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

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

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

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

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

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

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

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

func main() {
	defer writer.Flush()
	t := sint64()
	for ; t > 0; t-- {
		printf("%d\n", sol(sstring()))
	}
}

func sol(s string) int64 {
	counts := map[byte]int64{}
	for i := range s {
		counts[s[i]]++
	}
	maxSoFar := int64(0)
	for _, c := range counts {
		maxSoFar = max(maxSoFar, c)
	}
	for i := '0'; i <= '9'; i++ {
		for j := '0'; j <= '9'; j++ {
			isI := true
			tmp := int64(0)
			for _, r := range s {
				if isI && r == i {
					tmp++
					isI = !isI
				} else if !isI && r == j {
					tmp++
					isI = !isI
				}
			}
			if tmp & 1 == 1 {
				tmp--
			}
			maxSoFar = max(maxSoFar, tmp)
		}
	}
	return int64(len(s)) - maxSoFar
}

package main

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

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

	T:= 0
	for Fscan(in, &T); T > 0; T-- {
		var s string
		Fscan(in, &s);
		n:=len(s)
		var dp[10][10]int

		for _,x :=range(s){
			cur:=int(x-'0')
			// Fprintln(out,cur)
			for i:=0;i<10;i++{
				if i!=cur && dp[i][cur]%2==1{
					dp[i][cur]++
				}

				if i!=cur && dp[cur][i]%2==0{
					dp[cur][i]++
				}
			}
			dp[cur][cur]++
		}
		ans:=0
		for i:=0;i<10;i++{
			for j:=0;j<10;j++{
				if dp[i][j]%2==1{
					dp[i][j]--
				}
				if ans < dp[i][j]{
					ans=dp[i][j]
				}
			}
		}
		Fprintln(out,n-ans)
	}
}

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

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	buffer := make([]byte, 1024*1024*10)
	scanner.Buffer(buffer, 20*1024*1024)
	scanner.Split(bufio.ScanLines)

	scanner.Scan()
	t, _ := strconv.Atoi(scanner.Text())

	for ; t > 0; t-- {
		scanner.Scan()
		seq := scanner.Text()

		a := make([]int, 100)

		for i := range seq {
			dig := int(seq[i]) - int('0')

			for i := 0; i < 10; i++ {
				num1 := i*10 + dig
				num2 := dig*10 + i

				if a[num1]%2 == 0 {
					a[num1]++
				}

				if a[num2]%2 == 1 {
					a[num2]++
				}
			}

			if i != 0 && i != len(seq)-1 {
				a[dig*10+dig]--
			}
		}

		max := 2

		for i := range a {
			if a[i]%2 == 0 {
				if max < a[i] {
					max = a[i]
				}
			}
		}

		fmt.Println(len(seq) - max)
	}

}

package main

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

type FastIn struct {
	scanner *bufio.Scanner
}

func MakeFastIn() (obj FastIn)  {
	obj = FastIn{bufio.NewScanner(os.Stdin)}
	obj.scanner.Split(bufio.ScanWords)
	return
}

func (fi *FastIn) ReadText() string {
	fi.scanner.Scan()
	return fi.scanner.Text()
}

func (fi *FastIn) ReadInt() int {
	ret, err := strconv.Atoi(fi.ReadText())
	if err != nil {
		panic(err)
	}
	return ret
}

func (fi *FastIn) ReadInts(arr []int) {
	for i := 0; i < len(arr); i++ {
		arr[i] = fi.ReadInt()
	}
}
func Min (a int64, b int64) int64 {
	if a < b {
		return a
	}
	return b
}

func (fi *FastIn) ReadInt64() int64 {
	ret, err := strconv.ParseInt(fi.ReadText(), 10, 64)
	if err != nil {
		panic(err)
	}
	return ret
}

func Test(str []rune, c1, c2 int32) int {
	j := 0
	ans := 0
	curr := c1
	for j < len(str) {
		for j < len(str) && str[j] != rune(curr) {
			j++
		}
		if j >= len(str) {
			break
		}
		ans++
		j++
		if curr == c1 {
			curr = c2
		} else {
			curr = c1
		}
	}
	if c1 != c2 && ans % 2 == 1 {
		ans--
	}
	return ans
}

func main() {
	fin := MakeFastIn()
	t := fin.ReadInt()
	for i := 0; i < t; i++ {
		str := fin.ReadText()
		r := []rune(str)
		if len(r) != len(str) {
			panic("")
		}

		max_sz := 0
		for c1 := '0'; c1 <= '9'; c1++ {
			for c2 := '0'; c2 <= '9'; c2++ {
				tmp := Test(r, c1, c2)
				if tmp > max_sz {
					max_sz = tmp
				}
			}
		}
		fmt.Printf("%d\n", len(str)-max_sz)
	}
}

package main

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

type FastIn struct {
	scanner *bufio.Scanner
}

func MakeFastIn() (obj FastIn)  {
	obj = FastIn{bufio.NewScanner(os.Stdin)}
	obj.scanner.Split(bufio.ScanWords)
	return
}

func (fi *FastIn) ReadText() string {
	fi.scanner.Scan()
	return fi.scanner.Text()
}

func (fi *FastIn) ReadInt() int {
	ret, err := strconv.Atoi(fi.ReadText())
	if err != nil {
		panic(err)
	}
	return ret
}

func (fi *FastIn) ReadInts(arr []int) {
	for i := 0; i < len(arr); i++ {
		arr[i] = fi.ReadInt()
	}
}
func Min (a int64, b int64) int64 {
	if a < b {
		return a
	}
	return b
}

func (fi *FastIn) ReadInt64() int64 {
	ret, err := strconv.ParseInt(fi.ReadText(), 10, 64)
	if err != nil {
		panic(err)
	}
	return ret
}

func Test(str []rune, c1 int32, c2 int32) int {
	j := 0
	ans := 0
	curr := c1
	for j < len(str) {
		for j < len(str) && str[j] != rune(curr) {
			j++
		}
		if j >= len(str) {
			break
		}
		ans++
		j++
		if curr == c1 {
			curr = c2
		} else {
			curr = c1
		}
	}
	if c1 != c2 && ans % 2 == 1 {
		ans--
	}
	return ans
}

func main() {
	fin := MakeFastIn()
	t := fin.ReadInt()
	for i := 0; i < t; i++ {
		str := fin.ReadText()
		r := []rune(str)
		if len(r) != len(str) {
			panic("")
		}

		max_sz := 0
		for c1 := '0'; c1 <= '9'; c1++ {
			for c2 := '0'; c2 <= '9'; c2++ {
				tmp := Test(r, c1, c2)
				if tmp > max_sz {
					max_sz = tmp
				}
			}
		}
		fmt.Printf("%d\n", len(str)-max_sz)
	}
}

package main

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

type FastIn struct {
	scanner *bufio.Scanner
}

func MakeFastIn() (obj FastIn)  {
	obj = FastIn{bufio.NewScanner(os.Stdin)}
	obj.scanner.Split(bufio.ScanWords)
	return
}

func (fi *FastIn) ReadText() string {
	fi.scanner.Scan()
	return fi.scanner.Text()
}

func (fi *FastIn) ReadInt() int {
	ret, err := strconv.Atoi(fi.ReadText())
	if err != nil {
		panic(err)
	}
	return ret
}

func (fi *FastIn) ReadInts(arr []int) {
	for i := 0; i < len(arr); i++ {
		arr[i] = fi.ReadInt()
	}
}
func Min (a int64, b int64) int64 {
	if a < b {
		return a
	}
	return b
}

func (fi *FastIn) ReadInt64() int64 {
	ret, err := strconv.ParseInt(fi.ReadText(), 10, 64)
	if err != nil {
		panic(err)
	}
	return ret
}

func Test(str []rune, c1, c2 int32) int {
	j := 0
	ans := 0
	curr := c1
	for j < len(str) {
		for j < len(str) && str[j] != rune(curr) {
			j++
		}
		if j >= len(str) {
			break
		}
		ans++
		j++
		if curr == c1 {
			curr = c2
		} else {
			curr = c1
		}
	}
	if c1 != c2 && ans % 2 == 1 {
		ans--
	}
	return ans
}

func main() {
	fin := MakeFastIn()
	t := fin.ReadInt()
	for i := 0; i < t; i++ {
		str := fin.ReadText()
		r := []rune(str)

		max_sz := 0
		for c1 := '0'; c1 <= '9'; c1++ {
			for c2 := '0'; c2 <= '9'; c2++ {
				tmp := Test(r, c1, c2)
				if tmp > max_sz {
					max_sz = tmp
				}
			}
		}
		fmt.Printf("%d\n", len(str)-max_sz)
	}
}


This is an interactive problem.Note: the XOR-sum of an array $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) is defined as $$$a_1 \oplus a_2 \oplus \ldots \oplus a_n$$$, where $$$\oplus$$$ denotes the bitwise XOR operation.Little Dormi received an array of $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ for Christmas. However, while playing with it over the winter break, he accidentally dropped it into his XOR machine, and the array got lost.The XOR machine is currently configured with a query size of $$$k$$$ (which you cannot change), and allows you to perform the following type of query: by giving the machine $$$k$$$ distinct indices $$$x_1, x_2, \ldots, x_k$$$, it will output $$$a_{x_1} \oplus a_{x_2} \oplus \ldots \oplus a_{x_k}$$$.As Little Dormi's older brother, you would like to help him recover the XOR-sum of his array $$$a_1, a_2, \ldots, a_n$$$ by querying the XOR machine.Little Dormi isn't very patient, so to be as fast as possible, you must query the XOR machine the minimum number of times to find the XOR-sum of his array. Formally, let $$$d$$$ be the minimum number of queries needed to find the XOR-sum of any array of length $$$n$$$ with a query size of $$$k$$$. Your program will be accepted if you find the correct XOR-sum in at most $$$d$$$ queries.Lastly, you also noticed that with certain configurations of the machine $$$k$$$ and values of $$$n$$$, it may not be possible to recover the XOR-sum of Little Dormi's lost array. If that is the case, you should report it as well.The array $$$a_1, a_2, \ldots, a_n$$$ is fixed before you start querying the XOR machine and does not change with the queries.

The only line of input contains the integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 500$$$, $$$1 \le k \le n$$$), the length of the lost array and the configured query size of the XOR machine. Elements of the original array satisfy $$$1 \le a_i \le 10^9$$$. It can be proven that that if it is possible to recover the XOR sum under the given constraints, it can be done in at most $$$500$$$ queries. That is, $$$d \le 500$$$. After taking $$$n$$$ and $$$k$$$, begin interaction.

If it is impossible to recover the XOR-sum of the array, output $$$-1$$$ immediately after taking $$$n$$$ and $$$k$$$. Do not begin interaction. Otherwise, when your program finds the XOR-sum of the lost array $$$a_1, a_2, \ldots, a_n$$$, report the answer in the following format: "! x", where $$$x$$$ is the XOR sum of the array $$$a_1, a_2, \ldots, a_n$$$, and terminate your program normally immediately after flushing the output stream.  Note that answering does not count as a query.

NoteIn the first example interaction, the array $$$a_1, a_2, \ldots, a_n$$$ is $$$2, 1, 7, 5, 6$$$ and its XOR-sum is $$$7$$$. The first query made asks for indices $$$1,2,3$$$, so the response is $$$a_1 \oplus a_2 \oplus a_3 = 2 \oplus 1 \oplus 7 = 4$$$.The second query made asks for indices $$$2,3,5$$$, so the response is $$$a_2 \oplus a_3 \oplus a_5 = 1 \oplus 7 \oplus 6 = 0$$$.The third query made asks for indices $$$4,1,5$$$, so the response is $$$a_4 \oplus a_1 \oplus a_5 = 5 \oplus 2 \oplus 6 = 1$$$. Note that the indices may be output in any order.Additionally, even though three queries were made in the example interaction, it is just meant to demonstrate the interaction format and does not necessarily represent an optimal strategy.In the second example interaction, there is no way to recover the XOR-sum of Little Dormi's array no matter what is queried, so the program immediately outputs $$$-1$$$ and exits.

package main
import(."fmt";"sort")

// github.com/EndlessCheng/codeforces-go
func main(){
	var n,k,r,ans int
	Scan(&n,&k)
	if n&1>0&&k&1==0{Println(-1);return}
	c:=make([]struct{v,i int},n)
	for i:=range c{c[i].i=i+1}
	s:=n
	for i:=0;s%k>0||c[0].v>=s/k;i=(i+1)%n{c[i].v+=2;s+=2}
	q:=make([]interface{},k)
	for;s>0;s-=k{
		sort.Slice(c,func(i,j int)bool{return c[i].v>c[j].v})
		for i:=range q{q[i]=c[i].i;c[i].v--}
		Print("? ");Println(q...)
		Scan(&r);ans^=r
	}
	Println("!",ans)
}

package main

import (
	. "fmt"
	"sort"
)

// github.com/EndlessCheng/codeforces-go
func main() {
	var n, k, res, ans int
	Scan(&n, &k)
	if n&1 > 0 && k&1 == 0 {
		Println(-1)
		return
	}
	type pair struct{ v, i int }
	c := make([]pair, n)
	for i := range c {
		c[i] = pair{1, i + 1}
	}
	tot := n
	for i := 0; tot%k > 0 || c[0].v > tot/k; i = (i + 1) % n {
		c[i].v += 2
		tot += 2
	}
	for ; tot > 0; tot -= k {
		sort.Slice(c, func(i, j int) bool { return c[i].v > c[j].v })
		q := make([]interface{}, k)
		for i := range q {
			q[i] = c[i].i
			c[i].v--
		}
		Print("? ")
		Println(q...)
		Scan(&res)
		ans ^= res
	}
	Println("!", ans)
}

package main

import (
	"bufio"
	"container/list"
	"fmt"
	"math"
	"os"
)

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

func ask(a []int, b []int) int {
	fmt.Fprint(out, "? ")
	for i := range a {
		fmt.Fprint(out, a[i], " ")
	}
	for i := range b {
		fmt.Fprint(out, b[i], " ")
	}
	fmt.Fprint(out, "\n")
	out.Flush()
	var r int
	fmt.Fscan(in, &r)
	return r
}

const MAXN int = 2000
const INF int = 0x3f3f3f3f

var distance, parent []int = make([]int, MAXN), make([]int, MAXN)

func main() {
	defer out.Flush()
	solve := func(Case int) {
		var n, k int
		fmt.Fscan(in, &n, &k)
		//BFS
		queue := list.New()
		memset(distance, INF)
		queue.PushBack(0)
		distance[0] = 0
		parent[0] = -1
		for queue.Len() != 0 {
			elem := queue.Remove(queue.Front())
			cur := elem.(int)
			for unSelected := 0; unSelected <= k; unSelected++ {
				if unSelected+cur <= n && k-unSelected <= cur {
					to := cur + unSelected - (k - unSelected)
					if distance[to] == INF {
						distance[to] = distance[cur] + 1
						parent[to] = cur
						queue.PushBack(to)
					}
				}
			}
		}
		if distance[n] == INF {
			fmt.Fprintln(out, -1)
			return
		}
		path := []int{}
		for i := n; i != -1; i = parent[i] {
			path = append(path, i)
		}
		path = reverseInt(path)
		unSelected, selected := make([]int, n), []int{}
		iota(unSelected, 1)
		ans := 0
		for i := 0; i < len(path)-1; i++ {
			a, b := path[i], path[i+1]
			d := b - a
			num := (d + k) / 2
			curUnselected, curSelected := []int{}, []int{}
			curSelected = unSelected[:num]
			unSelected = unSelected[num:]
			curUnselected = selected[:k-num]
			selected = selected[k-num:]
			ans ^= ask(curUnselected, curSelected)
			unSelected = append(unSelected, curUnselected...)
			selected = append(selected, curSelected...)
		}

		fmt.Fprintln(out, "!", ans)
	}

	T := 1
	//fmt.Fscan(in, &T) //
	for Case := 1; Case <= T; Case++ {
		solve(Case)
	}
}

func readArray(n int) []int {
	a := make([]int, n)
	for i := range a {
		fmt.Fscan(in, &a[i])
	}
	return a
}

func absInt(x int) int {
	if x < 0 {
		return -x
	}
	return x
}
func prependInt(x []int, y int) []int {
	x = append(x, 0)
	copy(x[1:], x)
	x[0] = y
	return x
}

func powMod(x, y, mod int64) int64 {
	ans := int64(1)
	for y != 0 {
		if y&1 != 0 {
			ans = (ans * x) % mod
		}
		y = y >> 1
		x = (x * x) % mod
	}
	return ans
}
func max(x ...int) int {
	ans := math.MinInt32
	for i := range x {
		if x[i] > ans {
			ans = x[i]
		}
	}
	return ans
}

func min(x ...int) int {
	ans := math.MaxInt32
	for i := range x {
		if x[i] < ans {
			ans = x[i]
		}
	}
	return ans
}
func gcd(x, y int) int {
	for y != 0 {
		x, y = y, x%y
	}
	return x
}

func reverseString(s []byte) []byte {
	a := []byte(s)
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
	return a
}

func reverseInt(s []int) []int {
	a := []int(s)
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
	return a
}

func memset(a []int, v int) {
	if len(a) == 0 {
		return
	}
	a[0] = v
	for bp := 1; bp < len(a); bp *= 2 {
		copy(a[bp:], a[:bp])
	}
}

func iota(a []int, val int) {
	for i := range a {
		a[i] = i + val
	}
}

package main
import(."fmt";"sort")

// github.com/EndlessCheng/codeforces-go
func main(){
	var n,k,r,ans int
	Scan(&n,&k)
	if n&1>0&&k&1==0{Println(-1);return}
	c:=make([]struct{v,i int},n)
	for i:=range c{c[i].i=i+1}
	s:=n
	for i:=0;s%k>0||c[0].v>=s/k;i=(i+1)%n{c[i].v+=2;s+=2}
	q:=make([]interface{},k)
	for;s>0;s-=k{
		sort.Slice(c,func(i,j int)bool{return c[i].v>c[j].v})
		for i:=range q{q[i]=c[i].i;c[i].v--}
		Print("?");Println(q...)
		Scan(&r);ans^=r
	}
	Println("!",ans)
}

package main

import (
	"bufio"
	"container/list"
	"fmt"
	"math"
	"os"
	"strings"
)

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

func ask(a []int) int {
	fmt.Fprintln(out, "?", strings.Trim(fmt.Sprint(a), "[]"))
	out.Flush()
	var r int
	fmt.Fscan(in, &r)
	return r
}

const MAXN int = 2000
const INF int = 0x3f3f3f3f

var distance, parent []int = make([]int, MAXN), make([]int, MAXN)

func main() {
	defer out.Flush()
	solve := func(Case int) {
		var n, k int
		fmt.Fscan(in, &n, &k)
		//BFS
		queue := list.New()
		memset(distance, INF)
		queue.PushBack(0)
		distance[0] = 0
		parent[0] = -1
		for queue.Len() != 0 {
			elem := queue.Remove(queue.Front())
			cur := elem.(int)
			for unSelected := 0; unSelected <= k; unSelected++ {
				if unSelected+cur <= n && k-unSelected <= cur {
					to := cur + unSelected - (k - unSelected)
					if distance[to] == INF {
						distance[to] = distance[cur] + 1
						parent[to] = cur
						queue.PushBack(to)
					}
				}
			}
		}
		if distance[n] == INF {
			fmt.Fprintln(out, -1)
			return
		}
		path := []int{}
		for i := n; i != -1; i = parent[i] {
			path = append(path, i)
		}
		path = reverseInt(path)
		unSelected, selected := make([]int, n), []int{}
		iota(unSelected, 1)
		ans := 0
		for i := 0; i < len(path)-1; i++ {
			a, b := path[i], path[i+1]
			d := b - a
			num := (d + k) / 2
			curUnselected, curSelected := []int{}, []int{}
			curSelected = unSelected[:num]
			unSelected = unSelected[num:]
			curUnselected = selected[:k-num]
			selected = selected[k-num:]
			ans ^= ask(append(curUnselected, curSelected...))
			unSelected = append(unSelected, curUnselected...)
			selected = append(selected, curSelected...)
		}

		fmt.Fprintln(out, "!", ans)
	}

	T := 1
	//fmt.Fscan(in, &T) //
	for Case := 1; Case <= T; Case++ {
		solve(Case)
	}
}

func readArray(n int) []int {
	a := make([]int, n)
	for i := range a {
		fmt.Fscan(in, &a[i])
	}
	return a
}

func absInt(x int) int {
	if x < 0 {
		return -x
	}
	return x
}
func prependInt(x []int, y int) []int {
	x = append(x, 0)
	copy(x[1:], x)
	x[0] = y
	return x
}

func powMod(x, y, mod int64) int64 {
	ans := int64(1)
	for y != 0 {
		if y&1 != 0 {
			ans = (ans * x) % mod
		}
		y = y >> 1
		x = (x * x) % mod
	}
	return ans
}
func max(x ...int) int {
	ans := math.MinInt32
	for i := range x {
		if x[i] > ans {
			ans = x[i]
		}
	}
	return ans
}

func min(x ...int) int {
	ans := math.MaxInt32
	for i := range x {
		if x[i] < ans {
			ans = x[i]
		}
	}
	return ans
}
func gcd(x, y int) int {
	for y != 0 {
		x, y = y, x%y
	}
	return x
}

func reverseString(s []byte) []byte {
	a := []byte(s)
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
	return a
}

func reverseInt(s []int) []int {
	a := []int(s)
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
	return a
}

func memset(a []int, v int) {
	if len(a) == 0 {
		return
	}
	a[0] = v
	for bp := 1; bp < len(a); bp *= 2 {
		copy(a[bp:], a[:bp])
	}
}

func iota(a []int, val int) {
	for i := range a {
		a[i] = i + val
	}
}

package main

import (
	"bufio"
	"container/list"
	"fmt"
	"math"
	"os"
	"strings"
)

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

func ask(a []int) int {
	fmt.Fprintln(out, "?", strings.Trim(fmt.Sprint(a), "[]"))
	out.Flush()
	var r int
	fmt.Fscan(in, &r)
	return r
}

const MAXN int = 2000
const INF int = 0x3f3f3f3f

var distance, parent []int = make([]int, MAXN), make([]int, MAXN)

func main() {
	defer out.Flush()
	solve := func(Case int) {
		var n, k int
		fmt.Fscan(in, &n, &k)
		//BFS
		queue := list.New()
		memset(distance, INF)
		queue.PushBack(0)
		distance[0] = 0
		parent[0] = -1
		for queue.Len() != 0 {
			elem := queue.Remove(queue.Front())
			cur := elem.(int)
			for unSelected := 0; unSelected <= k; unSelected++ {
				if unSelected+cur <= n && k-unSelected <= cur {
					to := cur + unSelected - (k - unSelected)
					if distance[to] == INF {
						distance[to] = distance[cur] + 1
						parent[to] = cur
						queue.PushBack(to)
					}
				}
			}
		}
		if distance[n] == INF {
			fmt.Fprintln(out, -1)
			return
		}
		path := []int{}
		for i := n; i >= 0; i = parent[i] {
			path = append(path, i)
		}
		path = reverseInt(path)
		unSelected, selected := make([]int, n), []int{}
		iota(unSelected, 1)
		ans := 0
		for i := 0; i < len(path)-1; i++ {
			a, b := path[i], path[i+1]
			d := b - a
			num := (d + k) / 2
			curUnselected, curSelected := []int{}, []int{}
			curSelected = unSelected[:num]
			unSelected = unSelected[num:]
			curUnselected = selected[:k-num]
			selected = selected[k-num:]
			ans ^= ask(append(curUnselected, curSelected...))
			unSelected = append(unSelected, curUnselected...)
			selected = append(selected, curSelected...)
		}

		fmt.Fprintln(out, "!", ans)
	}

	T := 1
	//fmt.Fscan(in, &T) //
	for Case := 1; Case <= T; Case++ {
		solve(Case)
	}
}

func readArray(n int) []int {
	a := make([]int, n)
	for i := range a {
		fmt.Fscan(in, &a[i])
	}
	return a
}

func absInt(x int) int {
	if x < 0 {
		return -x
	}
	return x
}
func prependInt(x []int, y int) []int {
	x = append(x, 0)
	copy(x[1:], x)
	x[0] = y
	return x
}

func powMod(x, y, mod int64) int64 {
	ans := int64(1)
	for y != 0 {
		if y&1 != 0 {
			ans = (ans * x) % mod
		}
		y = y >> 1
		x = (x * x) % mod
	}
	return ans
}
func max(x ...int) int {
	ans := math.MinInt32
	for i := range x {
		if x[i] > ans {
			ans = x[i]
		}
	}
	return ans
}

func min(x ...int) int {
	ans := math.MaxInt32
	for i := range x {
		if x[i] < ans {
			ans = x[i]
		}
	}
	return ans
}
func gcd(x, y int) int {
	for y != 0 {
		x, y = y, x%y
	}
	return x
}

func reverseString(s []byte) []byte {
	a := []byte(s)
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
	return a
}

func reverseInt(s []int) []int {
	a := []int(s)
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
	return a
}

func memset(a []int, v int) {
	if len(a) == 0 {
		return
	}
	a[0] = v
	for bp := 1; bp < len(a); bp *= 2 {
		copy(a[bp:], a[:bp])
	}
}

func iota(a []int, val int) {
	for i := range a {
		a[i] = i + val
	}
}