You are given a string $$$s$$$, consisting of brackets of two types: '(', ')', '[' and ']'.A string is called a regular bracket sequence (RBS) if it's of one of the following types:   empty string;  '(' + RBS + ')';  '[' + RBS + ']';  RBS + RBS. where plus is a concatenation of two strings.In one move you can choose a non-empty subsequence of the string $$$s$$$ (not necessarily consecutive) that is an RBS, remove it from the string and concatenate the remaining parts without changing the order.What is the maximum number of moves you can perform?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Each of the next $$$t$$$ lines contains a non-empty string, consisting only of characters '(', ')', '[' and ']'. The total length of the strings over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase print a single integer — the maximum number of moves you can perform on a given string $$$s$$$.

NoteIn the first example you can just erase the whole string.In the second example you can first erase the brackets on positions $$$1$$$ and $$$2$$$: "[]()", then "()" is left. After that you can erase it whole. You could erase the whole string from the beginning but you would get one move instead of two.In the third example you can first erase the brackets on positions $$$1$$$ and $$$3$$$: "([)]". They form an RBS "()". Then "[]" is left, so you can erase it whole.In the fourth example there is no subsequence that is an RBS, so you can't perform a move at all.In the fifth example you can erase the brackets on positions $$$2$$$ and $$$4$$$: ")[(]" and get ")(" as a result. You can erase nothing from it.

package main

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

/*
func main() {

	t := 0
	reader := bufio.NewReader(os.Stdin)
	fmt.Fscan(reader, &t)

	for t > 0 {

		var str string
		var s, sCount, m, mCount = 0, 0, 0, 0

		fmt.Fscan(reader, &str)
		//fmt.Printf("%d, %d, %d, %d", '(', ')', '[', ']')

		for i := 0; i < strings.Count(str, "")-1; i++ {
			if str[i] == 40 {
				s++
			}

			if str[i] == 91 {
				m++
			}

			if str[i] == 41 && s > 0 {
				sCount++
				s--
			}

			if str[i] == 93 && m > 0 {
				mCount++
				m--
			}

		}

		fmt.Println(mCount + sCount)
		t--
	}

}
*/

func main() {
	in := bufio.NewReader(os.Stdin)
	var t, ans, a, b int
	var s string
	fmt.Fscan(in, &t)
	for ; t > 0; t-- {
		fmt.Fscan(in, &s)
		a = 0
		b = 0
		ans = 0
		for i := range s {
			if s[i] == '(' {
				a++
			}
			if s[i] == '[' {
				b++
			}
			if s[i] == ')' && a > 0 {
				a--
				ans++
			}
			if s[i] == ']' && b > 0 {
				b--
				ans++
			}
		}
		fmt.Println(ans)
	}

}

package main

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

func main() {

	t := 0
	reader := bufio.NewReader(os.Stdin)
	fmt.Fscan(reader, &t)

	for t > 0 {

		var str string
		var s, sCount, m, mCount = 0, 0, 0, 0

		fmt.Fscan(reader, &str)
		//fmt.Printf("%d, %d, %d, %d", '(', ')', '[', ']')

		for i := range str {
			if str[i] == 40 {
				s++
			}

			if str[i] == 91 {
				m++
			}

			if str[i] == 41 && s > 0 {
				sCount++
				s--
			}

			if str[i] == 93 && m > 0 {
				mCount++
				m--
			}

		}

		fmt.Println(mCount + sCount)
		t--
	}

}

/*
func main() {
	in := bufio.NewReader(os.Stdin)
	var t, ans, a, b int
	var s string
	fmt.Fscan(in, &t)
	for ; t > 0; t-- {
		fmt.Fscan(in, &s)
		a = 0
		b = 0
		ans = 0
		for i := range s {
			if s[i] == '(' {
				a++
			}
			if s[i] == '[' {
				b++
			}
			if s[i] == ')' && a > 0 {
				a--
				ans++
			}
			if s[i] == ']' && b > 0 {
				b--
				ans++
			}
		}
		fmt.Println(ans)
	}

}
*/

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	var t, ans, a, b int
	var s string
	fmt.Fscan(in, &t)
	for ; t > 0; t-- {
		fmt.Fscan(in, &s)
		a = 0
		b = 0
		ans=0
		for i := range s {
			if s[i] == '(' {
				a++
			}
			if s[i] == '[' {
				b++
			}
			if s[i] == ')' && a > 0 {
				a--
				ans++
			}
			if s[i] == ']' && b > 0 {
				b--
				ans++
			}
		}
		fmt.Println(ans)
	}

}

package main

import (
	"fmt"
)

func solve(s string) (res int) {
	var a []struct{}
	var b []struct{}
	for i := range s {
		if s[i] == '[' {
			a = append(a, struct{}{})
		} else if s[i] == ']' {
			if len(a) != 0 {
				a = a[1:]
				res++
			}
		} else if s[i] == '(' {
			b = append(b, struct{}{})
		} else if s[i] == ')' {
			if len(b) != 0 {
				b = b[1:]
				res++
			}
		}
	}

	return
}

func main() {
	var n int

	fmt.Scanln(&n)
	s := make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Scanln(&s[i])
	}
	for i := 0; i < n; i++ {
		fmt.Println(solve(s[i]))
	}
}

/*
URL:
https://codeforces.com/contest/1452/problem/C
*/

package main

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

var (
	tc int

	S []rune
)

func main() {
	defer stdout.Flush()

	tc = readi()
	for i := 0; i < tc; i++ {
		S = readrs()

		solve()
	}
}

func solve() {
	R, P := []rune{}, []rune{}

	for _, r := range S {
		if r == '(' || r == ')' {
			P = append(P, r)
		} else {
			R = append(R, r)
		}
	}

	ans := 0

	st := []rune{}
	for _, r := range P {
		if len(st) == 0 || r == '(' {
			st = append(st, r)
			continue
		}

		m := len(st)
		if st[m-1] == '(' {
			st = st[:m-1]
			ans++
		}
	}

	st = []rune{}
	for _, r := range R {
		if len(st) == 0 || r == '[' {
			st = append(st, r)
			continue
		}

		m := len(st)
		if st[m-1] == '[' {
			st = st[:m-1]
			ans++
		}
	}

	fmt.Println(ans)
}

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

/********** common constants **********/

const (
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPH_N  = 26
	INF_I64 = math.MaxInt64
	INF_B60 = 1 << 60
	INF_I32 = math.MaxInt32
	INF_B30 = 1 << 30
	NIL     = -1
	EPS     = 1e-10
)

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

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

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

// min returns the min integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func min(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

// max returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func max(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

// chmin accepts a pointer of integer and a target value.
// If target value is SMALLER than the first argument,
//	then the first argument will be updated by the second argument.
func chmin(updatedValue *int, target int) bool {
	if *updatedValue > target {
		*updatedValue = target
		return true
	}
	return false
}

// chmax accepts a pointer of integer and a target value.
// If target value is LARGER than the first argument,
//	then the first argument will be updated by the second argument.
func chmax(updatedValue *int, target int) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

// sum returns multiple integers sum.
func sum(integers ...int) int {
	var s int
	s = 0

	for _, i := range integers {
		s += i
	}

	return s
}

// abs is integer version of math.Abs
func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

// pow is integer version of math.Pow
// pow calculate a power by Binary Power (二分累乗法(O(log e))).
func pow(a, e int) int {
	if a < 0 || e < 0 {
		panic(errors.New("[argument error]: PowInt does not accept negative integers"))
	}

	if e == 0 {
		return 1
	}

	if e%2 == 0 {
		halfE := e / 2
		half := pow(a, halfE)
		return half * half
	}

	return a * pow(a, e-1)
}

/********** FAU standard libraries **********/

//fmt.Sprintf("%b\n", 255) 	// binary expression

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

//str := reads()
//i := readi()
//X := readis(n)
//S := readrs()
//a := readf()
//A := readfs(n)

//str := ZeroPaddingRuneSlice(num, 32)
//str := PrintIntsLine(X...)

/*********** Input ***********/

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

func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	r.Split(sf)

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

// readi returns an integer.
func readi() int {
	return int(_readInt64())
}
func readi2() (int, int) {
	return int(_readInt64()), int(_readInt64())
}
func readi3() (int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64())
}
func readi4() (int, int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64()), int(_readInt64())
}

// readll returns as integer as int64.
func readll() int64 {
	return _readInt64()
}
func readll2() (int64, int64) {
	return _readInt64(), _readInt64()
}
func readll3() (int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64()
}
func readll4() (int64, int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64(), _readInt64()
}

func _readInt64() int64 {
	i, err := strconv.ParseInt(reads(), 0, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

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

// readlls returns as int64 slice that has n integers.
func readlls(n int) []int64 {
	b := make([]int64, n)
	for i := 0; i < n; i++ {
		b[i] = readll()
	}
	return b
}

// readf returns an float64.
func readf() float64 {
	return float64(_readFloat64())
}

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

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

// readrs returns a rune slice.
func readrs() []rune {
	return []rune(reads())
}

/*********** Output ***********/

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

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

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

	return string(res)
}

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

	for i := 0; i < len(A); i++ {
		str := strconv.FormatInt(A[i], 10) // 64bit int version
		res = append(res, []rune(str)...)

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

	return string(res)
}

// Printf is function for output strings to buffered os.Stdout.
// You may have to call stdout.Flush() finally.
func printf(format string, a ...interface{}) {
	fmt.Fprintf(stdout, format, a...)
}

/*********** Debugging ***********/

// debugf is wrapper of fmt.Fprintf(os.Stderr, format, a...)
func debugf(format string, a ...interface{}) {
	fmt.Fprintf(os.Stderr, format, a...)
}

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

package main

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

// 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 s []byte
		Fscan(in, &s)
		ans := 0
		f := func(l, r byte) {
			c := 0
			for _, b := range s {
				if b == l {
					c++
				} else if b == r && c > 0 {
					c--
					ans++
				}
			}
		}
		f('(', ')')
		f('[', ']')
		Fprintln(out, ans)
	}

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

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

package main

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

