Many years ago Berland was a small country where only $$$n$$$ people lived. Each person had some savings: the $$$i$$$-th one had $$$a_i$$$ burles.The government considered a person as wealthy if he had at least $$$x$$$ burles. To increase the number of wealthy people Berland decided to carry out several reforms. Each reform looked like that:   the government chooses some subset of people (maybe all of them);  the government takes all savings from the chosen people and redistributes the savings among the chosen people equally. For example, consider the savings as list $$$[5, 1, 2, 1]$$$: if the government chose the $$$1$$$-st and the $$$3$$$-rd persons then it, at first, will take all $$$5 + 2 = 7$$$ burles and after that will return $$$3.5$$$ burles to the chosen people. As a result, the savings will become $$$[3.5, 1, 3.5, 1]$$$.A lot of data was lost from that time, so we don't know how many reforms were implemented and to whom. All we can do is ask you to calculate the maximum possible number of wealthy people after several (maybe zero) reforms.

The first line contains single integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of test cases. Next $$$2T$$$ lines contain the test cases — two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le x \le 10^9$$$) — the number of people and the minimum amount of money to be considered as wealthy. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial savings of each person. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.

Print $$$T$$$ integers — one per test case. For each test case print the maximum possible number of wealthy people after several (maybe zero) reforms.

NoteThe first test case is described in the statement.In the second test case, the government, for example, could carry out two reforms: $$$[\underline{11}, \underline{9}, 11, 9] \rightarrow [10, 10, \underline{11}, \underline{9}] \rightarrow [10, 10, 10, 10]$$$.In the third test case, the government couldn't make even one person wealthy.In the fourth test case, the government could choose all people to carry out a reform: $$$[\underline{9}, \underline{4}, \underline{9}] \rightarrow [7\frac{1}{3}, 7\frac{1}{3}, 7\frac{1}{3}]$$$.

package main

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

var reader = bufio.NewReader(os.Stdin)
var 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 scanIntArr() ([]int, error) {
	str, err := reader.ReadString('\n')
	if err != nil {
		return nil, err
	}
	str = strings.TrimRight(str, "\n\r")
	strArr := strings.Split(str, " ")

	arr := make([]int, len(strArr))
	for i, strA := range strArr {
		arr[i], err = strconv.Atoi(strA)
		if err != nil {
			return nil, err
		}
	}

	return arr, nil
}

func main() {
	defer writer.Flush()

	var t int
	scanf("%d\n", &t)

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

func exec() {
	var n, x int
	scanf("%d %d\n", &n, &x)

	arrA, err := scanIntArr()
	if err != nil {
		fmt.Println(err.Error())
		panic(err)
	}

	richArr := make([]int, 0, len(arrA))
	richSum := uint64(0)
	richNum := uint64(0)
	poorArr := make([]int, 0, len(arrA))
	for _, a := range arrA {
		if a < x {
			poorArr = append(poorArr, a)
			continue
		}
		richSum += uint64(a)
		richNum++
		richArr = append(richArr, a)
	}

	if richNum == 0 {
		printf("0\n")
		return
	}

	sort.Ints(poorArr)
	for i := len(poorArr) - 1; i >= 0; i-- {
		if (uint64(poorArr[i])+richSum)/(richNum+1) >= uint64(x) {
			richSum += uint64(poorArr[i])
			richNum++
			continue
		}
		break
	}
	printf("%d\n", richNum)
}

package main

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

)
func max(a,b int) int{
	if(a>b){
		return a
	}
	return b;
}
func main(){
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var T int;
	fmt.Fscanln(reader, &T)
	for t:=0;t<T;t++ {
		var n int;
		var x int64;
		fmt.Fscanln(reader,&n,&x)
		nums:=make([]int,n)
		var sum int64;
		sum=0
		// count:=0
		for i:=0;i<n;i++{
			if i == n-1 {
				fmt.Fscanf(reader, "%d\n", &nums[i])

			} else {
				fmt.Fscanf(reader, "%d", &nums[i])
			}

		}
		// sum = sum - (count*x)
		sort.Ints(nums);
		// fmt.Println(sum,nums,count)
		// for i:=len(nums)-1-count;i>=0;i--{
		// 	diff:= x-nums[i];
		// 	if(sum-diff>=0){
		// 	sum-=diff;

		// 	count++
		// }
		// }
		prefix:=n;
		for prefix>0 && sum+int64(nums[prefix-1])-x >=0 {
				prefix--
				sum= sum+int64(nums[prefix])-x
		}

		// for i:=len(nums)-count-1;i>=0;i--{
		// 	fmt.Println(nums[i],"here")
		// 	if( sum+nums[i]>=(count+1)*x ){
		// 		count++
		// 		sum+=nums[i]
		// 	}else{
		// 		break;
		// 	}
		// }

		fmt.Fprintln(writer,n-prefix);
	}
}

package main

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

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

	var t, n, x int
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n, &x)
		a := make([]int, n)
		for i := range a {
			Fscan(in, &a[i])
		}
		sort.Ints(a)
		sum := int64(0)
		cnt := int64(0)
		ans := 0
		for i := n - 1; i >= 0; i-- {
			if v := a[i]; v > x {
				sum += int64(v)
				cnt++
				ans = n - i
			} else if v == x {
				ans = n - i
			} else {
				sum += int64(v)
				cnt++
				if int64(x)*cnt <= sum {
					ans = n - i
				} else {
					break
				}
			}
		}
		Fprintln(out, ans)
	}
}

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

package main

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

func main() {
	for t := ScanInt(); t > 0; t-- {
		n, x := ScanInt(), ScanInt()
		a := ScanIntSlice(n)
		P(solve(n, x, a))
	}

	close(O)
	oWg.Wait()
}

func solve(n, x int, a []int) int {
	sort.Ints(a)

	l, r, c := -1, -1, 0

	for i := 0; i < n; i++ {
		if a[i] < x {
			l = i
		}
		if a[i] >= x {
			r = i
		}
	}
	if r == -1 {
		return 0
	}
	if l == -1 {
		return n
	}

	result := l
	for i := l; i >= 0; i-- {
		for c < (x-a[i]) && r > l {
			c += (a[r] - x)
			r--
		}
		if a[i]+c >= x {
			c -= (x - a[i])
			a[i] = x
			result--
		}
	}
	return n - result - 1
}

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

var O chan string
var in *bufio.Scanner
var oWg *sync.WaitGroup
var P func(a ...interface{}) (n int, err error)

func init() {
	P = fmt.Println

	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(1e+9))
	in.Split(bufio.ScanWords)

	O = make(chan string, 16)
	oWg = &sync.WaitGroup{}
	oWg.Add(1)

	writer := bufio.NewWriter(os.Stdout)
	go func() {
		defer oWg.Done()
		defer writer.Flush()

		for line := range O {
			writer.WriteString(line + "\n")
		}
	}()
}

func ScanWord() string { in.Scan(); return in.Text() }
func ScanInt() int     { i, _ := strconv.Atoi(ScanWord()); return i }
func ScanInt64() int64 { i, _ := strconv.ParseInt(ScanWord(), 10, 64); return i }
func ScanStringSlice(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ScanWord()
	}
	return s
}
func ScanIntSlice(n int) []int {
	arr := make([]int, n)
	for i := 0; i < n; i++ {
		arr[i] = ScanInt()
	}
	return arr
}
func ScanInt64Slice(n int) []int64 {
	arr := make([]int64, n)
	for i := 0; i < n; i++ {
		arr[i] = ScanInt64()
	}
	return arr
}

/*********************** Utils ***********************/

func S(v interface{}) string { return fmt.Sprintf("%v", v) }
func SArr(a []int) string {
	sb := strings.Builder{}
	sb.Grow(len(a) * 9)
	for i := range a {
		sb.WriteString(strconv.Itoa(a[i]) + " ")
	}
	return sb.String()
}
func SArr64(a []int64) string {
	sb := strings.Builder{}
	sb.Grow(len(a) * 9)
	for i := range a {
		sb.WriteString(strconv.FormatInt(a[i], 10) + " ")
	}
	return sb.String()
}
func MnMx(args ...int64) (int64, int64) {
	minVal, maxVal := int64(math.MaxInt64), int64(math.MinInt64)
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
		if v > maxVal {
			maxVal = v
		}
	}
	return minVal, maxVal
}
func Mn(args ...int64) int64 { mn, _ := MnMx(args...); return mn }
func Mx(args ...int64) int64 { _, mx := MnMx(args...); return mx }
func LCM(a, b int64) int64   { return a / GCD(a, b) * b }
func GCD(a, b int64) int64 {
	if a == 0 {
		return b
	}
	return GCD(b%a, a)
}
func sortInt64Slice(a []int64) { sort.Slice(a, func(i, j int) bool { return a[i] < a[j] }) }
func abs(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

package main

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

func main() {
	r := bufio.NewReaderSize(os.Stdin, 50*1024*1024)
	T := readInt(r)
	for t := 1; t <= T; t++ {
		N, X := readTwoInts(r)
		sums := readInts(r, N)
		cnt := solve(sums, float64(X))
		fmt.Print(cnt)
		if t < T {
			fmt.Println()
		}
	}
}

func solve(sums []int, X float64) (result int) {
	sort.Sort(sort.Reverse(sort.IntSlice(sums)))
	curr := float64(0)
	for i := 0; i < len(sums); i++ {
		curr += float64(sums[i])
		avg := curr / float64(i+1)
		if avg < X {
			return i
		}
	}
	return len(sums)
}

/**
* Utils
*/
func readInt(r *bufio.Reader) int {
	return strToInt(readLine(r))
}

func readTwoInts(r *bufio.Reader) (int, int) {
	ints := readInts(r, 2)
	return ints[0], ints[1]
}

func readInts(r *bufio.Reader, n int) []int {
	result := make([]int, n)
	strs := strings.Split(readLine(r), " ")
	for i := 0; i < n; i++ {
		result[i] = strToInt(strs[i])
	}
	return result
}

func readLine(r *bufio.Reader) string {
	str, _, err := r.ReadLine()
	noError(err)
	return string(str)
}

func readLines(r *bufio.Reader, n int) []string {
	result := make([]string, n)
	for i := 0; i < n; i++ {
		result[i] = readLine(r)
	}
	return result
}

func strToInt(s string) int {
	num, err := strconv.Atoi(s)
	noError(err)
	return num
}

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

package main

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

func newScanner() *bufio.Scanner {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	return scanner
}

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

func scanInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = scanInt()
	}
	return a
}

