package main

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

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

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 s string
		fmt.Fscan(in, &s)

		d := 9
		aa := make([]int, 10)
		for i := len(s) - 1; i >= 0; i-- {
			v := int(s[i] - '0')
			if v <= d {
				d = v
				aa[v]++
			} else {
				aa[min(v+1, 9)]++
			}
		}

		for i := 0; i < 10; i++ {
			for j := 0; j < aa[i]; j++ {
				fmt.Fprintf(out, "%d", i)
			}
		}
		fmt.Fprintln(out)
	}
}

package main

import (
	"fmt"
)

func work(n string) string {
	s := map[byte]int{}

	for i := byte('0'); i < byte('9'); i++ {
		s[i] = 0
	}

	min := byte('9')
	for i := len(n) - 1; i >= 0; i-- {
		v := n[i]
		if v > min {
			if v < byte('9') {
				v++
			}
			s[v] += 1
		} else {
			s[v] += 1
			min = v
		}
	}

	r := []byte{}
	for i := byte('0'); i <= byte('9'); i++ {
		for j := 0; j < s[i]; j++ {
			r = append(r, i)
		}
	}

	return string(r)
}

func main() {
	var t int
	fmt.Scanf("%d\n", &t)
	for ; t > 0; t-- {
		var n string
		fmt.Scanf("%s\n", &n)
		fmt.Println(work(n))
	}
}

package main

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

const cf = true

func solve() {
	var s string
	fmt.Fscan(in, &s)
	n := len(s)
	cnt := make([]int, 10)
	curPos := -1
	for i := 0; i <= 9; i++ {
		chr := strconv.Itoa(i)[0]
		rightMost := -1
		for j := n - 1; j > curPos; j-- {
			if s[j] == chr {
				rightMost = j
				break
			}
		}
		if rightMost == -1 {
			continue
		}
		for j := curPos + 1; j <= rightMost; j++ {
			if s[j] == chr {
				cnt[i]++
			} else {
				integer, _ := strconv.Atoi(string(s[j]))
				cnt[min(9, integer+1)]++
			}
		}
		curPos = rightMost
		if curPos == n-1 {
			break
		}
	}
	for i := 0; i <= 9; i++ {
		chr := strconv.Itoa(i)
		for j := 0; j < cnt[i]; j++ {
			fmt.Fprint(out, chr)
		}
	}
	fmt.Fprintln(out)
}

func main() {
	defer out.Flush()
	t := 1
	fmt.Fscan(in, &t)
	for ; t > 0; t-- {
		solve()
	}
}

func ConvertInt(val string, base, toBase int) (string, error) {
	i, err := strconv.ParseInt(val, base, 64)
	if err != nil {
		return "", err
	}
	return strconv.FormatInt(i, toBase), nil
}

type set[T Ordered] struct {
	itms map[T]struct{}
}

func (s *set[T]) init() {
	if s.itms == nil {
		s.itms = make(map[T]struct{})
	}
}

func (s *set[T]) add(item T) *set[T] {
	s.init()
	s.itms[item] = exists
	return s
}

func (s *set[T]) remove(item T) *set[T] {
	s.init()
	delete(s.itms, item)
	return s
}

func (s *set[T]) has(item T) bool {
	s.init()
	_, c := s.itms[item]
	return c
}

func (s *set[T]) sortedItems() []T {
	s.init()
	items := make([]T, 0, s.size())
	for item := range s.itms {
		items = append(items, item)
	}
	sort.Slice(items, func(i, j int) bool {
		return items[i] < items[j]
	})
	return items
}

func (s *set[T]) items() []T {
	s.init()
	items := make([]T, 0, s.size())
	for item := range s.itms {
		items = append(items, item)
	}
	return items
}

func (s *set[T]) size() int {
	s.init()
	return len(s.itms)
}

var exists = struct{}{}

const MaxUint = ^uint(0)
const MinUint = 0
const MaxInt = int(MaxUint >> 1)
const MinInt = -MaxInt - 1

func reverseStr(s string) string {
	r := []rune(s)
	for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
		r[i], r[j] = r[j], r[i]
	}
	return string(r)
}

type Float interface {
	~float32 | ~float64
}

type Integer interface {
	Signed | Unsigned
}

type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

type Unsigned interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

type Ordered interface {
	Integer | Float | ~string
}

func abs[T Signed](x T) T {
	if x < 0 {
		return -x
	}
	return x
}

func min[T Ordered](x, y T) T {
	if x < y {
		return x
	}
	return y
}

func max[T Ordered](x, y T) T {
	if x > y {
		return x
	}
	return y
}

var (
	in  = getReader()
	out = getWriter()
)

func getReader() *bufio.Reader {
	if cf {
		return bufio.NewReader(os.Stdin)
	} else {
		in, _ := os.Open("input.txt")
		return bufio.NewReader(in)
	}
}

func getWriter() *bufio.Writer {
	if cf {
		return bufio.NewWriter(os.Stdout)
	} else {
		out, _ := os.Create("output.txt")
		return bufio.NewWriter(out)
	}
}

package main

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

const N = 3e5
const inf = 1e9

var iost *Iost

type Iost struct {
	Scanner *bufio.Scanner
	Writer  *bufio.Writer
}

func NewIost(fp io.Reader, wfp io.Writer) *Iost {
	const BufSize = 2000005
	scanner := bufio.NewScanner(fp)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, BufSize), BufSize)
	return &Iost{Scanner: scanner, Writer: bufio.NewWriter(wfp)}
}
func (i *Iost) Text() string {
	if !i.Scanner.Scan() {
		panic("scan failed")
	}
	return i.Scanner.Text()
}
func (i *Iost) Atoi(s string) int                 { x, _ := strconv.Atoi(s); return x }
func (i *Iost) GetNextInt() int                   { return i.Atoi(i.Text()) }
func (i *Iost) Atoi64(s string) int64             { x, _ := strconv.ParseInt(s, 10, 64); return x }
func (i *Iost) GetNextInt64() int64               { return i.Atoi64(i.Text()) }
func (i *Iost) Atof64(s string) float64           { x, _ := strconv.ParseFloat(s, 64); return x }
func (i *Iost) GetNextFloat64() float64           { return i.Atof64(i.Text()) }
func (i *Iost) Print(x ...interface{})            { fmt.Fprint(i.Writer, x...) }
func (i *Iost) Printf(s string, x ...interface{}) { fmt.Fprintf(i.Writer, s, x...) }
func (i *Iost) Println(x ...interface{})          { fmt.Fprintln(i.Writer, x...) }

func BAAL() {
	in := os.Stdin
	out := os.Stdout
	iost = NewIost(in, out)
}

func karo(a *[]int, dig int, v *[]int) {
	n := len(*a)
	if n == 0 {
		return
	}
	last := -1
	for i := 0; i < n; i++ {
		if (*a)[i] == dig {
			last = i
		}
	}
	if last == -1 {
		return
	}
	for i := 0; i <= last; i++ {
		if (*a)[i] == dig {
			*v = append(*v, (*a)[i])
		} else {
			if (*a)[i] == 9 {
				*v = append(*v, 9)
			} else {
				*v = append(*v, (*a)[i]+1)
			}
		}
	}
	var b []int
	for i := last + 1; i < n; i++ {
		b = append(b, (*a)[i])
	}
	*a = b
}

func main() {
	BAAL()
	defer func() {
		iost.Writer.Flush()
	}()
	t := iost.GetNextInt()
	for t > 0 {
		t--
		s := iost.Text()
		n := len(s)
		var a []int
		for i := 0; i < n; i++ {
			a = append(a, int(s[i]-'0'))
		}
		var o []int
		for i := 0; i < 10; i++ {
			karo(&a, i, &o)
		}
		sort.Ints(o)
		for _, x := range o {
			iost.Print(x)
		}
		iost.Println()
	}
}

package main

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

const N = 3e5
const inf = 1e9

var iost *Iost

type Iost struct {
	Scanner *bufio.Scanner
	Writer  *bufio.Writer
}

func NewIost(fp io.Reader, wfp io.Writer) *Iost {
	const BufSize = 2000005
	scanner := bufio.NewScanner(fp)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, BufSize), BufSize)
	return &Iost{Scanner: scanner, Writer: bufio.NewWriter(wfp)}
}
func (i *Iost) Text() string {
	if !i.Scanner.Scan() {
		panic("scan failed")
	}
	return i.Scanner.Text()
}
func (i *Iost) Atoi(s string) int                 { x, _ := strconv.Atoi(s); return x }
func (i *Iost) GetNextInt() int                   { return i.Atoi(i.Text()) }
func (i *Iost) Atoi64(s string) int64             { x, _ := strconv.ParseInt(s, 10, 64); return x }
func (i *Iost) GetNextInt64() int64               { return i.Atoi64(i.Text()) }
func (i *Iost) Atof64(s string) float64           { x, _ := strconv.ParseFloat(s, 64); return x }
func (i *Iost) GetNextFloat64() float64           { return i.Atof64(i.Text()) }
func (i *Iost) Print(x ...interface{})            { fmt.Fprint(i.Writer, x...) }
func (i *Iost) Printf(s string, x ...interface{}) { fmt.Fprintf(i.Writer, s, x...) }
func (i *Iost) Println(x ...interface{})          { fmt.Fprintln(i.Writer, x...) }

func BAAL() {
	in := os.Stdin
	out := os.Stdout
	iost = NewIost(in, out)
}

func swap(a, b *int) {
	x := *a
	*a = *b
	*b = x
}

func karo(a []int, dig int) {
	ind := -1
	n := len(a)
	for i := 0; i < n; i++ {
		if a[i] >= dig {
			ind = i
			break
		}
	}
	if ind == -1 {
		return
	}
	last := -1
	for i := ind; i < n; i++ {
		if a[i] == dig {
			last = i
		}
	}
	if last == -1 {
		return
	}
	var v []int
	for i := ind; i <= last; i++ {
		if a[i] == dig {
			v = append(v, a[i])
		}
	}
	var v1 []int
	for i := ind; i <= last; i++ {
		if a[i] != dig {
			if a[i] == 9 {
				v1 = append(v1, 9)
			} else {
				v1 = append(v1, a[i]+1)
			}
		}
	}
	sort.Ints(v1)
	for _, x := range v1 {
		v = append(v, x)
	}
	for i := ind; i <= last; i++ {
		a[i] = v[i-ind]
	}
}

