You are given string $$$s$$$ of length $$$n$$$ consisting of 0-s and 1-s. You build an infinite string $$$t$$$ as a concatenation of an infinite number of strings $$$s$$$, or $$$t = ssss \dots$$$ For example, if $$$s =$$$ 10010, then $$$t =$$$ 100101001010010...Calculate the number of prefixes of $$$t$$$ with balance equal to $$$x$$$. The balance of some string $$$q$$$ is equal to $$$cnt_{0, q} - cnt_{1, q}$$$, where $$$cnt_{0, q}$$$ is the number of occurrences of 0 in $$$q$$$, and $$$cnt_{1, q}$$$ is the number of occurrences of 1 in $$$q$$$. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".

The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. Next $$$2T$$$ lines contain descriptions of test cases — two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$-10^9 \le x \le 10^9$$$) — the length of string $$$s$$$ and the desired balance, respectively. The second line contains the binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{\text{0}, \text{1}\}$$$). 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 number of prefixes or $$$-1$$$ if there is an infinite number of such prefixes.

NoteIn the first test case, there are 3 good prefixes of $$$t$$$: with length $$$28$$$, $$$30$$$ and $$$32$$$.

package main

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

//•*¨*•.¸¸♪I/O•*¨*•.¸¸♪

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

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

func scanInt64() int64 {
	sc.Scan()
	a,_ := strconv.ParseInt(sc.Text(),10,64)
	return a
}

func scanFloat64() float64 {
	sc.Scan()
	a,_ := strconv.Atoi(sc.Text())
	return float64(a)
}

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

func scanText() string {
	sc.Scan()
	return sc.Text()
}

func printInts(a ...int) {
	for i, e := range a {
		fmt.Fprint(wr, e)
		if i != len(a)-1 { fmt.Fprint(wr, " ") }
	}
	fmt.Fprintln(wr)
	wr.Flush()
}

//•*¨*•.¸¸♪Main•*¨*•.¸¸♪(　-ω-)ノ　(　・ω・)

func main() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 10000), 100000000)

	t := scanInt()

	L: for i := 0; i < t; i++ {
		n := scanInt()
		x := scanInt()
		s := scanText()

		c0,c1 := 0,0

		for j := 0; j < n; j++ {
			if s[j] == '0' {
				c0++
			} else {
				c1++
			}
		}

		a,b := 0,0
		ans := 0

		f := false
		if c0 == c1 {
			f = true
		}

		if x == 0 {
			ans++
		}

		// if !f && x == c0-c1 {
		// 	ans++
		// }

		for j := 0; j < n; j++ {
			if s[j] == '0' {
				a++
			} else {
				b++
			}

			if f && a-b == x {
				fmt.Println(-1)
				continue L
			}

			if !f && (x-a+b)%(c0-c1) == 0 && (x-a+b)/(c0-c1) >= 0 {
				ans++
			}
		}

		fmt.Println(ans)
	}
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1295B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	moveToRange := func(st, d, l, r int) (firstPos int, ok bool) {
		switch {
		case st < l:
			if d < 0 {
				return
			}
			return l + ((st-l)%d+d)%d, true
		case st <= r:
			return st, true
		default:
			if d > 0 {
				return
			}
			return r + ((st-r)%d+d)%d, true
		}
	}

	var t, n, x int
	var s []byte
	solve := func() (ans int) {
		cnts := map[int]int{0: 1}
		d, l, r := 0, 0, 0
		for i, b := range s {
			if b == '0' {
				d++
				if d > r {
					r = d
				}
			} else {
				d--
				if d < l {
					l = d
				}
			}
			if i+1 < n {
				cnts[d]++
			}
		}
		if d == 0 {
			if c, ok := cnts[x]; ok && c > 0 {
				return -1
			}
		} else if x, ok := moveToRange(x, -d, l, r); ok {
			for ; x >= l && x <= r; x -= d {
				ans += cnts[x]
			}
		}
		return
	}
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n, &x, &s)
		Fprintln(out, solve())
	}
}

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

package main

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

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

// IO helper functions

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// IO functions

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

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

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

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

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

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

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

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

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

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

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

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

// Simple math functions

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

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

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

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

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

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

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

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

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

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

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

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

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

func main() {
	defer Flush()

	T := readi()
	for i := 0; i < T; i++ {
		n := readi()
		x := readi()
		s := reads()
		println(solve(n, x, s))
	}
}

func solve(n, x int, s string) int {
	// 010010
	// 101212
	var v int
	m := make([]int, n)
	for i, c := range s {
		if c == '0' {
			v++
		} else {
			v--
		}
		m[i] = v
	}

	if v == 0 {
		for _, a := range m {
			if a == x {
				return -1
			}
		}
		return 0
	}

	var ans int
	if x == 0 {
		ans++
	}
	// q * v + a = x
	// q * v  = x-a
	// q = (x-a)/v
	for _, a := range m {
		q := (x - a) / v
		if 0 <= q && q*v+a == x {
			ans++
		}
	}

	return ans
}

package main

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

const N = 100010
var n int
var nt, x int
var s string
var a[N] int

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

		for i := 1; i <= n; i++ {
			var value = int(s[i - 1] - '0')
			a[i] = a[i - 1]
			if value == 0 {
				a[i]++
			} else {
				a[i]--
			}
		}
		var ret = 0

		if x == 0 {
			ret++
		}

		var circle = a[n]
		for i := 1; i <= n; i++ {
			var need = x - a[i]

			if circle == 0 && need == 0 {
				ret = -1
				break
			}

			if circle == 0 {
				continue
			}

			var mul = need / circle
			if mul >= 0 && mul * circle == need {
				//fmt.Println("work at... ", i)
				ret++
			}
		}

		fmt.Fprintf(writer, "%d\n", ret)
	}
}

package main

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

//•*¨*•.¸¸♪I/O•*¨*•.¸¸♪

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

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

func scanInt64() int64 {
	sc.Scan()
	a,_ := strconv.ParseInt(sc.Text(),10,64)
	return a
}

func scanFloat64() float64 {
	sc.Scan()
	a,_ := strconv.Atoi(sc.Text())
	return float64(a)
}

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

func scanText() string {
	sc.Scan()
	return sc.Text()
}

func printInts(a ...int) {
	for i, e := range a {
		fmt.Fprint(wr, e)
		if i != len(a)-1 { fmt.Fprint(wr, " ") }
	}
	fmt.Fprintln(wr)
	wr.Flush()
}

//•*¨*•.¸¸♪Main•*¨*•.¸¸♪(　-ω-)ノ　(　・ω・)

func main() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 10000), 100000000)

	t := scanInt()

	L: for i := 0; i < t; i++ {
		n := scanInt()
		x := scanInt()
		s := scanText()

		c0,c1 := 0,0

		for j := 0; j < n; j++ {
			if s[j] == '0' {
				c0++
			} else {
				c1++
			}
		}

		a,b := 0,0
		ans := 0

		f := false
		if c0 == c1 {
			f = true
		}

		if x == 0 {
			ans++
		}

		// if !f && x == c0-c1 {
		// 	ans++
		// }

		for j := 0; j < n; j++ {
			if s[j] == '0' {
				a++
			} else {
				b++
			}

			if f && a-b == x {
				fmt.Println(-1)
				break L
			}

			if !f && (x-a+b)%(c0-c1) == 0 && (x-a+b)/(c0-c1) >= 0 {
				ans++
			}
		}

		fmt.Println(ans)
	}
}

package main

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

//•*¨*•.¸¸♪I/O•*¨*•.¸¸♪

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

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

func scanInt64() int64 {
	sc.Scan()
	a,_ := strconv.ParseInt(sc.Text(),10,64)
	return a
}

func scanFloat64() float64 {
	sc.Scan()
	a,_ := strconv.Atoi(sc.Text())
	return float64(a)
}

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

func scanText() string {
	sc.Scan()
	return sc.Text()
}

func printInts(a ...int) {
	for i, e := range a {
		fmt.Fprint(wr, e)
		if i != len(a)-1 { fmt.Fprint(wr, " ") }
	}
	fmt.Fprintln(wr)
	wr.Flush()
}

//•*¨*•.¸¸♪Main•*¨*•.¸¸♪(　-ω-)ノ　(　・ω・)

func main() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 10000), 100000000)

	t := scanInt()

	L: for i := 0; i < t; i++ {
		n := scanInt()
		x := scanInt()
		s := scanText()

		c0,c1 := 0,0

		for j := 0; j < n; j++ {
			if s[j] == '0' {
				c0++
			} else {
				c1++
			}
		}

		a,b := 0,0
		ans := 0

		f := false
		if c0==c1 {
			f = true
		}

		if x == 0 {
			ans++
		}

		if !f && x == c0-c1 {
			ans++
		}

		for j := 0; j < n; j++ {
			if s[j] == '0' {
				a++
			} else {
				b++
			}

			if f && a-b == x {
				fmt.Println(-1)
				break L
			}

			if !f && (x-a+b)%(c0-c1) == 0 && (x-a+b)/(c0-c1) >= 0 {
				ans++
			}
		}

		fmt.Println(ans)
	}
}


Monocarp is a tutor of a group of $$$n$$$ students. He communicates with them using a conference in a popular messenger.Today was a busy day for Monocarp — he was asked to forward a lot of posts and announcements to his group, that's why he had to write a very large number of messages in the conference. Monocarp knows the students in the group he is tutoring quite well, so he understands which message should each student read: Monocarp wants the student $$$i$$$ to read the message $$$m_i$$$.Of course, no one's going to read all the messages in the conference. That's why Monocarp decided to pin some of them. Monocarp can pin any number of messages, and if he wants anyone to read some message, he should pin it — otherwise it will definitely be skipped by everyone.Unfortunately, even if a message is pinned, some students may skip it anyway. For each student $$$i$$$, Monocarp knows that they will read at most $$$k_i$$$ messages. Suppose Monocarp pins $$$t$$$ messages; if $$$t \le k_i$$$, then the $$$i$$$-th student will read all the pinned messages; but if $$$t > k_i$$$, the $$$i$$$-th student will choose exactly $$$k_i$$$ random pinned messages (all possible subsets of pinned messages of size $$$k_i$$$ are equiprobable) and read only the chosen messages.Monocarp wants to maximize the expected number of students that read their respective messages (i.e. the number of such indices $$$i$$$ that student $$$i$$$ reads the message $$$m_i$$$). Help him to choose how many (and which) messages should he pin!

The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of students in the conference. Then $$$n$$$ lines follow. The $$$i$$$-th line contains two integers $$$m_i$$$ and $$$k_i$$$ ($$$1 \le m_i \le 2 \cdot 10^5$$$; $$$1 \le k_i \le 20$$$) — the index of the message which Monocarp wants the $$$i$$$-th student to read and the maximum number of messages the $$$i$$$-th student will read, respectively.