func scanString() string {
	if sc.Scan() {
		return sc.Text()
	}
	panic(sc.Err())
}

var sc = newScanner()

func main() {
	for t := scanInt(); t > 0; t-- {
		n, x := scanInt(), scanInt()
		a := scanInts(n)
		sort.Sort(sort.Reverse(sort.IntSlice(a)))
		sum := int64(0)
		i := 0
		for ; i < n; i++ {
			sum += int64(a[i])
			if sum/int64(i+1) < int64(x) {
				break
			}
		}
		fmt.Println(i)
	}
}

package main

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

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt() int
	NextInt64() int64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	// adjust the following size as needed
	// 2 << 17 is good enough to scan strings of len 2*10^5
	// it could go as high as 2 << 26 before cf judge breaks
	size := 2 << 20
	buf := make([]byte, size)
	s.Buffer(buf, size)
	return &wordScannerImpl{Scanner: s}
}

func (impl *wordScannerImpl) NextInt() int {
	impl.Scan()
	bb := impl.Bytes()
	i := 0
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextInt64() int64 {
	impl.Scan()
	bb := impl.Bytes()
	i := int64(0)
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int64(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

func main() {
	defer writer.Flush()
	t := reader.NextInt64()
	for ; t > 0; t-- {
		n, x := reader.NextInt64(), reader.NextInt64()
		aa := make([]int64, n)
		for i := 0; i < len(aa); i++ {
			aa[i] = reader.NextInt64()
		}
		writer.Printf("%d\n", sol(aa, x))
	}
}

func sol(aa []int64, x int64) int64 {
	sort.Slice(aa, func(a, b int) bool {
        return aa[a] < aa[b]
	})
    ret := int64(0)
    currTotal := int64(0)
    for i := len(aa)-1; i > -1; i-- {
        if (currTotal + aa[i]) / (ret+1) >= x {
            ret++
            currTotal += aa[i]
            continue
        }
        break
    }
	return ret
}

package main

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

)
func max(a,b int) int{
	if(a>b){
		return a
	}
	return b;
}
func main(){
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var T int;
	fmt.Fscanln(reader, &T)
	for t:=0;t<T;t++ {
		var n,x int;
		fmt.Fscanln(reader,&n,&x)
		nums:=make([]int,n)
		sum:=0
		count:=0
		for i:=0;i<n;i++{
			if i == n-1 {
				fmt.Fscanf(reader, "%d\n", &nums[i])

			} else {
				fmt.Fscanf(reader, "%d", &nums[i])
			}
			if(nums[i]>=x){
			sum+=nums[i]
			count++
			}
		}
		// sum = sum - (count*x)
		sort.Ints(nums);
		for i:=len(nums)-1-count;i>=0;i--{
			if( sum+nums[i]>=(count+1)*x ){
				count++
				sum+=nums[i]
			}
		}
		// fmt.Println(sum,nums,count)
		// for i:=len(nums)-1-count;i>=0;i--{
		// 	diff:= x-nums[i];
		// 	if(sum-diff>=0){
		// 	sum-=diff;

		// 	count++
		// }
		// }
		fmt.Fprintln(writer,count);
	}
}

package main

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

)
func max(a,b int) int{
	if(a>b){
		return a
	}
	return b;
}
func main(){
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var T int;
	fmt.Fscanln(reader, &T)
	for t:=0;t<T;t++ {
		var n,x int;
		fmt.Fscanln(reader,&n,&x)
		nums:=make([]int,n)
		sum:=0
		// count:=0
		for i:=0;i<n;i++{
			if i == n-1 {
				fmt.Fscanf(reader, "%d\n", &nums[i])

			} else {
				fmt.Fscanf(reader, "%d", &nums[i])
			}
			// if(nums[i]>=x){
			// sum+=nums[i]
			// count++
			// }
		}
		// sum = sum - (count*x)
		sort.Ints(nums);
		// fmt.Println(sum,nums,count)
		// for i:=len(nums)-1-count;i>=0;i--{
		// 	diff:= x-nums[i];
		// 	if(sum-diff>=0){
		// 	sum-=diff;

		// 	count++
		// }
		// }
		prefix:=n;
		for prefix>0 && sum+nums[prefix-1]-x>=0 {
				prefix--
				sum= sum+nums[prefix]-x
		}

		// for i:=len(nums)-count-1;i>=0;i--{
		// 	fmt.Println(nums[i],"here")
		// 	if( sum+nums[i]>=(count+1)*x ){
		// 		count++
		// 		sum+=nums[i]
		// 	}else{
		// 		break;
		// 	}
		// }

		fmt.Fprintln(writer,n-prefix);
	}
}

package main

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

)
func max(a,b int) int{
	if(a>b){
		return a
	}
	return b;
}
func main(){
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var T int;
	fmt.Fscanln(reader, &T)
	for t:=0;t<T;t++ {
		var n,x int;
		fmt.Fscanln(reader,&n,&x)
		nums:=make([]int,n)
		sum:=0
		// count:=0
		for i:=0;i<n;i++{
			if i == n-1 {
				fmt.Fscanf(reader, "%d\n", &nums[i])

			} else {
				fmt.Fscanf(reader, "%d", &nums[i])
			}
			// if(nums[i]>=x){
			// sum+=nums[i]
			// count++
			// }
		}
		// sum = sum - (count*x)
		sort.Ints(nums);
		// fmt.Println(sum,nums,count)
		// for i:=len(nums)-1-count;i>=0;i--{
		// 	diff:= x-nums[i];
		// 	if(sum-diff>=0){
		// 	sum-=diff;

		// 	count++
		// }
		// }
		prefix:=n;
		for prefix>0 && sum+nums[prefix-1]-x>=0 {
				prefix--
				sum= sum+prefix-x
		}

		// for i:=len(nums)-count-1;i>=0;i--{
		// 	fmt.Println(nums[i],"here")
		// 	if( sum+nums[i]>=(count+1)*x ){
		// 		count++
		// 		sum+=nums[i]
		// 	}else{
		// 		break;
		// 	}
		// }

		fmt.Fprintln(writer,n-prefix);
	}
}

package main

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

)
func max(a,b int) int{
	if(a>b){
		return a
	}
	return b;
}
func main(){
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var T int;
	fmt.Fscanln(reader, &T)
	for t:=0;t<T;t++ {
		var n,x int;
		fmt.Fscanln(reader,&n,&x)
		nums:=make([]int,n)
		sum:=0
		count:=0
		for i:=0;i<n;i++{
			if i == n-1 {
				fmt.Fscanf(reader, "%d\n", &nums[i])

			} else {
				fmt.Fscanf(reader, "%d", &nums[i])
			}
			if(nums[i]>=x){
			sum+=nums[i]
			count++
			}
		}
		// sum = sum - (count*x)
		sort.Ints(nums);
// 		fmt.Println(sum,"SUM",len(nums)-count-1)
		for i:=len(nums)-count-1;i>=0;i--{
			if( sum+nums[i]>=(count+1)*x ){
				count++
				sum+=nums[i]
			}else{
				break;
			}
		}
		// fmt.Println(sum,nums,count)
		// for i:=len(nums)-1-count;i>=0;i--{
		// 	diff:= x-nums[i];
		// 	if(sum-diff>=0){
		// 	sum-=diff;

		// 	count++
		// }
		// }
		fmt.Fprintln(writer,count);
	}
}

package main

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

)
func max(a,b int) int{
	if(a>b){
		return a
	}
	return b;
}
func main(){
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var T int;
	fmt.Fscanln(reader, &T)
	for t:=0;t<T;t++ {
		var n,x int;
		fmt.Fscanln(reader,&n,&x)
		nums:=make([]int,n)
		sum:=0
		count:=0
		for i:=0;i<n;i++{
			if i == n-1 {
				fmt.Fscanf(reader, "%d\n", &nums[i])

			} else {
				fmt.Fscanf(reader, "%d", &nums[i])
			}
			if(nums[i]>=x){
			sum+=nums[i]
			count++
			}
		}
		sum = sum - (count*x)
		sort.Ints(nums);
		// fmt.Println(sum,nums,count)
		for i:=len(nums)-1-count;i>=0;i--{
			diff:= x-nums[i];
			if(sum-diff>=0){
			sum-=diff;

			count++
		}
		}
		fmt.Fprintln(writer,count);
	}
}

package main

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

)
func max(a,b int) int{
	if(a>b){
		return a
	}
	return b;
}
func main(){
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var T int;
	fmt.Fscanln(reader, &T)
	for t:=0;t<T;t++ {
		var n,x int;
		fmt.Fscanln(reader,&n,&x)
		nums:=make([]int,n)
		sum:=0
		count:=0
		for i:=0;i<n;i++{
			if i == n-1 {
				fmt.Fscanf(reader, "%d\n", &nums[i])

			} else {
				fmt.Fscanf(reader, "%d", &nums[i])
			}
			if(nums[i]>=x){
			sum+=nums[i]
			count++
			}
		}
		// sum = sum - (count*x)
		sort.Ints(nums);
		fmt.Println(sum,"SUM",len(nums)-count-1)
		for i:=len(nums)-count-1;i>=0;i--{
			if( sum+nums[i]>=(count+1)*x ){
				count++
				sum+=nums[i]
			}else{
				break;
			}
		}
		// fmt.Println(sum,nums,count)
		// for i:=len(nums)-1-count;i>=0;i--{
		// 	diff:= x-nums[i];
		// 	if(sum-diff>=0){
		// 	sum-=diff;

		// 	count++
		// }
		// }
		fmt.Fprintln(writer,count);
	}
}

package main

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

func main() {
	r := bufio.NewReaderSize(os.Stdin, 50*1024*1024)
	T := readInt(r)
	for t := 1; t <= T; t++ {
		N, X := readTwoInts(r)
		sums := readInts(r, N)
		cnt := solve(sums, X)
		fmt.Print(cnt)
		if t < T {
			fmt.Println()
		}
	}
}

func solve(sums []int, X int) (result int) {
	sort.Sort(sort.Reverse(sort.IntSlice(sums)))
	curr := 0
	for i := 0; i < len(sums); i++ {
		curr += sums[i]
		avg := curr / (i+1)
		if avg < X {
			return i
		}
	}
	return len(sums)
}

/**
* Utils
*/
func readInt(r *bufio.Reader) int {
	return strToInt(readLine(r))
}

func readTwoInts(r *bufio.Reader) (int, int) {
	ints := readInts(r, 2)
	return ints[0], ints[1]
}