func main() {
	BAAL()
	defer func() {
		iost.Writer.Flush()
	}()
	t := iost.GetNextInt()
	for t > 0 {
		t--
		s := iost.Text()
		n := len(s)
		var a []int
		for i := 0; i < n; i++ {
			a = append(a, int(s[i]-'0'))
		}
		for i := 0; i < 10; i++ {
			karo(a, i)
		}
		for _, x := range a {
			iost.Print(x)
		}
		iost.Println()
	}
}


package main

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

// var m []int
// err = json.Unmarshal([]byte(r.FormValue("example")), &m)

// for i := 0; i < len(m); i++ {
// 	fmt.Println(m[i])
// }

func MIN(x, y int64) int64 {
	if x > y {
		return y
	} else {
		return x
	}
}

func MKO(x, y int64) int64 {
	if x < y {
		return 0
	} else {
		return x - y + 1
	}
}

func MAX(x, y int64) int64 {
	if x > y {
		return x
	} else {
		return y
	}
}

func LCM(x, y int) int {
	if x >= y {
		initial := x
		for i := 1; i < y+2; i++ {
			if initial%y == 0 {
				break
			} else {
				initial = initial + x
			}

		}
		return initial
	} else {
		initial := y
		for i := 1; i < x+2; i++ {
			if initial%x == 0 {
				break
			} else {
				initial = initial + y
			}

		}
		return initial
	}
}

func GCD(x, y int64) int64 {
	var l, q int64
	l = MAX(x, y)
	q = MIN(x, y)
	var m int64
	for l*q > 0 {
		a := l % q
		b := l - a
		cc := int64(b / q)
		remain := l - cc*q
		l = MAX(remain, q)
		q = MIN(remain, q)
		if l*q == 0 {
			m = l + q
			break
		}

	}
	return m

}

func IsItPrime(x int) bool {
	if x < 10 {
		if x == 2 || x == 3 || x == 5 || x == 7 {
			return true
		} else {
			return false
		}
	} else {
		j := 0
		k := math.Sqrt(float64(x))
		for m := 3; m <= int(k); {
			if x%m == 0 {
				j = 1
				break
			}
			m = m + 2
		}
		if j == 1 {
			return false
		} else {
			return true
		}
	}

}

// sort.Slice(arr, func(i, j int) bool {
// 	return arr[i] > arr[j]
// })
var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &t)

	for o := 0; o < t; o++ {
		var n int
		fmt.Fscan(input, &n)
		TMT := make([]byte, 0)
		fmt.Fscan(input, &TMT)

		ini := 0
		qqq := 0
		for i := 0; i < n; i++ {
			if string(TMT[i]) == "T" {
				ini++
			} else {
				ini--
			}
			if ini < 0 {
				qqq = 1
				break
			}

		}
		if ini != int(n/3) || qqq == 1 {
			fmt.Println("NO")
		} else {
			www := 0
			iii := 0
			for i := n - 1; i > -1; i-- {
				if string(TMT[i]) == "T" {
					iii++
				} else {
					iii--
				}
				if iii < 0 {
					www = 1
					fmt.Println("NO")
					break
				}
			}
			if www == 0 {
				fmt.Println("YES")
			}
		}

	}
}

package main

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

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

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

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

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

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

/**
 Run solve the problem CF1509B
 Date: 17/04/21
 User: pepradere
 URL: https://codeforces.com/contest/1509/problem/B
 Problem: CF1509B
**/
func (in *CF1509B) Run() {
	T := in.NextInt()
	for ; T > 0; T-- {
		in.NextInt()
		cad := in.NextString()
		M, P := 0, 0
		ws := true
		for i := 0; i < len(cad); i++ {
			if cad[i] == 'M' {
				M++
			} else {
				P++
			}
			if M > P {
				ws = false
			}
		}
		M = 0
		P = 0
		for i := len(cad)-1; i>=0; i-- {
			if cad[i] == 'M' {
				M++
			} else {
				P++
			}
			if M > P {
				ws = false
			}
		}

		if M*2 != P || cad[len(cad)-1] == 'M' {
			ws = false
		}

		if ws {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

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

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

package main

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

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

	var T, n int
	var s string
o:
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &s)
		m := strings.Count(s, "M")
		if m*3 != n {
			Fprintln(out, "NO")
			continue
		}
		c := 0
		for _, b := range s {
			if b == 'T' {
				c++
			} else {
				c--
				if c < 0 {
					Fprintln(out, "NO")
					continue o
				}
			}
		}
		c = 0
		for i := n - 1; i >= 0; i-- {
			if s[i] == 'T' {
				c++
			} else {
				c--
				if c < 0 {
					Fprintln(out, "NO")
					continue o
				}
			}
		}
		Fprintln(out, "YES")
	}
}

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

package main

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

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

func Scan(a ...interface{})    { fmt.Fscan(reader, a...) }
func Scanln(a ...interface{})  { fmt.Fscanln(reader, a...) }
func Print(a ...interface{})   { fmt.Fprint(writer, a...) }
func Println(a ...interface{}) { fmt.Fprintln(writer, a...) }

func main() {
	defer writer.Flush()
	var t int
	Scanln(&t)
	for ; t > 0; t-- {
		fi := 0
		se := 0
		var n int
		Scanln(&n)
		var s string
		Scanln(&s)
		te := 0
		em := 0
		valid := true
		for _, v := range s {
			if v == 'T' {
				te++
			} else {
				em++
			}
		}
		if te != 2*em {
			valid = false
		}
		cnt_t := 0
		for _, v := range s {
			if v == 'T' {
				if cnt_t < em {
					cnt_t++
					fi++
				} else if se != 0 {
					se--
				} else {
					valid = false
					break
				}
			} else {
				if fi == 0 {
					valid = false
					break
				}
				se++
				fi--
			}
		}
		if fi > 0 || se > 0 {
			valid = false
		}
		if !valid {
			Println("NO")
		} else {
			Println("YES")
		}
	}
}

package main

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

const REPEAT bool = true
const CASE   bool = false

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

  if REPEAT {
    var t int
    Fscan(in, &t);
    for i := 1; i <= t; i++ {
      if CASE {
        Fprintf(out, "Case #%d: ", i)
      }
      solve(in, out)
    }
  } else {
    solve(in, out)
  }
}

func solve(in io.Reader, out io.Writer) {
  var n int
  var s string
  Fscan(in, &n, &s)
  tc, mc := 0, 0
  for _, c := range s {
    if c == 'T' {
      tc++
    } else {
      mc++
    }
  }
  if tc != 2 * mc {
    Fprintln(out, "NO")
  } else {
    lim, cntr := n / 3, 0
    for _, c := range s {
      if c == 'T' {
        cntr++
      } else {
        cntr--
      }
      if cntr > lim || cntr < 0 {
        Fprintln(out, "NO")
        return
      }
    }
    Fprintln(out, "YES")
  }
}

package main

import "fmt"