var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)

	fmt.Fscan(input, &t)

	for o := 0; o < t; o++ {
		var arr string

		fmt.Fscan(input, &arr)
		n := len(arr)

		var one int // '('
		var two int // '['
		var ans int // answer
		for i := 0; i < n; i++ {

			if arr[i] == '(' {
				one++
			}

			if arr[i] == '[' {
				two++
			}

			if arr[i] == ')' && one > 0 {
				ans++
				one--
			}

			if arr[i] == ']' && two > 0 {
				ans++
				two--
			}
		}

		fmt.Println(ans)
	}
}

package main

import (
	"fmt"
)

func main() {
	var strArr []string
	var strLen int
	_, _ = fmt.Scanln(&strLen)
	for i := 1; i <= strLen; i++ {
		var input string
		_, _ = fmt.Scanln(&input)
		strArr = append(strArr, input)
	}
	for i := 0; i < len(strArr); i++ {
		str := strArr[i]
		fmt.Println(evalStr(str))
	}
	return
}

func evalStr(str string) int {
	pCount, bCount, pEval, bEval := 0, 0, 0, 0
	for i := 0; i < len(str); i++ {
		ltr := string(str[i])
		if ltr == ")" {
			if pEval > 0 {
				pCount++
				pEval--
			} else {
				continue
			}
		}
		if ltr == "]" {
			if bEval > 0 {
				bCount++
				bEval--
			} else {
				continue
			}
		}
		if ltr == "(" {
			pEval++
		}
		if ltr == "[" {
			bEval++
		}
	}
	return bCount + pCount
}

package main

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

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

	var t int
	var s string
	fmt.Fscan(in, &t)

	for ; t > 0; t-- {
		fmt.Fscan(in, &s)
		circleOpen := 0
		circleClosed := 0
		squareOpen := 0
		squareClosed := 0
		for i := range s {
			if s[i] == '(' {
				circleOpen++
			}
			if s[i] == '[' {
				squareOpen++
			}
			if s[i] == ')' && circleOpen > 0 {
				circleOpen--
				circleClosed++
			}
			if s[i] == ']' && squareOpen > 0 {
				squareOpen--
				squareClosed++
			}
		}
		fmt.Println(circleClosed + squareClosed)
	}
}

package main

import (
	"fmt"
)

func main() {
	n := 0
	fmt.Scanf("%d\n", &n)
	for ; n > 0; n-- {
		str := ""
		fmt.Scanf("%s\n", &str)
		t, c1, c2 := 0, 0, 0
		for _, r := range str {
			switch r {
			case '(':
				c1++
			case ')':
				if c1 > 0 {
					t++
					c1--
				}
			case '[':
				c2++
			case ']':
				if c2 > 0 {
					t++
					c2--
				}
			}
		}
		fmt.Println(t)
	}
}

package main

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

func main() {

	t := 0
	fmt.Scanln(&t)

	for t > 0 {

		//var str string
		var s, sCount, m, mCount = 0, 0, 0, 0

		reader := bufio.NewReader(os.Stdin)
		str, _ := reader.ReadString('\n')

		//fmt.Scanln(&str)
		//fmt.Printf("%d, %d, %d, %d", '(', ')', '[', ']')

		for i := 0; i < strings.Count(str, "")-1; i++ {
			if str[i] == 40 {
				s++
			}

			if str[i] == 91 {
				m++
			}

			if str[i] == 41 && s > 0 {
				sCount++
				s--
			}

			if str[i] == 93 && m > 0 {
				mCount++
				m--
			}

		}

		fmt.Println(mCount + sCount)
		t--
	}

}

package main

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

func main() {

	t := 0
	fmt.Scanln(&t)

	for t > 0 {

		//var str string
		var s, sCount, m, mCount = 0, 0, 0, 0

		reader := bufio.NewReader(os.Stdin)
		str, _ := reader.ReadString('\n')
		str = strings.TrimSpace(str)

		//fmt.Scanln(&str)
		//fmt.Printf("%d, %d, %d, %d", '(', ')', '[', ']')

		for i := 0; i < strings.Count(str, "")-1; i++ {
			if str[i] == 40 {
				s++
			}

			if str[i] == 91 {
				m++
			}

			if str[i] == 41 && s > 0 {
				sCount++
				s--
			}

			if str[i] == 93 && m > 0 {
				mCount++
				m--
			}

		}

		fmt.Println(mCount + sCount)
		t--
	}

}

package main

import (
	"fmt"
)

func solve(s string) (res int) {
	for s != "" {
		ss := s
		for i := 0; i < len(s); i++ {
			if s[i] == '[' {
				for j := i; j < len(s); j++ {
					if s[j] == ']' {
						s = s[:i] + s[i+1:j] + s[j+1:]
						res++
					}
				}
			}
		}
		for i := 0; i < len(s); i++ {
			if s[i] == '(' {
				for j := i; j < len(s); j++ {
					if s[j] == ')' {
						s = s[:i] + s[i+1:j] + s[j+1:]
						res++
					}
				}
			}
		}
		if ss == s {
			return
		}
	}

	return
}

func main() {
	var n int

	fmt.Scanln(&n)
	s := make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Scanln(&s[i])
	}
	for i := 0; i < n; i++ {
		fmt.Println(solve(s[i]))
	}
}

package main

import (
	"fmt"
)

func solve(s string) (res int) {
	for i := 0; i < len(s); i++ {
		if s[i] == '[' {
			for j := i; j < len(s); j++ {
				if s[j] == ']' {
					s = s[:i] + s[i+1:j] + s[j+1:]
					res++
				}
			}
		}
	}
	for i := 0; i < len(s); i++ {
		if s[i] == '(' {
			for j := i; j < len(s); j++ {
				if s[j] == ')' {
					s = s[:i] + s[i+1:j] + s[j+1:]
					res++
				}
			}
		}
	}
	return
}

func main() {
	var n int

	fmt.Scanln(&n)
	s := make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Scanln(&s[i])
	}
	for i := 0; i < n; i++ {
		fmt.Println(solve(s[i]))
	}
}

package main

import (
	"fmt"
)

func solve(s string) (res int) {
	for s != "" {
		ss := s
		for i := 0; i < len(s); i++ {
			if s[i] == '[' {
				for j := i; j < len(s); j++ {
					if s[j] == ']' {
						s = s[:i] + s[i+1:j] + s[j+1:]
						res++
						break
					}
				}
			}
		}
		fmt.Println(s)
		for i := 0; i < len(s); i++ {
			if s[i] == '(' {
				for j := i; j < len(s); j++ {
					if s[j] == ')' {
						s = s[:i] + s[i+1:j] + s[j+1:]
						res++
						break
					}
				}
			}
		}
		fmt.Println(s)
		if ss == s {
			return
		}
	}

	return
}

func main() {
	var n int

	fmt.Scanln(&n)
	s := make([]string, n)
	for i := 0; i < n; i++ {
		fmt.Scanln(&s[i])
	}
	for i := 0; i < n; i++ {
		fmt.Println(solve(s[i]))
	}
}

package main

import (
	"fmt"
)

func main() {
	n := 0
	fmt.Scanf("%d", &n)
	for ; n > 0; n-- {
		str := ""
		fmt.Scanf("%s\n", &str)
		t, c1, c2 := 0, 0, 0
		for _, r := range str {
			switch r {
			case '(':
				c1++
			case ')':
				if c1 > 0 {
					t++
					c1--
				}
			case '[':
				c2++
			case ']':
				if c2 > 0 {
					t++
					c2--
				}
			}
		}
		fmt.Println(t)
	}
}


— What is my mission?  — To count graph diameters.You and Your SubmissionA tree is a connected undirected graph without cycles. A weighted tree has a weight assigned to each edge. The degree of a vertex is the number of edges connected to this vertex.You are given a weighted tree with $$$n$$$ vertices, each edge has a weight of $$$1$$$. Let $$$L$$$ be the set of vertices with degree equal to $$$1$$$. You have to answer $$$q$$$ independent queries. In the $$$i$$$-th query:  You are given a positive integer $$$x_i$$$.  For all $$$u,v \in L$$$ such that $$$u < v$$$, add edge $$$(u, v)$$$ with weight $$$x_i$$$ to the graph (initially the given tree).  Find the diameter of the resulting graph. The diameter of a graph is equal to $$$\max\limits_{1 \le u < v \le n}{\operatorname{d}(u, v)}$$$, where $$$\operatorname{d}(u, v)$$$ is the length of the shortest path between vertex $$$u$$$ and vertex $$$v$$$.

The first line contains a single integer $$$n$$$ ($$$3 \le n \le 10^6$$$). The second line contains $$$n - 1$$$ integers $$$p_2,p_3,\ldots,p_n$$$ ($$$1 \le p_i < i$$$) indicating that there is an edge between vertices $$$i$$$ and $$$p_i$$$. It is guaranteed that the given edges form a tree. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10$$$). The fourth line contains $$$q$$$ integers $$$x_1,x_2,\ldots,x_q$$$ ($$$1 \le x_i \le n$$$). All $$$x_i$$$ are distinct.

Print $$$q$$$ integers in a single line — the answers to the queries.

NoteThe graph in the first test after adding the edges:

package main

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

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

	var buf bytes.Buffer
	n := readNum(reader)
	P := readNNums(reader, n-1)
	m := readNum(reader)
	X := readNNums(reader, m)
	res := solve(n, P, X)
	for i := 0; i < m; i++ {
		buf.WriteString(fmt.Sprintf("%d\n", res[i]))
	}
	fmt.Print(buf.String())
}

func readString(reader *bufio.Reader) string {
	s, _ := reader.ReadString('\n')
	for i := 0; i < len(s); i++ {
		if s[i] == '\n' || s[i] == '\r' {
			return s[:i]
		}
	}
	return s
}

func normalize(s string) string {

	for i := len(s); i > 0; i-- {
		if s[i-1] >= 'a' && s[i-1] <= 'z' {
			return s[:i]
		}
	}
	return ""
}

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

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

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

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

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

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

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

	return i
}

const INF = 1 << 30