In the first line, print one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of messages Monocarp should pin. In the second line, print $$$t$$$ distinct integers $$$c_1$$$, $$$c_2$$$, ..., $$$c_t$$$ ($$$1 \le c_i \le 2 \cdot 10^5$$$) — the indices of the messages Monocarp should pin. The messages can be listed in any order. If there are multiple answers, print any of them.

NoteLet's consider the examples from the statement. In the first example, Monocarp pins the messages $$$5$$$ and $$$10$$$.  if the first student reads the message $$$5$$$, the second student reads the messages $$$5$$$ and $$$10$$$, and the third student reads the messages $$$5$$$ and $$$10$$$, the number of students which have read their respective messages will be $$$2$$$;  if the first student reads the message $$$10$$$, the second student reads the messages $$$5$$$ and $$$10$$$, and the third student reads the messages $$$5$$$ and $$$10$$$, the number of students which have read their respective messages will be $$$3$$$. So, the expected number of students which will read their respective messages is $$$\frac{5}{2}$$$. In the second example, Monocarp pins the message $$$10$$$.  if the first student reads the message $$$10$$$, the second student reads the message $$$10$$$, and the third student reads the message $$$10$$$, the number of students which have read their respective messages will be $$$2$$$. So, the expected number of students which will read their respective messages is $$$2$$$. If Monocarp had pinned both messages $$$5$$$ and $$$10$$$, the expected number of students which read their respective messages would have been $$$2$$$ as well. In the third example, the expected number of students which will read their respective messages is $$$\frac{8}{3}$$$. In the fourth example, the expected number of students which will read their respective messages is $$$2$$$.

package main
import (
  "fmt"
  "bufio"
  "os"
  "strconv"
  "sort"
)
/*
老师将发布c条消息。对于第i个（共n个）学生，老师希望他读到第M[i]条，
该学生共读取c中的K[i]条消息，若K[i]<c，他会等概率选择其中的K[i]条。
求使得“读到老师希望的消息的学生数量的期望值”最大时，老师应该发布几条、具体哪几条消息。

枚举[1,n]中的c，发布M中“计数”最多的c个元素（p），
对于学生i，若M[i]不在p中，s[i]=0；若存在、M[i]>=c，则i读取所有消息，s[i]=1；
若存在、M[i]<c，“均等选择K[i]个，选到其中的数字M[i]的概率”s[i]=C(c-1,K[i]-1)/C(c,K[i])=K[i]/c。
即c越大、s[i]越小，而K[i]<=20，即c超过20时答案不会更优，所以枚举[1,20]中的c即可；
亦根据该式，求计数最多的M时，根据累加的K来倒排序。
sum(s)/c最大时，c与p就是答案。复杂度O(20 * nlogn)。
*/
var sc *bufio.Scanner
func min(a,b int)int{if a<b{return a};return b}
func I()int{sc.Scan();v,_:=strconv.Atoi(sc.Text());return v}
func main(){
  inp,out:=os.Stdin,os.Stdout
  sc=bufio.NewScanner(inp);W:=bufio.NewWriter(out);sc.Split(bufio.ScanWords);defer W.Flush()

  zs,zc,z:=0,1,[]int{};n:=I();Ms,M,S:=map[int]int{},[]int{},[][]int{}
  for i:=0;i<n;i++{m,k:=I(),I();Ms[m]=1;S=append(S,[]int{m,k})}
  for i:=range Ms{M=append(M,i)}
  for c:=1;c<min(21,len(M)+1);c++{
    C:=map[int]int{}
    for _,v:=range S{C[v[0]]+=min(c,v[1])}
    p:=make([]int,len(M));copy(p,M);s:=0
    sort.Slice(p,func(i,j int)bool{return C[p[i]]>C[p[j]]});p=p[:c]
    for _,i:=range p{s+=C[i]}
    if s*zc>zs*c{zs,zc,z=s,c,p}
  }
  fmt.Fprintln(W,len(z))
  for _,v:=range z{fmt.Fprint(W,v," ")}
}

package main
import (
  "fmt"
  "bufio"
  "os"
  "strconv"
  "sort"
)
var sc *bufio.Scanner
func min(a,b int)int{if a<b{return a};return b}
func I()int{sc.Scan();v,_:=strconv.Atoi(sc.Text());return v}
func main(){
  inp,out:=os.Stdin,os.Stdout
  sc=bufio.NewScanner(inp);W:=bufio.NewWriter(out);sc.Split(bufio.ScanWords);defer W.Flush()

  zs,zc,z:=0,1,[]int{};n:=I();Ms,M,S:=map[int]int{},[]int{},[][]int{}
  for i:=0;i<n;i++{m,k:=I(),I();Ms[m]=1;S=append(S,[]int{m,k})}
  for i:=range Ms{M=append(M,i)}
  for c:=1;c<min(21,len(M)+1);c++{
    C:=map[int]int{}
    for _,v:=range S{C[v[0]]+=min(c,v[1])}
    p:=make([]int,len(M));copy(p,M);s:=0
    sort.Slice(p,func(i,j int)bool{return C[p[i]]>C[p[j]]});p=p[:c]
    for _,i:=range p{s+=C[i]}
    if s*zc>zs*c{zs,zc,z=s,c,p}
  }
  fmt.Fprintln(W,len(z))
  for _,v:=range z{fmt.Fprint(W,v," ")}
}

package main

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

var n int

var m []int
var k []int

func main() {

	r := bufio.NewReader(os.Stdin)

	fmt.Fscan(r, &n)

	m = make([]int, n)
	k = make([]int, n)

	for i := 0; i < n; i++ {
		fmt.Fscan(r, &m[i], &k[i])
	}

	solve()

	fmt.Println()

}

type pair struct {
	key, v int
}

type ByV []*pair

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

type item struct {
	la, ra int
	lb, rb int
}

const MAX int = 2e5

var arr [22][]*pair

var cmp [22]int

func solve() {
	var ans []int

	fr := make(map[int]int)
	ids := make(map[int][]int)

	for i := 0; i < n; i++ {
		fr[m[i]]++
		ids[m[i]] = append(ids[m[i]], i)
	}

	for i := 1; i <= 21; i++ {

		for key, _ := range fr {

			var s int

			for j := 0; j < len(ids[key]); j++ {
				index := ids[key][j]

				if k[index] > i {
					s += i
				} else {
					s += k[index]
				}
			}

			arr[i] = append(arr[i], &pair{key, s})
		}
	}

	for i := 1; i <= 21; i++ {
		sort.Sort(ByV(arr[i]))
	}

	for i := 1; i <= 21; i++ {

		var sum int

		cur := arr[i]

		var cnt int
		for j := len(cur) - 1; j >= 0 && cnt < i; j-- {
			sum += cur[j].v
			cnt++
		}
		cmp[i] = sum
	}

	var max float64
	var maxIdx int

	var prevSum int

	for i := 1; i <= len(fr); i++ {
		if i <= 20 {
			s := cmp[i]

			if float64(s)/float64(i) > max {
				max = float64(s)/float64(i)
				maxIdx = i
			}
		} else if  i == 21 {
			prevSum = cmp[21]

			if float64(prevSum)/float64(i) > max {
				max = float64(prevSum)/float64(i)
				maxIdx = i
			}

		} else {
			sum := prevSum + arr[21][i - 1].v

			if float64(sum)/float64(i) > max {
				max = float64(sum)/float64(i)
				maxIdx = i
			}

			prevSum = sum
		}
	}

	var ind int

	if maxIdx <= 21 {
		ind = maxIdx
	} else {
		ind = 21
	}

	var cnt int
	for j := len(arr[ind]) - 1; j >= 0 && cnt < maxIdx; j-- {
		key := arr[ind][j].key
		ans = append(ans, key)
		cnt++
	}

	fmt.Println(len(ans))

	for j := 0; j < len(ans); j++ {
		fmt.Print(ans[j])
		fmt.Print(" ")
	}
}

func gcdExtended(a int64, b int64, x *int64, y *int64) int64 {

	// Base Case
	if a == 0 {
		*x, *y = 0,1
		return b
	}

	// To store results of recursive call
	var x1, y1 int64
	gcd := gcdExtended(b%a, a, &x1, &y1);

	// Update x and y using results of recursive
	// call
	*x = y1 - (b/a)*x1;
	*y = x1
	return gcd
}

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

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

//A -  1 3 5 3 1

//B -  4 3 6 1

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

package main

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

var n int

var m []int
var k []int

func main() {

	r := bufio.NewReader(os.Stdin)

	fmt.Fscan(r, &n)

	m = make([]int, n)
	k = make([]int, n)

	for i := 0; i < n; i++ {
		fmt.Fscan(r, &m[i], &k[i])
	}

	solve()

	fmt.Println()

}

type pair struct {
	key, v int
}

type ByV []*pair

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

type item struct {
	la, ra int
	lb, rb int
}

const MAX int = 2e5

func solve() {
	mp := make(map[int]int)
	ids := make(map[int][]int)

	keys := make(map[int]int)

	for i := 0; i < n; i++ {
		mp[m[i]]++
		ids[m[i]] = append(ids[m[i]], i)
	}

	var p []*pair

	for key, _ := range mp {
		v  := ids[key]

		var s int

		for j := 0; j < len(v); j ++ {
			s += k[v[j]]
		}

		p = append(p, &pair{key, s})
	}

	sort.Sort(ByV(p))

	var pin int

	var ans []int

	var a, b int

	for i := len(p) - 1; i >= 0; i-- {

		index := p[i].key

		if pin == 0 {
			pin = 1

			id := ids[index]

			var sum int

			for j := 0; j < len(id); j++ {
				if k[id[j]] > pin {
					sum += pin
				} else {
					sum += k[id[j]]
				}

				keys[k[id[j]]]++
			}

			b = 1
			a = sum

			ans = append(ans, index)

		} else {
			// a/b    aa/(b + 1) + ss/(b +1)
			var aa int

			for k, v := range keys {
				if k > b + 1 {
					aa += (b + 1) * v
				} else {
					aa += k * v
				}
			}

			var ss int

			for j := 0; j < len(ids[index]); j++ {
				key := k[ids[index][j]]

				if key > b + 1 {
					ss += (b + 1)
				} else {
					ss += key
				}
			}

			if a * (b + 1) < b * (aa + ss) {

				b += 1
				a = aa + ss

				pin++

				for j := 0; j < len(ids[index]); j++ {
					key := k[ids[index][j]]
					keys[key]++
				}

				ans = append(ans, index)
			}
		}
	}
	fmt.Println(len(ans))

	for j := 0; j < len(ans); j++ {
		fmt.Print(ans[j])
		fmt.Print(" ")
	}
}