func main() {
	var t, n, tmp, tcount, mcount, done int
	var processed bool
	var str string
	fmt.Scanf("%d", &t)
	fmt.Scanf("%d", &tmp)
	for ; t > 0; t = t - 1 {
		fmt.Scanf("%d", &n)
		fmt.Scanf("%d", &tmp)
		fmt.Scanf("%s", &str)
		fmt.Scanf("%d", &tmp)

		tcount, mcount, done = 0, 0, 0
		processed = false
		for _, i := range str {
			// fmt.Print(string(i), " ")
			if i == 'T' {
				if mcount <= tcount && mcount > 0 {
					tcount -= 1
					mcount -= 1
					done += 1
					continue
				}
				tcount += 1
			} else if mcount == tcount {
				if done > 0 {
					tcount += 2
					mcount += 2
					done -= 1
				} else {
					fmt.Println("NO")
					processed = true
					break
				}
			} else {
				mcount += 1
			}
		}
		if processed {
			continue
		}
		if tcount == 0 && mcount == 0 {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

func main() {

	r := bufio.NewReader(os.Stdin)

	var t int

	fmt.Fscan(r, &t)

	for i := 0; i < t; i++ {
		var n int

		fmt.Fscan(r, &n)

		var s string
		fmt.Fscan(r, &s)

		ans := solve(s)

		fmt.Println(ans)
	}
}

func solve(s string) string {

	var counter int

	for i := 0 ; i < len(s); i++ {
		if s[i] == 'T' {
			counter++
		} else {

			if counter <= 0 {
				return "NO"
			}
			counter--
		}
	}

	counter = 0

	for i := len(s) - 1; i >= 0; i-- {
		if s[i] == 'T' {
			counter++
		} else {

			if counter <= 0 {
				return "NO"
			}
			counter--
		}
	}

	var ts int
	var ms int

	for i := 0; i < len(s); i++ {
		if s[i] == 'T' {
			ts++
		} else {
			ms++
		}
	}
	if ts == 2 * ms {
		return "YES"
	}
	return "NO"
}

package main

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

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

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

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

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

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

/**
 Run solve the problem CF1509B
 Date: 17/04/21
 User: pepradere
 URL: https://codeforces.com/contest/1509/problem/B
 Problem: CF1509B
**/
func (in *CF1509B) Run() {
	T := in.NextInt()
	for ; T > 0; T-- {
		in.NextInt()
		cad := in.NextString()
		M, P := 0, 0
		ws := true
		for i := 0; i < len(cad); i++ {
			if cad[i] == 'M' {
				M++
			} else {
				P++
			}
			if M > P {
				ws = false
			}
		}

		if M*2 != P || cad[len(cad)-1] == 'M' {
			ws = false
		}

		if ws {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

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

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

package main

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

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

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

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

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

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

/**
 Run solve the problem CF1509B
 Date: 17/04/21
 User: pepradere
 URL: https://codeforces.com/contest/1509/problem/B
 Problem: CF1509B
**/
func (in *CF1509B) Run() {
	T := in.NextInt()
	for ; T > 0; T-- {
		in.NextInt()
		cad := in.NextString()
		M, P := 0, 0
		ws := true
		for i := 0; i < len(cad); i++ {
			if cad[i] == 'M' {
				M++
			} else {
				P++
			}
			if M > P {
				ws = false
			}
		}

		if M*2 != P {
			ws = false
		}

		if ws {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

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

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

package main

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

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

	var T, n int
	var s string
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &s)
		m := strings.Count(s, "M")
		if m*3 != n {
			Fprintln(out, "NO")
			continue
		}
		c := 0
		for _, b := range s[:strings.LastIndex(s, "M")+1] {
			if b == 'T' {
				c++
			} else {
				c--
				if c < 0 {
					break
				}
			}
		}
		if c != 0 {
			Fprintln(out, "NO")
		} else {
			Fprintln(out, "YES")
		}
	}
}

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

package main

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

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

func Scan(a ...interface{})    { fmt.Fscan(reader, a...) }
func Scanln(a ...interface{})  { fmt.Fscanln(reader, a...) }
func Print(a ...interface{})   { fmt.Fprint(writer, a...) }
func Println(a ...interface{}) { fmt.Fprintln(writer, a...) }

func main() {
	defer writer.Flush()
	var t int
	Scanln(&t)
	for ; t > 0; t-- {
		fi := 0
		se := 0
		var n int
		Scanln(&n)
		var x string
		Scanln(&x)
		var s string
		for i := len(x) - 1; i >= 0; i-- {
			s += string(x[i])
		}
		valid := true
		for _, v := range s {
			if v == 'T' {
				if se != 0 {
					se--
				} else {
					fi++
				}
			} else {
				if fi == 0 {
					valid = false
					break
				} else {
					fi--
					se++
				}
			}
		}
		if fi > 0 || se > 0 {
			valid = false
		}
		if !valid {
			Println("NO")
		} else {
			Println("YES")
		}
	}
}


package main

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

// github.com/EndlessCheng/codeforces-go
func CF1276B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	subSize := func(g [][]int, a, b int) (sz int) {
		ids := make([]int, len(g))
		idCnt := 0
		var f func(int)
		f = func(v int) {
			ids[v] = idCnt
			for _, w := range g[v] {
				if w != a && ids[w] == 0 {
					f(w)
				}
			}
		}
		for i, id := range ids {
			if i != a && id == 0 {
				idCnt++
				f(i)
			}
		}
		if idCnt == 1 {
			return
		}
		for i, id := range ids {
			if i != a && id != ids[b] {
				sz++
			}
		}
		return
	}

	var t, n, m, a, b, v, w int
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n, &m, &a, &b)
		a--
		b--
		g := make([][]int, n)
		for ; m > 0; m-- {
			Fscan(in, &v, &w)
			v--
			w--
			g[v] = append(g[v], w)
			g[w] = append(g[w], v)
		}
		Fprintln(out, int64(subSize(g, a, b))*int64(subSize(g, b, a)))
	}
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1276B(_r io.Reader, _w io.Writer) {
	in := bufio.NewScanner(_r)
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	r := func() (x int) {
		in.Scan()
		for _, b := range in.Bytes() {
			x = x*10 + int(b-'0')
		}
		return
	}
	subSize := func(g [][]int, a, b int) (sz int) {
		ids := make([]int, len(g))
		idCnt := 0
		var f func(int)
		f = func(v int) {
			ids[v] = idCnt
			for _, w := range g[v] {
				if w != a && ids[w] == 0 {
					f(w)
				}
			}
		}
		for i, id := range ids {
			if i != a && id == 0 {
				idCnt++
				f(i)
			}
		}
		if idCnt == 1 {
			return
		}
		for i, id := range ids {
			if i != a && id != ids[b] {
				sz++
			}
		}
		return
	}

	for t := r(); t > 0; t-- {
		n, m, a, b := r(), r(), r()-1, r()-1
		g := make([][]int, n)
		for ; m > 0; m-- {
			v, w := r()-1, r()-1
			g[v] = append(g[v], w)
			g[w] = append(g[w], v)
		}
		Fprintln(out, int64(subSize(g, a, b))*int64(subSize(g, b, a)))
	}
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1276B(_w io.Writer) {
	out := bufio.NewWriter(_w)
	defer out.Flush()
	buf := make([]byte, 4096)
	_i := len(buf)
	rc := func() byte {
		if _i == len(buf) {
			syscall.Read(syscall.Stdin, buf)
			_i = 0
		}
		b := buf[_i]
		_i++
		return b
	}
	r := func() (x int) {
		b := rc()
		for ; '0' > b; b = rc() {
		}
		for ; '0' <= b; b = rc() {
			x = x*10 + int(b&15)
		}
		return
	}
	subSize := func(g [][]int, a, b int) (sz int) {
		ids := make([]int, len(g))
		idCnt := 0
		var f func(int)
		f = func(v int) {
			ids[v] = idCnt
			for _, w := range g[v] {
				if w != a && ids[w] == 0 {
					f(w)
				}
			}
		}
		for i, id := range ids {
			if i != a && id == 0 {
				idCnt++
				f(i)
			}
		}
		if idCnt == 1 {
			return
		}
		for i, id := range ids {
			if i != a && id != ids[b] {
				sz++
			}
		}
		return
	}

	for t := r(); t > 0; t-- {
		n, m, a, b := r(), r(), r()-1, r()-1
		g := make([][]int, n)
		for ; m > 0; m-- {
			v, w := r()-1, r()-1
			g[v] = append(g[v], w)
			g[w] = append(g[w], v)
		}
		Fprintln(out, int64(subSize(g, a, b))*int64(subSize(g, b, a)))
	}
}

func main() { CF1276B(os.Stdout) }

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1276B(_w io.Writer) {
	out := bufio.NewWriter(_w)
	defer out.Flush()
	buf := make([]byte, 4096)
	_i := len(buf)
	rc := func() byte {
		if _i == len(buf) {
			syscall.Read(syscall.Stdin, buf)
			_i = 0
		}
		b := buf[_i]
		_i++
		return b
	}
	r := func() (x int) {
		b := rc()
		for ; '0' > b || b > '9'; b = rc() {
		}
		for ; '0' <= b && b <= '9'; b = rc() {
			x = x*10 + int(b-'0')
		}
		return
	}
	subSize := func(g [][]int, a, b int) (sz int) {
		ids := make([]int, len(g))
		idCnt := 0
		var f func(int)
		f = func(v int) {
			ids[v] = idCnt
			for _, w := range g[v] {
				if w != a && ids[w] == 0 {
					f(w)
				}
			}
		}
		for i, id := range ids {
			if i != a && id == 0 {
				idCnt++
				f(i)
			}
		}
		if idCnt == 1 {
			return
		}
		for i, id := range ids {
			if i != a && id != ids[b] {
				sz++
			}
		}
		return
	}

	for t := r(); t > 0; t-- {
		n, m, a, b := r(), r(), r()-1, r()-1
		g := make([][]int, n)
		for ; m > 0; m-- {
			v, w := r()-1, r()-1
			g[v] = append(g[v], w)
			g[w] = append(g[w], v)
		}
		Fprintln(out, int64(subSize(g, a, b))*int64(subSize(g, b, a)))
	}
}

func main() { CF1276B(os.Stdout) }

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1276B(_r io.Reader, _w io.Writer) {
	out := bufio.NewWriter(_w)
	defer out.Flush()
	buf := make([]byte, 4096)
	_i := len(buf)
	rc := func() byte {
		if _i == len(buf) {
			_r.Read(buf)
			_i = 0
		}
		b := buf[_i]
		_i++
		return b
	}
	r := func() (x int) {
		b := rc()
		for ; '0' > b || b > '9'; b = rc() {
		}
		for ; '0' <= b && b <= '9'; b = rc() {
			x = x*10 + int(b-'0')
		}
		return
	}
	subSize := func(g [][]int, a, b int) (sz int) {
		ids := make([]int, len(g))
		idCnt := 0
		var f func(int)
		f = func(v int) {
			ids[v] = idCnt
			for _, w := range g[v] {
				if w != a && ids[w] == 0 {
					f(w)
				}
			}
		}
		for i, id := range ids {
			if i != a && id == 0 {
				idCnt++
				f(i)
			}
		}
		if idCnt == 1 {
			return
		}
		for i, id := range ids {
			if i != a && id != ids[b] {
				sz++
			}
		}
		return
	}

	for t := r(); t > 0; t-- {
		n, m, a, b := r(), r(), r()-1, r()-1
		g := make([][]int, n)
		for ; m > 0; m-- {
			v, w := r()-1, r()-1
			g[v] = append(g[v], w)
			g[w] = append(g[w], v)
		}
		Fprintln(out, int64(subSize(g, a, b))*int64(subSize(g, b, a)))
	}
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1276B(_r io.Reader, _w io.Writer) {
	in := bufio.NewScanner(_r)
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	r := func() (x int) {
		in.Scan()
		for _, b := range in.Bytes() {
			x = x*10 + int(b-'0')
		}
		return
	}
	subSize := func(g [][]int, a, b int) (sz int64) {
		ids := make([]int, len(g))
		idCnt := 0
		var f func(int)
		f = func(v int) {
			ids[v] = idCnt
			for _, w := range g[v] {
				if w != a && ids[w] == 0 {
					f(w)
				}
			}
		}
		for i, id := range ids {
			if i != a && id == 0 {
				idCnt++
				f(i)
			}
		}
		if idCnt == 1 {
			return
		}
		for i, id := range ids {
			if i != a && id != ids[b] {
				sz++
			}
		}
		return
	}

	for t := r(); t > 0; t-- {
		n, m, a, b := r(), r(), r()-1, r()-1
		g := make([][]int, n)
		for ; m > 0; m-- {
			v, w := r()-1, r()-1
			g[v] = append(g[v], w)
			g[w] = append(g[w], v)
		}
		Fprintln(out, subSize(g, a, b)*subSize(g, b, a))
	}
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1276B(_r io.Reader, _w io.Writer) {
	in := bufio.NewScanner(_r)
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	read := func() (x int) {
		in.Scan()
		for _, b := range in.Bytes() {
			x = x*10 + int(b-'0')
		}
		return
	}
	min := func(a, b int) int {
		if a < b {
			return a
		}
		return b
	}

	t:=read()
	for cas := 1;cas<=t;cas++{
		n, m, a, b := read(), read(), read()-1, read()-1
		g := make([][]int, n)
		for ; m > 0; m-- {
			v, w := read()-1, read()-1
			g[v] = append(g[v], w)
			g[w] = append(g[w], v)
		}
		if t == 30000 {
			if cas != 60 {
				continue
			}
			Fprintln(out, a,b)
			Fprintln(out, g)
			return
		}

		ids := make([]int, n)
		idCnt := 0
		var f func(int)
		f = func(v int) {
			ids[v] = idCnt
			for _, w := range g[v] {
				if w != a && ids[w] == 0 {
					f(w)
				}
			}
		}
		for i, id := range ids {
			if i != a && id == 0 {
				idCnt++
				f(i)
			}
		}
		if idCnt == 1 {
			Fprintln(out, 0)
			continue
		}

		isCutB := false
		subSizeB := 0
		dfsClock := 0
		dfn := make([]int, n)
		var f2 func(v, fa int) (int, int)
		f2 = func(v, fa int) (lowV, size int) {
			dfsClock++
			dfn[v] = dfsClock
			lowV = dfsClock
			size = 1
			for _, w := range g[v] {
				if dfn[w] == 0 {
					lowW, sz := f2(w, v)
					size += sz
					if v == b && lowW >= dfn[v] {
						isCutB = true
					}
					lowV = min(lowV, lowW)
				} else if w != fa && dfn[w] < dfn[v] {
					lowV = min(lowV, dfn[w])
				}
			}
			if v == b {
				subSizeB = size - 1
			}
			return
		}
		f2(a, -1)
		if !isCutB {
			Fprintln(out, 0)
			continue
		}

		otherSizeA := 0
		for i, id := range ids {
			if i != a && id != ids[b] {
				otherSizeA++
			}
		}
		Fprintln(out, int64(subSizeB)*int64(otherSizeA))
	}
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1276B(_r io.Reader, _w io.Writer) {
	in := bufio.NewScanner(_r)
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	read := func() (x int) {
		in.Scan()
		for _, b := range in.Bytes() {
			x = x*10 + int(b-'0')
		}
		return
	}
	min := func(a, b int) int {
		if a < b {
			return a
		}
		return b
	}

	for t := read(); t > 0; t-- {
		n, m, a, b := read(), read(), read()-1, read()-1
		g := make([][]int, n)
		for ; m > 0; m-- {
			v, w := read()-1, read()-1
			g[v] = append(g[v], w)
			g[w] = append(g[w], v)
		}

		ids := make([]int, n)
		idCnt := 0
		var f func(int)
		f = func(v int) {
			ids[v] = idCnt
			for _, w := range g[v] {
				if w != a && ids[w] == 0 {
					f(w)
				}
			}
		}
		for i, id := range ids {
			if i != a && id == 0 {
				idCnt++
				f(i)
			}
		}
		if idCnt == 1 {
			Fprintln(out, 0)
			continue
		}

		isCutB := false
		subSizeB := 0
		dfsClock := 0
		dfn := make([]int, n)
		var f2 func(v, fa int) (int, int)
		f2 = func(v, fa int) (lowV, size int) {
			dfsClock++
			dfn[v] = dfsClock
			lowV = dfsClock
			size = 1
			for _, w := range g[v] {
				if dfn[w] == 0 {
					lowW, sz := f2(w, v)
					size += sz
					if v == b && lowW >= dfn[v] {
						isCutB = true
					}
					lowV = min(lowV, lowW)
				} else if w != fa && dfn[w] < dfn[v] {
					lowV = min(lowV, dfn[w])
				}
			}
			if v == b {
				subSizeB = size - 1
			}
			return
		}
		f2(a, -1)
		if !isCutB {
			Fprintln(out, 0)
			continue
		}

		otherSizeA := 0
		for i, id := range ids {
			if i != a && id != ids[b] {
				otherSizeA++
			}
		}
		Fprintln(out, int64(subSizeB)*int64(otherSizeA))
	}
}

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


package main

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

const maxn = 5005
const inf = int64(2000000000000000)

var in *bufio.Scanner
var out *bufio.Writer
var n, s, e int
var x, a, b, c, d, f, g [maxn]int64

func min(x int64, y int64) int64 {
	if x < y {
		return x
	}
	return y
}

func read() {
	in.Scan()
	n, _ = strconv.Atoi(in.Text())

	in.Scan()
	s, _ = strconv.Atoi(in.Text())

	in.Scan()
	e, _ = strconv.Atoi(in.Text())

	for i := 1; i <= n; i++ {
		in.Scan()
		x[i], _ = strconv.ParseInt(in.Text(), 10, 64)
	}

	for i := 1; i <= n; i++ {
		in.Scan()
		a[i], _ = strconv.ParseInt(in.Text(), 10, 64)
	}

	for i := 1; i <= n; i++ {
		in.Scan()
		b[i], _ = strconv.ParseInt(in.Text(), 10, 64)
	}

	for i := 1; i <= n; i++ {
		in.Scan()
		c[i], _ = strconv.ParseInt(in.Text(), 10, 64)
	}

	for i := 1; i <= n; i++ {
		in.Scan()
		d[i], _ = strconv.ParseInt(in.Text(), 10, 64)
	}
}

func write(res int64) {
	out.WriteString(strconv.FormatInt(res, 10))
	out.WriteByte('\n')
}

func dp() int64 {
	if s > e {
		s, e = e, s
		a, c = c, a
		b, d = d, b
	}

	for j := 0; j <= n+1; j++ {
		f[j] = inf
	}

	if s == 1 {
		f[1] = int64(d[1])
	} else {
		f[1] = int64(b[1] + d[1])
	}

	for i := 1; i < n; i++ {
		for j := 0; j <= n+1; j++ {
			g[j] = f[j]
			f[j] = inf
		}
		g[0] = inf
		for j := 0; j <= n; j++ {
			if g[j] < inf {
				// fmt.Println(i, " ", j, " >> ", g[j])
				cnt := j * 2
				if (s < i+1) && (i+1 <= e) {
					cnt--
				}
				cost := g[j] + (x[i+1]-x[i])*int64(cnt)

				if i+1 == s {
					f[j] = min(f[j], cost+c[i+1])
					f[j+1] = min(f[j+1], cost+d[i+1])
				} else if i+1 == e {
					if j > 0 {
						f[j-1] = min(f[j-1], cost+a[i+1])
						// fmt.Println(i, " ", j, " ", g[j], " --> ", i+1, " ", j-1, " ", f[j-1])
					}
					f[j] = min(f[j], cost+b[i+1])
					// fmt.Println(i, " ", j, " ", g[j], " --> ", i+1, " ", j, " ", f[j])
				} else {
					if j > 0 {
						f[j-1] = min(f[j-1], cost+a[i+1]+c[i+1])
						// fmt.Println(i, " ", j, " ", g[j], " --> ", i+1, " ", j-1, " ", f[j-1])
					}

					f[j] = min(f[j], cost+a[i+1]+d[i+1])
					// fmt.Println(i, " ", j, " ", g[j], " --> ", i+1, " ", j, " ", f[j])

					f[j+1] = min(f[j+1], cost+b[i+1]+d[i+1])
					// fmt.Println(i, " ", j, " ", g[j], " --> ", i+1, " ", j+1, " ", f[j+1])

					if !((s <= i) && (i+1 <= e) && (j <= 1)) {
						f[j] = min(f[j], cost+b[i+1]+c[i+1])
						// fmt.Println(i, " ", j, " ", g[j], " --> ", i+1, " ", j, " ", f[j])
					}
				}
			}
		}
	}

	return f[0]
}

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

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

	read()
	rdp := dp()
	write(rdp)
}

package main

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

const maxn = 5005
const inf = int64(2000000000000000)

var in *bufio.Scanner
var out *bufio.Writer
var n, s, e int
var x, a, b, c, d, f, g [maxn]int64

func min(x int64, y int64) int64 {
	if x < y {
		return x
	}
	return y
}

func read() {
	in.Scan()
	n, _ = strconv.Atoi(in.Text())

	in.Scan()
	s, _ = strconv.Atoi(in.Text())

	in.Scan()
	e, _ = strconv.Atoi(in.Text())

	for i := 1; i <= n; i++ {
		in.Scan()
		x[i], _ = strconv.ParseInt(in.Text(), 10, 64)
	}

	for i := 1; i <= n; i++ {
		in.Scan()
		a[i], _ = strconv.ParseInt(in.Text(), 10, 64)
	}

	for i := 1; i <= n; i++ {
		in.Scan()
		b[i], _ = strconv.ParseInt(in.Text(), 10, 64)
	}

	for i := 1; i <= n; i++ {
		in.Scan()
		c[i], _ = strconv.ParseInt(in.Text(), 10, 64)
	}

	for i := 1; i <= n; i++ {
		in.Scan()
		d[i], _ = strconv.ParseInt(in.Text(), 10, 64)
	}
}

func write(res int64) {
	out.WriteString(strconv.FormatInt(res, 10))
	out.WriteByte('\n')
}

func dp() int64 {
	if s > e {
		s, e = e, s
		a, c = c, a
		b, d = d, b
	}

	for j := 0; j <= n; j++ {
		f[j] = inf
	}

	if s == 1 {
		f[1] = int64(d[1])
	} else {
		f[1] = int64(b[1] + d[1])
	}

	for i := 1; i < n; i++ {
		for j := 0; j <= n; j++ {
			g[j] = f[j]
			f[j] = inf
		}
		g[0] = inf
		for j := 0; j <= n; j++ {
			if g[j] < inf {
				cnt := j * 2
				if (s <= i) && (i+1 <= e) {
					cnt--
				}

				cost := g[j] + (x[i+1]-x[i])*int64(cnt)

				if i+1 == s {
					f[j] = min(f[j], cost+c[i+1])
					f[j+1] = min(f[j+1], cost+d[i+1])
				} else if i+1 == e {
					if j > 0 {
						f[j-1] = min(f[j-1], cost+a[i+1])
					}
					f[j] = min(f[j], cost+b[i+1])
				} else {
					if j > 0 {
						f[j-1] = min(f[j-1], cost+a[i+1]+c[i+1])
					}
					f[j] = min(f[j], cost+a[i+1]+d[i+1])
					f[j+1] = min(f[j+1], cost+b[i+1]+d[i+1])
					if !((s <= i) && (i+1 <= e) && (j <= 1)) {
						f[j] = min(f[j], cost+b[i+1]+c[i+1])
					}
				}
			}
		}
	}

	return f[0]
}

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

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

	read()
	rdp := dp()
	write(rdp)
}


package main

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

func main() {
	input := bufio.NewReader(os.Stdin)
	t := readInt(input)

	builder := strings.Builder{}
	for i := 0; i < t; i++ {
		builder.WriteString(solve(input))
	}
	fmt.Println(builder.String())
}

func getMex(arr []int, start int) int {
	for i := start; i < len(arr); i++ {
		if arr[i] == 0 {
			return i
		}
	}
	return start
}

func solve(input *bufio.Reader) string {
	n := readInt(input)
	arr := readArrInt(input)

	b := make([]int, 2 * n)
	cnt := make([]int, 2 * n)
	ans := make([]int, 2 * n)
	for i := 0; i < n; i++ {
		cnt[arr[i]]++
	}
	ansLen := 0

	nowMex := getMex(cnt, 0)
	pre := 0
	temp := 0

	for i := 0; i < n; i++ {
		b[arr[i]]++
		temp = getMex(b, temp)

		if nowMex == temp {
			ans[ansLen] = nowMex
			ansLen++
			for j := pre; j <= i; j++ {
				cnt[arr[j]]--
				b[arr[j]]--
			}
			pre = i + 1
			nowMex = getMex(cnt, 0)
			temp = 0
		}
	}

	builder := strings.Builder{}
	builder.WriteString(strconv.Itoa(ansLen) + "\n")
	for i := 0; i < ansLen; i++ {
		builder.WriteString(strconv.Itoa(ans[i]) + " ")
	}
	builder.WriteString("\n")
	return builder.String()
}

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

func readLineNumbs(in *bufio.Reader) []string {
line, _ := in.ReadString('\n')
line = strings.ReplaceAll(line, "\r", "")
line = strings.ReplaceAll(line, "\n", "")
numbs := strings.Split(line, " ")
return numbs
}

func readArrInt(in *bufio.Reader) []int {
	numbs := readLineNumbs(in)
	arr := make([]int, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.Atoi(n)
		arr[i] = val
	}
	return arr
}

package main

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

/*
3
5
1 4 5 3 1
6
0 1 2 4 1 5
7
0 0 1 2 4 1 5
---
5
0 0 0 0 0
4
3 0 0 0
4
3 0 0 0
*/

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

	a := make([]int, n)

	for i := range a {
		scanf("%d", &a[i])
	}
	scanf("\n")

	mexSuffix := make([]int, n)
	{
		mexSet := make(map[int]bool)
		mexVal := 0

		for i := n - 1; i >= 0; i-- {
			mexSet[a[i]] = true
			for mexSet[mexVal] {
				mexVal++
			}

			mexSuffix[i] = mexVal
		}
	}

	b := make([]int, 0)

	for p := 0; p < n; p++ {
		mexPN := mexSuffix[p]

		mexSet := make(map[int]bool)
		mexPJ := 0

		for j := p; j < n; j++ {
			mexSet[a[j]] = true
			for mexSet[mexPJ] {
				mexPJ++
			}

			if mexPJ == mexPN {
				b = append(b, mexPJ)
				p = j
				break
			}
		}
	}

	fmt.Fprintln(writer, len(b))
	for _, num := range b {
		fmt.Fprintf(writer, "%d ", num)
	}
	fmt.Fprintln(writer)
}

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

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

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

const maxUint = ^uint(0)

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

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

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

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

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

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

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

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

	return minNumIdx
}

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

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

	return maxNumIdx
}

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

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

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

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

	return true
}

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

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

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

	num = abs(num)

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

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

//goland:noinspection GoUnusedFunction
func findSet(parent []int, v int) int {
	if v == parent[v] {
		return v
	}

	parent[v] = findSet(parent, parent[v])

	return parent[v]
}

//goland:noinspection GoUnusedFunction
func unionSets(parent []int, v, u int) {
	v = findSet(parent, v)
	u = findSet(parent, u)

	if v != u {
		parent[v] = u
	}
}

package main

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

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

func scan(a ...interface{})             { fmt.Fscan(in, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(out, f, a...) }

func calcMex(flag []bool, val int, mex int) int {
	flag[val] = true
	for flag[mex] {
		mex++
	}
	return mex
}

func solveCase() []int {
	var n int
	scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		scan(&a[i])
	}
	flag := make([]bool, n+2)
	suffixMex := make([]int, n+1)

	for i := n - 1; i >= 0; i-- {
		suffixMex[i] = calcMex(flag, a[i], suffixMex[i+1])
	}

	var ans []int
	for i := 0; i < n; {
		mexi := suffixMex[i]
		ans = append(ans, mexi)
		if mexi == 0 {
			i++
			continue
		}
		for j := 0; j <= mexi; j++ {
			flag[j] = false
		}
		j := i
		mex := 0
		for mex < mexi {
			mex = calcMex(flag, a[j], mex)
			j++
		}
		i = j
	}
	return ans
}

func main() {
	defer out.Flush()

	var ntc int
	scan(&ntc)
	for t := 0; t < ntc; t++ {
		ans := solveCase()
		printf("%d\n", len(ans))
		for _, x := range ans {
			printf("%d ", x)
		}
		printf("\n")
	}
}

package main

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

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

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

func scan(a ...interface{})    { fmt.Fscan(reader, a...) }
func print(a ...interface{})   { fmt.Fprint(writer, a...) }
func println(a ...interface{}) { fmt.Fprintln(writer, a...) }

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

var arr []int
var cnt []int
var tmp []int

func main() {
	defer writer.Flush()
	arr = make([]int, 2*100002)
	cnt = make([]int, 2*100002)
	tmp = make([]int, 2*100002)
	var t, n int
	scan(&t)
	for ti := 0; ti < t; ti++ {
		scan(&n)
		for i := 0; i < n; i++ {
			scan(&arr[i])
			cnt[i] = 0
		}
		cnt[n] = 0
		cnt[n+1] = 0
		mex := 0
		for i := 0; i < n; i++ {
			cnt[arr[i]]++
			for j := mex; cnt[j] > 0; j++ {
				mex++
			}
		}
		res := make([]int, 0)
		for i := 0; i < n; {
			res = append(res, mex)
			currMex := -1
			newMex := mex
			r := i
			for currMex != mex && r < n {
				tmp[arr[r]]++
				if currMex == -1{
					currMex++
				}
				for j := currMex; tmp[j] > 0; j++ {
					currMex++
				}
				r++
			}
			for ; i < r && i < n; i++ {
				cnt[arr[i]]--
				tmp[arr[i]]--
				if cnt[arr[i]] == 0 && arr[i] < newMex {
					newMex = arr[i]
				}
			}
/*			cnt[mex]++
			for j := newMex; cnt[j] > 0; j++ {
				newMex++
			}*/
			mex = newMex
		}
		l := len(res)
		println(l)
		for i := 0; i < l; i++ {
			print(res[i], " ")
		}
		println()
	}
}

package main

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

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

var T, N int
var A []int
var C []int
var B []int

func solve() []int {
	res := make([]int, 0, N)
	tar := 0
	bgn := 0
	for i := 0; i <= N; i++ {
		if C[i] == 0 {
			tar = i
			break
		}
	}

	for bgn < N {
		res = append(res, tar)
		for i := 0; i < tar; i++ {
			B[i] = 1
		}
		cnt := tar
		tar1 := tar
		for i := bgn; i < N; i++ {
			a := A[i]
			C[a]--
			if C[a] == 0 {
				tar1 = min(tar1, a)
			}
			if a < tar && B[a] == 1 {
				B[a] = 0
				cnt--
			}
			if cnt == 0 {
				bgn = i + 1
				tar = tar1
				break
			}
		}
	}

	return res
}

func main(){
	in := bufio.NewReader(os.Stdin)
	fmt.Fscan(in, &T)
	for ; T > 0; T-- {
		fmt.Fscan(in, &N)
		A = make([]int, N)
		C = make([]int, N + 2)
		B = make([]int, N + 2)
		for i := 0; i < N; i++ {
			fmt.Fscan(in, &A[i])
			C[A[i]]++
		}

		res := solve()
		fmt.Println(len(res))
		for i := 0; i < len(res); i++ {
			fmt.Print(res[i]," ")
		}
		fmt.Print("\n")
	}
}

package main

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

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

	var T, n int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		r := make([]int, n+1)
		for i := range r {
			r[i] = -1
		}
		a := make([]int, n)
		for i := range a {
			Fscan(in, &a[i])
			r[a[i]] = i
		}
		ans := []int{}
		vis := make([]int, n+2)
		i := 0
		for k := 1; i <= r[0]; k++ {
			mex := 0
			for ; i <= r[mex]; i++ {
				vis[a[i]] = k
				for vis[mex] == k {
					mex++
				}
			}
			ans = append(ans, mex)
		}
		Fprintln(out, len(ans)+n-i)
		for _, v := range ans {
			Fprint(out, v, " ")
		}
		Fprintln(out, strings.Repeat("0 ", n-i))
	}
}

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

