package main

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

// github.com/EndlessCheng/codeforces-go
func CF940E(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	max := func(a, b int64) int64 {
		if a > b {
			return a
		}
		return b
	}

	var n, c int
	Fscan(in, &n, &c)
	s := int64(0)
	a := make([]int, n)
	for i := range a {
		Fscan(in, &a[i])
		s += int64(a[i])
	}

	dp := make([]int64, n+1)
	idQ := make([]int, n)
	l, r := 0, 0
	for i, v := range a {
		if l < r && i-idQ[l]+1 > c {
			l++
		}
		for ; l < r && a[idQ[r-1]] >= v; r-- {
		}
		idQ[r] = i
		r++
		if i+1 >= c {
			dp[i+1] = max(dp[i], dp[i+1-c]+int64(a[idQ[l]]))
		}
	}
	Fprint(out, s-dp[n])
}

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

package main

import (
	"bufio"
	. "fmt"
	"io"
	"math/bits"
	"os"
)

// github.com/EndlessCheng/codeforces-go
func CF940E(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	min := func(a, b int) int {
		if a < b {
			return a
		}
		return b
	}
	max := func(a, b int64) int64 {
		if a > b {
			return a
		}
		return b
	}

	var n, c, v int
	Fscan(in, &n, &c)
	st := make([][17]int, n)
	s := int64(0)
	for i := range st {
		Fscan(in, &v)
		st[i][0] = v
		s += int64(v)
	}
	for j := 1; 1<<j <= n; j++ {
		for i := 0; i+1<<j <= n; i++ {
			st[i][j] = min(st[i][j-1], st[i+1<<(j-1)][j-1])
		}
	}
	q := func(l, r int) int { k := bits.Len(uint(r-l)) - 1; return min(st[l][k], st[r-1<<k][k]) }

	dp := make([]int64, n+1)
	for r := c; r <= n; r++ {
		dp[r] = max(dp[r-1], dp[r-c]+int64(q(r-c, r)))
	}
	Fprint(out, s-dp[n])
}

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

package main

import (
	"bufio"
	. "fmt"
	"io"
	"math/bits"
	"os"
)

// github.com/EndlessCheng/codeforces-go
func CF940E(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	min := func(a, b int) int {
		if a < b {
			return a
		}
		return b
	}

	var n, c int
	Fscan(in, &n, &c)
	a := make([]int, n)
	st := make([][17]int, n)
	s := int64(0)
	for i := range a {
		Fscan(in, &a[i])
		st[i][0] = a[i]
		s += int64(a[i])
	}
	for j := 1; 1<<j <= n; j++ {
		for i := 0; i+1<<j <= n; i++ {
			st[i][j] = min(st[i][j-1], st[i+1<<(j-1)][j-1])
		}
	}
	q := func(l, r int) int { k := bits.Len(uint(r-l)) - 1; return min(st[l][k], st[r-1<<k][k]) }
	ans := s
	for i := 0; i < c; i++ {
		ss := s
		for l := i; l+c <= n; l += c {
			ss -= int64(q(l, l+c))
		}
		if ss < ans {
			ans = ss
		}
	}
	Fprint(out, ans)
}

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


package main

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

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

    a := make(map[string]int)
    for i := 0; i < n; i++ {
        scanner.Scan()
        v:=scanner.Text()
        _, ok := a[v]
        if(ok){
           a[v]++
        } else {
           a[v]=1
        }
    }

    max := 0
    var maxteam string
    for i,j := range a {
        if j > max {
            max = j
            maxteam = i
        }
    }
     fmt.Println(maxteam)

}

package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scan(&n)

	first := ""
	score := 1
	fmt.Scan(&first)

	team := ""
	second := ""
	for i := 0; i < n-1; i++ {
		fmt.Scan(&team)
		if team == first {
			score++
		} else {
			score--
			if len(second) == 0 {
				second = team
			}
		}
	}

	if score > 0 {
		fmt.Println(first)
	} else {
		fmt.Println(second)
	}
}

package main

import "fmt"

func main() {
	var (
		count       int
		str, winner string
	)

	fmt.Scanf("%d\n", &count)
	goalMap := make(map[string]int)
	fmt.Scan(&str)
	winner = str
	goalMap[str]++
	for i := 1; i < count; i++ {

		fmt.Scan(&str)
		goalMap[str]++

		if goalMap[str] > goalMap[winner] {
			winner = str
		}
	}

	fmt.Println(winner)
}

package main

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

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

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

	mp := make(map[string]int)
	for i := 0; i < n; i++ {
		var x string
		fmt.Fscan(reader, &x)

		mp[x]++
	}

	var mx int
	var ans string
	for cm, vl := range mp {
		if vl > mx {
			ans = cm
			mx = vl
		}
	}

	fmt.Println(ans)
}

// 43A-mic
package main

import (
    "fmt"
)

func main() {
    var n, sk1, sk2 int
    var s, s1, s2 string
    fmt.Scan(&n)
    fmt.Scan(&s)
    sk1++
    for i := 1; i < n; i++ {
        fmt.Scan(&s2)
        if s2 == s {
            sk1++
        } else {
            sk2++
            s1 = s2
        }
    }
    if sk1 > sk2 {
        fmt.Println(s)
    } else {
        fmt.Println(s1)
    }

}

package main

import "fmt"

func main() {
	m:=make(map[string]int)
	var n int
	max:=0
	sr:=""
	var str string
	fmt.Scanln(&n)
	for i:=0; i<n;i++  {
		fmt.Scanln(&str)
		m[str]+=1;
		if m[str]>max {
			max = m[str]
			sr = str
		}
	}
	fmt.Println(sr)
}

package main

import "fmt"

func main() {
    var n int
    var s string
    c := map[string]int{}
    fmt.Scan(&n)
    for i := 0; i < n; i++ {
        fmt.Scan(&s)
        c[s]++
    }
    ans, m := "", 0
    for k, v := range c {
        if v > m { ans = k; m = v }
    }
    fmt.Println(ans)
}

package main

import "fmt"

func main(){
	var n int
	fmt.Scan(&n)
	goal := map[string]int{}
	var name string
	fmt.Scan(&name)
	goal[name]+=1
	max := name
	max1 := goal[name]
	for i:= 1; i<n; i++ {
		fmt.Scan(&name)
		goal[name]+=1
		if goal[name] > max1 {
			max = name
			max1 = goal[name]
		}
	}
	fmt.Println(max)
}

package main
import (
	"fmt"
	"sort"
	//"unicode/utf8"
)
func main() {
	var n int
	fmt.Scan(&n)
	s:=make([]string,n)
	for i:=0;i<n;i++ {
		fmt.Scan(&s[i])
	}
	sort.Strings(s)
	fmt.Println(s[n/2])
}

package main

import "fmt"

type team struct {
	name string
	x int
}
func main() {
	var s team
	n:=0
	fmt.Scanln(&n)
	fmt.Scanln(&s.name)
	s.x=1
	str:=""
	st:=""
	for i:=0; i<n-1; i++ {
		fmt.Scanln(&str)
		if str==s.name {
			s.x++
		}else {
			st=str
			s.x--
		}
	}
	if s.x>0 {
		st=s.name
	}
	fmt.Println(st)
}

package main

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

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

	reader := bufio.NewReader(os.Stdin)
	re := regexp.MustCompile(`\r?\n`)

	name := [2]string{"", ""}
	score := [2]int{0, 0}

	for i := 0; i < n; i++ {
		if _in, err := reader.ReadString('\n'); err != nil {
			if err == io.EOF {
				break
			} else {
				return
			}
		} else {
			in := re.ReplaceAllString(_in, "")
			if name[0] == "" || name[0] == in {
				name[0] = in
				score[0] += 1
			} else if name[1] == "" || name[1] == in {
				name[1] = in
				score[1] += 1
			}
		}
	}

	if score[0] > score[1] {
		fmt.Println(name[0])
	} else {
		fmt.Println(name[1])
	}
}

