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


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

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
}


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

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

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

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


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)

}


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

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


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


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


package main

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

// github.com/EndlessCheng/codeforces-go
func CF482B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type pair struct{ l, r int }

	var n, q, l, r, v int
	Fscan(in, &n, &q)
	fas := [30][]int{}
	for i := range fas {
		fas[i] = make([]int, n+1)
		for j := range fas[i] {
			fas[i][j] = j
		}
	}
	var find func([]int, int) int
	find = func(fa []int, x int) int {
		if fa[x] != x {
			fa[x] = find(fa, fa[x])
		}
		return fa[x]
	}
	same := func(fa []int, x, y int) bool { return find(fa, x) == find(fa, y) }
	mergeRange := func(fa []int, l, r int) {
		for i := find(fa, l); i < r; i = find(fa, i+1) {
			fa[i] = r
		}
	}
	check0 := [30][]pair{}
	for ; q > 0; q-- {
		Fscan(in, &l, &r, &v)
		l--
		for i, fa := range fas {
			if v>>i&1 == 0 {
				check0[i] = append(check0[i], pair{l, r})
			} else {
				mergeRange(fa, l, r)
			}
		}
	}
	for i, qs := range check0 {
		fa := fas[i]
		for _, q := range qs {
			if same(fa, q.l, q.r) {
				Fprintln(out, "NO")
				return
			}
		}
	}
	ans := make([]int, n)
	for j, fa := range fas {
		for i, f := range fa {
			if f != i {
				ans[i] |= 1 << j
			}
		}
	}
	Fprintln(out, "YES")
	for _, v := range ans {
		Fprint(out, v, " ")
	}
}

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

package main

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

var segTree [300000]int
var l, r, q [100000]int

func treeUpdate(index, l, r, left, right, mask int) {
	mid := (l + r) / 2
	if l == left && r == right {
		segTree[index] |= mask
	} else if mid >= right {
		segTree[index*2+1] |= segTree[index]
		segTree[index*2+2] |= segTree[index]
		treeUpdate(index*2+1, l, mid, left, right, mask)
		segTree[index] = segTree[index*2+1] & segTree[index*2+2]
	} else if mid < left {
		segTree[index*2+1] |= segTree[index]
		segTree[index*2+2] |= segTree[index]
		treeUpdate(index*2+2, mid+1, r, left, right, mask)
		segTree[index] = segTree[index*2+1] & segTree[index*2+2]
	} else {
		segTree[index*2+1] |= segTree[index]
		segTree[index*2+2] |= segTree[index]
		treeUpdate(index*2+1, l, mid, left, mid, mask)
		treeUpdate(index*2+2, mid+1, r, mid+1, right, mask)
		segTree[index] = segTree[index*2+1] & segTree[index*2+2]
	}
}

func treeQuery(index, l, r, left, right int) int {
	mid := (l + r) / 2
	if l == left && r == right {
		return segTree[index]
	} else if mid >= right {
		segTree[index*2+1] |= segTree[index]
		segTree[index*2+2] |= segTree[index]
		return treeQuery(index*2+1, l, mid, left, right)
	} else if mid < left {
		segTree[index*2+1] |= segTree[index]
		segTree[index*2+2] |= segTree[index]
		return treeQuery(index*2+2, mid+1, r, left, right)
	} else {
		segTree[index*2+1] |= segTree[index]
		segTree[index*2+2] |= segTree[index]
		return treeQuery(index*2+1, l, mid, left, mid) & treeQuery(index*2+2, mid+1, r, mid+1, right)
	}
}

func treeTraverse(index, l, r, mask int) {
	if l > r {
		return
	} else if l == r {
		fmt.Printf("%d ", mask|segTree[index])
	} else {
		mid := (l + r) / 2
		treeTraverse(index*2+1, l, mid, mask|segTree[index])
		treeTraverse(index*2+2, mid+1, r, mask|segTree[index])
	}
}

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)
	var n, m int
	fmt.Fscanf(reader, "%d %d\n", &n, &m)
	for i := 0; i < m; i++ {
		fmt.Fscanf(reader, "%d %d %d\n", &l[i], &r[i], &q[i])
		treeUpdate(0, 0, n-1, l[i]-1, r[i]-1, q[i])
	}
	for i := 0; i < m; i++ {
		if treeQuery(0, 0, n-1, l[i]-1, r[i]-1) != q[i] {
			fmt.Printf("NO")
			return
		}
	}
	fmt.Printf("YES\n")
	treeTraverse(0, 0, n-1, 0)
}

package main

import (
	"bufio"
	"bytes"
	"errors"
	"io"
	"math/rand"
	"os"
	"strconv"
	"time"
	"unicode/utf8"
)

// ******************************** CODE STARTS ********************************

const (
	height int = 30
)

var (
	length int
	tree [height][]int
	seg_left []int
	seg_right []int
	seg_value []int
)