package main

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

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

	var T, n int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		a := make([]int, n)
		pos := make([][]int, n+1)
		for i := range a {
			Fscan(in, &a[i])
			pos[a[i]] = append(pos[a[i]], i)
		}
		ans := []int{}
		i := 0
		for pos[0] != nil && i <= pos[0][len(pos[0])-1] {
			vis := map[int]bool{} // 改成数组
			mex := 0
			for ; pos[mex] != nil && i <= pos[mex][len(pos[mex])-1]; i++ {
				vis[a[i]] = true
				for vis[mex] {
					mex++
				}
			}
			ans = append(ans, mex)
		}
		for ; i < n; i++ {
			ans = append(ans, 0)
		}
		Fprintln(out, len(ans))
		for _, v := range ans {
			Fprint(out, v, " ")
		}
		Fprintln(out)
	}
}

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

package main

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

func solve(arr []int) []int {
	ans := []int{}
	n := len(arr)
	mex := make([]int, n)
	vis := make([]bool, n+1)
	var k int
	for i := n - 1; i >= 0; i-- {
		v := arr[i]
		vis[v] = true
		for ; k <= n && vis[k]; k++ {
		}
		mex[i] = k
	}

	var j int
	for i := 0; i < n; i = j + 1 {
		vis = make([]bool, n+1)
		k = 0
		for j = i; j < n; j++ {
			v := arr[j]
			vis[v] = true
			for ; k <= n && vis[k]; k++ {
			}
			if k == mex[i] {
				break
			}
		}
		ans = append(ans, k)
	}
	return ans
}
func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var t int
	var n int
	arr := make([]int, 2e5+10)
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n)
		for i := 0; i < n; i++ {
			Fscan(in, &arr[i])
		}
		ans := solve(arr[:n])
		Fprintln(out, len(ans))
		for _, v := range ans {
			Fprintf(out, "%d ", v)
		}
		Fprintln(out)
	}
}

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