func gcdExtended(a int64, b int64, x *int64, y *int64) int64 {

	// Base Case
	if a == 0 {
		*x, *y = 0,1
		return b
	}

	// To store results of recursive call
	var x1, y1 int64
	gcd := gcdExtended(b%a, a, &x1, &y1);

	// Update x and y using results of recursive
	// call
	*x = y1 - (b/a)*x1;
	*y = x1
	return gcd
}

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

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

//A -  1 3 5 3 1

//B -  4 3 6 1

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


There are n beacons located at distinct positions on a number line. The i-th beacon has position ai and power level bi. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance bi inclusive. The beacon itself is not destroyed however. Saitama will activate the beacons one at a time from right to left. If a beacon is destroyed, it cannot be activated.Saitama wants Genos to add a beacon strictly to the right of all the existing beacons, with any position and any power level, such that the least possible number of beacons are destroyed. Note that Genos's placement of the beacon means it will be the first beacon activated. Help Genos by finding the minimum number of beacons that could be destroyed.

The first line of input contains a single integer n (1 ≤ n ≤ 100 000) — the initial number of beacons. The i-th of next n lines contains two integers ai and bi (0 ≤ ai ≤ 1 000 000, 1 ≤ bi ≤ 1 000 000) — the position and power level of the i-th beacon respectively. No two beacons will have the same position, so ai ≠ aj if i ≠ j.

Print a single integer — the minimum number of beacons that could be destroyed if exactly one beacon is added.

NoteFor the first sample case, the minimum number of beacons destroyed is 1. One way to achieve this is to place a beacon at position 9 with power level 2.For the second sample case, the minimum number of beacons destroyed is 3. One way to achieve this is to place a beacon at position 1337 with power level 42.

// Author: sighduck
// URL: https://codeforces.com/problemset/problem/607/A

package main

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

type Beacon struct {
	Ai int
	Bi int
}

func Solve(n int, beacons []Beacon) int {
	maxPos := 0
	for _, b := range beacons {
		if b.Ai > maxPos {
			maxPos = b.Ai
		}
	}
	dp := make([]int, maxPos+1)
	b := make([]int, maxPos+1)
	for _, beacon := range beacons {
		b[beacon.Ai] = beacon.Bi
	}
	if b[0] > 0 {
		dp[0] = 1
	}
	maxAlive := dp[0]
	for i := 1; i < len(dp); i++ {
		if b[i] == 0 {
			dp[i] = dp[i-1]
		} else if b[i] >= i {
			dp[i] = 1
		} else {
			dp[i] = dp[i-b[i]-1] + 1
		}
		if dp[i] > maxAlive {
			maxAlive = dp[i]
		}
	}
	return n - maxAlive
}

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

	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	beacons := make([]Beacon, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d %d\n", &beacons[i].Ai, &beacons[i].Bi)
	}

	fmt.Fprintf(writer, "%d\n", Solve(n, beacons))
}

// Author: sighduck
// URL: https://codeforces.com/problemset/problem/607/A

package main

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

type Beacon struct {
	Ai int
	Bi int
}

func max(a []int) int {
	maxElem := 0
	for _, elem := range a {
		if elem > maxElem {
			maxElem = elem
		}
	}
	return maxElem
}

func Solve(n int, beacons []Beacon) int {
	dp := make([]int, beacons[len(beacons)-1].Ai+1)
	beaconMap := make(map[int]int)
	for _, b := range beacons {
		beaconMap[b.Ai] = b.Bi
	}
	if beaconMap[0] > 0 {
		dp[0] = 1
	}
	for i := 1; i < len(dp); i++ {
		if beaconMap[i] == 0 {
			dp[i] = dp[i-1]
		} else if beaconMap[i] >= i {
			dp[i] = 1
		} else {
			dp[i] = dp[i-beaconMap[i]-1] + 1
		}
	}
	return n - max(dp)
}

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

	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	beacons := make([]Beacon, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d %d\n", &beacons[i].Ai, &beacons[i].Bi)
	}

	fmt.Fprintf(writer, "%d\n", Solve(n, beacons))
}

// Author: sighduck
// URL: https://codeforces.com/problemset/problem/607/A

package main

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

type Beacon struct {
	Ai int
	Bi int
}

func max(a []int) int {
	maxElem := 0
	for _, elem := range a {
		if elem > maxElem {
			maxElem = elem
		}
	}
	return maxElem
}

func Solve(n int, beacons []Beacon) int {
	dp := make([]int, beacons[len(beacons)-1].Ai+1)
	beaconMap := make(map[int]int)
	for _, b := range beacons {
		beaconMap[b.Ai] = b.Bi
	}
	for i := 1; i < len(dp); i++ {
		if beaconMap[i] == 0 {
			dp[i] = dp[i-1]
		} else if beaconMap[i] >= i {
			dp[i] = 1
		} else {
			dp[i] = dp[i-beaconMap[i]-1] + 1
		}
	}
	return n - max(dp)
}

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

	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	beacons := make([]Beacon, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d %d\n", &beacons[i].Ai, &beacons[i].Bi)
	}

	fmt.Fprintf(writer, "%d\n", Solve(n, beacons))
}


Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that:   r ≥ 2;  for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds;  each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled:   no pair of tubes has common cells;  each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.

The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.

Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.

NotePicture for the first sample:   Picture for the second sample:

package main

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

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

//Wrong
func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	n, m, k := nextInt(), nextInt(), nextInt()
	x, y := 1, 1

	for i := k; i > 1; i-- {
		print(2, x, y)
		x, y = nextCell(x, y, m, n)
		println("", x, y)
		x, y = nextCell(x, y, m, n)
	}

	print(n * m - 2 * (k - 1))

	for x <= n {
		print(" ", x, y)
		x, y = nextCell(x, y, m, n)
	}
}

func nextCell(x, y, m, n int) (int, int) {
	if x % 2 == 0 {
		y--
	} else {
		y++
	}

	if y > m {
		x++
		y--
	}

	if y < 1 {
		x++
		y++
	}

	return x, y
}

func next() string {
	if !scanner.Scan() {
		panic("Scan error")
	}
	return scanner.Text()
}

func nextInt() int {
	n, err := strconv.Atoi(next())
	if err != nil {
		panic(err)
	}
	return n
}

func nextFloat() float64 {
	n, err := strconv.ParseFloat(next(), 64)
	if err != nil {
		panic(err)
	}
	return n
}

func println(a ...interface{}) {
	fmt.Fprintln(writer, a...)
}

func print(a ...interface{}) {
	fmt.Fprint(writer, a...)
}

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

package main

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

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

var (
	xx   = [4]int{0, 0, -1, 1}
	yy   = [4]int{1, -1, 0, 0}
	used [305][305]bool
	n    int
	m    int
	k    int
	div  int
	mod  int
)

func dfs(x int, y int, ln int) {

	if x == 0 || y == 0 || x > n || y > m {
		return
	}

	if ln == 1 {
		write(div + mod)
	}

	used[x][y] = true
	write(x, y)

	if ln == div+mod {
		mod, ln = 0, 0
		writeln()
	}

	for i := 0; i < 4; i++ {
		if !used[x+xx[i]][y+yy[i]] {
			dfs(x+xx[i], y+yy[i], ln+1)
		}
	}
}

func main() {
	defer out.Flush()
	in.Split(bufio.ScanWords)

	read(&n, &m, &k)

	mod = (n * m) % k
	div = (n * m) / k

	dfs(1, 1, 1)
}

func write(num ...int) {
	for _, value := range num {
		str := strconv.Itoa(value)
		out.WriteString(str + " ")
	}
}

func writeln() {
	out.WriteString("\n")
}

func read(num ...*int) {
	for _, value := range num {
		in.Scan()
		*value, _ = strconv.Atoi(in.Text())
	}
}

package main

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

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

	var n, m, k int

	fmt.Sscanf(line, "%d %d %d", &n, &m, &k)

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

	i := 0
	j := 0
	for k > 0 {
		tube := make([]int, 0, 10)
		for i < n {
			tubeChange := false
			for j < m && j >= 0 {
				tube = append(tube, i)
				tube = append(tube, j)
				if i%2 == 0 {
					j++
				} else {
					j--
				}
				if len(tube) >= 4 && k > 1 {
					tubeChange = true
					break
				}
			}

			if j == -1 || j == m {
				if i%2 == 0 {
					j--
				} else {
					j++
				}
				i++
			}
			if tubeChange {
				break
			}
		}
		fmt.Print(len(tube)/2, " ")
		for _, i := range tube {
			fmt.Print(i+1, " ")
		}
		fmt.Println()
		k--
	}
}

// 441C
package main

import (
	"fmt"
)

func main() {
	var a, n, m, k, clen int
	fmt.Scan(&n, &m, &k)
	length := n * m / k
	cx, cy := 0, 1
	for i := 0; i < k; i++ {
		if i == k-1 {
			clen = length + (n*m - k*length)
		} else {
			clen = length
		}
		fmt.Printf("%d ",clen)
		for j := 0; j < clen; j++ {
			cx = (cx + 1) % (2 * m)
			if cx > m {
				a = 2*m - cx + 1
			} else {
				if cx == 0 {
					a = 1
				} else {
					a = cx
				}
			}
			fmt.Printf("%d %d ",cy, a)
			if cx == 0 || cx == m {
				cy++
			}
		}
		fmt.Println()
	}
}

// 441C
package main

import (
	"fmt"
)

func main() {
	var a, n, m, k, clen int
	fmt.Scan(&n, &m, &k)
	length := n * m / k
	cx, cy := 0, 1
	for i := 0; i < k; i++ {
		if i == k-1 {
			clen = length + (n*m - k*length)
		} else {
			clen = length
		}
		fmt.Printf("%d ", clen)
		for j := 0; j < clen; j++ {
			cx = (cx + 1) % (2 * m)
			if cx > m {
				a = 2*m - cx + 1
			} else {
				if cx == 0 {
					a = 1
				} else {
					a = cx
				}
			}
			fmt.Print("%d %d ", cy, a)
			if cx == 0 || cx == m {
				cy++
			}
		}
		fmt.Println()
	}
}

// 441C
package main

import (
	"fmt"
)

func main() {
	var a, n, m, k, clen int
	fmt.Scan(&n, &m, &k)
	length := n * m / k
	cx, cy := 0, 1
	for i := 0; i < k; i++ {
		if i == k-1 {
			clen = length + (n*m - k*length)
		} else {
			clen = length
		}
		fmt.Print(clen)
		for j := 0; j < clen; j++ {
			cx = (cx + 1) % (2 * m)
			if cx > m {
				a = 2*m - cx + 1
			} else {
				if cx == 0 {
					a = 1
				} else {
					a = cx
				}
			}
			fmt.Print(cy, a)
			if cx == 0 || cx == m {
				cy++
			}
		}
		fmt.Println()
	}
}