func tree_init(n int) {
	length = 1
	for length < n {
		length *= 2
	}
	for i := 0; i < height; i++ {
		tree[i] = make([]int, length * 2)
	}
}

func tree_update(bit, pos, value int) {
	pos += length
	tree[bit][pos] = value
	pos /= 2
	for pos > 0 {
		tree[bit][pos] = minInt(tree[bit][pos * 2], tree[bit][pos * 2 + 1])
		pos /= 2
	}
}

func tree_min(bit, left, right int) int {
	left += length
	right += length

	ans := tree[bit][left]
	for left <= right {
		ans = minInt(ans, tree[bit][left])
		ans = minInt(ans, tree[bit][right])

		left = (left + 1) / 2
		right = (right - 1) / 2
	}

	return ans
}

func solve() {
	n := readInt()
	m := readInt()

	var add [height][]int
	var sub [height][]int
	for i := 0; i < height; i++ {
		add[i] = make([]int, n)
		sub[i] = make([]int, n)
	}

	seg_left = make([]int, m)
	seg_right = make([]int, m)
	seg_value = make([]int, m)

	for i := 0; i < m; i++ {
		seg_left[i] = readInt() - 1
		seg_right[i] = readInt() - 1
		seg_value[i] = readInt()
		for bit := 0; bit < height; bit++ {
			if ((seg_value[i] >> uint(bit)) & 1) == 1 {
				add[bit][seg_left[i]]++
				sub[bit][seg_right[i]]++
			}
		}
	}

	// set 1
	tree_init(n)
  count := 0
	for bit := 0; bit < height; bit++ {
		for i := 0; i < n; i++ {
			count += add[bit][i]
			if count > 0 {
				tree_update(bit, i, 1)
			}
			count -= sub[bit][i]
		}
	}

	// check 0
	for i := 0; i < m; i++ {
		for bit := 0; bit < height; bit++ {
			if ((seg_value[i] >> uint(bit)) & 1) == 0 {
				value := tree_min(bit, seg_left[i], seg_right[i])
				if value == 1 {
					printString("NO")
					printLine()
					return
				}
			}
		}
	}

	// OK, output
	printString("YES")
	printLine()
	for i := 0; i < n; i++ {
		value := 0
		for bit := 0; bit < height; bit++ {
			if tree_min(bit, i, i) == 1 {
				value ^= 1 << uint(bit)
			}
		}
		printInt(value)
		printSpace()
	}
}

// ********************************* CODE ENDS *********************************

// IO.

var (
	scanner *Scanner
	writer  *bufio.Writer
)

func main() {
	input := os.Stdin
	output := os.Stdout
	//	input, _ := os.Open("")
	//	output, _ := os.Create("")

	defer input.Close()
	defer output.Close()

	scanner = NewScanner(input)
	scanner.Split(bufio.ScanWords)

	writer = bufio.NewWriter(output)
	defer writer.Flush()

	rand.Seed(int64(time.Now().Nanosecond()))
	solve()
}

// Read.

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

func readLine() string {
	scanner.Split(bufio.ScanLines)
	defer scanner.Split(bufio.ScanWords)
	return readString()
}

func readInt() int {
	ans, _ := strconv.ParseInt(readString(), 10, 0)
	return int(ans)
}

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

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

// Write.

func printString(value string) {
	writer.WriteString(value)
}

func printLine() {
	printString("\n")
}

func printSpace() {
	printString(" ")
}

func printInt(value int) {
	printString(strconv.FormatInt(int64(value), 10))
}

func printInt64(value int64) {
	printString(strconv.FormatInt(value, 10))
}

func printFloat64(value float64) {
	printString(strconv.FormatFloat(value, 'f', 20, 64))
}

// Tuple

type Tuple struct {
	a, b int
}

func (p Tuple) Equals(key Key) bool {
	return p.a == key.(Tuple).a
}

func (p Tuple) Less(key Key) bool {
	return p.a < key.(Tuple).a
}

// Sorting

type TupleSlice []Tuple

func (p TupleSlice) Len() int {
	return len(p)
}

func (p TupleSlice) Less(j, i int) bool {
	if p[j].a == p[i].a {
		return p[j].b < p[i].b
	} else {
		return p[j].a < p[i].a
	}
}

func (p TupleSlice) Swap(j, i int) {
	p[j], p[i] = p[i], p[j]
}

// Min, max, abs.

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

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

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

func maxInt64(a, b int64) int64 {
	if a > b {
		return a
	} else {
		return b
	}
}

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

