One of my most productive days was throwing away 1,000 lines of code.— Ken ThompsonFibonacci addition is an operation on an array $$$X$$$ of integers, parametrized by indices $$$l$$$ and $$$r$$$. Fibonacci addition increases $$$X_l$$$ by $$$F_1$$$, increases $$$X_{l + 1}$$$ by $$$F_2$$$, and so on up to $$$X_r$$$ which is increased by $$$F_{r - l + 1}$$$.$$$F_i$$$ denotes the $$$i$$$-th Fibonacci number ($$$F_1 = 1$$$, $$$F_2 = 1$$$, $$$F_{i} = F_{i - 1} + F_{i - 2}$$$ for $$$i > 2$$$), and all operations are performed modulo $$$MOD$$$.You are given two arrays $$$A$$$ and $$$B$$$ of the same length. We will ask you to perform several Fibonacci additions on these arrays with different parameters, and after each operation you have to report whether arrays $$$A$$$ and $$$B$$$ are equal modulo $$$MOD$$$.

The first line contains 3 numbers $$$n$$$, $$$q$$$ and $$$MOD$$$ ($$$1 \le n, q \le 3\cdot 10^5, 1 \le MOD \le 10^9+7$$$) — the length of the arrays, the number of operations, and the number modulo which all operations are performed. The second line contains $$$n$$$ numbers — array $$$A$$$ ($$$0 \le A_i < MOD$$$). The third line also contains $$$n$$$ numbers — array $$$B$$$ ($$$0 \le B_i < MOD$$$). The next $$$q$$$ lines contain character $$$c$$$ and two numbers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — operation parameters. If $$$c$$$ is "A", Fibonacci addition is to be performed on array $$$A$$$, and if it is is "B", the operation is to be performed on $$$B$$$.

After each operation, print "YES" (without quotes) if the arrays are equal and "NO" otherwise. Letter case does not matter.

package main

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

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

func flush()                            { out.Flush() }
func scan(a ...interface{})             { fmt.Fscan(in, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(out, f, a...) }
func assert(f bool) {
	if !f {
		panic("gg")
	}
}

// ----------------------------- TEMPLATE END ----------------------------------

var d []int
var fib []int
var zeroes, n, mod int

func neg(x int) int {
	return (mod - x) % mod
}

func add(x, y int) int {
	return (x + y) % mod
}

func sub(x, y int) int {
	return (x + mod - y) % mod
}

func replace(i, x int) {
	if d[i] == 0 {
		zeroes--
	}
	if x == 0 {
		zeroes++
	}
	d[i] = x
}

func apply(i, x, y int) {
	replace(i, add(d[i], x))
	if i+1 < n {
		i++
		replace(i, sub(add(d[i], y), x))
	}
}

func apply2(i, x, y int) {
	if i >= n {
		return
	}
	replace(i, sub(d[i], y))
	if i+1 < n {
		i++
		replace(i, sub(d[i], x))
	}
}

func main() {
	defer flush()

	var nQ int
	scan(&n, &nQ, &mod)
	d = make([]int, n)

	var ai int
	var sign int = 1
	for j := 0; j < 2; j++ {
		for i := 0; i < n; i++ {
			scan(&ai)
			ai = (mod + ai*sign) % mod
			d[i] = add(d[i], ai)
			if i+1 < n {
				d[i+1] = sub(d[i+1], ai)
				if i+2 < n {
					d[i+2] = sub(d[i+2], ai)
				}
			}
		}
		sign = -sign
	}

	fib = make([]int, n+2)
	fib[0] = 1 % mod
	fib[1] = 1 % mod
	for i := 2; i < n; i++ {
		fib[i] = add(fib[i-1], fib[i-2])
	}

	for i := 0; i < n; i++ {
		if d[i] == 0 {
			zeroes++
		}
	}

	var op []byte
	var fr, to int
	for q := 0; q < nQ; q++ {
		scan(&op, &fr, &to)
		fr--
		to--
		if op[0] == 'A' {
			apply(fr, fib[0], fib[1])
			apply2(to+1, fib[to-fr], fib[to-fr+1])
		} else {
			apply(fr, neg(fib[0]), neg(fib[1]))
			apply2(to+1, neg(fib[to-fr]), neg(fib[to-fr+1]))
		}
		if zeroes == n {
			printf("YES\n")
		} else {
			printf("NO\n")
		}
	}
}


You are fighting with Zmei Gorynich — a ferocious monster from Slavic myths, a huge dragon-like reptile with multiple heads!   Initially Zmei Gorynich has $$$x$$$ heads. You can deal $$$n$$$ types of blows. If you deal a blow of the $$$i$$$-th type, you decrease the number of Gorynich's heads by $$$min(d_i, curX)$$$, there $$$curX$$$ is the current number of heads. But if after this blow Zmei Gorynich has at least one head, he grows $$$h_i$$$ new heads. If $$$curX = 0$$$ then Gorynich is defeated. You can deal each blow any number of times, in any order.For example, if $$$curX = 10$$$, $$$d = 7$$$, $$$h = 10$$$ then the number of heads changes to $$$13$$$ (you cut $$$7$$$ heads off, but then Zmei grows $$$10$$$ new ones), but if $$$curX = 10$$$, $$$d = 11$$$, $$$h = 100$$$ then number of heads changes to $$$0$$$ and Zmei Gorynich is considered defeated.Calculate the minimum number of blows to defeat Zmei Gorynich!You have to answer $$$t$$$ independent queries.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) – the number of queries. The first line of each query contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 100$$$, $$$1 \le x \le 10^9$$$) — the number of possible types of blows and the number of heads Zmei initially has, respectively. The following $$$n$$$ lines of each query contain the descriptions of types of blows you can deal. The $$$i$$$-th line contains two integers $$$d_i$$$ and $$$h_i$$$ ($$$1 \le d_i, h_i \le 10^9$$$) — the description of the $$$i$$$-th blow.

For each query print the minimum number of blows you have to deal to defeat Zmei Gorynich.  If Zmei Gorynuch cannot be defeated print $$$-1$$$.

NoteIn the first query you can deal the first blow (after that the number of heads changes to $$$10 - 6 + 3 = 7$$$), and then deal the second blow.In the second query you just deal the first blow three times, and Zmei is defeated. In third query you can not defeat Zmei Gorynich. Maybe it's better to convince it to stop fighting?

package main

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

type point struct {
	x, y int
}

var ans int64

const (
	mod = int(1e9 + 7)
)

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

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := 0
	fmt.Fscanf(in, "%d\n", &t)
	for i := 0; i < t; i++ {
		n, h := 0, 0
		fmt.Fscanf(in, "%d %d\n", &n, &h)
		maxm := 0
		maxh := 0
		for j := 0; j < n; j++ {
			a, b := 0, 0
			fmt.Fscanf(in, "%d %d\n", &a, &b)
			if a-b > maxm {
				maxm = a - b
			}
			if a > maxh {
				maxh = a
			}
		}
		if maxm <= 0 && maxh < h {
			fmt.Fprintf(out, "-1\n")
			continue
		}
		ans := 0
		ans++
		h -= maxh
		if h > 0 {
			tmp := h / maxm
			for maxm*tmp < h {
				tmp++
			}
			ans += tmp
		}
		fmt.Fprintf(out, "%d\n", ans)
	}
	return
}

func help(i int, n int, total int, t []int, g []int, cur int, c1, c2, c3 int, remaining int) {
	//fmt.Println(i, cur)
	if i == n {
		if cur == total {
			cal(c1, c2, c3)
		}
		return
	}
	if cur > total {
		return
	}
	if cur+remaining < total {
		return
	}
	switch g[i] {
	case 1:
		help(i+1, n, total, t, g, cur+t[i], c1+1, c2, c3, remaining-t[i])
	case 2:
		help(i+1, n, total, t, g, cur+t[i], c1, c2+1, c3, remaining-t[i])
	case 3:
		help(i+1, n, total, t, g, cur+t[i], c1, c2, c3+1, remaining-t[i])
	}
	help(i+1, n, total, t, g, cur, c1, c2, c3, remaining-t[i])
}

