package main

import "fmt"

func main() {
	var n int
	t1, t2 := 0, 0
	_, _ = fmt.Scan(&n)
	for i := 0; i < n; i++ {
		var x int
		_, _ = fmt.Scan(&x)
		if x&1 == 1 {
			t1++
		} else {
			t2++
		}
	}
	if t1 > t2 {
		fmt.Println(t2)
	} else {
		fmt.Println(t1)
	}
}

package main

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

/* solution */

func solve() {

	n := readInt()
	odd := 0
	for i := 0; i < n; i++ {
		if readInt()%2 == 1 {
			odd++
		}
	}

	if odd < n-odd {
		printInt(odd)
	} else {
		printInt(n - odd)
	}

}

/* stubs */

func main() {

	var f *os.File
	if runtime.GOROOT() == "C:\\Soft\\Go" {
		f, _ = os.Open("input.txt")
		defer f.Close()
	} else {
		f = os.Stdin
	}

	writer = bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	reader = bufio.NewScanner(f)

	const maxCapacity = 1024 * 1024
	buf := make([]byte, maxCapacity)
	reader.Buffer(buf, maxCapacity)

	reader.Split(bufio.ScanWords)

	solve()

}

var reader *bufio.Scanner
var writer *bufio.Writer

func read() string {
	reader.Scan()
	return reader.Text()
}

func readInt() int {
	reader.Scan()
	ret, _ := strconv.Atoi(reader.Text())
	return ret
}

func print(s string) {
	writer.WriteString(s)
	writer.WriteString("\n")
}

func printInt(i int) {
	print(strconv.Itoa(i))
}

func printInt64(i int64) {
	print(strconv.FormatInt(i, 10))
}

func readInt64() int64 {
	reader.Scan()
	ret, _ := strconv.ParseInt(reader.Text(), 10, 64)
	return ret
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n, k int

	// scr := bufio.NewReader(os.Stdin)
	// ocr := bufio.NewWriter(os.Stdout)

	fmt.Scanln(&n)
	a := make([]int, 2)

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

		a[k%2]++

	}

	sort.Ints(a)

	fmt.Println(a[0])

}

package main

import "fmt"

func main() {
	var n, a, even, odd int
	fmt.Scan(&n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a)
		if a%2 == 0 {
			even++
		} else {
			odd++
		}
	}
	if even < odd {
		fmt.Println(even)
	} else {
		fmt.Println(odd)
	}

}

package main

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

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

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

	n, err := strconv.ParseInt(readLine(reader), 10, 64)
	checkError(err)

	xTemp := strings.Split(readLine(reader), " ")
	zero := 0
	one := 0
	for i := 0; i < int(n); i++ {
		scoresItem, err := strconv.ParseInt(xTemp[i], 10, 64)
		checkError(err)
		if scoresItem&1 == 0 {
			zero++
		} else {
			one++
		}
	}
	fmt.Println(min(zero, one))
}

func readLine(reader *bufio.Reader) string {
	str, _, err := reader.ReadLine()
	if err == io.EOF {
		return ""
	}

	return strings.TrimRight(string(str), "\r\n")
}

func checkError(err error) {
	if err != nil {
		panic(err)
	}
}

package main

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

func main() {
	inputreader := bufio.NewReader(os.Stdin)
	var str string
	str,_= inputreader.ReadString('\n')
	str=strings.TrimSpace(str)
	temp:=strings.Split(str," ")
	N,_:= strconv.Atoi(temp[0])
	odd:=0
	even:=0
	str,_= inputreader.ReadString('\n')
	str=strings.TrimSpace(str)
	temp=strings.Split(str," ")
	for i:=0;i<N;i++{
		a,_:= strconv.Atoi(temp[i])
		if a%2==0{
			even++
		}else{
				odd++
		}
	}
ans:=even
if ans>odd{
	ans=odd
}
fmt.Println(ans)

}

//HOWDY! IT'S ME! A HARD BLACKISH DICK MOVE!
package main

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

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

//str := ReadString()
//i := ReadInt()
//X := ReadIntSlice(n)
//S := ReadRuneSlice()
//a := ReadFloat64()
//A := ReadFloat64Slice(n)

//str := PrintlnInts(X...)

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

func main() {
	n := ReadInt()
	x := ReadIntSlice(n)
	var parities [2]int
	for _, v := range x {
		parities[v%2]++
	}
	fmt.Println(min(parities[0], parities[1]))
}

/*********** Math ***********/
func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

func min(args ...int) int {
	if len(args) == 0 {
		panic("empty!")
	}
	min := args[0]
	for i := 1; i < len(args); i++ {
		if args[i] < min {
			min = args[i]
		}
	}
	return min
}

func max(args ...int) int {
	if len(args) == 0 {
		panic("empty!")
	}
	max := args[0]
	for i := 1; i < len(args); i++ {
		if args[i] > max {
			max = args[i]
		}
	}
	return max
}

func _gcd(a, b int) int {
	if b == 0 {
		return a
	}
	return _gcd(b, a%b)
}

func gcd(args ...int) int {
	if len(args) == 0 {
		panic("empty!")
	}
	gcd := args[0]
	for i := 1; i < len(args); i++ {
		gcd = _gcd(gcd, args[i])
	}
	return gcd
}

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

var (
	// ReadString returns a WORD string.
	ReadString func() string
	stdout     *bufio.Writer
)

func init() {
	ReadString = newReadString(os.Stdin)
	stdout = bufio.NewWriter(os.Stdout)
}

func newReadString(ior io.Reader) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9))
	// Split sets the split function for the Scanner. The default split function is ScanLines.
	// Split panics if it is called after scanning has started.
	r.Split(bufio.ScanWords)

	return func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
}

// ReadInt returns an integer.
func ReadInt() int {
	return readInt()
}
func ReadInt2() (int, int) {
	return readInt(), readInt()
}
func ReadInt3() (int, int, int) {
	return readInt(), readInt(), readInt()
}
func ReadInt4() (int, int, int, int) {
	return readInt(), readInt(), readInt(), readInt()
}

func readInt64() int64 {
	return readIntNbits(64)
}

func readInt() int {
	return int(readIntNbits(32))
}

func readIntNbits(n int) int64 {
	i, err := strconv.ParseInt(ReadString(), 0, n)
	if err != nil {
		panic(err.Error())
	}
	return i
}

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

// ReadFloat64 returns an float64.
func ReadFloat64() float64 {
	return float64(readFloat64())
}

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

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

// ReadRuneSlice returns a rune slice.
func ReadRuneSlice() []rune {
	return []rune(ReadString())
}

// PrintIntsLine returns integers string delimited by a space.
func PrintlnInts(A ...int) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

package main

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

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

// IO helper functions

// Returns next token from input.  It must be initialized by SetInput()
// before the first call.
var nextToken func() ([]byte, error)
var nextLine func() ([]byte, error)

// Holds a buffer for output.  It must be initialized by SetOutput().
// All IO fucntions (read*() and [e]print*()) should write to OutputWriter
// instead of this.
var OutputBuffer *bufio.Writer

// Holds an io.Writer.  It must be initialized by SetOutput()
var OutputWriter io.Writer

// Set IO functions for interactive input/output.
func SetInteractive(w io.Writer, r io.Reader) {
	SetUnbefferedInput(r)
	OutputBuffer = nil
	OutputWriter = w
}

// Setup OutputBuffer and OutputWriter.
func SetOutput(w io.Writer) {
	OutputBuffer = bufio.NewWriter(w)
	OutputWriter = OutputBuffer
}

// Flushes OutputBuffer
func Flush() {
	if OutputBuffer != nil {
		OutputBuffer.Flush()
	}
}

// Returns true if c is a white space
func IsSpace(c byte) bool {
	switch c {
	case '\t', '\n', '\v', '\f', '\r', ' ':
		return true
	}
	return false
}

func IsNewLine(c byte) bool {
	switch c {
	case '\n', '\r':
		return true
	}
	return false
}

// Setup nextToken with input buffer.
func SetInput(r io.Reader) {
	buf := new(bytes.Buffer)
	var b []byte

	var i int
	rest := func() ([]byte, error) {
		for i < len(b) && IsSpace(b[i]) {
			i++
		}
		if i == len(b) {
			return nil, io.ErrUnexpectedEOF
		}
		j := i
		for i < len(b) && !IsSpace(b[i]) {
			i++
		}
		return b[j:i], nil
	}
	initial := func() ([]byte, error) {
		io.Copy(buf, r)
		b = buf.Bytes()
		nextToken = rest
		return rest()
	}
	nextToken = initial

	restLn := func() ([]byte, error) {
		for i < len(b) && IsNewLine(b[i]) {
			i++
		}
		if i == len(b) {
			return nil, io.ErrUnexpectedEOF
		}
		j := i
		for i < len(b) && !IsNewLine(b[i]) {
			i++
		}
		return b[j:i], nil
	}

	initialLn := func() ([]byte, error) {
		io.Copy(buf, r)
		b = buf.Bytes()
		nextLine = restLn
		return restLn()
	}
	nextLine = initialLn
}

// Setup nextToken without input buffer.
func SetUnbefferedInput(r io.Reader) {
	buf := bufio.NewReader(r)
	var b []byte

	var i int
	nextToken = func() ([]byte, error) {
		var err error
		if i == len(b) {
			b, err = buf.ReadBytes('\n')
			if err != nil {
				return nil, err
			}
			i = 0
			j := len(b) - 1
			for 0 <= j && IsSpace(b[j]) {
				j--
			}
			b = b[0 : j+1]
		}
		for i < len(b) && IsSpace(b[i]) {
			i++
		}
		j := i
		for i < len(b) && !IsSpace(b[i]) {
			i++
		}
		if i == j {
			return nil, io.ErrUnexpectedEOF
		}
		return b[j:i], nil
	}
}

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

// IO functions

// Reads next token and return it as []byte
func readb() []byte {
	b, err := nextToken()
	if err != nil {
		panic(err)
	}
	return b
}

// Reads next token and return it as string
func reads() string {
	return string(readb())
}

// Read next line as []byte
func readbln() []byte {
	b, err := nextLine()
	if err != nil {
		panic(err)
	}
	return b
}

// Read next line as string
func readsln() string {
	return string(readbln())
}

// Reads next token and return it as int64
func readll() int64 {
	i, err := strconv.ParseInt(reads(), 10, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// Reads next token and return it as int
func readi() int {
	return int(readll())
}

// Reads next token and return it as float64
func readf() float64 {
	f, err := strconv.ParseFloat(reads(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// Write args to OutputWriter with the format f
func printf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(OutputWriter, f, args...)
}

// Write args to OutputWriter without format
func println(args ...interface{}) (int, error) {
	return fmt.Fprintln(OutputWriter, args...)
}

// Write args to stderr with the format f
func eprintf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(os.Stderr, f, args...)
}

// Write args to stderr without format
func eprintln(args ...interface{}) (int, error) {
	return fmt.Fprintln(os.Stderr, args...)
}

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

// Simple math functions

const (
	// big prime
	INF  = 1000000007
	INF2 = 1000000009
	INF3 = 998244353
)

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

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

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

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

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

func absll(a int64) int64 {
	if a < 0 {
		return -a
	}
	return a
}

// egcd(a, b) returns d, x, y:
//   d is gcd(a,b)
//   x, y are  integers that satisfy ax + by = d
func egcd(a, b int) (int, int, int) {
	if b == 0 {
		return a, 1, 0
	}
	d, x, y := egcd(b, a%b)
	return d, y, x - a/b*y
}

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

func gcd(a, b int) int {
	d, _, _ := egcd(a, b)
	return d
}

func gcdll(a, b int64) int64 {
	d, _, _ := egcdll(a, b)
	return d
}

// set up IO functions
func init() {
	// for non-interactive
	SetInput(os.Stdin)
	SetOutput(os.Stdout)

	// Enable below when interactive.  Its ok to leave above intact.
	// SetInteractive(os.Stdout, os.Stdin)
}

func main() {
	defer Flush()

	n := readi()
	x := make([]int, n)
	for i := range x {
		x[i] = readi()
	}
	var odd, even int
	for _, v := range x {
		if v%2 == 0 {
			even++
		} else {
			odd++
		}
	}
	println(min(odd, even))
}

package main

import "fmt"

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

func main() {
	var n, x int
	fmt.Scan(&n)
	cnt := 0
	for i := 0; i < n; i++ {
		fmt.Scan(&x)
		if x%2 == 0 {
			cnt++
		}
	}
	fmt.Println(min(cnt, n-cnt))
}

package main

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

func main() {
	sc := NewScanner()
	_ = sc.NextInt()
	A := sc.NextIntArray()
	mn := -1
	for _, v := range A {
		count := 0
		for _, q := range A {
			if (v+q)%2 == 1 {
				count++
			}
		}
		if mn == -1 || count < mn {
			mn = count
		}
	}

	fmt.Println(mn)
}

type Scanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewScanner() *Scanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1000)
	return &Scanner{r: rdr}
}
func (s *Scanner) Next() string {
	s.pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	result := string(s.buf[start:s.p])
	s.p++
	return result
}
func (s *Scanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *Scanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}
func (s *Scanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(s.Next(), 10, 64)
	return v
}

func (s *Scanner) NextFloat() float64 {
	v, _ := strconv.ParseFloat(s.Next(), 64)
	return v
}

func (s *Scanner) NextIntArray() []int {
	s.pre()
	start := s.p
	result := []int{}
	for ; s.p < len(s.buf)+1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 0)
			result = append(result, int(v))
			start = s.p + 1
		}
	}

	return result
}
func (s *Scanner) NextInt64Array() []int64 {
	s.pre()
	start := s.p
	result := []int64{}
	for ; s.p < len(s.buf)+1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 64)
			result = append(result, v)
			start = s.p + 1
		}
	}
	return result
}