func readInts(r *bufio.Reader, n int) []int {
	result := make([]int, n)
	strs := strings.Split(readLine(r), " ")
	for i := 0; i < n; i++ {
		result[i] = strToInt(strs[i])
	}
	return result
}

func readLine(r *bufio.Reader) string {
	str, _, err := r.ReadLine()
	noError(err)
	return string(str)
}

func readLines(r *bufio.Reader, n int) []string {
	result := make([]string, n)
	for i := 0; i < n; i++ {
		result[i] = readLine(r)
	}
	return result
}

func strToInt(s string) int {
	num, err := strconv.Atoi(s)
	noError(err)
	return num
}

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

package main

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

func main() {
	r := bufio.NewReaderSize(os.Stdin, 100*1024*1024)
	T := readInt(r)
	for t := 1; t <= T; t++ {
		N, X := readTwoInts(r)
		sums := readInts(r, N)
		cnt := solve(sums, X)
		fmt.Print(cnt)
		if t < T {
			fmt.Println()
		}
	}
}

func solve(sums []int, X int) (result int) {
	sort.Sort(sort.Reverse(sort.IntSlice(sums)))
	curr := 0
	for i := 0; i < len(sums); i++ {
		curr += sums[i]
		avg := curr / (i+1)
		if avg < X {
			return i
		}
	}
	return len(sums)
}

/**
* Utils
*/
func readInt(r *bufio.Reader) int {
	return strToInt(readLine(r))
}

func readTwoInts(r *bufio.Reader) (int, int) {
	ints := readInts(r, 2)
	return ints[0], ints[1]
}

func readInts(r *bufio.Reader, n int) []int {
	result := make([]int, n)
	strs := strings.Split(readLine(r), " ")
	for i := 0; i < n; i++ {
		result[i] = strToInt(strs[i])
	}
	return result
}

func readLine(r *bufio.Reader) string {
	str, _, err := r.ReadLine()
	noError(err)
	return string(str)
}

func readLines(r *bufio.Reader, n int) []string {
	result := make([]string, n)
	for i := 0; i < n; i++ {
		result[i] = readLine(r)
	}
	return result
}

func strToInt(s string) int {
	num, err := strconv.Atoi(s)
	noError(err)
	return num
}

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

package main

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

func newScanner() *bufio.Scanner {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	return scanner
}

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

func scanInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = scanInt()
	}
	return a
}

func scanString() string {
	if sc.Scan() {
		return sc.Text()
	}
	panic(sc.Err())
}

var sc = newScanner()

func main() {
	for t := scanInt(); t > 0; t-- {
		n, x := scanInt(), scanInt()
		a := scanInts(n)
		sort.Sort(sort.Reverse(sort.IntSlice(a)))
		sum := 0
		i := 0
		for ; i < n; i++ {
			sum += a[i]
			if sum/(i+1) < x {
				break
			}
		}
		fmt.Println(i)
	}
}


Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them.The tree looks like a polyline on the plane, consisting of all sticks. The polyline starts at the point $$$(0, 0)$$$. While constructing the polyline, Alexey will attach sticks to it one by one in arbitrary order. Each stick must be either vertical or horizontal (that is, parallel to $$$OX$$$ or $$$OY$$$ axis). It is not allowed for two consecutive sticks to be aligned simultaneously horizontally or simultaneously vertically. See the images below for clarification.Alexey wants to make a polyline in such a way that its end is as far as possible from $$$(0, 0)$$$. Please help him to grow the tree this way.Note that the polyline defining the form of the tree may have self-intersections and self-touches, but it can be proved that the optimal answer does not contain any self-intersections or self-touches.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the number of sticks Alexey got as a present. The second line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$) — the lengths of the sticks.

Print one integer — the square of the largest possible distance from $$$(0, 0)$$$ to the tree end.

NoteThe following pictures show optimal trees for example tests. The squared distance in the first example equals $$$5 \cdot 5 + 1 \cdot 1 = 26$$$, and in the second example $$$4 \cdot 4 + 2 \cdot 2 = 20$$$.

package main

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

/* solution */

func solve() {
	n := readInt()
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = readInt()
	}
	sort.Ints(a)
	var c, d int64
	for i := 0; i < n/2; i++ {
		c += int64(a[i])
		d += int64(a[n-i-1])
	}
	if n%2 > 0 {
		d += int64(a[n/2])
	}
	printInt64(c*c + d*d)
}

/* stubs */

func main() {

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

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

	reader = bufio.NewScanner(f)

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

	reader.Split(bufio.ScanWords)

	solve()

}

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

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

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

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

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

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

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

package main

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

const (
	MX_INT int64 = math.MaxInt64
	MN_INT int64 = math.MinInt64
)

func main() {
	n := ScanInt64()
	array := ScanInt64Slice(n)
	sort.Slice(array, func(i, j int) bool {
		return array[i] < array[j]
	})
	vertical, horizontal := int64(0), int64(0)
	for i := int64(0); i < n; i++ {
		if i < n/2 {

			horizontal += array[i]
		} else {
			vertical += array[i]
		}
	}

	fmt.Println(vertical * vertical + horizontal * horizontal)

	close(O)
	oWg.Wait()
}

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

var O chan string
var in *bufio.Scanner
var oWg *sync.WaitGroup
var Pl func(a ...interface{}) (n int, err error)

func init() {
	Pl = fmt.Println

	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(1e8))
	in.Split(bufio.ScanWords)

	O = make(chan string, 16)
	oWg = &sync.WaitGroup{}
	oWg.Add(1)

	writer := bufio.NewWriterSize(os.Stdout, int(1e5))
	go func(writer *bufio.Writer) {
		defer oWg.Done()
		defer writer.Flush()

		for line := range O {
			writer.WriteString(line + "\n")
		}
	}(writer)
}

func ScanWord() string {
	in.Scan()
	return in.Text()
}

func ScanStringSlice(n int64) []string {
	length := int(n)
	s := make([]string, n)
	for i := 0; i < length; i++ {
		s[i] = ScanWord()
	}
	return s
}

func ScanInt64() int64 {
	intStr := ScanWord()
	i, err := strconv.ParseInt(intStr, 10, 64)
	if err != nil {
		panic(err)
	}
	return i
}

func ScanInt() int {
	intStr := ScanWord()
	i, err := strconv.Atoi(intStr)
	if err != nil {
		panic(err)
	}
	return i
}

func ScanInt64Slice(n int64) []int64 {
	length := int(n)
	arr := make([]int64, n)
	for i := 0; i < length; i++ {
		arr[i] = ScanInt64()
	}
	return arr
}

/*********************** Utils ***********************/

func Mx(args ...int64) int64 {
	maxVal := MN_INT
	for _, v := range args {
		if v > maxVal {
			maxVal = v
		}
	}
	return maxVal
}

func Mn(args ...int64) int64 {
	minVal := MX_INT
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
	}
	return minVal
}

func LCM(a, b int64) int64 {
	return a / GCD(a, b) * b
}

func GCD(a, b int64) int64 {
	if a == 0 {
		return b
	}
	return GCD(b%a, a)
}

func S(v interface{}) string {
	return fmt.Sprintf("%v", v)
}

package main

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

func main() {
	var number int
	fmt.Scanf("%d\n", &number)
	// fmt.Println(number)
	reader := bufio.NewReader(os.Stdin)
	line := readLine2(reader)
	arr := strings.Split(string(line), " ")
	sticks := make([]int, 0)
	sum := int64(0)
	for i := 0; i < number; i++ {
		n, _ := strconv.Atoi(arr[i])
		sticks = append(sticks, n)
		sum += int64(n)
	}
	sort.Ints(sticks)
	half1 := int64(0)
	for i:=0;i<len(sticks)/2;i++ {
		half1 += int64(sticks[i])
	}
	half2 := sum - half1
	// fmt.Println(sticks, sum, half1)
	length := half1 * half1 + half2 * half2
	fmt.Println(length)
}

func readLine2(reader *bufio.Reader) []byte {
	result := make([]byte, 0)
	for {
		s, isPrefix, err := reader.ReadLine()
		if err != nil {
			fmt.Printf("error=%+v\n", err)
			break
		}
		result = append(result, s...)
		if !isPrefix {
			// fmt.Println(string(result))
			break
		}
	}
	return result
}

package main

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

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

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

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

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

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

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

// ReadInt64 returns as integer as int64.
func ReadInt64() int64 {
	return readInt64()
}
func ReadInt64_2() (int64, int64) {
	return readInt64(), readInt64()
}
func ReadInt64_3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func ReadInt64_4() (int64, int64, int64, int64) {
	return readInt64(), readInt64(), readInt64(), readInt64()
}

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

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

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

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

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

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

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

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

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

/*********** DP sub-functions ***********/

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

// NthBit returns nth bit value of an argument.
// n starts from 0.
func NthBit(num, nth int) int {
	return num >> uint(nth) & 1
}

// OnBit returns the integer that has nth ON bit.
// If an argument has nth ON bit, OnBit returns the argument.
func OnBit(num, nth int) int {
	return num | (1 << uint(nth))
}

// OffBit returns the integer that has nth OFF bit.
// If an argument has nth OFF bit, OffBit returns the argument.
func OffBit(num, nth int) int {
	return num & ^(1 << uint(nth))
}

// PopCount returns the number of ON bit of an argument.
func PopCount(num int) int {
	res := 0

	for i := 0; i < 70; i++ {
		if ((num >> uint(i)) & 1) == 1 {
			res++
		}
	}

	return res
}

/*********** Arithmetic ***********/

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

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

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

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

	return s
}

// PowInt is integer version of math.Pow
// PowInt calculate a power by Binary Power (二分累乗法(O(log e))).
func PowInt(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 := PowInt(a, halfE)
		return half * half
	}

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

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

// Gcd returns the Greatest Common Divisor of two natural numbers.
// Gcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Gcd uses the Euclidean Algorithm.
func Gcd(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}
	if a < b {
		a, b = b, a
	}

	// Euclidean Algorithm
	for b > 0 {
		div := a % b
		a, b = b, div
	}

	return a
}

// Lcm returns the Least Common Multiple of two natural numbers.
// Lcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Lcd uses the Euclidean Algorithm indirectly.
func Lcm(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2
	// a' and b' are relatively prime numbers
	// gcd consists of prime numbers, that are included in a and b
	gcd := Gcd(a, b)

	// not (a * b / gcd), because of reducing a probability of overflow
	return (a / gcd) * b
}