func solve(n int, P []int, X []int) []int {
	// D(u, v) = min(fu + fv + x, d(u, v))
	g := NewGraph(n, 2*n)
	deg := make([]int, n)

	for i := 2; i <= n; i++ {
		p := P[i-2]
		deg[i-1]++
		deg[p-1]++
		g.AddEdge(i-1, p-1)
		g.AddEdge(p-1, i-1)
	}

	f := make([]int, n)
	for i := 0; i < n; i++ {
		f[i] = INF
	}

	que := make([]int, n)
	var front, end int
	for i := 0; i < n; i++ {
		if deg[i] == 1 {
			f[i] = 0
			que[end] = i
			end++
		}
	}

	for front < end {
		u := que[front]
		front++
		for i := g.node[u]; i > 0; i = g.next[i] {
			v := g.to[i]
			if f[v] == INF {
				f[v] = f[u] + 1
				que[end] = v
				end++
			}
		}
	}

	depth := make([]int, n)

	val := make([][]int, n)
	for i := 0; i < n; i++ {
		val[i] = make([]int, 0, 1)
	}

	ans := make([]int, len(X))

	merge := func(x, y int) {
		if len(val[x]) < len(val[y]) {
			val[x], val[y] = val[y], val[x]
		}
		// merge y to x, and val[x] is what we want
		for id := 0; id < len(X); id++ {
			for i := 0; i < len(val[y]); i++ {
				j := max(0, ans[id]-i-X[id])
				for j < len(val[x]) && val[y][i]+val[x][j]-2*depth[x] >= ans[id] {
					ans[id]++
					j = max(0, ans[id]-i-X[id])
				}
			}
		}

		for i := 0; i < len(val[y]); i++ {
			val[x][i] = max(val[x][i], val[y][i])
		}
	}

	var dfs func(p int, u int)

	dfs = func(p int, u int) {
		for i := g.node[u]; i > 0; i = g.next[i] {
			v := g.to[i]
			if p == v {
				continue
			}
			depth[v] = depth[u] + 1
			dfs(u, v)
			merge(u, v)
		}

		for id := 0; id < len(X); id++ {
			j := max(0, ans[id]-f[u]-X[id])
			if j < len(val[u]) && val[u][j]+depth[u]-2*depth[u] >= ans[id] {
				ans[id]++
			}
		}

		if f[u] == len(val[u]) {
			val[u] = append(val[u], depth[u])
		}
	}

	dfs(0, 0)

	for i := 0; i < len(X); i++ {
		ans[i]--
	}

	return ans
}

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

type Graph struct {
	node []int
	next []int
	to   []int
	cur  int
}

func NewGraph(n int, e int) *Graph {
	g := new(Graph)
	g.node = make([]int, n)
	g.to = make([]int, e+1)
	g.next = make([]int, e+1)
	g.cur = 0
	return g
}

func (g *Graph) AddEdge(u, v int) {
	g.cur++
	g.next[g.cur] = g.node[u]
	g.node[u] = g.cur
	g.to[g.cur] = v
}

package main

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

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

	var buf bytes.Buffer
	n := readNum(reader)
	P := readNNums(reader, n-1)
	m := readNum(reader)
	X := readNNums(reader, m)
	res := solve(n, P, X)
	for i := 0; i < m; i++ {
		buf.WriteString(fmt.Sprintf("%d\n", res[i]))
	}
	fmt.Print(buf.String())
}

func readString(reader *bufio.Reader) string {
	s, _ := reader.ReadString('\n')
	for i := 0; i < len(s); i++ {
		if s[i] == '\n' || s[i] == '\r' {
			return s[:i]
		}
	}
	return s
}

func normalize(s string) string {

	for i := len(s); i > 0; i-- {
		if s[i-1] >= 'a' && s[i-1] <= 'z' {
			return s[:i]
		}
	}
	return ""
}

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

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

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

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

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

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

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

	return i
}

const INF = 1 << 30

func solve(n int, P []int, X []int) []int {
	// D(u, v) = min(fu + fv + x, d(u, v))
	g := NewGraph(n, 2*n)
	deg := make([]int, n)

	for i := 2; i <= n; i++ {
		p := P[i-2]
		deg[i-1]++
		deg[p-1]++
		g.AddEdge(i-1, p-1)
		g.AddEdge(p-1, i-1)
	}

	f := make([]int, n)
	for i := 0; i < n; i++ {
		f[i] = INF
	}

	que := make([]int, n)
	var front, end int
	for i := 0; i < n; i++ {
		if deg[i] == 1 {
			f[i] = 0
			que[end] = i
			end++
		}
	}

	for front < end {
		u := que[front]
		front++
		for i := g.node[u]; i > 0; i = g.next[i] {
			v := g.to[i]
			if f[v] == INF {
				f[v] = f[u] + 1
				que[end] = v
				end++
			}
		}
	}

	depth := make([]int, n)

	var dfs func(p int, u int)
	dfs = func(p int, u int) {
		for i := g.node[u]; i > 0; i = g.next[i] {
			v := g.to[i]
			if p != v {
				depth[v] = depth[u] + 1
				dfs(u, v)
			}
		}
	}

	dfs(0, 0)

	val := make([][]int, n)
	for i := 0; i < n; i++ {
		val[i] = make([]int, 0, 1)
	}

	ans := make([]int, len(X))

	merge := func(x, y int) {
		if len(val[x]) < len(val[y]) {
			val[x], val[y] = val[y], val[x]
		}
		// merge y to x, and val[x] is what we want
		for i := 0; i < len(val[y]); i++ {
			for id := 0; id < len(X); id++ {
				j := max(0, ans[id]-i-X[id])
				for j < len(val[x]) && val[y][i]+val[x][j]-2*depth[x] >= ans[id] {
					ans[id]++
					j = max(0, ans[id]-i-X[id])
				}
			}
			val[x][i] = max(val[x][i], val[y][i])
		}

	}

	var dfs1 func(p int, u int)

	dfs1 = func(p int, u int) {
		for i := g.node[u]; i > 0; i = g.next[i] {
			v := g.to[i]
			if p == v {
				continue
			}
			dfs1(u, v)
			merge(u, v)
		}

		for id := 0; id < len(X); id++ {
			j := max(0, ans[id]-f[u]-X[id])
			for j < len(val[u]) && val[u][j]+depth[u]-2*depth[u] >= ans[id] {
				ans[id]++
				j = max(0, ans[id]-f[u]-X[id])
			}
		}

		if f[u] == len(val[u]) {
			val[u] = append(val[u], depth[u])
		}
	}

	dfs1(0, 0)

	for i := 0; i < len(X); i++ {
		ans[i]--
	}

	return ans
}

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

type Graph struct {
	node []int
	next []int
	to   []int
	cur  int
}

func NewGraph(n int, e int) *Graph {
	g := new(Graph)
	g.node = make([]int, n)
	g.to = make([]int, e+1)
	g.next = make([]int, e+1)
	g.cur = 0
	return g
}

func (g *Graph) AddEdge(u, v int) {
	g.cur++
	g.next[g.cur] = g.node[u]
	g.node[u] = g.cur
	g.to[g.cur] = v
}

package main

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

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

	var buf bytes.Buffer
	n := readNum(reader)
	P := readNNums(reader, n-1)
	m := readNum(reader)
	X := readNNums(reader, m)
	res := solve(n, P, X)
	for i := 0; i < m; i++ {
		buf.WriteString(fmt.Sprintf("%d\n", res[i]))
	}
	fmt.Print(buf.String())
}

func readString(reader *bufio.Reader) string {
	s, _ := reader.ReadString('\n')
	for i := 0; i < len(s); i++ {
		if s[i] == '\n' || s[i] == '\r' {
			return s[:i]
		}
	}
	return s
}

func normalize(s string) string {

	for i := len(s); i > 0; i-- {
		if s[i-1] >= 'a' && s[i-1] <= 'z' {
			return s[:i]
		}
	}
	return ""
}

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

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

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

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

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

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

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

	return i
}

const INF = 1 << 30

func solve(n int, P []int, X []int) []int {
	// D(u, v) = min(fu + fv + x, d(u, v))
	g := NewGraph(n, 2*n)
	deg := make([]int, n)

	for i := 2; i <= n; i++ {
		p := P[i-2]
		deg[i-1]++
		deg[p-1]++
		g.AddEdge(i-1, p-1)
		g.AddEdge(p-1, i-1)
	}

	f := make([]int, n)
	for i := 0; i < n; i++ {
		f[i] = INF
	}

	que := make([]int, n)
	var front, end int
	for i := 0; i < n; i++ {
		if deg[i] == 1 {
			f[i] = 0
			que[end] = i
			end++
		}
	}

	for front < end {
		u := que[front]
		front++
		for i := g.node[u]; i > 0; i = g.next[i] {
			v := g.to[i]
			if f[v] == INF {
				f[v] = f[u] + 1
				que[end] = v
				end++
			}
		}
	}

	depth := make([]int, n)

	var dfs func(p int, u int)
	dfs = func(p int, u int) {
		for i := g.node[u]; i > 0; i = g.next[i] {
			v := g.to[i]
			if p != v {
				depth[v] = depth[u] + 1
				dfs(u, v)
			}
		}
	}

	dfs(0, 0)

	val := make([][]int, n)
	for i := 0; i < n; i++ {
		val[i] = make([]int, 0, 1)
	}

	ans := make([]int, len(X))

	var dfs1 func(p int, u int)

	dfs1 = func(p int, u int) {
		big := -1
		for i := g.node[u]; i > 0; i = g.next[i] {
			v := g.to[i]
			if p == v {
				continue
			}
			dfs1(u, v)
			if big < 0 || len(val[big]) < len(val[v]) {
				big = v
			}
		}

		for i := g.node[u]; i > 0; i = g.next[i] {
			v := g.to[i]
			if p == v || v == big {
				continue
			}
			for l1 := 0; l1 < len(val[v]); l1++ {
				for id := 0; id < len(X); id++ {
					l2 := max(0, ans[id]-l1-X[id])
					for l2 < len(val[big]) && val[v][l1]+val[big][l2]-2*depth[u] >= ans[id] {
						ans[id]++
						l2 = max(0, ans[id]-l1-X[id])
					}
				}
				val[big][l1] = max(val[big][l1], val[v][l1])
			}
		}

		if big > 0 {
			l1 := f[u]
			for id := 0; id < len(X); id++ {
				l2 := max(0, ans[id]-l1-X[id])
				for l2 < len(val[big]) && depth[u]+val[big][l2]-2*depth[u] >= ans[id] {
					ans[id]++
					l2 = max(0, ans[id]-l1-X[id])
				}
			}
			if f[u] < len(val[big]) {
				val[big][f[u]] = max(val[big][f[u]], depth[u])
			} else {
				val[big] = append(val[big], depth[u])
			}
			val[u] = val[big]
		} else {
			val[u] = append(val[u], depth[u])
		}
	}

	dfs1(0, 0)

	for i := 0; i < len(X); i++ {
		ans[i]--
	}

	return ans
}

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