func absInt64(a int64) int64 {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

func maxFloat64(a, b float64) float64 {
	if a > b {
		return a
	} else {
		return b
	}
}

func minFloat64(a, b float64) float64 {
	if a < b {
		return a
	} else {
		return b
	}
}

func absFloat64(a float64) float64 {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

// Set Key interface implementations.

type Int int

func (p Int) Equals(key Key) bool {
	return int(p) == int(key.(Int))
}

func (p Int) Less(key Key) bool {
	return int(p) < int(key.(Int))
}

// Set.

type Key interface {
	Equals(key Key) bool
	Less(key Key) bool
}

type node struct {
	key   Key
	left  *node
	right *node
}

func newNode(key Key) *node {
	return &node{key, nil, nil}
}

type SplayTree struct {
	root *node
	tmp  *node
	len  int
}

func NewSplayTree() *SplayTree {
	return &SplayTree{nil, newNode(nil), 0}
}

func rotateLeft(x, p *node) {
	p.right = x.left
	x.left = p
}

func rotateRight(x, p *node) {
	p.left = x.right
	x.right = p
}

func (p *SplayTree) splay(x *node, key Key) *node {
	if x == nil {
		return nil
	}

	left := p.tmp
	right := p.tmp

	for {
		if key.Less(x.key) {
			y := x.left
			if y == nil {
				break
			}
			if key.Less(y.key) { // zig-zig
				rotateRight(y, x)
				x = y
				if x.left == nil {
					break
				}
			}
			// link right
			right.left = x
			right = x
			// move left
			x = x.left
		} else if x.key.Less(key) {
			y := x.right
			if y == nil {
				break
			}
			if y.key.Less(key) { // zig-zig
				rotateLeft(y, x)
				x = y
				if x.right == nil {
					break
				}
			}
			// link left
			left.right = x
			left = x
			// move right
			x = x.right
		} else {
			break
		}
	}

	left.right = x.left
	right.left = x.right
	x.left = p.tmp.right
	x.right = p.tmp.left

	return x
}

// left <= key < right
func (p *SplayTree) split(key Key) (left, right *node) {
	p.root = p.splay(p.root, key)
	if p.root.key.Equals(key) || p.root.key.Less(key) {
		right := p.root.right
		p.root.right = nil
		return p.root, right
	} else {
		left := p.root.left
		p.root.left = nil
		return left, p.root
	}
}

// keys from left tree must be less then keys from right tree
func (p *SplayTree) join(left, right *node) *node {
	if left == nil {
		return right
	} else if right == nil {
		return left
	}
	left = p.splay(left, right.key)
	left.right = right
	return left
}

type Set interface {
	Len() int
	Insert(key Key) error
	Find(key Key) bool
	Remove(key Key) error
}

func NewSet() Set {
	return Set(NewSplayTree())
}

func (p *SplayTree) Len() int {
	return p.len
}

func (p *SplayTree) Insert(key Key) error {
	if p.root == nil {
		p.root = newNode(key)
		p.len++
	} else {
		p.root = p.splay(p.root, key)
		if p.root.key.Equals(key) {
			return errors.New("Such key already exists")
		} else {
			left, right := p.split(key)
			p.root = newNode(key)
			p.root.left = left
			p.root.right = right
			p.len++
		}
	}
	return nil
}

func (p *SplayTree) Find(key Key) bool {
	if p.root == nil {
		return false
	}
	p.root = p.splay(p.root, key)
	return p.root.key.Equals(key)
}

func (p *SplayTree) Remove(key Key) error {
	p.root = p.splay(p.root, key)
	if p.root == nil || !p.root.key.Equals(key) {
		return errors.New("Such key doesn't exist")
	}
	p.root = p.join(p.split(key))
	return nil
}

// Copied scan.go
// Scanner provides a convenient interface for reading data such as
// a file of newline-delimited lines of text. Successive calls to
// the Scan method will step through the 'tokens' of a file, skipping
// the bytes between the tokens. The specification of a token is
// defined by a split function of type SplitFunc; the default split
// function breaks the input into lines with line termination stripped. Split
// functions are defined in this package for scanning a file into
// lines, bytes, UTF-8-encoded runes, and space-delimited words. The
// client may instead provide a custom split function.
//
// Scanning stops unrecoverably at EOF, the first I/O error, or a token too
// large to fit in the buffer. When a scan stops, the reader may have
// advanced arbitrarily far past the last token. Programs that need more
// control over error handling or large tokens, or must run sequential scans
// on a reader, should use bufio.Reader instead.
//
type Scanner struct {
	r            io.Reader // The reader provided by the client.
	split        SplitFunc // The function to split the tokens.
	maxTokenSize int       // Maximum size of a token; modified by tests.
	token        []byte    // Last token returned by split.
	buf          []byte    // Buffer used as argument to split.
	start        int       // First non-processed byte in buf.
	end          int       // End of data in buf.
	err          error     // Sticky error.
}

// SplitFunc is the signature of the split function used to tokenize the
// input. The arguments are an initial substring of the remaining unprocessed
// data and a flag, atEOF, that reports whether the Reader has no more data
// to give. The return values are the number of bytes to advance the input
// and the next token to return to the user, plus an error, if any. If the
// data does not yet hold a complete token, for instance if it has no newline
// while scanning lines, SplitFunc can return (0, nil, nil) to signal the
// Scanner to read more data into the slice and try again with a longer slice
// starting at the same point in the input.
//
// If the returned error is non-nil, scanning stops and the error
// is returned to the client.
//
// The function is never called with an empty data slice unless atEOF
// is true. If atEOF is true, however, data may be non-empty and,
// as always, holds unprocessed text.
type SplitFunc func(data []byte, atEOF bool) (advance int, token []byte, err error)

// Errors returned by Scanner.
var (
	ErrTooLong         = errors.New("bufio.Scanner: token too long")
	ErrNegativeAdvance = errors.New("bufio.Scanner: SplitFunc returns negative advance count")
	ErrAdvanceTooFar   = errors.New("bufio.Scanner: SplitFunc returns advance count beyond input")
)

const (
	// Maximum size used to buffer a token. The actual maximum token size
	// may be smaller as the buffer may need to include, for instance, a newline.
	MaxScanTokenSize = 1 << 20
)

// NewScanner returns a new Scanner to read from r.
// The split function defaults to ScanLines.
func NewScanner(r io.Reader) *Scanner {
	return &Scanner{
		r:            r,
		split:        ScanLines,
		maxTokenSize: MaxScanTokenSize,
		buf:          make([]byte, 4096), // Plausible starting size; needn't be large.
	}
}

// Err returns the first non-EOF error that was encountered by the Scanner.
func (s *Scanner) Err() error {
	if s.err == io.EOF {
		return nil
	}
	return s.err
}

// Bytes returns the most recent token generated by a call to Scan.
// The underlying array may point to data that will be overwritten
// by a subsequent call to Scan. It does no allocation.
func (s *Scanner) Bytes() []byte {
	return s.token
}

// Text returns the most recent token generated by a call to Scan
// as a newly allocated string holding its bytes.
func (s *Scanner) Text() string {
	return string(s.token)
}

// Scan advances the Scanner to the next token, which will then be
// available through the Bytes or Text method. It returns false when the
// scan stops, either by reaching the end of the input or an error.
// After Scan returns false, the Err method will return any error that
// occurred during scanning, except that if it was io.EOF, Err
// will return nil.
func (s *Scanner) Scan() bool {
	// Loop until we have a token.
	for {
		// See if we can get a token with what we already have.
		if s.end > s.start {
			advance, token, err := s.split(s.buf[s.start:s.end], s.err != nil)
			if err != nil {
				s.setErr(err)
				return false
			}
			if !s.advance(advance) {
				return false
			}
			s.token = token
			if token != nil {
				return true
			}
		}
		// We cannot generate a token with what we are holding.
		// If we've already hit EOF or an I/O error, we are done.
		if s.err != nil {
			// Shut it down.
			s.start = 0
			s.end = 0
			return false
		}
		// Must read more data.
		// First, shift data to beginning of buffer if there's lots of empty space
		// or space is neded.
		if s.start > 0 && (s.end == len(s.buf) || s.start > len(s.buf)/2) {
			copy(s.buf, s.buf[s.start:s.end])
			s.end -= s.start
			s.start = 0
		}
		// Is the buffer full? If so, resize.
		if s.end == len(s.buf) {
			if len(s.buf) >= s.maxTokenSize {
				s.setErr(ErrTooLong)
				return false
			}
			newSize := len(s.buf) * 2
			if newSize > s.maxTokenSize {
				newSize = s.maxTokenSize
			}
			newBuf := make([]byte, newSize)
			copy(newBuf, s.buf[s.start:s.end])
			s.buf = newBuf
			s.end -= s.start
			s.start = 0
			continue
		}
		// Finally we can read some input. Make sure we don't get stuck with
		// a misbehaving Reader. Officially we don't need to do this, but let's
		// be extra careful: Scanner is for safe, simple jobs.
		for loop := 0; ; {
			n, err := s.r.Read(s.buf[s.end:len(s.buf)])
			s.end += n
			if err != nil {
				s.setErr(err)
				break
			}
			if n > 0 {
				break
			}
			loop++
			if loop > 100 {
				s.setErr(io.ErrNoProgress)
				break
			}
		}
	}
}

// advance consumes n bytes of the buffer. It reports whether the advance was legal.
func (s *Scanner) advance(n int) bool {
	if n < 0 {
		s.setErr(ErrNegativeAdvance)
		return false
	}
	if n > s.end-s.start {
		s.setErr(ErrAdvanceTooFar)
		return false
	}
	s.start += n
	return true
}

// setErr records the first error encountered.
func (s *Scanner) setErr(err error) {
	if s.err == nil || s.err == io.EOF {
		s.err = err
	}
}

// Split sets the split function for the Scanner. If called, it must be
// called before Scan. The default split function is ScanLines.
func (s *Scanner) Split(split SplitFunc) {
	s.split = split
}

// Split functions

// ScanBytes is a split function for a Scanner that returns each byte as a token.
func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	return 1, data[0:1], nil
}

var errorRune = []byte(string(utf8.RuneError))

// ScanRunes is a split function for a Scanner that returns each
// UTF-8-encoded rune as a token. The sequence of runes returned is
// equivalent to that from a range loop over the input as a string, which
// means that erroneous UTF-8 encodings translate to U+FFFD = "\xef\xbf\xbd".
// Because of the Scan interface, this makes it impossible for the client to
// distinguish correctly encoded replacement runes from encoding errors.
func ScanRunes(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}

	// Fast path 1: ASCII.
	if data[0] < utf8.RuneSelf {
		return 1, data[0:1], nil
	}

	// Fast path 2: Correct UTF-8 decode without error.
	_, width := utf8.DecodeRune(data)
	if width > 1 {
		// It's a valid encoding. Width cannot be one for a correctly encoded
		// non-ASCII rune.
		return width, data[0:width], nil
	}

	// We know it's an error: we have width==1 and implicitly r==utf8.RuneError.
	// Is the error because there wasn't a full rune to be decoded?
	// FullRune distinguishes correctly between erroneous and incomplete encodings.
	if !atEOF && !utf8.FullRune(data) {
		// Incomplete; get more bytes.
		return 0, nil, nil
	}

	// We have a real UTF-8 encoding error. Return a properly encoded error rune
	// but advance only one byte. This matches the behavior of a range loop over
	// an incorrectly encoded string.
	return 1, errorRune, nil
}