func (s *Scanner) NextMap() map[int]bool {
	s.pre()
	start := s.p
	mp := map[int]bool{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			mp[v] = true
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	mp[v] = true

	return mp
}

func (s *Scanner) pre() {
	if s.p >= len(s.buf) {
		s.readLine()
		s.p = 0
	}
}
func (s *Scanner) readLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, e := s.r.ReadLine()
		if e != nil {
			panic(e)
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}

package main
import "fmt"
import "bufio"
import "os"

var input *bufio.Reader

func main(){
	input = bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscanf(input, "%d\n", &n)
	ans := 0
	for i:=0; i<n; i++ {
		var x int
		fmt.Fscanf(input, "%d", &x)
		if x%2==0 {
			ans++
		}
	}
	if ans>n-ans {
		ans=n-ans
	}
	fmt.Println(ans)
}

package main

import "fmt"

func solve(n int, x []int) int {
	var co int = 0
	var ce int = 0
    for i := 0; i < n; i++ {
		if x[i] % 2 == 0 {
			co += 1
		} else{
			ce += 1
		}
	}
	if co >= ce {
		return ce
	}
	return co
}

func main() {
    var n int
    var x []int
    fmt.Scanf("%d\n", &n)
    for i := 0; i < n; i++ {
        var xi int
        fmt.Scanf("%d", &xi)
        x = append(x, xi)
    }
	ret := solve(n, x)
    fmt.Println(ret)
}

package main

import (
	"fmt"
	"sort"
)

// reusable

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

func valueCounts(arr []int) map[int]int {
	dict := make(map[int]int)
	for _, num := range arr {
		dict[num] = dict[num] + 1
	}
	return dict
}

func minArray(arr []int) int {
	sort.Ints(arr)
	return arr[0]
}

func read() []int {
	var n int
	fmt.Scan(&n)
	input := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&input[i])
	}
	return input
}

// solution

func movePrice(elem int, elemCount int, elemTo int) int {
	posDiff := abs(elemTo - elem)
	price := 0
	if posDiff%2 != 0 {
		price++
	}
	price *= elemCount
	return price
}

func solve(input []int) int {
	// initialization
	coinCounts := valueCounts(input)
	coins := make([]int, 0, len(coinCounts))
	for k := range coinCounts {
		coins = append(coins, k)
	}
	movePrices := make([]int, len(coinCounts))
	// calculate final price for each target coin
	for i, targetCoin := range coins {
		for otherCoin, otherCoinCount := range coinCounts {
			if targetCoin != otherCoin {
				movePrices[i] += movePrice(otherCoin, otherCoinCount, targetCoin)
			}
		}
	}
	ans := minArray(movePrices)
	return ans
}

func main() {
	input := read()
	fmt.Println(solve(input))
}

package main

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

func main() {

	//stdin, err := os.Open("in.txt")
	//if err != nil {
	//	panic(err)
	//}
	//defer stdin.Close()
	stdin := os.Stdin
	reader := bufio.NewReaderSize(stdin, 1024*1024)

	//stdout, err := os.Create("test.txt")
	//if err != nil {
	//	panic(err)
	//}
	//defer stdout.Close()
	stdout := os.Stdout
	writer := bufio.NewWriterSize(stdout, 1024*1024)

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

	var a, odd, even int
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d", &a)
		if a%2 == 0 {
			even++
		} else {
			odd++
		}
	}

	if odd < even {
		fmt.Fprintf(writer, "%d\n", odd)
	} else {
		fmt.Fprintf(writer, "%d\n", even)
	}

	writer.Flush()
}

package main

import "fmt"

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

func main() {
	var n int
	fmt.Scan(&n)
	count := 0
	var x int
	for i := 0; i < n; i++ {
		fmt.Scan(&x)
		if x%2 == 0 {
			count++
		}
	}
	fmt.Println(min(count, n-count))
}

// Codeforces 1.12.6
// AtCoder 1.6
// Paiza 1.7.3

package main

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

type in struct {
	Scanner *bufio.Scanner
}

func (in *in) s() string {
	in.Scanner.Scan()
	return in.Scanner.Text()
}
func (in *in) i() int64 {
	return in.ibase(10)
}
func (in *in) ibase(base int) int64 {
	i, _ := strconv.ParseInt(in.s(), base, 64)
	return i
}
func (in *in) f() float64 {
	i, _ := strconv.ParseFloat(in.s(), 64)
	return i
}
func (in *in) ss(n int64) []string {
	a := make([]string, n)
	for i := range a {
		a[i] = in.s()
	}
	return a
}
func (in *in) is(n int64) []int64 {
	a := make([]int64, n)
	for i := range a {
		a[i] = in.i()
	}
	return a
}
func (in *in) fs(n int64) []float64 {
	a := make([]float64, n)
	for i := range a {
		a[i] = in.f()
	}
	return a
}
func (in *in) imat(h int64, w int64) [][]int64 {
	a := make([][]int64, h)
	for y := range a {
		a[y] = make([]int64, w)
		for x := range a[y] {
			a[y][x] = in.i()
		}
	}
	return a
}

func stdin() in {
	scn := bufio.NewScanner(os.Stdin)
	scn.Split(bufio.ScanWords)
	max := 1048576
	buf := make([]byte, max)
	scn.Buffer(buf, max)
	return in{Scanner: scn}
}

type lm struct{}

func (*lm) max(a ...int64) int64 {
	t := a[0]
	for _, v := range a {
		if t < v {
			t = v
		}
	}
	return t
}
func (*lm) min(a ...int64) int64 {
	t := a[0]
	for _, v := range a {
		if t > v {
			t = v
		}
	}
	return t
}
func (*lm) sum(a ...int64) int64 {
	t := int64(0)
	for _, v := range a {
		t += v
	}
	return t
}
func (*lm) abs(a int64) int64 {
	if a < 0 {
		return -a
	}
	return a
}
func (lm *lm) gcd(a, b int64) int64 {
	// returns greatest common divisor.
	if a < b {
		a, b = b, a
	}
	if b == 0 {
		return a
	}
	return lm.gcd(b, a%b)
}
func (lm *lm) lcm(a, b int64) int64 {
	// returns least common multiple.
	gcd := lm.gcd(a, b)
	return gcd * (a / gcd) * (b / gcd)
}

type su struct{}

func (*su) iarr(arr []int64) string {
	// int slice to string.
	ret := make([]string, len(arr))
	for i, x := range arr {
		ret[i] = strconv.FormatInt(x, 10)
	}
	return strings.Join(ret, " ")
}
func (*su) ilns(arr []int64) string {
	// int slice to string.
	ret := make([]string, len(arr))
	for i, x := range arr {
		ret[i] = strconv.FormatInt(x, 10)
	}
	return strings.Join(ret, "\n")
}
func (su *su) imat(matrix [][]int64) string {
	// int slice matrix to string.
	ret := make([]string, len(matrix))
	for i := range matrix {
		ret[i] = su.iarr(matrix[i])
	}
	return strings.Join(ret, "\n")
}
func (*su) bool(b bool) str {
	if b {
		return "Yes"
	}
	return "No"
}

type str string

func (s str) upper() string { return strings.ToUpper(string(s)) }
func (s str) lower() string { return strings.ToLower(string(s)) }

type runes []rune

func (p runes) Len() int           { return len(p) }
func (p runes) Less(i, j int) bool { return p[i] < p[j] }
func (p runes) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }

type comps [][]int64

func (p comps) Len() int { return len(p) }
func (p comps) Less(i, j int) bool {
	for x := range p[0] {
		// Yes, every row in matrix must have the same length.
		if p[i][x] < p[j][x] {
			return true
		}
	}
	return false
}

func (p comps) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p *comps) Push(arr interface{}) {
	x := arr.([]int64)
	*p = append(*p, x)
}
func (p *comps) Pop() interface{} {
	// https://golang.org/pkg/container/heap/
	var ret []int64
	n := len(*p)
	ret, *p = (*p)[n-1], (*p)[0:n-1]
	return ret
}
func (p *comps) pop() []int64 {
	x := heap.Pop(p).([]int64)
	return x
}

func main() {
	// utilities.
	const zr int64 = int64(0)
	const mod int64 = int64(1000000007)
	in, lm, su := stdin(), lm{}, su{}
	_, _, _ = in, lm, su

	// --- read here.
	n := in.i()
	x := in.is(n)

	// --- solve here.
	odds := zr
	for _, v := range x {
		odds += v % 2
	}
	ans := lm.min(n-odds, odds)

	// --- print here.
	fmt.Println(ans)
}

package main

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

func main()  {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var  n int
	fmt.Fscan(in,&n)

//	fmt.Println(len(array));
	var x int
	juft,toq := 0,0
	for i := 0 ; i < n ;i ++{
		fmt.Fscan(in,&x)
		if x % 2 == 0{
			juft ++
		}else{
			toq ++
		}

	}
	if juft < toq{
		fmt.Fprint(out,juft)
	}else{
		fmt.Fprint(out,toq)
	}

}

package main

import (
	"fmt"
)

func main() {
	var q, n, k, cnt int

	// scr := bufio.NewReader(os.Stdin)
	// ocr := bufio.NewWriter(os.Stdout)

	fmt.Scanln(&n)

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

		if i == 0 {
			if k%2 == 0 {
				q = 1
			} else {
				q = 0
			}
		} else {
			if q == 1 && k%2 == 1 {
				cnt++
			} else if q == 0 && k%2 == 0 {
				cnt++
			}
		}

	}

	fmt.Println(cnt)

}

package main

import "fmt"

func main() {
	var n int
	t1, t2 := 0, 0
	_, _ = fmt.Scanf("%d", &n)
	for i := 0; i < n; i++ {
		var x int
		_, _ = fmt.Scanf("%d", &x)
		if x&1 != 0 {
			t1++
		} else {
			t2++
		}
	}
	if t1 > t2 {
		fmt.Println(t2)
	} else {
		fmt.Println(t1)
	}
}

package main

import "fmt"

func solve(n int, x []int) int {
	var co int = 0
	var ce int = 0
    for i := 0; i < n; i++ {
		if x[i] & 1 != 0 {
			co += 1
		} else{
			ce += 1
		}
	}
	if co > ce {
		return ce
	}
	return co
}

func main() {
    var n int
    var x []int
    fmt.Scanf("%d\n", &n)
    for i := 0; i < n; i++ {
        var xi int
        fmt.Scanf("%x", &xi)
        x = append(x, xi)
    }
	ret := solve(n, x)
    fmt.Println(ret)
}

package main

import "fmt"

func solve(n int, x []int) int {
    var co, ce int
    for i := 0; i < n; i++ {
		tmp := x[i] & 1
		if tmp == 1 {
			co += 1
		} else{
			ce += 1
		}
	}
	if co > ce {
		return ce
	}
	return co
}

func main() {
    var n int
    var x []int
    fmt.Scanf("%d\n", &n)
    for i := 0; i < n; i++ {
        var xi int
        fmt.Scanf("%x", &xi)
        x = append(x, xi)
    }
	ret := solve(n, x)
    fmt.Println(ret)
}

package main

import "fmt"

func solve(n int, x []int) int {
    var co, ce int
    for i := 0; i < n; i++ {
		if x[i] & 1 != 0 {
			co += 1
		} else{
			ce += 1
		}
	}
	if co > ce {
		return ce
	}
	return co
}

func main() {
    var n int
    var x []int
    fmt.Scanf("%d\n", &n)
    for i := 0; i < n; i++ {
        var xi int
        fmt.Scanf("%x", &xi)
        x = append(x, xi)
    }
	ret := solve(n, x)
    fmt.Println(ret)
}