// Strtoi is a wrapper of strconv.Atoi().
// If strconv.Atoi() returns an error, Strtoi calls panic.
func Strtoi(s string) int {
	if i, err := strconv.Atoi(s); err != nil {
		panic(errors.New("[argument error]: Strtoi only accepts integer string"))
	} else {
		return i
	}
}

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

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

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

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

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

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

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

const MOD = 1000000000 + 7
const ALPHABET_NUM = 26
const INF_INT64 = math.MaxInt64
const INF_BIT60 = 1 << 60

var n int
var A []int

func main() {
	n = ReadInt()
	A = ReadIntSlice(n)

	sort.Sort(sort.IntSlice(A))

	l, r := 0, n-1
	hori, verti := int64(0), int64(0)
	for i := 0; i < n; i++ {
		if i%2 == 0 {
			// 後から
			a := A[r]
			r--
			hori += int64(a)
		} else {
			// 前から
			a := A[l]
			l++
			verti += int64(a)
		}
	}

	ans := hori*hori + verti*verti
	fmt.Println(ans)
}

// MODはとったか？
// 遷移だけじゃなくて最後の最後でちゃんと取れよ？

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

package main

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

var inf int = 0x3f3f3f3f
var reader *bufio.Reader

func init() {
	stdin := os.Stdin
	// stdin, _ = os.Open("1.in")
	reader = bufio.NewReaderSize(stdin, 1<<20)
}

var n int
var a []int

func main() {
	fmt.Fscan(reader, &n)
	a = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &a[i])
	}
	sort.Sort(sort.IntSlice(a))
	var x, y int64
	for i := 0; i < n; i++ {
		if i < n/2 {
			x += int64(a[i])
		} else {
			y += int64(a[i])
		}
	}
	fmt.Println(x*x + y*y)
}

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"os"
	"sort"
	"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([]int64, N)

	for i := range a {
		a[i] = readll()
	}

	sort.Slice(a, func(i, j int) bool { return a[i] < a[j] })
	var x, y int64
	for i, j := 0, N-1; i <= j; i, j = i+1, j-1 {
		x += a[j]
		if i == j {
			break
		}
		y += a[i]
	}
	println(x*x + y*y)
}

package main

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

const (
	MX_INT int64 = math.MaxInt64
	MN_INT int64 = math.MinInt64
)

func main() {
    n := ScanInt()
    a := ScanInt64Slice(n)
	sort.Slice(a, func(i, j int) bool {return a[i] < a[j]})

    middle := n/2
    h, v := int64(0), int64(0)
    for i := 0; i < n; i++ {
        if i < middle {
        	h += a[i]
		} else {
			v += a[i]
		}
    }

    P(((h*h) + (v*v)))

	close(O)
	oWg.Wait()
}

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

var O chan string
var in *bufio.Scanner
var oWg *sync.WaitGroup
var P func(a ...interface{}) (n int, err error)

func init() {
	P = fmt.Println

	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(1e+9))
	in.Split(bufio.ScanWords)

	O = make(chan string, 16)
	oWg = &sync.WaitGroup{}
	oWg.Add(1)

	writer := bufio.NewWriter(os.Stdout)
	go func() {
		defer oWg.Done()
		defer writer.Flush()

		for line := range O {
			writer.WriteString(line + "\n")
		}
	}()
}

func ScanWord() string {in.Scan(); return in.Text() }
func ScanInt() int {i, _ := strconv.Atoi(ScanWord()); return i}
func ScanInt64() int64 {i, _ := strconv.ParseInt(ScanWord(), 10, 64); return i}
func ScanStringSlice(n int) []string {s := make([]string, n); for i := 0; i < n; i++ {s[i] = ScanWord()}; return s}
func ScanInt64Slice(n int) []int64 {arr := make([]int64, n); for i := 0; i < n; i++ {arr[i] = ScanInt64()}; return arr}

/*********************** Utils ***********************/

func S(v interface{}) string {return fmt.Sprintf("%v", v)}
func SArr(a []int64) string {sb := strings.Builder{}; sb.Grow(len(a) * 9); for i := range a {sb.WriteString(strconv.FormatInt(a[i], 10) + " ")}; return sb.String()}
func MnMx(args ...int64) (int64, int64) {minVal, maxVal := MX_INT, MN_INT; for _, v := range args {if v < minVal {minVal = v}; if v > maxVal {maxVal = v}}; return minVal, maxVal}
func Mn(args ...int64) int64 { mn, _ := MnMx(args...); return mn }
func Mx(args ...int64) int64 { _, mx := MnMx(args...); return mx }
func LCM(a, b int64) int64 {return a / GCD(a, b) * b}
func GCD(a, b int64) int64 {if (a == 0) {return b}; return GCD(b%a, a)}
func sortInt64Slice(a []int64) {sort.Slice(a, func(i, j int) bool { return a[i] < a[j] })}
func abs(x int64) int64 {if x < 0 {return -x}; return x}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	var n int
	fmt.Fscanf(reader, "%d\n", &n)

	a := make([]int, n)
	for i := 0; i < n; i++ {
		if i+1 != n {
			fmt.Fscanf(reader, "%d", &a[i])
		} else {
			fmt.Fscanf(reader, "%d\n", &a[i])
		}
	}

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

	//fmt.Println(a)

	var x, y int64
	for i := 0; i < n/2; i++ {
		x += int64(a[i])
	}
	for i := n / 2; i < n; i++ {
		y += int64(a[i])
	}
	fmt.Printf("%d\n", x*x+y*y)

}

package main

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

var inf int = 0x3f3f3f3f
var reader *bufio.Reader

func init() {
	stdin := os.Stdin
	// stdin, _ = os.Open("1.in")
	reader = bufio.NewReaderSize(stdin, 1<<20)
}

var n int
var a []int

func main() {
	fmt.Fscan(reader, &n)
	a = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &a[i])
	}
	sort.Sort(sort.IntSlice(a))
	var x, y int
	for i := 0; i < n; i++ {
		if i < n/2 {
			x += a[i]
		} else {
			y += a[i]
		}
	}
	fmt.Println(x*x + y*y)
}


There are $$$n$$$ points on a plane. The $$$i$$$-th point has coordinates $$$(x_i, y_i)$$$. You have two horizontal platforms, both of length $$$k$$$. Each platform can be placed anywhere on a plane but it should be placed horizontally (on the same $$$y$$$-coordinate) and have integer borders. If the left border of the platform is $$$(x, y)$$$ then the right border is $$$(x + k, y)$$$ and all points between borders (including borders) belong to the platform.Note that platforms can share common points (overlap) and it is not necessary to place both platforms on the same $$$y$$$-coordinate.When you place both platforms on a plane, all points start falling down decreasing their $$$y$$$-coordinate. If a point collides with some platform at some moment, the point stops and is saved. Points which never collide with any platform are lost.Your task is to find the maximum number of points you can save if you place both platforms optimally.You have to answer $$$t$$$ independent test cases.For better understanding, please read the Note section below to see a picture for the first test case.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$1 \le k \le 10^9$$$) — the number of points and the length of each platform, respectively. The second line of the test case contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$), where $$$x_i$$$ is $$$x$$$-coordinate of the $$$i$$$-th point. The third line of the input contains $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$), where $$$y_i$$$ is $$$y$$$-coordinate of the $$$i$$$-th point. All points are distinct (there is no pair $$$1 \le i < j \le n$$$ such that $$$x_i = x_j$$$ and $$$y_i = y_j$$$). It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer: the maximum number of points you can save if you place both platforms optimally.

NoteThe picture corresponding to the first test case of the example:Blue dots represent the points, red segments represent the platforms. One of the possible ways is to place the first platform between points $$$(1, -1)$$$ and $$$(2, -1)$$$ and the second one between points $$$(4, 3)$$$ and $$$(5, 3)$$$. Vectors represent how the points will fall down. As you can see, the only point we can't save is the point $$$(3, 7)$$$ so it falls down infinitely and will be lost. It can be proven that we can't achieve better answer here. Also note that the point $$$(5, 3)$$$ doesn't fall at all because it is already on the platform.

package main

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

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

	T:= 0
	for Fscan(in, &T); T > 0; T-- {
		var n,k int
		Fscan(in,&n,&k)
		a:=make([]int,n)
		for i:=0;i<n;i++{
			Fscan(in,&a[i])
		}

		for i:=0;i<n;i++{
			var j int
			Fscan(in,&j)
		}
		sort.Ints(a)
		if a[n-1]-a[0]<=2*k{
			Fprintln(out,n)
			continue
		}
		// Fprintln(out,k,a)
		dp1:=make([]int,n+1)
		dp2:=make([]int,n+1)

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

		i:=0
		for j,x:=range(a){
			for x-a[i]>k{
				i++
			}
			dp1[j+1]=max(dp1[j+1],j-i+1)
			dp2[j+1]=max(dp2[j+1],dp1[i]+j-i+1)

			dp1[j+1]=max(dp1[j+1],dp1[j])
			dp2[j+1]=max(dp2[j+1],dp2[j])
		}

		Fprintln(out,max(dp1[n],dp2[n]))
	}
}

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

package main

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

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	for t := io.NextInt(); t > 0; t-- {
		n, k := io.NextInt(), io.NextInt()
		a := io.NextInts(n)
		io.NextInts(n)

		sort.Ints(a)
		ans := 0
		best := make([]int, n+1)
		for i := n - 1; i >= 0; i-- {
			j := sort.Search(n, func(j int) bool { return a[j] > a[i]+k })
			best[i] = max(best[i+1], j-i)
			ans = max(ans, j-i+best[j])
		}

		io.Println(ans)
	}
}

func max(i, j int) int {
	if i > j {
		return i
	}
	return j
}