type Graph struct {
	node []int
	next []int
	to   []int
	cur  int
}

func NewGraph(n int, e int) *Graph {
	g := new(Graph)
	g.node = make([]int, n)
	g.to = make([]int, e+1)
	g.next = make([]int, e+1)
	g.cur = 0
	return g
}

func (g *Graph) AddEdge(u, v int) {
	g.cur++
	g.next[g.cur] = g.node[u]
	g.node[u] = g.cur
	g.to[g.cur] = v
}


Polycarp plays a (yet another!) strategic computer game. In this game, he leads an army of mercenaries.Polycarp wants to gather his army for a quest. There are $$$n$$$ mercenaries for hire, and the army should consist of some subset of them.The $$$i$$$-th mercenary can be chosen if the resulting number of chosen mercenaries is not less than $$$l_i$$$ (otherwise he deems the quest to be doomed) and not greater than $$$r_i$$$ (he doesn't want to share the trophies with too many other mercenaries). Furthermore, $$$m$$$ pairs of mercenaries hate each other and cannot be chosen for the same quest. How many non-empty subsets does Polycarp need to consider? In other words, calculate the number of non-empty subsets of mercenaries such that the size of this subset belongs to $$$[l_i, r_i]$$$ for each chosen mercenary, and there are no two mercenaries in the subset that hate each other.The answer may be large, so calculate it modulo $$$998244353$$$.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$, $$$0 \le m \le \min(20, \dfrac{n(n-1)}{2})$$$) — the number of mercenaries and the number of pairs of mercenaries that hate each other. Then $$$n$$$ lines follow, the $$$i$$$-th of them contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$). Then $$$m$$$ lines follow, the $$$i$$$-th of them contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i < b_i \le n$$$) denoting that the mercenaries $$$a_i$$$ and $$$b_i$$$ hate each other. There are no two equal pairs in this list.

Print one integer — the number of non-empty subsets meeting the constraints, taken modulo $$$998244353$$$.

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	n, m := readTwoNums(reader)
	L, R := make([]int, n), make([]int, n)
	for i := 0; i < n; i++ {
		L[i], R[i] = readTwoNums(reader)
	}
	E := make([][]int, m)
	for i := 0; i < m; i++ {
		E[i] = readNNums(reader, 2)
	}
	fmt.Println(solve(n, m, L, R, E))
}

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

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

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

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

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

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

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

	return i
}

const N = 300043
const MOD = 998244353

var fact [N]int64
var ifact [N]int64

func init() {
	fact[0] = 1
	for i := 1; i < N; i++ {
		fact[i] = int64(i) * fact[i-1] % MOD
	}
	ifact[N-1] = inverse(fact[N-1])

	for i := N - 2; i >= 0; i-- {
		ifact[i] = int64(i+1) * ifact[i+1] % MOD
	}
}

func inverse(a int64) int64 {
	return pow(a, MOD-2)
}

func pow(a int64, b int64) int64 {
	var r int64 = 1
	for b > 0 {
		if b&1 == 1 {
			r = r * a % MOD
		}
		a = a * a % MOD
		b >>= 1
	}
	return r
}

func nCr(n, r int) int64 {
	if n < 0 || r < 0 || n < r {
		return 0
	}
	res := fact[n] * ifact[r] % MOD
	res = res * ifact[n-r] % MOD
	return res
}

func solve(n int, m int, L []int, R []int, E [][]int) int {
	cnt := make([]int, n+2)
	for i := 0; i < n; i++ {
		cnt[L[i]]++
		cnt[R[i]+1]--
	}

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

	P := make([][]int64, 2*m+1)
	for i := 0; i < len(P); i++ {
		P[i] = make([]int64, n+1)
	}

	for i := 1; i <= n; i++ {
		for j := 0; j <= 2*m; j++ {
			P[j][i] = P[j][i-1] + nCr(cnt[i]-j, i-j)
			if P[j][i] >= MOD {
				P[j][i] -= MOD
			}
		}
	}

	var ans int64

	for mask := 0; mask < 1<<m; mask++ {
		var sign int64 = 1
		used := make(map[int]bool)
		for i := 0; i < m; i++ {
			if mask&(1<<i) > 0 {
				u, v := E[i][0], E[i][1]
				u--
				v--
				used[u] = true
				used[v] = true
				sign = sign * (MOD - 1) % MOD
			}
		}
		l, r := 1, n
		for k := range used {
			l = max(l, L[k])
			r = min(r, R[k])
		}
		if r < l {
			continue
		}
		ans = add(ans, mul(sign, add(P[len(used)][r], -P[len(used)][l-1])))
	}

	return int(ans)
}

func add(a, b int64) int64 {
	return ((a+b)%MOD + MOD) % MOD
}

func mul(a, b int64) int64 {
	return (a * b) % MOD
}

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

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


You are given a string $$$s$$$ consisting of lowercase English letters and a number $$$k$$$. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by $$$k$$$. You are asked to find the lexicographically smallest beautiful string of length $$$n$$$, which is lexicographically greater or equal to string $$$s$$$. If such a string does not exist, output $$$-1$$$.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds:   $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$;  in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 10\,000$$$) — the number of test cases. The next $$$2 \cdot T$$$ lines contain the description of test cases. The description of each test case consists of two lines. The first line of the description contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^5$$$) — the length of string $$$s$$$ and number $$$k$$$ respectively. The second line contains string $$$s$$$ consisting of lowercase English letters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case output in a separate line lexicographically smallest beautiful string of length $$$n$$$, which is greater or equal to string $$$s$$$, or $$$-1$$$ if such a string does not exist.

4
4 2
abcd
3 1
abc
4 3
aaaa
9 3
abaabaaaa

NoteIn the first test case "acac" is greater than or equal to $$$s$$$, and each letter appears $$$2$$$ or $$$0$$$ times in it, so it is beautiful.In the second test case each letter appears $$$0$$$ or $$$1$$$ times in $$$s$$$, so $$$s$$$ itself is the answer.We can show that there is no suitable string in the third test case.In the fourth test case each letter appears $$$0$$$, $$$3$$$, or $$$6$$$ times in "abaabaaab". All these integers are divisible by $$$3$$$.

package main

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

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

	var T, n, k int
	var s []byte
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &k, &s)
		if n%k > 0 {
			Fprintln(out, -1)
			continue
		}
		cnt := make([]int, 26)
		for _, b := range s {
			cnt[b-'a']++
		}
	O:
		for _, c := range cnt {
			if c%k == 0 {
				continue
			}
			for i := n - 1; i >= 0; i-- {
			o:
				for s[i]++; s[i] <= 'z'; s[i]++ {
					cnt[s[i]-1-'a']--
					cnt[s[i]-'a']++
					left := n - 1 - i
					for _, c := range cnt {
						need := (k - c%k) % k
						if left < need {
							continue o
						}
						left -= need
					}
					for i++; left > 0; left-- {
						s[i] = 'a'
						i++
					}
					for p := byte(0); i < n; i++ {
						for ; cnt[p]%k == 0; p++ {
						}
						s[i] = 'a' + p
						cnt[p]++
					}
					break O
				}
				cnt[25]--
			}
		}
		Fprintln(out, string(s))
	}
}

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

package main

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

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

	var T, n, k int
	var s []byte
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &k, &s)
		if n%k > 0 {
			Fprintln(out, -1)
			continue
		}
		cnt := make([]int, 26)
		for _, b := range s {
			cnt[b-'a']++
		}
	O:
		for _, c := range cnt {
			if c%k > 0 {
				for i := n - 1; i >= 0; i-- {
				o:
					for s[i]++; s[i] <= 'z'; s[i]++ {
						cnt[s[i]-1-'a']--
						cnt[s[i]-'a']++
						left := n - 1 - i
						for _, c := range cnt {
							need := (k - c%k) % k
							if left < need {
								continue o
							}
							left -= need
						}
						if left%k > 0 {
							continue
						}
						for i++; left > 0; left-- {
							s[i] = 'a'
							i++
						}
						for p := byte(0); i < n; i++ {
							for ; cnt[p]%k == 0; p++ {
							}
							s[i] = 'a' + p
							cnt[p]++
						}
						break O
					}
					cnt[25]--
				}
			}
		}
		Fprintln(out, string(s))
	}
}

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

package main

import (
	"fmt"
)

var n, k int
var s string

const maxn = 1e5 + 5

var pre [maxn][30]int

func idx(ch byte) int {
	return int(ch - 'a')
}
func work() {
	fmt.Scanln(&n, &k)
	fmt.Scanln(&s)
	if n%k != 0 {
		fmt.Println("-1")
		return
	}
	cnt := [30]int{}
	for _, ch := range s {
		cnt[ch-'a']++
	}
	for i := 0; i <= 26; i++ {
		if i == 26 {
			fmt.Println(s)
			return
		}
		if cnt[i]%k != 0 {
			break
		}
	}
	s = "#" + s
	for i := 1; i <= n; i++ {
		for j := 0; j < 26; j++ {
			pre[i][j] = pre[i-1][j]
		}
		pre[i][idx(s[i])]++
	}
	var ans []byte
	for i := n; i >= 1; i-- {
		for j := int(s[i] - 'a' + 1); j < 26; j++ {
			sum := 0
			for c := 0; c < 26; c++ {
				tmp := pre[i-1][c]
				if j == c {
					tmp++
				}
				sum += (k - tmp%k) % k
			}
			if sum <= n-i && (n-i-sum)%k == 0 {
				for x := 1; x < i; x++ {
					ans = append(ans, s[x])
				}
				ans = append(ans, byte(j+'a'))
				for x := 0; x < n-i-sum; x++ {
					ans = append(ans, 'a')
				}
				for x := 0; x < 26; x++ {
					tmp := pre[i-1][x]
					if x == j {
						tmp++
					}
					for y := 0; y < (k-tmp%k)%k; y++ {
						ans = append(ans, byte(x+'a'))
					}
				}
				fmt.Printf("%s\n", ans)
				return
			}
		}
	}
}
func main() {
	var T int
	fmt.Scanln(&T)
	for cas := 1; cas <= T; cas++ {
		work()
	}
	return
}