// 43A
package main

import (
	"fmt"
	"sort"
)

func main() {
	var n int
	fmt.Scan(&n)
	win := n / 2
	goal := make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&goal[i])
	}
	sort.Strings(goal)
	fmt.Println(goal[win])
}

package main

import "fmt"

func main(){
    var n int
    var s string
    goals := make(map[string]int)
    fmt.Scanf("%d\n", &n)
    for i:=0; i<n; i++{
        fmt.Scanf("%s\n", &s)
        goals[s] ++
    }
    won_goals  := 0
    won_key := ""
    for key, amount := range goals{
        if amount > won_goals{
            won_goals = amount
            won_key = key
        }
    }
    fmt.Println(won_key)
}

package main

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

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

	reader := bufio.NewReader(os.Stdin)
	re := regexp.MustCompile(`\r?\n`)

	name := [2]string{"", ""}
	score := [2]int{0, 0}

	for i := 0; i < n; i++ {
		if _in, err := reader.ReadString('\n'); err != nil {
			if err == io.EOF {
				break
			} else {
				return
			}
		} else {
			in := re.ReplaceAllString(_in, "")
			if name[0] == "" {
				name[0] = in
			} else if name[1] == "" {
				name[1] = in
			}

			if name[0] == in {
				score[0] += 1
			} else if name[1] == in {
				score[1] += 1
			}
		}
	}

	if score[0] > score[1] {
		fmt.Println(name[0])
	} else {
		fmt.Println(name[1])
	}
}

// 43A
package main

import (
	"fmt"
)

func main() {
	n, goal := 0, 0
	fmt.Scan(&n)
	var win, tim string
	for i := 0; i < n; n++ {
		fmt.Scan(&tim)
		if goal != 0 {
			if tim == win {
				goal++
			} else {
				goal--
			}
		} else {
			fmt.Scan(&win)
			goal = 1
		}
		if i == n-1 {
			break
		}

	}
	fmt.Println(win)
}

// 43A
package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scan(&n)
	goal := make([]string, n)
	var t string
	for i := 0; i < n; i++ {
		fmt.Scan(&goal[i])
		for j := 0; j < n; j++ {
			if j == 2 {
				if goal[j] == goal[j-1] || goal[j] == goal[j-2] {
					t = goal[j]
				}
			} else {
				continue
			}
		}
	}
	fmt.Println(t)
}

// 43A
package main

import (
	"fmt"
)

func main() {
	var n, goal int
	var win, tim string
	fmt.Scan(&n)
	for i := 0; i < n; i++ {
		fmt.Scan(&tim)
		for j := 0; j < n; j++ {
			if goal != 0 {
				if tim == win {
					goal += 1
				} else {
					goal -= 1
				}
			} else {
				fmt.Scan(&win)
				goal = 1
			}
		}
	}
	fmt.Println(win)
}

// 43A
package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scan(&n)
	var goal [1000]int
	var win, tim string
	for i := 0; i < n; i++ {
		fmt.Scan(&tim)
		for j := 0; j < n; j++ {
			if goal[i] != 0 {
				if tim == win {
					goal[i] += 1
				} else {
					goal[i] -= 1
				}
			} else {
				fmt.Scan(&win)
				goal[i] = 1
			}
		}
	}
	fmt.Println(win)
}

package main

import "fmt"

func main(){
    var n int
    var s string
    goals := make(map[string]int)
    fmt.Scanf("%d\n", &n)
    for i:=0; i<n; i++{
        fmt.Scanf("%s", &s)
        goals[s] ++
    }
    won_goals  := 0
    won_key := ""
    for key, amount := range goals{
        if amount > won_goals{
            won_goals = amount
            won_key = key
        }
    }
    fmt.Println(won_key)
}

package main

import (
    "fmt"
)

func main(){
    n := 0
    fmt.Scanf("%d\n", &n)
    mods := make([]int, 4)
    aux := 0
    fmt.Println(n)
    for i:=0; i <n; i++{
        fmt.Scanf("%d", &aux)
        fmt.Println(aux)
        mods[aux%3] ++
    }
    x := mods[1]
    if x > mods[2]{
        x = mods[2]
    }
    fmt.Println(int(mods[0]/2) + x)
}

package main

import "fmt"

func main(){
    var n int
    var s string
    goals := make(map[string]int)
    fmt.Scanf("%d", &n)
    for i:=0; i<n; i++{
        fmt.Scanf("%s", &s)
        goals[s] ++
    }
    won_goals  := 0
    won_key := ""
    for key, amount := range goals{
        if amount > won_goals{
            won_goals = amount
            won_key = key
        }
    }
    fmt.Println(won_key)
}

package main

import "fmt"

func main() {
	var (
		count       int
		str, winner string
	)

	fmt.Scanf("%d\n", &count)
	goalMap := make(map[string]int)
	for i := 0; i < count; i++ {
		goalMap[str]++

		fmt.Scan(&str)
		if goalMap[str] > goalMap[winner] {
			winner = str
		}
	}

	fmt.Println(winner)
}

package main

import "fmt"

func main() {
	var (
		count       int
		str, winner string
	)

	fmt.Scanf("%d\n", &count)
	for i := 0; i < count; i++ {

		fmt.Scan(&str)
		winner = str
	}

	fmt.Println(winner)
}


package main

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

/*
-3 5 -3 1
*/

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

	var T int64
	var R string
	for Fscan(in, &T); T > 0; T-- {

		Fscan(in, &R)
		var stack []byte
		for i := 0; i < len(R); i++ {
			if len(stack) == 0 || R[i] == 'A' {
				stack = append(stack, R[i])
			} else {
				if (stack[len(stack)-1] == 'A' || stack[len(stack)-1] == 'B') && R[i] == 'B' {
					stack = stack[:len(stack)-1]
				}
			}
		}

		Fprintln(out, len(stack))

	}
}

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

package main

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

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 int64) int64 {
	if a < 0 {
		return -a
	}
	return a
}

const mod = 1000000007

func Add(a, b int64) int64 {
	return (a + b) % mod
}

func Mult(a, b int64) int64 {
	return (a * b) % mod
}

func solve() {
	arr := []byte(next())
	stack := []int{0}
	res := len(arr)
	for i := 1; i < len(arr); i++ {
		if arr[i] == 'B' && len(stack) > 0 {
			res -= 2
			stack = stack[0 : len(stack)-1]
		} else {
			stack = append(stack, i)
		}
	}
	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"
)

func main() {
	defer _w.Flush()
	t := ReadInt()
	for i := 0; i < t; i++ {
		s := ReadString()
		Println(solve(s))
	}

}

func solve(s string) int {
	var a, b int
	for i := 0; i < len(s); i++ {
		if s[i] == 'A' {
			a++
			continue
		}
		if a > 0 {
			a--
		} else if b > 0 {
			b--
		} else {
			b++
		}
	}
	return a + b
}

var _r, _w = bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)

func Print(a ...interface{})            { fmt.Fprint(_w, a...) }
func Printf(f string, a ...interface{}) { fmt.Fprintf(_w, f, a...) }
func Println(a ...interface{})          { fmt.Fprintln(_w, a...) }
func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(_r, a...); err != nil {
		panic(err)
	}
}
func ReadString() (s string) { Scan(&s); return }
func ReadInt() (i int)       { Scan(&i); return }
func ReadInts(n int) (a []int) {
	for i := 0; i < n; i++ {
		a = append(a, ReadInt())
	}
	return
}
func ReadInt64() (i int64) { Scan(&i); return }
func ReadInt64s(n int) (a []int64) {
	for i := 0; i < n; i++ {
		a = append(a, ReadInt64())
	}
	return
}

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