type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{r: r, Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) NextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt()
	}
	return a
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f, a...)
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1409E(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type pair struct{ v, c int }
	max := func(a, b int) int {
		if a > b {
			return a
		}
		return b
	}

	var T, n, l, v int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &l)
		cnt := map[int]int{}
		for i := 0; i < n; i++ {
			Fscan(in, &v)
			cnt[v]++
		}
		for i := 0; i < n; i++ {
			Fscan(in, &v)
		}

		n = len(cnt)
		a := make([]int, 0, n)
		for v := range cnt {
			a = append(a, v)
		}
		sort.Ints(a)
		sum := make([]int, n+1)
		for i, v := range a {
			sum[i+1] = sum[i] + cnt[v]
		}
		cs := make([]int, n)
		for i, v := range a {
			cs[i] = sum[i+1] - sum[sort.SearchInts(a[:i], v-l)]
		}
		mxC := make([]int, n)
		mxC[0] = cs[0]
		for i := 1; i < n; i++ {
			mxC[i] = max(mxC[i-1], cs[i])
		}
		ans := 0
		for i, c := range cs {
			if j := sort.SearchInts(a[:i], a[i]-l); j > 0 {
				c += mxC[j-1]
			}
			ans = max(ans, c)
		}
		Fprintln(out, ans)
	}
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1409E(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type pair struct{ v, c int }
	max := func(a, b int) int {
		if a > b {
			return a
		}
		return b
	}

	var T, n, l, v int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &l)
		cnt := map[int]int{}
		for i := 0; i < n; i++ {
			Fscan(in, &v)
			cnt[v]++
		}
		for i := 0; i < n; i++ {
			Fscan(in, &v)
		}

		n = len(cnt)
		a := make([]int, 0, n)
		for v := range cnt {
			a = append(a, v)
		}
		sort.Ints(a)
		sum := make([]int, n+1)
		for i, v := range a {
			sum[i+1] = sum[i] + cnt[v]
		}
		cs := make([]int, n)
		for i, v := range a {
			cs[i] = sum[i+1] - sum[sort.SearchInts(a[:i], v-l)]
		}
		mxC := make([]int, n)
		mxC[0] = cs[0]
		for i := 1; i < n; i++ {
			mxC[i] = max(mxC[i-1], cs[i])
		}
		ans := 0
		for i, v := range a {
			j := sort.SearchInts(a[:i], v-l)
			c := sum[i+1] - sum[j]
			if j > 0 {
				c += mxC[j-1]
			}
			ans = max(ans, c)
		}
		Fprintln(out, ans)
	}
}

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


You're a mikemon breeder currently in the middle of your journey to become a mikemon master. Your current obstacle is go through the infamous Biridian Forest.The forestThe Biridian Forest is a two-dimensional grid consisting of r rows and c columns. Each cell in Biridian Forest may contain a tree, or may be vacant. A vacant cell may be occupied by zero or more mikemon breeders (there may also be breeders other than you in the forest). Mikemon breeders (including you) cannot enter cells with trees. One of the cells is designated as the exit cell.The initial grid, including your initial position, the exit cell, and the initial positions of all other breeders, will be given to you. Here's an example of such grid (from the first example):  MovesBreeders (including you) may move in the forest. In a single move, breeders may perform one of the following actions:   Do nothing.  Move from the current cell to one of the four adjacent cells (two cells are adjacent if they share a side). Note that breeders cannot enter cells with trees.  If you are located on the exit cell, you may leave the forest. Only you can perform this move — all other mikemon breeders will never leave the forest by using this type of movement. After each time you make a single move, each of the other breeders simultaneously make a single move (the choice of which move to make may be different for each of the breeders).Mikemon battleIf you and t (t > 0) mikemon breeders are located on the same cell, exactly t mikemon battles will ensue that time (since you will be battling each of those t breeders once). After the battle, all of those t breeders will leave the forest to heal their respective mikemons.Note that the moment you leave the forest, no more mikemon battles can ensue, even if another mikemon breeder move to the exit cell immediately after that. Also note that a battle only happens between you and another breeders — there will be no battle between two other breeders (there may be multiple breeders coexisting in a single cell).Your goalYou would like to leave the forest. In order to do so, you have to make a sequence of moves, ending with a move of the final type. Before you make any move, however, you post this sequence on your personal virtual idol Blog. Then, you will follow this sequence of moves faithfully.Goal of other breedersBecause you post the sequence in your Blog, the other breeders will all know your exact sequence of moves even before you make your first move. All of them will move in such way that will guarantee a mikemon battle with you, if possible. The breeders that couldn't battle you will do nothing.Your taskPrint the minimum number of mikemon battles that you must participate in, assuming that you pick the sequence of moves that minimize this number. Note that you are not required to minimize the number of moves you make.

The first line consists of two integers: r and c (1 ≤ r, c ≤ 1000), denoting the number of rows and the number of columns in Biridian Forest. The next r rows will each depict a row of the map, where each character represents the content of a single cell:    'T': A cell occupied by a tree.  'S': An empty cell, and your starting position. There will be exactly one occurence of this in the map.  'E': An empty cell, and where the exit is located. There will be exactly one occurence of this in the map.  A digit (0-9): A cell represented by a digit X means that the cell is empty and is occupied by X breeders (in particular, if X is zero, it means that the cell is not occupied by any breeder).  It is guaranteed that it will be possible for you to go from your starting position to the exit cell through a sequence of moves.

A single line denoted the minimum possible number of mikemon battles that you have to participate in if you pick a strategy that minimize this number.

NoteThe following picture illustrates the first example. The blue line denotes a possible sequence of moves that you should post in your blog:  The three breeders on the left side of the map will be able to battle you — the lone breeder can simply stay in his place until you come while the other two breeders can move to where the lone breeder is and stay there until you come. The three breeders on the right does not have a way to battle you, so they will stay in their place.For the second example, you should post this sequence in your Blog:  Here's what happens. First, you move one cell to the right.  Then, the two breeders directly to the right of the exit will simultaneously move to the left. The other three breeder cannot battle you so they will do nothing.  You end up in the same cell with 2 breeders, so 2 mikemon battles are conducted. After those battles, all of your opponents leave the forest.  Finally, you make another move by leaving the forest.

package main

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

var scanner *bufio.Scanner

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

type State struct {
  R, C, Steps int
}

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer := bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  numR, numC := getI(), getI()
  startR, startC, exitR, exitC := 0, 0, 0, 0
  g := make([][]int, numR)
  for r := 0; r < numR; r++ {
    s := getS()
    g[r] = make([]int, numC)
    for c, char := range s {
      if char == 'T' {
        g[r][c] = -1
      } else if char == 'S' {
        startR, startC = r, c
      } else if char == 'E' {
        exitR, exitC = r, c
      } else {
        g[r][c] = int(char - '0')
      }
    }
  }
  dr, dc := []int{ -1, 0, 1, 0 }, []int{ 0, 1, 0, -1 }
  queue := []*State{ &State{ exitR, exitC, 0 } }
  tail, maxSteps := 0, 1000*1000
  result := 0
  for tail != len(queue) && queue[tail].Steps <= maxSteps {
    state := queue[tail]
    tail++
    r, c, steps := state.R, state.C, state.Steps
    if g[r][c] < 0 {
      continue
    }
    result += g[r][c]
    g[r][c] = -2
    if r == startR && c == startC {
      maxSteps = steps
    }
    if steps == maxSteps {
      continue
    }
    for i := 0; i < 4; i++ {
      R, C := r + dr[i], c + dc[i]
      if R == -1 || R == numR || C == -1 || C == numC || g[R][C] < 0 {
        continue
      }
      queue = append(queue, &State{ R, C, steps+1 } )
    }
  }
  writer.WriteString(fmt.Sprintf("%d\n", result))
}

package main

import (
    "fmt"
)

type Tuple struct{
    x int
    y int
    len int
}
func main(){
    var r, c int
    fmt.Scanf("%d%d", &r, &c)
    start := Tuple{}

    g:= make([][]int8, r)
    for i:= 0; i < r; i++{
        g[i] = make([]int8, c)
        var s string
        fmt.Scan(&s)
        for j:= 0; j < c; j++{
            switch s[j] {
                case byte('T') : g[i][j] = -1
                case byte('S') : g[i][j] =  -2
                case byte('E') : start, g[i][j] = Tuple{i, j, 0}, 10
                default : g[i][j] = int8(s[j] - '0')
            }
        }
    }
    fights:= 0
    var q []Tuple
    var startdist = 1000000000
    q = append(q, start)
    deltas := []Tuple{{-1, 0, 0}, {1, 0, 0}, {0, -1, 0}, {0, 1, 0}}
    for len(q) > 0{
        var v Tuple
        v, q = q[0], q[1:]
        if g[v.x][v.y] != -1{
            if v.len > startdist {
                break;
            }
            if g[v.x][v.y] == -2 {
                //We have reached start position
                startdist = v.len
            }else if g[v.x][v.y] < 10 {
                fights += int(g[v.x][v.y])
            }
            g[v.x][v.y] = -1
            for _, d := range deltas {
                dx, dy := v.x + d.x, v.y + d.y
                if (dx >= 0) && (dy >= 0) && (dx < r) && (dy < c) && (g[dx][dy] != -1){
                    q = append(q, Tuple{dx, dy, v.len + 1})
                }
            }

        }
    }
    fmt.Println(fights)

}

package main

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

var scanner *bufio.Scanner

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

type Location struct {
	x , y ,cost int
}

func main(){
	scanner = bufio.NewScanner(os.Stdin)
  	scanner.Split(bufio.ScanWords)
  	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	n , m := getI() , getI()

	cell := make([][]int , n)
	shortestPath := make([][]int , n)
	visited := make([][]bool , n)

	var startx , starty , endx, endy int
	for i := 0 ; i < n ; i ++{
		cell[i] = make([]int , m)
		shortestPath[i] = make([]int , m)
		visited[i] = make([]bool , m)
		var s string
		s = getS()

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

			if s[j] == 'S'{
				endx = i
				endy = j

			} else if s[j] == 'E' {
				startx = i
				starty = j
			}else if s[j] == 'T'{
				visited[i][j] = true
			}else {
				cell[i][j] = int(s[j] - '0')
			}
		}

	}

	dx := [4]int{1,0,-1,0}
	dy := [4]int{0,1,0,-1}

	var queue []Location;

	queue = append(queue, Location{startx,starty,0} )
	visited[startx][starty] = true
	en := 1
	for ;len(queue) > 0; {

		now := queue[0]
		X := now.x
		Y := now.y;
		queue = queue[1:]

		//fmt.Printf("!!%d %d \n",X,Y)

		shortestPath[X][Y] = now.cost

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

			nextX := now.x + dx[i]
			nextY := now.y + dy[i]

			if 0<= nextX && nextX < n && 0 <= nextY && nextY < m && !visited[nextX][nextY]  {
				visited[nextX][nextY] = true
				queue = append(queue, Location{nextX,nextY,now.cost+1})
				en ++
			}

		}

	}

	fight := 0
	bound := shortestPath[endx][endy]

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

		for j := 0 ; j < m ; j ++ {
		//	fmt.Printf("!!%d %d %d %d\n",i,j,cell[i][j],visited[i][j])
			if 1 <= cell[i][j] && cell[i][j] <= 9 && shortestPath[i][j] <= bound && visited[i][j] {

				fight += cell[i][j]
			}
		}
	}
	writer.WriteString(fmt.Sprintf("%d\n", fight))

}