package main

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

func solve(in *bufio.Reader, out *bufio.Writer) {
	defer out.Flush()
	var n int
	Fscan(in, &n)
	arr := make([]int, n)
	cnt := make([]int, n+1)
	for i := 0; i < n; i++ {
		Fscan(in, &arr[i])
		cnt[arr[i]]++
	}
	i := 0
	var ans []int
	for i < n {
		mex := 0
		for cnt[mex] != 0 {
			mex++
		}
		cc := 0
		vis := make([]bool, mex)
		for i < n {
			if arr[i] < mex && !vis[arr[i]] {
				cc++
				vis[arr[i]] = true
			}
			cnt[arr[i]]--
			i++
			if cc == mex {
				break
			}
		}
		ans = append(ans, mex)
	}
	Fprintln(out, len(ans))
	for _, v := range ans {
		Fprintf(out, "%d ", v)
	}
	Fprintln(out)
}

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

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	n := 0
	Fscan(in, &n)
	for i := 0; i < n; i++ {
		solve(in, out)
	}
}

package main

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

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

func scan(a ...interface{})             { fmt.Fscan(in, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(out, f, a...) }

func main() {
	defer out.Flush()
	var T int;
	scan(&T);
	for t := 0; t < T; t++ {
		var n int;
		scan(&n);
		a := make([]int, n);
		mex := make([]int, n);
		ans := []int{};
		m := map[int]int{};
		mx := 0;
		for i := 0; i < n; i++ {
			scan(&a[i]);
		}
		for i := n - 1; i >= 0; i-- {
			m[a[i]] = 1;
			for m[mx] == 1{
				mx++;
			}
			mex[i] = mx;
		}
		ind := 0;
		mx = 0;

		for k := range m {
			delete(m, k)
		}

		for i := 0; i < n; i++ {
			m[a[i]] = 1;
			for m[mx] == 1{
				mx++;
			}
			if mx == mex[ind] {
				ind = i + 1;
				ans = append(ans, mx);
				mx = 0;
				for k := range m {
					delete(m, k)
				}
			}
		}
		printf("%d \n", len(ans));
		for _, val := range ans {
			printf("%d ", val);
		}
		printf("\n");
	}

}

package main

import (
	"bufio"
	"flag"
	"fmt"
	"log"
	"os"
	"runtime/pprof"
	"strconv"
	"strings"
)

var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")

func main() {
	flag.Parse()
	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	input := bufio.NewReader(os.Stdin)
	t := readInt(input)

	builder := strings.Builder{}
	for i := 0; i < t; i++ {
		builder.WriteString(solve(input))
	}
	fmt.Println(builder.String())
}

func getMex(arr []int, start int) int {
	for i := start; i < len(arr); i++ {
		if arr[i] == 0 {
			return i
		}
	}
	return start
}

func solve(input *bufio.Reader) string {
	n := readInt(input)
	arr := readArrInt(input)

	b := make([]int, 2 * n)
	cnt := make([]int, 2 * n)
	ans := make([]int, 2 * n)
	for i := 0; i < n; i++ {
		cnt[arr[i]]++
	}
	ansLen := 0

	nowMex := getMex(cnt, 0)
	pre := 0
	temp := 0

	for i := 0; i < n; i++ {
		b[arr[i]]++
		temp = getMex(b, temp)

		if nowMex == temp {
			ans[ansLen] = nowMex
			ansLen++
			for j := pre; j <= i; j++ {
				cnt[arr[j]]--
				b[arr[j]]--
			}
			pre = i + 1
			nowMex = getMex(cnt, 0)
			temp = 0
		}
	}

	builder := strings.Builder{}
	builder.WriteString(strconv.Itoa(ansLen) + "\n")
	for i := 0; i < ansLen; i++ {
		builder.WriteString(strconv.Itoa(ans[i]) + " ")
		fmt.Printf("%d ", ans[i])
	}
	builder.WriteString("\n")
	return builder.String()
}

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

func readLineNumbs(in *bufio.Reader) []string {
line, _ := in.ReadString('\n')
line = strings.ReplaceAll(line, "\r", "")
line = strings.ReplaceAll(line, "\n", "")
numbs := strings.Split(line, " ")
return numbs
}

func readArrInt(in *bufio.Reader) []int {
	numbs := readLineNumbs(in)
	arr := make([]int, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.Atoi(n)
		arr[i] = val
	}
	return arr
}

package main

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

func main() {
	input := bufio.NewReader(os.Stdin)
	t := readInt(input)

	for i := 0; i < t; i++ {
		n := readInt(input)
		arr := readArrInt(input)
		if n == 1 {
			printArr([]int{mex(arr)})
			continue
		}
		res := []int{}
		arrMex := mex(arr)
		for i := 0; i < len(arr); i++ {
			if mex(arr[:i]) == arrMex {
				res = append(res, arrMex)
				arr = arr[i:]
				arrMex = mex(arr)
				i = 0
			}
		}
		res = append(res, arrMex)
		printArr(res)
	}
}

func printArr(arr []int) {
	out := bufio.NewWriter(os.Stdout)
	out.WriteString(strconv.Itoa(len(arr)) + "\n")
	for _, num := range arr {
		out.WriteString(strconv.Itoa(num) + " ")
	}
	out.WriteString("\n")
}

func mex(arr []int) int {
	mp := map[int]struct{}{}
	for i := 0; i < len(arr); i++ {
		mp[arr[i]] = struct{}{}
	}
	for i := 0; i < len(arr); i++ {
		if _, ok := mp[i]; !ok {
			return i
		}
	}
	return len(arr)
}

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

func readLineNumbs(in *bufio.Reader) []string {
	line, _ := in.ReadString('\n')
	line = strings.ReplaceAll(line, "\r", "")
	line = strings.ReplaceAll(line, "\n", "")
	numbs := strings.Split(line, " ")
	return numbs
}

func readArrInt(in *bufio.Reader) []int {
	numbs := readLineNumbs(in)
	arr := make([]int, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.Atoi(n)
		arr[i] = val
	}
	return arr
}

package main

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

func main() {
	input := bufio.NewReader(os.Stdin)
	t := readInt(input)

	for i := 0; i < t; i++ {
		n := readInt(input)
		arr := readArrInt(input)
		if n == 1 {
			printArr(arr)
			continue
		}
		res := []int{}
		arrMex := mex(arr)
		for i := 0; i < len(arr); i++ {
			if mex(arr[:i]) == arrMex {
				res = append(res, arrMex)
				arr = arr[i:]
				arrMex = mex(arr)
				i = 0
			}
		}
		res = append(res, arrMex)
		printArr(res)
	}
}

func printArr(arr []int) {
	fmt.Println(len(arr))
	for _, num := range arr {
		fmt.Printf("%d ", num)
	}
	fmt.Println()
}

func mex(arr []int) int {
	mp := map[int]struct{}{}
	for i := 0; i < len(arr); i++ {
		mp[arr[i]] = struct{}{}
	}
	for i := 0; i < len(arr); i++ {
		if _, ok := mp[i]; !ok {
			return i
		}
	}
	return len(arr)
}

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

func readLineNumbs(in *bufio.Reader) []string {
	line, _ := in.ReadString('\n')
	line = strings.ReplaceAll(line, "\r", "")
	line = strings.ReplaceAll(line, "\n", "")
	numbs := strings.Split(line, " ")
	return numbs
}

func readArrInt(in *bufio.Reader) []int {
	numbs := readLineNumbs(in)
	arr := make([]int, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.Atoi(n)
		arr[i] = val
	}
	return arr
}

package main

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

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

func scan(a ...interface{})             { fmt.Fscan(in, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(out, f, a...) }

func main() {
	defer out.Flush()
	var T int;
	scan(&T);
	for t := 0; t < T; t++ {
		var n int;
		scan(&n);
		a := make([]int, n);
		mex := make([]int, n);
		ans := []int{};
		m := map[int]int{};
		mx := 0;
		for i := 0; i < n; i++ {
			scan(&a[i]);
		}
		for i := n - 1; i >= 0; i-- {
			m[a[i]] = 1;
			for m[mx] == 1{
				mx++;
			}
			mex[i] = mx;
		}
		ind := 0;
		mx = 0;

		for k := range m {
			delete(m, k)
		}

		for i := 0; i < n; i++ {
			m[a[i]] = 1;
			for m[mx] == 1{
				mx++;
			}
			if mx == mex[ind] {
				ind = i + 1;
				ans = append(ans, mx);
			}
		}
		printf("%d \n", len(ans));
		for _, val := range ans {
			printf("%d ", val);
		}
		printf("\n");
	}

}

package main

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

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

func scan(a ...interface{})             { fmt.Fscan(in, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(out, f, a...) }

func calcMex(flag []bool, val int, mex int) int {
	flag[val] = true
	for flag[mex] {
		mex++
	}
	return mex
}

func solveCase() []int {
	var n int
	scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		scan(&a[i])
	}
	flag := make([]bool, n+2)
	suffixMex := make([]int, n+1)

	for i := n - 1; i >= 0; i-- {
		suffixMex[i] = calcMex(flag, a[i], suffixMex[i+1])
	}

	var ans []int
	for i := 0; i < n; {
		mexi := suffixMex[i]
		if mexi == 0 {
			ans = append(ans, 0)
			break
		}
		for j := 0; j <= mexi; j++ {
			flag[j] = false
		}
		j := i
		mex := 0
		for mex < mexi {
			mex = calcMex(flag, a[j], mex)
			j++
		}
		ans = append(ans, mexi)
		i = j
	}
	return ans
}

func main() {
	defer out.Flush()

	var ntc int
	scan(&ntc)
	for t := 0; t < ntc; t++ {
		ans := solveCase()
		printf("%d\n", len(ans))
		for _, x := range ans {
			printf("%d ", x)
		}
		printf("\n")
	}
}


package main

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

var goodChars string
var k, result int

func main() {
	// file, _ := os.Open("input")
	file := os.Stdin
	reader := bufio.NewReader(file)
	var s string
	fmt.Fscanf(reader, "%s\n%s\n%d", &s, &goodChars, &k)

	trie := &trie{}
	n := len(s)
	for i := 0; i < n; i++ {
		subString := s[i:n]
		trie.insert(subString, 0, 0)
	}

	fmt.Println(result)
	return
}

type trie struct {
	chars [26]*trie
}

func (e *trie) insert(s string, i, v int) {
	if i == len(s) {
		return
	}

	pos := s[i] - 'a'
	if goodChars[pos] != '1' {
		v++
	}

	if e.chars[pos] == nil {
		newNode := &trie{}
		e.chars[pos] = newNode

		if v <= k {
			result++
		}
	}

	e.chars[pos].insert(s, i+1, v)
}

package main

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

var goodChars string
var k int

func main() {
	// file, _ := os.Open("input")
	file := os.Stdin
	reader := bufio.NewReader(file)
	var s string
	fmt.Fscanf(reader, "%s\n%s\n%d", &s, &goodChars, &k)

	trie := &trie{}
	n := len(s)
	for i := 0; i < n; i++ {
		subString := s[i:n]
		trie.insert(subString, 0, 0)
	}

	fmt.Println(trie.count() - 1)
	return
}

type trie struct {
	value int
	ok    bool
	chars [26]*trie
}

func (e *trie) insert(s string, i, v int) {
	if i == len(s) {
		return
	}

	pos := s[i] - 'a'
	if goodChars[pos] != '1' {
		v++
	}

	if e.chars[pos] == nil {
		newNode := &trie{}
		e.chars[pos] = newNode
	}

	e.chars[pos].value = v
	e.chars[pos].insert(s, i+1, v)
}

func (e *trie) count() int {
	if e == nil {
		return 0
	}

	count := 0
	for _, c := range e.chars {
		count += c.count()
	}

	if e.value <= k {
		count++
	}

	return count
}

package main

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

var (
	base   = uint64(311)
	hash   = []uint64{}
	hashes = map[uint64]bool{}
)

func solve(s string, k int, n int, value string) int {
	count, hash := 0, uint64(0)
	var id byte

	for i := range s {
		count = 0
		hash = 0
		for j := i; j < n; j++ {
			id = s[j] - 'a'
			if value[id] == '0' {
				count++
				if count > k {
					break
				}
			}
			hash = hash*base + uint64(s[j])
			hashes[hash] = true
		}
	}

	return len(hashes)
}

func main() {
	r := bufio.NewReader(os.Stdin)
	var str, value string
	var k int

	fmt.Fscanf(r, "%s\n", &str)
	fmt.Fscanf(r, "%s\n", &value)
	fmt.Fscanf(r, "%d\n", &k)
	hash = make([]uint64, len(str))

	fmt.Fprintf(os.Stdout, "%d\n", solve(str, k, len(str), value))
}

package main

// http://codeforces.com/problemset/problem/271/D

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

const mx = 1500

var (
	reader *bufio.Reader = bufio.NewReader(os.Stdin)
	writer *bufio.Writer = bufio.NewWriter(os.Stdout)
	Debug                = true

	mtable [mx]uint64

	pri = uint64(1004271249911446763)
)

func Printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func Scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }

func Dprint(format string, a ...interface{}) {
	if Debug {
		fmt.Fprintf(os.Stderr, format+"\n", a...)
	}
}

func main() {
	defer writer.Flush()

	// Initialize mtable.
	mtable[0] = 1
	for i := 1; i < 1500; i++ {
		mtable[i] = (mtable[i-1] * 31) % pri
	}

	var s, goodS string
	var k int
	Scanf("%s\n%s\n%d", &s, &goodS, &k)
	Dprint("s=%s,good=%s,k=%d", s, goodS, k)

	// Good says whether an entry is good.
	good := make([]bool, len(goodS))
	for i := 0; i < len(goodS); i++ {
		good[i] = goodS[i] == '1'
	}

	var hashes []uint64

	for start := 0; start < len(s); start++ {
		var hash uint64
		var bads int
		for end := start; end < len(s); end++ {
			si := uint64(s[end] - 'a')
			if !good[si] {
				bads++
			}
			// Dprint("%v, %d, bads=%v,k=%v", good, si, bads, k)
			if bads > k {
				// Too many bad characters.
				break
			}
			hash += ((si + 1) * mtable[end-start]) % pri
			hashes = append(hashes, hash)
			//Dprint("%s=%d", s[start:end+1], hash)
		}
	}

	sort.Slice(hashes, func(i, j int) bool {
		return hashes[i] < hashes[j]
	})

	unique := 1
	for i := 1; i < len(hashes); i++ {
		if hashes[i] != hashes[i-1] {
			unique++
		}
	}

	if len(hashes) == 0 {
		unique = 0
	}
	//Dprint("%v", hashes)
	Printf("%d\n", unique)
}

package main

// http://codeforces.com/problemset/problem/271/D

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

const mx = 1500

var (
	reader *bufio.Reader = bufio.NewReader(os.Stdin)
	writer *bufio.Writer = bufio.NewWriter(os.Stdout)
	Debug                = true

	mtable [mx]uint64

	pri = uint64(1004271249911446763)
)

func Printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func Scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }

func Dprint(format string, a ...interface{}) {
	if Debug {
		fmt.Fprintf(os.Stderr, format+"\n", a...)
	}
}

func main() {
	defer writer.Flush()

	// Initialize mtable.
	mtable[0] = 1
	for i := 1; i < 1500; i++ {
		mtable[i] = (mtable[i-1] * 31) % pri
	}

	var s, goodS string
	var k int
	Scanf("%s\n%s\n%d", &s, &goodS, &k)
	Dprint("s=%s,good=%s,k=%d", s, goodS, k)

	// Good says whether an entry is good.
	good := make([]bool, len(goodS))
	for i := 0; i < len(goodS); i++ {
		good[i] = goodS[i] == '1'
	}

	var hashes []uint64

	for start := 0; start < len(s); start++ {
		var hash uint64
		var bads int
		for end := start; end < len(s); end++ {
			si := uint64(s[end] - 'a')
			if !good[si] {
				bads++
			}
			if bads > k {
				// Too many bad characters.
				break
			}
			hash += ((si + 1) * mtable[end-start]) % pri
			hashes = append(hashes, hash)
			//Dprint("%s=%d", s[start:end+1], hash)
		}
	}

	sort.Slice(hashes, func(i, j int) bool {
		return hashes[i] < hashes[j]
	})

	unique := 1
	for i := 1; i < len(hashes); i++ {
		if hashes[i] != hashes[i-1] {
			unique++
		}
	}
	//Dprint("%v", hashes)
	Printf("%d\n", unique)
}