You are given a non-empty string s consisting of lowercase letters. Find the number of pairs of non-overlapping palindromic substrings of this string.In a more formal way, you have to find the quantity of tuples (a, b, x, y) such that 1 ≤ a ≤ b < x ≤ y ≤ |s| and substrings s[a... b], s[x... y] are palindromes.A palindrome is a string that can be read the same way from left to right and from right to left. For example, "abacaba", "z", "abba" are palindromes.A substring s[i... j] (1 ≤ i ≤ j ≤ |s|) of string s = s1s2... s|s| is a string sisi + 1... sj. For example, substring s[2...4] of string s = "abacaba" equals "bac".

The first line of input contains a non-empty string s which consists of lowercase letters ('a'...'z'), s contains at most 2000 characters.

Output a single number — the quantity of pairs of non-overlapping palindromic substrings of s. Please do not use the %lld format specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d format specifier.

package main

import "os"
import "bufio"
import "strconv"

func main(){
	var s string
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	w := bufio.NewWriter(os.Stdout)
	r.Scan()
	s = r.Text()
	k := 0
	var end [2100]int
	var start [2100]int
	var ans int64 = 0
	for i:=0; i<2; i++ {
		for j:=0; j+i<len(s); j++ {
			l := 0
			k = j+i
			for j-l >= 0 && k+l < len(s) {
				if s[j-l] == s[k+l] {
					start[j-l] += 1
					end[k+l] += 1
					l += 1
					continue
				}
				break
			}
		}
	}
	for i:=len(s)-2; i>=0; i-- {
		start[i] += start[i+1]
	}
	for i:=0; i+1<len(s); i++ {
		ans += int64(end[i]*start[i+1])
	}
	w.WriteString(strconv.FormatInt(ans, 10)+"\n")
	w.Flush()
}


A continued fraction of height n is a fraction of form . You are given two rational numbers, one is represented as  and the other one is represented as a finite fraction of height n. Check if they are equal.

The first line contains two space-separated integers p, q (1 ≤ q ≤ p ≤ 1018) — the numerator and the denominator of the first fraction. The second line contains integer n (1 ≤ n ≤ 90) — the height of the second fraction. The third line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 1018) — the continued fraction. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

Print "YES" if these fractions are equal and "NO" otherwise.

NoteIn the first sample .In the second sample .In the third sample .

// Codeforces 305 B
package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
	"strconv"
	"math/big"
)
var in *bufio.Reader

func readFive() (int64,int64,int64,int64,int64) {
    var a [5]int64
	s, err := in.ReadString('\n')
	if err != nil {
		fmt.Println("first read failure", err)
		panic(err)
	}
	ss := strings.Split(strings.Trim(s, " \n\r"), " ")
    for i:=0; i<len(ss); i++ {
        a[i], err = strconv.ParseInt(ss[i],10,64)
        if err != nil {
            fmt.Println("n atoi failure", err)
            panic(err)
        }
    }
    return a[0],a[1],a[2],a[3],a[4]
}

func readLineNumbs(n int) []int64 {
    a := make([]int64, n)
    s, err := in.ReadString('\n')
    if err != nil {
        fmt.Println("read failure", err)
        panic(err)
    }
    ss := strings.Split(strings.Trim(s, " \n\r"), " ")
    for j:=0; j<n; j++ {
        aa,err := strconv.ParseInt(ss[j],10,64)
        if err != nil {
            fmt.Println("aa conv failed", err)
            panic(err)
        }
        a[j] = aa
    }
    return a
}

var p,q int64
var n int
var a []int64
var equal string  // YES or NO

func readData() {
 	in = bufio.NewReader(os.Stdin)
	// reading n
    p,q,_,_,_ = readFive()
    ni,_,_,_,_ := readFive()
    n = int(ni)
    //fmt.Printf("p,q,n= %d %d %d\n", p,q,n)
    ai := readLineNumbs(n)
    a = make([]int64, n)
    for i:=0; i<n; i++ {
    	a[i] = int64(ai[i])
    	//fmt.Printf("i,a[i]= %d %d\n", i, a[i])
    }
}

func solve() {
	pq := big.NewRat(p,q)
	//fmt.Printf("solve n,a[0]= %d %d, pq: %s\n", n,a[0], pq.RatString())
	aa := big.NewRat(a[n-1],1)
	for i:=n-2; i>=0; i-- {
		ai := big.NewRat(a[i],1)
		aa.Inv(aa)
		aa.Add(aa, ai)
		//fmt.Println("aa:" + aa.RatString())
	}
	cmp := aa.Cmp(pq)
	//fmt.Printf("cmp= %d\n",cmp)
	if cmp==0 {
		equal = "YES"
	} else {
		equal = "NO"
	}
}

func main() {
 	readData()

    solve()

    fmt.Println(equal)
}


You are playing a new famous fighting game: Kortal Mombat XII. You have to perform a brutality on your opponent's character.You are playing the game on the new generation console so your gamepad have $$$26$$$ buttons. Each button has a single lowercase Latin letter from 'a' to 'z' written on it. All the letters on buttons are pairwise distinct.You are given a sequence of hits, the $$$i$$$-th hit deals $$$a_i$$$ units of damage to the opponent's character. To perform the $$$i$$$-th hit you have to press the button $$$s_i$$$ on your gamepad. Hits are numbered from $$$1$$$ to $$$n$$$.You know that if you press some button more than $$$k$$$ times in a row then it'll break. You cherish your gamepad and don't want to break any of its buttons.To perform a brutality you have to land some of the hits of the given sequence. You are allowed to skip any of them, however changing the initial order of the sequence is prohibited. The total damage dealt is the sum of $$$a_i$$$ over all $$$i$$$ for the hits which weren't skipped.Note that if you skip the hit then the counter of consecutive presses the button won't reset.Your task is to skip some hits to deal the maximum possible total damage to the opponent's character and not break your gamepad buttons.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$) — the number of hits and the maximum number of times you can push the same button in a row. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the damage of the $$$i$$$-th hit. The third line of the input contains the string $$$s$$$ consisting of exactly $$$n$$$ lowercase Latin letters — the sequence of hits (each character is the letter on the button you need to press to perform the corresponding hit).

Print one integer $$$dmg$$$ — the maximum possible damage to the opponent's character you can deal without breaking your gamepad buttons.

NoteIn the first example you can choose hits with numbers $$$[1, 3, 4, 5, 6, 7]$$$ with the total damage $$$1 + 16 + 18 + 7 + 2 + 10 = 54$$$.In the second example you can choose all hits so the total damage is $$$2 + 4 + 1 + 3 + 1000 = 1010$$$.In the third example you can choose all hits expect the third one so the total damage is $$$2 + 4 + 3 + 1000 = 1009$$$.In the fourth example you can choose hits with numbers $$$[2, 3, 6, 8]$$$. Only this way you can reach the maximum total damage $$$15 + 2 + 8 + 16 = 41$$$.In the fifth example you can choose only hits with numbers $$$[2, 4, 6]$$$ with the total damage $$$18 + 19 + 15 = 52$$$.In the sixth example you can change either first hit or the second hit (it does not matter) with the total damage $$$10$$$.

package main

import (
	"unicode"
	"bufio"
	"fmt"
	"os"
	"math/big"
	"sort"
)

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() {
	//STDOUT MUST BE FLUSHED MANUALLY
	defer writer.Flush()

	max := big.NewInt(0)

	var n, k int
	scanf("%d %d\n", &n, &k)
	dmg := make([]int64, n)
	for i := 0; i < n; i++ {
		scanf("%d ", &dmg[i])
	}
	seq := make([]rune, n)

	var t rune
	for i := 0; i < n;  {
		scanf("%c", &t)
		if !unicode.IsSpace(t) {
			seq[i] = t
			i++
		}
	}
	// SOLUTION
	var lp, rp int
	i := 0
	for {
		if i >= len(seq) - 1 {
			// special case: len(seq) == 1
			if len(seq) == 1 {
				max.Add(max, big.NewInt(dmg[i]))
				break
			}
			// add last one
			if i == len(seq) - 1 && seq[i-1] != seq[i] {
				max.Add(max, big.NewInt(dmg[i]))
			}
			break
		}
		if seq[i] != seq[i+1] {
			// printf("add: %d", dmg[i])
			max.Add(max, big.NewInt(dmg[i]))
			// printf("\tmax: %v\n", max)
			i++
			continue
		}
		// find sequence with same chars
		lp = i
		rp = i
		for {
			rp++
			if seq[lp] != seq[rp] {
				rp--
				break
			} else if rp == len(seq) - 1 {
				break
			}
		}
		// printf("same chars: %+v\n", dmg[lp:rp+1])
		tmp := make([]int64, len(dmg[lp:rp+1]))
		copy(tmp, dmg[lp:rp+1])
		sort.Slice(tmp, func(i, j int) bool { return tmp[i] < tmp[j] })
		// printf("Sorted tmp: %+v\n", tmp)
		// get k max elements from tmp
		for i := 0; i < k && i < len(tmp); i++  {
			curMax := tmp[len(tmp)-1-i]
			// printf("add: %d", curMax)
			max.Add(max, big.NewInt(curMax))
			// printf("\tmax: %v\n", max)
		}
		// printf("max: %v\n", max)
		i = rp + 1
	}
	printf("%v\n", max)
}

package main

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

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 n, k int

	scanf("%d %d\n", &n, &k)

	var a [200001]int64

	for i := 0; i < n; i++ {
		scanf("%d", &a[i])
	}

	scanf("\n")

	var s string

	scanf("%s\n", &s)

	char := s[0]

	var x []int64

	var ans int64

	x = append(x, a[0])

	for i := 1; i < n; i++ {
		if s[i] == char {
			x = append(x, a[i])
		} else {
			sort.Slice(x, func(i, j int) bool {
				return x[i] > x[j]
			})
			for j := 0; j < k && j < len(x); j++ {
				// printf("Added %d to the answer\n", x[j])
				ans += x[j]
			}
			char = s[i]
			x = []int64{a[i]}
		}
	}
	sort.Slice(x, func(i, j int) bool {
		return x[i] > x[j]
	})
	for j := 0; j < k && j < len(x); j++ {
		// printf("Added %d to the answer\n", x[j])
		ans += x[j]
	}
	printf("%d\n", ans)

}

package main

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

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

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

// An IntHeap is a min-heap of ints.
type IntHeap []int

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

func (h *IntHeap) Push(x interface{}) {
	// Push and Pop use pointer receivers because they modify the slice's length,
	// not just its contents.
	*h = append(*h, x.(int))
}