package main

import (
	"fmt"
//	"os"
//	"bufio"

)

type Location struct {
	x , y ,cost int
}

func main(){

	//r := bufio.NewReader(os.Stdin)
//	w := bufio.NewWriter(os.Stdout)

	var n , m int
	//fmt.Fprintf(w,"kuy!@#!@#!@#\n")
	fmt.Scanf("%d%d",&n,&m)
	//fmt.Printf("!!%d %d\n",n,m)

	cell := make([][]int , n)
	shortestPath := make([][]int , n)
	visited := make([][]bool , n)

	var startx , starty , endx, endy int
	for i := 0 ; i < n ; i ++{
		cell[i] = make([]int , m)
		shortestPath[i] = make([]int , m)
		visited[i] = make([]bool , m)
		var s string
		fmt.Scan(&s)

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

			if s[j] == 'S'{
				endx = i
				endy = j

			} else if s[j] == 'E' {
				startx = i
				starty = j
			}else if s[j] == 'T'{
				visited[i][j] = true
			}else {
				cell[i][j] = int(s[j] - '0')
			}
		}

	}

	dx := [4]int{1,0,-1,0}
	dy := [4]int{0,1,0,-1}

	var queue []Location;

	queue = append(queue, Location{startx,starty,0} )
	en := 1
	for i := 0 ; i < en ; i ++ {
		now := queue[i]
		X := now.x
		Y := now.y;

		visited[X][Y] = true

		shortestPath[X][Y] = now.cost

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

			nextX := now.x + dx[i]
			nextY := now.y + dy[i]

			if 0<= nextX && nextX < n && 0 <= nextY && nextY < m && !visited[nextX][nextY]  {

				queue = append(queue, Location{nextX,nextY,now.cost+1})
				en ++
			}

		}

	}

	fight := 0
	bound := shortestPath[endx][endy]

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

		for j := 0 ; j < m ; j ++ {
			if 1 <= cell[i][j] && cell[i][j] <= 9 && shortestPath[i][j] <= bound {
				fight += cell[i][j]
			}
		}
	}

	fmt.Printf("%d\n",fight)

}

package main

import (
	"fmt"
//	"os"
//	"bufio"

)

type Location struct {
	x , y ,cost int
}

func main(){

	var n , m int

	fmt.Scanf("%d%d",&n,&m)

	cell := make([][]int , n)
	shortestPath := make([][]int , n)
	visited := make([][]bool , n)

	var startx , starty , endx, endy int
	for i := 0 ; i < n ; i ++{
		cell[i] = make([]int , m)
		shortestPath[i] = make([]int , m)
		visited[i] = make([]bool , m)
		var s string
		fmt.Scan(&s)

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

			if s[j] == 'S'{
				endx = i
				endy = j

			} else if s[j] == 'E' {
				startx = i
				starty = j
			}else if s[j] == 'T'{
				visited[i][j] = true
			}else {
				cell[i][j] = int(s[j] - '0')
			}
		}

	}

	dx := [4]int{1,0,-1,0}
	dy := [4]int{0,1,0,-1}

	var queue []Location;

	queue = append(queue, Location{startx,starty,0} )
	visited[startx][starty] = true
	en := 1
	for ;len(queue) > 0; {
		now := queue[0	]
		X := now.x
		Y := now.y;
		queue = queue[1:]

		shortestPath[X][Y] = now.cost

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

			nextX := now.x + dx[i]
			nextY := now.y + dy[i]

			if 0<= nextX && nextX < n && 0 <= nextY && nextY < m && !visited[nextX][nextY]  {
				visited[X][Y] = true
				queue = append(queue, Location{nextX,nextY,now.cost+1})
				en ++
			}

		}

	}

	fight := 0
	bound := shortestPath[endx][endy]

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

		for j := 0 ; j < m ; j ++ {
			if 1 <= cell[i][j] && cell[i][j] <= 9 && shortestPath[i][j] <= bound && visited[i][j] {
				fight += cell[i][j]
			}
		}
	}

	fmt.Printf("%d\n",fight)

}


You are given a square matrix $$$A$$$ of size $$$n \times n$$$ whose elements are integers. We will denote the element on the intersection of the $$$i$$$-th row and the $$$j$$$-th column as $$$A_{i,j}$$$.You can perform operations on the matrix. In each operation, you can choose an integer $$$k$$$, then for each index $$$i$$$ ($$$1 \leq i \leq n$$$), swap $$$A_{i, k}$$$ with $$$A_{k, i}$$$. Note that cell $$$A_{k, k}$$$ remains unchanged.For example, for $$$n = 4$$$ and $$$k = 3$$$, this matrix will be transformed like this:    The operation $$$k = 3$$$ swaps the blue row with the green column. You can perform this operation any number of times. Find the lexicographically smallest matrix$$$^\dagger$$$ you can obtain after performing arbitrary number of operations.$$${}^\dagger$$$ For two matrices $$$A$$$ and $$$B$$$ of size $$$n \times n$$$, let $$$a_{(i-1) \cdot n + j} = A_{i,j}$$$ and $$$b_{(i-1) \cdot n + j} = B_{i,j}$$$. Then, the matrix $$$A$$$ is lexicographically smaller than the matrix $$$B$$$ when there exists an index $$$i$$$ ($$$1 \leq i \leq n^2$$$) such that $$$a_i < b_i$$$ and for all indices $$$j$$$ such that $$$1 \leq j < i$$$, $$$a_j = b_j$$$.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 1000$$$) — the size of the matrix. The $$$i$$$-th line of the next $$$n$$$ lines contains $$$n$$$ integers $$$A_{i, 1}, A_{i, 2}, \dots, A_{i, n}$$$ ($$$1 \le A_{i, j} \le 10^9$$$) — description of the matrix $$$A$$$. It is guaranteed that the sum of $$$n^2$$$ over all test cases does not exceed $$$10^6$$$.

For each test case, print $$$n$$$ lines with $$$n$$$ integers each — the lexicographically smallest matrix.

NoteNote that in every picture below the matrix is transformed in such a way that the blue rows are swapped with the green columns.In the first test case, we can perform $$$1$$$ operation for $$$k = 3$$$. The matrix will be transformed as below:    In the second test case, we can perform $$$2$$$ operations for $$$k = 1$$$ and $$$k = 3$$$:

package main

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

var _, _, _ = main, rw, do

func main() {
	r, w := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer w.Flush()
	rw(r, w)
}

func rw(r io.Reader, w io.Writer) {
	var t int
	fmt.Fscan(r, &t)
	for ti := 0; ti < t; ti++ {
		var n int
		fmt.Fscan(r, &n)
		a := make([][]int, n)
		for i := range a {
			a[i] = make([]int, n)
			for j := range a[i] {
				fmt.Fscan(r, &a[i][j])
			}
		}
		w1 := do(n, a)
		for _, v := range w1 {
			for i, v := range v {
				if i > 0 {
					fmt.Fprint(w, " ")
				}
				fmt.Fprint(w, v)
			}
			fmt.Fprintln(w)
		}
	}
}

func do(n int, a [][]int) [][]int {
	f := make([]int, n+n+2)
	for i := range f {
		f[i] = i
	}
	g := ((n + 1) >> 1) << 1
	for i := 0; i < n-1; i++ {
		for j := i + 1; j < n; j++ {
			if a[i][j] == a[j][i] {
				continue
			}
			fi := getf(f, i)
			fj := getf(f, j)
			if a[i][j] > a[j][i] {
				if fi < n && fj < n {
					f[fi], f[fj] = g, g+1
					g += 2
				} else if fi < n {
					f[fi] = fj ^ 1
				} else if fj < n {
					f[fj] = fi ^ 1
				} else if fi != fj && fi != fj^1 {
					f[fj] = fi ^ 1
					f[fj^1] = fi
				}
			} else {
				if fi < n && fj < n {
					f[fi], f[fj] = g, g
					g += 2
				} else if fi < n {
					f[fi] = fj
				} else if fj < n {
					f[fj] = fi
				} else if fi != fj && fi != fj^1 {
					f[fj] = fi
					f[fj^1] = fi ^ 1
				}
			}
		}
	}
	m := make(map[int]bool)
	for i := 0; i < n; i++ {
		fi := getf(f, i)
		if fi < n {
			continue
		}
		if m[fi] {
			continue
		} else if m[fi^1] {
			for j := 0; j < n; j++ {
				a[i][j], a[j][i] = a[j][i], a[i][j]
			}
			continue
		}
		m[fi] = true
	}
	return a
}

func getf(f []int, x int) int {
	if f[x] != x {
		f[x] = getf(f, f[x])
	}
	return f[x]
}

package main

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

func readLine() string {
	s, err := in.ReadString('\n')
	if err != nil {
		panic(err)
	}
	s = strings.ReplaceAll(s, "\n", "")
	s = strings.ReplaceAll(s, "\r", "")
	return s
}

func readLines(n int) []string {
	res := make([]string, n)
	for i := 0; i < n; i++ {
		res[i] = readLine()
	}
	return res
}

func readInt() int {
	n, err := strconv.ParseInt(readLine(), 10, 32)
	if err != nil {
		panic(err)
	}
	return int(n)
}

func readInt2() (int, int) {
	as := readInts(2)
	return as[0], as[1]
}

func readInt3() (int, int, int) {
	as := readInts(3)
	return as[0], as[1], as[2]
}

func readUint() uint64 {
	n, err := strconv.ParseUint(readLine(), 10, 64)
	if err != nil {
		panic(err)
	}
	return n
}

func readInts(n int) []int {
	s := readLine()
	as := strings.SplitN(s, " ", n)
	if len(as) != n {
		panic("invalid len")
	}
	arr := make([]int, n)
	for k, a := range as {
		x, _ := strconv.ParseInt(a, 10, 64)
		arr[k] = int(x)
	}
	return arr
}

func readStrings(n int) []string {
	s := readLine()
	as := strings.SplitN(s, " ", n)
	if len(as) != n {
		panic("invalid len")
	}
	return as
}

func arr(n, m int) [][]int {
	a := make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, m)
	}
	return a
}

const MAXN int = 1007

var in = bufio.NewReader(os.Stdin)
var out = bufio.NewWriter(os.Stdout)
var a [MAXN][MAXN]int
var pre [MAXN << 1]int