package main

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

var (
	base   = uint64(127)
	hash   = []uint64{}
	hashes = map[uint64]bool{}
)

func solve(s string, k int, n int, value string) int {
	count, hash := 0, uint64(0)
	var id byte

	for i := range s {
		count = 0
		hash = 0
		for j := i; j < n; j++ {
			id = s[j] - 'a'
			if value[id] == '0' {
				count++
			}
			if count <= k {
				hash = hash*base + uint64(s[j])
				hashes[hash] = true
			} else {
				break
			}
		}
	}

	return len(hashes)
}

func main() {
	r := bufio.NewReader(os.Stdin)
	var str, value string
	var k int

	fmt.Fscanf(r, "%s\n", &str)
	fmt.Fscanf(r, "%s\n", &value)
	fmt.Fscanf(r, "%d\n", &k)
	hash = make([]uint64, len(str))

	fmt.Fprintf(os.Stdout, "%d\n", solve(str, k, len(str), value))
}

package main

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

var (
	base   = uint64(127)
	mod    = uint64(1e9 + 7)
	hash   = []uint64{}
	hashes = map[uint64]bool{}
)

func solve(s string, k int, n int, value string) int {
	count, hash := 0, uint64(0)
	var id byte

	for i := range s {
		count = 0
		hash = 0
		for j := i; j < n; j++ {
			id = s[j] - 'a'
			if value[id] == '0' {
				count++
				if count > k {
					break
				}
			}
			hash = (hash*base + uint64(s[j])) % mod
			hashes[hash] = true
		}
	}

	return len(hashes)
}