// dropCR drops a terminal \r from the data.
func dropCR(data []byte) []byte {
	if len(data) > 0 && data[len(data)-1] == '\r' {
		return data[0 : len(data)-1]
	}
	return data
}

// ScanLines is a split function for a Scanner that returns each line of
// text, stripped of any trailing end-of-line marker. The returned line may
// be empty. The end-of-line marker is one optional carriage return followed
// by one mandatory newline. In regular expression notation, it is `\r?\n`.
// The last non-empty line of input will be returned even if it has no
// newline.
func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	if i := bytes.IndexByte(data, '\n'); i >= 0 {
		// We have a full newline-terminated line.
		return i + 1, dropCR(data[0:i]), nil
	}
	// If we're at EOF, we have a final, non-terminated line. Return it.
	if atEOF {
		return len(data), dropCR(data), nil
	}
	// Request more data.
	return 0, nil, nil
}

// isSpace reports whether the character is a Unicode white space character.
// We avoid dependency on the unicode package, but check validity of the implementation
// in the tests.
func isSpace(r rune) bool {
	if r <= '\u00FF' {
		// Obvious ASCII ones: \t through \r plus space. Plus two Latin-1 oddballs.
		switch r {
		case ' ', '\t', '\n', '\v', '\f', '\r':
			return true
		case '\u0085', '\u00A0':
			return true
		}
		return false
	}
	// High-valued ones.
	if '\u2000' <= r && r <= '\u200a' {
		return true
	}
	switch r {
	case '\u1680', '\u180e', '\u2028', '\u2029', '\u202f', '\u205f', '\u3000':
		return true
	}
	return false
}