package main

import "fmt"

func solve(n int, x []int) int {
	var co int = 0
	var ce int = 0
    for i := 0; i < n; i++ {
		if x[i] % 2 != 0 {
			co += 1
		} else{
			ce += 1
		}
	}
	if co > ce {
		return ce
	}
	return co
}

func main() {
    var n int
    var x []int
    fmt.Scanf("%d\n", &n)
    for i := 0; i < n; i++ {
        var xi int
        fmt.Scanf("%x", &xi)
        x = append(x, xi)
    }
	ret := solve(n, x)
    fmt.Println(ret)
}

package main

import (
	"fmt"
	)

func main()  {
	var  n int
	fmt.Scanf("%d",&n);

//	fmt.Println(len(array));
	var x int
	juft,toq := 0,0
	for i := 0 ; i < n ;i ++{
		fmt.Scanf("%d",&x)
		if x % 2 == 0{
			juft ++
		}else{
			toq ++
		}

	}
	if juft < toq{
		fmt.Print(juft)
	}else{
		fmt.Print(toq)
	}

}

package main

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

func main()  {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var  n int
	fmt.Fscan(in,&n)

//	fmt.Println(len(array));
	var x int
	juft,toq := 0,0
	for i := 0 ; i < n ;i ++{
		fmt.Scanf("%d",&x)
		if x % 2 == 0{
			juft ++
		}else{
			toq ++
		}

	}
	ans := 0
	if juft < toq{
		ans = juft
	}else{
		ans = toq
	}
	fmt.Fprint(out,ans)

}

package main

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

func main()  {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var  n int
	fmt.Fscan(in,&n)

//	fmt.Println(len(array));
	var x int
	juft,toq := 0,0
	for i := 0 ; i < n ;i ++{
		fmt.Scanf("%d",&x)
		if x % 2 == 0{
			juft ++
		}else{
			toq ++
		}

	}
	if juft < toq{
		fmt.Fprint(out,juft)
	}else{
		fmt.Fprint(out,toq)
	}

}


package main

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

type Scanner struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) *Scanner {
	scanner := bufio.NewScanner(reader)
	scanner.Split(bufio.ScanWords)
	return &Scanner{scanner}
}

func (s *Scanner) Word() string {
	s.Scan()
	return s.Text()
}

func (s *Scanner) Int() int {
	s.Scan()
	n, _ := strconv.Atoi(s.Text())
	return n
}

func (s *Scanner) Int64() int64 {
	s.Scan()
	n, _ := strconv.ParseInt(s.Text(), 10, 64)
	return n
}

func (s *Scanner) Ints(count int) []int {
	ints := make([]int, count)
	for i := range ints {
		ints[i] = s.Int()
	}
	return ints
}

func (s *Scanner) Int64s(count int) []int64 {
	int64s := make([]int64, count)
	for i := range int64s {
		int64s[i] = s.Int64()
	}
	return int64s
}

func solve(v []int, k int) []int {
	pos := make(map[int][]int)
	for i, num := range v {
		if len(pos[num]) < k {
			pos[num] = append(pos[num], i)
		}
	}

	colors := make([]int, len(v))
	lastPos := make([]int, k)
	index := 0

	for _, p := range pos {
		for _, actualPos := range p {
			colors[actualPos] = index + 1
			lastPos[index] = actualPos
			index = (index + 1) % k
		}
	}
	for i := 0; i < index; i += 1 {
		colors[lastPos[i]] = 0
	}
	return colors
}

func main() {
	stdin := NewWordScanner(os.Stdin)
	tests := stdin.Int()

	for i := 0; i < tests; i += 1 {
		n, k := stdin.Int(), stdin.Int()
		v := stdin.Ints(n)

		for _, color := range solve(v, k) {
			fmt.Printf("%d ", color)
		}
		fmt.Println()
	}
}

package main

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

type e struct {
	idx int
	v   int
	c   int
}

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

	var T int
	fmt.Fscan(in, &T)
	for t := 0; t < T; t++ {
		var n, k int
		fmt.Fscan(in, &n, &k)

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

			arr[i] = e{i, v, 0}
		}

		sort.SliceStable(arr, func(i, j int) bool {
			return arr[i].v < arr[j].v
		})

		color := 1
		freq := 1
		arr[0].c = 1
		for i := 1; i < n; i++ {
			if arr[i].v == arr[i-1].v {
				freq++
			} else {
				freq = 1
			}

			if freq > k {
				continue
			}

			color++
			if color > k {
				color = 1
			}
			arr[i].c = color
			if arr[i].c == 0 {
				arr[i].c = k
			}
		}

		if color != k {
			for i := 1; i <= color; i++ {
				for j := range arr {
					if arr[j].c == i {
						arr[j].c = 0
						break
					}
				}
			}
		}

		arr2 := make([]int, n)
		for _, e2 := range arr {
			arr2[e2.idx] = e2.c
		}

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

package main

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

type e struct {
	idx int
	v   int
	c   int
}

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

	var T int
	fmt.Fscan(in, &T)
	for t := 0; t < T; t++ {
		var n, k int
		fmt.Fscan(in, &n, &k)

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

			arr[i] = e{i, v, 0}
		}

		sort.SliceStable(arr, func(i, j int) bool {
			return arr[i].v < arr[j].v
		})

		color := 1
		freq := 1
		arr[0].c = 1
		for i := 1; i < n; i++ {
			if arr[i].v == arr[i-1].v {
				freq++
			} else {
				freq = 1
			}

			if freq > k {
				continue
			}

			color++
			arr[i].c = color % k
			if arr[i].c == 0 {
				arr[i].c = k
			}
		}

		if color%k != 0 {
			for i := 1; i <= color%k; i++ {
				for j := range arr {
					if arr[j].c == i {
						arr[j].c = 0
						break
					}
				}
			}
		}

		arr2 := make([]int, n)
		for _, e2 := range arr {
			arr2[e2.idx] = e2.c
		}

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

package main

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

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

	solve := func(Case int) {
		var n, k int
		Fscan(in, &n, &k)
		type pair struct{ v, i int }
		a := make([]pair, n)
		c := make([]int, n+1)
		for i := range a {
			Fscan(in, &a[i].v)
			c[a[i].v]++
			a[i].i = i
		}
		sort.Slice(a, func(i, j int) bool { return a[i].v < a[j].v })

		ans := make([]int, n)

		tot := 0
		for i, v := range c {
			if v > k {
				v = k
				c[i] = k
			}
			tot += v
		}
		tot -= tot % k

		color := 1
		for _, p := range a {
			if c[p.v] == 0 || tot == 0 {
				continue
			}
			ans[p.i] = color
			color++
			if color > k {
				color = 1
			}
			c[p.v]--
			tot--
		}

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

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

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

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

package main

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

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

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

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

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

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

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

func main() {
	defer writer.Flush()
	for t := _int(); t > 0; t-- {
		n := _int()
		k := _int()
		a := make([]int, n)
		for i := range a {
			a[i] = _int()
		}
		res := sol(n, k, a)
		for _, d := range res {
			printf("%d ", d)
		}
		printf("\n")
	}
}

func sol(n, k int, a []int) []int {
	m, c := getReverseMap(a, k)
	ass := make([]int, n)
	p := 1
	for _, indexes := range m {
		for j := range indexes {
			if p == 1 && c < k {
				break
			}
			ass[indexes[j]] = p
			p++
			c--
			if p > k {
				p -= k
			}
		}
	}
	return ass
}

func getReverseMap(a []int, k int) (map[int][]int, int) {
	ret := map[int][]int{}
	count := 0
	for i := range a {
		if len(ret[a[i]]) == k {
			continue
		}
		ret[a[i]] = append(ret[a[i]], i)
		count++
	}
	return ret, count
}

package main

import (
    "fmt"
    "bufio"
    "os"
    // "strings"
    "strconv"
	// "sort"
	// "math"
)

func main() {
    reader := bufio.NewReader(os.Stdin)
    input, _ := reader.ReadString('\n')

	// Get t
	t, _ := GetInt(input)

	for i:=0; i<t; i++ {
		input, _ =  reader.ReadString('\n')
		var n, k int
		n, input = GetInt(input)
		k, _ = GetInt(input)

		input, _ = reader.ReadString('\n')
		// Get nums
		bucket, m := make(map[int][]int), 0
		for j:=0; j<n; j++ {
			var num int
			num, input = GetInt(input)
			if len(bucket[num]) < k {
				bucket[num] = append(bucket[num], j)
				m++
			}
		}

		m -= m%k
		color, result := 0, make([]int, n)
		for _, positions := range bucket {
			for _, val := range positions {
				result[val] = color+1
				color++; color %= k
				m--
				if m == 0 {
					goto output
				}
			}
		}
output:
		for _, val := range result {
			fmt.Printf("%d ", val)
		}
		fmt.Println()
	}
}

// func abs(val float64) float64 {
//     if val >= 0.0 {
//         return val
//     }
//     return -val
// }

func GetInt(s string) (result int, output string) {
	iter, n := 0, len(s)
	for iter < n && s[iter] >= '0' && s[iter] <= '9' {
		iter++
	}
	result, _ = strconv.Atoi(s[:iter])
	// Skip the redundant characters
	for iter < n && (s[iter] < '0' || s[iter] > '9') {
		iter++
	}
	if iter == n {
		output = ""

	} else {
		output = s[iter:]
	}
	return
}

func GetInt64(s string) (result int64, output string) {
	iter, n := 0, len(s)
	for iter < n && s[iter] >= '0' && s[iter] <= '9' {
		iter++
	}
	result, _ = strconv.ParseInt(s[:iter], 10, 64)
	// Skip the redundant characters
	for iter < n && (s[iter] < '0' || s[iter] > '9') {
		iter++
	}
	if iter == n {
		output = ""

	} else {
		output = s[iter:]
	}
	return
}

package main

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

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

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

type pair struct{ v, i int }

func main() {
	defer out.Flush()

	var (
		n, t, k int
	)
	fmt.Fscanf(in, "%d", &t)
	for t > 0 {
		t--
		fmt.Fscan(in, &n, &k)
		a := make([]pair, n)
		num := make([]int, n+1)
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &a[i].v)
			a[i].i = i
			num[a[i].v]++
		}
		sort.Slice(a, func(i, j int) bool { return a[i].v > a[j].v })
		ans := make([]int, n)
		tot := 0
		for i, v := range num {
			if v > k {
				v = k
				num[i] = k
			}
			tot += v
		}
		tot = tot - tot%k
		color := 1
		for _, p := range a {
			if tot == 0 || num[p.v] == 0 {
				continue
			}
			ans[p.i] = color
			color++
			if color > k {
				color = 1
			}
			num[p.v]--
			tot--
		}
		for i := 0; i < n; i++ {
			printf("%d ", ans[i])
		}
		printf("\n")
	}

}

package main

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

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

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

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

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

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

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

type pair struct{ v, i int }

func main() {
	defer writer.Flush()

	var (
		n, t, k int
	)
	t = _int()
	for t > 0 {
		t--
		n = _int()
		k = _int()
		a := make([]pair, n)
		num := make([]int, n+1)
		for i := 0; i < n; i++ {
			a[i].v = _int()
			a[i].i = i
			num[a[i].v]++
		}
		sort.Slice(a, func(i, j int) bool { return a[i].v > a[j].v })
		ans := make([]int, n)
		tot := 0
		for i, v := range num {
			if v > k {
				v = k
				num[i] = k
			}
			tot += v
		}
		tot = tot - tot%k
		color := 1
		for _, p := range a {
			if tot == 0 || num[p.v] == 0 {
				continue
			}
			ans[p.i] = color
			color++
			if color > k {
				color = 1
			}
			num[p.v]--
			tot--
		}
		for i := 0; i < n; i++ {
			printf("%d ", ans[i])
		}
		printf("\n")
	}

}

package main

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

type Pair struct {
	count int
	num int
}
func (p *Pair) String() string {
	return fmt.Sprintf("{count: %d, num: %d}", p.count, p.num)
}
type Pairs []*Pair

func (p Pairs) Len() int {
	return len(p)
}

func (p Pairs) Less(i, j int) bool {
	return p[i].count < p[j].count
}

func (p Pairs) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

type Color struct {
	current int
	total int
	startColor int
}