package main

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

var (
	t int

	S []rune
)

func main() {
	defer stdout.Flush()

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

		solve()
	}
}

func solve() {
	st := []rune{}

	for _, r := range S {
		if r == 'A' {
			st = append(st, r)
			continue
		}

		if len(st) > 0 {
			l := len(st)
			st = st[:l-1]
		} else {
			st = append(st, r)
		}
	}

	printf("%d\n", len(st))
}

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

/********** common constants **********/

const (
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPH_N  = 26
	INF_I64 = math.MaxInt64
	INF_B60 = 1 << 60
	INF_I32 = math.MaxInt32
	INF_B30 = 1 << 30
	NIL     = -1
	EPS     = 1e-10
)

/********** bufio setting **********/

func init() {
	// bufio.ScanWords <---> bufio.ScanLines
	reads = newReadString(os.Stdin, bufio.ScanWords)
	stdout = bufio.NewWriter(os.Stdout)
}

// mod can calculate a right residual whether value is positive or negative.
func mod(val, m int) int {
	res := val % m
	if res < 0 {
		res += m
	}
	return res
}

// min returns the min integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func min(integers ...int) int {
	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 ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

// 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
}

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

// sum returns multiple integers sum.
func sum(integers ...int) int {
	var s int
	s = 0

	for _, i := range integers {
		s += i
	}

	return s
}

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

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

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

//str := reads()
//i := readi()
//X := readis(n)
//S := readrs()
//a := readf()
//A := readfs(n)

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

/*********** Input ***********/

var (
	// reads returns a WORD string.
	reads  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()
	}
}

// readi returns an integer.
func readi() int {
	return int(_readInt64())
}
func readi2() (int, int) {
	return int(_readInt64()), int(_readInt64())
}
func readi3() (int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64())
}
func readi4() (int, int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64()), int(_readInt64())
}

// readll returns as integer as int64.
func readll() int64 {
	return _readInt64()
}
func readll2() (int64, int64) {
	return _readInt64(), _readInt64()
}
func readll3() (int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64()
}
func readll4() (int64, int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64(), _readInt64()
}

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

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

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

// readf returns an float64.
func readf() float64 {
	return float64(_readFloat64())
}

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

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

// readrs returns a rune slice.
func readrs() []rune {
	return []rune(reads())
}

/*********** Output ***********/

// 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)
}

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

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

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

// 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
}

package main

import (
	"fmt"
)

func solve(s string) int {
	// B总能带走其之前的字符

	l := 0 // 扫过的字符串的 爆炸后 剩余长度
	for i := range s {
		if s[i] == 'A' {
			l += 1
		}
		if s[i] == 'B' {
			if l == 0 {
				l += 1
			} else {
				l -= 1
			}
		}
	}

	return l
}

func main() {

	//log.SetLogLevel(log.DebugLevel)

	t := 0
	fmt.Scanf("%d\n", &t)

	for t > 0 {
		var s string
		fmt.Scanf("%s\n", &s)
		fmt.Println(solve(s))
		t -= 1
	}
}

package main

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

var reader = bufio.NewReader(os.Stdin)

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

	for i := 0; i < t; i++ {
		var s string
		fmt.Fscan(reader, &s)

		var stack []rune
		for _, r := range s {
			if len(stack) == 0 {
				stack = append(stack, r)
				continue
			}

			if r == 'A' {
				stack = append(stack, r)
				continue
			}

			stack = stack[:len(stack)-1]
		}

		fmt.Println(len(stack))
	}
}

package main

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

func configure(scanner *bufio.Scanner) {
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 1000005), 1000005)
}
func getNextString(scanner *bufio.Scanner) string {
	scanned := scanner.Scan()
	if !scanned {
		panic("scan failed")
	}
	return scanner.Text()
}
func getNextInt(scanner *bufio.Scanner) int {
	i, _ := strconv.Atoi(getNextString(scanner))
	return i
}
func getNextInt64(scanner *bufio.Scanner) int64 {
	i, _ := strconv.ParseInt(getNextString(scanner), 10, 64)
	return i
}
func getNextFloat64(scanner *bufio.Scanner) float64 {
	i, _ := strconv.ParseFloat(getNextString(scanner), 64)
	return i
}
func main() {
	fp := os.Stdin
	wfp := os.Stdout
	extra := 0
	if os.Getenv("I") == "IronMan" {
		fp, _ = os.Open(os.Getenv("END_GAME"))
		extra = 100
	}
	scanner := bufio.NewScanner(fp)
	configure(scanner)
	writer := bufio.NewWriter(wfp)
	defer func() {
		r := recover()
		if r != nil {
			fmt.Fprintln(writer, r)
		}
		writer.Flush()
	}()
	solve(scanner, writer)
	for i := 0; i < extra; i++ {
		fmt.Fprintln(writer, "-----------------------------------")
		solve(scanner, writer)
	}
}
func solve(scanner *bufio.Scanner, writer *bufio.Writer) {
	t := getNextInt(scanner)
	for t > 0 {
		t--
		func() {
			s := getNextString(scanner)
			n := len(s)
			stack := make([]byte, 0)
			for i := 0; i < n; i++ {
				if len(stack) == 0 || s[i] == 'A' {
					stack = append(stack, s[i])
					continue
				}
				stack = stack[:len(stack)-1]
			}
			fmt.Fprintln(writer, len(stack))
		}()
	}
}

package main

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

var reader = bufio.NewReader(os.Stdin)

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

	for i := 0; i < t; i++ {
		var s string
		fmt.Fscan(reader, &s)

		var leftover []int
		for j := 0; j < len(s); {
			if j < len(s)-1 && ((s[j] == 'A' && s[j+1] == 'B') || (s[j] == 'B' && s[j+1] == 'B')) {
				j += 2
				continue
			}

			if len(leftover) > 0 {
				last := leftover[len(leftover)-1]
				if (s[last] == 'A' && s[j] == 'B') || (s[last] == 'B' && s[j] == 'B') {
					leftover = leftover[:len(leftover)-1]
					j++
					continue
				}
			}

			leftover = append(leftover, j)
			j++
		}

		fmt.Println(len(leftover))
	}
}


package main

import "bufio"
import "os"
import "fmt"
import "math"

func Read(s *bufio.Reader) string {
    line, _ := s.ReadString('\n')
    return line
}

func Write(s *bufio.Writer, a ...interface{}) {
    fmt.Fprintln(s, a...)
    s.Flush()
}

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

    var n int
    fmt.Sscanln(Read(reader), &n)

    a := make([]int, n)

    for i := 0; i < n - 1; i++ {
        line, _ := reader.ReadString(' ')
        fmt.Sscanln(line, &a[i])
    }

    fmt.Sscanln(Read(reader), &a[n - 1])

    var last int = 0

    writer := bufio.NewWriter(os.Stdout)
    for _, v := range a {
        mod := int(math.Mod(float64(v), 2.0))
        winner := 0
        if mod != 0 {
            winner = 1
        }

        if last == 1 {
            winner = 1 - winner
        }

        if winner == 0 {
            Write(writer, 1)
        } else {
            Write(writer, 2)
        }

        last = 1 - winner
    }
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	qty_str, _ := reader.ReadString('\n')
	cycles_str, _ := reader.ReadString('\n')
	cycles_qty, err := strconv.Atoi(strings.TrimSpace(qty_str))
	if err != nil {
		panic(err)
	}

	cycle_parts := strings.Split(strings.TrimSpace(cycles_str), " ")

	var cycles []int64
	for i:= 0; i < cycles_qty; i++ {
		new_i, _ := strconv.ParseInt(cycle_parts[i], 10, 64)
		cycles = append(cycles, new_i)
	}

	var result int64
	for i := 0; i < cycles_qty; i++ {
	    if cycles[i] % 2 == 0 {
	    	result += 1
	    } else {
	    	result += 2
	    }

	    if result % 2 == 0 {
			fmt.Println(2)
	    } else {
	    	fmt.Println(1)
	    }
	}
}

