Dmitry has an array of $$$n$$$ non-negative integers $$$a_1, a_2, \dots, a_n$$$.In one operation, Dmitry can choose any index $$$j$$$ ($$$1 \le j \le n$$$) and increase the value of the element $$$a_j$$$ by $$$1$$$. He can choose the same index $$$j$$$ multiple times.For each $$$i$$$ from $$$0$$$ to $$$n$$$, determine whether Dmitry can make the $$$\mathrm{MEX}$$$ of the array equal to exactly $$$i$$$. If it is possible, then determine the minimum number of operations to do it.The $$$\mathrm{MEX}$$$ of the array is equal to the minimum non-negative integer that is not in the array. For example, the $$$\mathrm{MEX}$$$ of the array $$$[3, 1, 0]$$$ is equal to $$$2$$$, and the array $$$[3, 3, 1, 4]$$$ is equal to $$$0$$$.

The first line of input data contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input.  The descriptions of the test cases follow. The first line of the description of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the array $$$a$$$. The second line of the description of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le n$$$) — elements of the array $$$a$$$. It is guaranteed that the sum of the values $$$n$$$ over all test cases in the test does not exceed $$$2\cdot10^5$$$.

For each test case, output $$$n + 1$$$ integer — $$$i$$$-th number is equal to the minimum number of operations for which you can make the array $$$\mathrm{MEX}$$$ equal to $$$i$$$ ($$$0 \le i \le n$$$), or -1 if this cannot be done.

NoteIn the first set of example inputs, $$$n=3$$$:  to get $$$\mathrm{MEX}=0$$$, it is enough to perform one increment: $$$a_1$$$++;  to get $$$\mathrm{MEX}=1$$$, it is enough to perform one increment: $$$a_2$$$++;  $$$\mathrm{MEX}=2$$$ for a given array, so there is no need to perform increments;  it is impossible to get $$$\mathrm{MEX}=3$$$ by performing increments.

package main

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

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

func main() {

	var t int64
	fmt.Fscan(rr, &t)

	for i := int64(0); i < t; i++ {

		var n int64
		fmt.Fscan(rr, &n)

		var pq []int64
		// pq := Create(n + 10)

		cnt := make(map[int64]int64, 0)

		for j := int64(0); j <= n; j++ {
			cnt[j] = 0
		}

		for j := int64(0); j < n; j++ {
			var tmp int64
			fmt.Fscan(rr, &tmp)

			cnt[tmp]++
		}

		// var ans []int64
		ans := make([]int64, n+1)
		prev := int64(0)

		ans1 := int64(0)

		for j := int64(0); j <= n; j++ {

			if ans1 == -1 {
				ans[j] = ans1
				fmt.Fprintf(ww, "%d ", ans[j])
				continue
			}

			ans1 = cnt[j]
			ans1 += prev

			ans[j] = ans1
			fmt.Fprintf(ww, "%d ", ans[j])

			for k := int64(0); k < cnt[j]-1; k++ {
				// pq = pq.Push(j)
				pq = append(pq, j)
			}

			if cnt[j] == 0 {

				val := int64(0)

				if len(pq) == 0 {
					ans1 = -1
					continue
				} else {
					// var lastElem int64
					// pq, lastElem = pq.Pop()

					lastElem := pq[len(pq)-1]

					val = lastElem
					pq = pq[:len(pq)-1]

				}

				prev += (j - val)
			}

		}

		fmt.Fprintln(ww)

	}
	ww.Flush()
}

package main

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

//dp[i]=dp[i-1]+count(i)
//dp[i]等价于0～i-1在， 但是i不在的操作次数
func mex2(nums []int) []int {
	n := len(nums)
	dp := make([]int, n+1)
	for i := 0; i <= n; i++{
		dp[i] = -1
	}
    count := make(map[int]int, 0)
    for _, v := range nums{
    	count[v]++
	}

	stack := make([]int, 0)
	dp[0] = count[0]
	if count[0] > 0 {
		stack = append(stack, 0)
	}else {
		return dp
	}

	prev := 0 //0~i的存在的操作次数
	for i := 1; i <= n; i++ {
		//凑出i-1
		add := 0
		if count[i-1] == 0 {
			if len(stack) == 0 {
				return dp
			}
			closeNum := stack[len(stack)-1]
			add = i - 1 - closeNum
			count[closeNum]--
			if count[closeNum] == 0 {
				stack = stack[:len(stack)-1]
			}
		}else {
			count[i-1]--
			if count[i-1] == 0 {
				stack = stack[:len(stack)-1]
			}
		}
		if count[i] > 0 {
			stack = append(stack, i)
		}

		prev += add
		dp[i] = prev + count[i]
	}
	return dp
}

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := readNInt(in, 1)[0]
	for i := 1; i <= t; i++ {
		n := readNInt(in, 1)[0]
		res := mex2(readNInt(in, n))
		for i := 0; i < len(res)-1; i++ {
			fmt.Fprint(out, res[i])
			fmt.Fprint(out, " ")
		}
		fmt.Fprintln(out, res[len(res)-1])
	}
}

package main

import (
	"fmt"
	"bufio"
	"sort"
	"time"
	//"github.com/emirpasic/gods/utils"
	"os"
)

// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Sort sorts values (in-place) with respect to the given comparator.
//
// Uses Go's sort (hybrid of quicksort for large and then insertion sort for smaller slices).
func Sort(values []interface{}, comparator Comparator) {
	sort.Sort(sortable{values, comparator})
}

type sortable struct {
	values     []interface{}
	comparator Comparator
}

func (s sortable) Len() int {
	return len(s.values)
}
func (s sortable) Swap(i, j int) {
	s.values[i], s.values[j] = s.values[j], s.values[i]
}
func (s sortable) Less(i, j int) bool {
	return s.comparator(s.values[i], s.values[j]) < 0
}

// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Comparator will make type assertion (see IntComparator for example),
// which will panic if a or b are not of the asserted type.
//
// Should return a number:
//    negative , if a < b
//    zero     , if a == b
//    positive , if a > b
type Comparator func(a, b interface{}) int

// StringComparator provides a fast comparison on strings
func StringComparator(a, b interface{}) int {
	s1 := a.(string)
	s2 := b.(string)
	min := len(s2)
	if len(s1) < len(s2) {
		min = len(s1)
	}
	diff := 0
	for i := 0; i < min && diff == 0; i++ {
		diff = int(s1[i]) - int(s2[i])
	}
	if diff == 0 {
		diff = len(s1) - len(s2)
	}
	if diff < 0 {
		return -1
	}
	if diff > 0 {
		return 1
	}
	return 0
}

