This problem is an extension of the problem "Wonderful Coloring - 1". It has quite many differences, so you should read this statement completely.Recently, Paul and Mary have found a new favorite sequence of integers $$$a_1, a_2, \dots, a_n$$$. They want to paint it using pieces of chalk of $$$k$$$ colors. The coloring of a sequence is called wonderful if the following conditions are met:  each element of the sequence is either painted in one of $$$k$$$ colors or isn't painted;  each two elements which are painted in the same color are different (i. e. there's no two equal values painted in the same color);  let's calculate for each of $$$k$$$ colors the number of elements painted in the color — all calculated numbers must be equal;  the total number of painted elements of the sequence is the maximum among all colorings of the sequence which meet the first three conditions. E. g. consider a sequence $$$a=[3, 1, 1, 1, 1, 10, 3, 10, 10, 2]$$$ and $$$k=3$$$. One of the wonderful colorings of the sequence is shown in the figure.    The example of a wonderful coloring of the sequence $$$a=[3, 1, 1, 1, 1, 10, 3, 10, 10, 2]$$$ and $$$k=3$$$. Note that one of the elements isn't painted. Help Paul and Mary to find a wonderful coloring of a given sequence $$$a$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of two lines. The first one contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2\cdot10^5$$$, $$$1 \le k \le n$$$) — the length of a given sequence and the number of colors, respectively. The second one contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

Output $$$t$$$ lines, each of them must contain a description of a wonderful coloring for the corresponding test case. Each wonderful coloring must be printed as a sequence of $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$0 \le c_i \le k$$$) separated by spaces where   $$$c_i=0$$$, if $$$i$$$-th element isn't painted;  $$$c_i>0$$$, if $$$i$$$-th element is painted in the $$$c_i$$$-th color.  Remember that you need to maximize the total count of painted elements for the wonderful coloring. If there are multiple solutions, print any one.

NoteIn the first test case, the answer is shown in the figure in the statement. The red color has number $$$1$$$, the blue color — $$$2$$$, the green — $$$3$$$.

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

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

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


Lunar New Year is approaching, and Bob is planning to go for a famous restaurant — "Alice's".The restaurant "Alice's" serves $$$n$$$ kinds of food. The cost for the $$$i$$$-th kind is always $$$c_i$$$. Initially, the restaurant has enough ingredients for serving exactly $$$a_i$$$ dishes of the $$$i$$$-th kind. In the New Year's Eve, $$$m$$$ customers will visit Alice's one after another and the $$$j$$$-th customer will order $$$d_j$$$ dishes of the $$$t_j$$$-th kind of food. The $$$(i + 1)$$$-st customer will only come after the $$$i$$$-th customer is completely served.Suppose there are $$$r_i$$$ dishes of the $$$i$$$-th kind remaining (initially $$$r_i = a_i$$$). When a customer orders $$$1$$$ dish of the $$$i$$$-th kind, the following principles will be processed. If $$$r_i > 0$$$, the customer will be served exactly $$$1$$$ dish of the $$$i$$$-th kind. The cost for the dish is $$$c_i$$$. Meanwhile, $$$r_i$$$ will be reduced by $$$1$$$. Otherwise, the customer will be served $$$1$$$ dish of the cheapest available kind of food if there are any. If there are multiple cheapest kinds of food, the one with the smallest index among the cheapest will be served. The cost will be the cost for the dish served and the remain for the corresponding dish will be reduced by $$$1$$$. If there are no more dishes at all, the customer will leave angrily. Therefore, no matter how many dishes are served previously, the cost for the customer is $$$0$$$.If the customer doesn't leave after the $$$d_j$$$ dishes are served, the cost for the customer will be the sum of the cost for these $$$d_j$$$ dishes.Please determine the total cost for each of the $$$m$$$ customers.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), representing the number of different kinds of food and the number of customers, respectively. The second line contains $$$n$$$ positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^7$$$), where $$$a_i$$$ denotes the initial remain of the $$$i$$$-th kind of dishes. The third line contains $$$n$$$ positive integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 10^6$$$), where $$$c_i$$$ denotes the cost of one dish of the $$$i$$$-th kind. The following $$$m$$$ lines describe the orders of the $$$m$$$ customers respectively. The $$$j$$$-th line contains two positive integers $$$t_j$$$ and $$$d_j$$$ ($$$1 \leq t_j \leq n$$$, $$$1 \leq d_j \leq 10^7$$$), representing the kind of food and the number of dishes the $$$j$$$-th customer orders, respectively.