package main

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

import "strings"

func main() {
	reader := bufio.NewReader(os.Stdin)
	text, _ := reader.ReadString('\n')
	text = strings.TrimRight(text, "\r\n")
	s := strings.Split(text, " ")

	c, _ := strconv.Atoi(s[0])
	text, _ = reader.ReadString('\n')
	text = strings.TrimRight(text, "\r\n")
	s = strings.Split(text, " ")
	//x, _ := strconv.ParseInt(s[1], 10, 64)
	moves := 0
	for i := 0; i < c; i++ {
		c, _ := strconv.Atoi(s[i])
		moves += (c - 1)
		if (moves % 2) == 0 {
			fmt.Println("2")
		} else {
			fmt.Println("1")
		}
	}

}

package main

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

func main() {
	in := bufio.NewScanner(os.Stdin)
	out := bufio.NewWriter(os.Stdout)

	in.Split(bufio.ScanWords)
	defer out.Flush()

	in.Scan()
	n, _ := strconv.Atoi(in.Text())

	g := 0
	for i := 1; i <= n; i++ {
		in.Scan()
		a, _ := strconv.Atoi(in.Text())

		g ^= ((a - 1) & 1)

		res := 1
		if g == 0 {
			res = 2
		}

		out.WriteString(strconv.Itoa(res))
		out.WriteByte('\n')
	}
}

package main

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

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

	moves := 0

	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := 0; i < n && scanner.Scan(); i++ {
		a, err := strconv.Atoi(scanner.Text())
		if err != nil {
			return
		}
		moves += a - 1

		if moves%2 == 0 {
			fmt.Println(2)
		} else {
			fmt.Println(1)
		}
	}
}


package main

import (
	"fmt"
	"math"
	"math/big"
	"sort"
)

var n int64

// f(x) := x ((x - 3) / 2 + 2^k))
func f(x int64, k uint) *big.Int {
	tmp := big.NewInt(x)
	tmp.Sub(tmp, big.NewInt(3))
	tmp.Div(tmp, big.NewInt(2))
	tmp.Add(tmp, big.NewInt(0).Lsh(big.NewInt(1), k))
	return tmp.Mul(tmp, big.NewInt(x))
}

func calcPlayers(x int64, k uint) int64 {
	return x * (int64(1) << k)
}

type Int64Slice []int64

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

func binSearch(k uint) (int64, bool) {
	/*left := int64(1) // x should be 0 for k>0 and 1 for k=1, but it must always be odd
	right := 2 * int64(math.Sqrt(float64(n)) + 1) // upper bound for x
	fmt.Println(left, right)
	for right - left > 1 {
		x := (left + right) / 2
	}*/
	bign := big.NewInt(n)
	left := int64(0)
	right := int64(math.Sqrt(float64(n))) + 1
	for right-left > 1 {
		mid := (left + right) / 2
		x := 2*mid + 1
		val := f(x, k)
		if bign.Cmp(val) < 0 {
			right = mid
		} else {
			left = mid
		}
	}
	if f(2*left+1, k).Cmp(bign) == 0 {
		return calcPlayers(2*left+1, k), true
	}
	return 0, false
}

func main() {
	fmt.Scan(&n)
	playerCnts := Int64Slice(make([]int64, 0, 60))
	for k := uint(0); k <= 59; k++ {
		if cnt, ok := binSearch(k); ok {
			playerCnts = append(playerCnts, cnt)
		}
	}
	if len(playerCnts) == 0 {
		playerCnts = append(playerCnts, -1)
	}
	sort.Sort(playerCnts)
	for _, cnt := range playerCnts {
		fmt.Println(cnt)
	}
}

package main

import (
	"fmt"
	"sort"
)

var n int64

func f(x int64, k uint) int64 {
	return x * ((x - 3) / 2 + (int64(1) << k))
}

func calcPlayers(x int64, k uint) int64 {
	return x * (int64(1) << k)
}

type Int64Slice []int64

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

func binSearch(k uint) (int64, bool) {
	left := int64(0)
	right := int64(1)
	for f(2*right+1, k) <= n {
		right *= 2
	}
	for right-left > 1 {
		mid := (left + right) / 2
		x := 2*mid + 1
		val := f(x, k)
		if n < val {
			right = mid
		} else {
			left = mid
		}
	}
	if f(2*left+1, k) == n {
		return calcPlayers(2*left+1, k), true
	}
	return 0, false
}

func main() {
	fmt.Scan(&n)
	cnts := Int64Slice(make([]int64, 0))
	for k := uint(0); k <= 59; k++ {
		if cnt, ok := binSearch(k); ok {
			cnts = append(cnts, cnt)
		}
	}
	if len(cnts) == 0 {
		cnts = append(cnts, -1)
	}
	sort.Sort(cnts)
	for _, cnt := range cnts {
		fmt.Println(cnt)
	}
}

package main

import (
	"fmt"
	"math"
	"math/big"
	"sort"
)

var n int64 = 25

// f(x) := x ((x - 3) / 2 + 2^k))
func f(x int64, k uint) *big.Int {
	tmp := big.NewInt(x)
	tmp.Sub(tmp, big.NewInt(3))
	tmp.Div(tmp, big.NewInt(2))
	tmp.Add(tmp, big.NewInt(0).Lsh(big.NewInt(1), k))
	return tmp.Mul(tmp, big.NewInt(x))
}

func calcPlayers(x int64, k uint) int64 {
	return x * (int64(1) << k)
}

type Int64Slice []int64

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

func binSearch(k uint) (int64, bool) {
	/*left := int64(1) // x should be 0 for k>0 and 1 for k=1, but it must always be odd
	right := 2 * int64(math.Sqrt(float64(n)) + 1) // upper bound for x
	fmt.Println(left, right)
	for right - left > 1 {
		x := (left + right) / 2
	}*/
	bign := big.NewInt(n)
	left := int64(0)
	right := int64(math.Sqrt(float64(n))) + 1
	for right-left > 1 {
		mid := (left + right) / 2
		x := 2*mid + 1
		val := f(x, k)
		if bign.Cmp(val) < 0 {
			right = mid
		} else {
			left = mid
		}
	}
	if f(2*left+1, k).Cmp(bign) == 0 {
		return calcPlayers(2*left+1, k), true
	}
	return 0, false
}

func main() {
	playerCnts := Int64Slice(make([]int64, 0, 59))
	for k := uint(0); k < 59; k++ {
		if cnt, ok := binSearch(k); ok {
			playerCnts = append(playerCnts, cnt)
		}
	}
	if len(playerCnts) == 0 {
		playerCnts = append(playerCnts, -1)
	}
	sort.Sort(playerCnts)
	for _, cnt := range playerCnts {
		fmt.Println(cnt)
	}
}

package main

import (
	"fmt"
	"math"
	"math/big"
	"sort"
)

var n int64 = 25

// f(x) := x ((x - 3) / 2 + 2^k))
func f(x int64, k uint) *big.Int {
	tmp := big.NewInt(x)
	tmp.Sub(tmp, big.NewInt(3))
	tmp.Div(tmp, big.NewInt(2))
	tmp.Add(tmp, big.NewInt(0).Lsh(big.NewInt(1), k))
	return tmp.Mul(tmp, big.NewInt(x))
}

func calcPlayers(x int64, k uint) int64 {
	return x * (int64(1) << k)
}

type Int64Slice []int64

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