// IntComparator provides a basic comparison on int
func IntComparator(a, b interface{}) int {
	aAsserted := a.(int)
	bAsserted := b.(int)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Int8Comparator provides a basic comparison on int8
func Int8Comparator(a, b interface{}) int {
	aAsserted := a.(int8)
	bAsserted := b.(int8)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Int16Comparator provides a basic comparison on int16
func Int16Comparator(a, b interface{}) int {
	aAsserted := a.(int16)
	bAsserted := b.(int16)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Int32Comparator provides a basic comparison on int32
func Int32Comparator(a, b interface{}) int {
	aAsserted := a.(int32)
	bAsserted := b.(int32)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Int64Comparator provides a basic comparison on int64
func Int64Comparator(a, b interface{}) int {
	aAsserted := a.(int64)
	bAsserted := b.(int64)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// UIntComparator provides a basic comparison on uint
func UIntComparator(a, b interface{}) int {
	aAsserted := a.(uint)
	bAsserted := b.(uint)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// UInt8Comparator provides a basic comparison on uint8
func UInt8Comparator(a, b interface{}) int {
	aAsserted := a.(uint8)
	bAsserted := b.(uint8)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// UInt16Comparator provides a basic comparison on uint16
func UInt16Comparator(a, b interface{}) int {
	aAsserted := a.(uint16)
	bAsserted := b.(uint16)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// UInt32Comparator provides a basic comparison on uint32
func UInt32Comparator(a, b interface{}) int {
	aAsserted := a.(uint32)
	bAsserted := b.(uint32)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// UInt64Comparator provides a basic comparison on uint64
func UInt64Comparator(a, b interface{}) int {
	aAsserted := a.(uint64)
	bAsserted := b.(uint64)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Float32Comparator provides a basic comparison on float32
func Float32Comparator(a, b interface{}) int {
	aAsserted := a.(float32)
	bAsserted := b.(float32)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Float64Comparator provides a basic comparison on float64
func Float64Comparator(a, b interface{}) int {
	aAsserted := a.(float64)
	bAsserted := b.(float64)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// ByteComparator provides a basic comparison on byte
func ByteComparator(a, b interface{}) int {
	aAsserted := a.(byte)
	bAsserted := b.(byte)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// RuneComparator provides a basic comparison on rune
func RuneComparator(a, b interface{}) int {
	aAsserted := a.(rune)
	bAsserted := b.(rune)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// TimeComparator provides a basic comparison on time.Time
func TimeComparator(a, b interface{}) int {
	aAsserted := a.(time.Time)
	bAsserted := b.(time.Time)

	switch {
	case aAsserted.After(bAsserted):
		return 1
	case aAsserted.Before(bAsserted):
		return -1
	default:
		return 0
	}
}

// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package containers provides core interfaces and functions for data structures.
//
// Container is the base interface for all data structures to implement.
//
// Iterators provide stateful iterators.
//
// Enumerable provides Ruby inspired (each, select, map, find, any?, etc.) container functions.
//
// Serialization provides serializers (marshalers) and deserializers (unmarshalers).

// Container is base interface that all data structures implement.
type Container interface {
	Empty() bool
	Size() int
	Clear()
	Values() []interface{}
	String() string
}

// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package redblacktree implements a red-black tree.
//
// Used by TreeSet and TreeMap.
//
// Structure is not thread safe.
//
// References: http://en.wikipedia.org/wiki/Red%E2%80%93black_tree

type color bool

const (
	black, red color = true, false
)

// Tree holds elements of the red-black tree
type Tree struct {
	Root       *Node
	size       int
	Comparator Comparator
}

// Node is a single element within the tree
type Node struct {
	Key    interface{}
	Value  interface{}
	color  color
	Left   *Node
	Right  *Node
	Parent *Node
}

// NewWith instantiates a red-black tree with the custom comparator.
func NewWith(comparator Comparator) *Tree {
	return &Tree{Comparator: comparator}
}

// NewWithIntComparator instantiates a red-black tree with the IntComparator, i.e. keys are of type int.
func NewWithIntComparator() *Tree {
	return &Tree{Comparator: IntComparator}
}

// NewWithStringComparator instantiates a red-black tree with the StringComparator, i.e. keys are of type string.
func NewWithStringComparator() *Tree {
	return &Tree{Comparator: StringComparator}
}

// Put inserts node into the tree.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Put(key interface{}, value interface{}) {
	var insertedNode *Node
	if tree.Root == nil {
		// Assert key is of comparator's type for initial tree
		tree.Comparator(key, key)
		tree.Root = &Node{Key: key, Value: value, color: red}
		insertedNode = tree.Root
	} else {
		node := tree.Root
		loop := true
		for loop {
			compare := tree.Comparator(key, node.Key)
			switch {
			case compare == 0:
				node.Key = key
				node.Value = value
				return
			case compare < 0:
				if node.Left == nil {
					node.Left = &Node{Key: key, Value: value, color: red}
					insertedNode = node.Left
					loop = false
				} else {
					node = node.Left
				}
			case compare > 0:
				if node.Right == nil {
					node.Right = &Node{Key: key, Value: value, color: red}
					insertedNode = node.Right
					loop = false
				} else {
					node = node.Right
				}
			}
		}
		insertedNode.Parent = node
	}
	tree.insertCase1(insertedNode)
	tree.size++
}

// Get searches the node in the tree by key and returns its value or nil if key is not found in tree.
// Second return parameter is true if key was found, otherwise false.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Get(key interface{}) (value interface{}, found bool) {
	node := tree.lookup(key)
	if node != nil {
		return node.Value, true
	}
	return nil, false
}

// GetNode searches the node in the tree by key and returns its node or nil if key is not found in tree.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) GetNode(key interface{}) *Node {
	return tree.lookup(key)
}

// Remove remove the node from the tree by key.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Remove(key interface{}) {
	var child *Node
	node := tree.lookup(key)
	if node == nil {
		return
	}
	if node.Left != nil && node.Right != nil {
		pred := node.Left.maximumNode()
		node.Key = pred.Key
		node.Value = pred.Value
		node = pred
	}
	if node.Left == nil || node.Right == nil {
		if node.Right == nil {
			child = node.Left
		} else {
			child = node.Right
		}
		if node.color == black {
			node.color = nodeColor(child)
			tree.deleteCase1(node)
		}
		tree.replaceNode(node, child)
		if node.Parent == nil && child != nil {
			child.color = black
		}
	}
	tree.size--
}

// Empty returns true if tree does not contain any nodes
func (tree *Tree) Empty() bool {
	return tree.size == 0
}

// Size returns number of nodes in the tree.
func (tree *Tree) Size() int {
	return tree.size
}

// Size returns the number of elements stored in the subtree.
// Computed dynamically on each call, i.e. the subtree is traversed to count the number of the nodes.
func (node *Node) Size() int {
	if node == nil {
		return 0
	}
	size := 1
	if node.Left != nil {
		size += node.Left.Size()
	}
	if node.Right != nil {
		size += node.Right.Size()
	}
	return size
}

// Keys returns all keys in-order
func (tree *Tree) Keys() []interface{} {
	keys := make([]interface{}, tree.size)
	it := tree.Iterator()
	for i := 0; it.Next(); i++ {
		keys[i] = it.Key()
	}
	return keys
}

// Values returns all values in-order based on the key.
func (tree *Tree) Values() []interface{} {
	values := make([]interface{}, tree.size)
	it := tree.Iterator()
	for i := 0; it.Next(); i++ {
		values[i] = it.Value()
	}
	return values
}

// Left returns the left-most (min) node or nil if tree is empty.
func (tree *Tree) Left() *Node {
	var parent *Node
	current := tree.Root
	for current != nil {
		parent = current
		current = current.Left
	}
	return parent
}

// Right returns the right-most (max) node or nil if tree is empty.
func (tree *Tree) Right() *Node {
	var parent *Node
	current := tree.Root
	for current != nil {
		parent = current
		current = current.Right
	}
	return parent
}

// Floor Finds floor node of the input key, return the floor node or nil if no floor is found.
// Second return parameter is true if floor was found, otherwise false.
//
// Floor node is defined as the largest node that is smaller than or equal to the given node.
// A floor node may not be found, either because the tree is empty, or because
// all nodes in the tree are larger than the given node.
//
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Floor(key interface{}) (floor *Node, found bool) {
	found = false
	node := tree.Root
	for node != nil {
		compare := tree.Comparator(key, node.Key)
		switch {
		case compare == 0:
			return node, true
		case compare < 0:
			node = node.Left
		case compare > 0:
			floor, found = node, true
			node = node.Right
		}
	}
	if found {
		return floor, true
	}
	return nil, false
}

// Ceiling finds ceiling node of the input key, return the ceiling node or nil if no ceiling is found.
// Second return parameter is true if ceiling was found, otherwise false.
//
// Ceiling node is defined as the smallest node that is larger than or equal to the given node.
// A ceiling node may not be found, either because the tree is empty, or because
// all nodes in the tree are smaller than the given node.
//
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Ceiling(key interface{}) (ceiling *Node, found bool) {
	found = false
	node := tree.Root
	for node != nil {
		compare := tree.Comparator(key, node.Key)
		switch {
		case compare == 0:
			return node, true
		case compare < 0:
			ceiling, found = node, true
			node = node.Left
		case compare > 0:
			node = node.Right
		}
	}
	if found {
		return ceiling, true
	}
	return nil, false
}

// Clear removes all nodes from the tree.
func (tree *Tree) Clear() {
	tree.Root = nil
	tree.size = 0
}

// String returns a string representation of container
func (tree *Tree) String() string {
	str := "RedBlackTree\n"
	if !tree.Empty() {
		output(tree.Root, "", true, &str)
	}
	return str
}

func (node *Node) String() string {
	return fmt.Sprintf("%v", node.Key)
}

func output(node *Node, prefix string, isTail bool, str *string) {
	if node.Right != nil {
		newPrefix := prefix
		if isTail {
			newPrefix += "│   "
		} else {
			newPrefix += "    "
		}
		output(node.Right, newPrefix, false, str)
	}
	*str += prefix
	if isTail {
		*str += "└── "
	} else {
		*str += "┌── "
	}
	*str += node.String() + "\n"
	if node.Left != nil {
		newPrefix := prefix
		if isTail {
			newPrefix += "    "
		} else {
			newPrefix += "│   "
		}
		output(node.Left, newPrefix, true, str)
	}
}

func (tree *Tree) lookup(key interface{}) *Node {
	node := tree.Root
	for node != nil {
		compare := tree.Comparator(key, node.Key)
		switch {
		case compare == 0:
			return node
		case compare < 0:
			node = node.Left
		case compare > 0:
			node = node.Right
		}
	}
	return nil
}

func (node *Node) grandparent() *Node {
	if node != nil && node.Parent != nil {
		return node.Parent.Parent
	}
	return nil
}

func (node *Node) uncle() *Node {
	if node == nil || node.Parent == nil || node.Parent.Parent == nil {
		return nil
	}
	return node.Parent.sibling()
}

func (node *Node) sibling() *Node {
	if node == nil || node.Parent == nil {
		return nil
	}
	if node == node.Parent.Left {
		return node.Parent.Right
	}
	return node.Parent.Left
}

func (tree *Tree) rotateLeft(node *Node) {
	right := node.Right
	tree.replaceNode(node, right)
	node.Right = right.Left
	if right.Left != nil {
		right.Left.Parent = node
	}
	right.Left = node
	node.Parent = right
}

func (tree *Tree) rotateRight(node *Node) {
	left := node.Left
	tree.replaceNode(node, left)
	node.Left = left.Right
	if left.Right != nil {
		left.Right.Parent = node
	}
	left.Right = node
	node.Parent = left
}

func (tree *Tree) replaceNode(old *Node, new *Node) {
	if old.Parent == nil {
		tree.Root = new
	} else {
		if old == old.Parent.Left {
			old.Parent.Left = new
		} else {
			old.Parent.Right = new
		}
	}
	if new != nil {
		new.Parent = old.Parent
	}
}

func (tree *Tree) insertCase1(node *Node) {
	if node.Parent == nil {
		node.color = black
	} else {
		tree.insertCase2(node)
	}
}

func (tree *Tree) insertCase2(node *Node) {
	if nodeColor(node.Parent) == black {
		return
	}
	tree.insertCase3(node)
}

func (tree *Tree) insertCase3(node *Node) {
	uncle := node.uncle()
	if nodeColor(uncle) == red {
		node.Parent.color = black
		uncle.color = black
		node.grandparent().color = red
		tree.insertCase1(node.grandparent())
	} else {
		tree.insertCase4(node)
	}
}

func (tree *Tree) insertCase4(node *Node) {
	grandparent := node.grandparent()
	if node == node.Parent.Right && node.Parent == grandparent.Left {
		tree.rotateLeft(node.Parent)
		node = node.Left
	} else if node == node.Parent.Left && node.Parent == grandparent.Right {
		tree.rotateRight(node.Parent)
		node = node.Right
	}
	tree.insertCase5(node)
}

func (tree *Tree) insertCase5(node *Node) {
	node.Parent.color = black
	grandparent := node.grandparent()
	grandparent.color = red
	if node == node.Parent.Left && node.Parent == grandparent.Left {
		tree.rotateRight(grandparent)
	} else if node == node.Parent.Right && node.Parent == grandparent.Right {
		tree.rotateLeft(grandparent)
	}
}

func (node *Node) maximumNode() *Node {
	if node == nil {
		return nil
	}
	for node.Right != nil {
		node = node.Right
	}
	return node
}

func (tree *Tree) deleteCase1(node *Node) {
	if node.Parent == nil {
		return
	}
	tree.deleteCase2(node)
}

func (tree *Tree) deleteCase2(node *Node) {
	sibling := node.sibling()
	if nodeColor(sibling) == red {
		node.Parent.color = red
		sibling.color = black
		if node == node.Parent.Left {
			tree.rotateLeft(node.Parent)
		} else {
			tree.rotateRight(node.Parent)
		}
	}
	tree.deleteCase3(node)
}

func (tree *Tree) deleteCase3(node *Node) {
	sibling := node.sibling()
	if nodeColor(node.Parent) == black &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Left) == black &&
		nodeColor(sibling.Right) == black {
		sibling.color = red
		tree.deleteCase1(node.Parent)
	} else {
		tree.deleteCase4(node)
	}
}

func (tree *Tree) deleteCase4(node *Node) {
	sibling := node.sibling()
	if nodeColor(node.Parent) == red &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Left) == black &&
		nodeColor(sibling.Right) == black {
		sibling.color = red
		node.Parent.color = black
	} else {
		tree.deleteCase5(node)
	}
}

func (tree *Tree) deleteCase5(node *Node) {
	sibling := node.sibling()
	if node == node.Parent.Left &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Left) == red &&
		nodeColor(sibling.Right) == black {
		sibling.color = red
		sibling.Left.color = black
		tree.rotateRight(sibling)
	} else if node == node.Parent.Right &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Right) == red &&
		nodeColor(sibling.Left) == black {
		sibling.color = red
		sibling.Right.color = black
		tree.rotateLeft(sibling)
	}
	tree.deleteCase6(node)
}

func (tree *Tree) deleteCase6(node *Node) {
	sibling := node.sibling()
	sibling.color = nodeColor(node.Parent)
	node.Parent.color = black
	if node == node.Parent.Left && nodeColor(sibling.Right) == red {
		sibling.Right.color = black
		tree.rotateLeft(node.Parent)
	} else if nodeColor(sibling.Left) == red {
		sibling.Left.color = black
		tree.rotateRight(node.Parent)
	}
}

func nodeColor(node *Node) color {
	if node == nil {
		return black
	}
	return node.color
}

// GetSortedValues returns sorted container's elements with respect to the passed comparator.
// Does not affect the ordering of elements within the container.
func GetSortedValues(container Container, comparator Comparator) []interface{} {
	values := container.Values()
	if len(values) < 2 {
		return values
	}
	Sort(values, comparator)
	return values
}

// Iterator holding the iterator's state
type Iterator struct {
	tree     *Tree
	node     *Node
	position position
}

type position byte

const (
	begin, between, end position = 0, 1, 2
)

// Iterator returns a stateful iterator whose elements are key/value pairs.
func (tree *Tree) Iterator() Iterator {
	return Iterator{tree: tree, node: nil, position: begin}
}

// IteratorAt returns a stateful iterator whose elements are key/value pairs that is initialised at a particular node.
func (tree *Tree) IteratorAt(node *Node) Iterator {
	return Iterator{tree: tree, node: node, position: between}
}

// Next moves the iterator to the next element and returns true if there was a next element in the container.
// If Next() returns true, then next element's key and value can be retrieved by Key() and Value().
// If Next() was called for the first time, then it will point the iterator to the first element if it exists.
// Modifies the state of the iterator.
func (iterator *Iterator) Next() bool {
	if iterator.position == end {
		goto end
	}
	if iterator.position == begin {
		left := iterator.tree.Left()
		if left == nil {
			goto end
		}
		iterator.node = left
		goto between
	}
	if iterator.node.Right != nil {
		iterator.node = iterator.node.Right
		for iterator.node.Left != nil {
			iterator.node = iterator.node.Left
		}
		goto between
	}
	for iterator.node.Parent != nil {
		node := iterator.node
		iterator.node = iterator.node.Parent
		if node == iterator.node.Left {
			goto between
		}
	}

end:
	iterator.node = nil
	iterator.position = end
	return false

between:
	iterator.position = between
	return true
}

// Prev moves the iterator to the previous element and returns true if there was a previous element in the container.
// If Prev() returns true, then previous element's key and value can be retrieved by Key() and Value().
// Modifies the state of the iterator.
func (iterator *Iterator) Prev() bool {
	if iterator.position == begin {
		goto begin
	}
	if iterator.position == end {
		right := iterator.tree.Right()
		if right == nil {
			goto begin
		}
		iterator.node = right
		goto between
	}
	if iterator.node.Left != nil {
		iterator.node = iterator.node.Left
		for iterator.node.Right != nil {
			iterator.node = iterator.node.Right
		}
		goto between
	}
	for iterator.node.Parent != nil {
		node := iterator.node
		iterator.node = iterator.node.Parent
		if node == iterator.node.Right {
			goto between
		}
	}

begin:
	iterator.node = nil
	iterator.position = begin
	return false

between:
	iterator.position = between
	return true
}

// Value returns the current element's value.
// Does not modify the state of the iterator.
func (iterator *Iterator) Value() interface{} {
	return iterator.node.Value
}

// Key returns the current element's key.
// Does not modify the state of the iterator.
func (iterator *Iterator) Key() interface{} {
	return iterator.node.Key
}

// Node returns the current element's node.
// Does not modify the state of the iterator.
func (iterator *Iterator) Node() *Node {
	return iterator.node
}

// Begin resets the iterator to its initial state (one-before-first)
// Call Next() to fetch the first element if any.
func (iterator *Iterator) Begin() {
	iterator.node = nil
	iterator.position = begin
}

// End moves the iterator past the last element (one-past-the-end).
// Call Prev() to fetch the last element if any.
func (iterator *Iterator) End() {
	iterator.node = nil
	iterator.position = end
}

// First moves the iterator to the first element and returns true if there was a first element in the container.
// If First() returns true, then first element's key and value can be retrieved by Key() and Value().
// Modifies the state of the iterator
func (iterator *Iterator) First() bool {
	iterator.Begin()
	return iterator.Next()
}

// Last moves the iterator to the last element and returns true if there was a last element in the container.
// If Last() returns true, then last element's key and value can be retrieved by Key() and Value().
// Modifies the state of the iterator.
func (iterator *Iterator) Last() bool {
	iterator.End()
	return iterator.Prev()
}

// NextTo moves the iterator to the next element from current position that satisfies the condition given by the
// passed function, and returns true if there was a next element in the container.
// If NextTo() returns true, then next element's key and value can be retrieved by Key() and Value().
// Modifies the state of the iterator.
func (iterator *Iterator) NextTo(f func(key interface{}, value interface{}) bool) bool {
	for iterator.Next() {
		key, value := iterator.Key(), iterator.Value()
		if f(key, value) {
			return true
		}
	}
	return false
}

// PrevTo moves the iterator to the previous element from current position that satisfies the condition given by the
// passed function, and returns true if there was a next element in the container.
// If PrevTo() returns true, then next element's key and value can be retrieved by Key() and Value().
// Modifies the state of the iterator.
func (iterator *Iterator) PrevTo(f func(key interface{}, value interface{}) bool) bool {
	for iterator.Prev() {
		key, value := iterator.Key(), iterator.Value()
		if f(key, value) {
			return true
		}
	}
	return false
}

type MuliSet struct {
	*Tree
	cntMap  map[interface{}]int
}

func NewMuliSet() *MuliSet{
	return &MuliSet{
		Tree: NewWithIntComparator(),
		cntMap: make(map[interface{}]int),
	}
}

func (m *MuliSet) Put(k interface{}, v interface{}) {
	m.Tree.Put(k, v)
	m.cntMap[k]++
}

func (m *MuliSet) Remove(k interface{}) {
	m.cntMap[k]--
	if m.cntMap[k] == 0 {
		m.Tree.Remove(k)
	}
}

func (m *MuliSet) Count(k interface{}) int {
	return m.cntMap[k]
}

func mex(nums []int) []int {
	n := len(nums)
	dp := make([]int, n+1)
	f := make([]int, n+1)//fi: 变成0～i的最小操作次数
	for i := 0; i <= n; i++{
		f[i] = -1
		dp[i] = -1
	}
	muliSet := NewMuliSet()
	for _, v := range nums {
		muliSet.Put(v, nil)
	}

	dp[0] = muliSet.Count(0)
	_, ok := muliSet.Get(0)
	if ok {
		f[0] = 0
		muliSet.Remove(0)
	}else {
		return dp
	}

	for i := 1; i<=n;i++{
		dp[i] = f[i-1] + muliSet.Count(i)

		_, ok := muliSet.Get(i)
		if ok {
			f[i] = f[i-1]
			muliSet.Remove(i)
		}else {
			node, ok := muliSet.Floor(i)
			if !ok {
				return dp
			}
			f[i] =f[i-1] + i- node.Key.(int)
			muliSet.Remove(node.Key)
		}
	}
	return dp
}

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := readNInt(in, 1)[0]
	for i := 1; i <= t; i++ {
		n := readNInt(in, 1)[0]
		res := mex(readNInt(in,n))
		for i := 0; i< len(res)-1; i++ {
			fmt.Fprint(out, res[i])
			fmt.Fprint(out, " ")
		}
		fmt.Fprintln(out, res[len(res)-1])
	}
}

package main

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

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

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

	var c int
	var n int64
	Fscan(in, &c)
	for ; c > 0; c-- {
		Fscan(in, &n)
		a := make([]int64, n)
		cnt := make(map[int64]int64) //统计每个元素
		for i := range a {
			Fscan(in, &a[i])
			cnt[a[i]]++
		}
		ans := make([]int64, n+1)
		stack := []int64{}
		var total int64
		for i := range ans {
			ans[i] = -1
		}
		for i := int64(0); i <= n; i++ {
			if i > 0 && cnt[i-1] == 0 {
				if len(stack) == 0 {
					break
				}
				top := stack[len(stack)-1]
				stack = stack[:len(stack)-1]
				total += i - top - 1
			}
			ans[i] = total + cnt[i]
			for cnt[i] > 1 {
				stack = append(stack, i)
				cnt[i]--
			}
		}
		for _, v := range ans {
			Fprintf(out, "%d%s", v, " ")
		}
		Fprintf(out, "\n")
	}
}

package main

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

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

// 0 1 2 3 4 3 2
// 1 1 2 2 1 0 2 6

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

	var T, n, x int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)

		c := make([]int, n+1)
		for i := 0; i < n; i++ {
			Fscan(in, &x)
			c[x]++
		}

		st := []int{}
		ans := make([]int, n+1)
		do := 0
		for i := 0; i <= n; i++ {
			// cal
			ans[i] = do + c[i]

			// construct
			if i < n && c[i] == 0 {
				if len(st) == 0 {
					for j := i + 1; j <= n; j++ {
						ans[j] = -1
					}
					break
				}
				x := st[len(st)-1]
				st = st[:len(st)-1]
				do += i - x
				continue
			}
			for j := 1; j < c[i]; j++ {
				st = append(st, i)
			}
		}

		for _, v := range ans {
			Fprintf(out, "%d ", v)
		}
		Fprintln(out, "")
	}
}

package main

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

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

// 0 1 2 3 4 3 2
// 1 1 2 2 1 0 2 6

type hl []int

func (h hl) Len() int            { return len(h) }
func (h hl) Less(i, j int) bool  { return h[i] > h[j] } // 大顶堆
func (h hl) Swap(i, j int)       { h[i], h[j] = h[j], h[i] }
func (h *hl) Push(v interface{}) { *h = append(*h, v.(int)) }
func (h *hl) Pop() interface{} {
	a := *h
	v := a[len(a)-1]
	*h = a[:len(a)-1]
	return v
}

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

	var T, n, x int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)

		c := make([]int, n+1)
		for i := 0; i < n; i++ {
			Fscan(in, &x)
			c[x]++
		}

		h := &hl{}
		ans := make([]int, n+1)
		do := 0
		for i := 0; i <= n; i++ {
			// cal
			ans[i] = do + c[i]

			//Fprintln(out, i, t, h.Len())

			// construct
			if i < n && c[i] == 0 {
				if h.Len() == 0 {
					for j := i + 1; j <= n; j++ {
						ans[j] = -1
					}
					break
				}
				x := heap.Pop(h).(int)
				do += i - x
				continue
			}
			for j := 1; j < c[i]; j++ {
				heap.Push(h, i)
			}
		}

		for _, v := range ans {
			Fprintf(out, "%d ", v)
		}
		Fprintln(out, "")
	}
}

package main

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

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

	var T, n, v int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		cnt := make([]int, n+1)
		for i := 0; i < n; i++ {
			Fscan(in, &v)
			cnt[v]++
		}
		Fprint(out, cnt[0], " ")
		s, ex, fill := 0, []int{}, int64(0)
		for i, c := range cnt[:n] {
			if s += c; s <= i {
				Fprint(out, strings.Repeat("-1 ", n-i))
				break
			}
			if c == 0 {
				fill += int64(i - ex[len(ex)-1])
				ex = ex[:len(ex)-1]
			}
			Fprint(out, fill+int64(cnt[i+1]), " ")
			for ; c > 1; c-- {
				ex = append(ex, i)
			}
		}
		Fprintln(out)
	}
}

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

package main

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

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

	var T, n, v int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		cnt := make([]int, n+1)
		for i := 0; i < n; i++ {
			Fscan(in, &v)
			cnt[v]++
		}
		Fprint(out, cnt[0], " ")
		s, ex, fill := 0, []int{}, int64(0)
		for i, c := range cnt[:n] {
			if s += c; s <= i {
				Fprint(out, strings.Repeat("-1 ", n-i))
				break
			}
			if c == 0 {
				fill += int64(i - ex[len(ex)-1])
				ex = ex[:len(ex)-1]
			}
			Fprint(out, fill+int64(cnt[i+1]), " ")
			for ; c > 1; c-- {
				ex = append(ex, i)
			}
		}
		Fprintln(out)
	}
}

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

package main

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

/*
* lets try some fancy go :)

sort existing numbers, iterate starting from 0
if current number eq it then ok, else if current number < it
put number on stack else take number from stack, ans+=diff.

Also we need to consider that we need to increase all
numbers eq it.
*/
func main() {
    re, w, e := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout), bufio.NewWriter(os.Stderr)
    defer w.Flush()
    defer e.Flush()

    var t int=0
    Fscan(re, &t)

    for i:=0; i<t; i++ {
        var n int
        Fscan(re, &n)

        var a=make([]int,n)
        var f=make([]int,n+1)

        for i:=0; i<n; i++ {
            Fscan(re, &a[i])
            f[a[i]]++
        }

        sort.Ints(a);
        st:=[]int{}
        var ans int64=0
        ok:=true;

        for i:=0; i<=n; i++ {
            if !ok {
                Fprintf(w, "-1 ")
                continue;
            }

            if f[i]>0 {
                Fprintf(w, "%d ", ans+int64(f[i]))
                for j:=1; j<f[i]; j++ {
                    st=append(st, i)
                }
            } else {
                Fprintf(w, "%d ", ans)
                if(len(st)==0) {
                    ok=false
                } else {
                    b:=st[len(st)-1]
                    ans+=int64(i-b)
                    st=st[:len(st)-1]
                }
            }
        }
        Fprintf(w,"\n")
    }
}

package main

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

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