package main

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

type contest struct {
	in  io.Reader
	out io.Writer
}

func (con *contest) Scan(a ...interface{}) (int, error) {
	return fmt.Fscan(con.in, a...)
}
func (con *contest) Scanln(a ...interface{}) (int, error) {
	return fmt.Fscanln(con.in, a...)
}
func (con *contest) Scanf(f string, a ...interface{}) (int, error) {
	return fmt.Fscanf(con.in, f, a...)
}
func (con *contest) Print(a ...interface{}) (int, error) {
	return fmt.Fprint(con.out, a...)
}
func (con *contest) Println(a ...interface{}) (int, error) {
	return fmt.Fprintln(con.out, a...)
}
func (con *contest) Printf(f string, a ...interface{}) (int, error) {
	return fmt.Fprintf(con.out, f, a...)
}
func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	con := &contest{in: in, out: out}
	con.main()
}

func (con *contest) main() error {
	var testcases int
	con.Scan(&testcases)
	for testcase := 0; testcase < testcases; testcase++ {
		var N, K int
		var S string
		con.Scan(&N, &K, &S)
		if N%K != 0 {
			con.Println(-1)
			continue
		}
		Z := false
		if len(S) < N {
			S += strings.Repeat("a", N-len(S))
		} else if len(S) > N {
			S = S[:N]
			Z = true
		}
		H := make([]int, 26)
		for _, d := range S {
			H[d-'a']++
		}
		var X, Y, I int
	loop:
		for I = N; I > 0; I-- {
			Y = int(S[I-1] - 'a')
			H[Y]--
			if Z {
				Y++
			} else {
				Z = true
			}
			for Y < 26 {
				H[Y]++
				X = modSum(H, K)
				//fmt.Printf("%d:%d:%v\n", I, X, H)
				if X <= N-I && (N-I-X)%K == 0 {
					break loop
				}
				H[Y]--
				Y++
			}
		}
		if I == 0 {
			con.Println(-1)
			continue
		}
		con.Printf("%s%c", S[:I-1], Y+'a')
		con.Print(strings.Repeat("a", N-I-X))
		for i := 0; i < 26; i++ {
			for H[i]%K != 0 {
				con.Printf("%c", 'a'+i)
				H[i]++
			}
		}
		con.Println()
	}
	return nil
}

func modSum(H []int, K int) int {
	s := 0
	for _, h := range H {
		m := h % K
		if m > 0 {
			s += K - m
		}
	}
	return s
}

package main

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

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

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

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

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

	T := 1
	scan(&T)
	for t := 0; t < T; t++ {
		var s string
		var n, k int
		scan(&n, &k, &s)
		solveC(s, k)
	}
}

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

func solveC(s string, k int) {
	cnt := [26]int{}

	var char byte
	prefIdx := -1
	for i := range s {
		if s[i] == 'z' {
			cnt[s[i]-'a']++
			continue
		}

		total := len(s) - 1 - i
		for nextsym := s[i] + 1; nextsym <= 'z'; nextsym++ {
			cnt[nextsym-'a']++

			need := 0
			for c := 'a'; c <= 'z'; c++ {
				need += (k - cnt[c-'a']%k) % k
			}
			if need <= total && (total-need)%k == 0 {
				if prefIdx < i {
					char = nextsym
					prefIdx = i
				}
			}

			cnt[nextsym-'a']--
		}

		cnt[s[i]-'a']++
	}

	ok := true
	for x := 'a'; x <= 'z'; x++ {
		if cnt[x-'a']%k != 0 {
			ok = false
		}
	}

	if ok {
		printf("%v\n", s)
		return
	}

	if prefIdx == -1 {
		printf("-1\n")
		return
	}

	ans := append([]byte{}, s[:prefIdx]...)
	ans = append(ans, char)

	cnt = [26]int{}
	for i := range ans {
		cnt[ans[i]-'a']++
	}

	need := 0
	for x := byte('a'); x <= 'z'; x++ {
		need += (k - cnt[x-'a']%k) % k
		cnt[x-'a'] = (k - cnt[x-'a']%k) % k
	}
	cnt[0] += len(s) - prefIdx - 1 - need

	for x := byte('a'); x <= 'z'; x++ {
		for i := 0; i < cnt[x-'a']; i++ {
			ans = append(ans, x)
		}
	}

	printf("%v\n", string(ans))
}

package main
import . "fmt"
/*
	快速移动当前行 shift + command + ⬆
	删除当前行    command + 删除
	查找+替换	command + R
*/
var (
	T int
	s []byte
	n,k int
)

func main() {
	for Scan(&T); T > 0; T-- {
		so()
	}
}
func so() {
	Scan(&n,&k)
	Scan(&s)
	var cnt [205]int
	for _,i := range s {
		cnt[int(i)]++
	}
	if n%k!=0 {
		Println(-1)
		return
	}
	w := 0
	for j:='a' ;j<='z' ;j++ {
		w+=(k-cnt[int(j)]%k)%k
	}
	if(w==0) {
		Printf("%s\n",s)
		return
	}
	for i:=n-1;i>=0;i-- {
		cnt[int(s[i])]--
		for j:=s[i]+1;j<='z';j++ {
			cnt[j]++
			fw:=0
			for l:='a';l<='z';l++ {
				fw+=(k-cnt[l]%k)%k
			}
			if n-1-i>=fw {
				for l:=0; l<i ;l++ {
					Printf("%c",s[l])
				}
				Printf("%c",j)
				for l:=1; l<=n-1-i-fw; l++ {
					Printf("%c",'a')
				}
				for l:='a'; l<='z'; l++ {
					for p:=1; p<=(k-cnt[l]%k)%k; p++ {
						Printf("%c",l)
					}
				}
				Println()
				return
			}
			cnt[j]--;
		}
	}

}

package main

import (
	"fmt"
)
var n,k int
var s string
const maxn=1e5+5
var pre[maxn][30]int
func idx(ch byte) int {
	return int(ch-'a')
}
func work() {
	fmt.Scanln(&n,&k)
	fmt.Scanln(&s);
	cnt:=[30]int{}
	for _,ch := range s{
		cnt[ch-'a']++
	}
	for i:=0;i<=26;i++{
		if i==26 {
			fmt.Println(s)
			return
		}
		if cnt[i]%k!=0{
			break
		}
	}
	s="#"+s
	if n%k!=0{
		fmt.Println("-1")
		return
	}
	for i:=1;i<=n;i++{
		for j:=0;j<26;j++{
			pre[i][j]=pre[i-1][j]
		}
		pre[i][idx(s[i])]++
	}
	var ans []byte
	for i:=n;i>=1;i--{
		for j:=int(s[i]-'a'+1);j<26;j++{
			sum:=0
			for c:=0;c<26;c++{
				tmp:=pre[i-1][c]
				if j==c {
					tmp++
				}
				sum+=(k-tmp%k)%k
			}
			if(sum<=n-i&&(n-i-sum)%k==0){
				for x:=1;x<i;x++{
					ans = append(ans, s[x])
				}
				ans = append(ans, byte(j+'a'))
				for x:=0;x<n-i-sum;i++{
					ans = append(ans, 'a')
				}
				for x:=0;x<26;x++{
					tmp:=pre[i-1][x]
					if x==j{
						tmp++
					}
					for y:=0;y<(k-tmp%k)%k;y++{
						ans = append(ans, byte(x+'a'))
					}
				}
				fmt.Printf("%s\n",ans)
				return
			}
		}
	}
}
func main() {
	var T int
	fmt.Scanln(&T)
	for cas:=1;cas<=T;cas++{
		work()
	}
	return
}

package main

import (
	"fmt"
)
var n,k int
var s string
const maxn=1e5+5
var pre[maxn][30]int
func idx(ch byte) int {
	return int(ch-'a')
}
func work() {
	fmt.Scanln(&n,&k)
	fmt.Scanln(&s);
	cnt:=[30]int{}
	for _,ch := range s{
		cnt[ch-'a']++
	}
	for i:=0;i<=26;i++{
		if i==26 {
			fmt.Println(s)
			return
		}
		if cnt[i]%k!=0{
			break
		}
	}
	s="#"+s
	if n%k!=0{
		fmt.Println("-1")
		return
	}
	for i:=1;i<=n;i++{
		for j:=0;j<26;j++{
			pre[i][j]=pre[i-1][j]
		}
		pre[i][idx(s[i])]++
	}
	var ans []byte
	for i:=n;i>=1;i--{
		for j:=int(s[i]-'a'+1);j<26;j++{
			sum:=0
			for c:=0;c<26;c++{
				tmp:=pre[i-1][c]
				if j==c {
					tmp++
				}
				sum+=(k-tmp%k)%k
			}
			if(sum<=n-i){
				for x:=1;x<i;x++{
					ans = append(ans, s[x])
				}
				ans = append(ans, byte(j+'a'))
				for x:=0;x<n-i-sum;i++{
					ans = append(ans, 'a')
				}
				for x:=0;x<26;x++{
					tmp:=pre[i-1][x]
					if x==j{
						tmp++
					}
					for y:=0;y<(k-tmp%k)%k;y++{
						ans = append(ans, byte(x+'a'))
					}
				}
				for _, x := range ans {
					fmt.Printf("%c",x)
				}
				fmt.Println("")
				return
			}
		}
	}
}
func main() {
	var T int
	fmt.Scanln(&T)
	for cas:=1;cas<=T;cas++{
		work()
	}
	return
}


Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties:  In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to zero.  When all elements of the array become equal to zero, the array explodes. Nastya is always busy, so she wants to explode the array as fast as possible. Compute the minimum time in which the array can be exploded.

The first line contains a single integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains n integers a1, a2, ..., an ( - 105 ≤ ai ≤ 105) — the elements of the array.

Print a single integer — the minimum number of seconds needed to make all elements of the array equal to zero.

NoteIn the first example you can add  - 1 to all non-zero elements in one second and make them equal to zero.In the second example you can add  - 2 on the first second, then the array becomes equal to [0, 0,  - 3]. On the second second you can add 3 to the third (the only non-zero) element.

//Nishant Arora

package main

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