func binSearch(k uint) (int64, bool) {
	/*left := int64(1) // x should be 0 for k>0 and 1 for k=1, but it must always be odd
	right := 2 * int64(math.Sqrt(float64(n)) + 1) // upper bound for x
	fmt.Println(left, right)
	for right - left > 1 {
		x := (left + right) / 2
	}*/
	bign := big.NewInt(n)
	left := int64(0)
	right := int64(math.Sqrt(float64(n))) + 1
	for right-left > 1 {
		mid := (left + right) / 2
		x := 2*mid + 1
		val := f(x, k)
		if bign.Cmp(val) < 0 {
			right = mid
		} else {
			left = mid
		}
	}
	if f(2*left+1, k).Cmp(bign) == 0 {
		return calcPlayers(2*left+1, k), true
	}
	return 0, false
}

func main() {
	fmt.Scan(&n)
	playerCnts := Int64Slice(make([]int64, 0, 59))
	for k := uint(0); k < 59; k++ {
		if cnt, ok := binSearch(k); ok {
			playerCnts = append(playerCnts, cnt)
		}
	}
	if len(playerCnts) == 0 {
		playerCnts = append(playerCnts, -1)
	}
	sort.Sort(playerCnts)
	for _, cnt := range playerCnts {
		fmt.Println(cnt)
	}
}


// 00
package main

import (
	"bufio"
	"container/list"
	"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, curr int
		fmt.Fscan(reader, &n)
		l := list.New()
		for i := 0; i < n; i++ {
			fmt.Fscan(reader, &curr)
			if l.Len() == 0 {
				l.PushBack(curr)
			} else {
				front := l.Front().Value.(int)
				if curr < front {
					l.PushFront(curr)
				} else {
					l.PushBack(curr)
				}
			}
		}
		for e := l.Front(); e != nil; e = e.Next() {
			write_int(f, e.Value.(int))
			write_string(f, " ")
		}
		write_string(f, "\n")

	}
}

package main

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

//problem E1

func main() {
	reader := bufio.NewReader(os.Stdin)
	var t, n int

	fmt.Fscanf(reader, "%d\n", &t)
	for ; t > 0; t-- {
		fmt.Fscanf(reader, "%d\n", &n)
		p := make([]int, n)

		for i := 0; i < n-1; i++ {
			fmt.Fscanf(reader, "%d ", &p[i])
		}
		fmt.Fscanf(reader, "%d\n", &p[n-1])

		l := list.New()
		l.PushBack(p[0])

		for i := 1; i < n; i++ {
			if p[i] < l.Front().Value.(int) {
				l.PushFront(p[i])
			} else {
				l.PushBack(p[i])
			}
		}

		for e := l.Front(); e != nil; e = e.Next() {
			fmt.Printf("%d ", e.Value)
		}
		fmt.Println()
	}
}

package main

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

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

	var T, n, v int
	for Fscan(in, &T); T > 0; T-- {
		var a, b []int
		for Fscan(in, &n); n > 0; n-- {
			if Fscan(in, &v); a == nil || v < a[len(a)-1] {
				a = append(a, v)
			} else {
				b = append(b, v)
			}
		}
		for i := len(a) - 1; i >= 0; i-- {
			Fprint(out, a[i], " ")
		}
		for _, v := range b {
			Fprint(out, v, " ")
		}
		Fprintln(out)
	}
}

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

package main

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

var n int

var a []int

var writer *bufio.Writer

func main() {

	read := bufio.NewReader(os.Stdin)
	writer = bufio.NewWriter(os.Stdout)

	var t int
	fmt.Fscan(read, &t)

	for i := 0; i < t; i++ {
		fmt.Fscan(read, &n)

		a = make([]int, n)

		for j := 0; j < n; j++ {
			fmt.Fscan(read, &a[j])
		}

		solve()
	}
}

type pair struct {
	v int
	idx int
}

type byV []*pair

func (a byV) Len() int           { return len(a) }
func (a byV) Less(i, j int) bool { return a[i].v < a[j].v }
func (a byV) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

func solve() {
	present := make([]bool, n + 1)
	ans := make([]int, n)

	start := 0
	end := n - 1

	lookFor := 1

	for j := n - 1; j >= 0; j-- {
		present[a[j]] = true

		if a[j] == lookFor {
			ans[start] = a[j]
			start++

			for j := lookFor + 1; j <= n; j++ {
				if !present[j] {
					lookFor = j
					break
				}
			}

		} else {
			ans[end] = a[j]
			end--
		}
	}

	for i := 0; i < n; i++ {
		fmt.Print(ans[i])
		fmt.Print(" ")
	}
	fmt.Println()

}

package main

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

func main() {
	r := bufio.NewReaderSize(os.Stdin, 1024*1024)

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

	for t := 0; t < T; t++ {
		var n int
		fmt.Fscanf(r, "%d\n", &n)
		arr := make([]int, n)

		for i := 0; i < n; i++ {
			fmt.Fscanf(r, "%d", &arr[i])
		}
		fmt.Fscanf(r, "\n")

		d := make([]int, 3*n)
		b := len(d) / 2
		e := b
		d[b] = arr[0]

		for i := 1; i < len(arr); i++ {
			if arr[i] < d[b] {
				b--
				d[b] = arr[i]
			} else {
				e++
				d[e] = arr[i]
			}
		}

		for i := b; i <= e; i++ {
			fmt.Print(d[i], " ")
		}
		fmt.Println()
	}
}

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)

		arr := make([]int, n)
		m := make([]int, n+1)
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &arr[i])
			m[arr[i]] = i
		}
		m[0] = n

		z := make([]int, n)
		l, r := 0, n
		last := m[1]
		for i := 1; i <= n; i++ {
			// if current index larger, then we have already saw it.
			if m[i] > last {
				continue
			}

			z[l] = i
			var k int
			if i == 1 {
				k = n - m[i] - 1
			} else {
				k = last - m[i] - 1
			}

			for j := 0; j < k; j++ {
				z[r-k+j] = arr[m[i]+1+j]
			}
			last = m[i]
			l++
			r -= k
		}
		for _, v := range z {
			fmt.Fprintf(out, "%d ", v)
		}
		fmt.Fprintln(out)
	}
}

package main

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

//------
// Main
//------

func main() {
	sc.Split(bufio.ScanWords)
	defer wr.Flush()
	d := NewDeque(0)
	testcases := nextInt()
	for testcase := 0; testcase < testcases; testcase++ {
		d.Clear()
		N := nextInt()
		arr := make([]int64, N)
		for i := range arr {
			arr[i] = nextInt64()
		}
		for _, v := range arr {
			if d.Len() == 0 {
				d.PushFront(v)
			} else {
				c := d.GetFront()
				if c >= v {
					d.PushFront(v)
				} else {
					d.PushBack(v)
				}
			}
		}
		for d.Len() != 0 {
			fmt.Fprintf(wr, "%d ", d.PopFront())
		}
		fmt.Fprintln(wr)
	}
}

//-------
// Deque
//-------

type Deque struct {
	item        []int64
	front, rear int
	cap         int
}

func NewDeque(cap int) *Deque {
	if cap <= 1 {
		cap = 2
	}
	d := new(Deque)
	d.item = make([]int64, cap)
	d.front, d.rear = 0, 0
	d.cap = cap
	return d
}

func (d *Deque) extend(newCap int) {
	newLen := d.Len()
	newArr := make([]int64, newCap)
	if d.rear >= d.front {
		copy(newArr, d.item[d.front:d.rear])
	} else {
		lenFront := len(d.item) - d.front
		copy(newArr, d.item[d.front:])
		copy(newArr[lenFront:], d.item[:d.rear])
	}
	d.item = newArr
	d.cap = newCap
	d.front, d.rear = 0, newLen
}

func (d *Deque) PushBack(n int64) {
	// If the deque is about to overflow, reallocate data
	if d.Len() >= d.cap-1 {
		d.extend(d.cap * 3 / 2)
	}

	d.item[d.rear] = n
	d.rear++
	d.rear %= d.cap
}