func cal(c1, c2, c3 int) {
	a := []int{c1, c2, c3}
	sort.Ints(a)
	tmp := int64(try(c1, c2, c3, 0))
	tmp %= int64(mod)
	for i := 1; i <= c1; i++ {
		tmp *= int64(i)
		tmp %= int64(mod)
	}
	for i := 1; i <= c2; i++ {
		tmp *= int64(i)
		tmp %= int64(mod)
	}
	for i := 1; i <= c3; i++ {
		tmp *= int64(i)
		tmp %= int64(mod)
	}
	ans += tmp
	ans %= int64(mod)
}

func try(a, b, c int, last int) int64 {
	if a == 0 && b == 0 && c == 0 {
		return 1
	}
	if a < 0 || b < 0 || c < 0 {
		return 0
	}
	if last == 0 {
		return try(a-1, b, c, 1) + try(a, b-1, c, 2) + try(a, b, c-1, 3)
	}
	if last == 1 {
		return try(a, b-1, c, 2) + try(a, b, c-1, 3)
	}
	if last == 2 {
		return try(a-1, b, c, 1) + try(a, b, c-1, 3)
	}
	return try(a-1, b, c, 1) + try(a, b-1, c, 2)
}

package main

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

func main() {
	stdin := os.Stdin
	reader := bufio.NewReaderSize(stdin, 1024*1024)
	var T int
	fmt.Fscanf(reader, "%d\n", &T)
	for ; T != 0; T-- {
		var n, x int
		fmt.Fscanf(reader, "%d%d\n", &n, &x)
		var d, h []int

		maxDi := 0
		for i := 0; i < n; i++ {
			var di, hi int
			fmt.Fscanf(reader, "%d%d\n", &di, &hi)
			d = append(d, di)
			h = append(h, hi)
			if maxDi < d[i] {
				maxDi = d[i]
			}
		}

		x -= maxDi
		if x <= 0 {
			fmt.Println(1)
			continue
		}

		for i := 0; i < n; i++ {
			d[i] -= h[i]
		}

		sort.Sort(sort.Reverse(sort.IntSlice(d)))
		if d[0] <= 0 {
			fmt.Println(-1)
			continue
		}
		ans := x/d[0] + 1
		if x%d[0] != 0 {
			ans++
		}
		fmt.Println(ans)
	}
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	firstRow, err := reader.ReadString('\n')
	if err != nil {
		log.Fatal(err)
	}

	var firstRowfields = strings.Fields(firstRow)
	n, err := strconv.Atoi(firstRowfields[0])
	if err != nil {
		log.Fatal(err)
	}

	for i := 0; i < n; i++ {
		line, err := reader.ReadString('\n')
		ints, err := parseInts(line)
		if err != nil {
			log.Fatal(err)
		}

		hitsCount, headsCount := ints[0], ints[1]

		mostPowerfullHit := int(0)
		mostEffectiveHit := int(0)

		for i := 0; i < hitsCount; i++ {
			line, err := reader.ReadString('\n')
			ints, err := parseInts(line)
			if err != nil {
				log.Fatal(err)
			}

			if ints[0] > mostPowerfullHit {
				mostPowerfullHit = ints[0]
			}

			if (ints[0] - ints[1]) > mostEffectiveHit {
				mostEffectiveHit = ints[0] - ints[1]
			}

		}

		result := solution(headsCount, mostPowerfullHit, mostEffectiveHit)

		fmt.Println(result)
	}
}

func parseInts(s string) ([]int, error) {
	var (
		fields = strings.Fields(s)
		ints   = make([]int, len(fields))
		err    error
	)
	for i, f := range fields {
		ints[i], err = strconv.Atoi(f)
		if err != nil {
			return nil, err
		}
	}
	return ints, nil
}

func solution(headsCount int, mostPowerfullHit int, mostEffectiveHit int) int {
	if mostPowerfullHit >= headsCount {
		return 1
	}

	if mostEffectiveHit <= 0 {
		return -1
	}

	if (headsCount - mostPowerfullHit)%mostEffectiveHit == 0 {
		return (headsCount - mostPowerfullHit)/mostEffectiveHit + 1
	} else {
		return (headsCount - mostPowerfullHit)/mostEffectiveHit + 2
	}
}

package main

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

var (
	reader  = bufio.NewReader(os.Stdin)
	T, n, x int
	d       = make([]int, 0, 105)
	h       = make([]int, 0, 105)
)

const maxAns = 1000*1000*1000 + 5

func main() {
	fmt.Fscan(reader, &T)
	for cs := 0; cs < T; cs++ {
		solve()
	}
}

func solve() {
	fmt.Fscan(reader, &n, &x)
	d = d[0:n]
	h = h[0:n]
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &d[i], &h[i])
	}

	ans := maxAns
	for i := 0; i < n; i++ {
		dec := d[i] - h[i]
		if dec > 0 {
			ans = min(ans, (x+dec-1)/dec)
		}
	}

	maxD := d[0]
	for i := 1; i < n; i++ {
		if d[i] > maxD {
			maxD = d[i]
		}
	}
	newx := x - maxD
	if newx <= 0 {
		ans = min(ans, 1)
	} else {
		for i := 0; i < n; i++ {
			dec := d[i] - h[i]
			if dec > 0 {
				ans = min(ans, 1+(newx+dec-1)/dec)
			}
		}
	}

	if ans == maxAns {
		fmt.Println(-1)
	} else {
		fmt.Println(ans)
	}
}

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

// Author: sighduck
// URL: https://codeforces.com/contest/1217/problem/B

package main

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

func Solve(n int, x int, d []int, h []int) int {
	maxD := -1
	maxDelta := -1
	for i := 0; i < n; i++ {
		delta := d[i] - h[i]
		if maxD == -1 || d[i] > maxD {
			maxD = d[i]
		}
		if maxDelta == -1 || delta > maxDelta {
			maxDelta = delta
		}
	}
	if maxD >= x {
		return 1
	}
	if maxDelta <= 0 {
		return -1
	}
	return (x-maxD+maxDelta-1)/maxDelta + 1
}

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

	var t int
	fmt.Fscanf(reader, "%d\n", &t)
	for i := 0; i < t; i++ {
		var n, x int
		fmt.Fscanf(reader, "%d %d\n", &n, &x)
		d, h := make([]int, n), make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscanf(reader, "%d %d\n", &d[i], &h[i])
		}
		fmt.Fprintf(writer, "%d\n", Solve(n, x, d, h))
	}
}

package main

import "fmt"

func main() {

	var t, n, curx, d, h int

	fmt.Scanln(&t)

	for i:=0; i < t; i++ {
		fmt.Scanln(&n, &curx)
		ans := 2000000000
		for j := 0; j < n; j++ {
			fmt.Scanln(&d, &h)
			tmpans := 2000000001
			if curx > d {
				if h-d < 0 {
					tmpans = (curx-d)/(d-h)+1
				}
				if tmpans == 1 {
					tmpans = 2
				}
			} else {
				tmpans = 1
			}
			if ans > tmpans {
				ans = tmpans
			}
		}
		if ans == 2000000000 {
			fmt.Println(-1)
		} else {
			fmt.Println(ans)
		}
	}
	// min(x, d)  if x>d  x = x-d+h  else ok
	// x  d h
	// 10 6 3   x = 7 // x=4
	// 10 8 2   x = 4
	// 10 1 4   x = -1

	// 10 4 1   7 4 1
	// 10 3 2   9 8 7 6 5 4 3 2
	// 10 2 6   -1
	// 10 1 100   -1
}

package main

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

func main() {
	stdin := os.Stdin
	reader := bufio.NewReaderSize(stdin, 1024*1024)
	var T int
	fmt.Fscanf(reader, "%d\n", &T)
	for ; T != 0; T-- {
		var n, x int
		fmt.Fscanf(reader, "%d%d\n", &n, &x)
		var d, h []int

		maxDi := 0
		for i := 0; i < n; i++ {
			var di, hi int
			fmt.Fscanf(reader, "%d%d\n", &di, &hi)
			d = append(d, di)
			h = append(h, hi)
			if maxDi < d[i] {
				maxDi = d[i]
			}
		}

		x -= maxDi
		if x < 0 {
			fmt.Println(1)
			continue
		}

		for i := 0; i < n; i++ {
			d[i] -= h[i]
		}

		sort.Sort(sort.Reverse(sort.IntSlice(d)))
		if d[0] <= 0 {
			fmt.Println(-1)
			continue
		}
		ans := x/d[0] + 1
		if x%d[0] != 0 {
			ans++
		}
		fmt.Println(ans)
	}
}

package main

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