var (
	T    int
	n    int
	a    []int
	last []int
)

func getOne(i int) int {
	if i < 0 {
		return -1
	}
	if a[i] <= 1 {
		k := getOne(last[i])
		last[i] = k
		return k
	}
	return i
}

func solve(i int) (int64, bool) {
	k := getOne(i)
	if k < 0 {
		return 0, false
	}
	a[k]--
	a[i]++
	return int64(i - k), true
}

func Init() {
	a = make([]int, n+1)
	last = make([]int, n+1)
}

func main() {
	_, _ = fmt.Fscan(rr, &T)
	for iCase := 0; iCase < T; iCase++ {
		_, _ = fmt.Fscan(rr, &n)

		Init()

		for i := 0; i < n; i++ {
			var t int
			_, _ = fmt.Fscan(rr, &t)
			a[t]++
		}

		base := int64(-1)
		for i := 0; i <= n; i++ {
			last[i] = int(base)
			if a[i] > 1 {
				base = int64(i)
			}
		}

		base = 0
		for i := 0; i <= n; i++ {
			if base < 0 {
				_, _ = fmt.Fprintf(ww, "%d ", -1)
			} else if base >= 0 && a[i] > 0 {
				_, _ = fmt.Fprintf(ww, "%d ", base+int64(a[i]))
			} else {
				_, _ = fmt.Fprintf(ww, "%d ", base)
				t, flag := solve(i)
				if flag {
					base += t
				} else {
					base = -1
				}
			}
		}
		_, _ = fmt.Fprintln(ww)
	}
	_ = ww.Flush()
}

package main

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

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

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

func redirectInputToFile(r *bufio.Reader, fp string) {
	f, err := os.Open(fp)
	if err != nil {
		panic(err)
	}
	r.Reset(f)
}

func main() {
	defer writer.Flush()
	// redirectInputToFile(reader, "input.txt")

	T := 1
	scan(&T)
	for t := 0; t < T; t++ {
		solve()
	}
}

func solve() {
	var n int64
	scan(&n)
	a := make([]int64, n)
	cnt := make([]int64, n+1)
	for i := range a {
		scan(&a[i])
		cnt[a[i]]++
	}

	frees := [][2]int64{}
	prevok, prevres := true, int64(0)
	for i := int64(0); i <= n; i++ {
		if !prevok {
			printf("-1 ")
			continue
		}
		printf("%v ", prevres+cnt[i])

		if cnt[i] > 1 {
			frees = append(frees, [2]int64{cnt[i] - 1, i})
			continue
		}
		if cnt[i] == 1 {
			continue
		}
		if len(frees) == 0 {
			prevok = false
			continue
		}
		prevres += i - frees[len(frees)-1][1]
		frees[len(frees)-1][0]--
		if frees[len(frees)-1][0] == 0 {
			frees = frees[:len(frees)-1]
		}
	}
	printf("\n")
}

package main

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

func solve() {
	f := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	N, n, p := 0, 0, 0
	fmt.Fscan(f, &N)
	for i := 0; i < N; i++ {
		fmt.Fscan(f, &n)
		stack, sum, o, count, mex := list.New(), int64(0), []int{}, make([]int, n+1), make([]int64, n+1)
		for j := 0; j < n; j++ {
			fmt.Fscan(f, &p)
			o = append(o, p)
			count[p]++
			mex[j] = -1
		}
		mex[n] = -1
		sort.Ints(o)
		for i := 0; i <= n; i++ {
			if i > 0 && count[i-1] == 0 {
				if stack.Len() == 0 {
					break
				}
				top := stack.Front()
				stack.Remove(top)
				sum += int64(i - top.Value.(int) - 1)
			}
			mex[i] = int64(sum) + int64(count[i])
			for i > 0 && count[i-1] > 1 {
				stack.PushFront(i - 1)
				count[i-1]--
			}
		}
		for _, v := range mex {
			fmt.Fprint(w, v, " ")
		}
		fmt.Fprintln(w, "")
	}
	w.Flush()
}

func main() {
	solve()
}

package main

import (
	"bufio"
	. "fmt"
	"io"

	//"math"
	"os"
	//"sort"
)

var stk [200010]int

func solve(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	var T int
	Fscan(in, &T)
	for ; T > 0; T-- {
		var n int
		Fscan(in, &n)
		a := make([]int, n)
		cnt := make([]int, n+10)
		for i := 0; i < n; i++ {
			Fscan(in, &a[i])
			cnt[a[i]]++
		}
		sum := 0
		ok := true

		tt := 0
		for i := 0; i <= n; i++ {
			if ok {
				Fprint(out, sum+cnt[i], " ")
			} else {
				Fprint(out, -1, " ")
			}
			if cnt[i] > 0 {
				cnt[i]--
				for ; cnt[i] >= 1; cnt[i]-- {
					tt++
					stk[tt] = i
				}
			} else {
				if tt > 0 {
					x := stk[tt]
					tt--
					sum += i - x
				} else {
					ok = false
				}
			}
		}
		Fprintln(out)
	}

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

package main

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

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

    var T, n, v int
    for Fscan(in, &T); T > 0; T-- {
    	Fscan(in, &n)
    	cnt := make([]int, n+1)
    	for i := 0; i < n; i++ {
    		Fscan(in, &v)
    		cnt[v]++
    	}
    	Fprint(out, cnt[0], " ")
    	s, ex, fill := 0, []int{}, int64(0)
    	for i, c := range cnt[:n] {
    		if s += c; s <= i {
    			Fprint(out, strings.Repeat("-1 ", n-i))
    			break
    		}
    		if c == 0 {
    			fill += int64(i - ex[len(ex)-1])
    			ex = ex[:len(ex)-1]
    		}
    		Fprint(out, fill+int64(cnt[i+1]), " ")
    		for ; c > 1; c-- {
    			ex = append(ex, i)
    		}
    	}
    	Fprintln(out)
    }
}

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

package main

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

/*
https://codeforces.com/problemset/problem/1619/E

@所有人  【腾讯文档】灵茶の试炼
https://docs.qq.com/sheet/DWGFoRGVZRmxNaXFz

输入 t (≤1e4) 表示 t 组数据，每组数据输入 n(≤2e5) 和一个长为 n 的数组 a (0≤a[i]≤n)。
	所有数据的 n 之和不超过 2e5。

每次操作，你可以把数组中的一个数加一。
定义 mex(a) 表示不在 a 中的最小非负整数。 // 0 -> n+1
定义 f(i) 表示使 mex(a) = i 的最小操作次数。如果无法做到，则 f(i) = -1。
输出 n+1 个数：f(0), f(1), ..., f(n)。

输入
5
3
0 1 3
7
0 1 2 3 4 3 2
4
3 0 0 0
7
4 6 2 3 5 0 5
5
4 0 1 0 4
输出
1 1 0 -1
1 1 2 2 1 0 2 6
3 0 1 4 3
1 0 -1 -1 -1 -1 -1 -1
2 1 0 2 -1 -1
*/

type Heap [][2]int

func (a Heap) Len() int           { return len(a) }
func (a Heap) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a Heap) Less(i, j int) bool { return a[i][0] > a[j][0] }
func (a *Heap) Push(v interface{}) {
	*a = append(*a, v.([2]int))
	return
}
func (a *Heap) Pop() (v interface{}) {
	l := len(*a)
	v = (*a)[l-1]
	(*a) = (*a)[:l-1]
	return
}

func solution(arr []int) (res []int) {
	n := len(arr)
	cnts := make([]int, n+1)
	for _, v := range arr {
		cnts[v]++
	}
	var h Heap
	for i, cost := 0, 0; i <= n; i++ {
		if len(res) > 0 && res[len(res)-1] == -1 { // 之前都达不到，现在更加达不到
			res = append(res, -1)
			continue
		}
		c := cnts[i]                 // 当前数字全部要加1
		if i > 0 && cnts[i-1] == 0 { // 需要填坑
			if h.Len() == 0 { // 填坑失败
				res = append(res, -1)
				continue
			}
			node := heap.Pop(&h).([2]int)
			cost += i - 1 - node[0]
			node[1]--
			if node[1] > 0 {
				heap.Push(&h, node)
			}
		}
		if cnts[i] > 1 {
			heap.Push(&h, [2]int{i, cnts[i] - 1})
		}
		res = append(res, cost+c)
	}
	return
}

func f(arr []int) {
	res := solution(arr)
	bl := []byte{}
	for _, e := range res {
		bl = append(bl, []byte(strconv.Itoa(e))...)
		bl = append(bl, ' ')
	}
	fmt.Println(string(bl))
}

func ReadNInt(in *bufio.Reader, n int) (arr []int) {
	for i := 0; i < n; i++ {
		var x int
		fmt.Fscan(in, &x)
		arr = append(arr, x)
	}
	return
}

func main() {
	in := bufio.NewReader(os.Stdin)
	t := ReadNInt(in, 1)[0]
	for i := 0; i < t; i++ {
		n := ReadNInt(in, 1)[0]
		f(ReadNInt(in, n))
	}
	return
	fmt.Println(solution([]int{0, 1, 3}), "1 1 0 -1")
	//return
	fmt.Println(solution([]int{0, 1, 2, 3, 4, 3, 2}), "1 1 2 2 1 0 2 6")
	fmt.Println(solution([]int{3, 0, 0, 0}), "3 0 1 4 3")
	fmt.Println(solution([]int{4, 6, 2, 3, 5, 0, 5}), "1 0 -1 -1 -1 -1 -1 -1")
	fmt.Println(solution([]int{4, 0, 1, 0, 4}), "2 1 0 2 -1 -1")
}

package main

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

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

func CF1619E(in io.Reader, out io.Writer) {
	r := bufio.NewReader(in)
	w := bufio.NewWriter(out)
	defer w.Flush()

	var T, n, v int
	for fmt.Fscan(r, &T); T > 0; T-- {
		fmt.Fscan(r, &n)
		cnt := make([]int, n+1)
		for i := 0; i < n; i++ {
			fmt.Fscan(r, &v)
			cnt[v]++
		}
		fmt.Fprint(w, cnt[0], " ")
		s, ex, fill := 0, []int{}, int64(0)
		for i, c := range cnt[:n] {
			if s += c; s <= i {
				fmt.Fprint(w, strings.Repeat("-1 ", n-i))
				break
			}
			if c == 0 {
				fill += int64(i - ex[len(ex)-1])
				ex = ex[:len(ex)-1]
			}
			fmt.Fprint(w, fill+int64(cnt[i+1]), " ")
			for ; c > 1; c-- {
				ex = append(ex, i)
			}
		}
		fmt.Fprintln(w)
	}

}

type pair struct {
	cost float64
	to   int
}
type hp []pair

func (h hp) Len() int { return len(h) }
func (h hp) Less(i, j int) bool {
	return h[i].cost < h[j].cost || (h[i].cost == h[j].cost && h[i].to < h[j].to)
}
func (h hp) Swap(i, j int)       { h[i], h[j] = h[j], h[i] }
func (h *hp) Push(v interface{}) { *h = append(*h, v.(pair)) }
func (h *hp) Pop() interface{}   { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }

func minFloat(a, b float64) float64 {
	if a < b {
		return a
	}
	return b
}

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

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

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

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

package main

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

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

type stack struct {
	List    []int
	Pointer int
}

func (s stack) Push(n int) stack {
	news := s.List
	news[s.Pointer] = n

	s.List = news
	s.Pointer++
	return s
}

func (s stack) Pop() (stack, int) {

	s.Pointer--
	return s, s.List[s.Pointer]
}

func Create(n int) stack {
	s := stack{}
	s.List = make([]int, n)
	s.Pointer = 0
	return s
}

func main() {

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

	for i := 0; i < t; i++ {

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

		var pq []int
		// pq := Create(n + 10)

		cnt := make(map[int]int, 0)

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

		for j := 0; j < n; j++ {
			var tmp int
			fmt.Fscan(rr, &tmp)

			cnt[tmp]++
		}

		// var ans []int
		ans := make([]int, n+1)
		prev := 0

		ans1 := 0

		for j := 0; j <= n; j++ {

			if ans1 == -1 {
				ans[j] = ans1
				fmt.Fprintf(ww, "%d ", ans[j])
				continue
			}

			ans1 = cnt[j]
			ans1 += prev

			ans[j] = ans1
			fmt.Fprintf(ww, "%d ", ans[j])

			for k := 0; k < cnt[j]-1; k++ {
				// pq = pq.Push(j)
				pq = append(pq, j)
			}

			if cnt[j] == 0 {

				val := 0

				if len(pq) == 0 {
					ans1 = -1
					continue
				} else {
					// var lastElem int
					// pq, lastElem = pq.Pop()

					lastElem := pq[len(pq)-1]

					val = lastElem
					pq = pq[:len(pq)-1]

				}

				prev += (j - val)
			}

		}

		fmt.Fprintln(ww)

	}
	ww.Flush()
}

package main

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

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

type stack struct {
	List    []int
	Pointer int
}

func (s stack) Push(n int) stack {
	news := s.List
	news[s.Pointer] = n

	s.List = news
	s.Pointer++
	return s
}

func (s stack) Pop() (stack, int) {

	s.Pointer--
	return s, s.List[s.Pointer]
}

func Create(n int) stack {
	s := stack{}
	s.List = make([]int, n)
	s.Pointer = 0
	return s
}

func main() {

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

	for i := 0; i < t; i++ {

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

		// var pq []int
		pq := Create(n + 10)

		cnt := make(map[int]int, 0)

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

		for j := 0; j < n; j++ {
			var tmp int
			fmt.Fscan(rr, &tmp)

			cnt[tmp]++
		}

		// var ans []int
		ans := make([]int, n+1)
		prev := 0

		ans1 := 0

		for j := 0; j <= n; j++ {

			if ans1 == -1 {
				ans[j] = ans1
				fmt.Fprintf(ww, "%d ", ans[j])
				continue
			}

			ans1 = cnt[j]
			ans1 += prev

			ans[j] = ans1
			fmt.Fprintf(ww, "%d ", ans[j])

			for k := 0; k < cnt[j]-1; k++ {
				pq = pq.Push(j)
			}

			if cnt[j] == 0 {

				val := 0

				if pq.Pointer == 0 {
					ans1 = -1
					continue
				} else {
					var lastElem int
					pq, lastElem = pq.Pop()

					// lastElem := pq[len(pq)-1]

					val = lastElem
					// pq = pq[:len(pq)-1]

				}

				prev += (j - val)
			}

		}

		// var ans2 string
		// for j := 0; j < len(ans); j++ {
		// 	ans2 += strconv.Itoa(ans[j]) + " "
		// }
		fmt.Fprintln(ww)

	}
	ww.Flush()
}

package main

import (
	"fmt"
	"sort"
)

func main() {

	var t int
	fmt.Scanln(&t)

	// prevList1 := make(map[int]int, 0)
	// prevList1[1] = 2
	// prevList1[2] = 2

	// fmt.Println(get(prevList1))

	for i := 0; i < t; i++ {

		var n int
		fmt.Scanln(&n)

		var a []int

		prevList := make(map[int]int, 0)
		cnt := make(map[int]int, 0)

		for j := 0; j <= n; j++ {
			cnt[j] = 0
			// prevList[j] = 0
		}

		for j := 0; j < n; j++ {
			var tmp int
			fmt.Scan(&tmp)

			cnt[tmp]++

			a = append(a, tmp)
		}

		var ans []int
		prev := 0

		ans1 := 0

		for j := 0; j <= n; j++ {

			if ans1 == -1 {
				ans = append(ans, ans1)
				continue
			}

			ans1 = cnt[j]
			ans1 += prev

			ans = append(ans, ans1)

			if cnt[j] > 1 {
				prevList[j] = cnt[j] - 1
			}

			if cnt[j] == 0 {
				val := check(prevList)
				if val == -1 {
					ans1 = -1
				}

				prev += (j - val)
			}

			// if len(ans) > 0 {
			// 	if ans[len(ans)-1] == -1 {
			// 		ans1 = -1
			// 	}
			// }

		}
		// fmt.Println(cnt)
		// fmt.Println(ans)
		for j := 0; j < len(ans); j++ {
			if j < len(ans)-1 {
				fmt.Print(ans[j], " ")
			} else {
				fmt.Println(ans[j], " ")
			}
		}

	}
}

func get(prevList map[int]int) (int, int) {
	if len(prevList) == 0 {
		return -1, -1
	}

	var keys []int

	for j := range prevList {
		keys = append(keys, j)
		// return j, k
	}

	sort.Ints(keys)

	news := keys[len(keys)-1]

	return news, prevList[news]
}

func check(prevList map[int]int) int {

	for j := 0; j < 1; j-- {
		a, b := get(prevList)
		if a == -1 {
			return -1
		}

		if b != 0 {
			prevList[a]--
			return a
		}

		delete(prevList, a)

		if len(prevList) == 0 {
			return -1
		}
	}
	return -1

}

package main

import (
	"fmt"
	"sort"
)