func main() {

	// fmt.Println("Hello")
 	in := bufio.NewReader(os.Stdin)
  	var n int
  	// fmt.Fscanf(in, "%d\n", &n)
	// var n int
	var x int
    m := make(map[int]int)
	ans := 0
  	fmt.Fscanf(in, "%d\n", &n)
    // fmt.Println(n)
	for i := 0; i < n ; i++ {
  		fmt.Fscanf(in, "%d", &x)
    // 	fmt.Println(x)
		if(x!=0) {
			m[x] = m[x] + 1
			if(m[x]==1) {
				ans++
			}
		}
	}

	fmt.Println(ans)

}

package main

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

var (
	bufin  = bufio.NewReader(os.Stdin)
	bufout = bufio.NewWriter(os.Stdout)
)

func main() {
	N := 0
	fmt.Fscan(bufin, &N)

	v := make(map[int]bool)
	for i := 0; i < N; i++ {
		x := 0
		fmt.Fscan(bufin, &x)
		v[x] = true
	}

	cnt := 0
	for i := range v {
		if i != 0 {
			cnt++
		}
	}

	fmt.Fprintln(bufout, cnt)
	bufout.Flush()
}

package main

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

var (
	bufin  = bufio.NewReader(os.Stdin)
	bufout = bufio.NewWriter(os.Stdout)
)

func main() {
	n := 0
	x := 0
	a := make(map[int]bool)
	fmt.Fscan(bufin, &n)
	for i := 0; i < n; i++ {
		fmt.Fscan(bufin, &x)
		a[x] = true

	}
	ans := 0
	for i := range a {
		if i != 0 {
			ans++
		}
	}
	fmt.Fprintln(bufout, ans)
	bufout.Flush()
}

package main

import (
  "fmt"
  "bufio"
  "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...) }
var n int
var x [200005]bool

func main() {
  defer writer.Flush()
  scanf("%d\n", &n)
  ans := 0
  for i := 0; i < n; i++ {
    var a int
    scanf("%d", &a)
    if a != 0 && !x[a + 100000] {
      ans++
      x[a + 100000] = true
    }
  }
  printf("%d\n", ans)
}

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()
	a := make([]int, n)
	for i := range a {
		a[i] = readi()
	}
	m := make(map[int]bool)
	for _, v := range a {
		if v == 0 {
			continue
		}
		m[v] = true
	}
	println(len(m))
}

package main

import (
	"fmt"
	"os"
	"bufio"

)
var (
    bufin = bufio.NewReader(os.Stdin)
    bufout = bufio.NewWriter(os.Stdout)
)

func main() {
	var n,i int64=0,0
	fmt.Fscan(bufin,&n)
	arr:=make([]int64,n)
	store:=make(map[int64]int64)
	for i=0;i<n;i++{
		fmt.Fscan(bufin,&arr[i])
		store[arr[i]]++
	}

	ans:=len(store)
	if store[0]!=0 {
	    ans--;
	}
	fmt.Fprint(bufout,ans)
	bufout.Flush()

}

package main

import (
	"bufio"
	"os"
	"fmt"
	"sort"
	"math"
)
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...) }
func readLine()(string,error) 			{ return reader.ReadString('\n') }

func main() {
	defer writer.Flush()
	var n int
	scanf("%d\n",&n);
	var nums = make([]int,n)
	for i :=0; i < n; i++ {
		scanf("%d" , &nums[i])
	}
	sort.Ints(nums)
	count := 0
	prev := math.MinInt32
	for _,i := range nums {
		if (prev != i && i != 0){
			count++;
			prev = i;
		}
	}
	fmt.Println(count)
}

package main

import "fmt"

func main() {
	n := 0
	x := 0
	a := make(map[int]int)
	fmt.Scanf("%d", &n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &x)
		a[x]++
		if n == 3 {
			fmt.Printf("%d\n", x)
		}
	}
	fmt.Printf("%d\n", len(a) - a[0])
}

package main

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

var (
	bufin  = bufio.NewReader(os.Stdin)
)

func main() {
	n := 0
	x := 0
	a := make(map[int]int)
	fmt.Fscan(bufin, &n)
	for i := 0; i < n; i++ {
		fmt.Fscan(bufin, &x)
		a[x]++

	}
	scad := a[0]
	print(len(a) - scad)
}

package main

import "fmt"

func main() {
	n := 0
	x := 0
	a := make(map[int]int)
	fmt.Scanf("%d", &n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &x)
		a[x]++
	}
	fmt.Printf("%d\n", len(a) - a[0])

}

package main

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

var (
	bufin  = bufio.NewReader(os.Stdin)
)

func main() {
	n := 0
	x := 0
	a := make(map[string]int)
	fmt.Fscan(bufin, &n)
	for i := 0; i < n; i++ {
		fmt.Fscan(bufin, &x)
		a[string(x)]++

	}
	scad := a[string(0)]
	fmt.Printf("%d\n", len(a) - scad)
}

package main

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

var (
	bufin  = bufio.NewReader(os.Stdin)
	bufout = bufio.NewWriter(os.Stdout)
)

func main() {
	n := 0
	x := 0
	a := make(map[int]int)
	fmt.Fscan(bufin, &n)
	for i := 0; i < n; i++ {
		fmt.Fscan(bufin, &x)
		a[x]++

	}
	scad := a[0]
	fmt.Fprint(bufout, len(a) - scad)
}

package main

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

var (
	bufin  = bufio.NewReader(os.Stdin)
)

func main() {
	n := 0
	x := 0
	a := make(map[int]int)
	fmt.Fscan(bufin, &n)
	for i := 0; i < n; i++ {
		fmt.Fscan(bufin, &x)
		a[x]++

	}
	scad := a[0]
	fmt.Printf("%d\n", len(a) - scad)
}

//Nishant Arora

package main

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

func main() {

	// fmt.Println("Hello")
 	in := bufio.NewReader(os.Stdin)
  	var n int
  	// fmt.Fscanf(in, "%d\n", &n)
	// var n int
	var x int
    m := make(map[int]int)
	ans := 0
  	fmt.Fscanf(in, "%d\n", &n)
    fmt.Println(n)
	for i := 0; i < n ; i++ {
  		fmt.Fscanf(in, "%d", &x)
	fmt.Println(x)
		if(x!=0) {
			m[x] = m[x] + 1
			if(m[x]==1) {
				ans++
			}
		}
	}

	fmt.Println(ans)

}

package main

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

func main() {

	// fmt.Println("Hello")
 	in := bufio.NewReader(os.Stdin)
  	var n int
  	// fmt.Fscanf(in, "%d\n", &n)
	// var n int
	var x int
    m := make(map[int]int)
	ans := 0
  	fmt.Fscanf(in, "%d\n", &n)
    // fmt.Println(n)
	for i := 0; i < n ; i++ {
  		fmt.Fscanf(in, "%d\n", &x)
	// fmt.Println(x)
		if(x!=0) {
			m[x] = m[x] + 1
			if(m[x]==1) {
				ans++
			}
		}
	}

	fmt.Println(ans)

}


You are given an undirected connected graph consisting of n vertices and m edges. There are no loops and no multiple edges in the graph.You are also given two distinct vertices s and t, and two values ds and dt. Your task is to build any spanning tree of the given graph (note that the graph is not weighted), such that the degree of the vertex s doesn't exceed ds, and the degree of the vertex t doesn't exceed dt, or determine, that there is no such spanning tree.The spanning tree of the graph G is a subgraph which is a tree and contains all vertices of the graph G. In other words, it is a connected graph which contains n - 1 edges and can be obtained by removing some of the edges from G.The degree of a vertex is the number of edges incident to this vertex.

The first line of the input contains two integers n and m (2 ≤ n ≤ 200 000, 1 ≤ m ≤ min(400 000, n·(n - 1) / 2)) — the number of vertices and the number of edges in the graph.  The next m lines contain the descriptions of the graph's edges. Each of the lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the ends of the corresponding edge. It is guaranteed that the graph contains no loops and no multiple edges and that it is connected. The last line contains four integers s, t, ds, dt (1 ≤ s, t ≤ n, s ≠ t, 1 ≤ ds, dt ≤ n - 1).

If the answer doesn't exist print "No" (without quotes) in the only line of the output.  Otherwise, in the first line print "Yes" (without quotes). In the each of the next (n - 1) lines print two integers — the description of the edges of the spanning tree. Each of the edges of the spanning tree must be printed exactly once. You can output edges in any order. You can output the ends of each edge in any order. If there are several solutions, print any of them.

package main

import "fmt"
import "bufio"
import "os"

var bufin *bufio.Reader
var bufout *bufio.Writer

var n, m, s, t, ds, dt, nc int
var adj [][]int
var comp, ru, rv []int

func dfs(u int) {
	for _, v := range adj[u] {
		if (v != s) && (v != t) && (comp[v] == -1) {
			ru = append(ru, u)
			rv = append(rv, v)
			comp[v] = nc
			dfs(v)
		}
	}
}

func yes() bool {
	comp = make([]int, n+1)
	for u := 1; u <= n; u++ {
		comp[u] = -1
	}

	nc = 0
	for u := 1; u <= n; u++ {
		if (u != s) && (u != t) && (comp[u] == -1) {
			comp[u] = nc
			dfs(u)
			nc++
		}
	}

	cs := make([]int, nc)
	ct := make([]int, nc)
	for c := 0; c < nc; c++ {
		cs[c] = -1
		ct[c] = -1
	}

	stEdge := false
	for _, u := range adj[s] {
		if u == t {
			stEdge = true
		}
		if comp[u] != -1 {
			cs[comp[u]] = u
		}
	}

	for _, u := range adj[t] {
		if comp[u] != -1 {
			ct[comp[u]] = u
		}
	}

	degS := 0
	degT := 0
	stConnected := false

	for c := 0; c < nc; c++ {
		if cs[c] == -1 {
			degT++
			ru = append(ru, t)
			rv = append(rv, ct[c])
		} else if ct[c] == -1 {
			degS++
			ru = append(ru, s)
			rv = append(rv, cs[c])
		} else {
			if !stConnected {
				degS++
				ru = append(ru, s)
				rv = append(rv, cs[c])
				degT++
				ru = append(ru, t)
				rv = append(rv, ct[c])
				stConnected = true
				cs[c] = -1
				ct[c] = -1
			}
		}
	}

	if stEdge && !stConnected {
		degS++
		degT++
		ru = append(ru, s)
		rv = append(rv, t)
		stConnected = true
	}

	for c := 0; c < nc; c++ {
		if (cs[c] != -1) && (ct[c] != -1) {
			if degS < ds {
				degS++
				ru = append(ru, s)
				rv = append(rv, cs[c])
			} else if degT < dt {
				degT++
				ru = append(ru, t)
				rv = append(rv, ct[c])
			} else {
				return false
			}
		}
	}

	return degS <= ds && degT <= dt && stConnected
}