func (c *Color) String() string {
	return fmt.Sprintf("{cur: %d, total: %d, startColor: %d}", c.current, c.total, c.startColor)
}

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

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

	for tc := 0; tc < t; tc++ {
		var n, k int
		fmt.Fscan(r, &n, &k)
		nums := make([]int, n, n)
		numMap := make(map[int]int, n)
		results := make([]int, n, n)
		var totalUsable int
		for i := 0; i < n; i++ {
			fmt.Fscan(r, &nums[i])
			if numMap[nums[i]] < k {
				numMap[nums[i]] += 1
			}
		}
		pairs := make(Pairs, len(numMap), len(numMap))
		idx := 0
		for key, value := range numMap {
			pairs[idx] = &Pair{count: value, num: key}
			idx += 1
			if value < k {
				totalUsable += value
			}
		}
		totalUsable = totalUsable - (totalUsable % k)
		// debug
		// fmt.Printf("DEBUG: totalUsable = %d\n", totalUsable)
		sort.Sort(pairs)
		// debug
		// for _, pair := range pairs {
		// 	fmt.Printf("DEBUG: sorted pair %s\n", pair.String())
		// }

		colorData := make(map[int]*Color, len(pairs))
		colorIdx := 0
		for _, pair := range pairs {
			var (
				t int
				c *Color
			)
			if pair.count >= k {
				t = k
				c = &Color{
					startColor: 0,
					total: t,
					current: 0,
				}
			} else {
				t = pair.count
				if totalUsable < t {
					t = totalUsable
				}
				c = &Color{
					startColor: colorIdx,
					total: t,
					current: 0,
				}
				colorIdx = (colorIdx + t) % k
				totalUsable -= t
			}
			colorData[pair.num] = c
		}

		// debug
		// for num, color := range colorData {
		// 	fmt.Printf("DEBUG: color num %d: %s\n", num, color.String())
		// }

		for i := 0; i < n; i++ {
			num := nums[i]
			color := colorData[num]
			if color.current >= color.total {
				results[i] = 0
			} else {
				results[i] = (color.startColor + color.current) % k + 1
				color.current += 1
			}
		}

		for i := 0; i < n; i++ {
			fmt.Printf("%d ", results[i])
		}
		fmt.Printf("\n")
	}
}

package main

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

type tp struct {
	order int
	val   int
}

func main() {
	rd := bufio.NewReader(os.Stdin)
	wr := bufio.NewWriter(os.Stdout)
	defer wr.Flush()
	var t, n, k, i, lastVal, lastValLen, lenC int
	A := make([]tp, 200000)
	B := make([]int, 200000)
	C := make([]int, 200000)
	fmt.Fscanf(rd, "%d\n", &t)
	for ti := 0; ti < t; ti++ {
		fmt.Fscanf(rd, "%d", &n)
		fmt.Fscanf(rd, "%d\n", &k)
		for i = 0; i < n; i++ {
			A[i].order = i
			fmt.Fscanf(rd, "%d", &(A[i].val))
		}
		fmt.Fscanf(rd, "\n")
		sort.Slice(A[:n], func(i, j int) bool {
			return A[i].val < A[j].val
		})
		lenC = 0
		lastVal = 0
		for i = 0; i < n; i++ {
			if lastVal == A[i].val {
				lastValLen++
			} else {
				lastVal = A[i].val
				lastValLen = 1
			}
			if lastValLen <= k {
				C[lenC] = A[i].order
				lenC++
			}
			B[i] = 0
		}
		for i = 0; i < (lenC/k)*k; i++ {
			B[C[i]] = i%k + 1
		}
		for i = 0; i < n; i++ {
			fmt.Fprintf(wr, "%d ", B[i])
		}
		fmt.Fprintf(wr, "\n")
	}
}

package main

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

type node struct {
	i int
	v int

	c int
}

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

	var t int
	var n, k int
	var v int
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n, &k)
		arr := make([]node, n)
		for i := 0; i < n; i++ {
			Fscan(in, &v)
			arr[i] = node{i, v, 0}
		}
		sort.Slice(arr, func(i, j int) bool {
			return arr[i].v < arr[j].v
		})
		// fmt.Println(arr)
		var m int
		var i, j int
		var t int
		for i = 0; i < n; i = j {
			m = 1
			for j = i + 1; j < n && arr[j].v == arr[i].v; j++ {
			}
			// fmt.Println("i,j", i, j)
			for r := i; r < j; r++ {
				if m <= k {
					arr[r].c = (t % k) + 1
					t++
					m++
				}
			}
		}
		// sort.Slice(arr, func(i, j int) bool {
		//     return arr[i].i < arr[j].i
		// })
		// fmt.Println(arr)
		colors := make([]int, k+1)
		for _, v := range arr {
			colors[v.c]++
		}
		mc := math.MaxInt32
		for i := 1; i <= k; i++ {
			if mc > colors[i] {
				mc = colors[i]
			}
		}
		ans := make([]int, n)
		for _, v := range arr {
			ans[v.i] = v.c
		}
		c := make([]int, k+1)
		for _, v := range ans {
			c[v]++
			if c[v] > mc {
				Fprintf(out, "%d ", 0)
			} else {
				Fprintf(out, "%d ", v)
			}
		}
		Fprintln(out)
	}
}

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

package main

import (
    "fmt"
    "bufio"
    "os"
    // "strings"
    "strconv"
	"sort"
	// "math"
)

type card struct {
	amount int
	positions []int
}

func main() {
    reader := bufio.NewReader(os.Stdin)
    input, _ := reader.ReadString('\n')

	// Get t
	t, _ := GetInt(input)

	for i:=0; i<t; i++ {
		input, _ =  reader.ReadString('\n')
		var n, k int
		n, input = GetInt(input)
		k, _ = GetInt(input)

		input, _ = reader.ReadString('\n')
		// Get nums
		bucket := make(map[int]*card)
		for j:=0; j<n; j++ {
			var num int
			num, input = GetInt(input)
			if bucket[num] == nil {
				bucket[num] = &card{0, []int{}}
			}
			bucket[num].amount++
			bucket[num].positions = append(bucket[num].positions, j)
		}

		// Binary search the number of painted cards of each color
		left, right := 0, n/k
		for left < right {
			mid := left + (right - left + 1) >> 1
			if check(bucket, k, mid) {
				left = mid

			} else {
				right = mid - 1
			}
		}
		max_card := left
		fmt.Println(max_card)
		result, cups := make([]int, n), [][]int{}
		for key, val := range bucket {
			cups = append(cups, []int{val.amount, key})
		}
		for cnt:=1; cnt<=k; cnt++ {
			sort.Slice(cups, func(l, r int) bool {
				return cups[l][0] > cups[r][0]
			})
			sum := 0
			for i, val := range cups {
				if sum == max_card {
					break
				}
				if val[0] > 0 {
					cups[i][0]--; sum++
					pos := len(bucket[val[1]].positions)-1
					result[bucket[val[1]].positions[pos]] = cnt
					bucket[val[1]].positions = bucket[val[1]].positions[:pos]

				}
			}
		}
		// fmt.Println(result)
		for _, val := range result {
			fmt.Printf("%d ", val)
		}
		fmt.Println()
	}
}

// func abs(val float64) float64 {
//     if val >= 0.0 {
//         return val
//     }
//     return -val
// }

func GetInt(s string) (result int, output string) {
	iter, n := 0, len(s)
	for iter < n && s[iter] >= '0' && s[iter] <= '9' {
		iter++
	}
	result, _ = strconv.Atoi(s[:iter])
	// Skip the redundant characters
	for iter < n && (s[iter] < '0' || s[iter] > '9') {
		iter++
	}
	if iter == n {
		output = ""

	} else {
		output = s[iter:]
	}
	return
}

func GetInt64(s string) (result int64, output string) {
	iter, n := 0, len(s)
	for iter < n && s[iter] >= '0' && s[iter] <= '9' {
		iter++
	}
	result, _ = strconv.ParseInt(s[:iter], 10, 64)
	// Skip the redundant characters
	for iter < n && (s[iter] < '0' || s[iter] > '9') {
		iter++
	}
	if iter == n {
		output = ""

	} else {
		output = s[iter:]
	}
	return
}

func check(bucket map[int]*card, k, mid int) bool {
	cups := []int{}
	for _, val := range bucket {
		cups = append(cups, val.amount)
	}

	// Greedy: Get card from the bucket with most cards
	for i:=0; i<k; i++ {
		sort.Slice(cups, func(l, r int) bool {
			return cups[l] > cups[r]
		})
		sum := 0
		for i, val := range cups {
			if sum == mid {
				break
			}
			if val > 0 {
				cups[i]--; sum++

			} else {
				break
			}
		}
		if sum != mid {
			return false
		}
	}
	return true
}

package main

import (
    "fmt"
    "bufio"
    "os"
    // "strings"
    "strconv"
	"sort"
	// "math"
)

type card struct {
	amount int
	positions []int
}

func main() {
    reader := bufio.NewReader(os.Stdin)
    input, _ := reader.ReadString('\n')

	// Get t
	t, _ := GetInt(input)

	for i:=0; i<t; i++ {
		input, _ =  reader.ReadString('\n')
		var n, k int
		n, input = GetInt(input)
		k, _ = GetInt(input)

		input, _ = reader.ReadString('\n')
		// Get nums
		bucket := make(map[int]*card)
		for j:=0; j<n; j++ {
			var num int
			num, input = GetInt(input)
			if bucket[num] == nil {
				bucket[num] = &card{0, []int{}}
			}
			bucket[num].amount++
			bucket[num].positions = append(bucket[num].positions, j)
		}

		// Binary search the number of painted cards of each color
		left, right := 0, n/k
		for left < right {
			mid := left + (right - left + 1) >> 1
			if check(bucket, k, mid) {
				left = mid

			} else {
				right = mid - 1
			}
		}
		max_card := left
		// fmt.Println(max_card)
		result, cups := make([]int, n), [][]int{}
		for key, val := range bucket {
			cups = append(cups, []int{val.amount, key})
		}
		for cnt:=1; cnt<=k; cnt++ {
			sort.Slice(cups, func(l, r int) bool {
				return cups[l][0] > cups[r][0]
			})
			sum := 0
			for _, val := range cups {
				if sum == max_card {
					break
				}
				if val[0] > 0 {
					val[0]--; sum++
					pos := len(bucket[val[1]].positions)-1
					result[bucket[val[1]].positions[pos]] = cnt
					bucket[val[1]].positions = bucket[val[1]].positions[:pos]
				}
			}
		}
		// fmt.Println(result)
		for _, val := range result {
			fmt.Printf("%d ", val)
		}
		fmt.Println()
	}
}

// func abs(val float64) float64 {
//     if val >= 0.0 {
//         return val
//     }
//     return -val
// }

func GetInt(s string) (result int, output string) {
	iter, n := 0, len(s)
	for iter < n && s[iter] >= '0' && s[iter] <= '9' {
		iter++
	}
	result, _ = strconv.Atoi(s[:iter])
	// Skip the redundant characters
	for iter < n && (s[iter] < '0' || s[iter] > '9') {
		iter++
	}
	if iter == n {
		output = ""

	} else {
		output = s[iter:]
	}
	return
}

func GetInt64(s string) (result int64, output string) {
	iter, n := 0, len(s)
	for iter < n && s[iter] >= '0' && s[iter] <= '9' {
		iter++
	}
	result, _ = strconv.ParseInt(s[:iter], 10, 64)
	// Skip the redundant characters
	for iter < n && (s[iter] < '0' || s[iter] > '9') {
		iter++
	}
	if iter == n {
		output = ""

	} else {
		output = s[iter:]
	}
	return
}

func check(bucket map[int]*card, k, mid int) bool {
	cups := []int{}
	for _, val := range bucket {
		cups = append(cups, val.amount)
	}

	// Greedy: Get card from the bucket with most cards
	for i:=0; i<k; i++ {
		sort.Slice(cups, func(l, r int) bool {
			return cups[l] > cups[r]
		})
		sum := 0
		for _, val := range cups {
			if sum == mid {
				break
			}
			if val > 0 {
				val--; sum++
			}
		}
		if sum != mid {
			return false
		}
	}
	return true
}

package main

import (
    "fmt"
    "bufio"
    "os"
    // "strings"
    "strconv"
	"sort"
	// "math"
)

type card struct {
	amount int
	positions []int
}