func (h *IntHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func main() {
	defer writer.Flush()
	var n, k, t int
	var s string
	scanf("%d %d\n", &n, &k)
	arr := []int{}
	for i := 0; i < n; i++ {
		scanf("%d", &t)
		arr = append(arr, t)
	}
	scanf("\n")
	scanf("%s\n", &s)
	last := byte('$')

	hp := &IntHeap{}

	ans := int64(0)

	for i := 0; i < n; i++ {
		if s[i] != last {
			for hp.Len() > 0 {
				t = heap.Pop(hp).(int)
				ans += int64(t)
			}
		}
		last = s[i]
		heap.Push(hp, arr[i])
		if hp.Len() > k {
			heap.Pop(hp)
		}
	}
	for hp.Len() > 0 {
		t = heap.Pop(hp).(int)
		ans += int64(t)
	}
	printf("%d\n", ans)
}

package main

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

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() {
	//STDOUT MUST BE FLUSHED MANUALLY
	defer writer.Flush()

	max := big.NewInt(0)

	var n, k int
	scanf("%d %d\n", &n, &k)
	dmg := make([]int64, n)
	for i := 0; i < n; i++ {
		scanf("%d ", &dmg[i])
	}
	seq := make([]rune, n)
	for i := 0; i < n; i++ {
		scanf("%c", &seq[i])
	}
	// SOLUTION
	var lp, rp int
	i := 0
	for {
		if i >= len(seq) - 1 {
			// add last one
			if i == len(seq) - 1 && seq[i-1] != seq[i] {
				max.Add(max, big.NewInt(dmg[i]))
			}
			break
		}
		if seq[i] != seq[i+1] {
			// printf("add: %d", dmg[i])
			max.Add(max, big.NewInt(dmg[i]))
			// printf("\tmax: %v\n", max)
			i++
			continue
		}
		// find sequence with same chars
		lp = i
		rp = i
		for {
			rp++
			if seq[lp] != seq[rp] {
				rp--
				break
			} else if rp == len(seq) - 1 {
				break
			}
		}
		// printf("same chars: %+v\n", dmg[lp:rp+1])
		tmp := make([]int64, len(dmg[lp:rp+1]))
		copy(tmp, dmg[lp:rp+1])
		// printf("tmp: %+v\n", tmp)
		sort.Slice(tmp, func(i, j int) bool { return tmp[i] < tmp[j] })
		// printf("Sorted tmp: %+v\n", tmp)
		// get k max elements from tmp
		for i := 0; i < k && i < len(tmp); i++  {
			curMax := tmp[len(tmp)-1-i]
			// printf("add: %d", curMax)
			max.Add(max, big.NewInt(curMax))
			// printf("\tmax: %v\n", max)
		}
		// printf("max: %v\n", max)
		i = rp + 1
	}
	printf("%v\n", max)
}

package main

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

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 n, k int

	scanf("%d %d\n", &n, &k)

	var a [200001]int

	for i := 0; i < n; i++ {
		scanf("%d", &a[i])
	}

	scanf("\n")

	var s string

	scanf("%s\n", &s)

	char := s[0]

	var x []int

	var ans int

	x = append(x, a[0])

	for i := 1; i < n; i++ {
		if s[i] == char {
			x = append(x, a[i])
		} else {
			sort.Slice(x, func(i, j int) bool {
				return x[i] > x[j]
			})
			for j := 0; j < k && j < len(x); j++ {
				// printf("Added %d to the answer\n", x[j])
				ans += x[j]
			}
			char = s[i]
			x = []int{a[i]}
		}
	}
	sort.Slice(x, func(i, j int) bool {
		return x[i] > x[j]
	})
	for j := 0; j < k && j < len(x); j++ {
		// printf("Added %d to the answer\n", x[j])
		ans += x[j]
	}
	printf("%d\n", ans)

}


You are given the string s of length n and the numbers p, q. Split the string s to pieces of length p and q.For example, the string "Hello" for p = 2, q = 3 can be split to the two strings "Hel" and "lo" or to the two strings "He" and "llo".Note it is allowed to split the string s to the strings only of length p or to the strings only of length q (see the second sample test).

The first line contains three positive integers n, p, q (1 ≤ p, q ≤ n ≤ 100). The second line contains the string s consists of lowercase and uppercase latin letters and digits.

If it's impossible to split the string s to the strings of length p and q print the only number "-1". Otherwise in the first line print integer k — the number of strings in partition of s. Each of the next k lines should contain the strings in partition. Each string should be of the length p or q. The string should be in order of their appearing in string s — from left to right. If there are several solutions print any of them.

package main

import (
         "fmt"
       )

func getPieceCount(s *string, p *int, q *int) (int, int) {
    slp := len(*s)/(*p)
    for a:= 0; a <= slp; a++ {
        b := (len(*s) - a*(*p))/(*q)
        if (b*(*q) + a*(*p)) == len(*s) {
            return a, b
        }
    }
    return -1, -1
}

func main() {
    var n,p,q int
    var s string
    fmt.Scanf("%d %d %d\n", &n, &p, &q)
    fmt.Scanf("%s", &s)

    //fmt.Printf("%d %d %d %s\n", n, p, q, s)

    a, b := getPieceCount(&s, &p, &q)

    if a == -1 {
        fmt.Printf("-1")
    } else {
        fmt.Printf("%d\n", a+b)
        current := 0
        for i := 0; i < a; i++ {
            fmt.Printf("%s\n", s[current:current+p])
            current += p
        }
        for i := 0; i < b; i++ {
            fmt.Printf("%s\n", s[current:current+q])
            current += q
        }
    }
}

package main

import (
	"fmt"
)

func findMults(n, p, q int) (bool, int, int) {
	var p0, q0 int

	for p0 = 0; p0*p <= n; p0++ {
		for q0 = 0; p0*p+q0*q <= n; q0++ {
			if p0*p+q0*q == n {
				return true, p0, q0
			}
		}
	}

	return false, 0, 0
}

func main() {
	var s string
	var n, p, q int

	fmt.Scanf("%d %d %d\n", &n, &p, &q)
	fmt.Scanf("%s\n", &s)

	found, p0, q0 := findMults(n, p, q)
	if !found {
		fmt.Println("-1")
		return
	}

	// if (p+q > n) && p > n && q > n {
	// 	fmt.Println("-1")
	// 	return
	// }

	// if n%(p+q) != 0 && n%(p+q) != p {
	// 	if n%p == 0 {
	// 		q = p
	// 	} else if n%q == 0 {
	// 		p = q
	// 	} else {
	// 		fmt.Println("-1")
	// 		return
	// 	}
	// }

	// fmt.Println(n, p, q)

	fmt.Println(p0 + q0)
	index := 0
	for i := 0; i < p0; i++ {
		fmt.Println(s[index : index+p])
		index += p
	}
	for i := 0; i < q0; i++ {
		fmt.Println(s[index : index+q])
		index += q
	}
}

package main

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

//N _
const (
	N = 2*1e5 + 5
)

func inputter(inputReader *bufio.Reader,strs chan *string){
	for {
		input , _ := inputReader.ReadString('\n')
		input = strings.TrimSpace(input)
		if len(input) > 0 {
			inputs := strings.Split(input, " ")
			for i := range inputs{
				strs <- &inputs[i]
			}
		}
	}
}

func main(){
	rs := bufio.NewReader(os.Stdin)
	ws := bufio.NewWriter(os.Stdout)

	strs := make(chan *string, 100)

	go inputter(rs, strs)

	n , _ := strconv.ParseInt(*<-strs, 10, 64)
	p , _ := strconv.ParseInt(*<-strs, 10, 64)
	q , _ := strconv.ParseInt(*<-strs, 10, 64)
	str := <-strs

	var x,y int64

	for i := int64(0); i * p <= n; i ++{
		if (n - i * p)%q == 0{
			x = i
			y = (n - i * p)/q
		}
	}

	if x + y == 0{
		ws.WriteString("-1")
		ws.Flush()
		return
	}

	ws.WriteString(fmt.Sprintln(x + y))

	for i := int64(0); i < x; i++{
		ws.WriteString((*str)[i * p: (i + 1) * p ] + "\n")
	}

	for i := int64(0); i < y; i++{
		ws.WriteString((*str)[x*p + i*q : x*p + (i + 1)*q ] + "\n")
	}

	ws.Flush()
}

package main

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

func Min(a int, b int) int {
	if a < b {
		return a
	}
	return b
}
func Max(a int, b int) int {
	if a > b {
		return a
	}
	return b
}

func Scan(args ...interface{}) (e error)             { _, e = fmt.Fscan(in, args...); return }
func Scanf(ft string, args ...interface{}) (e error) { _, e = fmt.Fscanf(in, ft, args...); return }
func Scanln(args ...interface{}) (e error)           { _, e = fmt.Fscanln(in, args...); return }
func Print(args ...interface{})                      { out.WriteString(fmt.Sprint(args...)) }
func Printf(ft string, args ...interface{})          { out.WriteString(fmt.Sprintf(ft, args...)) }
func Println(args ...interface{})                    { out.WriteString(fmt.Sprintln(args...)) }

var (
	dataIn = "data.in"
	in     = bufio.NewReader(os.Stdin)
	//in, _ = os.Open(dataIn)
	out   = bufio.NewWriter(os.Stdout)
)

var n, p, q int
var dp, cnt []int
var str string

func read() {
	dp = make([]int, n)
	cnt = make([]int, n)
	Scan(&str)
}

func dfs(pos int) {
	if pos == -1 {
		return
	}
	dfs(dp[pos])
	Println(str[dp[pos]+1 : pos+1])
}

func solve() {
	dp[p-1], dp[q-1] = -1, -1
	cnt[p-1], cnt[q-1] = 1, 1
	for i := 0; i < n; i++ {
		if cnt[i] > 0 {
			if i+p < n && dp[i+p] == 0 {
				dp[i+p] = i
				cnt[i+p] = cnt[i] + 1
			}
			if i+q < n && dp[i+q] == 0 {
				dp[i+q] = i
				cnt[i+q] = cnt[i] + 1
			}
		}
	}
	if dp[n-1] == 0 {
		Println("-1")
	} else {
		Println(cnt[n-1])
		dfs(n - 1)
	}
}

func main() {
	defer out.Flush()
	for Scan(&n, &p, &q) != io.EOF {
		read()
		solve()
	}
	return
}

package main

import (
	"fmt"
)