Print $$$m$$$ lines. In the $$$j$$$-th line print the cost for the $$$j$$$-th customer.

NoteIn the first sample, $$$5$$$ customers will be served as follows. Customer $$$1$$$ will be served $$$6$$$ dishes of the $$$2$$$-nd kind, $$$1$$$ dish of the $$$4$$$-th kind, and $$$1$$$ dish of the $$$6$$$-th kind. The cost is $$$6 \cdot 3 + 1 \cdot 2 + 1 \cdot 2 = 22$$$. The remain of the $$$8$$$ kinds of food will be $$$\{8, 0, 2, 0, 4, 4, 7, 5\}$$$. Customer $$$2$$$ will be served $$$4$$$ dishes of the $$$1$$$-st kind. The cost is $$$4 \cdot 6 = 24$$$. The remain will be $$$\{4, 0, 2, 0, 4, 4, 7, 5\}$$$. Customer $$$3$$$ will be served $$$4$$$ dishes of the $$$6$$$-th kind, $$$3$$$ dishes of the $$$8$$$-th kind. The cost is $$$4 \cdot 2 + 3 \cdot 2 = 14$$$. The remain will be $$$\{4, 0, 2, 0, 4, 0, 7, 2\}$$$. Customer $$$4$$$ will be served $$$2$$$ dishes of the $$$3$$$-rd kind, $$$2$$$ dishes of the $$$8$$$-th kind. The cost is $$$2 \cdot 3 + 2 \cdot 2 = 10$$$. The remain will be $$$\{4, 0, 0, 0, 4, 0, 7, 0\}$$$. Customer $$$5$$$ will be served $$$7$$$ dishes of the $$$7$$$-th kind, $$$3$$$ dishes of the $$$1$$$-st kind. The cost is $$$7 \cdot 3 + 3 \cdot 6 = 39$$$. The remain will be $$$\{1, 0, 0, 0, 4, 0, 0, 0\}$$$.In the second sample, each customer is served what they order except the last one, who leaves angrily without paying. For example, the second customer is served $$$6$$$ dishes of the second kind, so the cost is $$$66 \cdot 6 = 396$$$.In the third sample, some customers may not be served what they order. For example, the second customer is served $$$6$$$ dishes of the second kind, $$$6$$$ of the third and $$$1$$$ of the fourth, so the cost is $$$66 \cdot 6 + 666 \cdot 6 + 6666 \cdot 1 = 11058$$$.

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

	}
}


Recently personal training sessions have finished in the Berland State University Olympiad Programmer Training Centre. By the results of these training sessions teams are composed for the oncoming team contest season. Each team consists of three people. All the students of the Centre possess numbers from 1 to 3n, and all the teams possess numbers from 1 to n. The splitting of students into teams is performed in the following manner: while there are people who are not part of a team, a person with the best total score is chosen among them (the captain of a new team), this person chooses for himself two teammates from those who is left according to his list of priorities. The list of every person's priorities is represented as a permutation from the rest of 3n - 1 students who attend the centre, besides himself.You are given the results of personal training sessions which are a permutation of numbers from 1 to 3n, where the i-th number is the number of student who has won the i-th place. No two students share a place. You are also given the arrangement of the already formed teams in the order in which they has been created. Your task is to determine the list of priorities for the student number k. If there are several priority lists, choose the lexicographically minimal one.

The first line contains an integer n (1 ≤ n ≤ 105) which is the number of resulting teams. The second line contains 3n space-separated integers from 1 to 3n which are the results of personal training sessions. It is guaranteed that every student appears in the results exactly once. Then follow n lines each containing three integers from 1 to 3n — each line describes the members of a given team. The members of one team can be listed in any order, but the teams themselves are listed in the order in which they were created. It is guaranteed that the arrangement is correct, that is that every student is a member of exactly one team and those teams could really be created from the given results using the method described above. The last line contains number k (1 ≤ k ≤ 3n) which is the number of a student for who the list of priorities should be found.