var (
	reader  = bufio.NewReader(os.Stdin)
	T, n, x int
	d       = make([]int, 0, 105)
	h       = make([]int, 0, 105)
)

const maxAns = 1000*1000*1000 + 5

func main() {
	fmt.Fscan(reader, &T)
	for cs := 0; cs < T; cs++ {
		solve()
	}
}

func solve() {
	fmt.Fscan(reader, &n, &x)
	d = d[0:n]
	h = h[0:n]
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &d[i], &h[i])
	}

	ans := maxAns
	for i := 0; i < n; i++ {
		dec := d[i] - h[i]
		if dec > 0 {
			ans = min(ans, (x+dec-1)/dec)
		}
	}

	maxD := d[0]
	for i := 1; i < n; i++ {
		if d[i] > maxD {
			maxD = d[i]
		}
	}
	newx := x - maxD
	for i := 0; i < n; i++ {
		dec := d[i] - h[i]
		if dec > 0 {
			ans = min(ans, 1+(newx+dec-1)/dec)
		}
	}

	if ans == maxAns {
		fmt.Println(-1)
	} else {
		fmt.Println(ans)
	}

}

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


Berland crossword is a puzzle that is solved on a square grid with $$$n$$$ rows and $$$n$$$ columns. Initially all the cells are white.To solve the puzzle one has to color some cells on the border of the grid black in such a way that:   exactly $$$U$$$ cells in the top row are black;  exactly $$$R$$$ cells in the rightmost column are black;  exactly $$$D$$$ cells in the bottom row are black;  exactly $$$L$$$ cells in the leftmost column are black. Note that you can color zero cells black and leave every cell white.Your task is to check if there exists a solution to the given puzzle.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The only line of each testcase contains $$$5$$$ integers $$$n, U, R, D, L$$$ ($$$2 \le n \le 100$$$; $$$0 \le U, R, D, L \le n$$$).

For each testcase print "YES" if the solution exists and "NO" otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

NoteHere are possible solutions to testcases $$$1$$$, $$$2$$$ and $$$4$$$:

package main

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

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

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

func main() {
	defer writer.Flush()

	var T int = 0
	scanf("%d\n", &T)

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

		var n, u, d, r, l int
		scanf("%d %d %d %d %d\n", &n, &u, &r, &d, &l)

		var is_ok bool = false
		for i := 0; i <= 15; i++ {
			var nu int = u
			var nr int = r
			var nd int = d
			var nl int = l

			if i&1 == 1 {
				nu = nu - 1
				nl = nl - 1
			}

			if i&2 == 2 {
				nu = nu - 1
				nr = nr - 1
			}

			if i&4 == 4 {
				nd = nd - 1
				nr = nr - 1
			}

			if i&8 == 8 {
				nd = nd - 1
				nl = nl - 1
			}

			if (nu >= 0 && nd >= 0 && nr >= 0 && nl >= 0) && (nu <= n-2 && nd <= n-2 && nr <= n-2 && nl <= n-2) {
				is_ok = true
				break
			}
		}

		if is_ok == true {
			printf("YES\n")
		} else {
			printf("NO\n")
		}
	}
}

package main

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

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

	var t, n int
	var a [4]int
T:
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n, &a[0], &a[1], &a[2], &a[3])
	o:
		for i := 0; i < 16; i++ {
			x := i | i&1<<4
			for j, v := range a {
				if v == 0 && x>>j&3 > 0 || v == 1 && x>>j&3 == 3 || v == n-1 && x>>j&3 == 0 || v == n && x>>j&3 < 3 {
					continue o
				}
			}
			Fprintln(out, "YES")
			continue T
		}
		Fprintln(out, "NO")
	}
}
func main() { CF1494B(os.Stdin, os.Stdout) }

package main
import . "fmt"

// github.com/EndlessCheng/codeforces-go
func main() {
	var t, n int
	var a [4]int
T:
	for Scan(&t); t > 0; t-- {
		Scan(&n, &a[0], &a[1], &a[2], &a[3])
	o:
		for i := 0; i < 16; i++ {
			x := i | i&1<<4
			for j, v := range a {
				if v == 0 && x>>j&3 > 0 || v == 1 && x>>j&3 == 3 || v == n-1 && x>>j&3 == 0 || v == n && x>>j&3 < 3 {
					continue o
				}
			}
			Println("YES")
			continue T
		}
		Println("NO")
	}
}

package main

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

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

	var t, n, u, r, d, l int
	fmt.Fscan(in, &t)

	for ; t > 0; t-- {
		fmt.Fscan(in, &n, &u, &r, &d, &l)
		minU, minR, minD, minL, minHor, minVer := 0, 0, 0, 0, 0, 0
		if u == n {
			minR++
			minL++
			minVer += 2
		}
		if u == n-1 {
			minVer++
		}
		if d == n {
			minR++
			minL++
			minVer += 2
		}
		if d == n-1 {
			minVer++
		}
		if l == n {
			minU++
			minD++
			minHor += 2
		}
		if l == n-1 {
			minHor++
		}
		if r == n {
			minU++
			minD++
			minHor += 2
		}
		if r == n-1 {
			minHor++
		}
		if u >= minU && d >= minD && r >= minR && l >= minL && u+d >= minHor && l+r >= minVer {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

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

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

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

		ans := false
		for i := 0; i < 16; i++ {
			temp := true
			for j := 0; j < 4; j++ {
				now := 0
				if (i & (1 << j)) > 0 {
					now++
				}
				k := (1 + j) % 4
				if (i & (1 << k)) > 0 {
					now++
				}
				if now > arr[j] {
					temp = false
				}
				if now+n-2 < arr[j] {
					temp = false
				}
			}
			ans = ans || temp
		}
		if ans {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

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

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

func main() {
	defer writer.Flush()

	var T int = 0
	scanf("%d\n", &T)

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

		var n, u, d, r, l int
		scanf("%d %d %d %d %d\n", &n, &u, &r, &d, &l)

		var is_ok bool = false
		for i := 0; i <= 15; i++ {
			var nu int = u
			var nr int = r
			var nd int = d
			var nl int = l

			if i&1 == 1 {
				nu = nu - 1
				nl = nl - 1
			}

			if i&2 == 1 {
				nu = nu - 1
				nr = nr - 1
			}

			if i&4 == 1 {
				nd = nd - 1
				nr = nr - 1
			}

			if i&8 == 1 {
				nd = nd - 1
				nl = nl - 1
			}

			if (nu >= 0 && nd >= 0 && nr >= 0 && nl >= 0) && (nu <= n-2 && nd <= n-2 && nr <= n-2 && nl <= n-2) {
				is_ok = true
				break
			}
		}

		if is_ok == true {
			printf("NO\n")
		} else {
			printf("YES\n")
		}
	}
}

package main

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

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

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

func main() {
	defer writer.Flush()

	var T int = 0
	scanf("%d\n", &T)

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

		var n, u, d, r, l int
		scanf("%d %d %d %d %d\n", &n, &u, &r, &d, &l)

		var is_ok bool = false
		for i := 0; i <= 15; i++ {
			var nu int = u
			var nr int = r
			var nd int = d
			var nl int = l

			if i&1 == 1 {
				nu = nu - 1
				nl = nl - 1
			}

			if i&2 == 1 {
				nu = nu - 1
				nr = nr - 1
			}

			if i&4 == 1 {
				nd = nd - 1
				nr = nr - 1
			}

			if i&8 == 1 {
				nd = nd - 1
				nl = nl - 1
			}

			if (nu >= 0 && nd >= 0 && nr >= 0 && nl >= 0) && (nu <= n-2 && nd <= n-2 && nr <= n-2 && nl <= n-2) {
				is_ok = true
				break
			}
		}

		if is_ok == true {
			printf("YES\n")
		} else {
			printf("NO\n")
		}
	}
}

	package main

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

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

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

	func main() {
		defer writer.Flush()

		var T int = 0
		scanf("%d\n", &T)

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

			var n, u, d, r, l int
			scanf("%d %d %d %d %d\n", &n, &u, &r, &d, &l)

			var is_ok bool = false
			for i := 0; i <= 15; i++ {
				var nu int = u
				var nr int = r
				var nd int = d
				var nl int = l

				if i&1 == 1 {
					nu = nu - 1
					nl = nl - 1
				}

				if i&2 == 1 {
					nu = nu - 1
					nr = nr - 1
				}

				if i&4 == 1 {
					nd = nd - 1
					nr = nr - 1
				}

				if i&8 == 1 {
					nd = nd - 1
					nl = nl - 1
				}

				if (nu >= 0 && nd >= 0 && nr >= 0 && nl >= 0) || (nu <= n-2 && nd <= n-2 && nr <= n-2 && nl <= n-2) {
					is_ok = true
					break
				}
			}

			if is_ok == true {
				printf("YES\n")
			} else {
				printf("NO\n")
			}
		}
	}