func (d *Deque) PushFront(n int64) {
	// If the deque is about to overflow, reallocate data
	if d.Len() >= d.cap-1 {
		d.extend(d.cap * 3 / 2)
	}

	d.front--
	d.front %= d.cap
	if d.front < 0 {
		d.front += d.cap
	}
	d.item[d.front] = n
}

func (d *Deque) PopBack() int64 {
	d.rear--
	d.rear %= d.cap
	if d.rear < 0 {
		d.rear += d.cap
	}
	return d.item[d.rear]
}

func (d *Deque) PopFront() int64 {
	temp := d.item[d.front]
	d.front++
	if d.front >= d.cap {
		d.front -= d.cap
	}
	return temp
}

func (d *Deque) GetBack() int64 {
	idx := d.rear - 1
	if idx < 0 {
		idx += d.cap
	}
	return d.item[idx]
}

func (d *Deque) GetFront() int64 {
	return d.item[d.front]
}

func (d *Deque) Len() int {
	length := (d.rear - d.front) % d.cap
	if length < 0 {
		length += d.cap
	}
	return length
}

func (d *Deque) Clear() {
	d.front, d.rear = 0, 0
}

//---------
// Fast IO
//---------

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

func nextInt() int {
	sc.Scan()
	text := sc.Text()
	v, _ := strconv.Atoi(text)
	return v
}

func nextInt64() int64 {
	sc.Scan()
	text := sc.Text()
	v, _ := strconv.ParseInt(text, 10, 64)
	return v
}

package main

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

func solve() {
	f := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	N, n := 0, 0
	fmt.Fscan(f, &N)
	for i := 0; i < N; i++ {
		fmt.Fscan(f, &n)
		o := list.New()
		for j := 0; j < n; j++ {
			p := 0
			fmt.Fscan(f, &p)
			if o.Len() == 0 || p <= o.Front().Value.(int) {
				o.PushFront(p)
			} else {
				o.PushBack(p)
			}
		}
		for j := o.Front(); j != nil; j = j.Next() {
			fmt.Fprint(w, j.Value.(int), " ")
		}
		fmt.Fprintln(w, "")
	}
	w.Flush()
}

func main() {
	solve()
}

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)

		arr := make([]int, n)
		m := make([]int, n+1)
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &arr[i])
			m[arr[i]] = i
		}
		m[0] = n

		z := make([]int, n)
		l, r := 0, n
		for i := 1; i <= n; i++ {
			// if current index larger, then we have already saw it.
			if m[i] > m[l] {
				continue
			}

			z[l] = i
			var k int
			if i == 1 {
				k = n - m[i] - 1
			} else {
				k = m[z[l-1]] - m[i] - 1
			}

			for j := 0; j < k; j++ {
				if r-k+j < n && m[i]+1+j < n {
					z[r-k+j] = arr[m[i]+1+j]
				}
			}
			l++
			r -= k
		}
		for _, v := range z {
			fmt.Fprintf(out, "%d ", v)
		}
		fmt.Fprintln(out)
	}
}

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)

		arr := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &arr[i])
		}

		low := 0
		for i := 1; i < n; i++ {
			if arr[i] > arr[low] {
				break
			}
			low = i
		}

		for i := low; i >= 0; i-- {
			fmt.Fprintf(out, "%d ", arr[i])
		}

		for i := low + 1; i < n; i++ {
			fmt.Fprintf(out, "%d ", arr[i])
		}
		fmt.Fprintln(out)
	}
}

package main

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

//------
// Main
//------

func main() {
	sc.Split(bufio.ScanWords)
	defer wr.Flush()
	s := NewSplay()
	d := NewDeque(0)
	testcases := nextInt()
	for testcase := 0; testcase < testcases; testcase++ {
		s.Clear()
		d.Clear()
		N := nextInt()
		for i := 0; i < N; i++ {
			v := nextInt()
			s.AddVal(v, 1)
			l := s.GetSumOfSmaller(v)
			r := s.GetSumOfLarger(v)

			if l < r {
				d.PushFront(v)
			} else if l > r {
				d.PushBack(v)
			} else {
				if d.Len() == 0 {
					d.PushFront(v)
				} else {
					if d.GetFront() < v {
						d.PushBack(v)
					} else {
						d.PushFront(v)
					}
				}
			}
		}
		for d.Len() != 0 {
			fmt.Fprintf(wr, "%d ", d.PopFront())
		}
		fmt.Fprintln(wr)
	}
}

//-------
// Deque
//-------

type Deque struct {
	item        []int
	front, rear int
	cap         int
}

func NewDeque(cap int) *Deque {
	if cap <= 1 {
		cap = 2
	}
	d := new(Deque)
	d.item = make([]int, cap)
	d.front, d.rear = 0, 0
	d.cap = cap
	return d
}

func (d *Deque) extend(newCap int) {
	newLen := d.Len()
	newArr := make([]int, newCap)
	if d.rear >= d.front {
		copy(newArr, d.item[d.front:d.rear])
	} else {
		lenFront := len(d.item) - d.front
		copy(newArr, d.item[d.front:])
		copy(newArr[lenFront:], d.item[:d.rear])
	}
	d.item = newArr
	d.cap = newCap
	d.front, d.rear = 0, newLen
}

func (d *Deque) PushBack(n int) {
	// If the deque is about to overflow, reallocate data
	if d.Len() >= d.cap-1 {
		d.extend(d.cap * 3 / 2)
	}

	d.item[d.rear] = n
	d.rear++
	d.rear %= d.cap
}

func (d *Deque) PushFront(n int) {
	// If the deque is about to overflow, reallocate data
	if d.Len() >= d.cap-1 {
		d.extend(d.cap * 3 / 2)
	}

	d.front--
	d.front %= d.cap
	if d.front < 0 {
		d.front += d.cap
	}
	d.item[d.front] = n
}

func (d *Deque) PopBack() int {
	d.rear--
	d.rear %= d.cap
	if d.rear < 0 {
		d.rear += d.cap
	}
	return d.item[d.rear]
}

func (d *Deque) PopFront() int {
	temp := d.item[d.front]
	d.front++
	if d.front >= d.cap {
		d.front -= d.cap
	}
	return temp
}

func (d *Deque) GetBack() int {
	idx := d.rear - 1
	if idx < 0 {
		idx += d.cap
	}
	return d.item[idx]
}

func (d *Deque) GetFront() int {
	return d.item[d.front]
}

func (d *Deque) Len() int {
	length := (d.rear - d.front) % d.cap
	if length < 0 {
		length += d.cap
	}
	return length
}

func (d *Deque) Clear() {
	d.front, d.rear = 0, 0
}

//------------
// Splay Tree
//------------

type Node struct {
	k       int
	v       int
	p, l, r *Node

	sum int
}

func NewNode(k int, v int) *Node {
	return &Node{k: k, v: v, sum: v}
}

func connect(p, c *Node, isLeft bool) {
	if c != nil {
		c.p = p
	}
	if p != nil {
		if isLeft {
			p.l = c
		} else {
			p.r = c
		}
	}
}

func (n *Node) update() {
	n.sum = n.v
	if n.l != nil {
		n.sum += n.l.sum
	}
	if n.r != nil {
		n.sum += n.r.sum
	}
}

type Splay struct {
	root *Node
}

func NewSplay() *Splay {
	sp := new(Splay)
	return sp
}

func (s *Splay) Clear() {
	s.root = nil
}

// panics if n == s.root
func (s *Splay) rotate(n *Node) {
	p := n.p
	if p.p == nil {
		n.p = nil
		s.root = n
	} else {
		if p.p.l == p {
			p.p.l = n
		} else {
			p.p.r = n
		}
		n.p = p.p
	}
	if p.l == n { // If x is left child
		b := n.r
		connect(n, p, false)
		connect(p, b, true)
	} else {
		b := n.l
		connect(n, p, true)
		connect(p, b, false)
	}
	if s.root == p {
		s.root = n
	}
	p.update()
	n.update()
}