func findPre(pos int) int {
	var temp, rcd int
	temp = pre[pos]
	for temp != pre[temp] {
		temp = pre[temp]
	}
	for pre[pos] != pos {
		rcd = pre[pos]
		pre[pos] = temp
		pos = rcd
	}
	return temp
}

func main() {
	defer out.Flush()
	var t, n int
	var ch byte
	fmt.Fscan(in, &t)
	for ; t != 0; t-- {
		fmt.Fscan(in, &n)
		for i := 1; i <= 2*n; i++ {
			pre[i] = i
		}
		for i := 1; i <= n; i++ {
			for j := 1; j <= n; j++ {
				fmt.Fscan(in, &a[i][j])
			}
		}
		for i := 1; i <= n; i++ {
			for j := i + 1; j <= n; j++ {
				if a[i][j] == a[j][i] {
					continue
				}
				ii, in, jj, jn := findPre(i), findPre(i+n), findPre(j), findPre(j+n)
				if ii == jj || in == jn {
					continue
				} else if ii == jn || jj == in {
					a[i][j], a[j][i] = a[j][i], a[i][j]
					continue
				}
				if a[i][j] < a[j][i] {
					pre[ii], pre[in] = jj, jn
				} else {
					pre[ii], pre[in] = jn, jj
					a[i][j], a[j][i] = a[j][i], a[i][j]
				}
			}
		}
		for i := 1; i <= n; i++ {
			for j := 1; j <= n; j++ {
				if j == n {
					ch = '\n'
				} else {
					ch = ' '
				}
				fmt.Fprintf(out, "%d%c", a[i][j], ch)
			}
		}
	}
}


Every December, VK traditionally holds an event for its employees named "Secret Santa". Here's how it happens.$$$n$$$ employees numbered from $$$1$$$ to $$$n$$$ take part in the event. Each employee $$$i$$$ is assigned a different employee $$$b_i$$$, to which employee $$$i$$$ has to make a new year gift. Each employee is assigned to exactly one other employee, and nobody is assigned to themselves (but two employees may be assigned to each other). Formally, all $$$b_i$$$ must be distinct integers between $$$1$$$ and $$$n$$$, and for any $$$i$$$, $$$b_i \ne i$$$ must hold.The assignment is usually generated randomly. This year, as an experiment, all event participants have been asked who they wish to make a gift to. Each employee $$$i$$$ has said that they wish to make a gift to employee $$$a_i$$$.Find a valid assignment $$$b$$$ that maximizes the number of fulfilled wishes of the employees.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^5$$$). Description of the test cases follows. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of participants of the event. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$; $$$a_i \ne i$$$) — wishes of the employees in order from $$$1$$$ to $$$n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print two lines. In the first line, print a single integer $$$k$$$ ($$$0 \le k \le n$$$) — the number of fulfilled wishes in your assignment. In the second line, print $$$n$$$ distinct integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$; $$$b_i \ne i$$$) — the numbers of employees assigned to employees $$$1, 2, \ldots, n$$$. $$$k$$$ must be equal to the number of values of $$$i$$$ such that $$$a_i = b_i$$$, and must be as large as possible. If there are multiple answers, print any.

NoteIn the first test case, two valid assignments exist: $$$[3, 1, 2]$$$ and $$$[2, 3, 1]$$$. The former assignment fulfills two wishes, while the latter assignment fulfills only one. Therefore, $$$k = 2$$$, and the only correct answer is $$$[3, 1, 2]$$$.

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := os.Stdout
	var t int
	fmt.Fscan(in,&t)
	for u:=1;u<=t;u++{
		var n int
		fmt.Fscan(in,&n)
		a := make([]int,n+5)
		for i:=1;i<=n;i++{
			fmt.Fscan(in,&a[i])
		}
		wish := map[int]int{}
		ans := make([]int,n+5)
		cnt:=0
		p := map[int]int{}
		for i:=1;i<=n;i++{
			if wish[a[i]]==0{
				wish[a[i]]=1
			}
		}
		l := []int{}
		for i:=1;i<=n;i++{
			if wish[i]==0{
				l = append(l,i)
			}
		}
		cnt = len(l)-1
		wish = map[int]int{}
		for i:=1;i<=n;i++{
			if wish[a[i]]==0{
				p[a[i]]=i
				wish[a[i]]=1
				ans[i]=a[i]
			}else{
				if l[cnt]!=i{
					ans[i]=l[cnt]
				}else{
					index := p[a[i]]
					ans[index]=i
					ans[i]=a[i]
					p[a[i]]=i
				}
				cnt--
			}
		}
		ret := 0
		for i:=1;i<=n;i++{
			if ans[i]==a[i]{
				ret++
			}
		}
		fmt.Fprintln(out,ret)
		for i:=1;i<=n;i++{
			fmt.Fprintf(out,"%d ", ans[i])
		}
		fmt.Fprintln(out)
	}
}

package main

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

var (
	read  = bufio.NewReader(os.Stdin)
	write = bufio.NewWriter(os.Stdout)
)

const N = 200005

func main() {
	defer write.Flush()

	var (
		T   int
		n   int
		k   int
		a   = [N]int{}
		fa  = [N]int{}
		pre = [N]int{}
	)

	fmt.Fscan(read, &T)
	for i := 0; i < T; i++ {
		k = 0
		fmt.Fscan(read, &n)
		for i := 1; i <= n; i++ {
			fmt.Fscan(read, &a[i])
			fa[a[i]] = i
		}
		for i := 1; i <= n; i++ {
			if fa[i] != 0 {
				k += 1
				pre[fa[i]] = i
			}
		}
		fmt.Fprintln(write, k)
		j := 1
		for i := 1; i <= n; i++ {
			if pre[i] == 0 {
				for fa[j] != 0 {
					j += 1
				}
				fa[j] = i
				pre[i] = j
			}
		}
		for i := 1; i <= n; i++ {
			if pre[i] == i {
				pre[i] = a[i]
				pre[fa[a[i]]] = i
				fa[a[i]] = i
			}
		}
		for i := 1; i <= n; i++ {
			fmt.Fprintf(write, "%d ", pre[i])
			pre[i] = 0
			fa[i] = 0
		}
		fmt.Fprint(write, "\n")
	}
}


You are given two integers $$$b$$$ and $$$w$$$. You have a chessboard of size $$$10^9 \times 10^9$$$ with the top left cell at $$$(1; 1)$$$, the cell $$$(1; 1)$$$ is painted white.Your task is to find a connected component on this chessboard that contains exactly $$$b$$$ black cells and exactly $$$w$$$ white cells. Two cells are called connected if they share a side (i.e. for the cell $$$(x, y)$$$ there are at most four connected cells: $$$(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)$$$). A set of cells is called a connected component if for every pair of cells $$$C_1$$$ and $$$C_2$$$ from this set, there exists a sequence of cells $$$c_1$$$, $$$c_2$$$, ..., $$$c_k$$$ such that $$$c_1 = C_1$$$, $$$c_k = C_2$$$, all $$$c_i$$$ from $$$1$$$ to $$$k$$$ are belong to this set of cells and for every $$$i \in [1, k - 1]$$$, cells $$$c_i$$$ and $$$c_{i + 1}$$$ are connected.Obviously, it can be impossible to find such component. In this case print "NO". Otherwise, print "YES" and any suitable connected component.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Then $$$q$$$ queries follow. The only line of the query contains two integers $$$b$$$ and $$$w$$$ ($$$1 \le b, w \le 10^5$$$) — the number of black cells required and the number of white cells required. It is guaranteed that the sum of numbers of cells does not exceed $$$2 \cdot 10^5$$$ ($$$\sum w + \sum b \le 2 \cdot 10^5$$$).

For each query, print the answer to it. If it is impossible to find the required component, print "NO" on the first line. Otherwise, print "YES" on the first line. In the next $$$b + w$$$ lines print coordinates of cells of your component in any order. There should be exactly $$$b$$$ black cells and $$$w$$$ white cells in your answer. The printed component should be connected. If there are several answers, you can print any. All coordinates in the answer should be in the range $$$[1; 10^9]$$$.

package main

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

/* solution */

func solve() {
	q := readInt()
	for i := 0; i < q; i++ {
		solveOne()
	}
}

func solveOne() {

	b, w := readInt(), readInt()

	var less, more int
	dx := 3
	if b > w {
		less, more = w, b
		dx = 2
	} else {
		less, more = b, w
	}

	if more > less*3+1 {
		println("NO")
		return
	}

	println("YES")

	for i := 0; i < less*2; i++ {
		printInt(1 + dx + i)
		printInt(3)
		println("")
	}

	remains := more - less
	if remains > 0 {
		printInt(0 + dx)
		printInt(3)
		println("")
		remains--
	}
	for i := 0; remains > 0 && i < less; i++ {
		printInt(1 + dx + i*2)
		printInt(2)
		println("")
		remains--
	}
	for i := 0; remains > 0 && i < less; i++ {
		printInt(1 + dx + i*2)
		printInt(4)
		println("")
		remains--
	}

}

/* stubs */

func main() {

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

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

	reader = bufio.NewScanner(f)

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

	reader.Split(bufio.ScanWords)

	solve()

}

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

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

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

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

func println(s string) {
	if len(s) > 0 {
		writer.WriteString(s)
	}
	writer.WriteString("\n")
}

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

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

package main

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

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)
	var q int
	fmt.Fscanf(reader, "%d\n", &q)
	for i := 0;i < q;i ++ {
		var b, w int
		fmt.Fscanf(reader, "%d %d\n", &b, &w)
		var big, small, col int
		if b > w {
			big, small, col = b, w, 2
		} else {
			big, small, col = w, b, 3
		}
		if big  - 1 > small * 3 {
			fmt.Printf("NO\n")
			continue
		} else {
			fmt.Printf("YES\n")
		}
		for i := 0;i < small;i ++ {
			fmt.Printf("%d %d\n", i * 2 + 1, col)
			fmt.Printf("%d %d\n", i * 2 + 2, col)
		}
		big = big - small
		if big > 0 {
			big --
			fmt.Printf("%d %d\n", 2 * small + 1, col)
		}
		for i := 0;i < big;i ++ {
			if i % 2 == 0 {
				fmt.Printf("%d %d\n", i + 2, col - 1)
			} else {
				fmt.Printf("%d %d\n", i + 1, col + 1)
			}
		}

	}
}

package main

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