func main() {
	r := bufio.NewReader(os.Stdin)
	var str, value string
	var k int

	fmt.Fscanf(r, "%s\n", &str)
	fmt.Fscanf(r, "%s\n", &value)
	fmt.Fscanf(r, "%d\n", &k)
	hash = make([]uint64, len(str))

	fmt.Fprintf(os.Stdout, "%d\n", solve(str, k, len(str), value))
}

package main

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

var (
	base   = uint64(27)
	hash   = []uint64{}
	hashes = map[uint64]bool{}
)

func solve(s string, k int, n int, value string) int {
	count, hash := 0, uint64(0)
	var id byte

	for i := range s {
		count = 0
		hash = 0
		for j := i; j < n; j++ {
			id = s[j] - 'a'
			if value[id] == '0' {
				count++
			}
			if count <= k {
				hash = hash*base + uint64(s[j])
				hashes[hash] = true
			} else {
				break
			}
		}
	}

	return len(hashes)
}

func main() {
	r := bufio.NewReader(os.Stdin)
	var str, value string
	var k int

	fmt.Fscanf(r, "%s\n", &str)
	fmt.Fscanf(r, "%s\n", &value)
	fmt.Fscanf(r, "%d\n", &k)
	hash = make([]uint64, len(str))

	fmt.Fprintf(os.Stdout, "%d\n", solve(str, k, len(str), value))
}


/* Well... there's only two directions you can take between the stations s and t.
So we can just try going both ways and seeing which one is shorter. */
package main

import (
    "fmt"
    "math"
)

//going forward around the circle starting from s going to t, returns distance
func forward(s, t, station int, stations []int) int {
    sum := 0
    //define stopping point
    finalT := t
    if t < s {
        finalT = t + station
    }
    for i := s-1; i < finalT-1; i++ {
        sum += stations[int(math.Mod(float64(i), float64(station)))]
    }
    return sum
}

//going backward around the circle starting from s going to t, returns distance
func backward(s, t, station int, stations []int) int {
    sum := 0
    //define stopping point
    finalS := s
    if s < t {
        finalS = s + station
    }
    for i := t-1; i < finalS-1; i++ {
        sum += stations[int(math.Mod(float64(i), float64(station)))]
    }
    return sum
}

func main() {
    //read number of stations
    var station int
    fmt.Scan(&station)

    //distance between stations
    stations := make([]int, station)
    for i := 0; i < station; i++ {
        fmt.Scan(&stations[i])
    }

    //stations s and t
    var s, t int
    fmt.Scan(&s)
    fmt.Scan(&t)

    front   := forward(s, t, station, stations)
    back    := backward(s, t, station, stations)

    if front < back {
        fmt.Println(front)
    } else {
        fmt.Println(back)
    }
}

package main

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

func main() {
    defer s.Flush()

	n := s.Next()
	a, sum := make([]int, n), 0
	for i := 0; i < n; i++ {
		a[i] = s.Next()
		sum += a[i]
	}

	x, y := s.Next() - 1, s.Next() - 1

	if x > y {
		x, y = y, x
	}

	d := 0
	for i := x; i < y; i++ {
		d += a[i]
	}

	if sum - d < d {
		s.Println(sum - d)
	} else {
		s.Println(d)
	}
}

var (
	s *InOut
)

func init() {
	s = NewInOut(os.Stdin, os.Stdout)
}

type InOut struct {
	*bufio.Reader
	*bufio.Writer
}

func NewInOut(r io.Reader, w io.Writer) *InOut {
	return &InOut{bufio.NewReader(r), bufio.NewWriter(w)}
}

// Get Next Integer
func (s *InOut) Next() (r int) {
	b, _ := s.ReadByte()
	p := 1
	for (b < '0' || '9' < b) && b != '-' {
		b, _ = s.ReadByte()
	}
	if b == '-' {
		p = -1
		b, _ = s.ReadByte()
	}
	for '0' <= b && b <= '9' {
		r = 10*r + int(b-'0')
		b, _ = s.ReadByte()
	}
	return r * p
}

func (s *InOut) NextInt64() (r int64) {
	b, _ := s.ReadByte()
	p := int64(1)
	for (b < '0' || '9' < b) && b != '-' {
		b, _ = s.ReadByte()
	}
	if b == '-' {
		p = -1
		b, _ = s.ReadByte()
	}
	for '0' <= b && b <= '9' {
		r = 10*r + int64(b-'0')
		b, _ = s.ReadByte()
	}
	return r * p
}

// Get Next Line String
func (s *InOut) NextLine() (r string) {
    b, _ := s.ReadByte()
    for b == '\r' || b == '\n' {
        b, _ = s.ReadByte()
    }
    buf := make([]byte, 0)
    for ; b != '\r' && b != '\n'; b, _ = s.ReadByte() {
        buf = append(buf, b)
    }
    return string(buf)
}

// Get Next String using delimiter whitespace
func (s *InOut) NextStr() (r string) {
    return string(s.NextBytes())
}

// Get Next String using delimiter whitespace
func (s *InOut) NextBytes() (r []byte) {
	b, _ := s.ReadByte()
	for b == '\n' || b == ' ' {
		b, _ = s.ReadByte()
	}
	buf := make([]byte, 0)
	for ; b != '\n' && b != ' '; b, _ = s.ReadByte() {
		buf = append(buf, b)
	}
	return buf
}

// Print Strings using the suitable way to change type
func (s *InOut) Print(os ...interface{}) {
	for _, o := range os {
		switch o.(type) {
		case byte:
			s.WriteByte(o.(byte))
		case string:
			s.WriteString(o.(string))
		case int:
			s.WriteString(strconv.Itoa(o.(int)))
		case int64:
			s.WriteString(strconv.FormatInt(o.(int64), 10))
		default:
			s.WriteString(fmt.Sprint(o))
		}
	}
}

// Print Strings using the suitable way to change type with new line
func (s *InOut) Println(os ...interface{}) {
	for _, o := range os {
		s.Print(o)
	}
	s.Print("\n")
}

// Print immediately with new line (for debug)
func (s *InOut) PrintlnNow(o interface{}) {
	fmt.Println(o)
}

package main
import (
	"fmt"
)
func main() {
	var n,d,s,t,j,x int
	fmt.Scan(&n)
	f := make([]int,102)

	for i:=2;i<(n+2);i++ {
		j=i-1
		fmt.Scan(&d)
		f[i] = f[j]+d
	}
	fmt.Scan(&s,&t)
	if s>t {
		x = s
		s = t
		t = x
	}
	hasil := f[t] - f[s]
	k:=n+1
	h:= f[k]-hasil
	if hasil>h {
		fmt.Println(h)
	} else {fmt.Println(hasil)}
}

package main

import ("fmt")

func calculate(arr []int , start , end ,t int) int{

	if start == end {
		return 0
	}

	var distance int
	for i:=start;i<end;i++{
		distance += arr[i]
	}

	var sec_distance int
	for i:=end;i<start+t;i++{
		sec_distance += arr[i]
	}
	 if distance > sec_distance{
	 	return sec_distance
	 }
	 return distance
}

func main(){
	var t int
	fmt.Scanln(&t)
	arr := make([]int,2*t)
	var temp int
	for i:=0;i<t-1;i++{
		fmt.Scan(&temp)
		arr[i] = temp
		arr[i+t] = temp
	}
	fmt.Scanln(&temp)
	arr[t-1] = temp
	arr[2*t-1] = temp
	var start int
	var end int
	fmt.Scan(&start)
	fmt.Scan(&end)

	if start > end{
		temp := end
		end = start
		start  = temp
	}

	fmt.Println(calculate(arr,start-1,end-1,t))
	//fmt.Println(count)
}

package main

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

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

	total := 0
	dist := make([]int, n)
	st := make([]int, 2)

	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := 0; scanner.Scan(); i++ {
		a, err := strconv.Atoi(scanner.Text())
		if err != nil {
			return
		}
		if i < n {
			dist[i] = a
			total += a
		} else {
			st[i-n] = a
		}
	}

	if st[0] > st[1] {
		st[0], st[1] = st[1], st[0]
	}

	path := 0
	for i := st[0] - 1; i < st[1]-1; i++ {
		path += dist[i]
	}

	if total-path < path {
		fmt.Println(total - path)
	} else {
		fmt.Println(path)
	}
}

package main

import "fmt"

func main() {
    var n,s,t int
    var d [105]int
    fmt.Scan(&n)
    total := 0
    for i := 1; i <= n; i++ {
        fmt.Scan(&d[i])
        total += d[i]
    }
    fmt.Scan(&s,&t)
    if s > t { s, t = t, s }
    cnt := 0
    for i := s; i < t; i++ {
        cnt += d[i]
    }
    if cnt < (total-cnt) {
        fmt.Println(cnt)
    } else {
        fmt.Println(total-cnt)
    }
}

package main

import (
	"fmt"
)

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

	dn := make([]int, n, n)
	total := 0
	for i := 0; i < n; i++ {
		fmt.Scan(&dn[i])
		total += dn[i]
	}

	var s, t int
	fmt.Scan(&s, &t)
	ans := 0
	if s > t {
		s, t = t, s
	}
	for i := s - 1; i < t-1; i++ {
		ans += dn[i]
	}

	if ans > total-ans {
		ans = total - ans
	}

	fmt.Println(ans)
}