Print 3n - 1 numbers — the lexicographically smallest list of priorities for the student number k.  The lexicographical comparison is performed by the standard < operator in modern programming languages. The list a is lexicographically less that the list b if exists such an i (1 ≤ i ≤ 3n), that ai < bi, and for any j (1 ≤ j < i) aj = bj. Note, that the list 1 9 10 is lexicographically less than the list 1 10 9. That is, the comparison of lists is different from the comparison of lines.

package main

import (
	"fmt"
	"os"
	"io/ioutil"
	"bytes"
)

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

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)
	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	pos := make([]int, 3 * n + 1)
	for i := 0;i < 3 * n - 1;i ++ {
		var p int
		fmt.Fscanf(reader, "%d ", &p)
		pos[p] = i
	}
	var p int
	fmt.Fscanf(reader, "%d\n", &p)
	pos[p] = 3 * n - 1
	team := make([][3]int, n)
	arranged := make([]bool, 3 * n + 1)
	for i := 0;i < n;i ++ {
		fmt.Fscanf(reader, "%d %d %d\n", &team[i][0], &team[i][1], &team[i][2])
	}
	var k int
	fmt.Fscanf(reader, "%d", &k)
	for i := 0;i < n;i ++ {
		t0, t1, t2 := team[i][0], team[i][1], team[i][2]
		arranged[t0], arranged[t1], arranged[t2] = true, true, true
		var x1, x2 int
		if k == t0 {
			x1, x2 = t1, t2
		} else if k == t1 {
			x1, x2 = t0, t2
		} else if k == t2 {
			x1, x2 = t0, t1
		} else {
			continue
		}
		if pos[k] < pos[x1] && pos[k] < pos[x2] {
			m := max(x1, x2)
			for j := 1;j <= m;j ++ {
				if arranged[j] && j != k {
					fmt.Printf("%d ", j)
				}
			}
			for j := 1;j <= m;j ++ {
				if !arranged[j] && j != k {
					fmt.Printf("%d ", j)
				}
			}
			for j := m + 1;j <= 3 * n;j ++ {
				if j != k {
					fmt.Printf("%d ", j)
				}
			}
			return
		} else {
			for j := 1;j <= 3 * n;j ++ {
				if j != k {
					fmt.Printf("%d ", j)
				}
			}
			return
		}
	}
}


In fact, the problems E1 and E2 do not have much in common. You should probably think of them as two separate problems.You are given an integer array $$$a[1 \ldots n] = [a_1, a_2, \ldots, a_n]$$$.Let us consider an empty deque (double-ended queue). A deque is a data structure that supports adding elements to both the beginning and the end. So, if there are elements $$$[3, 4, 4]$$$ currently in the deque, adding an element $$$1$$$ to the beginning will produce the sequence $$$[\color{red}{1}, 3, 4, 4]$$$, and adding the same element to the end will produce $$$[3, 4, 4, \color{red}{1}]$$$.The elements of the array are sequentially added to the initially empty deque, starting with $$$a_1$$$ and finishing with $$$a_n$$$. Before adding each element to the deque, you may choose whether to add it to the beginning or to the end.For example, if we consider an array $$$a = [3, 7, 5, 5]$$$, one of the possible sequences of actions looks like this: $$$\quad$$$ 1.add $$$3$$$ to the beginning of the deque:deque has a sequence $$$[\color{red}{3}]$$$ in it;$$$\quad$$$ 2.add $$$7$$$ to the end of the deque:deque has a sequence $$$[3, \color{red}{7}]$$$ in it;$$$\quad$$$ 3.add $$$5$$$ to the end of the deque:deque has a sequence $$$[3, 7, \color{red}{5}]$$$ in it;$$$\quad$$$ 4.add $$$5$$$ to the beginning of the deque:deque has a sequence $$$[\color{red}{5}, 3, 7, 5]$$$ in it;Find the minimal possible number of inversions in the deque after the whole array is processed. An inversion in sequence $$$d$$$ is a pair of indices $$$(i, j)$$$ such that $$$i < j$$$ and $$$d_i > d_j$$$. For example, the array $$$d = [5, 3, 7, 5]$$$ has exactly two inversions — $$$(1, 2)$$$ and $$$(3, 4)$$$, since $$$d_1 = 5 > 3 = d_2$$$ and $$$d_3 = 7 > 5 = d_4$$$.

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

Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to a test case should be a single integer — the minimal possible number of inversions in the deque after executing the described algorithm.