// ScanWords is a split function for a Scanner that returns each
// space-separated word of text, with surrounding spaces deleted. It will
// never return an empty string. The definition of space is set by
// unicode.IsSpace.
func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error) {
	// Skip leading spaces.
	start := 0
	for width := 0; start < len(data); start += width {
		var r rune
		r, width = utf8.DecodeRune(data[start:])
		if !isSpace(r) {
			break
		}
	}
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	// Scan until space, marking end of word.
	for width, i := 0, start; i < len(data); i += width {
		var r rune
		r, width = utf8.DecodeRune(data[i:])
		if isSpace(r) {
			return i + width, data[start:i], nil
		}
	}
	// If we're at EOF, we have a final, non-empty, non-terminated word. Return it.
	if atEOF && len(data) > start {
		return len(data), data[start:], nil
	}
	// Request more data.
	return 0, nil, nil
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF482B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type pair struct{ l, r int }

	var n, q, l, r, v int
	Fscan(in, &n, &q)
	fas := [30][]int{}
	for i := range fas {
		fas[i] = make([]int, n+1)
		for j := range fas[i] {
			fas[i][j] = j
		}
	}
	var find func([]int, int) int
	find = func(fa []int, x int) int {
		if fa[x] != x {
			fa[x] = find(fa, fa[x])
		}
		return fa[x]
	}
	same := func(fa []int, x, y int) bool { return find(fa, x) == find(fa, y) }
	mergeRange := func(fa []int, l, r int) {
		for i := find(fa, l); i < r; i = find(fa, i+1) {
			fa[i] = r
		}
	}
	check0 := [30][]pair{}
	for ; q > 0; q-- {
		Fscan(in, &l, &r, &v)
		l--
		for i, fa := range fas {
			if w := v >> i & 1; w == 0 {
				check0[i] = append(check0[i], pair{l, r})
			} else {
				mergeRange(fa, l, r)
			}
		}
	}
	for i, qs := range check0 {
		fa := fas[i]
		for _, q := range qs {
			l, r := q.l, q.r
			if same(fa, l, r) {
				Fprintln(out, "NO")
				return
			}
		}
	}
	ans := make([]int, n)
	for j, fa := range fas {
		for i, f := range fa {
			if f != i {
				ans[i] |= 1 << j
			}
		}
	}
	Fprintln(out, "YES")
	for _, v := range ans {
		Fprint(out, v, " ")
	}
}

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