func main() {

	var t int
	fmt.Scanln(&t)

	// prevList1 := make(map[int]int, 0)
	// prevList1[1] = 2
	// prevList1[2] = 2

	// fmt.Println(get(prevList1))

	for i := 0; i < t; i++ {

		var n int
		fmt.Scanln(&n)

		var a []int

		prevList := make(map[int]int, 0)
		cnt := make(map[int]int, 0)

		for j := 0; j <= n; j++ {
			cnt[j] = 0
			// prevList[j] = 0
		}

		for j := 0; j < n; j++ {
			var tmp int
			fmt.Scan(&tmp)

			cnt[tmp]++

			a = append(a, tmp)
		}

		var ans []int
		prev := 0

		ans1 := 0

		for j := 0; j <= n; j++ {

			if ans1 == -1 {
				ans = append(ans, ans1)
				continue
			}

			ans1 = cnt[j]
			ans1 += prev

			ans = append(ans, ans1)

			if cnt[j] > 1 {
				prevList[j] = cnt[j] - 1
			}

			if cnt[j] == 0 {
				val := check(prevList)
				if val == -1 {
					ans1 = -1
				}

				prev += (j - val)
			}

			// if len(ans) > 0 {
			// 	if ans[len(ans)-1] == -1 {
			// 		ans1 = -1
			// 	}
			// }

		}
		// fmt.Println(cnt)
		// fmt.Println(ans)
		for j := 0; j < len(ans); j++ {
			if j < len(ans)-1 {
				fmt.Print(ans[j], " ")
			} else {
				fmt.Println(ans[j])
			}
		}

	}
}

func get(prevList map[int]int) (int, int) {
	if len(prevList) == 0 {
		return -1, -1
	}

	var keys []int

	for j := range prevList {
		keys = append(keys, j)
		// return j, k
	}

	sort.Ints(keys)

	news := keys[len(keys)-1]

	return news, prevList[news]
}

func check(prevList map[int]int) int {

	for j := 0; j < 1; j-- {
		a, b := get(prevList)
		if a == -1 {
			return -1
		}

		if b != 0 {
			prevList[a]--
			return a
		}

		delete(prevList, a)

		if len(prevList) == 0 {
			return -1
		}
	}
	return -1

}

package main

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

//dp[i]=dp[i-1]+count(i)
//dp[i]等价于0～i-1在， 但是i不在的操作次数
func mex(nums []int) []int {
	n := len(nums)
	dp := make([]int, n+1)
	for i:=0; i<=n; i++{
		dp[i] = -1
	}
    count := make(map[int]int, 0)
    for _, v := range nums{
    	count[v]++
	}

	stack := make([]int, 0)
	dp[0] = 0
	if count[0] > 0 {
		count[0]--
		if count[0] > 0 {
			stack = append(stack, 0)
		}
	}else {
		return dp
	}
	for i := 1; i <= n; i++ {
		//凑出i-1
		add := 0
		if count[i-1] == 0 {
			if len(stack) == 0 {
				return dp
			}
			closeNum := stack[len(stack)-1]
			add = i-1-closeNum
			count[closeNum]--
			if count[closeNum] == 0 {
				stack = stack[:len(stack)-1]
			}
		}
		if count[i] > 0 {
			stack = append(stack, i)
		}
		dp[i] = dp[i-1] + count[i] + add
	}

	return dp
}

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := readNInt(in, 1)[0]
	for i := 1; i <= t; i++ {
		n := readNInt(in, 1)[0]
		res := mex(readNInt(in, n))
		for i := 0; i < len(res)-1; i++ {
			fmt.Fprint(out, res[i])
			fmt.Fprint(out, " ")
		}
		fmt.Fprintln(out, res[len(res)-1])
	}
}

package main

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

//dp[i]=dp[i-1]+count(i)
//dp[i]等价于0～i-1在， 但是i不在的操作次数
func mex(nums []int) []int {
	n := len(nums)
	dp := make([]int, n+1)
	for i:=0;i<=n;i++{
		dp[i] = -1
	}
    count := make(map[int]int, 0)
    for _, v := range nums{
    	count[v]++
	}

	stack := make([]int, 0)
	dp[0] = 0
	if count[0] > 0 {
		count[0]--
		if count[0] > 0 {
			stack = append(stack, 0)
		}
	}else {
		return dp
	}
	for i := 1; i <= n; i++ {
		//凑出i-1
		add := 0
		if count[i-1] == 0 {
			if len(stack) == 0 {
				return dp
			}
			closeNum := stack[len(stack)-1]
			add = i-1-closeNum
			count[closeNum]--
			if count[closeNum] == 0 {
				stack = stack[:len(stack)-1]
			}
		}
		if count[i] > 0 {
			stack = append(stack, i)
		}
		dp[i] = dp[i-1] + count[i] + add
	}

	return dp
}

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := readNInt(in, 1)[0]
	for i := 1; i <= t; i++ {
		n := readNInt(in, 1)[0]
		res := mex(readNInt(in, n))
		for i := 0; i < len(res)-1; i++ {
			fmt.Fprint(out, res[i])
			fmt.Fprint(out, " ")
		}
		fmt.Fprintln(out, res[len(res)-1])
	}
}

package main

import (
	"fmt"
	"bufio"
	"sort"
	"time"
	//"github.com/emirpasic/gods/utils"
	"os"
)

// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Sort sorts values (in-place) with respect to the given comparator.
//
// Uses Go's sort (hybrid of quicksort for large and then insertion sort for smaller slices).
func Sort(values []interface{}, comparator Comparator) {
	sort.Sort(sortable{values, comparator})
}

type sortable struct {
	values     []interface{}
	comparator Comparator
}

func (s sortable) Len() int {
	return len(s.values)
}
func (s sortable) Swap(i, j int) {
	s.values[i], s.values[j] = s.values[j], s.values[i]
}
func (s sortable) Less(i, j int) bool {
	return s.comparator(s.values[i], s.values[j]) < 0
}

// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Comparator will make type assertion (see IntComparator for example),
// which will panic if a or b are not of the asserted type.
//
// Should return a number:
//    negative , if a < b
//    zero     , if a == b
//    positive , if a > b
type Comparator func(a, b interface{}) int

// StringComparator provides a fast comparison on strings
func StringComparator(a, b interface{}) int {
	s1 := a.(string)
	s2 := b.(string)
	min := len(s2)
	if len(s1) < len(s2) {
		min = len(s1)
	}
	diff := 0
	for i := 0; i < min && diff == 0; i++ {
		diff = int(s1[i]) - int(s2[i])
	}
	if diff == 0 {
		diff = len(s1) - len(s2)
	}
	if diff < 0 {
		return -1
	}
	if diff > 0 {
		return 1
	}
	return 0
}