func main() {
	var n, p, q int
	var s string
	fmt.Scanf("%d %d %d\n", &n, &p, &q)
	fmt.Scanln(&s)

	var parts []string
	str := []rune(s)
	i := 0
	impossible := false
	for {

		if n%p == 0 {
			parts = append(parts, (string)(str[i:i+p]))
			n -= p
			i += p
		} else if n%q == 0 {
			parts = append(parts, (string)(str[i:i+q]))
			n -= q
			i += q
		} else if n > p && n-p >= q {
			parts = append(parts, (string)(str[i:i+p]))
			n -= p
			i += p
		} else if n > q && n-q >= p {
			parts = append(parts, (string)(str[i:i+q]))
			n -= q
			i += q
		} else {
			impossible = true
			break
		}

		if n <= 0 {
			break
		}
	}

	if impossible {
		fmt.Println("-1")
	} else {
		fmt.Println(len(parts))
		for i := 0; i < len(parts); i++ {
			fmt.Println(parts[i])
		}
	}
}

package main

import "fmt"

func split(n, p, q int) (int, int, bool) {
	for a := 0; a*p <= n; a++ {
		b := (n - a*p) / q
		if a*p+b*q == n {
			return a, b, true
		}
	}
	return 0, 0, false
}

func main() {
	var n, p, q int
	fmt.Scanln(&n, &p, &q)
	if a, b, ok := split(n, p, q); !ok {
		fmt.Println(-1)
	} else {
		var s string
		fmt.Scanln(&s)
		fmt.Println(a + b)
		for i := 0; i < a; i++ {
			fmt.Println(s[i*p : (i+1)*p])
		}
		for i := 0; i < b; i++ {
			fmt.Println(s[a*p+i*q : a*p+(i+1)*q])
		}
	}
}

package main

import (
         "fmt"
       )

func getPieceCount(s *string, p *int, q *int) (int, int) {
    slp := len(*s)/(*p)
    for a:= 0; a < slp; a++ {
        b := (len(*s) - a*(*p))/(*q)
        if b*(*q) + a*(*p) == len(*s) {
            return a, b
        }
    }
    return -1, -1
}

func main() {
    var n,p,q int
    var s string
    fmt.Scanf("%d %d %d\n", &n, &p, &q)
    fmt.Scanf("%s", &s)

    a, b := getPieceCount(&s, &p, &q)

    if a == -1 {
        fmt.Printf("-1")
    } else {
        fmt.Printf("%d\n", a+b)
        current := 0
        for i := 0; i < a; i++ {
            fmt.Printf("%s\n", s[current:current+p])
            current += p
        }
        for i := 0; i < b; i++ {
            fmt.Printf("%s\n", s[current:current+q])
            current += q
        }
    }
}

package main

import (
	"fmt"
)

func main() {
	var s string
	var n, p, q int

	fmt.Scanf("%d %d %d\n", &n, &p, &q)
	fmt.Scanf("%s\n", &s)

	if (p+q > n) && p > n && q > n {
		fmt.Println("-1")
		return
	}

	if n%(p+q) != 0 && n%(p+q) != p {
		if n%p == 0 {
			q = p
		} else if n%q == 0 {
			p = q
		} else {
			fmt.Println("-1")
			return
		}
	}

	// fmt.Println(n, p, q)

	i := 0
	count := (n/(p+q))*2 + (n%(p+q))/p
	fmt.Println(count)

	for i < len(s) {
		fmt.Println(s[i : i+p])
		i += p

		if i >= len(s) {
			break
		}

		fmt.Println(s[i : i+q])
		i += q
	}
}

package main

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

//N _
const (
	N = 2*1e5 + 5
)

func inputter(inputReader *bufio.Reader,strs chan *string){
	for {
		input , _ := inputReader.ReadString('\n')
		input = strings.TrimSpace(input)
		if len(input) > 0 {
			inputs := strings.Split(input, " ")
			for i := range inputs{
				strs <- &inputs[i]
			}
		}
	}
}

func main(){
	rs := bufio.NewReader(os.Stdin)
	ws := bufio.NewWriter(os.Stdout)

	strs := make(chan *string, 100)

	go inputter(rs, strs)

	n , _ := strconv.ParseInt(*<-strs, 10, 64)
	p , _ := strconv.ParseInt(*<-strs, 10, 64)
	q , _ := strconv.ParseInt(*<-strs, 10, 64)
	str := <-strs

	var x,y int64

	for i := int64(0); i * p <= n; i ++{
		if (n - i * p)%q == 0{
			x = i
			y = (n-i)/q
		}
	}

	if x + y == 0{
		ws.WriteString("-1")
		ws.Flush()
		return
	}

	for i := int64(0); i < x; i++{
		ws.WriteString((*str)[i * p: (i + 1) * p ] + "\n")
	}

	for i := int64(0); i < y; i++{
		ws.WriteString((*str)[x*p + i*q : x*p + (i + 1)*q ] + "\n")
	}

	ws.Flush()
}

package main

import (
	"fmt"
)

func main() {
	var n, p, q int
	var s string
	fmt.Scanf("%d %d %d\n", &n, &p, &q)
	fmt.Scanln(&s)

	var parts []string
	str := []rune(s)
	i := 0
	impossible := false
	for {
		if n-p >= p && n-p >= q {
			parts = append(parts, (string)(str[i:i+p]))
			n -= p
			i += p
		} else if n-q >= p && n-q >= q {
			parts = append(parts, (string)(str[i:i+q]))
			n -= q
			i += q
		} else if n%p == 0 || n%p >= q {
			parts = append(parts, (string)(str[i:i+p]))
			n -= p
			i += p
		} else if n%q == 0 || n%q >= p {
			parts = append(parts, (string)(str[i:i+q]))
			n -= q
			i += q
		} else {
			impossible = true
			break
		}

		if n <= 0 {
			break
		}
	}

	if impossible {
		fmt.Println("-1")
	} else {
		fmt.Println(len(parts))
		for i := 0; i < len(parts); i++ {
			fmt.Println(parts[i])
		}
	}
}

package main

import (
	"fmt"
)

func main() {
	var n, p, q int
	var s string
	fmt.Scanf("%d %d %d\n", &n, &p, &q)
	fmt.Scanln(&s)

	var parts []string
	str := []rune(s)
	i := 0
	impossible := false
	for {
		if n-p >= p && n-p >= q {
			parts = append(parts, (string)(str[i:i+p]))
			n -= p
			i += p
		} else if n-q >= p && n-q >= q {
			parts = append(parts, (string)(str[i:i+q]))
			n -= q
			i += q
		} else if n%p == 0 || (n > p && n%p >= q) {
			parts = append(parts, (string)(str[i:i+p]))
			n -= p
			i += p
		} else if n%q == 0 || (n > q && n%q >= p) {
			parts = append(parts, (string)(str[i:i+q]))
			n -= q
			i += q
		} else {
			impossible = true
			break
		}

		if n <= 0 {
			break
		}
	}

	if impossible {
		fmt.Println("-1")
	} else {
		fmt.Println(len(parts))
		for i := 0; i < len(parts); i++ {
			fmt.Println(parts[i])
		}
	}
}


You are given a sequence of $$$n$$$ pairs of integers: $$$(a_1, b_1), (a_2, b_2), \dots , (a_n, b_n)$$$. This sequence is called bad if it is sorted in non-descending order by first elements or if it is sorted in non-descending order by second elements. Otherwise the sequence is good. There are examples of good and bad sequences:  $$$s = [(1, 2), (3, 2), (3, 1)]$$$ is bad because the sequence of first elements is sorted: $$$[1, 3, 3]$$$;  $$$s = [(1, 2), (3, 2), (1, 2)]$$$ is bad because the sequence of second elements is sorted: $$$[2, 2, 2]$$$;  $$$s = [(1, 1), (2, 2), (3, 3)]$$$ is bad because both sequences (the sequence of first elements and the sequence of second elements) are sorted;  $$$s = [(1, 3), (3, 3), (2, 2)]$$$ is good because neither the sequence of first elements $$$([1, 3, 2])$$$ nor the sequence of second elements $$$([3, 3, 2])$$$ is sorted. Calculate the number of permutations of size $$$n$$$ such that after applying this permutation to the sequence $$$s$$$ it turns into a good sequence. A permutation $$$p$$$ of size $$$n$$$ is a sequence $$$p_1, p_2, \dots , p_n$$$ consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ ($$$1 \le p_i \le n$$$). If you apply permutation $$$p_1, p_2, \dots , p_n$$$ to the sequence $$$s_1, s_2, \dots , s_n$$$ you get the sequence $$$s_{p_1}, s_{p_2}, \dots , s_{p_n}$$$. For example, if $$$s = [(1, 2), (1, 3), (2, 3)]$$$ and $$$p = [2, 3, 1]$$$ then $$$s$$$ turns into $$$[(1, 3), (2, 3), (1, 2)]$$$.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$). The next $$$n$$$ lines contains description of sequence $$$s$$$. The $$$i$$$-th line contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) — the first and second elements of $$$i$$$-th pair in the sequence. The sequence $$$s$$$ may contain equal elements.

Print the number of permutations of size $$$n$$$ such that after applying this permutation to the sequence $$$s$$$ it turns into a good sequence. Print the answer modulo $$$998244353$$$ (a prime number).

package main

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

/* solution */

type pairs [][2]int
type pairs2 [][2]int

func (s pairs) Len() int {
	return len(s)
}
func (s pairs) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}
func (s pairs) Less(i, j int) bool {
	return s[i][0] < s[j][0] || (s[i][0] == s[j][0] && s[i][1] < s[j][1])
}

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

var factStorage = []int64{1, 1, 2}

func solve() {

	n := readInt()
	a := make([]int, n)
	b := make([]int, n)
	c := make(pairs, n)
	for i := 0; i < n; i++ {
		a[i] = readInt()
		b[i] = readInt()
		c[i] = [2]int{a[i], b[i]}
	}

	ans := fact(len(a))
	sort.Ints(a)
	ans -= count(a)
	sort.Ints(b)
	ans -= count(b)
	sort.Sort(c)
	if sort.IsSorted(pairs2(c)) {
		ans += countPairs(c)
	}

	printInt64(((ans % 998244353) + 998244353) % 998244353)

}

func count(a []int) int64 {
	ans := int64(1)
	cnt := 1
	for i := 1; i < len(a); i++ {
		if a[i-1] < a[i] {
			ans = (ans * fact(cnt)) % 998244353
			cnt = 1
		} else {
			cnt++
		}
	}
	ans = (ans * fact(cnt)) % 998244353
	return ans
}

func countPairs(a pairs) int64 {
	ans := int64(1)
	cnt := 1
	for i := 1; i < len(a); i++ {
		if pairs.Less(a, i-1, i) {
			ans = (ans * fact(cnt)) % 998244353
			cnt = 1
		} else {
			cnt++
		}
	}
	ans = (ans * fact(cnt)) % 998244353
	return ans
}

func fact(i int) int64 {
	length := int64(len(factStorage))
	k := int64(i)
	for k >= length {
		next := (factStorage[length-1] * (length % 998244353)) % 998244353
		factStorage = append(factStorage, next)
		length++
	}
	return factStorage[k]
}