package main

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

var segTree [300000]int
var l, r, q [100000]int

func treeUpdate(index, l, r, left, right, mask int) {
	mid := (l + r) / 2
	if l == left && r == right {
		segTree[index] |= mask
	} else if mid >= right {
		treeUpdate(index*2+1, l, mid, left, right, mask)
		segTree[index] = segTree[index*2+1] & segTree[index*2+2]
	} else if mid < left {
		treeUpdate(index*2+2, mid+1, r, left, right, mask)
		segTree[index] = segTree[index*2+1] & segTree[index*2+2]
	} else {
		treeUpdate(index*2+1, l, mid, left, mid, mask)
		treeUpdate(index*2+2, mid+1, r, mid+1, right, mask)
		segTree[index] = segTree[index*2+1] & segTree[index*2+2]
	}
}

func treeQuery(index, l, r, left, right int) int {
	mid := (l + r) / 2
	if l == left && r == right {
		return segTree[index]
	} else if mid >= right {
		return treeQuery(index*2+1, l, mid, left, right)
	} else if mid < left {
		return treeQuery(index*2+2, mid+1, r, left, right)
	} else {
		return treeQuery(index*2+1, l, mid, left, mid) & treeQuery(index*2+2, mid+1, r, mid+1, right)
	}
}

func treeTraverse(index, l, r, mask int) {
	if l > r {
		return
	} else if l == r {
		fmt.Printf("%d ", mask|segTree[index])
	} else {
		mid := (l + r) / 2
		treeTraverse(index*2+1, l, mid, mask|segTree[index])
		treeTraverse(index*2+2, mid+1, r, mask|segTree[index])
	}
}

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)
	var n, m int
	fmt.Fscanf(reader, "%d %d\n", &n, &m)
	for i := 0; i < m; i++ {
		fmt.Fscanf(reader, "%d %d %d\n", &l[i], &r[i], &q[i])
		treeUpdate(0, 0, n-1, l[i]-1, r[i]-1, q[i])
	}
	for i := 0; i < m; i++ {
		if treeQuery(0, 0, n-1, l[i]-1, r[i]-1) != q[i] {
			fmt.Printf("NO")
			return
		}
	}
	fmt.Printf("YES\n")
	treeTraverse(0, 0, n-1, 0)
}

package main

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

var segTree [300000]int
var l, r, q [100000]int

func treeUpdate(index, l, r, left, right, mask int) {
	mid := (l + r) / 2
	if l == left && r == right {
		segTree[index] |= mask
	} else if mid >= right {
		segTree[index*2+1] |= segTree[index]
		segTree[index*2+2] |= segTree[index]
		treeUpdate(index*2+1, l, mid, left, right, mask)
		segTree[index] = segTree[index*2+1] & segTree[index*2+2]
	} else if mid < left {
		segTree[index*2+1] |= segTree[index]
		segTree[index*2+2] |= segTree[index]
		treeUpdate(index*2+2, mid+1, r, left, right, mask)
		segTree[index] = segTree[index*2+1] & segTree[index*2+2]
	} else {
		segTree[index*2+1] |= segTree[index]
		segTree[index*2+2] |= segTree[index]
		treeUpdate(index*2+1, l, mid, left, mid, mask)
		treeUpdate(index*2+2, mid+1, r, mid+1, right, mask)
		segTree[index] = segTree[index*2+1] & segTree[index*2+2]
	}
}

func treeQuery(index, l, r, left, right int) int {
	mid := (l + r) / 2
	if l == left && r == right {
		return segTree[index]
	} else if mid >= right {
		segTree[index*2+1] |= segTree[index]
		segTree[index*2+2] |= segTree[index]
		return treeQuery(index*2+1, l, mid, left, right)
	} else if mid < left {
		segTree[index*2+1] |= segTree[index]
		segTree[index*2+2] |= segTree[index]
		return treeQuery(index*2+2, mid+1, r, left, right)
	} else {
		segTree[index*2+1] |= segTree[index]
		segTree[index*2+2] |= segTree[index]
		return treeQuery(index*2+1, l, mid, left, mid) & treeQuery(index*2+2, mid+1, r, mid+1, right)
	}
}

