Since you are the best Wraith King, Nizhniy Magazin «Mir» at the centre of Vinnytsia is offering you a discount.You are given an array a of length n and an integer c. The value of some array b of length k is the sum of its elements except for the  smallest. For example, the value of the array [3, 1, 6, 5, 2] with c = 2 is 3 + 6 + 5 = 14.Among all possible partitions of a into contiguous subarrays output the smallest possible sum of the values of these subarrays.

The first line contains integers n and c (1 ≤ n, c ≤ 100 000). The second line contains n integers ai (1 ≤ ai ≤ 109) — elements of a.

Output a single integer  — the smallest possible sum of values of these subarrays of some partition of a.

NoteIn the first example any partition yields 6 as the sum.In the second example one of the optimal partitions is [1, 1], [10, 10, 10, 10, 10, 10, 9, 10, 10, 10] with the values 2 and 90 respectively.In the third example one of the optimal partitions is [2, 3], [6, 4, 5, 7], [1] with the values 3, 13 and 1 respectively.In the fourth example one of the optimal partitions is [1], [3, 4, 5, 5, 3, 4], [1] with the values 1, 21 and 1 respectively.

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

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


One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie.

The first line contains an integer n (1 ≤ n ≤ 100) — the number of lines in the description. Then follow n lines — for each goal the names of the teams that scored it. The names are non-empty lines consisting of uppercase Latin letters whose lengths do not exceed 10 symbols. It is guaranteed that the match did not end in a tie and the description contains no more than two different teams.

Print the name of the winning team. We remind you that in football the team that scores more goals is considered the winner.

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

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"
    "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)

}

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


Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated.For example, Zookeeper can use two such operations: AABABBA $$$\to$$$ AABBA $$$\to$$$ AAA.Zookeeper wonders what the shortest string he can make is. Can you help him find the length of the shortest string?

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 20000)$$$  — the number of test cases. The description of the test cases follows. Each of the next $$$t$$$ lines contains a single test case each, consisting of a non-empty string $$$s$$$: the string that Zookeeper needs to bomb. It is guaranteed that all symbols of $$$s$$$ are either 'A' or 'B'. It is guaranteed that the sum of $$$|s|$$$ (length of $$$s$$$) among all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print a single integer: the length of the shortest string that Zookeeper can make.

NoteFor the first test case, you can't make any moves, so the answer is $$$3$$$.For the second test case, one optimal sequence of moves is BABA $$$\to$$$ BA. So, the answer is $$$2$$$.For the third test case, one optimal sequence of moves is AABBBABBBB $$$\to$$$ AABBBABB $$$\to$$$ AABBBB $$$\to$$$ ABBB $$$\to$$$ AB $$$\to$$$ (empty string). So, the answer is $$$0$$$.

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


Peter Parker wants to play a game with Dr. Octopus. The game is about cycles. Cycle is a sequence of vertices, such that first one is connected with the second, second is connected with third and so on, while the last one is connected with the first one again. Cycle may consist of a single isolated vertex.Initially there are k cycles, i-th of them consisting of exactly vi vertices. Players play alternatively. Peter goes first. On each turn a player must choose a cycle with at least 2 vertices (for example, x vertices) among all available cycles and replace it by two cycles with p and x - p vertices where 1 ≤ p < x is chosen by the player. The player who cannot make a move loses the game (and his life!).Peter wants to test some configurations of initial cycle sets before he actually plays with Dr. Octopus. Initially he has an empty set. In the i-th test he adds a cycle with ai vertices to the set (this is actually a multiset because it can contain two or more identical cycles). After each test, Peter wants to know that if the players begin the game with the current set of cycles, who wins? Peter is pretty good at math, but now he asks you to help.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of tests Peter is about to make. The second line contains n space separated integers a1, a2, ..., an (1 ≤ ai ≤ 109), i-th of them stands for the number of vertices in the cycle added before the i-th test.

Print the result of all tests in order they are performed. Print 1 if the player who moves first wins or 2 otherwise.

NoteIn the first sample test:In Peter's first test, there's only one cycle with 1 vertex. First player cannot make a move and loses.In his second test, there's one cycle with 1 vertex and one with 2. No one can make a move on the cycle with 1 vertex. First player can replace the second cycle with two cycles of 1 vertex and second player can't make any move and loses.In his third test, cycles have 1, 2 and 3 vertices. Like last test, no one can make a move on the first cycle. First player can replace the third cycle with one cycle with size 1 and one with size 2. Now cycles have 1, 1, 2, 2 vertices. Second player's only move is to replace a cycle of size 2 with 2 cycles of size 1. And cycles are 1, 1, 1, 1, 2. First player replaces the last cycle with 2 cycles with size 1 and wins.In the second sample test:Having cycles of size 1 is like not having them (because no one can make a move on them). In Peter's third test: There a cycle of size 5 (others don't matter). First player has two options: replace it with cycles of sizes 1 and 4 or 2 and 3.  If he replaces it with cycles of sizes 1 and 4: Only second cycle matters. Second player will replace it with 2 cycles of sizes 2. First player's only option to replace one of them with two cycles of size 1. Second player does the same thing with the other cycle. First player can't make any move and loses.  If he replaces it with cycles of sizes 2 and 3: Second player will replace the cycle of size 3 with two of sizes 1 and 2. Now only cycles with more than one vertex are two cycles of size 2. As shown in previous case, with 2 cycles of size 2 second player wins. So, either way first player loses.

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

}