package main

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

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

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

func main() {
	defer writer.Flush()

	var T int = 0
	scanf("%d\n", &T)

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

		var n, u, d, r, l int
		scanf("%d %d %d %d %d\n", &n, &u, &r, &d, &l)

		var is_ok bool = false
		for i := 1; i <= 15; i++ {
			var nu int = u
			var nr int = r
			var nd int = d
			var nl int = l

			if i&1 == 1 {
				nu = nu - 1
				nl = nl - 1
			}

			if i&2 == 1 {
				nu = nu - 1
				nr = nr - 1
			}

			if i&4 == 1 {
				nd = nd - 1
				nr = nr - 1
			}

			if i&8 == 1 {
				nd = nd - 1
				nl = nl - 1
			}

			if (nu >= 0 && nd >= 0 && nr >= 0 && nl >= 0) || (nu <= n-2 && nd <= n-2 && nr <= n-2 && nl <= n-2) {
				is_ok = true
				break
			}
		}

		if is_ok == true {
			printf("YES\n")
		} else {
			printf("NO\n")
		}
	}
}

package main

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

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

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

func main() {
	defer writer.Flush()

	var T int = 0
	scanf("%d\n", &T)

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

		var n, u, d, r, l int
		scanf("%d %d %d %d %d\n", &n, &u, &r, &d, &l)

		var is_ok bool = false
		for i := 1; i <= 15; i++ {
			var nu int = u
			var nr int = r
			var nd int = d
			var nl int = l

			if i&1 == 1 {
				nu = nu - 1
				nl = nl - 1
			}

			if i&2 == 1 {
				nu = nu - 1
				nr = nr - 1
			}

			if i&4 == 1 {
				nd = nd - 1
				nr = nr - 1
			}

			if i&8 == 1 {
				nd = nd - 1
				nl = nl - 1
			}

			if (nu > 0 && nd > 0 && nr > 0 && nl > 0) || (nu < n-2 && nd < n-2 && nr < n-2 && nl < n-2) {
				is_ok = true
				break
			}
		}

		if is_ok == true {
			printf("YES\n")
		} else {
			printf("NO\n")
		}
	}
}

package main

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

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

	var t, n, u, r, d, l int
	fmt.Fscan(in, &t)

	for ; t > 0; t-- {
		fmt.Fscan(in, &n, &u, &r, &d, &l)
		var minU, minR, minD, minL, minHor, minVer int
		if u == n {
			minR++
			minL++
		}
		if u == n-1 {
			minVer++
		}
		if d == n {
			minR++
			minL++
		}
		if d == n-1 {
			minVer++
		}
		if l == n {
			minU++
			minD++
		}
		if l == n-1 {
			minHor++
		}
		if r == n {
			minU++
			minD++
		}
		if r == n-1 {
			minHor++
		}
		if u >= minU && d >= minD && r >= minR && l >= minL && u+d >= minHor && l+r >= minVer {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}


In the lattice points of the coordinate line there are n radio stations, the i-th of which is described by three integers:  xi — the coordinate of the i-th station on the line,  ri — the broadcasting range of the i-th station,  fi — the broadcasting frequency of the i-th station. We will say that two radio stations with numbers i and j reach each other, if the broadcasting range of each of them is more or equal to the distance between them. In other words min(ri, rj) ≥ |xi - xj|.Let's call a pair of radio stations (i, j) bad if i < j, stations i and j reach each other and they are close in frequency, that is, |fi - fj| ≤ k.Find the number of bad pairs of radio stations.

The first line contains two integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 10) — the number of radio stations and the maximum difference in the frequencies for the pair of stations that reach each other to be considered bad. In the next n lines follow the descriptions of radio stations. Each line contains three integers xi, ri and fi (1 ≤ xi, ri ≤ 109, 1 ≤ fi ≤ 104) — the coordinate of the i-th radio station, it's broadcasting range and it's broadcasting frequency. No two radio stations will share a coordinate.

Output the number of bad pairs of radio stations.

package main

import (
	"bufio"
	"fmt"
	"math/rand"
	"os"
	"sort"
	"time"
)

func I(i ...interface{}) error {
	_, err := fmt.Fscan(r, i...)
	return err
}

func O(o ...interface{}) {
	fmt.Fprint(w, o...)
}

var (
	r *bufio.Reader
	w *bufio.Writer
)

func init() {
	if f, err := os.Open("in.goC"); err == nil {
		r = bufio.NewReader(f)
	} else {
		r = bufio.NewReader(os.Stdin)
	}
	w = bufio.NewWriter(os.Stdout)
}

func main() {
	var n int
	for I(&n) == nil {
		solve(n)
	}
	w.Flush()
}

func solve(n int) {
	rand.Seed(time.Now().Unix())
	k := readInt()
	in := make(arr, n)
	treap := make([]*Node, 1e4+10)
	for i := range treap {
		treap[i] = &Node{nil, 0, 100, 0, nil}
	}
	for i := 0; i < n; i++ {
		in[i][0], in[i][1], in[i][2] = readInt(), readInt(), readInt()
	}
	sort.Sort(in)
	var ans int64
	for i := 0; i < n; i++ {
		for j := max(1, in[i][2]-k); j <= min(1e4, in[i][2]+k); j++ {
			ans += int64(rank(treap[j], in[i][0]+in[i][1]+1)) - int64(rank(treap[j], in[i][0]-in[i][1]))
		}
		insert(treap[in[i][2]], in[i][0])
	}
	O(ans, "\n")
}

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

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

type arr [][3]int

func (a arr) Len() int           { return len(a) }
func (a arr) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a arr) Less(i, j int) bool { return a[i][1] > a[j][1] }

func readInt() int {
	var o bool
	var i int
	b, err := r.ReadByte()
	for err == nil {
		if b != ' ' && b != '\n' && b != '\r' {
			i = i*10 + int(b) - 48
			o = true
		} else if o {
			break
		}
		b, err = r.ReadByte()
	}
	return i
}

type Node struct {
	Left     *Node
	Value    int
	Priority int
	Count    int
	Right    *Node
}

func newNode(value int) *Node {
	return &Node{nil, value, rand.Intn(100), 1, nil}
}

func rightRotate(node *Node) *Node {
	res := node.Left
	node.Left = res.Right
	res.Right = node
	node.Count = count(node.Left) + count(node.Right) + 1
	res.Count = count(res.Left) + count(res.Right) + 1
	return res
}

func leftRotate(node *Node) *Node {
	res := node.Right
	node.Right = res.Left
	res.Left = node
	node.Count = count(node.Left) + count(node.Right) + 1
	res.Count = count(res.Left) + count(res.Right) + 1
	return res
}

func insert(node *Node, value int) *Node {
	if node == nil {
		return newNode(value)
	}
	node.Count++
	if node.Value > value {
		node.Left = insert(node.Left, value)
		if node.Left.Priority > node.Priority {
			node = rightRotate(node)
		}
		return node
	}
	node.Right = insert(node.Right, value)
	if node.Right.Priority > node.Priority {
		node = leftRotate(node)
	}
	return node
}

func count(node *Node) int {
	if node != nil {
		return node.Count
	}
	return 0
}

func rank(node *Node, value int) int {
	x := node
	r := 0
	for x != nil {
		if x.Value >= value {
			x = x.Left
		} else {
			r += count(x.Left) + 1
			x = x.Right
		}
	}
	if r != 0 {
		r--
	}
	return r
}

package main

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

func I(i ...interface{}) error {
	_, err := fmt.Fscan(r, i...)
	return err
}

func O(o ...interface{}) {
	fmt.Fprint(w, o...)
}

var (
	r *bufio.Reader
	w *bufio.Writer
)

func init() {
	if f, err := os.Open("in.goC"); err == nil {
		r = bufio.NewReader(f)
	} else {
		r = bufio.NewReader(os.Stdin)
	}
	w = bufio.NewWriter(os.Stdout)
}