/* 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)
	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 printInt64(i int64) {
	print(strconv.FormatInt(i, 10))
}

package main

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

/* solution */

type pairs [][2]int
type pairs2 [][2]int

func (s pairs) Len() int {
	return len(s)
}
func (s pairs) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}
func (s pairs) Less(i, j int) bool {
	return s[i][0] < s[j][0] || (s[i][0] == s[j][0] && s[i][1] < s[j][1])
}

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

var factStorage = []int64{1, 1, 2}

func solve() {

	n := readInt()
	a := make([]int, n)
	b := make([]int, n)
	c := make(pairs, n)
	for i := 0; i < n; i++ {
		a[i] = readInt()
		b[i] = readInt()
		c[i] = [2]int{a[i], b[i]}
	}

	ans := fact(len(a))
	sort.Ints(a)
	ans -= count(a)
	sort.Ints(b)
	ans -= count(b)
	sort.Sort(c)
	if sort.IsSorted(pairs2(c)) {
		ans += countPairs(c)
	}

	printInt64(ans)

}

func count(a []int) int64 {
	ans := int64(1)
	cnt := 1
	for i := 1; i < len(a); i++ {
		if a[i-1] < a[i] {
			ans = (ans * fact(cnt)) % 998244353
			cnt = 1
		} else {
			cnt++
		}
	}
	ans = (ans * fact(cnt)) % 998244353
	return ans
}

func countPairs(a pairs) int64 {
	ans := int64(1)
	cnt := 1
	for i := 1; i < len(a); i++ {
		if pairs.Less(a, i-1, i) {
			ans = (ans * fact(cnt)) % 998244353
			cnt = 1
		} else {
			cnt++
		}
	}
	ans = (ans * fact(cnt)) % 998244353
	return ans
}

func fact(i int) int64 {
	length := int64(len(factStorage))
	k := int64(i)
	for k >= length {
		next := (factStorage[length-1] * (length % 998244353)) % 998244353
		factStorage = append(factStorage, next)
		length++
	}
	return factStorage[k]
}

/* 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)
	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 printInt64(i int64) {
	print(strconv.FormatInt(i, 10))
}

package main

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

/* solution */

type pairs [][2]int
type pairs2 [][2]int

func (s pairs) Len() int {
	return len(s)
}
func (s pairs) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}
func (s pairs) Less(i, j int) bool {
	return s[i][0] < s[j][0] || (s[i][0] == s[j][0] && s[i][1] < s[j][1])
}

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

var factStorage = []int{1, 1, 2}

func solve() {

	n := readInt()
	a := make([]int, n)
	b := make([]int, n)
	c := make(pairs, n)
	for i := 0; i < n; i++ {
		a[i] = readInt()
		b[i] = readInt()
		c[i] = [2]int{a[i], b[i]}
	}

	ans := fact(len(a))
	sort.Ints(a)
	ans -= count(a)
	sort.Ints(b)
	ans -= count(b)
	sort.Sort(c)
	if sort.IsSorted(pairs2(c)) {
		ans += countPairs(c)
	}

	printInt(ans)

}

func count(a []int) int {
	ans := 1
	cnt := 1
	for i := 1; i < len(a); i++ {
		if a[i-1] < a[i] {
			ans = (ans * fact(cnt)) % 998244353
			cnt = 1
		} else {
			cnt++
		}
	}
	ans = (ans * fact(cnt)) % 998244353
	return ans
}

func countPairs(a pairs) int {
	ans := 1
	cnt := 1
	for i := 1; i < len(a); i++ {
		if pairs.Less(a, i-1, i) {
			ans = (ans * fact(cnt)) % 998244353
			cnt = 1
		} else {
			cnt++
		}
	}
	ans = (ans * fact(cnt)) % 998244353
	return ans
}

func fact(k int) int {
	for k >= len(factStorage) {
		next := (factStorage[len(factStorage)-1] * (len(factStorage) % 998244353)) % 998244353
		factStorage = append(factStorage, next)
	}
	return factStorage[k]
}

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


Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks.  There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank i has initial strength ai.Let us define some keywords before we proceed. Bank i and bank j are neighboring if and only if there exists a wire directly connecting them. Bank i and bank j are semi-neighboring if and only if there exists an online bank k such that bank i and bank k are neighboring and bank k and bank j are neighboring.When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1.To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank x if and only if all these conditions are met:  Bank x is online. That is, bank x is not hacked yet.  Bank x is neighboring to some offline bank.  The strength of bank x is less than or equal to the strength of Inzane's computer. Determine the minimum strength of the computer Inzane needs to hack all the banks.

The first line contains one integer n (1 ≤ n ≤ 3·105) — the total number of banks. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the strengths of the banks. Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — meaning that there is a wire directly connecting banks ui and vi. It is guaranteed that the wires connect the banks in such a way that Inzane can somehow hack all the banks using a computer with appropriate strength.

Print one integer — the minimum strength of the computer Inzane needs to accomplish the goal.

NoteIn the first sample, Inzane can hack all banks using a computer with strength 5. Here is how:  Initially, strengths of the banks are [1, 2, 3, 4, 5].  He hacks bank 5, then strengths of the banks become [1, 2, 4, 5,  - ].  He hacks bank 4, then strengths of the banks become [1, 3, 5,  - ,  - ].  He hacks bank 3, then strengths of the banks become [2, 4,  - ,  - ,  - ].  He hacks bank 2, then strengths of the banks become [3,  - ,  - ,  - ,  - ].  He completes his goal by hacking bank 1. In the second sample, Inzane can hack banks 4, 2, 3, 1, 5, 7, and 6, in this order. This way, he can hack all banks using a computer with strength 93.

package main
import (
    "fmt"
    "os"
    "bufio"
    "math"
    )

func main(){
    in := bufio.NewReader(os.Stdin)
    var n,pos int
    fmt.Fscanf(in,"%d\n",&n)
    strength:=make([]int,n)
    max:=math.MinInt32
    cnt:=0
    for i:=0;i<n;i++{
        fmt.Fscanf(in,"%d",&strength[i])
        if strength[i]>max{
            max=strength[i]
            cnt=1
            pos=i
        }else if strength[i]==max{
            cnt++
        }
    }
    cnt2:=0
    for i:=0;i<n;i++{
        if strength[i]==max-1{
            cnt2++
        }
    }
    fmt.Fscanf(in,"\n")
    G:=make([][]int,n)
    for i:=0;i<n-1;i++{
        var u,v int
        fmt.Fscanf(in,"%d %d\n",&u,&v)
        u--
        v--
        G[u]=append(G[u],v)
        G[v]=append(G[v],u)
    }
    cur:=0
    for _,v:=range G[pos]{
        if strength[v]==max-1{
            cur++
        }
    }
    if cnt==1&&cur==cnt2{
        fmt.Println(max)
        return
    }
    found:=false
    for u:=0;u<n;u++{
        cur=0
        if strength[u]==max{
            cur++
        }
        for _,v:=range G[u]{
            if strength[v]==max{
                cur++
            }
        }
        if(cur==cnt){
            found=true
            break
        }
    }
    if(found){
        fmt.Println(max+1)
        return
    }
    fmt.Println(max+2)
}

package main

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

func main() {
	io := FastIO{reader: bufio.NewReader(os.Stdin), writer: bufio.NewWriter(os.Stdout)}

	N := io.NextInt()

	freq := make(map[int]int)
	nodes := make([]Node, N + 1)
	maxStr := math.MinInt32

	for i := 1; i <= N; i++ {
		A := io.NextInt()
		nodes[i].strength = A
		freq[A + 2]++
		maxStr = Max(maxStr, A)
	}

	for i := 1; i < N; i++ {
		U := io.NextInt()
		V := io.NextInt()
		nodes[U].neighbors = append(nodes[U].neighbors, &nodes[V])
		nodes[V].neighbors = append(nodes[V].neighbors, &nodes[U])
	}

	best := math.MaxInt32
	for i := 1; i <= N; i++ {
		curr := nodes[i]

		freq[curr.strength + 2]--
		freq[curr.strength]++
		for _, next := range curr.neighbors {
			freq[next.strength + 2]--
			freq[next.strength + 1]++
		}

		for s := maxStr + 2; s >= maxStr; s-- {
			if freq[s] > 0 {
				best = Min(best, s)
				break;
			}
		}

		freq[curr.strength + 2]++
		freq[curr.strength]--
		for _, next := range curr.neighbors {
			freq[next.strength + 2]++
			freq[next.strength + 1]--
		}
	}
	io.Printf("%d\n", best)

	io.FlushOutput()
}

type Node struct {
	neighbors []*Node
	strength int
}

func Min(lhs, rhs int) int {
	if lhs < rhs {
		return lhs
	} else {
		return rhs
	}
}

func Max(lhs, rhs int) int {
	if lhs > rhs {
		return lhs
	} else {
		return rhs
	}
}

type FastIO struct {
	reader *bufio.Reader
	writer *bufio.Writer
}

func (io *FastIO) NextChar() byte {
	c, _ := io.reader.ReadByte()
	return c
}

func (io *FastIO) NextInt() int {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := 1
	if (c == '-') {
		sgn = -1
		c = io.NextChar()
	}
	res := 0
	for !IsSpaceChar(c) {
		res = (res * 10) + int(c - '0')
		c = io.NextChar()
	}
	return sgn * res
}

func (io *FastIO) NextLong() int64 {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := int64(1)
	if (c == '-') {
		sgn = -1
		c = io.NextChar()
	}
	res := int64(0)
	for !IsSpaceChar(c) {
		res = (res * 10) + int64(c - '0')
		c = io.NextChar()
	}
	return sgn * res
}

func (io *FastIO) NextIntArray(size int) []int {
	return io.NextIntArrayOffset(size, 0)
}

func (io *FastIO) NextIntArrayOffset(size, offset int) []int {
	arr := make([]int, size + offset)
	for i := 0; i < size; i++ {
		arr[i + offset] = io.NextInt()
	}
	return arr
}

func (io *FastIO) NextLongArray(size int) []int64 {
	return io.NextLongArrayOffset(size, 0)
}

func (io *FastIO) NextLongArrayOffset(size, offset int) []int64 {
	arr := make([]int64, size + offset)
	for i := 0; i < size; i++ {
		arr[i + offset] = io.NextLong()
	}
	return arr
}

func (io *FastIO) NextString() string {
	c := io.NextChar()
	for (IsSpaceChar(c)) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsSpaceChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}

func (io *FastIO) NextLine() string {
	c := io.NextChar()
	for (IsSpaceChar(c)) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsLineBreakChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}

func (io *FastIO) Printf(format string, args ...interface{}) {
	io.writer.WriteString(fmt.Sprintf(format, args...))
}