Daniel is organizing a football tournament. He has come up with the following tournament format:   In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even.  Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are x teams, there will be  games), and the tournament ends. For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games.Daniel has already booked the stadium for n games. Help him to determine how many teams he should invite so that the tournament needs exactly n games. You should print all possible numbers of teams that will yield exactly n games in ascending order, or -1 if there are no such numbers.

The first line contains a single integer n (1 ≤ n ≤ 1018), the number of games that should be played. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

Print all possible numbers of invited teams in ascending order, one per line. If exactly n games cannot be played, output one number: -1.

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

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


In fact, the problems E1 and E2 do not have much in common. You should probably think of them as two separate problems.A permutation $$$p$$$ of size $$$n$$$ is given. A permutation of size $$$n$$$ is an array of size $$$n$$$ in which each integer from $$$1$$$ to $$$n$$$ occurs exactly once. For example, $$$[1, 4, 3, 2]$$$ and $$$[4, 2, 1, 3]$$$ are correct permutations while $$$[1, 2, 4]$$$ and $$$[1, 2, 2]$$$ are not.Let us consider an empty deque (double-ended queue). A deque is a data structure that supports adding elements to both the beginning and the end. So, if there are elements $$$[1, 5, 2]$$$ currently in the deque, adding an element $$$4$$$ to the beginning will produce the sequence $$$[\color{red}{4}, 1, 5, 2]$$$, and adding same element to the end will produce $$$[1, 5, 2, \color{red}{4}]$$$.The elements of the permutation are sequentially added to the initially empty deque, starting with $$$p_1$$$ and finishing with $$$p_n$$$. Before adding each element to the deque, you may choose whether to add it to the beginning or the end.For example, if we consider a permutation $$$p = [3, 1, 2, 4]$$$, one of the possible sequences of actions looks like this: $$$\quad$$$ 1.add $$$3$$$ to the end of the deque:deque has a sequence $$$[\color{red}{3}]$$$ in it;$$$\quad$$$ 2.add $$$1$$$ to the beginning of the deque:deque has a sequence $$$[\color{red}{1}, 3]$$$ in it;$$$\quad$$$ 3.add $$$2$$$ to the end of the deque:deque has a sequence $$$[1, 3, \color{red}{2}]$$$ in it;$$$\quad$$$ 4.add $$$4$$$ to the end of the deque:deque has a sequence $$$[1, 3, 2, \color{red}{4}]$$$ in it;Find the lexicographically smallest possible sequence of elements in the deque after the entire permutation has been processed. A sequence $$$[x_1, x_2, \ldots, x_n]$$$ is lexicographically smaller than the sequence $$$[y_1, y_2, \ldots, y_n]$$$ if there exists such $$$i \leq n$$$ that $$$x_1 = y_1$$$, $$$x_2 = y_2$$$, $$$\ldots$$$, $$$x_{i - 1} = y_{i - 1}$$$ and $$$x_i < y_i$$$. In other words, if the sequences $$$x$$$ and $$$y$$$ have some (possibly empty) matching prefix, and the next element of the sequence $$$x$$$ is strictly smaller than the corresponding element of the sequence $$$y$$$. For example, the sequence $$$[1, 3, 2, 4]$$$ is smaller than the sequence $$$[1, 3, 4, 2]$$$ because after the two matching elements $$$[1, 3]$$$ in the start the first sequence has an element $$$2$$$ which is smaller than the corresponding element $$$4$$$ in the second sequence.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases.  The first line of each test case description contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — permutation size. The second line of the description contains $$$n$$$ space-separated integers $$$p_i$$$ ($$$1 \le p_i \le n$$$; all $$$p_i$$$ are all unique) — elements of the permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to a test case should contain $$$n$$$ space-separated integer numbers — the elements of the lexicographically smallest permutation that is possible to find in the deque after executing the described algorithm.

NoteOne of the ways to get a lexicographically smallest permutation $$$[1, 3, 2, 4]$$$ from the permutation $$$[3, 1, 2, 4]$$$ (the first sample test case) is described in the problem statement.

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

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