func main() {
	defer w.Flush()
	var n int
	for I(&n) == nil {
		solve(n)
	}
}

func solve(n int) {
	var k int
	I(&k)
	in := make(arr, n)
	iin := make(arrr, n)
	for i := 0; i < n; i++ {
		I(&in[i][0], &in[i][1], &in[i][2])
	}
	sort.Sort(in)
	for i := 0; i < n; i++ {
		in[i][3] = sort.Search(n, func(z int) bool { return in[z][2]-in[i][2] > k })
	}
	copy(iin, in)
	sort.Sort(iin)
	var ans int64
	for i := 0; i < n; i++ {
		f := sort.Search(n, func(z int) bool { return iin[z][0]-iin[i][0] > iin[i][1] })
		if f < in[i][3] {
			for j := i + 1; j < f; j++ {
				if k >= abs(iin[i][2]-iin[j][2]) {
					ans++
				}
			}
		} else {
			for j := i + 1; j < in[i][3]; j++ {
				r := in[i][1]
				if r > in[j][1] {
					r = in[j][1]
				}
				if r >= abs(in[i][0]-in[j][0]) {
					ans++
				}
			}
		}
	}
	O(ans, "\n")
}

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

type arr [][4]int

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

type arrr [][4]int

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

package main

import (
	"bufio"
	"fmt"
	"math/rand"
	"os"
	"sort"
	"time"
)

func I(i ...interface{}) error {
	_, err := fmt.Fscan(r, i...)
	return err
}

func O(o ...interface{}) {
	fmt.Fprint(w, o...)
}

var (
	r *bufio.Reader
	w *bufio.Writer
)

func init() {
	if f, err := os.Open("in.goC"); err == nil {
		r = bufio.NewReader(f)
	} else {
		r = bufio.NewReader(os.Stdin)
	}
	w = bufio.NewWriter(os.Stdout)
}

func main() {
	var n int
	for I(&n) == nil {
		solve(n)
	}
	w.Flush()
}

func solve(n int) {
	rand.Seed(time.Now().Unix())
	k := readInt()
	in := make(arr, n)
	treap := make([]*Node, 1e4+10)
	for i := range treap {
		treap[i] = &Node{nil, 0, 100, 0, nil}
	}
	for i := 0; i < n; i++ {
		in[i][0], in[i][1], in[i][2] = readInt(), readInt(), readInt()
	}
	sort.Sort(in)
	var ans int
	for i := 0; i < n; i++ {
		for j := max(1, in[i][2]-k); j <= min(1e4, in[i][2]+k); j++ {
			ans += rank(treap[j], in[i][0]+in[i][1]+1) - rank(treap[j], in[i][0]-in[i][1])
		}
		insert(treap[in[i][2]], in[i][0])
	}
	O(ans, "\n")
}

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

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

type arr [][3]int

func (a arr) Len() int           { return len(a) }
func (a arr) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a arr) Less(i, j int) bool { return a[i][1] > a[j][1] }

func readInt() int {
	var o bool
	var i int
	b, err := r.ReadByte()
	for err == nil {
		if b != ' ' && b != '\n' && b != '\r' {
			i = i*10 + int(b) - 48
			o = true
		} else if o {
			break
		}
		b, err = r.ReadByte()
	}
	return i
}

type Node struct {
	Left     *Node
	Value    int
	Priority int
	Count    int
	Right    *Node
}

func newNode(value int) *Node {
	return &Node{nil, value, rand.Intn(100), 1, nil}
}

func rightRotate(node *Node) *Node {
	res := node.Left
	node.Left = res.Right
	res.Right = node
	node.Count = count(node.Left) + count(node.Right) + 1
	res.Count = count(res.Left) + count(res.Right) + 1
	return res
}

func leftRotate(node *Node) *Node {
	res := node.Right
	node.Right = res.Left
	res.Left = node
	node.Count = count(node.Left) + count(node.Right) + 1
	res.Count = count(res.Left) + count(res.Right) + 1
	return res
}

func insert(node *Node, value int) *Node {
	if node == nil {
		return newNode(value)
	}
	node.Count++
	if node.Value > value {
		node.Left = insert(node.Left, value)
		if node.Left.Priority > node.Priority {
			node = rightRotate(node)
		}
		return node
	}
	node.Right = insert(node.Right, value)
	if node.Right.Priority > node.Priority {
		node = leftRotate(node)
	}
	return node
}

func count(node *Node) int {
	if node != nil {
		return node.Count
	}
	return 0
}

func rank(node *Node, value int) int {
	x := node
	r := 0
	for x != nil {
		if x.Value >= value {
			x = x.Left
		} else {
			r += count(x.Left) + 1
			x = x.Right
		}
	}
	if r != 0 {
		r--
	}
	return r
}


You are given $$$n$$$ segments $$$[l_1, r_1], [l_2, r_2], \dots, [l_n, r_n]$$$. Each segment has one of two colors: the $$$i$$$-th segment's color is $$$t_i$$$.Let's call a pair of segments $$$i$$$ and $$$j$$$ bad if the following two conditions are met:  $$$t_i \ne t_j$$$;  the segments $$$[l_i, r_i]$$$ and $$$[l_j, r_j]$$$ intersect, embed or touch, i. e. there exists an integer $$$x$$$ such that $$$x \in [l_i, r_i]$$$ and $$$x \in [l_j, r_j]$$$. Calculate the maximum number of segments that can be selected from the given ones, so that there is no bad pair among the selected ones.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of segments. The next $$$n$$$ lines contains three integers $$$l_i, r_i, t_i$$$ ($$$1 \le l_i \le r_i \le 10^9; t_i \in \{1, 2\}$$$) — description of the $$$i$$$-th segment.

Print the maximum number of segments that can be selected, so that there is no bad pair among the selected segments.

package main

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

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

	type Event struct {
		l, r, t, i, x int
	}
	type End struct {
		r, i int
	}

	n := io.NextInt()
	var ev []Event
	for i := 0; i < n; i++ {
		l, r, t := io.NextInt(), io.NextInt()+1, io.NextInt()-1
		ev = append(ev, Event{l, r, t, i, l}, Event{l, r, t, i, r})
	}
	sort.Slice(ev, func(i, j int) bool {
		a, b := ev[i], ev[j]
		if a.x != b.x {
			return a.x < b.x
		}
		return a.x == a.r && b.x != b.r
	})

	cmp := func(i, j interface{}) bool { return i.(End).r < j.(End).r }
	h := []Heap{{Les: cmp}, {Les: cmp}}
	rem := make([]bool, n)
	ans := n
	for _, e := range ev {
		if e.x == e.l {
			h[e.t].HPush(End{e.r, e.i})
		} else if !rem[e.i] {
			rem[e.i] = true
			for h[e.t^1].Len() > 0 {
				i := h[e.t^1].HPop().(End).i
				if !rem[i] {
					rem[i] = true
					ans--
					break
				}
			}
		}
	}

	io.Println(ans)
}

type Heap struct {
	Les func(_, _ interface{}) bool
	h   []interface{}
}

func (h Heap) Len() int           { return len(h.h) }
func (h Heap) Less(i, j int) bool { return h.Les(h.h[i], h.h[j]) }
func (h Heap) Swap(i, j int)      { h.h[i], h.h[j] = h.h[j], h.h[i] }

func (h *Heap) Push(x interface{}) {
	h.h = append(h.h, x)
}

func (h *Heap) Pop() interface{} {
	x := h.h[h.Len()-1]
	h.h = h.h[:h.Len()-1]
	return x
}

func (h *Heap) HPush(x interface{}) {
	heap.Push(h, x)
}

func (h *Heap) HPop() interface{} {
	return heap.Pop(h)
}

type FastIO struct {
	*bufio.Reader
	*bufio.Writer
	c [1]byte
}

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

func (f *FastIO) readC() byte {
	f.Read(f.c[:])
	return f.c[0]
}

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) Println(a ...interface{}) {
	fmt.Fprintln(f, a...)
}

