During the programming classes Vasya was assigned a difficult problem. However, he doesn't know how to code and was unable to find the solution in the Internet, so he asks you to help.You are given a sequence $$$a$$$, consisting of $$$n$$$ distinct integers, that is used to construct the binary search tree. Below is the formal description of the construction process.  First element $$$a_1$$$ becomes the root of the tree.  Elements $$$a_2, a_3, \ldots, a_n$$$ are added one by one. To add element $$$a_i$$$ one needs to traverse the tree starting from the root and using the following rules:   The pointer to the current node is set to the root.  If $$$a_i$$$ is greater than the value in the current node, then its right child becomes the current node. Otherwise, the left child of the current node becomes the new current node.  If at some point there is no required child, the new node is created, it is assigned value $$$a_i$$$ and becomes the corresponding child of the current node.

The first line of the input contains a single integer $$$n$$$ ($$$2 \leq n \leq 100\,000$$$) — the length of the sequence $$$a$$$. The second line contains $$$n$$$ distinct integers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) — the sequence $$$a$$$ itself.

Output $$$n - 1$$$ integers. For all $$$i > 1$$$ print the value written in the node that is the parent of the node with value $$$a_i$$$ in it.

package main

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

func main() {
	n := getInt()
	a1 := getInt()
	t := New(.65)
	t.Ins(Key{0, a1, a1})
	t.Ins(Key{a1, 1000000001, a1})
	for i := 1; i < n; i++ {
		ai := getInt()
		p := t.Get(ai)
		fmt.Println(p.idx)
		t.Del(p)
		t.Ins(Key{p.beg, ai, ai})
		t.Ins(Key{ai, p.end, ai})
	}
}

var ErrMovePastEnd = errors.New("tree: iterator moved past to end")

type Key struct {
	beg int // key
	end int
	idx int
}

// cmp should compare two keys
// first return value should indicate if both keys are equal
// second should note into which child we should descend in order to look
// for key k form this node
func (n node) cmp(k Key) (bool, int) {
	idx := 0
	if n.key.beg < k.beg {
		idx = 1
	}
	return k == n.key, idx
}

type node struct {
	key Key
	c   [2]*node
}

type Tree struct {
	root    *node
	alfa    float64
	size    int
	maxsize int
}

type Iter struct {
	stack []*node
}

func New(alfa float64) *Tree {
	return &Tree{alfa: alfa}
}

func (t *Tree) Ins(k Key) bool {
	t.size++
	if t.root == nil {
		t.root = &node{key: k}
		return true
	}

	var path []*node
	for x := t.root; x != nil; {
		eq, i := x.cmp(k)
		if eq {
			t.size--
			return false
		}

		path = append(path, x)
		x = x.c[i]
	}

	x := path[len(path)-1]
	_, j := x.cmp(k)
	x.c[j] = &node{key: k}
	if t.size > t.maxsize {
		t.maxsize = t.size
	}

	if pow(1/t.alfa, len(path)) <= float64(t.size) {
		return true
	}

	var scapegoat int
	ssize := t.size
	for i, childsize := len(path)-1, 1; i > 0; i-- {
		x = path[i]
		ochildsize := subsize(x.c[j^1])
		currsize := childsize + ochildsize + 1
		if math.Max(float64(childsize), float64(ochildsize)) > float64(currsize)*t.alfa {
			scapegoat = i
			ssize = currsize
			break
		}
		childsize = currsize
		_, j = path[i-1].cmp(k)
	}

	x = rebalance(path[scapegoat], ssize)
	if scapegoat == 0 {
		t.root = x
		t.maxsize = ssize
	} else {
		_, i := path[scapegoat-1].cmp(k)
		path[scapegoat-1].c[i] = x
	}

	return true
}

func (t Tree) Get(val int) Key {
	for x := t.root; x != nil; {
		if x.key.beg <= val && val <= x.key.end {
			return x.key
		}
		eq, i := x.cmp(Key{val,val,val})
		if eq {
			panic("eq")
		}
		x = x.c[i]
	}
	panic("false")
}

func (t *Tree) Del(k Key) bool {
	p := &t.root
	x := t.root
	for x != nil {
		eq, i := x.cmp(k)
		if eq {
			break
		}
		p = &x.c[i]
		x = x.c[i]
	}

	if x == nil {
		return false
	}

	if x.c[0] != nil && x.c[1] != nil {
		y := x.c[1]
		p = &x.c[1]
		for y.c[0] != nil {
			p = &y.c[0]
			y = y.c[0]
		}

		*p = y.c[1] // it is fine both for nil and non-nil

		x.key = y.key
	} else if x.c[0] == nil {
		*p = x.c[1] // it is fine also for nil
	} else {
		*p = x.c[0]
	}

	t.size--
	if t.size > 0 && float64(t.size) <= t.alfa*float64(t.maxsize) {
		t.maxsize = t.size
		t.root = rebalance(t.root, t.size)
	}
	return true
}

func rebalance(x *node, subsize int) *node {
	// we will construct full tree plus some (even) nodes appended to its leafs
	fullCnt := 1
	for fullCnt <= subsize {
		fullCnt += fullCnt + 1
	}
	fullCnt /= 2
	evenLeft := subsize - fullCnt

	d := make([]*node, subsize)
	even := d[:0]
	odd := d[evenLeft:evenLeft]

	for it := first(0, &Iter{stack: []*node{x}}); it.Ok(); it.Inc() {
		x := it.top()

		if evenLeft > 0 && len(even) == len(odd) {
			even = append(even, x)
			evenLeft--
		} else {
			odd = append(odd, x)
		}
	}

	for _, x := range d {
		x.c[0] = nil
		x.c[1] = nil
	}
	for i, x := range even {
		odd[i&^1].c[i&1] = x
	}
	for i := 1; i < len(odd); i += 2 {
		j := ((i ^ (i + 1)) & (i + 1)) >> 1
		odd[i].c[0] = odd[i-j]
		odd[i].c[1] = odd[i+j]
	}

	return odd[fullCnt/2]
}

func (it *Iter) top() *node { return it.stack[len(it.stack)-1] }
func (it *Iter) pop() *node { x := it.top(); it.stack = it.stack[:len(it.stack)-1]; return x }

func first(dir int, it *Iter) *Iter {
	x := it.pop()
	if x == nil {
		return it
	}

	for x.c[dir] != nil {
		it.stack = append(it.stack, x)
		x = x.c[dir]
	}
	it.stack = append(it.stack, x)
	return it
}

func move(dir int, it *Iter) error {
	x := it.pop()
	if x == nil {
		return ErrMovePastEnd
	}
	if x.c[dir^1] == nil {
		for {
			if len(it.stack) == 0 {
				return nil
			}

			if it.top().c[dir] == x {
				x = it.pop()
				it.stack = append(it.stack, x)
				return nil
			}

			x = it.pop()
		}
	}
	it.stack = append(it.stack, x)
	x = x.c[dir^1]
	it.stack = append(it.stack, x)
	first(dir, it)
	return nil
}

func (t Tree) First() *Iter { return first(0, &Iter{stack: []*node{t.root}}) }
func (t Tree) Last() *Iter  { return first(1, &Iter{stack: []*node{t.root}}) }
func (it *Iter) Inc() error { return move(0, it) }
func (it *Iter) Dec() error { return move(1, it) }
func (it *Iter) Ok() bool   { return len(it.stack) > 0 }

// User must be sure that Ok() is true before call.
func (it *Iter) Key() Key { return it.top().key }

func subsize(x *node) int {
	if x == nil {
		return 0
	}
	return 1 + subsize(x.c[0]) + subsize(x.c[1])
}

func pow(x float64, n int) float64 {
	res := 1.0
	for n > 0 {
		if n&1 == 1 {
			res *= x
		}
		x *= x
		n >>= 1
	}
	return res
}

type Input struct {
	*bufio.Scanner
}

var globalInput = wrapStdin()

func wrapStdin() Input {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	return Input{Scanner: sc}
}
func getInt() int {
	globalInput.Scan()
	x, _ := strconv.Atoi(globalInput.Text())
	return x
}
func getIntOk() (int, bool) {
	ok := globalInput.Scan()
	x, _ := strconv.Atoi(globalInput.Text())
	return x, ok
}
func getNint(n int) []int {
	v := make([]int, n)
	for i := 0; i < n; i++ {
		v[i] = getInt()
	}
	return v
}
func getVint(v []int) bool {
	var ok bool
	for i := 0; i < len(v); i++ {
		v[i], ok = getIntOk()
	}
	return ok
}
func getWord() string {
	globalInput.Scan()
	return globalInput.Text()
}
func getWordOk() (string, bool) {
	ok := globalInput.Scan()
	return globalInput.Text(), ok
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func max(a, b int) int {
	if a < b {
		return b
	}
	return a
}
func min64(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}
func max64(a, b int64) int64 {
	if a < b {
		return b
	}
	return a
}
func minStr(a, b string) string {
	if a < b {
		return a
	}
	return b
}
func maxStr(a, b string) string {
	if a < b {
		return b
	}
	return a
}
func remin(a *int, b int) bool {
	if b < *a {
		*a = b
		return true
	}
	return false
}
func remax(a *int, b int) bool {
	if b > *a {
		*a = b
		return true
	}
	return false
}
func remin64(a *int64, b int64) bool {
	if b < *a {
		*a = b
		return true
	}
	return false
}
func remax64(a *int64, b int64) bool {
	if b > *a {
		*a = b
		return true
	}
	return false
}
func reminStr(a *string, b string) bool {
	if b < *a {
		*a = b
		return true
	}
	return false
}
func remaxStr(a *string, b string) bool {
	if b > *a {
		*a = b
		return true
	}
	return false
}

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

type (
	FLess    func(i, j int) bool
	FSwap    func(i, j int)
	wrapSort struct {
		Length int
		FLess
		FSwap
	}
)

func (w *wrapSort) Len() int           { return w.Length }
func (w *wrapSort) Less(i, j int) bool { return w.FLess(i, j) }
func (w *wrapSort) Swap(i, j int)      { w.FSwap(i, j) }
func wsort(length int, fless func(i, j int) bool, fswap func(i, j int)) {
	sort.Sort(&wrapSort{length, fless, fswap})
}


Vasya has a multiset $$$s$$$ consisting of $$$n$$$ integer numbers. Vasya calls some number $$$x$$$ nice if it appears in the multiset exactly once. For example, multiset $$$\{1, 1, 2, 3, 3, 3, 4\}$$$ contains nice numbers $$$2$$$ and $$$4$$$.Vasya wants to split multiset $$$s$$$ into two multisets $$$a$$$ and $$$b$$$ (one of which may be empty) in such a way that the quantity of nice numbers in multiset $$$a$$$ would be the same as the quantity of nice numbers in multiset $$$b$$$ (the quantity of numbers to appear exactly once in multiset $$$a$$$ and the quantity of numbers to appear exactly once in multiset $$$b$$$).

The first line contains a single integer $$$n~(2 \le n \le 100)$$$. The second line contains $$$n$$$ integers $$$s_1, s_2, \dots s_n~(1 \le s_i \le 100)$$$ — the multiset $$$s$$$.

If there exists no split of $$$s$$$ to satisfy the given requirements, then print "NO" in the first line. Otherwise print "YES" in the first line. The second line should contain a string, consisting of $$$n$$$ characters. $$$i$$$-th character should be equal to 'A' if the $$$i$$$-th element of multiset $$$s$$$ goes to multiset $$$a$$$ and 'B' if if the $$$i$$$-th element of multiset $$$s$$$ goes to multiset $$$b$$$. Elements are numbered from $$$1$$$ to $$$n$$$ in the order they are given in the input. If there exist multiple solutions, then print any of them.

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	scanner.Scan()
	numMap := map[int]int{}
	indexMap := map[int]int{}
	isInA := []bool{}

	for i, raw := range strings.Split(scanner.Text(), " ") {
		num, _ := strconv.Atoi(raw)
		isInA = append(isInA, true)
		numMap[num]++
		if _, ok := indexMap[num]; ok == false {
			indexMap[num] = i
		}
	}

	niceNumsInA := 0
	// Indicates the first index for an item with more than 1 siblings
	thePowerIndex := -1
	even := false
	for k, v := range numMap {
		if v == 1 {
			niceNumsInA++
			if even {
				isInA[indexMap[k]] = false
			}
			even = !even
		}
		if v > 2 {
			thePowerIndex = indexMap[k]
		}
	}

	if niceNumsInA%2 == 0 {
		fmt.Println("YES")
		for _, v := range isInA {
			if v {
				fmt.Print("A")
			} else {
				fmt.Print("B")
			}
		}
		fmt.Println()
	} else if thePowerIndex > -1 {
		fmt.Println("YES")
		for i, v := range isInA {
			if i == thePowerIndex {
				fmt.Print("B")
				continue
			}
			if v {
				fmt.Print("A")
			} else {
				fmt.Print("B")
			}
		}
		fmt.Println()
	} else {
		fmt.Println("NO")
	}
}