func main() {
	bufin = bufio.NewReader(os.Stdin)
	bufout = bufio.NewWriter(os.Stdout)
	defer bufout.Flush()

	fmt.Fscanf(bufin, "%d %d\n", &n, &m)

	var u, v int

	adj = make([][]int, n+1)
	for u = 1; u <= n; u++ {
		adj[u] = make([]int, 0)
	}

	for i := 0; i < m; i++ {
		fmt.Fscanf(bufin, "%d %d\n", &u, &v)
		adj[u] = append(adj[u], v)
		adj[v] = append(adj[v], u)
	}

	fmt.Fscanf(bufin, "%d %d %d %d\n", &s, &t, &ds, &dt)

	if yes() {
		fmt.Fprintf(bufout, "Yes\n")
		for i := 0; i < len(ru); i++ {
			fmt.Fprintf(bufout, "%d %d\n", ru[i], rv[i])
		}
	} else {
		fmt.Fprintf(bufout, "No\n")
	}
}


In some country there are exactly n cities and m bidirectional roads connecting the cities. Cities are numbered with integers from 1 to n. If cities a and b are connected by a road, then in an hour you can go along this road either from city a to city b, or from city b to city a. The road network is such that from any city you can get to any other one by moving along the roads.You want to destroy the largest possible number of roads in the country so that the remaining roads would allow you to get from city s1 to city t1 in at most l1 hours and get from city s2 to city t2 in at most l2 hours.Determine what maximum number of roads you need to destroy in order to meet the condition of your plan. If it is impossible to reach the desired result, print -1.

The first line contains two integers n, m (1 ≤ n ≤ 3000, ) — the number of cities and roads in the country, respectively.  Next m lines contain the descriptions of the roads as pairs of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi). It is guaranteed that the roads that are given in the description can transport you from any city to any other one. It is guaranteed that each pair of cities has at most one road between them. The last two lines contains three integers each, s1, t1, l1 and s2, t2, l2, respectively (1 ≤ si, ti ≤ n, 0 ≤ li ≤ n).

Print a single number — the answer to the problem. If the it is impossible to meet the conditions, print -1.

package main

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

// github.com/EndlessCheng/codeforces-go
func CF543B(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	var n, m, v, w, s1, t1, l1, s2, t2, l2 int
	Fscan(in, &n, &m)
	g := make([][]int, n+1)
	for i := 0; i < m; i++ {
		Fscan(in, &v, &w)
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}
	d := make([][]int, n+1)
	for i := 1; i <= n; i++ {
		d[i] = make([]int, n+1)
		for j := range d[i] {
			d[i][j] = -1
		}
		d[i][i] = 0
		q := []int{i}
		for len(q) > 0 {
			v, q = q[0], q[1:]
			for _, w := range g[v] {
				if d[i][w] < 0 {
					d[i][w] = d[i][v] + 1
					q = append(q, w)
				}
			}
		}
	}

	Fscan(in, &s1, &t1, &l1, &s2, &t2, &l2)
	if d[s1][t1] > l1 || d[s2][t2] > l2 {
		Fprint(out, -1)
		return
	}
	ans := m - d[s1][t1] - d[s2][t2]
	for i := 1; i <= n; i++ {
		for j := 1; j <= n; j++ {
			if d[i][s1]+d[i][j]+d[j][t1] <= l1 && d[i][s2]+d[i][j]+d[j][t2] <= l2 {
				if v := m - d[i][j] - d[i][s1] - d[i][s2] - d[j][t1] - d[j][t2]; v > ans {
					ans = v
				}
			}
			if d[i][s1]+d[i][j]+d[j][t1] <= l1 && d[i][t2]+d[i][j]+d[j][s2] <= l2 {
				if v := m - d[i][j] - d[i][s1] - d[i][t2] - d[j][t1] - d[j][s2]; v > ans {
					ans = v
				}
			}
		}
	}
	Fprint(out, ans)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF543B(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	var n, m, v, w, s1, t1, l1, s2, t2, l2 int
	Fscan(in, &n, &m)
	g := make([][]int, n+1)
	for i := 0; i < m; i++ {
		Fscan(in, &v, &w)
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}
	d := make([][]int, n+1)
	for i := 1; i <= n; i++ {
		d[i] = make([]int, n+1)
		for j := range d[i] {
			d[i][j] = -1
		}
		d[i][i] = 0
		q := []int{i}
		for len(q) > 0 {
			v, q = q[0], q[1:]
			for _, w := range g[v] {
				if d[i][w] < 0 {
					d[i][w] = d[i][v] + 1
					q = append(q, w)
				}
			}
		}
	}

	Fscan(in, &s1, &t1, &l1, &s2, &t2, &l2)
	if d[s1][t1] > l1 || d[s2][t2] > l2 {
		Fprint(out, -1)
		return
	}
	ans := m - d[s1][t1] - d[s2][t2]
	for i := 1; i <= n; i++ {
		for j := 1; j <= n; j++ {
			if d[i][s1]+d[i][j]+d[j][t1] <= l1 && d[i][s2]+d[i][j]+d[j][t2] <= l2 {
				if v := m - d[i][j] - d[i][s1] - d[i][s2] - d[j][t1] - d[j][t2]; v > ans {
					ans = v
				}
			}
		}
	}
	Fprint(out, ans)
}

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


Phoenix has $$$n$$$ blocks of height $$$h_1, h_2, \dots, h_n$$$, and all $$$h_i$$$ don't exceed some value $$$x$$$. He plans to stack all $$$n$$$ blocks into $$$m$$$ separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than $$$x$$$. Please help Phoenix build $$$m$$$ towers that look beautiful. Each tower must have at least one block and all blocks must be used.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$x$$$ ($$$1 \le m \le n \le 10^5$$$; $$$1 \le x \le 10^4$$$) — the number of blocks, the number of towers to build, and the maximum acceptable height difference of any two towers, respectively.  The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le h_i \le x$$$) — the heights of the blocks.  It is guaranteed that the sum of $$$n$$$ over all the test cases will not exceed $$$10^5$$$.

For each test case, if Phoenix cannot build $$$m$$$ towers that look beautiful, print NO. Otherwise, print YES, followed by $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$, where $$$y_i$$$ ($$$1 \le y_i \le m$$$) is the index of the tower that the $$$i$$$-th block is placed in. If there are multiple solutions, print any of them.

NoteIn the first test case, the first tower has height $$$1+2+3=6$$$ and the second tower has height $$$1+2=3$$$. Their difference is $$$6-3=3$$$ which doesn't exceed $$$x=3$$$, so the towers are beautiful.In the second test case, the first tower has height $$$1$$$, the second tower has height $$$1+2=3$$$, and the third tower has height $$$3$$$. The maximum height difference of any two towers is $$$3-1=2$$$ which doesn't exceed $$$x=3$$$, so the towers are beautiful.

package main

import (
	"container/heap"
	"fmt"
)

type Pair struct {
	h, i int
}

type PairHeap []Pair

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

func main() {
	var t int
	fmt.Scan(&t)
	for t > 0 {
		var n, m, x int
		fmt.Scan(&n, &m, &x)

		fmt.Println("YES")
		h := make(PairHeap, m)

		for i := range h {
			h[i] = Pair{0, i}
		}
		heap.Init(&h)

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

			p := heap.Pop(&h).(Pair)
			heap.Push(&h, Pair{p.h + block, p.i})
			fmt.Printf("%d ", p.i+1)
		}

		fmt.Println()
		t--
	}
}

package main

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

type elem struct {
	val int
	idx int
}

func main_gr_14_C() {
	_in, _out := os.Stdin, os.Stdout
	in, out := bufio.NewReader(_in), bufio.NewWriter(_out)
	defer out.Flush()
	var cas int = 1
	Fscan(in, &cas)
	var sol func()
	sol = func() {
		var n, m, x int
		Fscan(in, &n, &m, &x)
		arr, ans := make([]elem, n), make([]int, n)
		for i := 0; i < n; i++ {
			var temp int
			Fscan(in, &temp)
			arr[i] = elem{temp, i}
		}
		sort.Slice(arr, func(i, j int) bool {
			return arr[i].val < arr[j].val
		})
		for i := 0; i < n; i++ {
			ans[arr[i].idx] = i % m
		}
		Fprintln(out, "YES")
		for _, v := range ans {
			Fprint(out, v+1, " ")
		}
		Fprintln(out)
	}
	for i := 0; i < cas; i++ {
		sol()
	}
}