func main() {
    reader := bufio.NewReader(os.Stdin)
    input, _ := reader.ReadString('\n')

	// Get t
	t, _ := GetInt(input)

	for i:=0; i<t; i++ {
		input, _ =  reader.ReadString('\n')
		var n, k int
		n, input = GetInt(input)
		k, _ = GetInt(input)

		input, _ = reader.ReadString('\n')
		// Get nums
		bucket := make(map[int]*card)
		for j:=0; j<n; j++ {
			var num int
			num, input = GetInt(input)
			if bucket[num] == nil {
				bucket[num] = &card{0, []int{}}
			}
			bucket[num].amount++
			bucket[num].positions = append(bucket[num].positions, j)
		}

		// Binary search the number of painted cards of each color
		left, right := 1, n/k
		for left < right {
			mid := left + (right - left + 1) >> 1
			if check(bucket, k, mid) {
				left = mid

			} else {
				right = mid - 1
			}
		}
		max_card := left
		// fmt.Println(max_card)
		result, cups := make([]int, n), [][]int{}
		for key, val := range bucket {
			cups = append(cups, []int{val.amount, key})
		}
		for cnt:=1; cnt<=k; cnt++ {
			sort.Slice(cups, func(l, r int) bool {
				return cups[l][0] > cups[r][0]
			})
			sum := 0
			for _, val := range cups {
				if sum == max_card {
					break
				}
				if val[0] > 0 {
					val[0]--; sum++
					pos := len(bucket[val[1]].positions)-1
					result[bucket[val[1]].positions[pos]] = cnt
					bucket[val[1]].positions = bucket[val[1]].positions[:pos]
				}
			}
		}
		// fmt.Println(result)
		for _, val := range result {
			fmt.Printf("%d ", val)
		}
		fmt.Printf("\n")
	}
}

// func abs(val float64) float64 {
//     if val >= 0.0 {
//         return val
//     }
//     return -val
// }

func GetInt(s string) (result int, output string) {
	iter, n := 0, len(s)
	for iter < n && s[iter] >= '0' && s[iter] <= '9' {
		iter++
	}
	result, _ = strconv.Atoi(s[:iter])
	// Skip the redundant characters
	for iter < n && (s[iter] < '0' || s[iter] > '9') {
		iter++
	}
	if iter == n {
		output = ""

	} else {
		output = s[iter:]
	}
	return
}

func GetInt64(s string) (result int64, output string) {
	iter, n := 0, len(s)
	for iter < n && s[iter] >= '0' && s[iter] <= '9' {
		iter++
	}
	result, _ = strconv.ParseInt(s[:iter], 10, 64)
	// Skip the redundant characters
	for iter < n && (s[iter] < '0' || s[iter] > '9') {
		iter++
	}
	if iter == n {
		output = ""

	} else {
		output = s[iter:]
	}
	return
}

func check(bucket map[int]*card, k, mid int) bool {
	cups := []int{}
	for _, val := range bucket {
		cups = append(cups, val.amount)
	}

	// Greedy: Get card from the bucket with most cards
	for i:=0; i<k; i++ {
		sort.Slice(cups, func(l, r int) bool {
			return cups[l] > cups[r]
		})
		sum := 0
		for _, val := range cups {
			if sum == mid {
				break
			}
			if val > 0 {
				val--; sum++
			}
		}
		if sum != mid {
			return false
		}
	}
	return true
}

package main

import (
    "fmt"
    "bufio"
    "os"
    // "strings"
    "strconv"
	"sort"
	// "math"
)

type card struct {
	amount int
	positions []int
}

func main() {
    reader := bufio.NewReader(os.Stdin)
    input, _ := reader.ReadString('\n')

	// Get t
	t, _ := GetInt(input)

	for i:=0; i<t; i++ {
		input, _ =  reader.ReadString('\n')
		var n, k int
		n, input = GetInt(input)
		k, _ = GetInt(input)

		input, _ = reader.ReadString('\n')
		// Get nums
		bucket := make(map[int]*card)
		for j:=0; j<n; j++ {
			var num int
			num, input = GetInt(input)
			if bucket[num] == nil {
				bucket[num] = &card{0, []int{}}
			}
			bucket[num].amount++
			bucket[num].positions = append(bucket[num].positions, j)
		}

		// Binary search the number of painted cards of each color
		left, right := 1, n/k
		for left < right {
			mid := left + (right - left + 1) >> 1
			if check(bucket, k, mid) {
				left = mid

			} else {
				right = mid - 1
			}
		}
		max_card := left
		// fmt.Println(max_card)
		result, cups := make([]int, n), [][]int{}
		for key, val := range bucket {
			cups = append(cups, []int{val.amount, key})
		}
		for cnt:=1; cnt<=k; cnt++ {
			sort.Slice(cups, func(l, r int) bool {
				return cups[l][0] > cups[r][0]
			})
			sum := 0
			for _, val := range cups {
				if sum == max_card {
					break
				}
				if val[0] > 0 {
					val[0]--; sum++
					pos := len(bucket[val[1]].positions)-1
					result[bucket[val[1]].positions[pos]] = cnt
					bucket[val[1]].positions = bucket[val[1]].positions[:pos]
				}
			}
		}
		// fmt.Println(result)
		for _, val := range result {
			fmt.Printf("%d ", val)
		}
	}
}

// func abs(val float64) float64 {
//     if val >= 0.0 {
//         return val
//     }
//     return -val
// }

func GetInt(s string) (result int, output string) {
	iter, n := 0, len(s)
	for iter < n && s[iter] >= '0' && s[iter] <= '9' {
		iter++
	}
	result, _ = strconv.Atoi(s[:iter])
	// Skip the redundant characters
	for iter < n && (s[iter] < '0' || s[iter] > '9') {
		iter++
	}
	if iter == n {
		output = ""

	} else {
		output = s[iter:]
	}
	return
}

func GetInt64(s string) (result int64, output string) {
	iter, n := 0, len(s)
	for iter < n && s[iter] >= '0' && s[iter] <= '9' {
		iter++
	}
	result, _ = strconv.ParseInt(s[:iter], 10, 64)
	// Skip the redundant characters
	for iter < n && (s[iter] < '0' || s[iter] > '9') {
		iter++
	}
	if iter == n {
		output = ""

	} else {
		output = s[iter:]
	}
	return
}

func check(bucket map[int]*card, k, mid int) bool {
	cups := []int{}
	for _, val := range bucket {
		cups = append(cups, val.amount)
	}

	// Greedy: Get card from the bucket with most cards
	for i:=0; i<k; i++ {
		sort.Slice(cups, func(l, r int) bool {
			return cups[l] > cups[r]
		})
		sum := 0
		for _, val := range cups {
			if sum == mid {
				break
			}
			if val > 0 {
				val--; sum++
			}
		}
		if sum != mid {
			return false
		}
	}
	return true
}

package main

import (
    "fmt"
    "bufio"
    "os"
    // "strings"
    "strconv"
	"sort"
	// "math"
)

type card struct {
	amount int
	positions []int
}

func main() {
    reader := bufio.NewReader(os.Stdin)
    input, _ := reader.ReadString('\n')

	// Get t
	t, _ := GetInt(input)

	for i:=0; i<t; i++ {
		input, _ =  reader.ReadString('\n')
		var n, k int
		n, input = GetInt(input)
		k, _ = GetInt(input)

		input, _ = reader.ReadString('\n')
		// Get nums
		bucket := make(map[int]*card)
		for j:=0; j<n; j++ {
			var num int
			num, input = GetInt(input)
			if bucket[num] == nil {
				bucket[num] = &card{0, []int{}}
			}
			bucket[num].amount++
			bucket[num].positions = append(bucket[num].positions, j)
		}

		// Binary search the number of painted cards of each color
		left, right := 1, n/k
		for left < right {
			mid := left + (right - left + 1) >> 1
			if check(bucket, k, mid) {
				left = mid

			} else {
				right = mid - 1
			}
		}
		max_card := left
		fmt.Println(max_card)
		result, cups := make([]int, n), [][]int{}
		for key, val := range bucket {
			cups = append(cups, []int{val.amount, key})
		}
		for cnt:=1; cnt<=k; cnt++ {
			sort.Slice(cups, func(l, r int) bool {
				return cups[l][0] > cups[r][0]
			})
			sum := 0
			for _, val := range cups {
				if sum == max_card {
					break
				}
				if val[0] > 0 {
					val[0]--; sum++
					pos := len(bucket[val[1]].positions)-1
					result[bucket[val[1]].positions[pos]] = cnt
					bucket[val[1]].positions = bucket[val[1]].positions[:pos]
				}
			}
		}
		// fmt.Println(result)
	}
}

// func abs(val float64) float64 {
//     if val >= 0.0 {
//         return val
//     }
//     return -val
// }

func GetInt(s string) (result int, output string) {
	iter, n := 0, len(s)
	for iter < n && s[iter] >= '0' && s[iter] <= '9' {
		iter++
	}
	result, _ = strconv.Atoi(s[:iter])
	// Skip the redundant characters
	for iter < n && (s[iter] < '0' || s[iter] > '9') {
		iter++
	}
	if iter == n {
		output = ""

	} else {
		output = s[iter:]
	}
	return
}

func GetInt64(s string) (result int64, output string) {
	iter, n := 0, len(s)
	for iter < n && s[iter] >= '0' && s[iter] <= '9' {
		iter++
	}
	result, _ = strconv.ParseInt(s[:iter], 10, 64)
	// Skip the redundant characters
	for iter < n && (s[iter] < '0' || s[iter] > '9') {
		iter++
	}
	if iter == n {
		output = ""

	} else {
		output = s[iter:]
	}
	return
}

func check(bucket map[int]*card, k, mid int) bool {
	cups := []int{}
	for _, val := range bucket {
		cups = append(cups, val.amount)
	}

	// Greedy: Get card from the bucket with most cards
	for i:=0; i<k; i++ {
		sort.Slice(cups, func(l, r int) bool {
			return cups[l] > cups[r]
		})
		sum := 0
		for _, val := range cups {
			if sum == mid {
				break
			}
			if val > 0 {
				val--; sum++
			}
		}
		if sum != mid {
			return false
		}
	}
	return true
}

package main

import (
	"fmt"
)

func main() {

	var (
		n, t, k int
	)
	fmt.Scan(&t)
	for t > 0 {
		t--
		fmt.Scan(&n, &k)
		var s, num, a [200001]int
		ans := 0
		for i := 0; i < n; i++ {
			fmt.Scan(&a[i])
			num[a[i]]++
			s[i] = num[a[i]]

		}
		remove := make([]int, 0)
		for i := 0; i < 200001; i++ {
			if num[i] >= k {
				num[i] = k
			} else if num[i] > 1 {
				remove = append(remove, num[i])
			}
			ans += num[i]
		}
		cnt := ans / k
		if cnt == 0 {
			for i := 0; i < n; i++ {
				fmt.Printf("%d ", 0)
			}
			fmt.Println()
			continue
		}
		l := 0
		for i := 0; i < n; i++ {
			if cnt == 0 {
				if s[i] == 1 && num[a[i]] == 1 {
					s[i] = 0
				}
				continue
			}
			if s[i] == k {
				cnt--
				continue
			}
			if s[i] > k {
				s[i] = 0
				continue
			}
			if s[i] == 1 && num[a[i]] == 1 {
				if l < len(remove) {
					remove[l]++
					s[i] = remove[l]
					if remove[l] == k {
						l++
						cnt--
					}
				} else {
					remove = append(remove, 1)
				}
			}
		}
		for i := 0; i < n; i++ {
			fmt.Printf("%d ", s[i])
		}
		fmt.Println()

	}

}

package main

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

type Pair struct {
	count int
	num int
}
func (p *Pair) String() string {
	return fmt.Sprintf("{count: %d, num: %d}", p.count, p.num)
}
type Pairs []*Pair

func (p Pairs) Len() int {
	return len(p)
}

func (p Pairs) Less(i, j int) bool {
	return p[i].count < p[j].count
}

func (p Pairs) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

type Color struct {
	current int
	total int
	startColor int
}

func (c *Color) String() string {
	return fmt.Sprintf("{cur: %d, total: %d, startColor: %d}", c.current, c.total, c.startColor)
}

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

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

	for tc := 0; tc < t; tc++ {
		var n, k int
		fmt.Fscan(r, &n, &k)
		nums := make([]int, n, n)
		numMap := make(map[int]int, n)
		results := make([]int, n, n)
		var totalUsable int
		for i := 0; i < n; i++ {
			fmt.Fscan(r, &nums[i])
			if numMap[nums[i]] < k {
				numMap[nums[i]] += 1
			}
		}
		pairs := make(Pairs, len(numMap), len(numMap))
		idx := 0
		for k, v := range numMap {
			pairs[idx] = &Pair{count: v, num: k}
			idx += 1
			if v < k {
				totalUsable += v
			}
		}
		totalUsable = totalUsable - (totalUsable % k)
		// debug
		// fmt.Printf("DEBUG: totalUsable = %d\n", totalUsable)
		sort.Sort(pairs)
		// debug
		// for _, pair := range pairs {
		// 	fmt.Printf("DEBUG: sorted pair %s\n", pair.String())
		// }

		colorData := make(map[int]*Color, len(pairs))
		colorIdx := 0
		for _, pair := range pairs {
			var (
				t int
				c *Color
			)
			if pair.count >= k {
				t = k
				c = &Color{
					startColor: 0,
					total: t,
					current: 0,
				}
			} else {
				t = pair.count
				if totalUsable < t {
					t = totalUsable
				}
				c = &Color{
					startColor: colorIdx,
					total: t,
					current: 0,
				}
				colorIdx = (colorIdx + t) % k
				totalUsable -= t
			}
			colorData[pair.num] = c
		}

		// debug
		// for num, color := range colorData {
		// 	fmt.Printf("DEBUG: color num %d: %s\n", num, color.String())
		// }

		for i := 0; i < n; i++ {
			num := nums[i]
			color := colorData[num]
			if color.current >= color.total {
				results[i] = 0
			} else {
				results[i] = (color.startColor + color.current) % k + 1
				color.current += 1
			}
		}

		for i := 0; i < n; i++ {
			fmt.Printf("%d ", results[i])
		}
		fmt.Printf("\n")
	}
}