Santa Claus has received letters from $$$n$$$ different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the $$$i$$$-th kid asked Santa to give them one of $$$k_i$$$ different items as a present. Some items could have been asked by multiple kids.Santa is really busy, so he wants the New Year Bot to choose the presents for all children. Unfortunately, the Bot's algorithm of choosing presents is bugged. To choose a present for some kid, the Bot does the following:  choose one kid $$$x$$$ equiprobably among all $$$n$$$ kids;  choose some item $$$y$$$ equiprobably among all $$$k_x$$$ items kid $$$x$$$ wants;  choose a kid $$$z$$$ who will receive the present equipropably among all $$$n$$$ kids (this choice is independent of choosing $$$x$$$ and $$$y$$$); the resulting triple $$$(x, y, z)$$$ is called the decision of the Bot. If kid $$$z$$$ listed item $$$y$$$ as an item they want to receive, then the decision valid. Otherwise, the Bot's choice is invalid.Santa is aware of the bug, but he can't estimate if this bug is really severe. To do so, he wants to know the probability that one decision generated according to the aforementioned algorithm is valid. Can you help him?

The first line contains one integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — the number of kids who wrote their letters to Santa. Then $$$n$$$ lines follow, the $$$i$$$-th of them contains a list of items wanted by the $$$i$$$-th kid in the following format: $$$k_i$$$ $$$a_{i, 1}$$$ $$$a_{i, 2}$$$ ... $$$a_{i, k_i}$$$ ($$$1 \le k_i, a_{i, j} \le 10^6$$$), where $$$k_i$$$ is the number of items wanted by the $$$i$$$-th kid, and $$$a_{i, j}$$$ are the items themselves. No item is contained in the same list more than once. It is guaranteed that $$$\sum \limits_{i = 1}^{n} k_i \le 10^6$$$.

Print the probatility that the Bot produces a valid decision as follows: Let this probability be represented as an irreducible fraction $$$\frac{x}{y}$$$. You have to print $$$x \cdot y^{-1} \mod 998244353$$$, where $$$y^{-1}$$$ is the inverse element of $$$y$$$ modulo $$$998244353$$$ (such integer that $$$y \cdot y^{-1}$$$ has remainder $$$1$$$ modulo $$$998244353$$$).

package main

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

const (
	mod = 998244353
)

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n := 0
	fmt.Fscanf(in, "%d\n", &n)
	a := make([][]int, n)
	totalM := 0
	likeCnt := make(map[int]int)
	for i := 0; i < n; i++ {
		m := 0
		fmt.Fscanf(in, "%d", &m)
		totalM += m
		a[i] = make([]int, m)
		for j := 0; j < m; j++ {
			fmt.Fscanf(in, "%d", &a[i][j])
			likeCnt[a[i][j]]++
		}
		fmt.Fscanf(in, "\n")
	}
	qt := int64(1)
	for i := 0; i < n; i++ {
		qt *= int64(len(a[i]))
		qt %= mod
	}
	//fmt.Println(qt)
	q1 := make([]int64, n)
	for i := 0; i < n; i++ {
		t1 := len(a[i])
		x, y := int64(0), int64(0)
		exgcd(int64(t1), mod, &x, &y)
		for x < 0 {
			x += mod
		}
		//fmt.Println("debug1", x)
		q1[i] = int64(int64(qt)*int64(x)) % mod
	}
	//fmt.Println(a)
	//fmt.Println(q1)

	top := int64(0)
	for i := 0; i < n; i++ {
		for j := 0; j < len(a[i]); j++ {
			top += int64(likeCnt[a[i][j]]) * int64(q1[i])
			top %= mod
		}
	}
	btm := int64(1)
	x, y := int64(0), int64(0)
	exgcd(int64(n), mod, &x, &y)
	for x < 0 {
		x += mod
	}
	btm *= x
	btm %= mod
	//fmt.Println("debugbtm", btm)
	exgcd(int64(n), mod, &x, &y)
	for x < 0 {
		x += mod
	}
	btm *= x
	btm %= mod
	for i := 0; i < n; i++ {
		//fmt.Println("debugbtm", btm)

		exgcd(int64(len(a[i])), mod, &x, &y)
		for x < 0 {
			x += mod
		}
		btm *= x
		btm %= mod
	}
	//fmt.Println("debug", top, btm)
	ans := (top * btm) % mod
	fmt.Fprintf(out, "%d\n", ans)
	return
}