func (s *Splay) splay(n *Node) {
	for {
		if n == s.root {
			return
		} else if n.p == s.root {
			s.rotate(n)
			return
		}
		p := n.p
		g := n.p.p
		if (p.l == n) == (g.l == p) {
			// Zig-Zig
			s.rotate(p)
			s.rotate(n)
		} else {
			// Zig-Zag
			s.rotate(n)
			s.rotate(n)
		}
	}
}

func (s *Splay) AddVal(k int, v int) {
	ptr := s.root
	if ptr == nil {
		s.root = NewNode(k, 1)
		return
	}
	var ins *Node

	loop := true
	for {
		switch {
		case ptr.k > k: // Insert left
			if ptr.l == nil {
				ins = NewNode(k, v)
				connect(ptr, ins, true)
				loop = false
			} else {
				ptr = ptr.l
			}
		case ptr.k < k: // Insert right
			if ptr.r == nil {
				ins = NewNode(k, v)
				connect(ptr, ins, false)
				loop = false
			} else {
				ptr = ptr.r
			}
		default: // Found k
			ptr.v += v
			ins = ptr
			loop = false
		}
		if !loop {
			break
		}
	}

	// Nodes above ins will be automatically updated when being rotated while splay
	s.splay(ins)
}

func (s *Splay) lookup(k int) *Node {
	ptr := s.root
	for {
		switch {
		case ptr.k > k: // At left
			if ptr.l == nil {
				return nil
			} else {
				ptr = ptr.l
			}
		case ptr.k < k: // At right
			if ptr.r == nil {
				return nil
			} else {
				ptr = ptr.r
			}
		default: // Found k
			return ptr
		}
	}
}

// Use this after inserting at least one k
func (s *Splay) GetSumOfSmaller(k int) int {
	x := s.lookup(k)
	s.splay(x)
	if x.l == nil {
		return 0
	}
	return x.l.sum
}

func (s *Splay) GetSumOfLarger(k int) int {
	x := s.lookup(k)
	s.splay(x)
	if x.r == nil {
		return 0
	}
	return x.r.sum
}

//---------
// Fast IO
//---------

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

func nextInt() int {
	sc.Scan()
	text := sc.Text()
	v, _ := strconv.Atoi(text)
	return v
}

package main

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

//------
// Main
//------

func main() {
	sc.Split(bufio.ScanWords)
	defer wr.Flush()
	s := NewSplay()
	d := NewDeque(0)
	testcases := nextInt()
	for testcase := 0; testcase < testcases; testcase++ {
		s.Clear()
		d.Clear()
		N := nextInt()
		for i := 0; i < N; i++ {
			v := nextInt()
			s.AddVal(v, 1)
			l := s.GetSumOfSmaller(v)
			r := s.GetSumOfLarger(v)

			if l <= r {
				d.PushFront(v)
			} else {
				d.PushBack(v)
			}
		}
		for d.Len() != 0 {
			fmt.Fprintf(wr, "%d ", d.PopFront())
		}
		fmt.Fprintln(wr)
	}
}

//-------
// Deque
//-------

type Deque struct {
	item        []int
	front, rear int
	cap         int
}

func NewDeque(cap int) *Deque {
	if cap <= 1 {
		cap = 2
	}
	d := new(Deque)
	d.item = make([]int, cap)
	d.front, d.rear = 0, 0
	d.cap = cap
	return d
}

func (d *Deque) extend(newCap int) {
	newLen := d.Len()
	newArr := make([]int, newCap)
	if d.rear >= d.front {
		copy(newArr, d.item[d.front:d.rear])
	} else {
		lenFront := len(d.item) - d.front
		copy(newArr, d.item[d.front:])
		copy(newArr[lenFront:], d.item[:d.rear])
	}
	d.item = newArr
	d.cap = newCap
	d.front, d.rear = 0, newLen
}

func (d *Deque) PushBack(n int) {
	// If the deque is about to overflow, reallocate data
	if d.Len() >= d.cap-1 {
		d.extend(d.cap * 3 / 2)
	}

	d.item[d.rear] = n
	d.rear++
	d.rear %= d.cap
}

func (d *Deque) PushFront(n int) {
	// If the deque is about to overflow, reallocate data
	if d.Len() >= d.cap-1 {
		d.extend(d.cap * 3 / 2)
	}

	d.front--
	d.front %= d.cap
	if d.front < 0 {
		d.front += d.cap
	}
	d.item[d.front] = n
}

func (d *Deque) PopBack() int {
	d.rear--
	d.rear %= d.cap
	if d.rear < 0 {
		d.rear += d.cap
	}
	return d.item[d.rear]
}

func (d *Deque) PopFront() int {
	temp := d.item[d.front]
	d.front++
	if d.front >= d.cap {
		d.front -= d.cap
	}
	return temp
}

func (d *Deque) GetBack() int {
	idx := d.rear - 1
	if idx < 0 {
		idx += d.cap
	}
	return d.item[idx]
}

func (d *Deque) GetFront() int {
	return d.item[d.front]
}

func (d *Deque) Len() int {
	length := (d.rear - d.front) % d.cap
	if length < 0 {
		length += d.cap
	}
	return length
}

func (d *Deque) Clear() {
	d.front, d.rear = 0, 0
}

//------------
// Splay Tree
//------------

type Node struct {
	k       int
	v       int
	p, l, r *Node

	sum int
}

func NewNode(k int, v int) *Node {
	return &Node{k: k, v: v, sum: v}
}

func connect(p, c *Node, isLeft bool) {
	if c != nil {
		c.p = p
	}
	if p != nil {
		if isLeft {
			p.l = c
		} else {
			p.r = c
		}
	}
}

func (n *Node) update() {
	n.sum = n.v
	if n.l != nil {
		n.sum += n.l.sum
	}
	if n.r != nil {
		n.sum += n.r.sum
	}
}

type Splay struct {
	root *Node
}

func NewSplay() *Splay {
	sp := new(Splay)
	return sp
}

func (s *Splay) Clear() {
	s.root = nil
}

// panics if n == s.root
func (s *Splay) rotate(n *Node) {
	p := n.p
	if p.p == nil {
		n.p = nil
		s.root = n
	} else {
		if p.p.l == p {
			p.p.l = n
		} else {
			p.p.r = n
		}
		n.p = p.p
	}
	if p.l == n { // If x is left child
		b := n.r
		connect(n, p, false)
		connect(p, b, true)
	} else {
		b := n.l
		connect(n, p, true)
		connect(p, b, false)
	}
	if s.root == p {
		s.root = n
	}
	p.update()
	n.update()
}

func (s *Splay) splay(n *Node) {
	for {
		if n == s.root {
			return
		} else if n.p == s.root {
			s.rotate(n)
			return
		}
		p := n.p
		g := n.p.p
		if (p.l == n) == (g.l == p) {
			// Zig-Zig
			s.rotate(p)
			s.rotate(n)
		} else {
			// Zig-Zag
			s.rotate(n)
			s.rotate(n)
		}
	}
}

func (s *Splay) AddVal(k int, v int) {
	ptr := s.root
	if ptr == nil {
		s.root = NewNode(k, 1)
		return
	}
	var ins *Node

	loop := true
	for {
		switch {
		case ptr.k > k: // Insert left
			if ptr.l == nil {
				ins = NewNode(k, v)
				connect(ptr, ins, true)
				loop = false
			} else {
				ptr = ptr.l
			}
		case ptr.k < k: // Insert right
			if ptr.r == nil {
				ins = NewNode(k, v)
				connect(ptr, ins, false)
				loop = false
			} else {
				ptr = ptr.r
			}
		default: // Found k
			ptr.v += v
			ins = ptr
			loop = false
		}
		if !loop {
			break
		}
	}

	// Nodes above ins will be automatically updated when being rotated while splay
	s.splay(ins)
}