package main

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

type Pair struct {
	count int
	num int
}
func (p *Pair) String() string {
	return fmt.Sprintf("{count: %d, num: %d}", p.count, p.num)
}
type Pairs []*Pair

func (p Pairs) Len() int {
	return len(p)
}

func (p Pairs) Less(i, j int) bool {
	return p[i].count < p[j].count
}

func (p Pairs) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

type Color struct {
	current int
	total int
	startColor int
}

func (c *Color) String() string {
	return fmt.Sprintf("{cur: %d, total: %d, startColor: %d}", c.current, c.total, c.startColor)
}

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

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

	for tc := 0; tc < t; tc++ {
		var n, k int
		fmt.Fscan(r, &n, &k)
		nums := make([]int, n, n)
		numMap := make(map[int]int, n)
		results := make([]int, n, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(r, &nums[i])
			if numMap[nums[i]] < k {
				numMap[nums[i]] += 1
			}
		}
		pairs := make(Pairs, len(numMap), len(numMap))
		idx := 0
		for k, v := range numMap {
			pairs[idx] = &Pair{count: v, num: k}
			idx += 1
		}
		sort.Sort(pairs)

		totalUsable := n - (n % k)
		colorData := make(map[int]*Color, len(pairs))
		colorIdx := 0
		for _, pair := range pairs {
			var t int
			if pair.count >= k {
				t = k
			} else {
				t = pair.count
			}
			if totalUsable < t {
				t = totalUsable
			}
			c := Color{
				startColor: colorIdx,
				total: t,
				current: 0,
			}
			colorIdx = (colorIdx + t) % k
			totalUsable -= t
			colorData[pair.num] = &c
		}

		for i := 0; i < n; i++ {
			num := nums[i]
			color := colorData[num]
			if color.current >= color.total {
				results[i] = 0
			} else {
				results[i] = (color.startColor + color.current) % k + 1
				color.current += 1
			}
		}

		for i := 0; i < n; i++ {
			fmt.Printf("%d ", results[i])
		}
		fmt.Printf("\n")
	}
}

package main

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

type Pair struct {
	count int
	num int
}
type Pairs []*Pair

func (p Pairs) Len() int {
	return len(p)
}

func (p Pairs) Less(i, j int) bool {
	return p[i].count < p[j].count
}

func (p Pairs) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

type Color struct {
	current int
	total int
	startColor int
}

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

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

	for tc := 0; tc < t; tc++ {
		var n, k int
		fmt.Fscan(r, &n, &k)
		nums := make([]int, n, n)
		numMap := make(map[int]int, n)
		results := make([]int, n, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(r, &nums[i])
			if numMap[nums[i]] < k {
				numMap[nums[i]] += 1
			}
		}
		pairs := make(Pairs, len(numMap), len(numMap))
		idx := 0
		for k, v := range numMap {
			pairs[idx] = &Pair{count: v, num: k}
			idx += 1
		}
		sort.Sort(pairs)

		colorData := make(map[int]*Color, len(pairs))
		colorIdx := 0
		for _, pair := range pairs {
			var t int
			if pair.count >= k {
				t = k
			} else {
				t = pair.count
			}
			c := Color{
				startColor: colorIdx,
				total: t,
				current: 0,
			}
			colorIdx = (colorIdx + t) % k
			colorData[pair.num] = &c
		}

		for i := 0; i < n; i++ {
			num := nums[i]
			color := colorData[num]
			if color.current >= color.total {
				results[i] = 0
			} else {
				results[i] = (color.startColor + color.current) % k + 1
				color.current += 1
			}
		}

		for i := 0; i < n; i++ {
			fmt.Printf("%d ", results[i])
		}
		fmt.Printf("\n")
	}
}

package main

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

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

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

	for tc := 0; tc < t; tc++ {
		var n, k int
		fmt.Fscan(r, &n, &k)
		nums := make([]int, n, n)
		numMap := make(map[int]int, n)
		results := make([]int, n, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(r, &nums[i])
			if numMap[nums[i]] < k {
				numMap[nums[i]] += 1
			}
		}

		for i := 0; i < n; i++ {
			currentNum := nums[i]
			currentNumRemain := numMap[currentNum]
			if currentNumRemain == 0 {
				results[i] = 0
			} else {
				results[i] = currentNumRemain
				numMap[currentNum] = currentNumRemain - 1
			}
		}

		for i := 0; i < n; i++ {
			fmt.Printf("%d ", results[i])
		}
		fmt.Printf("\n")
	}
}

package main

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

type tp struct {
	order int
	val   int
}

func main() {
	rd := bufio.NewReader(os.Stdin)
	wr := bufio.NewWriter(os.Stdout)
	defer wr.Flush()
	var t, n, k, i, lastVal, lastValLen, inx int
	A := make([]tp, 200000)
	B := make([]int, 200000)
	fmt.Fscanf(rd, "%d\n", &t)
	for ti := 0; ti < t; ti++ {
		fmt.Fscanf(rd, "%d", &n)
		fmt.Fscanf(rd, "%d\n", &k)
		for i = 0; i < n; i++ {
			A[i].order = i
			fmt.Fscanf(rd, "%d", &(A[i].val))
		}
		fmt.Fscanf(rd, "\n")
		sort.Slice(A[:n], func(i, j int) bool {
			return A[i].val < A[j].val
		})
		inx = 0
		lastVal = 0
		for i = 0; i < n; i++ {
			if lastVal == A[i].val {
				lastValLen++
			} else {
				lastVal = A[i].val
				lastValLen = 1
			}
			if lastValLen > k {
				B[A[i].order] = 0
			} else {
				B[A[i].order] = inx%k + 1
				inx++
			}
		}
		for i = 0; i < n; i++ {
			fmt.Fprintf(wr, "%d ", B[i])
		}
		fmt.Fprintf(wr, "\n")
	}
}

package main

import (
	"fmt"
	"sort"
)

type tp struct {
	order int
	val   int
}

func main() {
	var t, n, k, i, lastVal, lastValLen, inx int
	A := make([]tp, 200000)
	B := make([]int, 200000)
	fmt.Scanf("%d", &t)
	for ti := 0; ti < t; ti++ {
		fmt.Scanf("%d %d", &n, &k)
		for i = 0; i < n; i++ {
			A[i].order = i
			//if i == n-1 {
			//	fmt.Scanf( "%d\n", &(A[i].val))
			//} else {
			fmt.Scanf("%d", &(A[i].val))
			//}
		}
		sort.Slice(A[:n], func(i, j int) bool {
			return A[i].val < A[j].val
		})
		inx = 0
		lastVal = 0
		for i = 0; i < n; i++ {
			if lastVal == A[i].val {
				lastValLen++
			} else {
				lastVal = A[i].val
				lastValLen = 1
			}
			if lastValLen > k {
				B[A[i].order] = 0
			} else {
				B[A[i].order] = inx%k + 1
				inx++
			}
		}
		for i = 0; i < n; i++ {
			fmt.Printf("%d ", B[i])
		}
		fmt.Printf("\n")
	}
}

package main

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

type tp struct {
	order int
	val   int
}

func main() {
	rd := bufio.NewReader(os.Stdin)
	wr := bufio.NewWriter(os.Stdout)
	var t, n, k, i, lastVal, lastValLen, inx int
	A := make([]tp, 200000)
	B := make([]int, 200000)
	fmt.Fscanf(rd, "%d\n", &t)
	for ti := 0; ti < t; ti++ {
		fmt.Fscanf(rd, "%d %d\n", &n, &k)
		for i = 0; i < n; i++ {
			A[i].order = i
			fmt.Fscanf(rd, "%d ", &(A[i].val))
		}
		sort.Slice(A[:n], func(i, j int) bool {
			return A[i].val < A[j].val
		})
		inx = 0
		lastVal = 0
		for i = 0; i < n; i++ {
			if lastVal == A[i].val {
				lastValLen++
			} else {
				lastVal = A[i].val
				lastValLen = 1
			}
			if lastValLen > k {
				B[A[i].order] = 0
			} else {
				B[A[i].order] = inx%k + 1
				inx++
			}
		}
		for i = 0; i < n; i++ {
			fmt.Fprintf(wr, "%d ", B[i])
		}
		fmt.Fprintf(wr, "\n")
	}
	wr.Flush()
}

package main

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

type node struct {
	i int
	v int

	c int
}

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

	var t int
	var n, k int
	var v int
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n, &k)
		arr := make([]node, n)
		for i := 0; i < n; i++ {
			Fscan(in, &v)
			arr[i] = node{i, v, 0}
		}
		sort.Slice(arr, func(i, j int) bool {
			return arr[i].v < arr[j].v
		})
		// fmt.Println(arr)
		var m int
		var i, j int
		var t int
		for i = 0; i < n; i = j {
			m = 1
			for j = i + 1; j < n && arr[j].v == arr[i].v; j++ {
			}
			// fmt.Println("i,j", i, j)
			for r := i; r < j; r++ {
				if m <= k {
					arr[r].c = (t % k) + 1
					t++
					m++
				}
			}
		}
		// sort.Slice(arr, func(i, j int) bool {
		//     return arr[i].i < arr[j].i
		// })
		// fmt.Println(arr)
		colors := make([]int, k+1)
		for _, v := range arr {
			colors[v.c]++
		}
		mc := math.MaxInt32
		for i := 1; i <= k; i++ {
			if mc > colors[i] {
				mc = colors[i]
			}
		}
		ans := make([]int, n)
		for _, v := range arr {
			ans[v.i] = v.c
		}
		c := make([]int, k+1)
		for _, v := range ans {
			c[v]++
			if c[v] > mc {
				Fprintf(out, "%d", 0)
			} else {
				Fprintf(out, "%d ", v)
			}
		}
		Fprintln(out)
	}
}

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

package main

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

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

	solve := func(Case int) {
		var n, k int
		Fscan(in, &n, &k)
		type pair struct{ v, i int }
		a := make([]pair, n)
		c := make([]int, n+1)
		for i := range a {
			Fscan(in, &a[i].v)
			c[a[i].v]++
			a[i].i = i
		}
		sort.Slice(a, func(i, j int) bool { return a[i].v < a[j].v })

		ans := make([]int, n)

		tot := 0
		for _, v := range c {
			if v > k {
				v = k
			}
			tot += v
		}
		tot -= tot % k

		color := 1
		for _, p := range a {
			if c[p.v] == 0 || tot == 0 {
				continue
			}
			ans[p.i] = color
			color++
			if color > k {
				color = 1
			}
			c[p.v]--
			tot--
		}

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

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

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

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


package main

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

type dish struct {
	idx, c, r int
}

func (d *dish) serve(n int) (cost int64, left int) {
	if d.r == 0 {
		return 0, n
	}
	if d.r > n {
		d.r -= n
		return int64(d.c) * int64(n), 0
	}
	ans := int64(d.c) * int64(d.r)
	defer func() {
		d.r = 0
	}()
	return ans, n - d.r
}

func main() {
	r := bufio.NewReader(os.Stdin)
	var n, m int
	fmt.Fscan(r, &n, &m)

	dishes := make([]*dish, 0, n)
	alice := make(map[int]*dish, n)
	for i := 0; i < n; i++ {
		d := dish{idx: i + 1}
		dishes = append(dishes, &d)
		alice[i+1] = &d
	}
	for _, d := range dishes {
		fmt.Fscan(r, &d.r)
	}
	for _, d := range dishes {
		fmt.Fscan(r, &d.c)
	}
	sort.Slice(dishes, func(i, j int) bool {
		if dishes[i].c == dishes[j].c {
			return dishes[i].idx < dishes[j].idx
		}
		return dishes[i].c < dishes[j].c
	})
	for i, j := 0, 0; i < m; i++ {
		var t, d int
		fmt.Fscan(r, &t, &d)
		var cost int64
		c, d := alice[t].serve(d)
		cost += c
		for d > 0 && j < n {
			c, d = dishes[j].serve(d)
			cost += c
			if d == 0 {
				break
			}
			j++
		}
		if d > 0 {
			cost = 0
		}
		fmt.Println(cost)
	}
}

package main

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

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

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

// An Item is something we manage in a priority queue.
type Item struct {
	value int // The value of the item; arbitrary.
	cnt   int // The priority of the item in the queue.
	// The index is needed by update and is maintained by the heap.Interface methods.
	index int // The index of the item in the heap.
	id    int
}

// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Item

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(i, j int) bool {
	// We want Pop to give us the highest, not lowest, priority so we use greater than here.
	if pq[i].value == pq[j].value {
		return pq[i].id < pq[j].id
	}
	return pq[i].value < pq[j].value
}

func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *PriorityQueue) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Item)
	item.index = n
	*pq = append(*pq, item)
}