package main

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

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

	type Seg struct {
		l, r, t int
	}

	n := io.NextInt()
	a := make([]Seg, n)
	x := []int{-1}
	for i := 0; i < n; i++ {
		a[i] = Seg{io.NextInt(), io.NextInt(), io.NextInt() - 1}
		x = append(x, a[i].l, a[i].r)
	}

	sort.Ints(x)
	lx := len(x)
	idx := func(v int) int { return sort.Search(lx, func(i int) bool { return v <= x[i] }) }
	e := make([][]Seg, lx)
	for _, s := range a {
		s.l, s.r = idx(s.l), idx(s.r)
		e[s.r] = append(e[s.r], s)
	}

	st := []*SegTree{NewSegTree(lx), NewSegTree(lx)}
	for i, ss := range e {
		for _, s := range ss {
			st[s.t].Update(0, s.l, 1)
		}
		c := max(st[0].Query(0, i), st[1].Query(0, i))
		st[0].Update(i, i+1, c)
		st[1].Update(i, i+1, c)
	}

	ans := max(st[0].Query(0, lx), st[1].Query(0, lx))
	io.Println(ans)
}

type SegTree struct {
	n    int
	data []int
	lazy []int
}

func NewSegTree(n int) *SegTree           { return &SegTree{n, make([]int, 4*n), make([]int, 4*n)} }
func (t *SegTree) Update(l, r int, v int) { t.update(1, 0, t.n, l, r, v) }
func (t *SegTree) Query(l, r int) int     { return t.query(1, 0, t.n, l, r) }

func (t *SegTree) get(i int) int { return t.data[i] + t.lazy[i] }

func (t *SegTree) update(i, s, e, l, r int, v int) {
	if e <= l || r <= s {
		return
	}
	if l <= s && e <= r {
		t.lazy[i] += v
		return
	}
	m := (s + e) / 2
	t.update(i*2, s, m, l, r, v)
	t.update(i*2+1, m, e, l, r, v)
	t.data[i] = max(t.get(i*2), t.get(i*2+1))
}

func (t *SegTree) query(i, s, e, l, r int) int {
	if e <= l || r <= s {
		return 0
	}
	if l <= s && e <= r {
		return t.get(i)
	}
	m := (s + e) / 2
	return t.lazy[i] + max(t.query(i*2, s, m, l, r), t.query(i*2+1, m, e, l, r))
}

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

type FastIO struct {
	*bufio.Reader
	*bufio.Writer
	c [1]byte
}

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

func (f *FastIO) readC() byte {
	f.Read(f.c[:])
	return f.c[0]
}

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) Println(a ...interface{}) {
	fmt.Fprintln(f, a...)
}


The determinant of a matrix 2 × 2 is defined as follows:A matrix is called degenerate if its determinant is equal to zero. The norm ||A|| of a matrix A is defined as a maximum of absolute values of its elements.You are given a matrix . Consider any degenerate matrix B such that norm ||A - B|| is minimum possible. Determine ||A - B||.

The first line contains two integers a and b (|a|, |b| ≤ 109), the elements of the first row of matrix A.  The second line contains two integers c and d (|c|, |d| ≤ 109) the elements of the second row of matrix A.

Output a single real number, the minimum possible value of ||A - B||. Your answer is considered to be correct if its absolute or relative error does not exceed 10 - 9.

NoteIn the first sample matrix B is In the second sample matrix B is

package main

import (
    "fmt"
    "math"
    "sort"
)

func makeRange(x, a, b float64) []float64 {
    values := []float64 {(a - x) * (b - x), (a - x) * (b + x), (a + x) * (b - x), (a + x) * (b + x)}
    sort.Float64s(values)

    ans := make([]float64, 0)
    ans = append(ans, values[0])
    ans = append(ans, values[len(values) - 1])
    return ans
}

func ok(mid, a, b, c, d float64) bool {
    r1 := makeRange(mid, a, d)
    r2 := makeRange(mid, b, c)
    if math.Max(r1[0], r2[0]) <= math.Min(r1[1], r2[1]) {
        return true
    } else {
        return false
    }
}

func main() {
    var a, b, c, d float64
    fmt.Scan(&a, &b, &c, &d)
    low, high := 0.0, 1e9
    for i := 0; i < 200; i++ {
        mid := (low + high)/2
        if ok(mid, a, b, c, d) {
            high = mid
        } else {
            low = mid
        }
    }
    fmt.Println(low)
}

package main

import (
    "fmt"
    "math"
)

func makeRange(x, a, b float64) []float64 {
    ans := make([]float64, 0)
    p := math.Min((a - x) * (b - x), (a - x) * (b + x))
    p = math.Min(p, (a + x) * (b - x))
    p = math.Min(p, (a + x) * (b + x))
    ans = append(ans, p)

    q := math.Max((a - x) * (b - x), (a - x) * (b + x))
    q = math.Max(p, (a + x) * (b - x))
    q = math.Max(p, (a + x) * (b + x))
    ans = append(ans, q)

    return ans
}

func ok(mid, a, b, c, d float64) bool {
    r1 := makeRange(mid, a, d)
    r2 := makeRange(mid, b, c)
    if r1[1] < r2[0] || r2[1] < r1[0] {
        return false
    } else {
        return true
    }
}

func main() {
    var a, b, c, d float64
    fmt.Scan(&a, &b, &c, &d)
    low, high := 0.0, 1e9
    for i := 0; i < 200; i++ {
        mid := (low + high)/2
        if ok(mid, a, b, c, d) {
            high = mid
        } else {
            low = mid
        }
    }
    fmt.Println(low)
}


Phoenix has a string $$$s$$$ consisting of lowercase Latin letters. He wants to distribute all the letters of his string into $$$k$$$ non-empty strings $$$a_1, a_2, \dots, a_k$$$ such that every letter of $$$s$$$ goes to exactly one of the strings $$$a_i$$$. The strings $$$a_i$$$ do not need to be substrings of $$$s$$$. Phoenix can distribute letters of $$$s$$$ and rearrange the letters within each string $$$a_i$$$ however he wants.For example, if $$$s = $$$ baba and $$$k=2$$$, Phoenix may distribute the letters of his string in many ways, such as:   ba and ba  a and abb  ab and ab  aa and bb But these ways are invalid:   baa and ba  b and ba  baba and empty string ($$$a_i$$$ should be non-empty) Phoenix wants to distribute the letters of his string $$$s$$$ into $$$k$$$ strings $$$a_1, a_2, \dots, a_k$$$ to minimize the lexicographically maximum string among them, i. e. minimize $$$max(a_1, a_2, \dots, a_k)$$$. Help him find the optimal distribution and print the minimal possible value of $$$max(a_1, a_2, \dots, a_k)$$$.String $$$x$$$ is lexicographically less than string $$$y$$$ if either $$$x$$$ is a prefix of $$$y$$$ and $$$x \ne y$$$, or there exists an index $$$i$$$ ($$$1 \le i \le min(|x|, |y|))$$$ such that $$$x_i$$$ < $$$y_i$$$ and for every $$$j$$$ $$$(1 \le j < i)$$$ $$$x_j = y_j$$$. Here $$$|x|$$$ denotes the length of the string $$$x$$$.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case consists of two lines. The first line of each test case consists of two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^5$$$) — the length of string $$$s$$$ and the number of non-empty strings, into which Phoenix wants to distribute letters of $$$s$$$, respectively. The second line of each test case contains a string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ over all test cases is $$$\le 10^5$$$.

Print $$$t$$$ answers — one per test case. The $$$i$$$-th answer should be the minimal possible value of $$$max(a_1, a_2, \dots, a_k)$$$ in the $$$i$$$-th test case.

6
4 2
baba
5 2
baacb
5 3
baacb
5 3
aaaaa
6 4
aaxxzz
7 1
phoenix

NoteIn the first test case, one optimal solution is to distribute baba into ab and ab. In the second test case, one optimal solution is to distribute baacb into abbc and a.In the third test case, one optimal solution is to distribute baacb into ac, ab, and b.In the fourth test case, one optimal solution is to distribute aaaaa into aa, aa, and a.In the fifth test case, one optimal solution is to distribute aaxxzz into az, az, x, and x.In the sixth test case, one optimal solution is to distribute phoenix into ehinopx.

package main

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

var reader io.Reader
var scanner *bufio.Scanner

func Init(io io.Reader, max_token_size int) {
	reader = bufio.NewReader(io)
	scanner = bufio.NewScanner(reader)
	// max token size
	scanner.Split(bufio.ScanWords)
	scanner.Buffer([]byte{}, max_token_size)
}

func stderr(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
}

func die(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
	os.Exit(1)
}

func NextInt() int {
	bytes := NextBytes()
	i, err := Atoi(bytes)
	if err != nil {
		die(err)
	}
	return i
}
func NextInt64() int64 {
	bytes := NextBytes()
	i, err := Atoi64(bytes)
	if err != nil {
		die(err)
	}
	return i
}