func main() {
	main_gr_14_C()
}

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++ {
		// Get n, m, x
		input, _ = reader.ReadString('\n')
		var n, m int
		n, input = GetInt(input)
		m, _ = GetInt(input)
		// x, _ = GetInt(input)

		// Get heights
		heights := [][]int{}
		input, _ = reader.ReadString('\n')
		for i:=0; i<n; i++ {
			var val int
			val, input = GetInt(input)
			heights = append(heights, []int{val, i})
		}

		sort.Slice(heights, func(l, r int) bool {
			return heights[l][0] < heights[r][0]
		})

		towers := make([][2]int64, m)
		for i:=0; i<m; i++ {
			towers[i][1] = int64(i+1)
		}

		curr, result, remainder := 0, make([]int, n), n%m
		for i:=0; i<n-remainder; i++ {
			val := heights[i]
			result[val[1]] = int(towers[curr][1])
			towers[curr][0] += int64(val[0])
			curr++
			if curr == m {
				curr = 0
				sort.Slice(towers, func(l, r int) bool {
					return towers[l][0] > towers[r][0]
				})
			}
		}

		curr = m-1
		for i:=n-remainder; i<n; i++ {
			val := heights[i]
			result[val[1]] = int(towers[curr][1])
			towers[curr][0] += int64(val[0])
			curr--
		}

		sort.Slice(towers, func(l, r int) bool {
			return towers[l][0] > towers[r][0]
		})

		fmt.Println("YES")
		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 (
    "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++ {
		// Get n, m, x
		input, _ = reader.ReadString('\n')
		var n, m, x int
		n, input = GetInt(input)
		m, input = GetInt(input)
		x, _ = GetInt(input)

		// Get heights
		heights := [][]int{}
		input, _ = reader.ReadString('\n')
		for i:=0; i<n; i++ {
			var val int
			val, input = GetInt(input)
			heights = append(heights, []int{val, i})
		}

		sort.Slice(heights, func(l, r int) bool {
			return heights[l][0] < heights[r][0]
		})

		towers := make([][2]int64, m)
		for i:=0; i<m; i++ {
			towers[i][1] = int64(i+1)
		}

		curr, result, remainder := 0, make([]int, n), n%m
		for i:=0; i<n-remainder; i++ {
			val := heights[i]
			result[val[1]] = int(towers[curr][1])
			towers[curr][0] += int64(val[0])
			curr++
			if curr == m {
				curr = 0
				sort.Slice(towers, func(l, r int) bool {
					return towers[l][0] > towers[r][0]
				})
			}
		}

		curr = m-1
		for i:=n-remainder; i<n; i++ {
			val := heights[i]
			result[val[1]] = int(towers[curr][1])
			towers[curr][0] += int64(val[0])
			curr--
		}

		sort.Slice(towers, func(l, r int) bool {
			return towers[l][0] > towers[r][0]
		})

		if towers[0][0] - towers[len(towers)-1][0] > int64(x) {
			fmt.Println("NO")
			continue
		}

		fmt.Println("YES")
		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"
	"io"
	"math"
	"os"
	"sort"
)

type pair struct {
	i, v int
}

type Node struct {
	p   []int
	sum int // cost; using this value to heapify
}

type heap []Node

func (h *heap) init(n int) {
	*h = make(heap, 1, n+1)
}
func (h *heap) push(n Node) {
	*h = append(*h, n)
	h.up(len(*h) - 1)
}
func (h *heap) pop() Node {
	t := (*h)[1]
	(*h)[1] = (*h)[len(*h)-1]
	(*h) = (*h)[:len(*h)-1]
	h.down(1)
	return t
}
func (h heap) isEmpty() bool {
	return h == nil || len(h) == 1
}
func (h heap) less(a, b int) bool {
	return h[a].sum < h[b].sum // '>' means maximum heap
}

func (h *heap) swap(a, b int) {
	(*h)[a], (*h)[b] = (*h)[b], (*h)[a]
}

func (h *heap) up(k int) {
	for ; k > 1 && h.less(k, k/2); k /= 2 {
		h.swap(k, k/2)
	}
}

func (h *heap) down(k int) {
	for k*2 < len(*h) {
		j := 2 * k
		if j < len(*h)-1 && h.less(j+1, j) {
			j++
		}
		if h.less(k, j) {
			break
		}
		h.swap(k, j)
		k = j
	}
}

func solve(arr []pair, m int, x int) []int {
	sort.Slice(arr, func(i, j int) bool {
		return arr[i].v > arr[j].v
	})
	// fmt.Println(arr)
	h := &heap{}
	h.init(m)
	for i := 0; i < m; i++ {
		h.push(Node{p: []int{}, sum: 0})
	}
	for _, v := range arr {
		node := h.pop()
		node.sum += v.v
		node.p = append(node.p, v.i)
		h.push(node)
	}
	res := make([]int, len(arr))
	maxSum, minSum := math.MinInt32, math.MaxInt32
	cnt := 1
	for !h.isEmpty() {
		node := h.pop()
		if maxSum < node.sum {
			maxSum = node.sum
		}
		if minSum > node.sum {
			minSum = node.sum
		}
		for _, v := range node.p {
			res[v] = cnt
		}
		cnt++
	}
	if maxSum-minSum > x {
		return []int{}
	}
	return res
}
func min(a, b int) int {
	if a > b {
		return b
	}
	return a
}
func max(a, b int) int {
	if a < b {
		return b
	}
	return a
}

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

	var t int
	var n, m, x int
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n, &m, &x)
		arr := make([]pair, n)
		for i := 0; i < n; i++ {
			Fscan(in, &arr[i].v)
			arr[i].i = i
		}
		ans := solve(arr, m, x)
		if len(ans) == 0 {
			Fprintln(out, "NO")
		} else {
			Fprintln(out, "YES")
			for _, v := range ans {
				Fprintf(out, "%d ", v)
			}
			Fprintln(out)
		}
	}
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1515C(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	var T, n, m, x int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &m, &x)
		a := make([]struct{ v, i int }, n)
		for i := range a {
			Fscan(in, &a[i].v)
			a[i].i = i
		}
		sort.Slice(a, func(i, j int) bool { return a[i].v < a[j].v })
		ans := make([]interface{}, n)
		for i, p := range a {
			ans[p.i] = i%m + 1
		}
		Fprintln(out, "YES")
		Fprintln(out, ans...)
	}
}

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

package main

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

type treeNode struct {
	index int
	value int
}

var T[4 * 100001] treeNode

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

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

func getMinNode(a treeNode, b treeNode) treeNode {
	var ret = treeNode{a.index, a.value}
	if ret.value > b.value {
		ret.index = b.index
		ret.value = b.value
	}
	return ret
}

func buildTree(node int, l int, r int)  {
	if l == r {
		T[node] = treeNode{l, 0}
		return
	}
	var mid = (l + r) >> 1
	buildTree(node * 2, l, mid)
	buildTree(node * 2 + 1, mid + 1, r)
	T[node] = getMinNode(T[node * 2], T[node * 2 + 1])
}

func addValue(node int, l int, r int, pos int, value int)  {
	if l > pos || r < pos {
		return
	}
	if l == r {
		if l != pos {
			return
		}
		T[node].value += value
		return
	}

	var mid = (l + r) >> 1
	addValue(node * 2, l, mid, pos, value)
	addValue(node * 2 + 1, mid + 1, r, pos, value)
	T[node] = getMinNode(T[node * 2], T[node * 2 + 1])
}

func main()  {
	var reader = bufio.NewReader(os.Stdin)
	var writer = bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var nt int
	fmt.Fscanf(reader, "%d\n", &nt)
	for kk := 0; kk < nt; kk++ {
		var n, m, x int
		fmt.Fscanf(reader, "%d%d%d\n", &n, &m, &x)

		var a = make([]treeNode, n)
		var res = make([]int, n)
		var agg = make([]int, m)

		for i := 0; i < n; i++ {
			var x int
			fmt.Fscanf(reader, "%d", &x)
			a[i] = treeNode{i, x}
		}

		fmt.Fscanf(reader, "\n")

		sort.Slice(a, func(i, j int) bool {
			return a[i].value > a[j].value
		})

		buildTree(1, 1, m)

		for _, record := range a {
			res[record.index] = T[1].index
			agg[T[1].index - 1] += record.value
			addValue(1, 1, m, T[1].index, record.value)
 		}

		var minValue = agg[0]
		var maxValue = agg[0]

		for i := 1; i < m; i++ {
			minValue = min(minValue, agg[i])
			maxValue = max(maxValue, agg[i])
		}

		//fmt.Println(agg)

		if maxValue - minValue > x {
			fmt.Fprintf(writer, "NO\n")
		} else {
			fmt.Fprintf(writer, "YES\n")
			for _, x := range res {
				fmt.Fprintf(writer, "%d ", x)
			}
			fmt.Fprintf(writer, "\n")
		}

	}

}

package main

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

func main() {
	var tcs int
	in := bufio.NewReader(os.Stdin)
	_, _ = fmt.Fscan(in, &tcs)

	for tc := 0; tc < tcs; tc++ {
		var n, m, x int
		_, _ = fmt.Fscan(in, &n, &m, &x)

		h := make([]int, n)
		for i := 0; i < n; i++ {
			_, _ = fmt.Fscan(in, &h[i])
		}

		towers := make([]int, n)
		pq := make(PriorityQueue, m)

		for i := 0; i < m; i++ {
			towers[i] = i

			pq[i] = &Item{
				value:    i,
				priority: h[i],
				index:    i,
			}
		}

		heap.Init(&pq)

		for i := m; i < n; i++ {
			temp := pq[0]
			towers[i] = temp.value

			pq.update(temp, temp.value, temp.priority+h[i])
		}

		fmt.Println("YES")
		for _, t := range towers {
			fmt.Printf("%d ", t+1)
		}
		fmt.Println()
	}
}

// An Item is something we manage in a priority queue.
type Item struct {
	value    int // The value of the item; arbitrary.
	priority 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.
}

// 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.
	return pq[i].priority < pq[j].priority
}

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]
	old[n-1] = nil  // avoid memory leak
	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, value int, priority int) {
	item.value = value
	item.priority = priority
	heap.Fix(pq, item.index)
}

package main

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

func main_gr_14_C() {
	_in, _out := os.Stdin, os.Stdout
	in, out := bufio.NewReader(_in), bufio.NewWriter(_out)
	defer out.Flush()
	var cas int = 1
	Fscan(in, &cas)
	var sol func()
	sol = func() {
		var n, m, x int
		Fscan(in, &n, &m, &x)
		arr, sum, ans := make([]int, n), make([]int, m), make([]int, n)
		for i := 0; i < n; i++ {
			Fscan(in, &arr[i])
		}
		sort.Ints(arr)
		var p int
		for i := 0; i < n; i++ {
			ans[i] = p % m
			sum[p%m] += arr[i]
			p++
		}
		min, max := int(1e9), 0
		for i := 0; i < m; i++ {
			if sum[i] > max {
				max = sum[p%m]
			}
			if sum[i] < min {
				min = sum[p%m]
			}
		}
		// Fprintln(out, ans)
		// Fprintln(out, max, min)
		if max-min > x {
			Fprintln(out, "NO")
			return
		}
		Fprintln(out, "YES")
		for _, v := range ans {
			Fprint(out, v+1, " ")
		}
		Fprintln(out)
	}
	for i := 0; i < cas; i++ {
		sol()
	}
}

func main() {
	main_gr_14_C()
}