func treeTraverse(index, l, r, mask int) {
	if l > r {
		return
	} else if l == r {
		fmt.Printf("%d ", mask|segTree[index])
	} else {
		mid := (l + r) / 2
		treeTraverse(index*2+1, l, mid, mask|segTree[index])
		treeTraverse(index*2+2, mid+1, r, mask|segTree[index])
	}
}

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)
	var n, m int
	fmt.Fscanf(reader, "%d %d\n", &n, &m)
	for i := 0; i < m; i++ {
		fmt.Fscanf(reader, "%d %d %d\n", &l[i], &r[i], &q[i])
		treeUpdate(0, 0, n-1, l[i]-1, r[i]-1, q[i])
	}
	treeTraverse(0, 0, n-1, 0)
	fmt.Printf("\n")
	for i := 0; i < m; i++ {
		if treeQuery(0, 0, n-1, l[i]-1, r[i]-1) != q[i] {
			fmt.Printf("NO #%d ans = %d", i, treeQuery(0, 0, n-1, l[i]-1, r[i]-1))
			return
		}
	}
	fmt.Printf("YES\n")
}

package main

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

var segTree [300000]int
var l, r, q [100000]int

func treeUpdate(index, l, r, left, right, mask int) {
	mid := (l + r) / 2
	if l == left && r == right {
		segTree[index] |= mask
	} else if mid >= right {
		treeUpdate(index*2+1, l, mid, left, right, mask)
		segTree[index] = segTree[index*2+1] & segTree[index*2+2]
	} else if mid < left {
		treeUpdate(index*2+2, mid+1, r, left, right, mask)
		segTree[index] = segTree[index*2+1] & segTree[index*2+2]
	} else {
		treeUpdate(index*2+1, l, mid, left, mid, mask)
		treeUpdate(index*2+2, mid+1, r, mid+1, right, mask)
		segTree[index] = segTree[index*2+1] & segTree[index*2+2]
	}
}

func treeQuery(index, l, r, left, right int) int {
	mid := (l + r) / 2
	if l == left && r == right {
		return segTree[index]
	} else if mid >= right {
		segTree[index*2+1] |= segTree[index]
		segTree[index*2+2] |= segTree[index]
		return treeQuery(index*2+1, l, mid, left, right)
	} else if mid < left {
		segTree[index*2+1] |= segTree[index]
		segTree[index*2+2] |= segTree[index]
		return treeQuery(index*2+2, mid+1, r, left, right)
	} else {
		segTree[index*2+1] |= segTree[index]
		segTree[index*2+2] |= segTree[index]
		return treeQuery(index*2+1, l, mid, left, mid) & treeQuery(index*2+2, mid+1, r, mid+1, right)
	}
}

func treeTraverse(index, l, r, mask int) {
	if l > r {
		return
	} else if l == r {
		fmt.Printf("%d ", mask|segTree[index])
	} else {
		mid := (l + r) / 2
		treeTraverse(index*2+1, l, mid, mask|segTree[index])
		treeTraverse(index*2+2, mid+1, r, mask|segTree[index])
	}
}

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)
	var n, m int
	fmt.Fscanf(reader, "%d %d\n", &n, &m)
	for i := 0; i < m; i++ {
		fmt.Fscanf(reader, "%d %d %d\n", &l[i], &r[i], &q[i])
		treeUpdate(0, 0, n-1, l[i]-1, r[i]-1, q[i])
	}
	for i := 0; i < m; i++ {
		if treeQuery(0, 0, n-1, l[i]-1, r[i]-1) != q[i] {
			fmt.Printf("NO")
			return
		}
	}
	fmt.Printf("YES\n")
	treeTraverse(0, 0, n-1, 0)
}


package main

import (
	"fmt"
)

func main() {
	var n,t int
	fmt.Scanf("%d%d",&n,&t)
	//fmt.Println(n,t)
	tme := make([]int,n)
	for i:= 0;i < n;i++{
		fmt.Scan(&tme[i])
		t -= (86400 - tme[i])
		//fmt.Println(tme[i],t)
		if t <= 0 {
			fmt.Println(i + 1)
			return
		}
	}
}

package main

import "fmt"

func main() {
	var n, t int
	fmt.Scanf("%d %d\n", &n, &t)

	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}

	for i := 0; i < n; i++ {
		t = t - (86400 - a[i])
		if t <= 0 {
			fmt.Println(i + 1)
			break
		}
	}
}

package main

import "fmt"

func main() {
	var (
		n, t int
	)
	fmt.Scanf("%d%d\n", &n, &t)
	for i := 1; i <= n; i++ {
		var a int
		fmt.Scanf("%d", &a)
		t -= 86400 - a
		if t <= 0 {
			fmt.Println(i)
			break
		}
	}
}

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[:len(b):len(b)]
}

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

// Read next line as []byte.  Trailing '\n' will not be included.
// See also comments on readb()
func readbln() []byte {
	b, err := nextLine()
	if err != nil {
		panic(err)
	}
	return b[:len(b):len(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...)
}

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

// Utilities

func sumSlice(a []int) int {
	var res int
	for _, v := range a {
		res += v
	}
	return res
}

func sumSlicell(a []int64) int64 {
	var res int64
	for _, v := range a {
		res += v
	}
	return res
}

func readInts(N int) (int, []int) {
	if N == 0 {
		N = readi()
	}
	a := make([]int, N)
	for i := range a {
		a[i] = readi()
	}
	return N, a
}

func readIntsll(N int) (int, []int64) {
	if N == 0 {
		N = readi()
	}
	a := make([]int64, N)
	for i := range a {
		a[i] = readll()
	}
	return N, a
}

// reverse slice in place
func reverse(a []int) {
	for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
		a[i], a[j] = a[j], a[i]
	}
}