func Sol1196E(reader io.Reader, writer io.Writer) {
	min := func(a, b int) int {
		if a <= b {
			return a
		}
		return b
	}

	in := bufio.NewReader(reader)
	out := bufio.NewWriter(writer)
	defer out.Flush()

	var n int
	Fscan(in, &n)
	for ; n > 0; n-- {
		var b, w int
		Fscan(in, &b, &w)

		start := 2
		if b > w {
			start = 1
			b, w = w, b
		}
		if w > 3*b+1 {
			Fprintln(out, "NO")
			continue
		}

		Fprintln(out, "YES")
		for i := 0; i < b; i++ {
			Fprintln(out, 2, start+2*i)
			Fprintln(out, 2, start+2*i+1)
		}
		w -= b
		if w > 0 {
			Fprintln(out, 2, start+2*b)
			w--
		}
		minC := min(w, b)
		for i := 0; i < minC; i++ {
			Fprintln(out, 1, start+2*i+1)
		}
		w -= minC
		for i := 0; i < w; i++ {
			Fprintln(out, 3, start+2*i+1)
		}
	}
}

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

// Author: sighduck
// URL: https://codeforces.com/contest/1196/problem/E

package main

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

type Cell struct {
	X int
	Y int
}

type Solution struct {
	Exists    bool
	Component []Cell
}

func getComponent(b int, w int, firstCell Cell) []Cell {
	component := []Cell{}
	for i := 0; i < 2*w; i++ {
		component = append(component, Cell{X: firstCell.X, Y: firstCell.Y + i})
	}
	b -= w
	if b > 0 {
		b -= 1
		component = append(component, Cell{X: firstCell.X, Y: firstCell.Y + 2*w})
	}
	secondCell := Cell{X: firstCell.X, Y: firstCell.Y + 1}
	for {
		nextCells := []Cell{
			{X: secondCell.X - 1, Y: secondCell.Y},
			{X: secondCell.X + 1, Y: secondCell.Y},
		}
		for _, cell := range nextCells {
			if b > 0 {
				b -= 1
				component = append(component, cell)
			}
		}
		secondCell.Y += 2
		if b == 0 {
			break
		}
	}
	return component
}

func _Solve(b int, w int, firstCell Cell) Solution {
	if (b > w) && (3*w+1 < b) {
		return Solution{Exists: false}
	}
	return Solution{Exists: true, Component: getComponent(b, w, firstCell)}
}

func Solve(b int, w int) Solution {
	if b >= w {
		return _Solve(b, w, Cell{2, 3})
	}
	return _Solve(w, b, Cell{2, 2})
}

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

	var q int
	fmt.Fscanf(reader, "%d\n", &q)
	for i := 0; i < q; i++ {
		var b, w int
		fmt.Fscanf(reader, "%d %d\n", &b, &w)
		solution := Solve(b, w)
		if solution.Exists {
			fmt.Fprintf(writer, "YES\n")
			for _, cell := range solution.Component {
				fmt.Fprintf(writer, "%d %d\n", cell.X, cell.Y)
			}
		} else {
			fmt.Fprintf(writer, "NO\n")
		}
	}
}

package main

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

/* solution */

func solve() {
	q := readInt()
	for i := 0; i < q; i++ {
		solveOne()
	}
}

func solveOne() {

	b, w := readInt(), readInt()

	var less, more int
	dx := 2
	if b > w {
		less, more = w, b
		dx = 3
	} else {
		less, more = b, w
	}

	if more > less*3+1 {
		println("NO")
		return
	}

	println("YES")

	for i := 0; i < less*2; i++ {
		printInt(1 + dx + i)
		printInt(3)
		println("")
	}

	remains := more - less
	if remains > 0 {
		printInt(0 + dx)
		printInt(3)
		println("")
		remains--
	}
	for i := 0; remains > 0 && i < less; i++ {
		printInt(1 + dx + i*2)
		printInt(2)
		println("")
		remains--
	}
	for i := 0; remains > 0 && i < less; i++ {
		printInt(1 + dx + i*2)
		printInt(4)
		println("")
		remains--
	}

}

/* stubs */

func main() {

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

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

	reader = bufio.NewScanner(f)

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

	reader.Split(bufio.ScanWords)

	solve()

}

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

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

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

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

func println(s string) {
	if len(s) > 0 {
		writer.WriteString(s)
	}
	writer.WriteString("\n")
}

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

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

package main

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

/* solution */

func solve() {
	q := readInt()
	for i := 0; i < q; i++ {
		solveOne()
	}
}

func solveOne() {

	b, w := readInt(), readInt()

	var less, more int
	dx := 2
	if b > w {
		less, more = w, b
		dx = 3
	} else {
		less, more = b, w
	}

	if more > less*3+1 {
		println("NO")
		return
	}

	println("YES")

	for i := 0; i < less*2; i++ {
		printInt(1 + dx + i)
		printInt(1)
		println("")
	}

	remains := more - less
	if remains > 0 {
		printInt(0 + dx)
		printInt(1)
		println("")
		remains--
	}
	for i := 0; remains > 0 && i < less; i++ {
		printInt(1 + dx + i*2)
		printInt(0)
		println("")
		remains--
	}
	for i := 0; remains > 0 && i < less; i++ {
		printInt(1 + dx + i*2)
		printInt(2)
		println("")
		remains--
	}

}

/* stubs */

func main() {

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

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

	reader = bufio.NewScanner(f)

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

	reader.Split(bufio.ScanWords)

	solve()

}

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

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

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

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

func println(s string) {
	if len(s) > 0 {
		writer.WriteString(s)
	}
	writer.WriteString("\n")
}

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

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

package main

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

/* solution */

func solve() {
	q := readInt()
	for i := 0; i < q; i++ {
		solveOne()
	}
}

func solveOne() {

	b, w := readInt(), readInt()

	var less, more int
	dx := 0
	if b > w {
		less, more = w, b
		dx = 1
	} else {
		less, more = b, w
	}

	if more > less*3+1 {
		println("NO")
		return
	}

	println("YES")

	for i := 0; i < less*2; i++ {
		printInt(1 + dx + i)
		printInt(1)
		println("")
	}

	remains := more - less
	if remains > 0 {
		printInt(0 + dx)
		printInt(1)
		println("")
		remains--
	}
	for i := 0; remains > 0 && i < less; i++ {
		printInt(1 + dx + i*2)
		printInt(0)
		println("")
		remains--
	}
	for i := 0; remains > 0 && i < less; i++ {
		printInt(1 + dx + i*2)
		printInt(2)
		println("")
		remains--
	}

}

/* stubs */

func main() {

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

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

	reader = bufio.NewScanner(f)

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

	reader.Split(bufio.ScanWords)

	solve()

}

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

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

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

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

func println(s string) {
	if len(s) > 0 {
		writer.WriteString(s)
	}
	writer.WriteString("\n")
}

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

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

package main

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

func Sol1196E(reader io.Reader, writer io.Writer) {
	min := func(a, b int) int {
		if a <= b {
			return a
		}
		return b
	}

	in := bufio.NewReader(reader)
	out := bufio.NewWriter(writer)
	defer out.Flush()

	var n int
	Fscan(in, &n)
	for ; n > 0; n-- {
		var b, w int
		Fscan(in, &b, &w)

		start := 2
		if b > w {
			start = 1
			b, w = w, b
		}
		if w > 3*b+1 {
			Fprintln(out, "NO")
			continue
		}

		Fprintln(out, "YES")
		for i := 0; i < b; i++ {
			Fprintln(out, 2, start+2*i)
			Fprintln(out, 2, start+2*i+1)
		}
		w -= b
		minC := min(w, b)
		for i := 0; i < minC; i++ {
			Fprintln(out, 1, start+2*i+1)
		}
		w -= b
		for i := 0; i < w; i++ {
			Fprintln(out, 3, start+2*i+1)
		}
	}
}

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

// Author: sighduck
// URL: https://codeforces.com/contest/1196/problem/E

package main

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

type Cell struct {
	X int
	Y int
}

type Solution struct {
	Exists    bool
	Component []Cell
}

func shiftCell(cell Cell, shift int) Cell {
	return Cell{X: cell.X, Y: cell.Y + shift}
}

func getComponent(w int, b int, firstMove bool, component []Cell, lastWhiteCell Cell, shift int) []Cell {
	if w == 0 && b == 0 {
		return component
	}
	if firstMove {
		whiteCell := Cell{X: 2, Y: 2}
		blackCells := []Cell{
			{X: whiteCell.X, Y: whiteCell.Y - 1},
			{X: whiteCell.X - 1, Y: whiteCell.Y},
			{X: whiteCell.X, Y: whiteCell.Y + 1},
			{X: whiteCell.X + 1, Y: whiteCell.Y},
		}
		component = append(component, shiftCell(whiteCell, shift))
		for _, cell := range blackCells {
			if b > 0 {
				b -= 1
				component = append(component, shiftCell(cell, shift))
			}
		}
		return getComponent(w-1, b, false, component, whiteCell, shift)
	}
	whiteCell := Cell{X: lastWhiteCell.X, Y: lastWhiteCell.Y + 2}
	blackCells := []Cell{
		{X: whiteCell.X - 1, Y: whiteCell.Y},
		{X: whiteCell.X, Y: whiteCell.Y + 1},
		{X: whiteCell.X + 1, Y: whiteCell.Y},
	}
	component = append(component, shiftCell(whiteCell, shift))
	for _, cell := range blackCells {
		if b > 0 {
			b -= 1
			component = append(component, shiftCell(cell, shift))
		}
	}
	return getComponent(w-1, b, false, component, whiteCell, shift)
}

func _Solve(b int, w int, shift int) Solution {
	if (b > w) && (3*w+1 < b) {
		return Solution{Exists: false}
	}
	return Solution{Exists: true, Component: getComponent(w, b, true, []Cell{}, Cell{}, shift)}
}

func Solve(b int, w int) Solution {
	if b >= w {
		return _Solve(b, w, 0)
	}
	return _Solve(w, b, 1)
}

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

	var q int
	fmt.Fscanf(reader, "%d\n", &q)
	for i := 0; i < q; i++ {
		var b, w int
		fmt.Fscanf(reader, "%d %d\n", &b, &w)
		solution := Solve(b, w)
		if solution.Exists {
			fmt.Fprintf(writer, "YES\n")
			for _, cell := range solution.Component {
				fmt.Fprintf(writer, "%d %d\n", cell.X, cell.Y)
			}
		} else {
			fmt.Fprintf(writer, "NO\n")
		}
	}
}