func (s *Splay) lookup(k int) *Node {
	ptr := s.root
	for {
		switch {
		case ptr.k > k: // At left
			if ptr.l == nil {
				return nil
			} else {
				ptr = ptr.l
			}
		case ptr.k < k: // At right
			if ptr.r == nil {
				return nil
			} else {
				ptr = ptr.r
			}
		default: // Found k
			return ptr
		}
	}
}

// Use this after inserting at least one k
func (s *Splay) GetSumOfSmaller(k int) int {
	x := s.lookup(k)
	s.splay(x)
	if x.l == nil {
		return 0
	}
	return x.l.sum
}

func (s *Splay) GetSumOfLarger(k int) int {
	x := s.lookup(k)
	s.splay(x)
	if x.r == nil {
		return 0
	}
	return x.r.sum
}

//---------
// Fast IO
//---------

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

func nextInt() int {
	sc.Scan()
	text := sc.Text()
	v, _ := strconv.Atoi(text)
	return v
}

package main

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

//------
// Main
//------

func main() {
	sc.Split(bufio.ScanWords)
	defer wr.Flush()
	s := NewSplay()
	d := NewDeque(0)
	testcases := nextInt()
	for testcase := 0; testcase < testcases; testcase++ {
		s.Clear()
		d.Clear()
		N := nextInt()
		for i := 0; i < N; i++ {
			v := nextInt()
			s.AddVal(v, 1)
			l := s.GetSumOfSmaller(v)
			r := s.GetSumOfLarger(v)

			if l < r {
				d.PushFront(v)
			} else {
				d.PushBack(v)
			}
		}
		for d.Len() != 0 {
			fmt.Fprintf(wr, "%d ", d.PopFront())
		}
		fmt.Fprintln(wr)
	}
}

//-------
// Deque
//-------

type Deque struct {
	item        []int
	front, rear int
	cap         int
}

func NewDeque(cap int) *Deque {
	if cap <= 1 {
		cap = 2
	}
	d := new(Deque)
	d.item = make([]int, cap)
	d.front, d.rear = 0, 0
	d.cap = cap
	return d
}

func (d *Deque) extend(newCap int) {
	newLen := d.Len()
	newArr := make([]int, newCap)
	if d.rear >= d.front {
		copy(newArr, d.item[d.front:d.rear])
	} else {
		lenFront := len(d.item) - d.front
		copy(newArr, d.item[d.front:])
		copy(newArr[lenFront:], d.item[:d.rear])
	}
	d.item = newArr
	d.cap = newCap
	d.front, d.rear = 0, newLen
}

func (d *Deque) PushBack(n int) {
	// If the deque is about to overflow, reallocate data
	if d.Len() >= d.cap-1 {
		d.extend(d.cap * 3 / 2)
	}

	d.item[d.rear] = n
	d.rear++
	d.rear %= d.cap
}

func (d *Deque) PushFront(n int) {
	// If the deque is about to overflow, reallocate data
	if d.Len() >= d.cap-1 {
		d.extend(d.cap * 3 / 2)
	}

	d.front--
	d.front %= d.cap
	if d.front < 0 {
		d.front += d.cap
	}
	d.item[d.front] = n
}

func (d *Deque) PopBack() int {
	d.rear--
	d.rear %= d.cap
	if d.rear < 0 {
		d.rear += d.cap
	}
	return d.item[d.rear]
}

func (d *Deque) PopFront() int {
	temp := d.item[d.front]
	d.front++
	if d.front >= d.cap {
		d.front -= d.cap
	}
	return temp
}

func (d *Deque) GetBack() int {
	idx := d.rear - 1
	if idx < 0 {
		idx += d.cap
	}
	return d.item[idx]
}

func (d *Deque) GetFront() int {
	return d.item[d.front]
}

func (d *Deque) Len() int {
	length := (d.rear - d.front) % d.cap
	if length < 0 {
		length += d.cap
	}
	return length
}

func (d *Deque) Clear() {
	d.front, d.rear = 0, 0
}

//------------
// Splay Tree
//------------

type Node struct {
	k       int
	v       int
	p, l, r *Node

	sum int
}

func NewNode(k int, v int) *Node {
	return &Node{k: k, v: v, sum: v}
}

func connect(p, c *Node, isLeft bool) {
	if c != nil {
		c.p = p
	}
	if p != nil {
		if isLeft {
			p.l = c
		} else {
			p.r = c
		}
	}
}

func (n *Node) update() {
	n.sum = n.v
	if n.l != nil {
		n.sum += n.l.sum
	}
	if n.r != nil {
		n.sum += n.r.sum
	}
}

type Splay struct {
	root *Node
}

func NewSplay() *Splay {
	sp := new(Splay)
	return sp
}

func (s *Splay) Clear() {
	s.root = nil
}

// panics if n == s.root
func (s *Splay) rotate(n *Node) {
	p := n.p
	if p.p == nil {
		n.p = nil
		s.root = n
	} else {
		if p.p.l == p {
			p.p.l = n
		} else {
			p.p.r = n
		}
		n.p = p.p
	}
	if p.l == n { // If x is left child
		b := n.r
		connect(n, p, false)
		connect(p, b, true)
	} else {
		b := n.l
		connect(n, p, true)
		connect(p, b, false)
	}
	if s.root == p {
		s.root = n
	}
	p.update()
	n.update()
}

func (s *Splay) splay(n *Node) {
	for {
		if n == s.root {
			return
		} else if n.p == s.root {
			s.rotate(n)
			return
		}
		p := n.p
		g := n.p.p
		if (p.l == n) == (g.l == p) {
			// Zig-Zig
			s.rotate(p)
			s.rotate(n)
		} else {
			// Zig-Zag
			s.rotate(n)
			s.rotate(n)
		}
	}
}

func (s *Splay) AddVal(k int, v int) {
	ptr := s.root
	if ptr == nil {
		s.root = NewNode(k, 1)
		return
	}
	var ins *Node

	loop := true
	for {
		switch {
		case ptr.k > k: // Insert left
			if ptr.l == nil {
				ins = NewNode(k, v)
				connect(ptr, ins, true)
				loop = false
			} else {
				ptr = ptr.l
			}
		case ptr.k < k: // Insert right
			if ptr.r == nil {
				ins = NewNode(k, v)
				connect(ptr, ins, false)
				loop = false
			} else {
				ptr = ptr.r
			}
		default: // Found k
			ptr.v += v
			ins = ptr
			loop = false
		}
		if !loop {
			break
		}
	}

	// Nodes above ins will be automatically updated when being rotated while splay
	s.splay(ins)
}

func (s *Splay) lookup(k int) *Node {
	ptr := s.root
	for {
		switch {
		case ptr.k > k: // At left
			if ptr.l == nil {
				return nil
			} else {
				ptr = ptr.l
			}
		case ptr.k < k: // At right
			if ptr.r == nil {
				return nil
			} else {
				ptr = ptr.r
			}
		default: // Found k
			return ptr
		}
	}
}

// Use this after inserting at least one k
func (s *Splay) GetSumOfSmaller(k int) int {
	x := s.lookup(k)
	s.splay(x)
	if x.l == nil {
		return 0
	}
	return x.l.sum
}

func (s *Splay) GetSumOfLarger(k int) int {
	x := s.lookup(k)
	s.splay(x)
	if x.r == nil {
		return 0
	}
	return x.r.sum
}

//---------
// Fast IO
//---------

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

func nextInt() int {
	sc.Scan()
	text := sc.Text()
	v, _ := strconv.Atoi(text)
	return v
}