func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

// update modifies the priority and value of an Item in the queue.
func (pq *PriorityQueue) update(item *Item) {
	heap.Fix(pq, item.index)
}

func main() {
	defer writer.Flush()
	var n, m, t1, t2 int
	max := int(^uint(0) >> 2)
	scanf("%d %d\n", &n, &m)
	cnts := make([]int, n)
	values := make([]int, n)
	for i := 0; i < n; i++ {
		scanf("%d", &cnts[i])
	}
	scanf("\n")
	for i := 0; i < n; i++ {
		scanf("%d", &values[i])
	}
	scanf("\n")

	pq := make(PriorityQueue, n)
	items := make([]Item, n)

	for i := 0; i < n; i++ {
		items[i] = Item{
			value: values[i],
			index: i,
			id:    i,
			cnt:   cnts[i],
		}
		pq[i] = &items[i]
	}

	// fmt.Println(items)
	// fmt.Println(cnts)
	// fmt.Println(values)

	heap.Init(&pq)

	for i := 0; i < m; i++ {
		scanf("%d %d\n", &t1, &t2)
		t1--
		t3 := int64(0)

		flag := true

		for flag {
			flag = false

			//fmt.Println("t1,t2 ", t1, t2)
			// for _, e := range items {
			// 	fmt.Print(e.cnt, " ")

			// }
			// fmt.Println()

			if items[t1].cnt > 0 && items[t1].cnt <= t2 {
				t3 += int64(items[t1].cnt) * int64(items[t1].value)
				t2 -= items[t1].cnt
				items[t1].value = max
				items[t1].cnt = 0

				pq.update(&items[t1])
				t1 = (pq)[0].id
				flag = true
			} else if items[t1].cnt > 0 && items[t1].cnt > t2 {
				t3 += int64(t2) * int64(items[t1].value)
				items[t1].cnt -= t2
				t2 = 0
				pq.update(&items[t1])
				break
			} else {
				t1 = (pq)[0].id
				if items[t1].cnt == 0 {
					break
				}
				flag = true
			}

		}
		if t2 > 0 {
			t3 = 0
		}

		printf("%d\n", t3)

	}
}

package main

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

type point struct {
	c, cnt int64
	id     int
}

type Point []*point

func (m Point) Less(i, j int) bool {
	if m[i].c < m[j].c {
		return true
	} else if m[i].c > m[j].c {
		return false
	}
	if m[i].id < m[j].id {
		return true
	} else {
		return false
	}
}
func (m Point) Swap(a, b int) {
	tmp := m[a]
	m[a] = m[b]
	m[b] = tmp
}
func (m Point) Len() int {
	return len(m)
}
func min(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}
func main() {
	buf := bufio.NewReader(os.Stdin)

	var n, m int
	fmt.Fscanf(buf, "%d %d\n", &n, &m)
	orderm := make(Point, n)
	mat := make(Point, n)
	for i := 0; i < n; i++ {
		mat[i] = &point{
			id: i,
		}
		orderm[i] = mat[i]
		fmt.Fscanf(buf, "%d", &mat[i].cnt)
	}
	fmt.Fscanf(buf, "\n")
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d", &mat[i].c)
	}

	fmt.Fscanf(buf, "\n")
	sort.Sort(orderm)
	//for i := 0; i < n; i++ {
	//	fmt.Printf( "mat=%d %d %d\n",orderm[i].id,orderm[i].c,orderm[i].cnt)
	//}
	front := 0
	end := false
	for i := 0; i < m; i++ {
		res := int64(0)
		var x int
		var y int64
		fmt.Fscanf(buf, "%d %d\n", &x, &y)
	//	fmt.Printf("x=%d y=%d\n",x,y)
		my := min(y, mat[x-1].cnt)
		mat[x-1].cnt -= my
		res += mat[x-1].c * my
	//	fmt.Printf("my=%d front=%d\n",my,front)
		if y > my {
			y -= my
			for front < n && y > 0 {
				if orderm[front].cnt <= 0{
					front++
					continue
				}
				my = min(y,orderm[front].cnt)
				orderm[front].cnt -= my
				y -= my
				res += orderm[front].c*my
			}
			if y > 0 {
				end = true
			}

		}
		if end {
			fmt.Printf("0\n")
		} else {
			fmt.Printf("%d\n", res)
		}
	}

}
/**
8 5
8 6 2 1 4 5 7 5
6 3 3 2 6 2 3 2
2 8
1 4
4 7
3 4
6 10
 */

package main

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

type dish struct {
	idx, c, r int
}

func (d *dish) serve(n int) (cost, left int) {
	if d.r == 0 {
		return 0, n
	}
	if d.r > n {
		d.r -= n
		return d.c * n, 0
	}
	ans := d.c * d.r
	defer func() {
		d.r = 0
	}()
	return ans, n - d.r
}

func main() {
	r := bufio.NewReader(os.Stdin)
	var n, m int
	fmt.Fscan(r, &n, &m)

	dishes := make([]*dish, 0, n)
	alice := make(map[int]*dish, n)
	for i := 0; i < n; i++ {
		d := dish{idx: i + 1}
		dishes = append(dishes, &d)
		alice[i+1] = &d
	}
	for _, d := range dishes {
		fmt.Fscan(r, &d.r)
	}
	for _, d := range dishes {
		fmt.Fscan(r, &d.c)
	}
	sort.Slice(dishes, func(i, j int) bool {
		if dishes[i].c == dishes[j].c {
			return dishes[i].idx < dishes[j].idx
		}
		return dishes[i].c < dishes[j].c
	})
	for i, j := 0, 0; i < m; i++ {
		var t, d int
		fmt.Fscan(r, &t, &d)
		var cost int
		c, d := alice[t].serve(d)
		cost += c
		for d > 0 && j < n {
			c, d = dishes[j].serve(d)
			cost += c
			if d == 0 {
				break
			}
			j++
		}
		if d > 0 {
			cost = 0
		}
		fmt.Println(cost)
	}
}

package main

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

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

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

// An Item is something we manage in a priority queue.
type Item struct {
	value int // The value of the item; arbitrary.
	cnt   int // The priority of the item in the queue.
	// The index is needed by update and is maintained by the heap.Interface methods.
	index int // The index of the item in the heap.
	id    int
}

// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Item

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(i, j int) bool {
	// We want Pop to give us the highest, not lowest, priority so we use greater than here.
	if pq[i].value == pq[j].value {
		return pq[i].id < pq[j].id
	}
	return pq[i].value < pq[j].value
}

func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *PriorityQueue) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Item)
	item.index = n
	*pq = append(*pq, item)
}

func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

// update modifies the priority and value of an Item in the queue.
func (pq *PriorityQueue) update(item *Item) {
	heap.Fix(pq, item.index)
}

func main() {
	defer writer.Flush()
	var n, m, t1, t2 int
	max := int(^uint(0) >> 2)
	scanf("%d %d\n", &n, &m)
	cnts := make([]int, n)
	values := make([]int, n)
	for i := 0; i < n; i++ {
		scanf("%d", &cnts[i])
	}
	scanf("\n")
	for i := 0; i < n; i++ {
		scanf("%d", &values[i])
	}
	scanf("\n")

	pq := make(PriorityQueue, n)
	items := make([]Item, n)

	for i := 0; i < n; i++ {
		items[i] = Item{
			value: values[i],
			index: i,
			id:    i,
			cnt:   cnts[i],
		}
		pq[i] = &items[i]
	}

	// fmt.Println(items)
	// fmt.Println(cnts)
	// fmt.Println(values)

	heap.Init(&pq)

	for i := 0; i < m; i++ {
		scanf("%d %d\n", &t1, &t2)
		t1--
		t3 := int64(0)

		flag := true

		for flag {
			flag = false

			//fmt.Println("t1,t2 ", t1, t2)
			for _, e := range items {
				fmt.Print(e.cnt, " ")

			}
			fmt.Println()

			if items[t1].cnt > 0 && items[t1].cnt <= t2 {
				t3 += int64(items[t1].cnt) * int64(items[t1].value)
				t2 -= items[t1].cnt
				items[t1].value = max
				items[t1].cnt = 0

				pq.update(&items[t1])
				t1 = (pq)[0].id
				flag = true
			} else if items[t1].cnt > 0 && items[t1].cnt > t2 {
				t3 += int64(t2) * int64(items[t1].value)
				items[t1].cnt -= t2
				t2 = 0
				pq.update(&items[t1])
				break
			} else {
				t1 = (pq)[0].id
				if items[t1].cnt == 0 {
					break
				}
				flag = true
			}

		}
		if t2 > 0 {
			t3 = 0
		}

		printf("%d\n", t3)

	}
}

package main

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

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

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

// An Item is something we manage in a priority queue.
type Item struct {
	value int // The value of the item; arbitrary.
	cnt   int // The priority of the item in the queue.
	// The index is needed by update and is maintained by the heap.Interface methods.
	index int // The index of the item in the heap.
	id    int
}

// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Item

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(i, j int) bool {
	// We want Pop to give us the highest, not lowest, priority so we use greater than here.
	if pq[i].value == pq[j].value {
		return pq[i].id < pq[j].id
	}
	return pq[i].value < pq[j].value
}

func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *PriorityQueue) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Item)
	item.index = n
	*pq = append(*pq, item)
}

func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

// update modifies the priority and value of an Item in the queue.
func (pq *PriorityQueue) update(item *Item) {
	heap.Fix(pq, item.index)
}

func main() {
	defer writer.Flush()
	var n, m, t1, t2 int
	max := int(^uint(0) >> 2)
	scanf("%d %d\n", &n, &m)
	cnts := make([]int, n)
	values := make([]int, n)
	for i := 0; i < n; i++ {
		scanf("%d", &cnts[i])
	}
	scanf("\n")
	for i := 0; i < n; i++ {
		scanf("%d", &values[i])
	}
	scanf("\n")

	pq := make(PriorityQueue, n)
	items := make([]Item, n)

	for i := 0; i < n; i++ {
		items[i] = Item{
			value: values[i],
			index: i,
			id:    i,
			cnt:   cnts[i],
		}
		pq[i] = &items[i]
	}

	// fmt.Println(items)
	// fmt.Println(cnts)
	// fmt.Println(values)

	heap.Init(&pq)

	for i := 0; i < m; i++ {
		scanf("%d %d\n", &t1, &t2)
		t1--
		t3 := int64(0)

		flag := true

		for flag {
			flag = false

			//fmt.Println("t1,t2 ", t1, t2)

			if items[t1].cnt > 0 && items[t1].cnt <= t2 {
				t3 += int64(items[t1].cnt) * int64(items[t1].value)
				t2 -= items[t1].cnt
				items[t1].value = max
				items[t1].cnt = 0

				pq.update(&items[t1])
				t1 = (pq)[0].id
				flag = true
			} else if items[t1].cnt > 0 && items[t1].cnt > t2 {
				t3 += int64(t2) * int64(items[t1].value)
				items[t1].cnt -= t2
				pq.update(&items[t1])
				break
			} else {
				t1 = (pq)[0].id
				if items[t1].cnt == 0 {
					break
				}
				flag = true
			}

		}

		printf("%d\n", t3)

	}
}

package main

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

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

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

// An Item is something we manage in a priority queue.
type Item struct {
	value int // The value of the item; arbitrary.
	cnt   int // The priority of the item in the queue.
	// The index is needed by update and is maintained by the heap.Interface methods.
	index int // The index of the item in the heap.
	id    int
}

// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Item

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(i, j int) bool {
	// We want Pop to give us the highest, not lowest, priority so we use greater than here.
	if pq[i].value == pq[j].value {
		return pq[i].id < pq[j].id
	}
	return pq[i].value < pq[j].value
}

func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *PriorityQueue) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Item)
	item.index = n
	*pq = append(*pq, item)
}

func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

// update modifies the priority and value of an Item in the queue.
func (pq *PriorityQueue) update(item *Item) {
	heap.Fix(pq, item.index)
}

func main() {
	defer writer.Flush()
	var n, m, t1, t2 int
	max := int(^uint(0) >> 2)
	scanf("%d %d\n", &n, &m)
	cnts := make([]int, n)
	values := make([]int, n)
	for i := 0; i < n; i++ {
		scanf("%d", &cnts[i])
	}
	scanf("\n")
	for i := 0; i < n; i++ {
		scanf("%d", &values[i])
	}
	scanf("\n")

	pq := make(PriorityQueue, n)
	items := make([]Item, n)

	for i := 0; i < n; i++ {
		items[i] = Item{
			value: values[i],
			index: i,
			id:    i,
			cnt:   cnts[i],
		}
		pq[i] = &items[i]
	}

	// fmt.Println(items)
	// fmt.Println(cnts)
	// fmt.Println(values)

	heap.Init(&pq)

	for i := 0; i < m; i++ {
		scanf("%d %d\n", &t1, &t2)
		t1--
		t3 := int64(0)

		flag := true

		for flag {
			flag = false

			fmt.Println("t1,t2 ", t1, t2)

			if items[t1].cnt > 0 && items[t1].cnt <= t2 {
				t3 += int64(items[t1].cnt) * int64(items[t1].value)
				t2 -= items[t1].cnt
				items[t1].value = max
				items[t1].cnt = 0

				pq.update(&items[t1])
				t1 = (pq)[0].id
				flag = true
			} else if items[t1].cnt > 0 && items[t1].cnt > t2 {
				t3 += int64(t2) * int64(items[t1].value)
				items[t1].cnt -= t2
				pq.update(&items[t1])
				break
			} else {
				t1 = (pq)[0].id
				if items[t1].cnt == 0 {
					break
				}
				flag = true
			}

		}

		printf("%d\n", t3)

	}
}


package main

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

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

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

			if l < r {
				ans += int64(l)
			} else {
				ans += int64(r)
			}
		}
		fmt.Fprintln(wr, ans)
	}
}

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

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

	sum int
}

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

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

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

type Splay struct {
	root *Node
}

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

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

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

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

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

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

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

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

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

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

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

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

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

package main

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

type IndexTree struct {
	n            int
	arr          []int
	f            func(i, j int) int
	defaultValue int
}

type Aggregation interface {
	DefaultValue() int
	Aggregate(left, right int) int
}

type MinIndex struct{}

func (m MinIndex) DefaultValue() int { return math.MaxInt32 }
func (m MinIndex) Aggregate(left, right int) int {
	if left < right {
		return left
	} else {
		return right
	}
}

type MaxIndex struct{}

func (m MaxIndex) DefaultValue() int { return math.MinInt32 }
func (m MaxIndex) Aggregate(left, right int) int {
	if left > right {
		return left
	} else {
		return right
	}
}

type SumIndex struct{}

func (m SumIndex) DefaultValue() int             { return 0 }
func (m SumIndex) Aggregate(left, right int) int { return left + right }

func NewIndexTree(n int, a Aggregation) *IndexTree {
	arr := make([]int, n*4)
	for i := 0; i < len(arr); i++ {
		arr[i] = a.DefaultValue()
	}

	return &IndexTree{n, arr, a.Aggregate, a.DefaultValue()}
}

func (i *IndexTree) Add(k, v int) {
	i.traverse(1, 0, i.n, func(node, b, e int) bool {
		if b <= k && e >= k {
			i.arr[node] = i.f(i.arr[node], v)
			return true
		}
		return false
	})
}

func (i *IndexTree) Get(qb, qe int) int {
	res := i.defaultValue
	i.traverse(1, 0, i.n, func(node, b, e int) bool {
		if b >= qb && e <= qe {
			res = i.f(res, i.arr[node])
			return false
		}
		return !(qe < b || qb > e)
	})
	return res
}

func (i *IndexTree) traverse(node int, b, e int, do func(node, b, e int) bool) {
	if !do(node, b, e) {
		return
	}
	m := (b + e) / 2
	if b != e {
		i.traverse(node*2, b, m, do)
		i.traverse(node*2+1, m+1, e, do)
	}
}

func compress(arr []int) []int {
	c := make(map[int]int)
	x := make([]int, 0)
	for _, v := range arr {
		if _, ok := c[v]; !ok {
			x = append(x, v)
			c[v] = 1
		}
	}

	sort.Ints(x)
	for i, v := range x {
		c[v] = i
	}
	for i, v := range arr {
		arr[i] = c[v]
	}
	return arr
}

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

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

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

		arr = compress(arr)

		idx := NewIndexTree(n+10, SumIndex{})

		res := int64(0)
		for _, v := range arr {
			less := idx.Get(0, v-1)
			more := idx.Get(v+1, n+1)

			if less < more {
				res += int64(less)
			} else {
				res += int64(more)
			}
			idx.Add(v, 1)
		}

		fmt.Println(res)
	}
}

package main

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

var n int

var a []int

var writer *bufio.Writer

func main() {

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

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

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

		a = make([]int, n)

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

		solve()
	}
}

type pair struct {
	v int
	idx int
}

type byV []*pair

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

const MAX = 2e5

func solve() {
	bit := make([]int, MAX + 1)

	p := make([]*pair, n)
	for i := 0; i < n; i++ {
		p[i] = &pair{a[i], i}
	}

	sort.Sort(byV(p))

	compressed := make([]int, n)

	var prev int = -1e9 - 1
	running := 0

	for i := 0; i < n; i++ {
		c := p[i]

		if c.v != prev {
			running++
			compressed[c.idx] = running

		} else {
			compressed[c.idx] = running
		}

		prev = p[i].v
	}

	//1 .. 2e5

	f := compressed[0]

	add(f, 1, &bit, MAX)

	var ans int64

	for i := 1; i < n; i++ {
		c := compressed[i]

		smaller := get(c - 1, &bit)

		larger := get(2e5, &bit) - get(c, &bit)

		ans += min(int64(smaller), int64(larger))

		add(c, 1, &bit, MAX)

	}

	fmt.Println(ans)
}

func add(idx int, delta int, bit *[]int, n int) {
	for ; idx <= n; idx += idx & -idx {
		(*bit)[idx] += delta
	}
}

func get(idx int, bit *[]int) int {
	ret := 0
	for ; idx > 0; idx -= idx & -idx {
		ret += (*bit)[idx];
	}
	return ret
}

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

package main

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

var c []int
var n int
func lowbit(x int)int{
	return x & (-x)
}
func update(x int,v int){
	for i:=x;i<=n;i+=lowbit(i){
		c[i]+=v
	}
}
func query(x int) int{
	ans := 0
	for i:=x;i!=0;i-=lowbit(i){
		ans += c[i]
	}
	return ans
}
func min(x,y int)int{
	if x<y{
		return x
	}else{
		return y
	}
}
func main() {
	var t int
	in := bufio.NewReader(os.Stdin)
	out := os.Stdout
	fmt.Fscan(in,&t)
	for u:=1;u<=t;u++{
		fmt.Fscan(in,&n)
		c = make([]int,2*n)
		a := make([]int,n)
		for i:=0;i<n;i++{
			fmt.Fscan(in,&a[i])
		}
		b := make([]int,n)
		copy(b,a)
		mp := map[int]int{}
		sort.Ints(a)
		cnt := 1
		lst := 0
		for i:=0;i<n;i++{
			if i==0{
				lst = a[i]
				mp[a[i]]=cnt
				cnt++
				continue
			}
			if a[i]==lst{
				continue
			}else{
				mp[a[i]]=cnt
				cnt++
				lst = a[i]
			}
		}
		var ret int64
		for i:=0;i<n;i++{
			l := query(mp[b[i]]-1)
			r := query(n)-query(mp[b[i]])
			update(mp[b[i]],1)
			ret += int64(min(l,r))
		}
		fmt.Fprintln(out,ret)
	}
}

package main

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

var c []int
var n int
func lowbit(x int)int{
	return x & (-x)
}
func update(x int,v int){
	for i:=x;i<=n;i+=lowbit(i){
		c[i]+=v
	}
}
func query(x int) int{
	ans := 0
	for i:=x;i!=0;i-=lowbit(i){
		ans += c[i]
	}
	return ans
}
func min(x,y int)int{
	if x<y{
		return x
	}else{
		return y
	}
}
func main() {
	var t int
	in := bufio.NewReader(os.Stdin)
	out := os.Stdout
	fmt.Fscan(in,&t)
	for u:=1;u<=t;u++{
		fmt.Fscan(in,&n)
		c = make([]int,2*n)
		a := make([]int,n)
		for i:=0;i<n;i++{
			fmt.Fscan(in,&a[i])
		}
		b := make([]int,n)
		copy(b,a)
		mp := map[int]int{}
		sort.Ints(a)
		cnt := 1
		lst := 0
		for i:=0;i<n;i++{
			if i==0{
				lst = a[i]
				mp[a[i]]=cnt
				cnt++
				continue
			}
			if a[i]==lst{
				continue
			}else{
				mp[a[i]]=cnt
				cnt++
				lst = a[i]
			}
		}
		ret := 0
		for i:=0;i<n;i++{
			l := query(mp[b[i]]-1)
			r := query(n)-query(mp[b[i]])
			update(mp[b[i]],1)
			ret += min(l,r)
		}
		fmt.Fprintln(out,ret)
	}
}

package main

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

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

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

			if l < r {
				ans += l
			} else {
				ans += r
			}
		}
		fmt.Fprintln(wr, ans)
	}
}

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

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

	sum int
}

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

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

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

type Splay struct {
	root *Node
}

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

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

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

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

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

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

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

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

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

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

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

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

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

package main

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

type IndexTree struct {
	n            int
	arr          []int
	f            func(i, j int) int
	defaultValue int
}

type Aggregation interface {
	DefaultValue() int
	Aggregate(left, right int) int
}

type MinIndex struct{}

func (m MinIndex) DefaultValue() int { return math.MaxInt32 }
func (m MinIndex) Aggregate(left, right int) int {
	if left < right {
		return left
	} else {
		return right
	}
}

type MaxIndex struct{}

func (m MaxIndex) DefaultValue() int { return math.MinInt32 }
func (m MaxIndex) Aggregate(left, right int) int {
	if left > right {
		return left
	} else {
		return right
	}
}

type SumIndex struct{}

func (m SumIndex) DefaultValue() int             { return 0 }
func (m SumIndex) Aggregate(left, right int) int { return left + right }

func NewIndexTree(n int, a Aggregation) *IndexTree {
	arr := make([]int, n*4)
	for i := 0; i < len(arr); i++ {
		arr[i] = a.DefaultValue()
	}

	return &IndexTree{n, arr, a.Aggregate, a.DefaultValue()}
}

func (i *IndexTree) Add(k, v int) {
	i.traverse(1, 0, i.n, func(node, b, e int) bool {
		if b <= k && e >= k {
			i.arr[node] = i.f(i.arr[node], v)
			return true
		}
		return false
	})
}

func (i *IndexTree) Get(qb, qe int) int {
	res := i.defaultValue
	i.traverse(1, 0, i.n, func(node, b, e int) bool {
		if b >= qb && e <= qe {
			res = i.f(res, i.arr[node])
			return false
		}
		return !(qe < b || qb > e)
	})
	return res
}

func (i *IndexTree) traverse(node int, b, e int, do func(node, b, e int) bool) {
	if !do(node, b, e) {
		return
	}
	m := (b + e) / 2
	if b != e {
		i.traverse(node*2, b, m, do)
		i.traverse(node*2+1, m+1, e, do)
	}
}

func compress(arr []int) []int {
	c := make(map[int]int)
	x := make([]int, 0)
	for _, v := range arr {
		if _, ok := c[v]; !ok {
			x = append(x, v)
			c[v] = 1
		}
	}

	sort.Ints(x)
	for i, v := range x {
		c[v] = i
	}
	for i, v := range arr {
		arr[i] = c[v]
	}
	return arr
}

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

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

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

		arr = compress(arr)

		idx := NewIndexTree(n+10, SumIndex{})

		res := 0
		for _, v := range arr {
			less := idx.Get(0, v-1)
			more := idx.Get(v+1, n+1)

			if less < more {
				res += less
			} else {
				res += more
			}
			idx.Add(v, 1)
		}

		fmt.Println(res)
	}
}