// IntComparator provides a basic comparison on int
func IntComparator(a, b interface{}) int {
	aAsserted := a.(int)
	bAsserted := b.(int)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Int8Comparator provides a basic comparison on int8
func Int8Comparator(a, b interface{}) int {
	aAsserted := a.(int8)
	bAsserted := b.(int8)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Int16Comparator provides a basic comparison on int16
func Int16Comparator(a, b interface{}) int {
	aAsserted := a.(int16)
	bAsserted := b.(int16)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Int32Comparator provides a basic comparison on int32
func Int32Comparator(a, b interface{}) int {
	aAsserted := a.(int32)
	bAsserted := b.(int32)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Int64Comparator provides a basic comparison on int64
func Int64Comparator(a, b interface{}) int {
	aAsserted := a.(int64)
	bAsserted := b.(int64)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// UIntComparator provides a basic comparison on uint
func UIntComparator(a, b interface{}) int {
	aAsserted := a.(uint)
	bAsserted := b.(uint)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// UInt8Comparator provides a basic comparison on uint8
func UInt8Comparator(a, b interface{}) int {
	aAsserted := a.(uint8)
	bAsserted := b.(uint8)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// UInt16Comparator provides a basic comparison on uint16
func UInt16Comparator(a, b interface{}) int {
	aAsserted := a.(uint16)
	bAsserted := b.(uint16)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// UInt32Comparator provides a basic comparison on uint32
func UInt32Comparator(a, b interface{}) int {
	aAsserted := a.(uint32)
	bAsserted := b.(uint32)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// UInt64Comparator provides a basic comparison on uint64
func UInt64Comparator(a, b interface{}) int {
	aAsserted := a.(uint64)
	bAsserted := b.(uint64)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Float32Comparator provides a basic comparison on float32
func Float32Comparator(a, b interface{}) int {
	aAsserted := a.(float32)
	bAsserted := b.(float32)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Float64Comparator provides a basic comparison on float64
func Float64Comparator(a, b interface{}) int {
	aAsserted := a.(float64)
	bAsserted := b.(float64)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// ByteComparator provides a basic comparison on byte
func ByteComparator(a, b interface{}) int {
	aAsserted := a.(byte)
	bAsserted := b.(byte)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// RuneComparator provides a basic comparison on rune
func RuneComparator(a, b interface{}) int {
	aAsserted := a.(rune)
	bAsserted := b.(rune)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// TimeComparator provides a basic comparison on time.Time
func TimeComparator(a, b interface{}) int {
	aAsserted := a.(time.Time)
	bAsserted := b.(time.Time)

	switch {
	case aAsserted.After(bAsserted):
		return 1
	case aAsserted.Before(bAsserted):
		return -1
	default:
		return 0
	}
}

// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package containers provides core interfaces and functions for data structures.
//
// Container is the base interface for all data structures to implement.
//
// Iterators provide stateful iterators.
//
// Enumerable provides Ruby inspired (each, select, map, find, any?, etc.) container functions.
//
// Serialization provides serializers (marshalers) and deserializers (unmarshalers).

// Container is base interface that all data structures implement.
type Container interface {
	Empty() bool
	Size() int
	Clear()
	Values() []interface{}
	String() string
}

// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package redblacktree implements a red-black tree.
//
// Used by TreeSet and TreeMap.
//
// Structure is not thread safe.
//
// References: http://en.wikipedia.org/wiki/Red%E2%80%93black_tree

type color bool

const (
	black, red color = true, false
)

// Tree holds elements of the red-black tree
type Tree struct {
	Root       *Node
	size       int
	Comparator Comparator
}

// Node is a single element within the tree
type Node struct {
	Key    interface{}
	Value  interface{}
	color  color
	Left   *Node
	Right  *Node
	Parent *Node
}

// NewWith instantiates a red-black tree with the custom comparator.
func NewWith(comparator Comparator) *Tree {
	return &Tree{Comparator: comparator}
}

// NewWithIntComparator instantiates a red-black tree with the IntComparator, i.e. keys are of type int.
func NewWithIntComparator() *Tree {
	return &Tree{Comparator: IntComparator}
}

// NewWithStringComparator instantiates a red-black tree with the StringComparator, i.e. keys are of type string.
func NewWithStringComparator() *Tree {
	return &Tree{Comparator: StringComparator}
}

// Put inserts node into the tree.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Put(key interface{}, value interface{}) {
	var insertedNode *Node
	if tree.Root == nil {
		// Assert key is of comparator's type for initial tree
		tree.Comparator(key, key)
		tree.Root = &Node{Key: key, Value: value, color: red}
		insertedNode = tree.Root
	} else {
		node := tree.Root
		loop := true
		for loop {
			compare := tree.Comparator(key, node.Key)
			switch {
			case compare == 0:
				node.Key = key
				node.Value = value
				return
			case compare < 0:
				if node.Left == nil {
					node.Left = &Node{Key: key, Value: value, color: red}
					insertedNode = node.Left
					loop = false
				} else {
					node = node.Left
				}
			case compare > 0:
				if node.Right == nil {
					node.Right = &Node{Key: key, Value: value, color: red}
					insertedNode = node.Right
					loop = false
				} else {
					node = node.Right
				}
			}
		}
		insertedNode.Parent = node
	}
	tree.insertCase1(insertedNode)
	tree.size++
}

// Get searches the node in the tree by key and returns its value or nil if key is not found in tree.
// Second return parameter is true if key was found, otherwise false.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Get(key interface{}) (value interface{}, found bool) {
	node := tree.lookup(key)
	if node != nil {
		return node.Value, true
	}
	return nil, false
}

// GetNode searches the node in the tree by key and returns its node or nil if key is not found in tree.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) GetNode(key interface{}) *Node {
	return tree.lookup(key)
}

// Remove remove the node from the tree by key.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Remove(key interface{}) {
	var child *Node
	node := tree.lookup(key)
	if node == nil {
		return
	}
	if node.Left != nil && node.Right != nil {
		pred := node.Left.maximumNode()
		node.Key = pred.Key
		node.Value = pred.Value
		node = pred
	}
	if node.Left == nil || node.Right == nil {
		if node.Right == nil {
			child = node.Left
		} else {
			child = node.Right
		}
		if node.color == black {
			node.color = nodeColor(child)
			tree.deleteCase1(node)
		}
		tree.replaceNode(node, child)
		if node.Parent == nil && child != nil {
			child.color = black
		}
	}
	tree.size--
}

// Empty returns true if tree does not contain any nodes
func (tree *Tree) Empty() bool {
	return tree.size == 0
}

// Size returns number of nodes in the tree.
func (tree *Tree) Size() int {
	return tree.size
}

// Size returns the number of elements stored in the subtree.
// Computed dynamically on each call, i.e. the subtree is traversed to count the number of the nodes.
func (node *Node) Size() int {
	if node == nil {
		return 0
	}
	size := 1
	if node.Left != nil {
		size += node.Left.Size()
	}
	if node.Right != nil {
		size += node.Right.Size()
	}
	return size
}

// Keys returns all keys in-order
func (tree *Tree) Keys() []interface{} {
	keys := make([]interface{}, tree.size)
	it := tree.Iterator()
	for i := 0; it.Next(); i++ {
		keys[i] = it.Key()
	}
	return keys
}

// Values returns all values in-order based on the key.
func (tree *Tree) Values() []interface{} {
	values := make([]interface{}, tree.size)
	it := tree.Iterator()
	for i := 0; it.Next(); i++ {
		values[i] = it.Value()
	}
	return values
}

// Left returns the left-most (min) node or nil if tree is empty.
func (tree *Tree) Left() *Node {
	var parent *Node
	current := tree.Root
	for current != nil {
		parent = current
		current = current.Left
	}
	return parent
}

// Right returns the right-most (max) node or nil if tree is empty.
func (tree *Tree) Right() *Node {
	var parent *Node
	current := tree.Root
	for current != nil {
		parent = current
		current = current.Right
	}
	return parent
}

// Floor Finds floor node of the input key, return the floor node or nil if no floor is found.
// Second return parameter is true if floor was found, otherwise false.
//
// Floor node is defined as the largest node that is smaller than or equal to the given node.
// A floor node may not be found, either because the tree is empty, or because
// all nodes in the tree are larger than the given node.
//
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Floor(key interface{}) (floor *Node, found bool) {
	found = false
	node := tree.Root
	for node != nil {
		compare := tree.Comparator(key, node.Key)
		switch {
		case compare == 0:
			return node, true
		case compare < 0:
			node = node.Left
		case compare > 0:
			floor, found = node, true
			node = node.Right
		}
	}
	if found {
		return floor, true
	}
	return nil, false
}

// Ceiling finds ceiling node of the input key, return the ceiling node or nil if no ceiling is found.
// Second return parameter is true if ceiling was found, otherwise false.
//
// Ceiling node is defined as the smallest node that is larger than or equal to the given node.
// A ceiling node may not be found, either because the tree is empty, or because
// all nodes in the tree are smaller than the given node.
//
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Ceiling(key interface{}) (ceiling *Node, found bool) {
	found = false
	node := tree.Root
	for node != nil {
		compare := tree.Comparator(key, node.Key)
		switch {
		case compare == 0:
			return node, true
		case compare < 0:
			ceiling, found = node, true
			node = node.Left
		case compare > 0:
			node = node.Right
		}
	}
	if found {
		return ceiling, true
	}
	return nil, false
}

// Clear removes all nodes from the tree.
func (tree *Tree) Clear() {
	tree.Root = nil
	tree.size = 0
}

// String returns a string representation of container
func (tree *Tree) String() string {
	str := "RedBlackTree\n"
	if !tree.Empty() {
		output(tree.Root, "", true, &str)
	}
	return str
}

func (node *Node) String() string {
	return fmt.Sprintf("%v", node.Key)
}

func output(node *Node, prefix string, isTail bool, str *string) {
	if node.Right != nil {
		newPrefix := prefix
		if isTail {
			newPrefix += "│   "
		} else {
			newPrefix += "    "
		}
		output(node.Right, newPrefix, false, str)
	}
	*str += prefix
	if isTail {
		*str += "└── "
	} else {
		*str += "┌── "
	}
	*str += node.String() + "\n"
	if node.Left != nil {
		newPrefix := prefix
		if isTail {
			newPrefix += "    "
		} else {
			newPrefix += "│   "
		}
		output(node.Left, newPrefix, true, str)
	}
}

func (tree *Tree) lookup(key interface{}) *Node {
	node := tree.Root
	for node != nil {
		compare := tree.Comparator(key, node.Key)
		switch {
		case compare == 0:
			return node
		case compare < 0:
			node = node.Left
		case compare > 0:
			node = node.Right
		}
	}
	return nil
}

func (node *Node) grandparent() *Node {
	if node != nil && node.Parent != nil {
		return node.Parent.Parent
	}
	return nil
}

func (node *Node) uncle() *Node {
	if node == nil || node.Parent == nil || node.Parent.Parent == nil {
		return nil
	}
	return node.Parent.sibling()
}

func (node *Node) sibling() *Node {
	if node == nil || node.Parent == nil {
		return nil
	}
	if node == node.Parent.Left {
		return node.Parent.Right
	}
	return node.Parent.Left
}

func (tree *Tree) rotateLeft(node *Node) {
	right := node.Right
	tree.replaceNode(node, right)
	node.Right = right.Left
	if right.Left != nil {
		right.Left.Parent = node
	}
	right.Left = node
	node.Parent = right
}

func (tree *Tree) rotateRight(node *Node) {
	left := node.Left
	tree.replaceNode(node, left)
	node.Left = left.Right
	if left.Right != nil {
		left.Right.Parent = node
	}
	left.Right = node
	node.Parent = left
}

func (tree *Tree) replaceNode(old *Node, new *Node) {
	if old.Parent == nil {
		tree.Root = new
	} else {
		if old == old.Parent.Left {
			old.Parent.Left = new
		} else {
			old.Parent.Right = new
		}
	}
	if new != nil {
		new.Parent = old.Parent
	}
}

func (tree *Tree) insertCase1(node *Node) {
	if node.Parent == nil {
		node.color = black
	} else {
		tree.insertCase2(node)
	}
}

func (tree *Tree) insertCase2(node *Node) {
	if nodeColor(node.Parent) == black {
		return
	}
	tree.insertCase3(node)
}

func (tree *Tree) insertCase3(node *Node) {
	uncle := node.uncle()
	if nodeColor(uncle) == red {
		node.Parent.color = black
		uncle.color = black
		node.grandparent().color = red
		tree.insertCase1(node.grandparent())
	} else {
		tree.insertCase4(node)
	}
}

func (tree *Tree) insertCase4(node *Node) {
	grandparent := node.grandparent()
	if node == node.Parent.Right && node.Parent == grandparent.Left {
		tree.rotateLeft(node.Parent)
		node = node.Left
	} else if node == node.Parent.Left && node.Parent == grandparent.Right {
		tree.rotateRight(node.Parent)
		node = node.Right
	}
	tree.insertCase5(node)
}

func (tree *Tree) insertCase5(node *Node) {
	node.Parent.color = black
	grandparent := node.grandparent()
	grandparent.color = red
	if node == node.Parent.Left && node.Parent == grandparent.Left {
		tree.rotateRight(grandparent)
	} else if node == node.Parent.Right && node.Parent == grandparent.Right {
		tree.rotateLeft(grandparent)
	}
}

func (node *Node) maximumNode() *Node {
	if node == nil {
		return nil
	}
	for node.Right != nil {
		node = node.Right
	}
	return node
}

func (tree *Tree) deleteCase1(node *Node) {
	if node.Parent == nil {
		return
	}
	tree.deleteCase2(node)
}

func (tree *Tree) deleteCase2(node *Node) {
	sibling := node.sibling()
	if nodeColor(sibling) == red {
		node.Parent.color = red
		sibling.color = black
		if node == node.Parent.Left {
			tree.rotateLeft(node.Parent)
		} else {
			tree.rotateRight(node.Parent)
		}
	}
	tree.deleteCase3(node)
}

func (tree *Tree) deleteCase3(node *Node) {
	sibling := node.sibling()
	if nodeColor(node.Parent) == black &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Left) == black &&
		nodeColor(sibling.Right) == black {
		sibling.color = red
		tree.deleteCase1(node.Parent)
	} else {
		tree.deleteCase4(node)
	}
}

func (tree *Tree) deleteCase4(node *Node) {
	sibling := node.sibling()
	if nodeColor(node.Parent) == red &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Left) == black &&
		nodeColor(sibling.Right) == black {
		sibling.color = red
		node.Parent.color = black
	} else {
		tree.deleteCase5(node)
	}
}

func (tree *Tree) deleteCase5(node *Node) {
	sibling := node.sibling()
	if node == node.Parent.Left &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Left) == red &&
		nodeColor(sibling.Right) == black {
		sibling.color = red
		sibling.Left.color = black
		tree.rotateRight(sibling)
	} else if node == node.Parent.Right &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Right) == red &&
		nodeColor(sibling.Left) == black {
		sibling.color = red
		sibling.Right.color = black
		tree.rotateLeft(sibling)
	}
	tree.deleteCase6(node)
}

func (tree *Tree) deleteCase6(node *Node) {
	sibling := node.sibling()
	sibling.color = nodeColor(node.Parent)
	node.Parent.color = black
	if node == node.Parent.Left && nodeColor(sibling.Right) == red {
		sibling.Right.color = black
		tree.rotateLeft(node.Parent)
	} else if nodeColor(sibling.Left) == red {
		sibling.Left.color = black
		tree.rotateRight(node.Parent)
	}
}

func nodeColor(node *Node) color {
	if node == nil {
		return black
	}
	return node.color
}

// GetSortedValues returns sorted container's elements with respect to the passed comparator.
// Does not affect the ordering of elements within the container.
func GetSortedValues(container Container, comparator Comparator) []interface{} {
	values := container.Values()
	if len(values) < 2 {
		return values
	}
	Sort(values, comparator)
	return values
}

// Iterator holding the iterator's state
type Iterator struct {
	tree     *Tree
	node     *Node
	position position
}

type position byte

const (
	begin, between, end position = 0, 1, 2
)

// Iterator returns a stateful iterator whose elements are key/value pairs.
func (tree *Tree) Iterator() Iterator {
	return Iterator{tree: tree, node: nil, position: begin}
}

// IteratorAt returns a stateful iterator whose elements are key/value pairs that is initialised at a particular node.
func (tree *Tree) IteratorAt(node *Node) Iterator {
	return Iterator{tree: tree, node: node, position: between}
}

// Next moves the iterator to the next element and returns true if there was a next element in the container.
// If Next() returns true, then next element's key and value can be retrieved by Key() and Value().
// If Next() was called for the first time, then it will point the iterator to the first element if it exists.
// Modifies the state of the iterator.
func (iterator *Iterator) Next() bool {
	if iterator.position == end {
		goto end
	}
	if iterator.position == begin {
		left := iterator.tree.Left()
		if left == nil {
			goto end
		}
		iterator.node = left
		goto between
	}
	if iterator.node.Right != nil {
		iterator.node = iterator.node.Right
		for iterator.node.Left != nil {
			iterator.node = iterator.node.Left
		}
		goto between
	}
	for iterator.node.Parent != nil {
		node := iterator.node
		iterator.node = iterator.node.Parent
		if node == iterator.node.Left {
			goto between
		}
	}

end:
	iterator.node = nil
	iterator.position = end
	return false

between:
	iterator.position = between
	return true
}

// Prev moves the iterator to the previous element and returns true if there was a previous element in the container.
// If Prev() returns true, then previous element's key and value can be retrieved by Key() and Value().
// Modifies the state of the iterator.
func (iterator *Iterator) Prev() bool {
	if iterator.position == begin {
		goto begin
	}
	if iterator.position == end {
		right := iterator.tree.Right()
		if right == nil {
			goto begin
		}
		iterator.node = right
		goto between
	}
	if iterator.node.Left != nil {
		iterator.node = iterator.node.Left
		for iterator.node.Right != nil {
			iterator.node = iterator.node.Right
		}
		goto between
	}
	for iterator.node.Parent != nil {
		node := iterator.node
		iterator.node = iterator.node.Parent
		if node == iterator.node.Right {
			goto between
		}
	}

begin:
	iterator.node = nil
	iterator.position = begin
	return false

between:
	iterator.position = between
	return true
}

// Value returns the current element's value.
// Does not modify the state of the iterator.
func (iterator *Iterator) Value() interface{} {
	return iterator.node.Value
}

// Key returns the current element's key.
// Does not modify the state of the iterator.
func (iterator *Iterator) Key() interface{} {
	return iterator.node.Key
}

// Node returns the current element's node.
// Does not modify the state of the iterator.
func (iterator *Iterator) Node() *Node {
	return iterator.node
}

// Begin resets the iterator to its initial state (one-before-first)
// Call Next() to fetch the first element if any.
func (iterator *Iterator) Begin() {
	iterator.node = nil
	iterator.position = begin
}

// End moves the iterator past the last element (one-past-the-end).
// Call Prev() to fetch the last element if any.
func (iterator *Iterator) End() {
	iterator.node = nil
	iterator.position = end
}

// First moves the iterator to the first element and returns true if there was a first element in the container.
// If First() returns true, then first element's key and value can be retrieved by Key() and Value().
// Modifies the state of the iterator
func (iterator *Iterator) First() bool {
	iterator.Begin()
	return iterator.Next()
}

// Last moves the iterator to the last element and returns true if there was a last element in the container.
// If Last() returns true, then last element's key and value can be retrieved by Key() and Value().
// Modifies the state of the iterator.
func (iterator *Iterator) Last() bool {
	iterator.End()
	return iterator.Prev()
}

// NextTo moves the iterator to the next element from current position that satisfies the condition given by the
// passed function, and returns true if there was a next element in the container.
// If NextTo() returns true, then next element's key and value can be retrieved by Key() and Value().
// Modifies the state of the iterator.
func (iterator *Iterator) NextTo(f func(key interface{}, value interface{}) bool) bool {
	for iterator.Next() {
		key, value := iterator.Key(), iterator.Value()
		if f(key, value) {
			return true
		}
	}
	return false
}

// PrevTo moves the iterator to the previous element from current position that satisfies the condition given by the
// passed function, and returns true if there was a next element in the container.
// If PrevTo() returns true, then next element's key and value can be retrieved by Key() and Value().
// Modifies the state of the iterator.
func (iterator *Iterator) PrevTo(f func(key interface{}, value interface{}) bool) bool {
	for iterator.Prev() {
		key, value := iterator.Key(), iterator.Value()
		if f(key, value) {
			return true
		}
	}
	return false
}

type MuliSet struct {
	*Tree
	cntMap  map[interface{}]int
}

func NewMuliSet() *MuliSet{
	return &MuliSet{
		Tree: NewWithIntComparator(),
		cntMap: make(map[interface{}]int),
	}
}

func (m *MuliSet) Put(k interface{}, v interface{}) {
	m.Tree.Put(k, v)
	m.cntMap[k]++
}

func (m *MuliSet) Remove(k interface{}) {
	m.cntMap[k]--
	if m.cntMap[k] == 0 {
		m.Tree.Remove(k)
	}
}

func (m *MuliSet) Count(k interface{}) int {
	return m.cntMap[k]
}

func mex(nums []int) []int {
	n := len(nums)
	dp := make([]int, n+1)
	f := make([]int, n+1)//fi: 变成0～i的最小操作次数
	for i := 0; i <= n; i++{
		f[i] = -1
		dp[i] = -1
	}
	dp[0] = 0
	muliSet := NewMuliSet()
	for _, v := range nums {
		muliSet.Put(v, nil)
	}

	_, ok := muliSet.Get(0)
	if ok {
		dp[0] = muliSet.Count(0)
		f[0] = 0
		muliSet.Remove(0)
	}else {
		return f
	}

	for i := 1; i<=n;i++{
		dp[i] = f[i-1] + muliSet.Count(i)

		_, ok := muliSet.Get(i)
		if ok {
			f[i] = f[i-1]
			muliSet.Remove(i)
		}else {
			node, ok := muliSet.Floor(i)
			if !ok {
				return dp
			}
			f[i] =f[i-1] + i- node.Key.(int)
			muliSet.Remove(node.Key)
		}
	}
	return dp
}

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := readNInt(in, 1)[0]
	for i := 1; i <= t; i++ {
		n := readNInt(in, 1)[0]
		res := mex(readNInt(in,n))
		for i := 0; i< len(res)-1; i++ {
			fmt.Fprint(out, res[i])
			fmt.Fprint(out, " ")
		}
		fmt.Fprintln(out, res[len(res)-1])
	}
}

package main

import (
	"fmt"
	"bufio"
	"sort"
	"time"
	//"github.com/emirpasic/gods/utils"
	"os"
)

// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Sort sorts values (in-place) with respect to the given comparator.
//
// Uses Go's sort (hybrid of quicksort for large and then insertion sort for smaller slices).
func Sort(values []interface{}, comparator Comparator) {
	sort.Sort(sortable{values, comparator})
}

type sortable struct {
	values     []interface{}
	comparator Comparator
}

func (s sortable) Len() int {
	return len(s.values)
}
func (s sortable) Swap(i, j int) {
	s.values[i], s.values[j] = s.values[j], s.values[i]
}
func (s sortable) Less(i, j int) bool {
	return s.comparator(s.values[i], s.values[j]) < 0
}

// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Comparator will make type assertion (see IntComparator for example),
// which will panic if a or b are not of the asserted type.
//
// Should return a number:
//    negative , if a < b
//    zero     , if a == b
//    positive , if a > b
type Comparator func(a, b interface{}) int

// StringComparator provides a fast comparison on strings
func StringComparator(a, b interface{}) int {
	s1 := a.(string)
	s2 := b.(string)
	min := len(s2)
	if len(s1) < len(s2) {
		min = len(s1)
	}
	diff := 0
	for i := 0; i < min && diff == 0; i++ {
		diff = int(s1[i]) - int(s2[i])
	}
	if diff == 0 {
		diff = len(s1) - len(s2)
	}
	if diff < 0 {
		return -1
	}
	if diff > 0 {
		return 1
	}
	return 0
}

// IntComparator provides a basic comparison on int
func IntComparator(a, b interface{}) int {
	aAsserted := a.(int)
	bAsserted := b.(int)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Int8Comparator provides a basic comparison on int8
func Int8Comparator(a, b interface{}) int {
	aAsserted := a.(int8)
	bAsserted := b.(int8)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Int16Comparator provides a basic comparison on int16
func Int16Comparator(a, b interface{}) int {
	aAsserted := a.(int16)
	bAsserted := b.(int16)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Int32Comparator provides a basic comparison on int32
func Int32Comparator(a, b interface{}) int {
	aAsserted := a.(int32)
	bAsserted := b.(int32)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Int64Comparator provides a basic comparison on int64
func Int64Comparator(a, b interface{}) int {
	aAsserted := a.(int64)
	bAsserted := b.(int64)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// UIntComparator provides a basic comparison on uint
func UIntComparator(a, b interface{}) int {
	aAsserted := a.(uint)
	bAsserted := b.(uint)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// UInt8Comparator provides a basic comparison on uint8
func UInt8Comparator(a, b interface{}) int {
	aAsserted := a.(uint8)
	bAsserted := b.(uint8)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// UInt16Comparator provides a basic comparison on uint16
func UInt16Comparator(a, b interface{}) int {
	aAsserted := a.(uint16)
	bAsserted := b.(uint16)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// UInt32Comparator provides a basic comparison on uint32
func UInt32Comparator(a, b interface{}) int {
	aAsserted := a.(uint32)
	bAsserted := b.(uint32)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// UInt64Comparator provides a basic comparison on uint64
func UInt64Comparator(a, b interface{}) int {
	aAsserted := a.(uint64)
	bAsserted := b.(uint64)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Float32Comparator provides a basic comparison on float32
func Float32Comparator(a, b interface{}) int {
	aAsserted := a.(float32)
	bAsserted := b.(float32)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Float64Comparator provides a basic comparison on float64
func Float64Comparator(a, b interface{}) int {
	aAsserted := a.(float64)
	bAsserted := b.(float64)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// ByteComparator provides a basic comparison on byte
func ByteComparator(a, b interface{}) int {
	aAsserted := a.(byte)
	bAsserted := b.(byte)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// RuneComparator provides a basic comparison on rune
func RuneComparator(a, b interface{}) int {
	aAsserted := a.(rune)
	bAsserted := b.(rune)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// TimeComparator provides a basic comparison on time.Time
func TimeComparator(a, b interface{}) int {
	aAsserted := a.(time.Time)
	bAsserted := b.(time.Time)

	switch {
	case aAsserted.After(bAsserted):
		return 1
	case aAsserted.Before(bAsserted):
		return -1
	default:
		return 0
	}
}

// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package containers provides core interfaces and functions for data structures.
//
// Container is the base interface for all data structures to implement.
//
// Iterators provide stateful iterators.
//
// Enumerable provides Ruby inspired (each, select, map, find, any?, etc.) container functions.
//
// Serialization provides serializers (marshalers) and deserializers (unmarshalers).

// Container is base interface that all data structures implement.
type Container interface {
	Empty() bool
	Size() int
	Clear()
	Values() []interface{}
	String() string
}

// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package redblacktree implements a red-black tree.
//
// Used by TreeSet and TreeMap.
//
// Structure is not thread safe.
//
// References: http://en.wikipedia.org/wiki/Red%E2%80%93black_tree

type color bool

const (
	black, red color = true, false
)

// Tree holds elements of the red-black tree
type Tree struct {
	Root       *Node
	size       int
	Comparator Comparator
}

// Node is a single element within the tree
type Node struct {
	Key    interface{}
	Value  interface{}
	color  color
	Left   *Node
	Right  *Node
	Parent *Node
}

// NewWith instantiates a red-black tree with the custom comparator.
func NewWith(comparator Comparator) *Tree {
	return &Tree{Comparator: comparator}
}

// NewWithIntComparator instantiates a red-black tree with the IntComparator, i.e. keys are of type int.
func NewWithIntComparator() *Tree {
	return &Tree{Comparator: IntComparator}
}

// NewWithStringComparator instantiates a red-black tree with the StringComparator, i.e. keys are of type string.
func NewWithStringComparator() *Tree {
	return &Tree{Comparator: StringComparator}
}

// Put inserts node into the tree.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Put(key interface{}, value interface{}) {
	var insertedNode *Node
	if tree.Root == nil {
		// Assert key is of comparator's type for initial tree
		tree.Comparator(key, key)
		tree.Root = &Node{Key: key, Value: value, color: red}
		insertedNode = tree.Root
	} else {
		node := tree.Root
		loop := true
		for loop {
			compare := tree.Comparator(key, node.Key)
			switch {
			case compare == 0:
				node.Key = key
				node.Value = value
				return
			case compare < 0:
				if node.Left == nil {
					node.Left = &Node{Key: key, Value: value, color: red}
					insertedNode = node.Left
					loop = false
				} else {
					node = node.Left
				}
			case compare > 0:
				if node.Right == nil {
					node.Right = &Node{Key: key, Value: value, color: red}
					insertedNode = node.Right
					loop = false
				} else {
					node = node.Right
				}
			}
		}
		insertedNode.Parent = node
	}
	tree.insertCase1(insertedNode)
	tree.size++
}

// Get searches the node in the tree by key and returns its value or nil if key is not found in tree.
// Second return parameter is true if key was found, otherwise false.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Get(key interface{}) (value interface{}, found bool) {
	node := tree.lookup(key)
	if node != nil {
		return node.Value, true
	}
	return nil, false
}

// GetNode searches the node in the tree by key and returns its node or nil if key is not found in tree.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) GetNode(key interface{}) *Node {
	return tree.lookup(key)
}

// Remove remove the node from the tree by key.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Remove(key interface{}) {
	var child *Node
	node := tree.lookup(key)
	if node == nil {
		return
	}
	if node.Left != nil && node.Right != nil {
		pred := node.Left.maximumNode()
		node.Key = pred.Key
		node.Value = pred.Value
		node = pred
	}
	if node.Left == nil || node.Right == nil {
		if node.Right == nil {
			child = node.Left
		} else {
			child = node.Right
		}
		if node.color == black {
			node.color = nodeColor(child)
			tree.deleteCase1(node)
		}
		tree.replaceNode(node, child)
		if node.Parent == nil && child != nil {
			child.color = black
		}
	}
	tree.size--
}

// Empty returns true if tree does not contain any nodes
func (tree *Tree) Empty() bool {
	return tree.size == 0
}

// Size returns number of nodes in the tree.
func (tree *Tree) Size() int {
	return tree.size
}

// Size returns the number of elements stored in the subtree.
// Computed dynamically on each call, i.e. the subtree is traversed to count the number of the nodes.
func (node *Node) Size() int {
	if node == nil {
		return 0
	}
	size := 1
	if node.Left != nil {
		size += node.Left.Size()
	}
	if node.Right != nil {
		size += node.Right.Size()
	}
	return size
}

// Keys returns all keys in-order
func (tree *Tree) Keys() []interface{} {
	keys := make([]interface{}, tree.size)
	it := tree.Iterator()
	for i := 0; it.Next(); i++ {
		keys[i] = it.Key()
	}
	return keys
}

// Values returns all values in-order based on the key.
func (tree *Tree) Values() []interface{} {
	values := make([]interface{}, tree.size)
	it := tree.Iterator()
	for i := 0; it.Next(); i++ {
		values[i] = it.Value()
	}
	return values
}

// Left returns the left-most (min) node or nil if tree is empty.
func (tree *Tree) Left() *Node {
	var parent *Node
	current := tree.Root
	for current != nil {
		parent = current
		current = current.Left
	}
	return parent
}

// Right returns the right-most (max) node or nil if tree is empty.
func (tree *Tree) Right() *Node {
	var parent *Node
	current := tree.Root
	for current != nil {
		parent = current
		current = current.Right
	}
	return parent
}

// Floor Finds floor node of the input key, return the floor node or nil if no floor is found.
// Second return parameter is true if floor was found, otherwise false.
//
// Floor node is defined as the largest node that is smaller than or equal to the given node.
// A floor node may not be found, either because the tree is empty, or because
// all nodes in the tree are larger than the given node.
//
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Floor(key interface{}) (floor *Node, found bool) {
	found = false
	node := tree.Root
	for node != nil {
		compare := tree.Comparator(key, node.Key)
		switch {
		case compare == 0:
			return node, true
		case compare < 0:
			node = node.Left
		case compare > 0:
			floor, found = node, true
			node = node.Right
		}
	}
	if found {
		return floor, true
	}
	return nil, false
}

// Ceiling finds ceiling node of the input key, return the ceiling node or nil if no ceiling is found.
// Second return parameter is true if ceiling was found, otherwise false.
//
// Ceiling node is defined as the smallest node that is larger than or equal to the given node.
// A ceiling node may not be found, either because the tree is empty, or because
// all nodes in the tree are smaller than the given node.
//
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Ceiling(key interface{}) (ceiling *Node, found bool) {
	found = false
	node := tree.Root
	for node != nil {
		compare := tree.Comparator(key, node.Key)
		switch {
		case compare == 0:
			return node, true
		case compare < 0:
			ceiling, found = node, true
			node = node.Left
		case compare > 0:
			node = node.Right
		}
	}
	if found {
		return ceiling, true
	}
	return nil, false
}

// Clear removes all nodes from the tree.
func (tree *Tree) Clear() {
	tree.Root = nil
	tree.size = 0
}

// String returns a string representation of container
func (tree *Tree) String() string {
	str := "RedBlackTree\n"
	if !tree.Empty() {
		output(tree.Root, "", true, &str)
	}
	return str
}

func (node *Node) String() string {
	return fmt.Sprintf("%v", node.Key)
}

func output(node *Node, prefix string, isTail bool, str *string) {
	if node.Right != nil {
		newPrefix := prefix
		if isTail {
			newPrefix += "│   "
		} else {
			newPrefix += "    "
		}
		output(node.Right, newPrefix, false, str)
	}
	*str += prefix
	if isTail {
		*str += "└── "
	} else {
		*str += "┌── "
	}
	*str += node.String() + "\n"
	if node.Left != nil {
		newPrefix := prefix
		if isTail {
			newPrefix += "    "
		} else {
			newPrefix += "│   "
		}
		output(node.Left, newPrefix, true, str)
	}
}

func (tree *Tree) lookup(key interface{}) *Node {
	node := tree.Root
	for node != nil {
		compare := tree.Comparator(key, node.Key)
		switch {
		case compare == 0:
			return node
		case compare < 0:
			node = node.Left
		case compare > 0:
			node = node.Right
		}
	}
	return nil
}

func (node *Node) grandparent() *Node {
	if node != nil && node.Parent != nil {
		return node.Parent.Parent
	}
	return nil
}

func (node *Node) uncle() *Node {
	if node == nil || node.Parent == nil || node.Parent.Parent == nil {
		return nil
	}
	return node.Parent.sibling()
}

func (node *Node) sibling() *Node {
	if node == nil || node.Parent == nil {
		return nil
	}
	if node == node.Parent.Left {
		return node.Parent.Right
	}
	return node.Parent.Left
}

func (tree *Tree) rotateLeft(node *Node) {
	right := node.Right
	tree.replaceNode(node, right)
	node.Right = right.Left
	if right.Left != nil {
		right.Left.Parent = node
	}
	right.Left = node
	node.Parent = right
}

func (tree *Tree) rotateRight(node *Node) {
	left := node.Left
	tree.replaceNode(node, left)
	node.Left = left.Right
	if left.Right != nil {
		left.Right.Parent = node
	}
	left.Right = node
	node.Parent = left
}

func (tree *Tree) replaceNode(old *Node, new *Node) {
	if old.Parent == nil {
		tree.Root = new
	} else {
		if old == old.Parent.Left {
			old.Parent.Left = new
		} else {
			old.Parent.Right = new
		}
	}
	if new != nil {
		new.Parent = old.Parent
	}
}

func (tree *Tree) insertCase1(node *Node) {
	if node.Parent == nil {
		node.color = black
	} else {
		tree.insertCase2(node)
	}
}

func (tree *Tree) insertCase2(node *Node) {
	if nodeColor(node.Parent) == black {
		return
	}
	tree.insertCase3(node)
}

func (tree *Tree) insertCase3(node *Node) {
	uncle := node.uncle()
	if nodeColor(uncle) == red {
		node.Parent.color = black
		uncle.color = black
		node.grandparent().color = red
		tree.insertCase1(node.grandparent())
	} else {
		tree.insertCase4(node)
	}
}

func (tree *Tree) insertCase4(node *Node) {
	grandparent := node.grandparent()
	if node == node.Parent.Right && node.Parent == grandparent.Left {
		tree.rotateLeft(node.Parent)
		node = node.Left
	} else if node == node.Parent.Left && node.Parent == grandparent.Right {
		tree.rotateRight(node.Parent)
		node = node.Right
	}
	tree.insertCase5(node)
}

func (tree *Tree) insertCase5(node *Node) {
	node.Parent.color = black
	grandparent := node.grandparent()
	grandparent.color = red
	if node == node.Parent.Left && node.Parent == grandparent.Left {
		tree.rotateRight(grandparent)
	} else if node == node.Parent.Right && node.Parent == grandparent.Right {
		tree.rotateLeft(grandparent)
	}
}

func (node *Node) maximumNode() *Node {
	if node == nil {
		return nil
	}
	for node.Right != nil {
		node = node.Right
	}
	return node
}

func (tree *Tree) deleteCase1(node *Node) {
	if node.Parent == nil {
		return
	}
	tree.deleteCase2(node)
}

func (tree *Tree) deleteCase2(node *Node) {
	sibling := node.sibling()
	if nodeColor(sibling) == red {
		node.Parent.color = red
		sibling.color = black
		if node == node.Parent.Left {
			tree.rotateLeft(node.Parent)
		} else {
			tree.rotateRight(node.Parent)
		}
	}
	tree.deleteCase3(node)
}

func (tree *Tree) deleteCase3(node *Node) {
	sibling := node.sibling()
	if nodeColor(node.Parent) == black &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Left) == black &&
		nodeColor(sibling.Right) == black {
		sibling.color = red
		tree.deleteCase1(node.Parent)
	} else {
		tree.deleteCase4(node)
	}
}

func (tree *Tree) deleteCase4(node *Node) {
	sibling := node.sibling()
	if nodeColor(node.Parent) == red &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Left) == black &&
		nodeColor(sibling.Right) == black {
		sibling.color = red
		node.Parent.color = black
	} else {
		tree.deleteCase5(node)
	}
}

func (tree *Tree) deleteCase5(node *Node) {
	sibling := node.sibling()
	if node == node.Parent.Left &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Left) == red &&
		nodeColor(sibling.Right) == black {
		sibling.color = red
		sibling.Left.color = black
		tree.rotateRight(sibling)
	} else if node == node.Parent.Right &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Right) == red &&
		nodeColor(sibling.Left) == black {
		sibling.color = red
		sibling.Right.color = black
		tree.rotateLeft(sibling)
	}
	tree.deleteCase6(node)
}

func (tree *Tree) deleteCase6(node *Node) {
	sibling := node.sibling()
	sibling.color = nodeColor(node.Parent)
	node.Parent.color = black
	if node == node.Parent.Left && nodeColor(sibling.Right) == red {
		sibling.Right.color = black
		tree.rotateLeft(node.Parent)
	} else if nodeColor(sibling.Left) == red {
		sibling.Left.color = black
		tree.rotateRight(node.Parent)
	}
}

func nodeColor(node *Node) color {
	if node == nil {
		return black
	}
	return node.color
}

// GetSortedValues returns sorted container's elements with respect to the passed comparator.
// Does not affect the ordering of elements within the container.
func GetSortedValues(container Container, comparator Comparator) []interface{} {
	values := container.Values()
	if len(values) < 2 {
		return values
	}
	Sort(values, comparator)
	return values
}

// Iterator holding the iterator's state
type Iterator struct {
	tree     *Tree
	node     *Node
	position position
}

type position byte

const (
	begin, between, end position = 0, 1, 2
)

// Iterator returns a stateful iterator whose elements are key/value pairs.
func (tree *Tree) Iterator() Iterator {
	return Iterator{tree: tree, node: nil, position: begin}
}

// IteratorAt returns a stateful iterator whose elements are key/value pairs that is initialised at a particular node.
func (tree *Tree) IteratorAt(node *Node) Iterator {
	return Iterator{tree: tree, node: node, position: between}
}

// Next moves the iterator to the next element and returns true if there was a next element in the container.
// If Next() returns true, then next element's key and value can be retrieved by Key() and Value().
// If Next() was called for the first time, then it will point the iterator to the first element if it exists.
// Modifies the state of the iterator.
func (iterator *Iterator) Next() bool {
	if iterator.position == end {
		goto end
	}
	if iterator.position == begin {
		left := iterator.tree.Left()
		if left == nil {
			goto end
		}
		iterator.node = left
		goto between
	}
	if iterator.node.Right != nil {
		iterator.node = iterator.node.Right
		for iterator.node.Left != nil {
			iterator.node = iterator.node.Left
		}
		goto between
	}
	for iterator.node.Parent != nil {
		node := iterator.node
		iterator.node = iterator.node.Parent
		if node == iterator.node.Left {
			goto between
		}
	}

end:
	iterator.node = nil
	iterator.position = end
	return false

between:
	iterator.position = between
	return true
}

// Prev moves the iterator to the previous element and returns true if there was a previous element in the container.
// If Prev() returns true, then previous element's key and value can be retrieved by Key() and Value().
// Modifies the state of the iterator.
func (iterator *Iterator) Prev() bool {
	if iterator.position == begin {
		goto begin
	}
	if iterator.position == end {
		right := iterator.tree.Right()
		if right == nil {
			goto begin
		}
		iterator.node = right
		goto between
	}
	if iterator.node.Left != nil {
		iterator.node = iterator.node.Left
		for iterator.node.Right != nil {
			iterator.node = iterator.node.Right
		}
		goto between
	}
	for iterator.node.Parent != nil {
		node := iterator.node
		iterator.node = iterator.node.Parent
		if node == iterator.node.Right {
			goto between
		}
	}

begin:
	iterator.node = nil
	iterator.position = begin
	return false

between:
	iterator.position = between
	return true
}

// Value returns the current element's value.
// Does not modify the state of the iterator.
func (iterator *Iterator) Value() interface{} {
	return iterator.node.Value
}

// Key returns the current element's key.
// Does not modify the state of the iterator.
func (iterator *Iterator) Key() interface{} {
	return iterator.node.Key
}

// Node returns the current element's node.
// Does not modify the state of the iterator.
func (iterator *Iterator) Node() *Node {
	return iterator.node
}

// Begin resets the iterator to its initial state (one-before-first)
// Call Next() to fetch the first element if any.
func (iterator *Iterator) Begin() {
	iterator.node = nil
	iterator.position = begin
}

// End moves the iterator past the last element (one-past-the-end).
// Call Prev() to fetch the last element if any.
func (iterator *Iterator) End() {
	iterator.node = nil
	iterator.position = end
}

// First moves the iterator to the first element and returns true if there was a first element in the container.
// If First() returns true, then first element's key and value can be retrieved by Key() and Value().
// Modifies the state of the iterator
func (iterator *Iterator) First() bool {
	iterator.Begin()
	return iterator.Next()
}

// Last moves the iterator to the last element and returns true if there was a last element in the container.
// If Last() returns true, then last element's key and value can be retrieved by Key() and Value().
// Modifies the state of the iterator.
func (iterator *Iterator) Last() bool {
	iterator.End()
	return iterator.Prev()
}

// NextTo moves the iterator to the next element from current position that satisfies the condition given by the
// passed function, and returns true if there was a next element in the container.
// If NextTo() returns true, then next element's key and value can be retrieved by Key() and Value().
// Modifies the state of the iterator.
func (iterator *Iterator) NextTo(f func(key interface{}, value interface{}) bool) bool {
	for iterator.Next() {
		key, value := iterator.Key(), iterator.Value()
		if f(key, value) {
			return true
		}
	}
	return false
}

// PrevTo moves the iterator to the previous element from current position that satisfies the condition given by the
// passed function, and returns true if there was a next element in the container.
// If PrevTo() returns true, then next element's key and value can be retrieved by Key() and Value().
// Modifies the state of the iterator.
func (iterator *Iterator) PrevTo(f func(key interface{}, value interface{}) bool) bool {
	for iterator.Prev() {
		key, value := iterator.Key(), iterator.Value()
		if f(key, value) {
			return true
		}
	}
	return false
}

type MuliSet struct {
	*Tree
	cntMap  map[interface{}]int
}

func NewMuliSet() *MuliSet{
	return &MuliSet{
		Tree: NewWithIntComparator(),
		cntMap: make(map[interface{}]int),
	}
}

func (m *MuliSet) Put(k interface{}, v interface{}) {
	m.Tree.Put(k, v)
	m.cntMap[k]++
}

func (m *MuliSet) Remove(k interface{}) {
	m.cntMap[k]--
	if m.cntMap[k] == 0 {
		m.Tree.Remove(k)
	}
}

func (m *MuliSet) Count(k interface{}) int {
	return m.cntMap[k]
}

func mex(nums []int) []int {
	n := len(nums)
	dp := make([]int, n+1)
	f := make([]int, n+1)//fi: 变成0～i的最小操作次数
	for i := 0; i <= n; i++{
		f[i] = -1
		dp[i] = -1
	}

	muliSet := NewMuliSet()
	for _, v := range nums {
		muliSet.Put(v, nil)
	}

	_, ok := muliSet.Get(0)
	if ok {
		dp[0] = muliSet.Count(0)
		f[0] = 0
		muliSet.Remove(0)
	}else {
		return f
	}

	for i := 1; i<=n;i++{
		dp[i] = f[i-1] + muliSet.Count(i)

		_, ok := muliSet.Get(i)
		if ok {
			f[i] = f[i-1]
			muliSet.Remove(i)
		}else {
			node, ok := muliSet.Floor(i)
			if !ok {
				return dp
			}
			f[i] =f[i-1] + i- node.Key.(int)
			muliSet.Remove(node.Key)
		}
	}
	return dp
}

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := readNInt(in, 1)[0]
	for i := 1; i <= t; i++ {
		n := readNInt(in, 1)[0]
		res := mex(readNInt(in,n))
		for i := 0; i< len(res)-1; i++ {
			fmt.Fprint(out, res[i])
			fmt.Fprint(out, " ")
		}
		fmt.Fprintln(out, res[len(res)-1])
	}
}

package main

import (
	"fmt"
	"bufio"
	"sort"
	"time"
	//"github.com/emirpasic/gods/utils"
	"os"
)

// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Sort sorts values (in-place) with respect to the given comparator.
//
// Uses Go's sort (hybrid of quicksort for large and then insertion sort for smaller slices).
func Sort(values []interface{}, comparator Comparator) {
	sort.Sort(sortable{values, comparator})
}

type sortable struct {
	values     []interface{}
	comparator Comparator
}

func (s sortable) Len() int {
	return len(s.values)
}
func (s sortable) Swap(i, j int) {
	s.values[i], s.values[j] = s.values[j], s.values[i]
}
func (s sortable) Less(i, j int) bool {
	return s.comparator(s.values[i], s.values[j]) < 0
}

// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Comparator will make type assertion (see IntComparator for example),
// which will panic if a or b are not of the asserted type.
//
// Should return a number:
//    negative , if a < b
//    zero     , if a == b
//    positive , if a > b
type Comparator func(a, b interface{}) int

// StringComparator provides a fast comparison on strings
func StringComparator(a, b interface{}) int {
	s1 := a.(string)
	s2 := b.(string)
	min := len(s2)
	if len(s1) < len(s2) {
		min = len(s1)
	}
	diff := 0
	for i := 0; i < min && diff == 0; i++ {
		diff = int(s1[i]) - int(s2[i])
	}
	if diff == 0 {
		diff = len(s1) - len(s2)
	}
	if diff < 0 {
		return -1
	}
	if diff > 0 {
		return 1
	}
	return 0
}

// IntComparator provides a basic comparison on int
func IntComparator(a, b interface{}) int {
	aAsserted := a.(int)
	bAsserted := b.(int)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Int8Comparator provides a basic comparison on int8
func Int8Comparator(a, b interface{}) int {
	aAsserted := a.(int8)
	bAsserted := b.(int8)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Int16Comparator provides a basic comparison on int16
func Int16Comparator(a, b interface{}) int {
	aAsserted := a.(int16)
	bAsserted := b.(int16)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Int32Comparator provides a basic comparison on int32
func Int32Comparator(a, b interface{}) int {
	aAsserted := a.(int32)
	bAsserted := b.(int32)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Int64Comparator provides a basic comparison on int64
func Int64Comparator(a, b interface{}) int {
	aAsserted := a.(int64)
	bAsserted := b.(int64)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// UIntComparator provides a basic comparison on uint
func UIntComparator(a, b interface{}) int {
	aAsserted := a.(uint)
	bAsserted := b.(uint)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// UInt8Comparator provides a basic comparison on uint8
func UInt8Comparator(a, b interface{}) int {
	aAsserted := a.(uint8)
	bAsserted := b.(uint8)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// UInt16Comparator provides a basic comparison on uint16
func UInt16Comparator(a, b interface{}) int {
	aAsserted := a.(uint16)
	bAsserted := b.(uint16)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// UInt32Comparator provides a basic comparison on uint32
func UInt32Comparator(a, b interface{}) int {
	aAsserted := a.(uint32)
	bAsserted := b.(uint32)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// UInt64Comparator provides a basic comparison on uint64
func UInt64Comparator(a, b interface{}) int {
	aAsserted := a.(uint64)
	bAsserted := b.(uint64)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Float32Comparator provides a basic comparison on float32
func Float32Comparator(a, b interface{}) int {
	aAsserted := a.(float32)
	bAsserted := b.(float32)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// Float64Comparator provides a basic comparison on float64
func Float64Comparator(a, b interface{}) int {
	aAsserted := a.(float64)
	bAsserted := b.(float64)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// ByteComparator provides a basic comparison on byte
func ByteComparator(a, b interface{}) int {
	aAsserted := a.(byte)
	bAsserted := b.(byte)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// RuneComparator provides a basic comparison on rune
func RuneComparator(a, b interface{}) int {
	aAsserted := a.(rune)
	bAsserted := b.(rune)
	switch {
	case aAsserted > bAsserted:
		return 1
	case aAsserted < bAsserted:
		return -1
	default:
		return 0
	}
}

// TimeComparator provides a basic comparison on time.Time
func TimeComparator(a, b interface{}) int {
	aAsserted := a.(time.Time)
	bAsserted := b.(time.Time)

	switch {
	case aAsserted.After(bAsserted):
		return 1
	case aAsserted.Before(bAsserted):
		return -1
	default:
		return 0
	}
}

// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package containers provides core interfaces and functions for data structures.
//
// Container is the base interface for all data structures to implement.
//
// Iterators provide stateful iterators.
//
// Enumerable provides Ruby inspired (each, select, map, find, any?, etc.) container functions.
//
// Serialization provides serializers (marshalers) and deserializers (unmarshalers).

// Container is base interface that all data structures implement.
type Container interface {
	Empty() bool
	Size() int
	Clear()
	Values() []interface{}
	String() string
}

// Copyright (c) 2015, Emir Pasic. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package redblacktree implements a red-black tree.
//
// Used by TreeSet and TreeMap.
//
// Structure is not thread safe.
//
// References: http://en.wikipedia.org/wiki/Red%E2%80%93black_tree

type color bool

const (
	black, red color = true, false
)

// Tree holds elements of the red-black tree
type Tree struct {
	Root       *Node
	size       int
	Comparator Comparator
}

// Node is a single element within the tree
type Node struct {
	Key    interface{}
	Value  interface{}
	color  color
	Left   *Node
	Right  *Node
	Parent *Node
}

// NewWith instantiates a red-black tree with the custom comparator.
func NewWith(comparator Comparator) *Tree {
	return &Tree{Comparator: comparator}
}

// NewWithIntComparator instantiates a red-black tree with the IntComparator, i.e. keys are of type int.
func NewWithIntComparator() *Tree {
	return &Tree{Comparator: IntComparator}
}

// NewWithStringComparator instantiates a red-black tree with the StringComparator, i.e. keys are of type string.
func NewWithStringComparator() *Tree {
	return &Tree{Comparator: StringComparator}
}

// Put inserts node into the tree.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Put(key interface{}, value interface{}) {
	var insertedNode *Node
	if tree.Root == nil {
		// Assert key is of comparator's type for initial tree
		tree.Comparator(key, key)
		tree.Root = &Node{Key: key, Value: value, color: red}
		insertedNode = tree.Root
	} else {
		node := tree.Root
		loop := true
		for loop {
			compare := tree.Comparator(key, node.Key)
			switch {
			case compare == 0:
				node.Key = key
				node.Value = value
				return
			case compare < 0:
				if node.Left == nil {
					node.Left = &Node{Key: key, Value: value, color: red}
					insertedNode = node.Left
					loop = false
				} else {
					node = node.Left
				}
			case compare > 0:
				if node.Right == nil {
					node.Right = &Node{Key: key, Value: value, color: red}
					insertedNode = node.Right
					loop = false
				} else {
					node = node.Right
				}
			}
		}
		insertedNode.Parent = node
	}
	tree.insertCase1(insertedNode)
	tree.size++
}

// Get searches the node in the tree by key and returns its value or nil if key is not found in tree.
// Second return parameter is true if key was found, otherwise false.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Get(key interface{}) (value interface{}, found bool) {
	node := tree.lookup(key)
	if node != nil {
		return node.Value, true
	}
	return nil, false
}

// GetNode searches the node in the tree by key and returns its node or nil if key is not found in tree.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) GetNode(key interface{}) *Node {
	return tree.lookup(key)
}

// Remove remove the node from the tree by key.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Remove(key interface{}) {
	var child *Node
	node := tree.lookup(key)
	if node == nil {
		return
	}
	if node.Left != nil && node.Right != nil {
		pred := node.Left.maximumNode()
		node.Key = pred.Key
		node.Value = pred.Value
		node = pred
	}
	if node.Left == nil || node.Right == nil {
		if node.Right == nil {
			child = node.Left
		} else {
			child = node.Right
		}
		if node.color == black {
			node.color = nodeColor(child)
			tree.deleteCase1(node)
		}
		tree.replaceNode(node, child)
		if node.Parent == nil && child != nil {
			child.color = black
		}
	}
	tree.size--
}

// Empty returns true if tree does not contain any nodes
func (tree *Tree) Empty() bool {
	return tree.size == 0
}

// Size returns number of nodes in the tree.
func (tree *Tree) Size() int {
	return tree.size
}

// Size returns the number of elements stored in the subtree.
// Computed dynamically on each call, i.e. the subtree is traversed to count the number of the nodes.
func (node *Node) Size() int {
	if node == nil {
		return 0
	}
	size := 1
	if node.Left != nil {
		size += node.Left.Size()
	}
	if node.Right != nil {
		size += node.Right.Size()
	}
	return size
}

// Keys returns all keys in-order
func (tree *Tree) Keys() []interface{} {
	keys := make([]interface{}, tree.size)
	it := tree.Iterator()
	for i := 0; it.Next(); i++ {
		keys[i] = it.Key()
	}
	return keys
}

// Values returns all values in-order based on the key.
func (tree *Tree) Values() []interface{} {
	values := make([]interface{}, tree.size)
	it := tree.Iterator()
	for i := 0; it.Next(); i++ {
		values[i] = it.Value()
	}
	return values
}

// Left returns the left-most (min) node or nil if tree is empty.
func (tree *Tree) Left() *Node {
	var parent *Node
	current := tree.Root
	for current != nil {
		parent = current
		current = current.Left
	}
	return parent
}

// Right returns the right-most (max) node or nil if tree is empty.
func (tree *Tree) Right() *Node {
	var parent *Node
	current := tree.Root
	for current != nil {
		parent = current
		current = current.Right
	}
	return parent
}

// Floor Finds floor node of the input key, return the floor node or nil if no floor is found.
// Second return parameter is true if floor was found, otherwise false.
//
// Floor node is defined as the largest node that is smaller than or equal to the given node.
// A floor node may not be found, either because the tree is empty, or because
// all nodes in the tree are larger than the given node.
//
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Floor(key interface{}) (floor *Node, found bool) {
	found = false
	node := tree.Root
	for node != nil {
		compare := tree.Comparator(key, node.Key)
		switch {
		case compare == 0:
			return node, true
		case compare < 0:
			node = node.Left
		case compare > 0:
			floor, found = node, true
			node = node.Right
		}
	}
	if found {
		return floor, true
	}
	return nil, false
}

// Ceiling finds ceiling node of the input key, return the ceiling node or nil if no ceiling is found.
// Second return parameter is true if ceiling was found, otherwise false.
//
// Ceiling node is defined as the smallest node that is larger than or equal to the given node.
// A ceiling node may not be found, either because the tree is empty, or because
// all nodes in the tree are smaller than the given node.
//
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Ceiling(key interface{}) (ceiling *Node, found bool) {
	found = false
	node := tree.Root
	for node != nil {
		compare := tree.Comparator(key, node.Key)
		switch {
		case compare == 0:
			return node, true
		case compare < 0:
			ceiling, found = node, true
			node = node.Left
		case compare > 0:
			node = node.Right
		}
	}
	if found {
		return ceiling, true
	}
	return nil, false
}

// Clear removes all nodes from the tree.
func (tree *Tree) Clear() {
	tree.Root = nil
	tree.size = 0
}

// String returns a string representation of container
func (tree *Tree) String() string {
	str := "RedBlackTree\n"
	if !tree.Empty() {
		output(tree.Root, "", true, &str)
	}
	return str
}

func (node *Node) String() string {
	return fmt.Sprintf("%v", node.Key)
}

func output(node *Node, prefix string, isTail bool, str *string) {
	if node.Right != nil {
		newPrefix := prefix
		if isTail {
			newPrefix += "│   "
		} else {
			newPrefix += "    "
		}
		output(node.Right, newPrefix, false, str)
	}
	*str += prefix
	if isTail {
		*str += "└── "
	} else {
		*str += "┌── "
	}
	*str += node.String() + "\n"
	if node.Left != nil {
		newPrefix := prefix
		if isTail {
			newPrefix += "    "
		} else {
			newPrefix += "│   "
		}
		output(node.Left, newPrefix, true, str)
	}
}

func (tree *Tree) lookup(key interface{}) *Node {
	node := tree.Root
	for node != nil {
		compare := tree.Comparator(key, node.Key)
		switch {
		case compare == 0:
			return node
		case compare < 0:
			node = node.Left
		case compare > 0:
			node = node.Right
		}
	}
	return nil
}

func (node *Node) grandparent() *Node {
	if node != nil && node.Parent != nil {
		return node.Parent.Parent
	}
	return nil
}

func (node *Node) uncle() *Node {
	if node == nil || node.Parent == nil || node.Parent.Parent == nil {
		return nil
	}
	return node.Parent.sibling()
}

func (node *Node) sibling() *Node {
	if node == nil || node.Parent == nil {
		return nil
	}
	if node == node.Parent.Left {
		return node.Parent.Right
	}
	return node.Parent.Left
}

func (tree *Tree) rotateLeft(node *Node) {
	right := node.Right
	tree.replaceNode(node, right)
	node.Right = right.Left
	if right.Left != nil {
		right.Left.Parent = node
	}
	right.Left = node
	node.Parent = right
}

func (tree *Tree) rotateRight(node *Node) {
	left := node.Left
	tree.replaceNode(node, left)
	node.Left = left.Right
	if left.Right != nil {
		left.Right.Parent = node
	}
	left.Right = node
	node.Parent = left
}

func (tree *Tree) replaceNode(old *Node, new *Node) {
	if old.Parent == nil {
		tree.Root = new
	} else {
		if old == old.Parent.Left {
			old.Parent.Left = new
		} else {
			old.Parent.Right = new
		}
	}
	if new != nil {
		new.Parent = old.Parent
	}
}

func (tree *Tree) insertCase1(node *Node) {
	if node.Parent == nil {
		node.color = black
	} else {
		tree.insertCase2(node)
	}
}

func (tree *Tree) insertCase2(node *Node) {
	if nodeColor(node.Parent) == black {
		return
	}
	tree.insertCase3(node)
}

func (tree *Tree) insertCase3(node *Node) {
	uncle := node.uncle()
	if nodeColor(uncle) == red {
		node.Parent.color = black
		uncle.color = black
		node.grandparent().color = red
		tree.insertCase1(node.grandparent())
	} else {
		tree.insertCase4(node)
	}
}

func (tree *Tree) insertCase4(node *Node) {
	grandparent := node.grandparent()
	if node == node.Parent.Right && node.Parent == grandparent.Left {
		tree.rotateLeft(node.Parent)
		node = node.Left
	} else if node == node.Parent.Left && node.Parent == grandparent.Right {
		tree.rotateRight(node.Parent)
		node = node.Right
	}
	tree.insertCase5(node)
}

func (tree *Tree) insertCase5(node *Node) {
	node.Parent.color = black
	grandparent := node.grandparent()
	grandparent.color = red
	if node == node.Parent.Left && node.Parent == grandparent.Left {
		tree.rotateRight(grandparent)
	} else if node == node.Parent.Right && node.Parent == grandparent.Right {
		tree.rotateLeft(grandparent)
	}
}

func (node *Node) maximumNode() *Node {
	if node == nil {
		return nil
	}
	for node.Right != nil {
		node = node.Right
	}
	return node
}

func (tree *Tree) deleteCase1(node *Node) {
	if node.Parent == nil {
		return
	}
	tree.deleteCase2(node)
}

func (tree *Tree) deleteCase2(node *Node) {
	sibling := node.sibling()
	if nodeColor(sibling) == red {
		node.Parent.color = red
		sibling.color = black
		if node == node.Parent.Left {
			tree.rotateLeft(node.Parent)
		} else {
			tree.rotateRight(node.Parent)
		}
	}
	tree.deleteCase3(node)
}

func (tree *Tree) deleteCase3(node *Node) {
	sibling := node.sibling()
	if nodeColor(node.Parent) == black &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Left) == black &&
		nodeColor(sibling.Right) == black {
		sibling.color = red
		tree.deleteCase1(node.Parent)
	} else {
		tree.deleteCase4(node)
	}
}

func (tree *Tree) deleteCase4(node *Node) {
	sibling := node.sibling()
	if nodeColor(node.Parent) == red &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Left) == black &&
		nodeColor(sibling.Right) == black {
		sibling.color = red
		node.Parent.color = black
	} else {
		tree.deleteCase5(node)
	}
}

func (tree *Tree) deleteCase5(node *Node) {
	sibling := node.sibling()
	if node == node.Parent.Left &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Left) == red &&
		nodeColor(sibling.Right) == black {
		sibling.color = red
		sibling.Left.color = black
		tree.rotateRight(sibling)
	} else if node == node.Parent.Right &&
		nodeColor(sibling) == black &&
		nodeColor(sibling.Right) == red &&
		nodeColor(sibling.Left) == black {
		sibling.color = red
		sibling.Right.color = black
		tree.rotateLeft(sibling)
	}
	tree.deleteCase6(node)
}

func (tree *Tree) deleteCase6(node *Node) {
	sibling := node.sibling()
	sibling.color = nodeColor(node.Parent)
	node.Parent.color = black
	if node == node.Parent.Left && nodeColor(sibling.Right) == red {
		sibling.Right.color = black
		tree.rotateLeft(node.Parent)
	} else if nodeColor(sibling.Left) == red {
		sibling.Left.color = black
		tree.rotateRight(node.Parent)
	}
}

func nodeColor(node *Node) color {
	if node == nil {
		return black
	}
	return node.color
}

// GetSortedValues returns sorted container's elements with respect to the passed comparator.
// Does not affect the ordering of elements within the container.
func GetSortedValues(container Container, comparator Comparator) []interface{} {
	values := container.Values()
	if len(values) < 2 {
		return values
	}
	Sort(values, comparator)
	return values
}

// Iterator holding the iterator's state
type Iterator struct {
	tree     *Tree
	node     *Node
	position position
}

type position byte

const (
	begin, between, end position = 0, 1, 2
)

// Iterator returns a stateful iterator whose elements are key/value pairs.
func (tree *Tree) Iterator() Iterator {
	return Iterator{tree: tree, node: nil, position: begin}
}

// IteratorAt returns a stateful iterator whose elements are key/value pairs that is initialised at a particular node.
func (tree *Tree) IteratorAt(node *Node) Iterator {
	return Iterator{tree: tree, node: node, position: between}
}

// Next moves the iterator to the next element and returns true if there was a next element in the container.
// If Next() returns true, then next element's key and value can be retrieved by Key() and Value().
// If Next() was called for the first time, then it will point the iterator to the first element if it exists.
// Modifies the state of the iterator.
func (iterator *Iterator) Next() bool {
	if iterator.position == end {
		goto end
	}
	if iterator.position == begin {
		left := iterator.tree.Left()
		if left == nil {
			goto end
		}
		iterator.node = left
		goto between
	}
	if iterator.node.Right != nil {
		iterator.node = iterator.node.Right
		for iterator.node.Left != nil {
			iterator.node = iterator.node.Left
		}
		goto between
	}
	for iterator.node.Parent != nil {
		node := iterator.node
		iterator.node = iterator.node.Parent
		if node == iterator.node.Left {
			goto between
		}
	}

end:
	iterator.node = nil
	iterator.position = end
	return false

between:
	iterator.position = between
	return true
}

// Prev moves the iterator to the previous element and returns true if there was a previous element in the container.
// If Prev() returns true, then previous element's key and value can be retrieved by Key() and Value().
// Modifies the state of the iterator.
func (iterator *Iterator) Prev() bool {
	if iterator.position == begin {
		goto begin
	}
	if iterator.position == end {
		right := iterator.tree.Right()
		if right == nil {
			goto begin
		}
		iterator.node = right
		goto between
	}
	if iterator.node.Left != nil {
		iterator.node = iterator.node.Left
		for iterator.node.Right != nil {
			iterator.node = iterator.node.Right
		}
		goto between
	}
	for iterator.node.Parent != nil {
		node := iterator.node
		iterator.node = iterator.node.Parent
		if node == iterator.node.Right {
			goto between
		}
	}

begin:
	iterator.node = nil
	iterator.position = begin
	return false

between:
	iterator.position = between
	return true
}

// Value returns the current element's value.
// Does not modify the state of the iterator.
func (iterator *Iterator) Value() interface{} {
	return iterator.node.Value
}

// Key returns the current element's key.
// Does not modify the state of the iterator.
func (iterator *Iterator) Key() interface{} {
	return iterator.node.Key
}

// Node returns the current element's node.
// Does not modify the state of the iterator.
func (iterator *Iterator) Node() *Node {
	return iterator.node
}

// Begin resets the iterator to its initial state (one-before-first)
// Call Next() to fetch the first element if any.
func (iterator *Iterator) Begin() {
	iterator.node = nil
	iterator.position = begin
}

// End moves the iterator past the last element (one-past-the-end).
// Call Prev() to fetch the last element if any.
func (iterator *Iterator) End() {
	iterator.node = nil
	iterator.position = end
}

// First moves the iterator to the first element and returns true if there was a first element in the container.
// If First() returns true, then first element's key and value can be retrieved by Key() and Value().
// Modifies the state of the iterator
func (iterator *Iterator) First() bool {
	iterator.Begin()
	return iterator.Next()
}

// Last moves the iterator to the last element and returns true if there was a last element in the container.
// If Last() returns true, then last element's key and value can be retrieved by Key() and Value().
// Modifies the state of the iterator.
func (iterator *Iterator) Last() bool {
	iterator.End()
	return iterator.Prev()
}

// NextTo moves the iterator to the next element from current position that satisfies the condition given by the
// passed function, and returns true if there was a next element in the container.
// If NextTo() returns true, then next element's key and value can be retrieved by Key() and Value().
// Modifies the state of the iterator.
func (iterator *Iterator) NextTo(f func(key interface{}, value interface{}) bool) bool {
	for iterator.Next() {
		key, value := iterator.Key(), iterator.Value()
		if f(key, value) {
			return true
		}
	}
	return false
}

// PrevTo moves the iterator to the previous element from current position that satisfies the condition given by the
// passed function, and returns true if there was a next element in the container.
// If PrevTo() returns true, then next element's key and value can be retrieved by Key() and Value().
// Modifies the state of the iterator.
func (iterator *Iterator) PrevTo(f func(key interface{}, value interface{}) bool) bool {
	for iterator.Prev() {
		key, value := iterator.Key(), iterator.Value()
		if f(key, value) {
			return true
		}
	}
	return false
}

type MuliSet struct {
	*Tree
	cntMap  map[interface{}]int
}

func NewMuliSet() *MuliSet{
	return &MuliSet{
		Tree: NewWithIntComparator(),
		cntMap: make(map[interface{}]int),
	}
}

func (m *MuliSet) Put(k interface{}, v interface{}) {
	m.Tree.Put(k, v)
	m.cntMap[k]++
}

func (m *MuliSet) Remove(k interface{}) {
	m.cntMap[k]--
	if m.cntMap[k] == 0 {
		m.Tree.Remove(k)
	}
}

func (m *MuliSet) Count(k interface{}) int {
	return m.cntMap[k]
}

func mex(nums []int) []int {
	n := len(nums)
	dp := make([]int, n+1)
	f := make([]int, n+1)//fi: 变成0～i的最小操作次数
	for i := 0; i <= n; i++{
		f[i] = -1
		dp[i] = -1
	}

	muliSet := NewMuliSet()
	for _, v := range nums {
		muliSet.Put(v, nil)
	}

	_, ok := muliSet.Get(0)
	if ok {
		dp[0] = muliSet.Count(0)
		f[0] = 0
		muliSet.Remove(0)
	}else {
		return f
	}

	for i := 1; i<=n;i++{
		dp[i] = f[i-1] + muliSet.Count(i)

		_, ok := muliSet.Get(i)
		if ok {
			f[i] = f[i-1]
			muliSet.Remove(i)
		}else {
			node, ok := muliSet.Floor(i)
			if !ok {
				return dp
			}
			f[i] =f[i-1] + i- node.Key.(int)
			muliSet.Remove(node.Key)
		}
	}
	return dp
}

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := readNInt(in, 1)[0]
	for i := 1; i <= t; i++ {
		n := readNInt(in, 1)[0]
		fmt.Fprintln(out, mex(readNInt(in,n)))
	}
}

package main

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

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

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

	var c int
	var n int
	Fscan(in, &c)
	for ; c > 0; c-- {
		Fscan(in, &n)
		a := make([]int, n)
		cnt := make(map[int]int) //统计每个元素
		for i := range a {
			Fscan(in, &a[i])
			cnt[a[i]]++
		}
		ans := make([]int, n+1)
		stack := []int{}
		total := 0
		for i := range ans {
			ans[i] = -1
		}
		for i := 0; i <= n; i++ {
			if i > 0 && cnt[i-1] == 0 {
				if len(stack) == 0 {
					break
				}
				top := stack[len(stack)-1]
				stack = stack[:len(stack)-1]
				total += i - top - 1
			}
			ans[i] = total + cnt[i]
			for cnt[i] > 1 {
				stack = append(stack, i)
				cnt[i]--
			}
		}
		for _, v := range ans {
			Fprintf(out, "%d%s", v, " ")
		}
		Fprintf(out, "\n")
	}
}

package main

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

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

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

	var c int
	var n int
	Fscan(in, &c)
	for ; c > 0; c-- {
		Fscan(in, &n)
		a := make([]int, n)
		cnt := make(map[int]int) //统计每个元素
		for i := range a {
			Fscan(in, &a[i])
			cnt[a[i]]++
		}
		dp := make([]int, n+1) //dp[i]表示小于i的元素的个数

		//预处理dp数组，找到小于i的元素的个数
		sort.Ints(a)
		p := 1
		stack := []int{a[0]}
		for i := 1; i <= n; i++ {
			dp[i] = dp[i-1]
			for ; p < n && a[p] < i; p++ {
				stack = append(stack, a[p])
			}
			for len(stack) > 0 {
				stack = stack[:len(stack)-1]
				dp[i]++
			}
		}
		ans := make([]int, n+1)
		if cnt[0] > 0 {
			ans[0] = cnt[0]
		}
		for i := 1; i <= n; i++ {
			if dp[i] < i { //无法构成
				for j := i; j <= n; j++ {
					ans[j] = -1
				}
				goto h1
			}
			x := i - 1
			j := dp[i] - 1
			z := 0
			for x > a[j] {
				z += x - a[j]
				x--
				j--
			}
			ans[i] = z + cnt[i] + ans[a[j]] - cnt[a[j]]
		}
	h1:
		for i, v := range ans {
			Fprintf(out, "%d%s", v, " ")
			if i == n {
				Fprintf(out, "\n")
			}
		}
	}
}

package main

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

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

	var T, n, v int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		cnt := make([]int, n+1)
		for i := 0; i < n; i++ {
			Fscan(in, &v)
			cnt[v]++
		}
		Fprint(out, cnt[0], " ")
		s, ex, fill := 0, []int{}, 0
		for i, c := range cnt[:n] {
			if s += c; s <= i {
				Fprint(out, strings.Repeat("-1 ", n-i))
				break
			}
			if c == 0 {
				fill += i - ex[len(ex)-1]
				ex = ex[:len(ex)-1]
			}
			Fprint(out, fill+cnt[i+1], " ")
			for ; c > 1; c-- {
				ex = append(ex, i)
			}
		}
		Fprintln(out)
	}
}

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

package main

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

/*
* lets try some fancy go :)

sort existing numbers, iterate starting from 0
if current number eq it then ok, else if current number < it
put number on stack else take number from stack, ans+=diff.

Also we need to consider that we need to increase all
numbers eq it.
*/
func main() {
    re, w, e := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout), bufio.NewWriter(os.Stderr)
    defer w.Flush()
    defer e.Flush()

    var t int=0
    Fscan(re, &t)

    for i:=0; i<t; i++ {
        var n int
        Fscan(re, &n)

        var a=make([]int,n)
        var f=make([]int,n+1)

        for i:=0; i<n; i++ {
            Fscan(re, &a[i])
            f[a[i]]++
        }

        sort.Ints(a);
        st:=[]int{}
        ans:=0
        ok:=true;

        for i:=0; i<=n; i++ {
            if !ok {
                Fprintf(w, "-1 ")
                continue;
            }

            if f[i]>0 {
                Fprintf(w, "%d ", ans+f[i])
                for j:=1; j<f[i]; j++ {
                    st=append(st, i)
                }
            } else {
                Fprintf(w, "%d ", ans)
                if(len(st)==0) {
                    ok=false
                } else {
                    b:=st[len(st)-1]
                    ans+=i-b
                    st=st[:len(st)-1]
                }
            }
        }
        Fprintf(w,"\n")
    }
}

package main

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

/*
* lets try some fancy go :)

sort existing numbers, iterate starting from 0
if current number eq it then ok, else if current number < it
put number on stack else take number from stack, ans+=diff.

Also we need to consider that we need to increase all
numbers eq it.
*/
func main() {
    re, w, e := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout), bufio.NewWriter(os.Stderr)
    defer w.Flush()
    defer e.Flush()

    var t int=0
    Fscan(re, &t)

    for i:=0; i<t; i++ {
        var n int
        Fscan(re, &n)

        var a=make([]int,n)
        var f=make([]int,n+1)
        for i:=0; i<n; i++ {
            Fscan(re, &a[i])
            f[a[i]]++
        }

        sort.Ints(a);
        var st=make([]int,0)
        ans:=0

        ok:=true;
        for i:=0; i<=n; i++ {
            if !ok {
                Fprintf(w, "-1 ")
                continue;
            }

            if f[i]>0 {
                Fprintf(w, "%d ", ans+f[i])
                for j:=1; j<f[i]; j++ {
                    st=append(st, i)
                }
                continue
            } else {
                Fprintf(w, "%d ", ans)
                if(len(st)==0) {
                    ok=false
                } else {
                    b:=st[len(st)-1]
                    ans+=i-b
                    st=st[:len(st)-1]
                }
            }
        }
        Fprintf(w,"\n")
    }
}

package main

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

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

var (
	T    int
	n    int
	a    []int
	last []int
)

func getOne(i int) int {
	if i < 0 {
		return -1
	}
	if a[i] <= 1 {
		k := getOne(last[i])
		last[i] = k
		return k
	}
	return i
}

func solve(i int) (int, bool) {
	k := getOne(i)
	if k < 0 {
		return 0, false
	}
	a[k]--
	a[i]++
	return i - k, true
}

func Init() {
	a = make([]int, n+1)
	last = make([]int, n+1)
}

func main() {
	_, _ = fmt.Fscan(rr, &T)
	for iCase := 0; iCase < T; iCase++ {
		_, _ = fmt.Fscan(rr, &n)

		Init()

		for i := 0; i < n; i++ {
			var t int
			_, _ = fmt.Fscan(rr, &t)
			a[t]++
		}

		base := -1
		for i := 0; i <= n; i++ {
			last[i] = base
			if a[i] > 1 {
				base = i
			}
		}

		base = 0
		for i := 0; i <= n; i++ {
			if base < 0 {
				_, _ = fmt.Fprintf(ww, "%d ", -1)
			} else if base >= 0 && a[i] > 0 {
				_, _ = fmt.Fprintf(ww, "%d ", base+a[i])
			} else {
				_, _ = fmt.Fprintf(ww, "%d ", base)
				t, flag := solve(i)
				if flag {
					base += t
				} else {
					base = -1
				}
			}
		}
		_, _ = fmt.Fprintln(ww)
	}
	_ = ww.Flush()
}

package main

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

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

var (
	T    int
	n    int
	a    []int
	last []int
)

func getOne(i int) int {
	if i < 0 {
		return -1
	}
	if a[i] <= 1 {
		k := getOne(last[i])
		last[i] = k
		return k
	}
	return i
}

func solve(i int) int {
	k := getOne(i)
	if k < 0 {
		return -1
	}
	a[k]--
	a[i]++
	return i - k
}

func Init() {
	a = make([]int, n+1)
	last = make([]int, n+1)
}

func main() {
	_, _ = fmt.Fscan(rr, &T)
	for iCase := 0; iCase < T; iCase++ {
		_, _ = fmt.Fscan(rr, &n)

		Init()

		for i := 0; i < n; i++ {
			var t int
			_, _ = fmt.Fscan(rr, &t)
			a[t]++
		}

		base := -1
		for i := 0; i <= n; i++ {
			last[i] = base
			if a[i] > 1 {
				base = i
			}
		}

		base = 0
		for i := 0; i <= n; i++ {
			if base >= 0 && a[i] != 0 {
				_, _ = fmt.Fprintf(ww, "%d ", base+a[i])
			} else {
				_, _ = fmt.Fprintf(ww, "%d ", base)
				if base >= 0 {
					t := solve(i)
					if t >= 0 {
						base += t
					} else {
						base = t
					}
				}
			}
		}
		_, _ = fmt.Fprintln(ww)
	}
	_ = ww.Flush()
}

package main

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

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

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

func redirectInputToFile(r *bufio.Reader, fp string) {
	f, err := os.Open(fp)
	if err != nil {
		panic(err)
	}
	r.Reset(f)
}

func main() {
	defer writer.Flush()
	// redirectInputToFile(reader, "input.txt")

	T := 1
	scan(&T)
	for t := 0; t < T; t++ {
		solve()
	}
}

func solve() {
	var n int
	scan(&n)
	a := make([]int, n)
	cnt := make([]int, n+1)
	for i := range a {
		scan(&a[i])
		cnt[a[i]]++
	}

	frees := [][2]int{}
	prevok, prevres := true, 0
	for i := 0; i <= n; i++ {
		if !prevok {
			printf("-1 ")
			continue
		}
		printf("%v ", prevres+cnt[i])

		if cnt[i] > 1 {
			frees = append(frees, [2]int{cnt[i] - 1, i})
			continue
		}
		if cnt[i] == 1 {
			continue
		}
		if len(frees) == 0 {
			prevok = false
			continue
		}
		prevres += i - frees[len(frees)-1][1]
		frees[len(frees)-1][0]--
		if frees[len(frees)-1][0] == 0 {
			frees = frees[:len(frees)-1]
		}
	}
	printf("\n")
}

package main

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

func solve() {
	f := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	N, n, p := 0, 0, 0
	fmt.Fscan(f, &N)
	for i := 0; i < N; i++ {
		fmt.Fscan(f, &n)
		stack, sum, o, count, mex := list.New(), 0, []int{}, make([]int, n+1), make([]int, n+1)
		for j := 0; j < n; j++ {
			fmt.Fscan(f, &p)
			o = append(o, p)
			count[p]++
			mex[j] = -1
		}
		mex[n] = -1
		sort.Ints(o)
		for i := 0; i <= n; i++ {
			if i > 0 && count[i-1] == 0 {
				if stack.Len() == 0 {
					break
				}
				top := stack.Front()
				stack.Remove(top)
				sum += i - top.Value.(int) - 1
			}
			mex[i] = sum + count[i]
			for i > 0 && count[i-1] > 1 {
				stack.PushFront(i - 1)
				count[i-1]--
			}
		}
		for _, v := range mex {
			fmt.Fprint(w, v, " ")
		}
		fmt.Fprintln(w, "")
	}
	w.Flush()
}

func main() {
	solve()
}