func (io *FastIO) FlushOutput() {
	io.writer.Flush()
}

func IsSpaceChar(c byte) bool {
	switch c {
	case 0, '\t', '\n', '\r', ' ':
		return true
	default:
		return false
	}
}

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

package main
import (
    "fmt"
    "os"
    "bufio"
    "math"
    )

func main(){
    in := bufio.NewReader(os.Stdin)
    var n int
    fmt.Fscanf(in,"%d\n",&n)
    strength:=make([]int,n)
    max:=math.MinInt32
    cnt:=0
    for i:=0;i<n;i++{
        fmt.Fscanf(in,"%d",&strength[i])
        if strength[i]>max{
            max=strength[i]
            cnt=1
        }else if strength[i]==max{
            cnt++
        }
    }
    fmt.Fscanf(in,"\n")
    G:=make([][]int,n)
    for i:=0;i<n-1;i++{
        var u,v int
        fmt.Fscanf(in,"%d %d\n",&u,&v)
        u--
        v--
        G[u]=append(G[u],v)
        G[v]=append(G[v],u)
    }
    if cnt==1{
        fmt.Println(max)
        return
    }
    found:=false
    for u:=0;u<n;u++{
        cur:=0
        if strength[u]==max{
            cur++
        }
        for _,v:=range G[u]{
            if strength[v]==max{
                cur++
            }
        }
        if(cur==cnt){
            found=true
            break
        }
    }
    if(found){
        fmt.Println(max+1)
        return
    }
    fmt.Println(max+2)
}

package main
import (
    "fmt"
    "os"
    "bufio"
    "math"
    )

func main(){
    in := bufio.NewReader(os.Stdin)
    var n,pos int
    fmt.Fscanf(in,"%d\n",&n)
    strength:=make([]int,n)
    max:=math.MinInt32
    cnt:=0
    for i:=0;i<n;i++{
        fmt.Fscanf(in,"%d",&strength[i])
        if strength[i]>max{
            max=strength[i]
            cnt=1
            pos=i
        }else if strength[i]==max{
            cnt++
        }
    }
    cnt2:=0
    for i:=0;i<n;i++{
        if strength[i]==max-1{
            cnt2++
        }
    }
    fmt.Fscanf(in,"\n")
    G:=make([][]int,n)
    for i:=0;i<n-1;i++{
        var u,v int
        fmt.Fscanf(in,"%d %d\n",&u,&v)
        u--
        v--
        G[u]=append(G[u],v)
        G[v]=append(G[v],u)
    }
    cur:=0
    found:=false
    for _,v:=range G[pos]{
        if strength[v]==max-1{
            cur++
        }
    }
    if cnt==1&&cur==cnt2{
        fmt.Println(max)
        return
    }
    found=false
    for u:=0;u<n;u++{
        cur=0
        if strength[u]>=max-1{
            cur++
        }
        for _,v:=range G[u]{
            if strength[v]>=max-1{
                cur++
            }
        }
        if(cur==cnt+cnt2){
            found=true
            break
        }
    }
    if(found){
        fmt.Println(max+1)
        return
    }
    fmt.Println(max+2)
}


You are given a set of points $$$x_1$$$, $$$x_2$$$, ..., $$$x_n$$$ on the number line.Two points $$$i$$$ and $$$j$$$ can be matched with each other if the following conditions hold:  neither $$$i$$$ nor $$$j$$$ is matched with any other point;  $$$|x_i - x_j| \ge z$$$. What is the maximum number of pairs of points you can match with each other?

The first line contains two integers $$$n$$$ and $$$z$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le z \le 10^9$$$) — the number of points and the constraint on the distance between matched points, respectively. The second line contains $$$n$$$ integers $$$x_1$$$, $$$x_2$$$, ..., $$$x_n$$$ ($$$1 \le x_i \le 10^9$$$).

Print one integer — the maximum number of pairs of points you can match with each other.

NoteIn the first example, you may match point $$$1$$$ with point $$$2$$$ ($$$|3 - 1| \ge 2$$$), and point $$$3$$$ with point $$$4$$$ ($$$|7 - 3| \ge 2$$$).In the second example, you may match point $$$1$$$ with point $$$3$$$ ($$$|5 - 10| \ge 5$$$).

package main

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

type SortableInts64 []int64

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

func solve(j Jam) {
	n, z := j.Int(), j.Int()
	x := make([]int64, n, n)
	for i := range x {
		x[i] = j.Int()
	}
	sort.Sort(SortableInts64(x))
	left, right, matchedPairs := int64(0), (n+1)/2, int64(0)
	for left < right && left < (n+1)/2 && right < n {
		if x[right]-x[left] >= z {
			left += 1
			right += 1
			matchedPairs += 1
		} else {
			right += 1
		}
	}
	j.P("%d\n", matchedPairs)
}

func main() {
	jam, closeFunc := JamNew()
	defer closeFunc()
	solve(jam)
}

type Jam interface {
	Scanner() *bufio.Scanner
	Writer() *bufio.Writer
	Close()

	Str() string
	Int() int64
	Float() float64

	P(format string, values ...interface{})
	PF(format string, values ...interface{})
}

func JamNew() (Jam, func()) {
	if len(os.Args) > 1 {
		panic("running with input file path is not supported")
	}

	var scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 0, 1024*1024), 1024*1024)

	var writer = bufio.NewWriter(os.Stdout)
	jam := &jam{scanner, writer}
	return jam, jam.Close
}

type jam struct {
	sc *bufio.Scanner
	wr *bufio.Writer
}

func (j *jam) Close() {
	if err := j.wr.Flush(); err != nil {
		panic(err)
	}
}

func (j *jam) Scanner() *bufio.Scanner {
	return j.sc
}

func (j *jam) Writer() *bufio.Writer {
	return j.wr
}

func (j *jam) Str() string {
	if !j.sc.Scan() {
		panic("failed to scan next token")
	}

	return j.sc.Text()
}

func (j *jam) Int() int64 {
	if !j.sc.Scan() {
		panic("failed to scan next token")
	}

	res, err := strconv.ParseInt(j.sc.Text(), 10, 64)
	if err != nil {
		panic(err)
	}

	return res
}

func (j *jam) Float() float64 {
	j.sc.Scan()
	res, err := strconv.ParseFloat(j.sc.Text(), 64)
	if err != nil {
		panic(err)
	}
	return res
}

func (j *jam) P(format string, values ...interface{}) {
	_, err := fmt.Fprintf(j.wr, format, values...)
	if err != nil {
		panic(err)
	}
}

func (j *jam) PF(format string, values ...interface{}) {
	_, err := fmt.Fprintf(j.wr, format, values...)
	if err != nil {
		panic(err)
	}
	if err = j.wr.Flush(); err != nil {
		panic(err)
	}
}

package main

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

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

func print(a ...interface{}) { fmt.Fprint(writer, a...) }
func scan(a ...interface{})  { fmt.Fscan(reader, a...) }

const (
	N int = int(2e5+1)
)

var (
	n int
	z int
	a [N](int)
)

func main() {
	// code GOes here

	scan(&n, &z)
	for i:=0; i<n; i++ {
		scan(&a[i])
	}
	sort.Ints(a[:n])

	valid := func(x int) bool {
		for i:=0; i<x; i++ {
			if a[n-x+i] - a[i] < z {
				return false
			}
		}
		return true
	}

	left := 0
	right := n/2
	for left < right {
		mid := (left+right+1)/2
		if valid(mid) {
			left = mid
		} else {
			right = mid-1
		}
	}
	print(left, "\n")

	writer.Flush()
	return
}

package main

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

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

func bscheck(x []int, pr, z int) bool {
    if pr > len(x) / 2 {
        return false
    }

    for i, j := 0, len(x) - pr; i < pr; {
        if x[j] - x[i] < z {
            return false
        }
        i++
        j++
    }

    return true
}

func main() {
    input := bufio.NewScanner(os.Stdin)
    input.Split(bufio.ScanWords)

    input.Scan()
    n, _ := strconv.Atoi(input.Text())

    input.Scan()
    z, _ := strconv.Atoi(input.Text())

    x := make([]int, n, n)
    for i := range x {
        input.Scan()
        x[i], _ = strconv.Atoi(input.Text())
    }
    sort.Ints(x)

    bsl, bsr := 0, n / 2
    ans := 0
    for bsr >= bsl {
        bsmid := (bsl + bsr) / 2
        if bscheck(x, bsmid, z) {
            ans = bsmid
            bsl = bsmid + 1
        } else {
            bsr = bsmid - 1
        }
    }

    fmt.Println(ans)
}

package main

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

var inStream = bufio.NewReader(os.Stdin)
var outStream = bufio.NewWriter(os.Stdout)

func main() {

	defer outStream.Flush()

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

	vec := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(inStream, "%d", &vec[i])
	}

	sort.Ints(vec)

	ans := 0
	half := n >> 1
	for i, j := 0, half; i < half && j < n; j++ {
		if vec[i]+z <= vec[j] {
			i++
			ans++
		}
	}

	//fmt.Fprintf(outStream, "%d, %d", n, z)
	fmt.Fprintln(outStream, ans)

}

package main

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

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

func main() {
    input := bufio.NewScanner(os.Stdin)
    input.Split(bufio.ScanWords)

    input.Scan()
    n, _ := strconv.Atoi(input.Text())

    input.Scan()
    z, _ := strconv.Atoi(input.Text())

    x := make([]int, n, n)
    for i := range x {
        input.Scan()
        x[i], _ = strconv.Atoi(input.Text())
    }
    sort.Ints(x)

    color := make([]bool, n, n)

    l, r := 0, 0
    ans := 0
    for l < n && r < n {
        for l < n && color[l] {
            l++
        }
        if l == n {
            break
        }

        for r = max(l, r); r < n && (x[r] - x[l] < z || color[r]); r++ {
            // void here.
        }
        if r == n {
            break
        }

        color[l] = true
        color[r] = true
        ans++
    }

    fmt.Println(ans)
}

package main

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

func main() {
    input := bufio.NewScanner(os.Stdin)
    input.Split(bufio.ScanWords)

    input.Scan()
    n, _ := strconv.Atoi(input.Text())

    input.Scan()
    z, _ := strconv.Atoi(input.Text())

    x := make([]int, n, n)
    for i := range x {
        input.Scan()
        x[i], _ = strconv.Atoi(input.Text())
    }
    sort.Ints(x)

    color := make([]bool, n, n)

    l, r := 0, 0
    ans := 0
    for r < n {
        for l < n && color[l] {
            l++
        }
        if l == n {
            break
        }

        for r = l; r < n && x[r] - x[l] < z; r++ {
            // void here.
        }
        if r == n {
            break
        }

        color[l] = true
        color[r] = true
        ans++
    }

    fmt.Println(ans)
}