// areverse: allocating reverse
func areverse(a []int) []int {
	b := make([]int, len(a))
	for i := range a {
		b[i] = a[len(a)-i-1]
	}
	return b
}

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

// Simple math functions

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

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

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

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

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

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

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

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

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

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

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

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

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

func main() {
	defer Flush()

	n := readi()
	t := readi()
	_, a := readInts(n)

	var i int
	for ; i < n && 0 < t; i++ {
		t -= (86400 - a[i])
	}
	println(i)

}

package main

import (
	"fmt"
)

func main() {
	var n,t int
	fmt.Scanf("%d%d",&n,&t)
	tme := make([]int,n)
	for i:= 0;i < n;i++{
		fmt.Scanf("%d",&tme[i])
		t -= 86400 - tme[i]
		if t <= 0 {
			fmt.Println(i + 1)
			break
		}
	}
}

package main

import (
	"fmt"
)

func main() {
	var n,t int
	fmt.Scanf("%d%d",&n,&t)
	fmt.Println(n,t)
	tme := make([]int,n)
	for i:= 0;i < n;i++{
		fmt.Scanf("%d",&tme[i])
		t -= (86400 - tme[i])
		if t <= 0 {
			fmt.Println(i + 1)
			break
		}
	}
}

package main

import (
	"fmt"
)

func main() {
	var n,t int
	fmt.Scanf("%d%d",&n,&t)
	fmt.Println(n,t)
	tme := make([]int,n)
	for i:= 0;i < n;i++{
		fmt.Scanf("%d",&tme[i])
		t -= (86400 - tme[i])
		fmt.Println(tme[i],t)
		if t <= 0 {
			fmt.Println(i + 1)
			break
		}
	}
}

package main

import (
	"fmt"
)

func main() {
	var n,t int
	fmt.Scanf("%d%d",&n,&t)
	tme := make([]int,n)
	for i:= 0;i < n;i++{
		fmt.Scanf("%d",&tme[i])
		t -= (86400 - tme[i])
		if t <= 0 {
			fmt.Println(i + 1)
			break
		}
	}
	//fmt.Println(n,t,tme[0],tme[1])
}

package main

import (
	"fmt"
	)

func main() {
	var n,t int
	fmt.Scanf("%d%d",&n,&t)
	tme := make([]int,n)
	for i:= 0;i < n;i++{
		fmt.Scanf("%d",&tme[i])
		t -= 86400 - tme[i]
		if t <= 0 {
			fmt.Println(i + 1)
			return
		}
	}
}

package main

import (
	"fmt"
)

func main() {
	var n,t int
	fmt.Scanf("%d%d",&n,&t)
	tme := make([]int,n)
	for i:= 0;i < n;i++{
		fmt.Scanf("%d",&tme[i])
		t -= 86400 - tme[i]
		if t <= 0 {
			fmt.Println(i + 1)
			break
		}
	}
	fmt.Println(n,t,tme[0],tme[1])
}

package main

import "fmt"

func main() {
	var n, t int
	fmt.Scanf("%d%d", &n, &t)

	ans := 0
	for i := 1; t > 0 && i <= n; i++ {
		var x int
		fmt.Scanf("%d", &x)
		t -= 86400 - x
		ans++
	}
	fmt.Println(ans)
}

package main

import "fmt"

func main() {
	var (
		n int
		t int
	)
	fmt.Scanf("%d%d", &n, &t)

	ans := 0
	for i := 1; t > 0 && i <= n; i++ {
		var x int
		fmt.Scanf("%d", &x)
		t -= 86400 - x
		ans++
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
)

func main() {

	var n, t int

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

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

	var ok bool

	for i := 0; i < n; i++ {
		if t <= 0 {
			fmt.Println(i)
			ok = true
			break
		}

		t -= (86400 - a[i])

	}
	if !ok {
		fmt.Println(n)
	}
}

package main

import (
	"fmt"
)

func main() {

	var n, t int

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

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

	var ok bool

	for i := 0; i < n; i++ {
		if t == 0 {
			fmt.Println(i)
			ok = true
			break
		}

		t -= (86400 - a[i])

	}
	if !ok {
		fmt.Println(n)
	}
}

package main

import (
	"fmt"
)

func main() {

	var n, t int

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

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

	var ok bool

	for i := 0; i < n; i++ {
		if t <= 0 {
			//fmt.Println(t)
			fmt.Println(i)
			ok = true
			break
		}

		t -= (86400 - a[i])

	}
	if !ok {
		fmt.Println(n)
	}
}