func exgcd(a, b int64, x, y *int64) int64 {
	if b == 0 {
		*x = 1
		*y = 0
		return a
	}
	r := exgcd(b, a%b, x, y)
	t := *x
	*x = *y
	*y = t - (a/b)*(*y)
	return r
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1279D(_r io.Reader, _w io.Writer) {
	in := bufio.NewScanner(_r)
	in.Split(bufio.ScanWords)
	r := func() (x int) {
		in.Scan()
		for _, b := range in.Bytes() {
			x = x*10 + int(b&15)
		}
		return
	}
	const mod int64 = 998244353
	pow := func(x, n int64) int64 {
		x %= mod
		res := int64(1)
		for ; n > 0; n >>= 1 {
			if n&1 == 1 {
				res = res * x % mod
			}
			x = x * x % mod
		}
		return res
	}
	inv := func(a int64) int64 { return pow(a, mod-2) }
	div := func(a, b int64) int64 { return a * inv(b) % mod }

	n := r()
	cnts := [1e6 + 1]int{}
	ps := make([][]int, n)
	for i := range ps {
		ps[i] = make([]int, r())
		for j := range ps[i] {
			ps[i][j] = r()
			cnts[ps[i][j]]++
		}
	}
	ans := int64(0)
	for _, p := range ps {
		s := 0
		for _, v := range p {
			s += cnts[v]
		}
		ans = (ans + div(int64(s), int64(len(p)))) % mod
	}
	Fprint(_w, div(ans, int64(n)*int64(n)))
}

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


Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries:  $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment.  $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example.

The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles.

Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries.

NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too.

package main

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

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

	n, q := readTwoNums(reader)
	P := readNNums(reader, n)
	queries := make([][]int, q)
	for i := 0; i < q; i++ {
		queries[i] = readNNums(reader, 2)
	}
	res := solve(n, P, q, queries)
	fmt.Print(res)
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func solve(n int, P []int, q int, queries [][]int) string {
	sort.Ints(P)
	var node *Node

	for i := 0; i < n; i++ {
		node = node.Set(P[i])
	}

	get := func() int {
		if node == nil {
			// empty node
			return 0
		}
		res := node.maxVal - node.minVal - node.maxGap
		return int(res)
	}

	var buf bytes.Buffer

	buf.WriteString(fmt.Sprintf("%d\n", get()))

	for i := 0; i < q; i++ {
		cur := queries[i]
		if cur[0] == 0 {
			node = node.Unset(cur[1])
		} else {
			node = node.Set(cur[1])
		}
		buf.WriteString(fmt.Sprintf("%d\n", get()))

	}

	return buf.String()
}

const MAX_X = 1000000010
const INF = 1 << 28
const N_INF = -INF

type Node struct {
	left, right *Node
	start, end  int
	maxGap      int64
	minVal      int64
	maxVal      int64
}

func NewNode(start, end int) *Node {
	node := new(Node)
	node.start = start
	node.end = end
	node.maxGap = -1
	node.minVal = INF
	node.maxVal = N_INF

	return node
}

func (node *Node) merge() *Node {
	if node.left == nil && node.right == nil {
		return nil
	}

	if node.right == nil {
		node.minVal = node.left.minVal
		node.maxVal = node.left.maxVal
		node.maxGap = node.left.maxGap
	} else if node.left == nil {
		node.minVal = node.right.minVal
		node.maxVal = node.right.maxVal
		node.maxGap = node.right.maxGap
	} else {
		node.minVal = min(node.left.minVal, node.right.minVal)
		node.maxVal = max(node.left.maxVal, node.right.maxVal)
		node.maxGap = max(node.right.minVal-node.left.maxVal, max(node.left.maxGap, node.right.maxGap))
	}

	return node
}

func (node *Node) Unset(p int) *Node {
	if node.start+1 == node.end {
		// node.start == p
		return nil
	}

	mid := (node.start + node.end) / 2

	if p < mid {
		node.left = node.left.Unset(p)
	} else {
		node.right = node.right.Unset(p)
	}

	return node.merge()
}

func (root *Node) Set(p int) *Node {
	var loop func(node *Node, start, end int) *Node

	loop = func(node *Node, start, end int) *Node {
		if node == nil {
			node = NewNode(start, end)
		}
		if start+1 == end {
			node.minVal = int64(p)
			node.maxVal = int64(p)
			node.maxGap = 0
			return node
		}

		mid := (start + end) / 2

		if p < mid {
			node.left = loop(node.left, start, mid)
		} else {
			node.right = loop(node.right, mid, end)
		}

		return node.merge()
	}

	return loop(root, 0, MAX_X)
}

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

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

/*
URL:
https://codeforces.com/contest/1418/problem/D
*/

package main

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

var (
	n, q int
	P    []int
)

func main() {
	defer stdout.Flush()

	n, q = readi2()
	P = readis(n)
	sort.Sort(sort.IntSlice(P))

	pt := NewTreap()
	dt := NewTreap()

	pt.Insert(P[0])
	for i := 1; i < n; i++ {
		diff := P[i] - P[i-1]
		pt.Insert(P[i])
		dt.Insert(diff)
	}
	maxp := pt.FindMaximum()
	minp := pt.FindMinimum()
	maxd := dt.FindMaximum()
	if maxd == nil {
		printf("%d\n", 0)
	} else {
		total := maxp.key - minp.key
		ans := total - maxd.key
		printf("%d\n", ans)
	}

	for i := 0; i < q; i++ {
		t, x := readi2()
		if t == 1 {
			// add
			r := pt.MinGreater(x)
			l := pt.MaxLess(x)
			if r != nil {
				diff := r.key - x
				dt.Insert(diff)
			}
			if l != nil {
				diff := x - l.key
				dt.Insert(diff)
			}
			if r != nil && l != nil {
				diff := r.key - l.key
				dt.Delete(diff)
			}
			pt.Insert(x)

			// calc
			maxp := pt.FindMaximum()
			minp := pt.FindMinimum()
			maxd := dt.FindMaximum()
			if maxd == nil {
				printf("%d\n", 0)
			} else {
				total := maxp.key - minp.key
				ans := total - maxd.key
				printf("%d\n", ans)
			}
		} else {
			// delete
			r := pt.MinGreater(x)
			l := pt.MaxLess(x)
			if r != nil {
				// 右のdiffを削除
				diff := r.key - x
				dt.Delete(diff)
			}
			if l != nil {
				// 左のdiffを削除
				diff := x - l.key
				dt.Delete(diff)
			}
			if r != nil && l != nil {
				// diffを追加
				diff := r.key - l.key
				dt.Insert(diff)
			}
			pt.Delete(x)

			// calc
			maxp := pt.FindMaximum()
			minp := pt.FindMinimum()
			maxd := dt.FindMaximum()
			if maxd == nil {
				printf("%d\n", 0)
			} else {
				total := maxp.key - minp.key
				ans := total - maxd.key
				printf("%d\n", ans)
			}
		}
	}
}

// Treap usage
// tr := NewTreap() 				// constructor
// tr.Insert(key) 					// insert one key node
// cnt := tr.Count(key) 		// return a number of key nodes
// node := tr.Find(key) 		// return a pointer
// min := tr.FindMinimum() 	// return a pointer
// max := tr.FindMaximum() 	// return a pointer
// tr.Delete(key) 					// delete one key node
// node := tr.MinGeq(x) 		// return a pointer
// node := tr.MinGreater(x) // return a pointer
// node := tr.MaxLeq(x) 		// return a pointer
// node := tr.MaxLess(x) 		// return a pointer

// fmt.Println(PrintIntsLine(tr.Inorder()...))
// fmt.Println(PrintIntsLine(tr.Preorder()...))
// tr.InsertBySettingPri(key, p)

type Node struct {
	key, priority int
	right, left   *Node
}

type Treap struct {
	root    *Node
	cnts    map[int]int
	randInt func() int
}

/*************************************/
// Public method
/*************************************/

// NewTreap returns a pointer of a Treap instance.
func NewTreap() *Treap {
	tr := new(Treap)

	tr.root = nil
	tr.cnts = make(map[int]int)

	// XorShiftによる乱数生成
	// 下記URLを参考
	// https://qiita.com/tubo28/items/f058582e457f6870a800#lower_bound-upper_bound
	_gtx, _gty, _gtz, _gtw := 123456789, 362436069, 521288629, 88675123
	tr.randInt = func() int {
		tt := (_gtx ^ (_gtx << 11))
		_gtx = _gty
		_gty = _gtz
		_gtz = _gtw
		_gtw = (_gtw ^ (_gtw >> 19)) ^ (tt ^ (tt >> 8))
		return _gtw
	}

	return tr
}

// Count method returns the number of the key.
// If there hasn't been the key in the treap, this returns 0.
func (tr *Treap) Count(key int) int {
	return tr.cnts[key]
}

// InsertBySettingPri method inserts a new node consisting of new key and priority.
// A duplicate key is ignored and nothing happens.
// func (tr *Treap) InsertBySettingPri(key, priority int) {
// 	tr.root = tr.insert(tr.root, key, priority)
// }

// Insert method inserts a new node consisting o new key.
// The priority is automatically set by random value.
// A duplicate key is ignored and nothing happens.
func (tr *Treap) Insert(key int) {
	preCnt := tr.Count(key)
	tr.increase(key, 1)
	if preCnt > 0 {
		return
	}

	tr.root = tr.insert(tr.root, key, tr.randInt())
}

// Find returns a node that has an argument key value.
// Find returns nil when there is no node that has an argument key value.
func (tr *Treap) Find(key int) *Node {
	cnt := tr.cnts[key]
	if cnt == 0 {
		return nil
	}

	u := tr.root
	for u != nil && key != u.key {
		if key < u.key {
			u = u.left
		} else {
			u = u.right
		}
	}
	return u
}

// FindMinimum returns a node that has the minimum key in the treap.
// FindMinimum returns nil when there is no nodes.
func (tr *Treap) FindMinimum() *Node {
	u := tr.root
	for u != nil && u.left != nil {
		u = u.left
	}
	return u
}

// FindMaximum returns a node that has the maximum key in the treap.
// FindMaximum returns nil when there is no nodes.
func (tr *Treap) FindMaximum() *Node {
	u := tr.root
	for u != nil && u.right != nil {
		u = u.right
	}
	return u
}

// Delete method deletes a node that has an argument key value.
// A duplicate key is ignored and nothing happens.
func (tr *Treap) Delete(key int) {
	tr.decrease(key, 1)
	curCnt := tr.Count(key)
	if curCnt > 0 {
		return
	}

	tr.root = tr.delete(tr.root, key)
}

// Inorder returns a slice consisting of treap nodes in order of INORDER.
// The nodes are sorted by key values.
func (tr *Treap) Inorder() []int {
	res := make([]int, 0, 200000+5)
	tr.inorder(tr.root, &res)
	return res
}

// Preorder returns a slice consisting of treap nodes in order of PREORDER.
func (tr *Treap) Preorder() []int {
	res := make([]int, 0, 200000+5)
	tr.preorder(tr.root, &res)
	return res
}

// MinGeq returns a node that has MINIMUM KEY MEETING key >= x.
// https://qiita.com/tubo28/items/f058582e457f6870a800#lower_bound-upper_bound
func (tr *Treap) MinGeq(x int) *Node {
	return tr.biggerLowerBound(tr.root, x)
}

// MinGreater returns a node that has MINIMUM KEY MEETING key > x.
// https://qiita.com/tubo28/items/f058582e457f6870a800#lower_bound-upper_bound
func (tr *Treap) MinGreater(x int) *Node {
	return tr.biggerUpperBound(tr.root, x)
}

// MaxLeq returns a node that has MAXIMUM KEY MEETING key <= x.
// for AGC005-B
func (tr *Treap) MaxLeq(x int) *Node {
	return tr.smallerUpperBound(tr.root, x)
}

// MaxLess returns a node that has MAXIMUM KEY MEETING key < x.
// for AGC005-B
func (tr *Treap) MaxLess(x int) *Node {
	return tr.smallerLowerBound(tr.root, x)
}

/*************************************/
// Private method
/*************************************/

func (tr *Treap) increase(key, num int) {
	tr.cnts[key] += num
}

func (tr *Treap) decrease(key, num int) {
	curCnt := tr.cnts[key]
	if curCnt-num < 0 {
		panic("too many elements is deleted!")
	}

	tr.cnts[key] -= num
}

func (tr *Treap) insert(t *Node, key, priority int) *Node {
	// 葉に到達したら新しい節点を生成して返す
	if t == nil {
		node := new(Node)
		node.key, node.priority = key, priority
		return node
	}

	// 重複したkeyは無視
	if key == t.key {
		return t
	}

	if key < t.key {
		// 左の子へ移動
		t.left = tr.insert(t.left, key, priority) // 左の子へのポインタを更新
		// 左の子の方が優先度が高い場合右回転
		if t.priority < t.left.priority {
			t = tr.rightRotate(t)
		}
	} else {
		// 右の子へ移動
		t.right = tr.insert(t.right, key, priority) // 右の子へのポインタを更新
		if t.priority < t.right.priority {
			// 右の子の方が優先度が高い場合左回転
			t = tr.leftRotate(t)
		}
	}

	return t
}

// 削除対象の節点を回転によって葉まで移動させた後に削除する
func (tr *Treap) delete(t *Node, key int) *Node {
	if t == nil {
		return nil
	}

	// 削除対象を検索
	if key < t.key {
		t.left = tr.delete(t.left, key)
	} else if key > t.key {
		t.right = tr.delete(t.right, key)
	} else {
		// 削除対象を発見、葉ノードとなるように回転を繰り返す
		return tr._delete(t, key)
	}

	return t
}

// 削除対象の節点の場合
func (tr *Treap) _delete(t *Node, key int) *Node {
	if t.left == nil && t.right == nil {
		// 葉の場合
		return nil
	} else if t.left == nil {
		// 右の子のみを持つ場合は左回転
		t = tr.leftRotate(t)
	} else if t.right == nil {
		// 左の子のみを持つ場合は右回転
		t = tr.rightRotate(t)
	} else {
		// 優先度が高い方を持ち上げる
		if t.left.priority > t.right.priority {
			t = tr.rightRotate(t)
		} else {
			t = tr.leftRotate(t)
		}
	}

	return tr.delete(t, key)
}

func (tr *Treap) rightRotate(t *Node) *Node {
	s := t.left
	t.left = s.right
	s.right = t
	return s
}

func (tr *Treap) leftRotate(t *Node) *Node {
	s := t.right
	t.right = s.left
	s.left = t
	return s
}

// rootからスタートする
func (tr *Treap) biggerLowerBound(t *Node, x int) *Node {
	if t == nil {
		return nil
	} else if t.key >= x {
		// 探索キーxが現在のノードキー以下の場合、左を探索する
		node := tr.biggerLowerBound(t.left, x)
		if node != nil {
			return node
		} else {
			return t
		}
	} else {
		// 探索キーxが現在のノードキーより大きい場合、右を探索する
		return tr.biggerLowerBound(t.right, x)
	}
}

// rootからスタートする
func (tr *Treap) biggerUpperBound(t *Node, x int) *Node {
	if t == nil {
		return nil
	} else if t.key > x {
		// 探索キーxが現在のノードキーより小さい場合、左を探索する
		node := tr.biggerUpperBound(t.left, x)
		if node != nil {
			return node
		} else {
			return t
		}
	} else {
		// 探索キーxが現在のノードキー以上の場合、右を探索する
		return tr.biggerUpperBound(t.right, x)
	}
}

// rootからスタートする
func (tr *Treap) smallerUpperBound(t *Node, x int) *Node {
	if t == nil {
		return nil
	} else if t.key <= x {
		node := tr.smallerUpperBound(t.right, x)
		if node != nil {
			return node
		} else {
			return t
		}
	} else {
		return tr.smallerUpperBound(t.left, x)
	}
}

// rootからスタートする
func (tr *Treap) smallerLowerBound(t *Node, x int) *Node {
	if t == nil {
		return nil
	} else if t.key < x {
		node := tr.smallerLowerBound(t.right, x)
		if node != nil {
			return node
		} else {
			return t
		}
	} else {
		return tr.smallerLowerBound(t.left, x)
	}
}

func (tr *Treap) inorder(u *Node, res *[]int) {
	if u == nil {
		return
	}
	tr.inorder(u.left, res)
	*res = append(*res, u.key)
	tr.inorder(u.right, res)
}

func (tr *Treap) preorder(u *Node, res *[]int) {
	if u == nil {
		return
	}
	*res = append(*res, u.key)
	tr.preorder(u.left, res)
	tr.preorder(u.right, res)
}

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

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

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

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

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

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

/********** 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 (
	"bufio"
	. "fmt"
	"io"
	"os"
	"sort"
)

type node struct {
	lr       [2]*node
	priority uint
	key      int
	dupCnt   int
	sz       int // JUST IGNORE
}

func (o *node) cmp(b int) int8 {
	switch {
	case b < o.key:
		return 0
	case b > o.key:
		return 1
	default:
		return -1
	}
}

func (o *node) size() int {
	if o != nil {
		return o.sz
	}
	return 0
}

func (o *node) maintain() { o.sz = o.dupCnt + o.lr[0].size() + o.lr[1].size() }

func (o *node) rotate(d int8) *node {
	x := o.lr[d^1]
	o.lr[d^1] = x.lr[d]
	x.lr[d] = o
	o.maintain()
	x.maintain()
	return x
}

type treap struct {
	rd   uint
	root *node
}

func (t *treap) fastRand() uint {
	t.rd ^= t.rd << 13
	t.rd ^= t.rd >> 17
	t.rd ^= t.rd << 5
	return t.rd
}

func (t *treap) _put(o *node, key int) *node {
	if o == nil {
		return &node{priority: t.fastRand(), key: key, dupCnt: 1, sz: 1}
	}
	if d := o.cmp(key); d >= 0 {
		o.lr[d] = t._put(o.lr[d], key)
		if o.lr[d].priority > o.priority {
			o = o.rotate(d ^ 1)
		}
	} else {
		o.dupCnt++
	}
	o.maintain()
	return o
}

func (t *treap) put(key int) { t.root = t._put(t.root, key) }

func (t *treap) _delete(o *node, key int) *node {
	if o == nil {
		return nil
	}
	if d := o.cmp(key); d >= 0 {
		o.lr[d] = t._delete(o.lr[d], key)
	} else {
		if o.dupCnt > 1 {
			o.dupCnt--
		} else {
			if o.lr[1] == nil {
				return o.lr[0]
			}
			if o.lr[0] == nil {
				return o.lr[1]
			}
			d = 0
			if o.lr[0].priority > o.lr[1].priority {
				d = 1
			}
			o = o.rotate(d)
			o.lr[d] = t._delete(o.lr[d], key)
		}
	}
	o.maintain()
	return o
}

func (t *treap) delete(key int) { t.root = t._delete(t.root, key) }

func (t *treap) get(key int) *node {
	for o := t.root; o != nil; {
		if d := o.cmp(key); d >= 0 {
			o = o.lr[d]
		} else {
			return o
		}
	}
	return nil
}

func (t *treap) max() (max *node) {
	for o := t.root; o != nil; o = o.lr[1] {
		max = o
	}
	return
}
func (t *treap) min() (min *node) {
	for o := t.root; o != nil; o = o.lr[0] {
		min = o
	}
	return
}

func (t *treap) lowerBound(key int) (lb *node) {
	for o := t.root; o != nil; {
		switch c := o.cmp(key); {
		case c == 0:
			lb = o
			o = o.lr[0]
		case c > 0:
			o = o.lr[1]
		default:
			return o
		}
	}
	return // NOTE: check nil
}

func (t *treap) prev(key int) (prev *node) {
	for o := t.root; o != nil; {
		if o.cmp(key) <= 0 {
			o = o.lr[0]
		} else {
			prev = o
			o = o.lr[1]
		}
	}
	return // NOTE: check nil
}

func newTreap() *treap { return &treap{rd: 1} }

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

	diff := newTreap()
	vs := newTreap()
	var n, q int
	Fscan(in, &n, &q)
	a := make([]int, n)
	for i := range a {
		Fscan(in, &a[i])
		vs.put(a[i])
	}
	sort.Ints(a)
	for i := 1; i < n; i++ {
		diff.put(a[i] - a[i-1])
	}
	if vs.root.size() < 3 {
		Fprintln(out, 0)
	} else {
		//println(vs.max().key,vs.min().key ,diff.max().key)
		Fprintln(out, vs.max().key-vs.min().key-diff.max().key)
	}
	for ; q > 0; q-- {
		var tp, x int
		Fscan(in, &tp, &x)
		if tp == 0 {
			// remove
			mi, mx := vs.min().key, vs.max().key
			if vs.root.size() > 1 {
				if x == mi {
					up := vs.lowerBound(x + 1).key
					diff.delete(up - x)
				} else if x == mx {
					low := vs.prev(x).key
					diff.delete(x - low)
				} else {
					up := vs.lowerBound(x + 1).key
					low := vs.prev(x).key
					diff.delete(up - x)
					diff.delete(x - low)
					diff.put(up - low)
				}
			}
			vs.delete(x)
		} else {
			// add
			if vs.root.size() > 0 {
				mi, mx := vs.min().key, vs.max().key
				if x < mi {
					diff.put(mi - x)
				} else if x > mx {
					diff.put(x - mx)
				} else {
					up := vs.lowerBound(x).key
					low := vs.prev(up).key
					diff.delete(up - low)
					diff.put(up - x)
					diff.put(x - low)
				}
			}
			vs.put(x)
		}
		if vs.root.size() < 3 {
			Fprintln(out, 0)
		} else {
			//println(vs.max().key,vs.min().key ,diff.max().key)
			Fprintln(out, vs.max().key-vs.min().key-diff.max().key)
		}
	}
}

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


There are $$$n$$$ cities in Shaazzzland, numbered from $$$0$$$ to $$$n-1$$$. Ghaazzzland, the immortal enemy of Shaazzzland, is ruled by AaParsa.As the head of the Ghaazzzland's intelligence agency, AaParsa is carrying out the most important spying mission in Ghaazzzland's history on Shaazzzland.AaParsa has planted $$$m$$$ transport cannons in the cities of Shaazzzland. The $$$i$$$-th cannon is planted in the city $$$a_i$$$ and is initially pointing at city $$$b_i$$$.It is guaranteed that each of the $$$n$$$ cities has at least one transport cannon planted inside it, and that no two cannons from the same city are initially pointing at the same city (that is, all pairs $$$(a_i, b_i)$$$ are distinct).AaParsa used very advanced technology to build the cannons, the cannons rotate every second. In other words, if the $$$i$$$-th cannon is pointing towards the city $$$x$$$ at some second, it will target the city $$$(x + 1) \mod n$$$ at the next second.As their name suggests, transport cannons are for transportation, specifically for human transport. If you use the $$$i$$$-th cannon to launch yourself towards the city that it's currently pointing at, you'll be airborne for $$$c_i$$$ seconds before reaching your target destination.If you still don't get it, using the $$$i$$$-th cannon at the $$$s$$$-th second (using which is only possible if you are currently in the city $$$a_i$$$) will shoot you to the city $$$(b_i + s) \mod n$$$ and you'll land in there after $$$c_i$$$ seconds (so you'll be there in the $$$(s + c_i)$$$-th second). Also note the cannon that you initially launched from will rotate every second but you obviously won't change direction while you are airborne. AaParsa wants to use the cannons for travelling between Shaazzzland's cities in his grand plan, and he can start travelling at second $$$0$$$. For him to fully utilize them, he needs to know the minimum number of seconds required to reach city $$$u$$$ from city $$$v$$$ using the cannons for every pair of cities $$$(u, v)$$$.Note that AaParsa can stay in a city for as long as he wants.

The first line contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 600 , n \le m \le n^2)$$$ — the number of cities and cannons correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains three integers $$$a_i$$$, $$$b_i$$$ and $$$c_i$$$ $$$( 0 \le a_i , b_i \le n-1 , 1 \le c_i \le 10^9)$$$, denoting the cannon in the city $$$a_i$$$, which is initially pointing to $$$b_i$$$ and travelling by which takes $$$c_i$$$ seconds. It is guaranteed that each of the $$$n$$$ cities has at least one transport cannon planted inside it, and that no two cannons from the same city are initially pointing at the same city (that is, all pairs $$$(a_i, b_i)$$$ are distinct).

Print $$$n$$$ lines, each line should contain $$$n$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line should be equal to the minimum time required to reach city $$$j$$$ from city $$$i$$$.

NoteIn the first example one possible path for going from $$$0$$$ to $$$2$$$ would be:   Stay inside $$$0$$$ and do nothing for $$$1$$$ second.  Use the first cannon and land at $$$2$$$ after $$$1$$$ second.  Note that: we could have used the second cannon in $$$0$$$-th second but it would have taken us $$$3$$$ seconds to reach city $$$2$$$ in that case.

package main

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

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

	var n, m, v, w, wt int
	Fscan(in, &n, &m)
	g := make([][]int, n)
	for i := range g {
		g[i] = make([]int, n)
		for j := range g[i] {
			g[i][j] = 1e9 + 1e3
		}
	}
	for ; m > 0; m-- {
		Fscan(in, &v, &w, &wt)
		g[v][w] = wt
	}
	for st, row := range g {
		dis := append([]int{}, row...)
		vis := make([]bool, n)
		for {
			v := -1
			for w, b := range vis {
				if !b && (v < 0 || dis[w] < dis[v]) {
					v = w
				}
			}
			if v < 0 {
				break
			}
			vis[v] = true
			d := dis[v]
			dis[(v+1)%n] = min(dis[(v+1)%n], d+1)
			for j, wt := range g[v] {
				dis[(j+d)%n] = min(dis[(j+d)%n], d+wt)
			}
		}
		for i, d := range dis {
			if i == st {
				d = 0
			}
			Fprint(out, d, " ")
		}
		Fprintln(out)
	}
}

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

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

package main

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

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

	var n, m, v, w, wt int
	Fscan(in, &n, &m)
	g := make([][]int, n)
	for i := range g {
		g[i] = make([]int, n)
		for j := range g[i] {
			g[i][j] = 1e9 + 1e3
		}
	}
	for ; m > 0; m-- {
		Fscan(in, &v, &w, &wt)
		g[v][w] = wt
	}
	for st, row := range g {
		dis := append([]int{}, row...)
		vis := make([]bool, n)
		for {
			v := -1
			for w, b := range vis {
				if !b && (v < 0 || dis[w] < dis[v]) {
					v = w
				}
			}
			if v < 0 {
				break
			}
			vis[v] = true
			dis[(v+1)%n] = min(dis[(v+1)%n], dis[v]+1)
			for j, wt := range g[v] {
				dis[(j+dis[v])%n] = min(dis[(j+dis[v])%n], dis[v]+wt)
			}
		}
		for i, d := range dis {
			if i == st {
				d = 0
			}
			Fprint(out, d, " ")
		}
		Fprintln(out)
	}
}

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

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

package main

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

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

	var n, m, v, w, wt int
	Fscan(in, &n, &m)
	g := make([][]int, n)
	for i := range g {
		g[i] = make([]int, n)
		for j := range g[i] {
			g[i][j] = 1e9 + 1e3
		}
	}
	for ; m > 0; m-- {
		Fscan(in, &v, &w, &wt)
		g[v][w] = wt
	}
	for st, row := range g {
		dis := append([]int{}, row...)
		vis := make([]bool, n)
		for {
			v := -1
			for w, b := range vis {
				if !b && (v < 0 || dis[w] < dis[v]) {
					v = w
				}
			}
			if v < 0 {
				break
			}
			vis[v] = true
			dis[(v+1)%n] = min(dis[(v+1)%n], dis[v]+1)
			for j := 0; j < n; j++ {
				dis[(j+dis[v])%n] = min(dis[(j+dis[v])%n], dis[v]+g[v][j])
			}
		}
		for i, d := range dis {
			if i == st {
				d = 0
			}
			Fprint(out, d, " ")
		}
		Fprintln(out)
	}
}

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

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

package main

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

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

	var n, m, v, w, wt int
	Fscan(in, &n, &m)
	g := make([][]int, n)
	for i := range g {
		g[i] = make([]int, n)
		for j := range g[i] {
			g[i][j] = 1e9
		}
	}
	for ; m > 0; m-- {
		Fscan(in, &v, &w, &wt)
		g[v][w] = wt
	}
	for st, row := range g {
		dis := append([]int{}, row...)
		vis := make([]bool, n)
		for {
			v := -1
			for w, b := range vis {
				if !b && (v < 0 || dis[w] < dis[v]) {
					v = w
				}
			}
			if v < 0 {
				break
			}
			vis[v] = true
			dis[(v+1)%n] = min(dis[(v+1)%n], dis[v]+1)
			for j := 0; j < n; j++ {
				dis[(j+dis[v])%n] = min(dis[(j+dis[v])%n], dis[v]+g[v][j])
			}
		}
		for i, d := range dis {
			if i == st {
				d = 0
			}
			Fprint(out, d, " ")
		}
		Fprintln(out)
	}
}

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

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


You are given an array $$$a$$$, consisting of $$$n$$$ positive integers.Let's call a concatenation of numbers $$$x$$$ and $$$y$$$ the number that is obtained by writing down numbers $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, a concatenation of numbers $$$12$$$ and $$$3456$$$ is a number $$$123456$$$.Count the number of ordered pairs of positions $$$(i, j)$$$ ($$$i \neq j$$$) in array $$$a$$$ such that the concatenation of $$$a_i$$$ and $$$a_j$$$ is divisible by $$$k$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$2 \le k \le 10^9$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).

Print a single integer — the number of ordered pairs of positions $$$(i, j)$$$ ($$$i \neq j$$$) in array $$$a$$$ such that the concatenation of $$$a_i$$$ and $$$a_j$$$ is divisible by $$$k$$$.

package main

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

const (
	MaxN = 200005
	MaxDigits = 11
)

var n, k uint64
var a [MaxN]uint64
var counts [MaxDigits]map[uint64]uint64

func digitCount(n uint64) int {
	cnt := 0
	for n > 0 {
		cnt++
		n /= 10
	}
	return cnt
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	for i := 0; i < MaxDigits; i++ {
		counts[i] = make(map[uint64]uint64)
	}
	fmt.Fscanf(buf, "%d %d\n", &n, &k)
	for i := uint64(0); i < n; i++ {
		fmt.Fscanf(buf, "%d ", &a[i])
		tmp := uint64(a[i])
		for j := uint64(1); j < MaxDigits; j++ {
			tmp = tmp * 10
			counts[j][tmp % k]++
		}
	}

	ans := uint64(0)
	for i := uint64(0); i < n; i++ {
		digits := digitCount(a[i])
		ans += counts[digits][(k - a[i] % k) % k]
		if (a[i] * uint64(math.Pow10(digits)) + a[i]) % k == 0 {
			ans--
		}
	}

	fmt.Println(ans)
}

package main

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

const (
	MaxN = 200005
	MaxDigits = 10
)

var n, k int64
var a [MaxN]int64
var counts [MaxDigits]map[int64]int

func digitCount(n int64) int {
	cnt := 0
	for n > 0 {
		cnt++
		n /= 10
	}
	return cnt
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	for i := 0; i < MaxDigits; i++ {
		counts[i] = make(map[int64]int)
	}
	fmt.Fscanf(buf, "%d %d\n", &n, &k)
	for i := int64(0); i < n; i++ {
		fmt.Fscanf(buf, "%d ", &a[i])
		tmp := int64(a[i])
		for j := int64(1); j < MaxDigits; j++ {
			tmp = tmp * 10
			counts[j][tmp % k]++
		}
	}

	ans := 0
	for i := int64(0); i < n; i++ {
		digits := digitCount(a[i])
		ans += counts[digits][(k - a[i] % k) % k]
		if (a[i] * int64(math.Pow10(digits)) + a[i]) % k == 0 {
			ans--
		}
	}

	fmt.Println(ans)
}


There are $$$n$$$ warriors in a row. The power of the $$$i$$$-th warrior is $$$a_i$$$. All powers are pairwise distinct.You have two types of spells which you may cast:   Fireball: you spend $$$x$$$ mana and destroy exactly $$$k$$$ consecutive warriors;  Berserk: you spend $$$y$$$ mana, choose two consecutive warriors, and the warrior with greater power destroys the warrior with smaller power. For example, let the powers of warriors be $$$[2, 3, 7, 8, 11, 5, 4]$$$, and $$$k = 3$$$. If you cast Berserk on warriors with powers $$$8$$$ and $$$11$$$, the resulting sequence of powers becomes $$$[2, 3, 7, 11, 5, 4]$$$. Then, for example, if you cast Fireball on consecutive warriors with powers $$$[7, 11, 5]$$$, the resulting sequence of powers becomes $$$[2, 3, 4]$$$.You want to turn the current sequence of warriors powers $$$a_1, a_2, \dots, a_n$$$ into $$$b_1, b_2, \dots, b_m$$$. Calculate the minimum amount of mana you need to spend on it.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the length of sequence $$$a$$$ and the length of sequence $$$b$$$ respectively. The second line contains three integers $$$x, k, y$$$ ($$$1 \le x, y, \le 10^9; 1 \le k \le n$$$) — the cost of fireball, the range of fireball and the cost of berserk respectively. The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$). It is guaranteed that all integers $$$a_i$$$ are pairwise distinct. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \dots, b_m$$$ ($$$1 \le b_i \le n$$$). It is guaranteed that all integers $$$b_i$$$ are pairwise distinct.

Print the minimum amount of mana for turning the sequnce $$$a_1, a_2, \dots, a_n$$$ into $$$b_1, b_2, \dots, b_m$$$, or $$$-1$$$ if it is impossible.

package main

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

type FastIn struct {
	scanner *bufio.Scanner
}

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

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

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

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

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

var x,k,y int64

func GetCost(arr []int, left_b int, right_b int) (int64, bool) {
	any_gt := false
	max_bound := left_b
	if max_bound < right_b {
		max_bound = right_b
	}
	for _,v := range arr {
		if  v > max_bound {
			any_gt = true
		}
	}

	len := int64(len(arr))
	if any_gt {
		if len < k {
			return 0, false
		}
		return Min((len/k)*x+(len%k)*y,x+(len-k)*y), true
	} else {
		return Min((len/k)*x+(len%k)*y, len * y), true
	}
}

func main() {
	fin := MakeFastIn()
	n, m := fin.ReadInt(), fin.ReadInt()
	x, k, y = fin.ReadInt64(), fin.ReadInt64(), fin.ReadInt64()
	a,b := make([]int, n), make([]int, m)
	fin.ReadInts(a)
	fin.ReadInts(b)

	a = append(a, -1)
	b = append(b,-1)
	j := 0
	var cost int64 = 0
	for i := 0; i < len(b); i++ {
		found := false
		tmp := make([]int, 0)
		for ; j < len(a) && !found; j++ {
			if a[j] == b[i] {
				found = true
			} else {
				tmp = append(tmp, a[j])
			}
		}
		if !found {
			fmt.Printf("-1")
			return
		}

		left_b, right_b := -1, b[i]
		if i > 0 {
			left_b = b[i-1]
		}
		ret, ok := GetCost(tmp, left_b, right_b)
		if !ok {
			fmt.Printf("-1")
			return
		}
		cost += ret
	}

	fmt.Printf("%d", cost)
}

package main

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

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

var (
	n, m, x, y, k int
	a, b, p       [200010]int
	ans           int64
	//debug
	//xcnt, ycnt int
)

func max(_x, _y int) int {
	if _x > _y {
		return _x
	}
	return _y
}

func min(_x, _y int) int {
	if _x < _y {
		return _x
	}
	return _y
}

func fail() {
	Fprintf(out, "-1\n")
	out.Flush()
	os.Exit(0)
}

func calc(len int, mustx int64) int64 {
	if mustx * int64(k) > int64(len) {
		fail()
	}
	x64, y64, k64, ret := int64(x), int64(y), int64(k), int64(0)
	ret += x64 * mustx
	len -= int(mustx) * k
	if x64 < y64*k64 {
		ret += x64 * int64(len/k)
		len %= k
	}
	ret += y64 * int64(len)
	return ret
}

func solve(l, r, mx int) int64 {
	ret, length, mustx := int64(0), r-l+1, int64(0)

	for i := l; i <= r; i++ {
		if a[i] > mx {
			mustx = 1
			break
		}
	}

	return ret + calc(length, mustx)
}

func main() {
	defer out.Flush()

	Fscan(in, &n, &m, &x, &k, &y)
	for i := 1; i <= n; i++ {
		Fscan(in, &a[i])
	}
	for i := 1; i <= m; i++ {
		Fscan(in, &b[i])
	}

	if m > n {
		fail()
	}

	for i, j := 1, 1; j <= m; i, j = i+1, j+1 {
		for i <= n && a[i] != b[j] {
			i++
		}
		if i > n {
			fail()
		}
		p[j] = i
	}

	if p[1] > 1 {
		ans += solve(1, p[1]-1, b[1])
	}
	if p[m] < n {
		ans += solve(p[m]+1, n, b[m])
	}

	for i := 1; i < m; i++ {
		if p[i]+1 == p[i+1] {
			continue
		}
		ans += solve(p[i]+1, p[i+1]-1, max(b[i], b[i+1]))
	}

	Fprintln(out, ans)
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1380D(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	var n, m, cur int
	var x, k, y, s int64
	Fscan(in, &n, &m, &x, &k, &y)
	a := make([]int, n)
	pos := make([]int, n+1)
	for i := range a {
		Fscan(in, &a[i])
		pos[a[i]] = i
	}

	pre := -1
	f := func() bool {
		l := int64(cur - pre - 1)
		if l < 0 {
			return true
		}
		max := 0
		for _, v := range a[pre+1 : cur] {
			if v > max {
				max = v
			}
		}
		edge := 0
		if pre >= 0 {
			edge = a[pre]
		}
		if cur < n && a[cur] > edge {
			edge = a[cur]
		}
		if l < k {
			if max > edge {
				return true
			}
			s += l * y
		} else if k*y < x {
			if max < edge {
				s += l * y
			} else {
				s += (l-k)*y + x
			}
		} else {
			s += l%k*y + l/k*x
		}
		return false
	}
	for ; m > 0; m-- {
		Fscan(in, &cur)
		cur = pos[cur]
		if f() {
			Fprint(out, -1)
			return
		}
		pre = cur
	}
	cur = n
	if f() {
		Fprint(out, -1)
		return
	}
	Fprint(out, s)
}

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

package main

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

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

var (
	n, m, x, y, k int
	a, b, p       [200010]int
	ans           int64
	qu            []int
	//debug
	//xcnt, ycnt int
)

func max(_x, _y int) int {
	if _x > _y {
		return _x
	}
	return _y
}

func min(_x, _y int) int {
	if _x < _y {
		return _x
	}
	return _y
}

func fail() {
	Fprintf(out, "-1\n")
	out.Flush()
	os.Exit(0)
}

func calc(len int) int64 {
	x64, y64, k64, ret := int64(x), int64(y), int64(k), int64(0)
	if x64 < y64*k64 {
		ret += x64 * int64(len/k)
		len %= k
	}
	ret += y64 * int64(len)
	return ret
}

func solve(l, r, mx int) int64 {
	ret, length := int64(0), r-l+1
	qu = []int{}

	for i := l; i <= r; i++ {
		if a[i] > mx {
			qu = append(qu, i)
		}
	}

	kcnt := (len(qu) + k - 1) / k
	if length < kcnt * k {
		fail()
	}
	length -= kcnt * k
	ret += int64(x) * int64(kcnt)

	return ret + calc(length)
}

func main() {
	defer out.Flush()

	Fscan(in, &n, &m, &x, &k, &y)
	for i := 1; i <= n; i++ {
		Fscan(in, &a[i])
	}
	for i := 1; i <= m; i++ {
		Fscan(in, &b[i])
	}

	if m > n {
		fail()
	}

	for i, j := 1, 1; j <= m; i, j = i+1, j+1 {
		for i <= n && a[i] != b[j] {
			i++
		}
		if i > n {
			fail()
		}
		p[j] = i
	}

	if p[1] > 1 {
		ans += solve(1, p[1]-1, b[1])
	}
	if p[m] < n {
		ans += solve(p[m]+1, n, b[m])
	}

	for i := 1; i < m; i++ {
		if p[i]+1 == p[i+1] {
			continue
		}
		ans += solve(p[i]+1, p[i+1]-1, max(b[i], b[i+1]))
	}

	Fprintln(out, ans)
}

package main

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

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

var (
	n, m, x, y, k int
	a, b, p       [200010]int
	ans           int64
	qu            []int
	//debug
	//xcnt, ycnt int
)

func max(_x, _y int) int {
	if _x > _y {
		return _x
	}
	return _y
}

func min(_x, _y int) int {
	if _x < _y {
		return _x
	}
	return _y
}

func fail() {
	Fprintf(out, "-1\n")
	out.Flush()
	os.Exit(0)
}

func calc(len int) int64 {
	x64, y64, k64, ret := int64(x), int64(y), int64(k), int64(0)
	if x64 < y64*k64 {
		ret += x64 * int64(len/k)
		len %= k
	}
	ret += y64 * int64(len)
	return ret
}

func solve(l, r, mx int) int64 {
	ret, length := int64(0), r-l+1
	qu = []int{}

	for i := l; i <= r; i++ {
		if a[i] > mx {
			qu = append(qu, i)
		}
	}

	kcnt := (len(qu) + k - 1) / k
	if length < kcnt * k {
		fail()
	}
	length -= kcnt * k
	ret += int64(x) * int64(kcnt)

	return ret + calc(length)
}

func main() {
	defer out.Flush()

	Fscan(in, &n, &m, &x, &k, &y)
	for i := 1; i <= n; i++ {
		Fscan(in, &a[i])
	}
	for i := 1; i <= m; i++ {
		Fscan(in, &b[i])
	}

	if m > n {
		fail()
	}

	for i, j := 1, 1; j <= m; i, j = i+1, j+1 {
		for i <= n && a[i] != b[j] {
			i++
		}
		if i > n {
			fail()
		}
		p[j] = i
	}

	if p[1] > 1 {
		ans += solve(1, p[1]-1, b[1])
	}
	if p[m] < n {
		ans += solve(p[m]+1, n, b[m])
	}

	for i := 1; i < m; i++ {
		if p[i]+1 == p[i+1] {
			continue
		}
		ans += solve(p[i]+1, p[i+1]-1, max(b[i], b[i+1]))
	}

	if n == 200000 && m == 2 {
		Fprintln(out, b[1], b[2], p[1], p[2])
	}
	Fprintln(out, ans)
}

package main

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

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

var (
	n, m, x, y, k int
	a, b, p       [200010]int
	ans           int64
	qu            []int
	//debug
	xcnt, ycnt int
)

func max(_x, _y int) int {
	if _x > _y {
		return _x
	}
	return _y
}

func min(_x, _y int) int {
	if _x < _y {
		return _x
	}
	return _y
}

func fail() {
	Fprintf(out, "-1\n")
	out.Flush()
	os.Exit(0)
}

func calc(len int) int64 {
	x64, y64, k64, ret := int64(x), int64(y), int64(k), int64(0)
	if x64 < y64*k64 {
		ret += x64 * int64(len/k)
		len %= k
		xcnt += len / k
	}
	ret += y64 * int64(len)
	ycnt += len
	return ret
}

func solve(l, r, mx int) int64 {
	ret, length := int64(0), r-l+1
	qu = []int{}

	for i := l; i <= r; i++ {
		if a[i] > mx {
			qu = append(qu, i)
		}
	}

	for len(qu) > 0 {
		if length < k {
			fail()
		}
		length -= k
		ret += int64(x)
		xcnt++
		R := min(r, qu[0]+k-1)
		i := 0
		for ; i < len(qu); i++ {
			if qu[i] > R {
				break
			}
		}
		if i > len(qu) {
			qu = []int{}
		} else {
			qu = qu[i:]
		}
	}

	return ret + calc(length)
}

func main() {
	defer out.Flush()

	Fscan(in, &n, &m, &x, &k, &y)
	for i := 1; i <= n; i++ {
		Fscan(in, &a[i])
	}
	for i := 1; i <= m; i++ {
		Fscan(in, &b[i])
	}

	if m > n {
		fail()
	}

	for i, j := 1, 1; j <= m; i, j = i+1, j+1 {
		for i <= n && a[i] != b[j] {
			i++
		}
		if i > n {
			fail()
		}
		p[j] = i
	}

	if p[1] > 1 {
		ans += solve(1, p[1]-1, b[1])
	}
	if p[m] < n {
		ans += solve(p[m]+1, n, b[m])
	}

	for i := 1; i < m; i++ {
		if p[i]+1 == p[i+1] {
			continue
		}
		ans += solve(p[i]+1, p[i+1]-1, max(b[i], b[i+1]))
	}

	if n == 200000 && m == 2 {
		Fprintln(out, ans, xcnt, ycnt)
	}
	Fprintln(out, ans)
}

package main

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

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

var (
	n, m, x, y, k int
	a, b, p       [200010]int
	ans           int64
	qu            []int
	//debug
	//xcnt, ycnt int
)

func max(_x, _y int) int {
	if _x > _y {
		return _x
	}
	return _y
}

func min(_x, _y int) int {
	if _x < _y {
		return _x
	}
	return _y
}

func fail() {
	Fprintf(out, "-1\n")
	out.Flush()
	os.Exit(0)
}

func calc(len int) int64 {
	x64, y64, k64, ret := int64(x), int64(y), int64(k), int64(0)
	if x64 < y64*k64 {
		ret += x64 * int64(len/k)
		len %= k
	}
	ret += y64 * int64(len)
	return ret
}

func solve(l, r, mx int) int64 {
	ret, length := int64(0), r-l+1
	qu = []int{}

	for i := l; i <= r; i++ {
		if a[i] > mx {
			qu = append(qu, i)
		}
	}

	kcnt := (len(qu) + k - 1) / k
	if length < kcnt * k {
		fail()
	}
	length -= kcnt * k
	ret += int64(x) * int64(kcnt)

	if n == 200000 && m == 2 {
		Fprintf(out, "l=%v, r=%v, maxcnt=%v, mincnt=%v\n", l, r, kcnt, length)
	}

	return ret + calc(length)
}

func main() {
	defer out.Flush()

	Fscan(in, &n, &m, &x, &k, &y)
	for i := 1; i <= n; i++ {
		Fscan(in, &a[i])
	}
	for i := 1; i <= m; i++ {
		Fscan(in, &b[i])
	}

	if m > n {
		fail()
	}

	for i, j := 1, 1; j <= m; i, j = i+1, j+1 {
		for i <= n && a[i] != b[j] {
			i++
		}
		if i > n {
			fail()
		}
		p[j] = i
	}

	if p[1] > 1 {
		ans += solve(1, p[1]-1, b[1])
	}
	if p[m] < n {
		ans += solve(p[m]+1, n, b[m])
	}

	for i := 1; i < m; i++ {
		if p[i]+1 == p[i+1] {
			continue
		}
		ans += solve(p[i]+1, p[i+1]-1, max(b[i], b[i+1]))
	}

	if n == 200000 && m == 2 {
		Fprintln(out, b[1], b[2], p[1], p[2])
	}
	Fprintln(out, ans)
}

package main

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

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

var (
	n, m, x, y, k int
	a, b, p       [200010]int
	ans           int64
	qu            []int
	//debug
	xcnt, ycnt int
)

func max(_x, _y int) int {
	if _x > _y {
		return _x
	}
	return _y
}

func min(_x, _y int) int {
	if _x < _y {
		return _x
	}
	return _y
}

func fail() {
	Fprintf(out, "-1\n")
	out.Flush()
	os.Exit(0)
}

func calc(len int) int64 {
	x64, y64, k64, ret := int64(x), int64(y), int64(k), int64(0)
	if x64 < y64*k64 {
		ret += x64 * int64(len/k)
		len %= k
		xcnt += len / k
	}
	ret += y64 * int64(len)
	ycnt += len
	return ret
}

func solve(l, r, mx int) int64 {
	ret, length := int64(0), r-l+1
	qu = []int{}

	for i := l; i <= r; i++ {
		if a[i] > mx {
			qu = append(qu, i)
		}
	}

	for len(qu) > 0 {
		if length < k {
			fail()
		}
		length -= k
		ret += int64(x)
		xcnt++
		R := min(r, qu[0]+k-1)
		i := 0
		for ; i < len(qu); i++ {
			if qu[i] > R {
				break
			}
		}
		if i > len(qu) {
			qu = []int{}
		} else {
			qu = qu[i:]
		}
	}

	return ret + calc(length)
}

func main() {
	defer out.Flush()

	Fscan(in, &n, &m, &x, &k, &y)
	for i := 1; i <= n; i++ {
		Fscan(in, &a[i])
	}
	for i := 1; i <= m; i++ {
		Fscan(in, &b[i])
	}

	if m > n {
		fail()
	}

	for i, j := 1, 1; j <= m; i, j = i+1, j+1 {
		for i <= n && a[i] != b[j] {
			i++
		}
		if i > n {
			fail()
		}
		p[j] = i
	}

	if p[1] > 1 {
		ans += solve(1, p[1]-1, b[1])
	}
	if p[m] < n {
		ans += solve(p[m]+1, n, b[m])
	}

	for i := 1; i < m; i++ {
		if p[i]+1 == p[i+1] {
			continue
		}
		ans += solve(p[i]+1, p[i+1]-1, max(b[i], b[i+1]))
	}

	if n == 200000 && m == 2 {
		Fprintln(out, ans, xcnt, ycnt, b[1], b[2])
	}
	Fprintln(out, ans)
}

package main

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

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

var (
	n, m, x, y, k int
	a, b, p       [200010]int
	ans           int64
	qu            []int
)

func max(_x, _y int) int {
	if _x > _y {
		return _x
	}
	return _y
}

func min(_x, _y int) int {
	if _x < _y {
		return _x
	}
	return _y
}

func fail() {
	Fprintf(out, "-1\n")
	out.Flush()
	os.Exit(0)
}

func calc(len int) int64 {
	x64, y64, k64, ret := int64(x), int64(y), int64(k), int64(0)
	if x64 < y64*k64 {
		ret += x64 * int64(len/k)
		len %= k
	}
	ret += y64 * int64(len)
	return ret
}

func solve(l, r, mx int) int64 {
	ret, length := int64(0), r-l+1
	qu = []int{}

	for i := l; i <= r; i++ {
		if a[i] > mx {
			qu = append(qu, i)
		}
	}

	for len(qu) > 0 {
		if length < k {
			fail()
		}
		length -= k
		ret += int64(x)
		R := min(r, qu[0]+k-1)
		i := 0
		for ; i < len(qu); i++ {
			if qu[i] > R {
				break
			}
		}
		if i > len(qu) {
			qu = []int{}
		} else {
			qu = qu[i:]
		}
	}

	return ret + calc(length)
}

func main() {
	defer out.Flush()

	Fscan(in, &n, &m, &x, &k, &y)
	for i := 1; i <= n; i++ {
		Fscan(in, &a[i])
	}
	for i := 1; i <= m; i++ {
		Fscan(in, &b[i])
	}

	if m > n {
		fail()
	}

	for i, j := 1, 1; j <= m; i, j = i+1, j+1 {
		for i <= n && a[i] != b[j] {
			i++
		}
		if i > n {
			fail()
		}
		p[j] = i
	}

	if p[1] > 1 {
		ans += solve(1, p[1]-1, b[1])
	}
	if p[m] < n {
		ans += solve(p[m]+1, n, b[m])
	}

	for i := 1; i < m; i++ {
		if p[i]+1 == p[i+1] {
			continue
		}
		ans += solve(p[i]+1, p[i+1]-1, max(b[i], b[i+1]))
	}

	Fprintln(out, ans)
}


A permutation is a sequence of $$$n$$$ integers from $$$1$$$ to $$$n$$$, in which all numbers occur exactly once. For example, $$$[1]$$$, $$$[3, 5, 2, 1, 4]$$$, $$$[1, 3, 2]$$$ are permutations, and $$$[2, 3, 2]$$$, $$$[4, 3, 1]$$$, $$$[0]$$$ are not.Polycarp was presented with a permutation $$$p$$$ of numbers from $$$1$$$ to $$$n$$$. However, when Polycarp came home, he noticed that in his pocket, the permutation $$$p$$$ had turned into an array $$$q$$$ according to the following rule:   $$$q_i = \max(p_1, p_2, \ldots, p_i)$$$. Now Polycarp wondered what lexicographically minimal and lexicographically maximal permutations could be presented to him.An array $$$a$$$ of length $$$n$$$ is lexicographically smaller than an array $$$b$$$ of length $$$n$$$ if there is an index $$$i$$$ ($$$1 \le i \le n$$$) such that the first $$$i-1$$$ elements of arrays $$$a$$$ and $$$b$$$ are the same, and the $$$i$$$-th element of the array $$$a$$$ is less than the $$$i$$$-th element of the array $$$b$$$. For example, the array $$$a=[1, 3, 2, 3]$$$ is lexicographically smaller than the array $$$b=[1, 3, 4, 2]$$$.For example, if $$$n=7$$$ and $$$p=[3, 2, 4, 1, 7, 5, 6]$$$, then $$$q=[3, 3, 4, 4, 7, 7, 7]$$$ and the following permutations could have been as $$$p$$$ initially:   $$$[3, 1, 4, 2, 7, 5, 6]$$$ (lexicographically minimal permutation);  $$$[3, 1, 4, 2, 7, 6, 5]$$$;  $$$[3, 2, 4, 1, 7, 5, 6]$$$;  $$$[3, 2, 4, 1, 7, 6, 5]$$$ (lexicographically maximum permutation). For a given array $$$q$$$, find the lexicographically minimal and lexicographically maximal permutations that could have been originally presented to Polycarp.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$q_1, q_2, \ldots, q_n$$$ ($$$1 \le q_i \le n$$$). It is guaranteed that the array $$$q$$$ was obtained by applying the rule from the statement to some permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output two lines:    on the first line output $$$n$$$ integers — lexicographically minimal permutation that could have been originally presented to Polycarp;  on the second line print $$$n$$$ integers — lexicographically maximal permutation that could have been originally presented to Polycarp;

package main

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

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

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

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

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

func sints(n int) []int {
	a := make([]int, n)
	for i := range a {
		a[i] = sint()
	}
	return a
}

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

func main() {
	defer writer.Flush()
	t := sint()
	for ; t > 0; t-- {
		n := sint()
		q := sints(n)
		printsl(solveMin(n, q))
		printsl(solveMax(n, q))
	}
}

func printsl(in []int) {
	for _, i := range in {
		printf("%d ", i)
	}
	printf("\n")
}

func solveMin(n int, q []int) []int {
	curr := 1
	ret := make([]int, n)
	seen := map[int]bool{}
	for i := range ret {
		if i == 0 || q[i-1] != q[i] {
			ret[i] = q[i]
			seen[q[i]] = true
			continue
		}
		for seen[curr] {
			curr++
		}
		ret[i] = curr
		seen[curr] = true
		curr++
	}
	return ret
}

func solveMax(n int, q []int) []int {
	ds := make([]int, n+1)
	for i := range ds {
		ds[i] = int(i)
	}
	var find func(int) int
	find = func(t int) int {
		if ds[t] == t {
			return t
		}
		ret := find(ds[t])
		ds[t] = ret
		return ret
	}
	ret := make([]int, n)
	for i := range ret {
		if i == 0 || q[i-1] != q[i] {
			ret[i] = q[i]
			ds[q[i]] = q[i] - 1
			continue
		}
		ret[i] = find(q[i])
		ds[ret[i]] = ret[i] - 1
	}
	return ret
}

package main

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

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

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

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

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

func sint64s(n int64) []int64 {
	a := make([]int64, n)
	for i := range a {
		a[i] = sint64()
	}
	return a
}

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

func main() {
	defer writer.Flush()
	t := sint64()
	for ; t > 0; t-- {
		n := sint64()
		q := sint64s(n)
		printsl(solveMin(n, q))
		printsl(solveMax(n, q))
	}
}

func printsl(in []int64) {
	for _, i := range in {
		printf("%d ", i)
	}
	printf("\n")
}

func solveMin(n int64, q []int64) []int64 {
	curr := int64(1)
	ret := make([]int64, n)
	seen := map[int64]bool{}
	for i := range ret {
		if i == 0 || q[i-1] != q[i] {
			ret[i] = q[i]
			seen[q[i]] = true
			continue
		}
		for seen[curr] {
			curr++
		}
		ret[i] = curr
		seen[curr] = true
		curr++
	}
	return ret
}

func solveMax(n int64, q []int64) []int64 {
	ds := make([]int64, n+1)
	for i := range ds {
		ds[i] = int64(i)
	}
	var find func(int64) int64
	find = func(t int64) int64 {
		if ds[t] == t {
			return t
		}
		ret := find(ds[t])
		ds[t] = ret
		return ret
	}
	ret := make([]int64, n)
	for i := range ret {
		if i == 0 || q[i-1] != q[i] {
			ret[i] = q[i]
			ds[q[i]] = q[i] - 1
			continue
		}
		ret[i] = find(q[i])
		ds[ret[i]] = ret[i] - 1
	}
	return ret
}

package main

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

type IntHeap []int

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x interface{}) {
	*h = append(*h, x.(int))
}
func (h *IntHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func main() {
	in := bufio.NewReader(os.Stdin)
	wr := bufio.NewWriter(os.Stdout)
	defer wr.Flush()
	var t int
	fmt.Fscan(in, &t)
	N := 200000
	v := make([]int, N)
	mn := make([]int, N)
	mx := make([]int, N)
	seen := make([]bool, N+1)
	for t > 0 {
		t--
		var n int
		fmt.Fscan(in, &n)
		h := &IntHeap{}
		heap.Init(h)
		val := 1
		valForMin := 1
		lastIdx := 0
		for i := 1; i <= n; i++ {
			seen[i] = false
		}
		for i := 0; i<=n; i++ {
			if i != n {
				fmt.Fscan(in, &v[i])
			}
			if i == 0 || i==n || v[i] != v[i-1] {
				for lastIdx != i {
					mx[lastIdx] = heap.Pop(h).(int)
					lastIdx++
				}
				if i == n {
					break
				}
				mn[i] = v[i]
				mx[i] = v[i]
				seen[v[i]] = true
				lastIdx = i + 1
			}else {
				for seen[valForMin] {
					valForMin++
				}
				mn[i] = valForMin
				valForMin++
			}
			for val <= v[i] {
				if val != v[i] {
					heap.Push(h, val)
				}
				val++
			}
		}
		for i := 0; i<n; i++ {
			fmt.Fprintf(wr, "%d ", mn[i])
		}
		fmt.Fprintln(wr, "")
		for i := 0; i<n; i++ {
			fmt.Fprintf(wr, "%d ", mx[i])
		}
		fmt.Fprintln(wr, "")
	}
}

package main

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

type IntHeap []int

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x interface{}) {
	*h = append(*h, x.(int))
}
func (h *IntHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func main() {
	in := bufio.NewReader(os.Stdin)
	var t int
	fmt.Fscan(in, &t)
	N := 200000
	v := make([]int, N)
	mn := make([]int, N)
	mx := make([]int, N)
	seen := make([]bool, N+1)
	for t > 0 {
		t--
		var n int
		fmt.Fscan(in, &n)
		h := &IntHeap{}
		heap.Init(h)
		val := 1
		valForMin := 1
		lastIdx := 0
		for i := 1; i <= n; i++ {
			seen[i] = false
		}
		for i := 0; i<=n; i++ {
			if i != n {
				fmt.Fscan(in, &v[i])
			}
			if i == 0 || i==n || v[i] != v[i-1] {
				for lastIdx != i {
					mx[lastIdx] = heap.Pop(h).(int)
					lastIdx++
				}
				if i == n {
					break
				}
				mn[i] = v[i]
				mx[i] = v[i]
				seen[v[i]] = true
				lastIdx = i + 1
			}else {
				for seen[valForMin] {
					valForMin++
				}
				mn[i] = valForMin
				valForMin++
			}
			for val <= v[i] {
				if val != v[i] {
					heap.Push(h, val)
				}
				val++
			}
		}
		for i := 0; i<n; i++ {
			fmt.Printf("%d ", mn[i])
		}
		fmt.Println("")
		for i := 0; i<n; i++ {
			fmt.Printf("%d ", mx[i])
		}
		fmt.Println("")
	}
}

package main

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

type IntHeap []int

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x interface{}) {
	*h = append(*h, x.(int))
}
func (h *IntHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func main() {
	in := bufio.NewReader(os.Stdin)
	var t int
	fmt.Fscan(in, &t)
	for t > 0 {
		t--
		var n int
		fmt.Fscan(in, &n)
		v := make([]int, n)
		h := &IntHeap{}
		heap.Init(h)
		val := 1
		valForMin := 1
		mn := make([]int, n)
		mx := make([]int, n)
		seen := make([]bool, n+1)
		lastIdx := 0
		for i := 0; i<=n; i++ {
			if i != n {
				fmt.Fscan(in, &v[i])
			}
			if i == 0 || i==n || v[i] != v[i-1] {
				for lastIdx != i {
					mx[lastIdx] = heap.Pop(h).(int)
					lastIdx++
				}
				if i == n {
					break
				}
				mn[i] = v[i]
				mx[i] = v[i]
				seen[v[i]] = true
				lastIdx = i + 1
			}else {
				for seen[valForMin] {
					valForMin++
				}
				mn[i] = valForMin
				valForMin++
			}
			for val <= v[i] {
				if val != v[i] {
					heap.Push(h, val)
				}
				val++
			}
		}
		for _, x := range mn {
			fmt.Printf("%d ", x)
		}
		fmt.Println("")
		for _, x := range mx {
			fmt.Printf("%d ", x)
		}
		fmt.Println("")
	}
}

package main

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

type IntHeap []int

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x interface{}) {
	*h = append(*h, x.(int))
}
func (h *IntHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func main() {
	in := bufio.NewReader(os.Stdin)
	var t int
	fmt.Fscan(in, &t)
	for t > 0 {
		t--
		var n int
		fmt.Fscan(in, &n)
		v := make([]int, n)
		h := &IntHeap{}
		heap.Init(h)
		val := 1
		valForMin := 1
		mn := make([]int, n)
		mx := make([]int, n)
		seen := make(map[int]bool)
		lastIdx := 0
		for i := 0; i<=n; i++ {
			if i != n {
				fmt.Fscan(in, &v[i])
			}
			if i == 0 || i==n || v[i] != v[i-1] {
				for lastIdx != i {
					mx[lastIdx] = heap.Pop(h).(int)
					lastIdx++
				}
				if i == n {
					break
				}
				mn[i] = v[i]
				mx[i] = v[i]
				seen[v[i]] = true
				lastIdx = i + 1
			}else {
				for seen[valForMin] {
					valForMin++
				}
				mn[i] = valForMin
				valForMin++
			}
			for val <= v[i] {
				if val != v[i] {
					heap.Push(h, val)
				}
				val++
			}
		}
		for _, x := range mn {
			fmt.Printf("%d ", x)
		}
		fmt.Println("")
		for _, x := range mx {
			fmt.Printf("%d ", x)
		}
		fmt.Println("")
	}
}

package main

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

type Scanner struct {
	bScanner *bufio.Scanner
}

func NewScanner() *Scanner {
	bScanner := bufio.NewScanner(os.Stdin)
	bScanner.Split(bufio.ScanWords)
	bScanner.Buffer([]byte{}, math.MaxInt32)
	return &Scanner{
		bScanner,
	}
}
func (s *Scanner) next() string {
	s.bScanner.Scan()
	return s.bScanner.Text()
}
func (s *Scanner) nextInt() int {
	s.bScanner.Scan()
	res, err := strconv.Atoi(s.bScanner.Text())
	if err != nil {
		panic(err)
	}
	return res
}
func (s *Scanner) nextInt64() int64 {
	s.bScanner.Scan()
	res, err := strconv.ParseInt(s.bScanner.Text(), 10, 64)
	if err != nil {
		panic(err)
	}
	return res
}
func (s *Scanner) nextFloat() float64 {
	s.bScanner.Scan()
	res, err := strconv.ParseFloat(s.bScanner.Text(), 64)
	if err != nil {
		panic(err)
	}
	return res
}
func (s *Scanner) nextInts(N int) []int {
	res := make([]int, N)
	for i := 0; i < N; i++ {
		res[i] = s.nextInt()
	}
	return res
}
func (s *Scanner) nextInt64s(N int) []int64 {
	res := make([]int64, N)
	for i := 0; i < N; i++ {
		res[i] = s.nextInt64()
	}
	return res
}
func min(nums ...int) int {
	ans := math.MaxInt32
	for _, num := range nums {
		if num < ans {
			ans = num
		}
	}
	return ans
}
func max(nums ...int) int {
	ans := math.MinInt32
	for _, num := range nums {
		if num > ans {
			ans = num
		}
	}
	return ans
}

type SegmentTreeNode struct {
	val int
}

func (n *SegmentTreeNode) merge(n2 *SegmentTreeNode) *SegmentTreeNode {
	return &SegmentTreeNode{val: n.val + n2.val}
}

type SegmentTree struct {
	size int
	tree []*SegmentTreeNode
}

func NewSegmentTree(arr []int) *SegmentTree {
	size := len(arr)
	tree := make([]*SegmentTreeNode, 4*size)
	result := &SegmentTree{
		size: size,
		tree: tree,
	}
	result.initTree(1, 0, size-1, arr)
	return result
}
func (s *SegmentTree) initTree(pos int, l int, r int, arr []int) {
	if l == r {
		s.tree[pos] = &SegmentTreeNode{val: arr[l]}
		return
	}
	m := (l + r) / 2
	s.initTree(pos*2, l, m, arr)
	s.initTree(pos*2+1, m+1, r, arr)
	s.tree[pos] = s.tree[pos*2].merge(s.tree[pos*2+1])
}
func (s *SegmentTree) query(pos int, l int, r int, ql int, qr int) *SegmentTreeNode {
	if ql <= l && r <= qr {
		return s.tree[pos]
	} else if ql <= r && l <= qr {
		m := (l + r) / 2
		return s.query(pos*2, l, m, ql, qr).merge(s.query(pos*2+1, m+1, r, ql, qr))
	} else {
		return &SegmentTreeNode{val: 0}
	}
}
func (s *SegmentTree) Query(ql int, qr int) int {
	queryResult := s.query(1, 0, s.size-1, ql, qr)
	return queryResult.val
}
func (s *SegmentTree) update(pos int, l int, r int, uidx int, uval int) {
	if l == r {
		s.tree[pos] = &SegmentTreeNode{val: uval}
		return
	}
	m := (l + r) / 2
	if uidx <= m {
		s.update(pos*2, l, m, uidx, uval)
	} else {
		s.update(pos*2+1, m+1, r, uidx, uval)
	}
	s.tree[pos] = s.tree[pos*2].merge(s.tree[pos*2+1])
}
func (s *SegmentTree) Update(uidx int, uval int) {
	s.update(1, 0, s.size-1, uidx, uval)
}

func (s *SegmentTree) traverse(pos int, l int, r int, rem int) int {
	if l == r {
		return l
	}
	m := (l + r) / 2
	if s.tree[pos*2].val < rem {
		return s.traverse(pos*2+1, m+1, r, rem-s.tree[pos*2].val)
	} else {
		return s.traverse(pos*2, l, m, rem)
	}
}
func (s *SegmentTree) Traverse(rem int) int {
	return s.traverse(1, 0, s.size-1, rem)
}

func main() {
	sc := NewScanner()
	wr := bufio.NewWriter(os.Stdout)
	defer wr.Flush()

	TC := sc.nextInt()
	for tc := 0; tc < TC; tc++ {
		N := sc.nextInt()
		q := sc.nextInts(N)

		minm := make([]int, N)
		maxm := make([]int, N)
		minm[0] = q[0]
		maxm[0] = q[0]
		for i := 1; i < N; i++ {
			if q[i] != q[i-1] {
				minm[i] = q[i]
				maxm[i] = q[i]
			}
		}

		used := make([]bool, N+1)
		for i := 0; i < N; i++ {
			if minm[i] > 0 {
				used[minm[i]] = true
			}
		}
		cur := 1
		for i := 0; i < N; i++ {
			if minm[i] == 0 {
				for used[cur] {
					cur++
				}
				minm[i] = cur
				used[cur] = true
			}
		}

		available := make([]int, N+1)
		for i := 1; i <= N; i++ {
			available[i] = 1
		}
		for i := 0; i < N; i++ {
			if maxm[i] != 0 {
				available[maxm[i]] = 0
			}
		}
		segTree := NewSegmentTree(available)
		for i := 0; i < N; i++ {
			if maxm[i] == 0 {
				cntOn := segTree.Query(0, q[i])
				maxm[i] = segTree.Traverse(cntOn)
				segTree.Update(maxm[i], 0)
			}
		}

		for i := 0; i < N; i++ {
			fmt.Fprint(wr, minm[i], " ")
		}
		fmt.Fprintln(wr)
		for i := 0; i < N; i++ {
			fmt.Fprint(wr, maxm[i], " ")
		}
		fmt.Fprintln(wr)

	}

}

package main

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

type uf struct {
	fa []int
}

func newUnionFind(n int) uf {
	fa := make([]int, n)
	for i := range fa {
		fa[i] = i
	}
	return uf{fa}
}

func (u uf) find(x int) int {
	if u.fa[x] != x {
		u.fa[x] = u.find(u.fa[x])
	}
	return u.fa[x]
}

func (u uf) merge(from, to int) (isNewMerge bool) {
	x, y := u.find(from), u.find(to)
	if x == y {
		return false
	}
	u.fa[x] = y
	return true
}

func (u uf) same(x, y int) bool { return u.find(x) == u.find(y) }

func (u uf) countRoots(l, r int) (cnt int) {
	for i := l; i <= r; i++ {
		if u.find(i) == i {
			cnt++
		}
	}
	return
}

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

	// single test case

	var tt int
	Fscan(in, &tt)

	for tt > 0 {
		tt--

		var n int
		Fscan(in, &n)

		a := make([]int, n)
		pmin := make([]int, n)
		pmax := make([]int, n)

		check := make(map[int]bool, n)

		u := newUnionFind(n + 1)

		for i := 0; i < n; i++ {
			Fscan(in, &a[i])
			if i == 0 || a[i] != a[i-1] {
				check[a[i]] = true
				pmin[i] = a[i]
				pmax[i] = a[i]
				u.merge(a[i], a[i]-1)
			}
		}

		cur := 1
		for k, v := range pmin {
			if v == 0 {
				for ; check[cur]; cur++ {
				}
				pmin[k] = cur
				cur++
			}
		}

		pre := 0
		for k, v := range pmax {
			if v > 0 {
				pre = v
			} else {
				cur := u.find(pre)
				pmax[k] = cur
				u.merge(pre, cur-1)
			}
		}

		for k := range pmin {
			Fprint(out, pmin[k])
			Fprint(out, " ")
		}
		Fprint(out, "\n")
		for k := range pmax {
			Fprint(out, pmax[k])
			Fprint(out, " ")
		}
		Fprint(out, "\n")
	}

	// 입력 에러 방지
	_leftData, _ := ioutil.ReadAll(in)
	if _s := strings.TrimSpace(string(_leftData)); _s != "" {
		panic("읽지않은 데이터 발견：\n" + _s)
	}
}

// LETYLETYLETY
func main() { CF1506E(os.Stdin, os.Stdout) }

// YTELYTELYTEL

package main

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

// github.com/EndlessCheng/codeforces-go
type uf struct {
	fa []int
}

func newUnionFind(n int) uf {
	fa := make([]int, n)
	for i := range fa {
		fa[i] = i
	}
	return uf{fa}
}

func (u uf) find(x int) int {
	if u.fa[x] != x {
		u.fa[x] = u.find(u.fa[x])
	}
	return u.fa[x]
}

func (u uf) merge(from, to int) (isNewMerge bool) {
	x, y := u.find(from), u.find(to)
	if x == y {
		return false
	}
	u.fa[x] = y
	return true
}

func (u uf) same(x, y int) bool { return u.find(x) == u.find(y) }

func (u uf) countRoots(l, r int) (cnt int) {
	for i := l; i <= r; i++ {
		if u.find(i) == i {
			cnt++
		}
	}
	return
}

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

	solve := func(Case int) {
		var n int
		Fscan(in, &n)
		q := make([]int, n)
		vis := make([]bool, n+1)
		mi := make([]int, n)
		mx := make([]int, n)
		u := newUnionFind(n + 1)
		for i := range q {
			Fscan(in, &q[i])
			if i == 0 || q[i] != q[i-1] {
				vis[q[i]] = true
				mi[i] = q[i]
				mx[i] = q[i]
				u.merge(q[i], q[i]-1)
			}
		}

		cur := 1
		for i, v := range mi {
			if v == 0 {
				for ; vis[cur]; cur++ {
				}
				mi[i] = cur
				cur++
			}
		}

		pre := 0
		for i, v := range mx {
			if v > 0 {
				pre = v
			} else {
				cur := u.find(pre)
				mx[i] = cur
				u.merge(pre, cur-1)
			}
		}

		for _, v := range mi {
			Fprint(out, v, " ")
		}
		Fprintln(out)
		for _, v := range mx {
			Fprint(out, v, " ")
		}
		Fprintln(out)
	}

	var t int
	Fscan(in, &t)
	for Case := 1; Case <= t; Case++ {
		solve(Case)
	}

	_leftData, _ := ioutil.ReadAll(in)
	if _s := strings.TrimSpace(string(_leftData)); _s != "" {
		panic("有未读入的数据：\n" + _s)
	}
}

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