func NextBytes() []byte {
	if !scanner.Scan() {
		die(scanner.Err())
	}
	bytes := scanner.Bytes()
	copied := make([]byte, len(bytes))
	copy(copied, bytes)
	return copied
}

func Atoi(b []byte) (int, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	n := 0
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func Atoi64(b []byte) (int64, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	var n int64
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int64(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func ExtendByteArray(a []byte, size int) []byte {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]byte, size-len(a))...)
	}
}

func ExtendIntArray(a []int, size int) []int {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]int, size-len(a))...)
	}
}

func reverseInts(a []int) {
	for l, r := 0, len(a)-1; l < r; l, r = l+1, r-1 {
		a[l], a[r] = a[r], a[l]
	}
}

func unique(a []int) int {
	newLen := 0
	n := len(a)
	for i := 0; i < n; i++ {
		if newLen == 0 || a[i] != a[newLen-1] {
			a[newLen] = a[i]
			newLen++
		}
	}
	return newLen
}

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

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

func main() {
	inf := os.Stdin
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	// inf, err := os.Open("a.in")
	// if err != nil {
	// 	die(err)
	// }
	// out, err := os.Create("a.out")
	// if err != nil {
	// 	die(err)
	// }
	// defer out.Close()
	Init(inf, 1000010)

	T := NextInt()
	c := make([]int, 26)

	for t := 0; t < T; t++ {
		n, k := NextInt(), NextInt()
		s := NextBytes()
		for i := 0; i < 26; i++ {
			c[i] = 0
		}
		for i := 0; i < n; i++ {
			c[s[i]-'a']++
		}
		filled := 0
		for i := 0; i < 26; i++ {
			if c[i] == 0 {
				continue
			}
			if filled < k {
				if filled+c[i] >= k {
					if filled > 0 {
						fmt.Fprint(out, string(byte('a'+i)))
						break
					} else {
						fmt.Fprint(out, string(byte('a'+i)))
						filled += k
						c[i] -= k
					}
				} else {
					filled += c[i]
					continue
				}
			}
			if c[i] == 0 {
				continue
			}
			if filled+c[i] < n {
				for j := 0; j < c[i]; j++ {
					fmt.Fprint(out, string(byte('a'+i)))
				}
				k = 1
			} else {
				l := c[i] / k
				r := c[i] % k
				for j := 0; j < l; j++ {
					fmt.Fprint(out, string(byte('a'+i)))
				}
				if r != 0 {
					fmt.Fprint(out, string(byte('a'+i)))
				}
			}
			filled += c[i]
		}
		fmt.Fprintln(out)
	}

}

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

package main

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