NoteOne of the ways to get the sequence $$$[5, 3, 7, 5]$$$ in the deque, containing only two inversions, from the initial array $$$[3, 7, 5, 5]$$$ (the first sample test case) is described in the problem statement. Also, in this example, you could get the answer of two inversions by simply putting each element of the original array at the end of the deque. In this case, the original sequence $$$[3, 7, 5, 5]$$$, also containing exactly two inversions, will be in the deque as-is.

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


You are given two arrays $$$a$$$ and $$$b$$$ of positive integers, with length $$$n$$$ and $$$m$$$ respectively. Let $$$c$$$ be an $$$n \times m$$$ matrix, where $$$c_{i,j} = a_i \cdot b_j$$$. You need to find a subrectangle of the matrix $$$c$$$ such that the sum of its elements is at most $$$x$$$, and its area (the total number of elements) is the largest possible.Formally, you need to find the largest number $$$s$$$ such that it is possible to choose integers $$$x_1, x_2, y_1, y_2$$$ subject to $$$1 \leq x_1 \leq x_2 \leq n$$$, $$$1 \leq y_1 \leq y_2 \leq m$$$, $$$(x_2 - x_1 + 1) \times (y_2 - y_1 + 1) = s$$$, and $$$$$$\sum_{i=x_1}^{x_2}{\sum_{j=y_1}^{y_2}{c_{i,j}}} \leq x.$$$$$$

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 2000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2000$$$). The third line contains $$$m$$$ integers $$$b_1, b_2, \ldots, b_m$$$ ($$$1 \leq b_i \leq 2000$$$). The fourth line contains a single integer $$$x$$$ ($$$1 \leq x \leq 2 \cdot 10^{9}$$$).

If it is possible to choose four integers $$$x_1, x_2, y_1, y_2$$$ such that $$$1 \leq x_1 \leq x_2 \leq n$$$, $$$1 \leq y_1 \leq y_2 \leq m$$$, and $$$\sum_{i=x_1}^{x_2}{\sum_{j=y_1}^{y_2}{c_{i,j}}} \leq x$$$, output the largest value of $$$(x_2 - x_1 + 1) \times (y_2 - y_1 + 1)$$$ among all such quadruplets, otherwise output $$$0$$$.

NoteMatrix from the first sample and the chosen subrectangle (of blue color):  Matrix from the second sample and the chosen subrectangle (of blue color):

// A good array questions!
package main

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

// // Returns the mapping between the length of "selection" to the min-sum.
// func parseChoice(nums []int) map[int]int {
// 	choice := map[int]int{}
// 	for i := 1; i <= len(nums); i++ {
// 		min := math.MaxInt32
// 		for j := 0; j < (len(nums) - i + 1); j++ {
// 			sum := 0
// 			for k := 0; k < i; k++ {
// 				sum += nums[j+k]
// 			}
// 			if min > sum {
// 				min = sum
// 			}
// 		}
// 		choice[i] = min
// 	}
// 	return choice
// }

// Returns the mapping between the length of "selection" to the min-sum.
func parseChoice(nums []int) map[int]int {
	choice := map[int]int{}
	// Optimization
	last := map[int]int{}
	for i := 1; i <= len(nums); i++ {
		min := math.MaxInt32
		for j := 0; j < (len(nums) - i + 1); j++ {
			sum := last[j] + nums[j+i-1]
			if min > sum {
				min = sum
			}
			last[j] = sum
		}
		choice[i] = min
	}
	return choice
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanInt := func() int {
		scanner.Scan()
		num, err := strconv.Atoi(scanner.Text())
		if err != nil {
			log.Fatal(err)
		}
		return num
	}

	n, m := scanInt(), scanInt()
	a, b := make([]int, n), make([]int, m)
	for i := 0; i < n; i++ {
		a[i] = scanInt()
	}
	for i := 0; i < m; i++ {
		b[i] = scanInt()
	}
	x := scanInt()

	choiceA, choiceB := parseChoice(a), parseChoice(b)

	bestS := 0
	for i := 1; i <= n; i++ {
		for j := 1; j <= m; j++ {
			if int64(choiceA[i])*int64(choiceB[j]) > int64(x) {
				continue
			}
			if i*j > bestS {
				bestS = i * j
			}
		}
	}

	fmt.Println(bestS)
}