/********** 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 (
	// General purpose
	MOD          = 1000000000 + 7
	ALPHABET_NUM = 26
	INF_INT64    = math.MaxInt64
	INF_BIT60    = 1 << 60
	INF_INT32    = math.MaxInt32
	INF_BIT30    = 1 << 30
	NIL          = -1

	// for dijkstra, prim, and so on
	WHITE = 0
	GRAY  = 1
	BLACK = 2
)

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

var (
	t int
)

func main() {
	t = ReadInt()
	for i := 0; i < t; i++ {
		n, k := ReadInt2()
		S := ReadRuneSlice()
		solve(n, k, S)
	}
}

func solve(n, k int, S []rune) {
	tmp := Char{}
	for _, r := range S {
		tmp = append(tmp, r)
	}
	sort.Stable(tmp)

	T := []rune{}
	for i := 0; i < len(tmp); i++ {
		T = append(T, rune(tmp[i]))
	}

	if T[0] != T[k-1] {
		fmt.Printf("%c\n", T[k-1])
		return
	}

	if T[0] == T[n-1] {
		num := Kiriage(n, k)
		for i := 0; i < num; i++ {
			fmt.Printf("%c", T[0])
		}
		fmt.Printf("\n")
		return
	}

	if T[k] == T[n-1] {
		num := Kiriage(n-k, k)
		fmt.Printf("%c", T[0])
		for i := 0; i < num; i++ {
			fmt.Printf("%c", T[k])
		}
		fmt.Printf("\n")
		return
	}

	fmt.Printf("%s\n", string(T[k-1:n]))

	// fmt.Println(string(T[k-1 : n]))
	// for i := 0; i+k-1 < n; i += k {
	// 	if T[i] == T[i+k-1] {
	// 		fmt.Printf("%c", T[i])
	// 	} else {
	// 		fmt.Printf("%s\n", string(T[i:n]))
	// 		return
	// 	}
	// }
	// fmt.Printf("\n")
}

// Kiriage returns Ceil(a/b)
// a >= 0, b > 0
func Kiriage(a, b int) int {
	return (a + (b - 1)) / b
}

type Char []rune

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

// S := Char{'a', 'b', 'c'}
// sort.Sort(S) or sort.Sort(sort.Reverse(S))

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

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

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

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

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

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

// 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])
		res = append(res, []rune(str)...)

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

	return string(res)
}

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

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

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

	return string(res)
}

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

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

package main

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

// github.com/EndlessCheng/codeforces-go
func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	var T, n, k int
	var b []byte
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &k, &b)
		sort.Slice(b, func(i, j int) bool { return b[i] < b[j] })
		if s := string(b); s[k-1] != s[0] {
			Fprintln(out, string(s[k-1]))
		} else if k == n || s[k] != s[n-1] {
			Fprintln(out, s[k-1:])
		} else {
			Fprintln(out, s[:1]+strings.Repeat(s[n-1:], (n-1)/k))
		}
	}
}

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-- {
		_, k := reader.NextInt64(), reader.NextInt64()
		s := reader.NextString()
		writer.Printf("%s\n", sol(s, k))
	}
}

func sol(s string, k int64) string {
	runes := []rune(s)
	sort.Slice(runes, func(a, b int) bool {
		return runes[a] < runes[b]
	})
	ans := make([][]rune, k)
	for i := int64(0); i < k; i++ {
		ans[i] = append(ans[i], runes[i])
	}
	remainCount := count(runes[k:])
	if remainCount == 1 {
		remainEle := int64(len(s)) - k
		var numToAppend int64
		if remainEle % k == 0 {
			numToAppend = remainEle / k
		} else {
			numToAppend = remainEle / k + 1
		}
		for i := int64(0); i < numToAppend; i++ {
			ans[0] = append(ans[0], runes[k])
		}
		first := string(ans[0])
		last := string(ans[len(ans)-1])
		if last > first {
			return last
		}
		return first
	}
	for i := k; i < int64(len(runes)); i++ {
		ans[0] = append(ans[0], runes[i])
	}
	first := string(ans[0])
	last := string(ans[len(ans)-1])
	if last > first {
		return last
	}
	return first
}

func count(runes []rune) int64 {
	m := map[rune]bool{}
	for _, r := range runes {
		m[r] = true
	}
	return int64(len(m))
}

func debug(runes [][]rune) {
	for _, r := range runes {
		writer.Printf("debug: %s \n", string(r))
	}
}

package main

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

var reader io.Reader
var scanner *bufio.Scanner

func Init(io io.Reader, max_token_size int) {
	reader = bufio.NewReader(io)
	scanner = bufio.NewScanner(reader)
	// max token size
	scanner.Split(bufio.ScanWords)
	scanner.Buffer([]byte{}, max_token_size)
}

func stderr(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
}

func die(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
	os.Exit(1)
}

func NextInt() int {
	bytes := NextBytes()
	i, err := Atoi(bytes)
	if err != nil {
		die(err)
	}
	return i
}
func NextInt64() int64 {
	bytes := NextBytes()
	i, err := Atoi64(bytes)
	if err != nil {
		die(err)
	}
	return i
}

func NextBytes() []byte {
	if !scanner.Scan() {
		die(scanner.Err())
	}
	bytes := scanner.Bytes()
	copied := make([]byte, len(bytes))
	copy(copied, bytes)
	return copied
}

func Atoi(b []byte) (int, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	n := 0
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func Atoi64(b []byte) (int64, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	var n int64
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int64(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func ExtendByteArray(a []byte, size int) []byte {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]byte, size-len(a))...)
	}
}

func ExtendIntArray(a []int, size int) []int {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]int, size-len(a))...)
	}
}

func reverseInts(a []int) {
	for l, r := 0, len(a)-1; l < r; l, r = l+1, r-1 {
		a[l], a[r] = a[r], a[l]
	}
}

func unique(a []int) int {
	newLen := 0
	n := len(a)
	for i := 0; i < n; i++ {
		if newLen == 0 || a[i] != a[newLen-1] {
			a[newLen] = a[i]
			newLen++
		}
	}
	return newLen
}

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

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

func main() {
	inf := os.Stdin
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	// inf, err := os.Open("a.in")
	// if err != nil {
	// 	die(err)
	// }
	// out, err := os.Create("a.out")
	// if err != nil {
	// 	die(err)
	// }
	// defer out.Close()
	Init(inf, 1000010)

	T := NextInt()
	c := make([]int, 26)

	for t := 0; t < T; t++ {
		n, k := NextInt(), NextInt()
		s := NextBytes()
		for i := 0; i < 26; i++ {
			c[i] = 0
		}
		for i := 0; i < n; i++ {
			c[s[i]-'a']++
		}
		filled := 0
		firstchars := 0
		for i := 0; i < 26; i++ {
			if filled < k {
				if filled+c[i] >= k {
					if filled > 0 {
						fmt.Fprint(out, string(byte('a'+i)))
						break
					} else {
						fmt.Fprint(out, string(byte('a'+i)))
						filled += k
						c[i] -= k
					}
				} else {
					filled += c[i]
					firstchars++
					continue
				}
			}
			if filled+c[i] < n {
				for j := 0; j < c[i]; j++ {
					fmt.Fprint(out, string(byte('a'+i)))
				}
			} else {
				l := c[i] / k
				r := c[i] % k
				for j := 0; j < l; j++ {
					fmt.Fprint(out, string(byte('a'+i)))
				}
				if r != 0 {
					fmt.Fprint(out, string(byte('a'+i)))
				}
			}
			filled += c[i]
		}
		fmt.Fprintln(out)
	}

}


Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items.

In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week).

Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now.

NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25.

package main

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

func main() {
	var n, k int
	if _, err := fmt.Scanf("%d %d\n", &n, &k); err != nil {
		return
	}

	ab := make([][2]int, n)

	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for j := 0; j < 2; j++ {
		for i := 0; i < n && scanner.Scan(); i++ {
			_in, err := strconv.Atoi(scanner.Text())
			if err != nil {
				return
			}
			ab[i][j] = _in
		}
	}

	merge_sort(ab, 0, n-1)

	money := 0
	for i := 0; i < n; i++ {
		if i < k {
			money += ab[i][0]
		} else if ab[i][0]-ab[i][1] < 0 {
			money += ab[i][0]
		} else {
			money += ab[i][1]
		}
	}
	fmt.Println(money)
}

func le(a, b [2]int) bool {
	return (a[0] - a[1]) <= (b[0] - b[1])
}

func merge(buffer [][2]int, start, middle, end int) {
	sorted := make([][2]int, end-start+1)

	i := start
	j := middle + 1
	k := 0
	for i <= middle && j <= end {
		if le(buffer[i], buffer[j]) {
			sorted[k] = buffer[i]
			i++
		} else {
			sorted[k] = buffer[j]
			j++
		}
		k++
	}
	for i <= middle {
		sorted[k] = buffer[i]
		k++
		i++
	}
	for j <= end {
		sorted[k] = buffer[j]
		k++
		j++
	}

	i = start
	k = 0
	for i <= end {
		buffer[i] = sorted[k]
		i++
		k++
	}
}

func merge_sort(buffer [][2]int, start, end int) {
	if end > start {
		middle := (end + start) / 2
		merge_sort(buffer, start, middle)
		merge_sort(buffer, middle+1, end)
		merge(buffer, start, middle, end)
	}
}

package main

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

var stdReader *bufio.Reader = bufio.NewReader(os.Stdin)

func readInt() (result int) {
	var negative, started bool
READER_LOOP:
	for {
		char, err := stdReader.ReadByte()
		switch {
		case err != nil:
			break READER_LOOP
		case char == '-':
			negative = true
		case unicode.IsDigit(rune(char)):
			started = true
			result = result*10 + int(char&0xf)
		case started:
			break READER_LOOP
		}
	}
	if negative {
		result = -result
	}
	return
}

func main() {
	n, k := readInt(), readInt()
	a := make([]int, n)
	for i := range a {
		a[i] = readInt()
	}
	var d []int
	var total, bought int
	for _, ai := range a {
		bi := readInt()
		if ai <= bi {
			total += ai
			bought++
		} else {
			total += bi
			d = append(d, ai-bi)
		}
	}
	sort.Ints(d)
	for i := 0; bought < k; i++ {
		total += d[i]
		bought++
	}
	fmt.Println(total)
}

package main

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

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

const (
	//MaxScanTokenSize = 64 * 1024 // package default
	MaxScanTokenSize = 8 * 1024 * 1024 // 8M
)

func init() {
	scanner.Buffer(make([]byte, 0, MaxScanTokenSize), MaxScanTokenSize)
	scanner.Split(bufio.ScanWords)
}

func readString() string {
	scanner.Scan()
	return scanner.Text()
}

func readInt() int {
	val, _ := strconv.Atoi(readString())
	return val
}

func readInt64() int64 {
	v, _ := strconv.ParseInt(readString(), 10, 64)
	return v
}

func readIntArray(size int) []int {
	a := make([]int, size)
	for i := 0; i < size; i++ {
		a[i] = readInt()
	}
	return a
}

func readInt64Array(n int) []int64 {
	res := make([]int64, n)
	for i := 0; i < n; i++ {
		res[i] = readInt64()
	}
	return res
}

func readFloat64() float64 {
	v, _ := strconv.ParseFloat(readString(), 64)
	return v
}

func readFloat64Array(n int) []float64 {
	res := make([]float64, n)
	for i := 0; i < n; i++ {
		res[i] = readFloat64()
	}
	return res
}

func main() {
	defer writer.Flush()

	n, k := readInt(), readInt()
	pre := readIntArray(n)
	aft := readIntArray(n)
	diff := make([]int, n, n)
	total := 0
	for i := 0; i < n; i++ {
		diff[i] = aft[i] - pre[i]
		total += pre[i]
	}
	sort.Sort(sort.Reverse(sort.IntSlice(diff)))
	//for i := 0; i < n; i++ {
	//	fmt.Printf("[%d] %d\n", i, diff[i])
	//}

	save := 0
	for i := 0; i < n; i++ {
		if i < k || diff[i] > 0 {
			continue
		} else {
			save += diff[i]
		}
	}
	total += save
	fmt.Fprintf(writer, "%d\n", total)
}

package main

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

var writer *bufio.Writer
var scanner *bufio.Scanner

type MySlice [][2]int

func (slice MySlice) Len() int           { return len(slice) }
func (slice MySlice) Less(i, j int) bool { return slice[i][1] < slice[j][1] }
func (slice MySlice) Swap(i, j int) {
	slice[i], slice[j] = slice[j], slice[i]
}

func main() {
	ini()
	defer writer.Flush()

	n := scanInt()
	k := scanInt()
	k++
	var a [200000]int
	var b MySlice

	for i:=0;i<n;i++ {
		a[i] = scanInt()
	}

	var temp [2]int
	for i:=0;i<n;i++ {
		temp[0] = i
		temp[1] = a[i] - scanInt()
		b = append(b, temp)
	}

	sort.Sort(b)
	//
	//for i:=0; i<n;i++ {
	//	writer.WriteString(strconv.Itoa(b[i][0]))
	//}
	//writer.WriteString("\n")
	//for i:=0; i<n;i++ {
	//	writer.WriteString(strconv.Itoa(b[i][1]))
	//}
	//writer.WriteString("\n")

	kt := 1
	result := 0
	for i:=0; i<n; i++ {
		if kt < k || b[i][1] < 0 {
			result += a[b[i][0]]
			kt++
			//writer.WriteString("1\n")
		} else {
			result += a[b[i][0]] - b[i][1]
			//writer.WriteString("2\n")
		}
	}

	writer.WriteString(strconv.Itoa(result))

	return

}

func ini() {
	scanner = bufio.NewScanner(os.Stdin)
	writer = bufio.NewWriter(os.Stdout)
	scanner.Split(bufio.ScanWords)
}

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

func scanString() string {
	scanner.Scan()
	return scanner.Text()
}