package main

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

type int = int64

type breakPoint struct {
	hours int
	sum   int
}

func solve(h int, a []int32) int {
	var r, sum int64

	L := len(a)

	j, t, k := -1, int64(0), -1
	bpts := make([]breakPoint, L+1)

	for i, n := range a {
		sum += int64(n)

		t += int64(n)

		if t < 0 || i == L-1 {
			k++
			bpts[k] = breakPoint{
				hours: int64(i - j),
				sum:   t,
			}

			t = 0
			j = i
		}

		if -sum >= h {
			return int64(i + 1)
		}
	}

	if sum >= 0 {
		return -1
	}

	bpts = bpts[:k+1]

	c := h / -sum

	r += c * int64(len(a))

	ans := r

	winCondition := func(h int) (bool, int) {
		var r int64

		for _, point := range bpts {
			if h <= 0 {
				return true, r
			}
			r += point.hours
			h += point.sum
		}

		return h <= 0, r
	}

	left, right := int64(0), r-1

	for left < right-1 {
		//	fmt.Println(left, right)
		mid := (left + right) >> 1
		condition, res := winCondition(h + sum*mid)

		if condition {
			ans = res + mid*int64(len(a))
			right = mid
		} else {
			left = mid
		}
	}

	return ans
}

func toInt(buf []byte) int32 {
	n, mul := int32(0), int32(1)
	for i, v := range buf {
		if i == 0 && v == '-' {
			mul = -1
			continue
		}
		n = n*10 + int32(v-'0')
	}

	return mul * n
}

func main() {
	var h, r int64
	fmt.Scan(&h, &r)

	a := make([]int32, r)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := range a {
		scanner.Scan()
		a[i] = toInt(scanner.Bytes())
	}

	ans := solve(h, a)
	fmt.Println(ans)
}

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

package main

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

func sum(d []int64) int64 {
	sum := int64(0)
	for _, elem := range d {
		sum += elem
	}
	return sum
}

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

func ceilDiv(x int64, y int64) int64 {
	return (x + y - 1) / y
}

func Solve(H int64, n int64, d []int64) int64 {
	prefix := int64(0)
	for i := int64(0); i < n; i++ {
		prefix += d[i]
		if H+prefix <= 0 {
			return i + 1
		}
	}
	sum := sum(d)
	if sum >= 0 {
		return -1
	}
	prefix = int64(0)
	minutes := int64(math.MaxInt64)
	for i := int64(0); i < n; i++ {
		prefix += d[i]
		cycles := ceilDiv(H+prefix, -sum)
		minutes = min(minutes, cycles*n+i+1)
	}
	return minutes
}

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

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

package main

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

func main() {
	buf := bufio.NewReader(os.Stdin)
	var n int
	var h int64
	fmt.Fscanf(buf, "%d %d\n", &h, &n)
	mat := make([]int64, n+1)
	mat[0] = 0
	minn := int64(0)
	for i := 1; i <= n; i++ {
		fmt.Fscanf(buf, "%d", &mat[i])
		mat[i] += mat[i-1]
		if i == 1 || mat[i] < minn {
			minn = mat[i]
		}
	}
	for i := 1; i <= n; i++ {
		if mat[i] + h <=0 {
			fmt.Printf("%d\n", i)
			return
		}
	}
	if mat[n] >= 0 {
		fmt.Printf("-1\n")
		return
	}
	hh := h + minn
	ans := 1 + (hh-1)/(0-mat[n])
	h += ans * mat[n]
	ans = ans * int64(n)
	//fmt.Printf("h=%d ans=%d\n", h,ans)

	for i := 1; h>0&&i <= n; i++ {
		ans++
		if mat[i]+h <= 0 {
			break
		}
	}
	fmt.Printf("%d\n", ans)

}

/*
1 10
10
1 1 2 1 1 1 2 1 1 1
1 1 1 1 1 1 1 1 1 1
1
1 1
*/

package main

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

func main() {
	buf := bufio.NewReader(os.Stdin)
	var n int
	var h int64
	fmt.Fscanf(buf, "%d %d\n", &h, &n)
	mat := make([]int64, n+1)
	mat[0] = 0
	minn := int64(0)
	for i := 1; i <= n; i++ {
		fmt.Fscanf(buf, "%d", &mat[i])
		mat[i] += mat[i-1]
		if i == 1 || mat[i] < minn {
			minn = mat[i]
		}
	}
	for i := 1; i <= n; i++ {
		if mat[i] >= h {
			fmt.Printf("%d\n", i)
			return
		}
	}
	if mat[n] >= 0 {
		fmt.Printf("-1\n")
		return
	}
	hh := h + minn
	ans := 1 + (hh-1)/(0-mat[n])
	h += ans * mat[n]
	ans = ans * int64(n)
	//fmt.Printf("h=%d ans=%d\n", h,ans)

	for i := 1; h>0&&i <= n; i++ {
		ans++
		if mat[i]+h <= 0 {
			break
		}
	}
	fmt.Printf("%d\n", ans)

}

/*
1 10
10
1 1 2 1 1 1 2 1 1 1
1 1 1 1 1 1 1 1 1 1
1
1 1
*/

package main

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

type int = int64

type breakPoint struct {
	hours int
	sum   int
}

func solve(h int, a []int32) int {
	var r, sum int64

	L := len(a)

	j, t, k := -1, int64(0), -1
	bpts := make([]breakPoint, L+1)

	max := int32(-1)

	for i, n := range a {
		sum += int64(n)

		t += int64(n)

		if t < 0 || i == L-1 {
			k++
			bpts[k] = breakPoint{
				hours: int64(i - j),
				sum:   t,
			}

			t = 0
			j = i
		}

		if n > max {
			max = n
		}

		if -sum >= h {
			return int64(i + 1)
		}
	}

	if sum >= 0 {
		return -1
	}

	bpts = bpts[:k+1]

	c := h / -sum
	if max > 0 && c >= int64(max>>1) {
		c -= int64(max >> 1)
	}

	r += c * int64(len(a))

	h += c * sum

	//	fmt.Println(max>>1, h/-sum, c)

	ans := r

	k = 0
	for ok := true; ok; {
		k++

		ok = false
		for i := len(bpts) - 1; i >= 0; i-- {
			r -= bpts[i].hours
			h -= bpts[i].sum

			if h <= 0 {
				ok = true
				ans = r
			}
		}
	}
	//fmt.Println(k)

	return ans
}

func toInt(buf []byte) int32 {
	n, mul := int32(0), int32(1)
	for i, v := range buf {
		if i == 0 && v == '-' {
			mul = -1
			continue
		}
		n = n*10 + int32(v-'0')
	}

	return mul * n
}

func main() {
	var h, r int64
	fmt.Scan(&h, &r)

	a := make([]int32, r)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := range a {
		scanner.Scan()
		a[i] = toInt(scanner.Bytes())
	}

	ans := solve(h, a)
	fmt.Println(ans)
}

package main

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

func solve(h int, a []int) int {
	r := 0
	sum := 0
	//t := h
	for i, n := range a {
		sum += n

		//		t += n
		//1fmt.Println(t)

		if sum >= h {
			return i + 1
		}
	}

	if sum >= 0 {
		return -1
	}

	c := h/-sum - 1
	r += c * len(a)

	h += c * sum

	for i := 0; h > 0; i++ {
		h += a[i]
		r++
	}

	return r
}

func toInt(buf []byte) int {
	n, mul := 0, 1
	for i, v := range buf {
		if i == 0 && v == '-' {
			mul = -1
			continue
		}
		n = n*10 + int(v-'0')
	}

	return mul * n
}

func main() {
	h, r := 0, 0
	fmt.Scan(&h, &r)

	a := make([]int, r)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := range a {
		scanner.Scan()
		a[i] = toInt(scanner.Bytes())
	}

	ans := solve(h, a)
	fmt.Println(ans)
}

package main

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

type int = int64

func solve(h int, a []int) int {
	var r, sum int64
	//t := h
	for i, n := range a {
		sum += n

		//		t += n
		//1fmt.Println(t)

		if -sum >= h {
			return int64(i + 1)
		}
	}

	if sum >= 0 {
		return -1
	}

	c := h/-sum - 1
	r += c * int64(len(a))

	h += c * sum

	//fmt.Println(h)

	for i := 0; h > 0; i++ {
		h += a[i]
		r++
	}

	return r
}

func toInt(buf []byte) int {
	n, mul := int64(0), int64(1)
	for i, v := range buf {
		if i == 0 && v == '-' {
			mul = -1
			continue
		}
		n = n*10 + int64(v-'0')
	}

	return mul * n
}

func main() {
	var h, r int64
	fmt.Scan(&h, &r)

	a := make([]int, r)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := range a {
		scanner.Scan()
		a[i] = toInt(scanner.Bytes())
	}

	ans := solve(h, a)
	fmt.Println(ans)
}

package main

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

type int = int64

type breakPoint struct {
	hours int
	sum   int
}

func solve(h int, a []int32) int {
	var r, sum int64

	L := len(a)

	j, t, k := -1, int64(0), -1
	bpts := make([]breakPoint, L+1)

	for i, n := range a {
		sum += int64(n)

		t += int64(n)

		if t < 0 || i == L-1 {
			k++
			bpts[k] = breakPoint{
				hours: int64(i - j),
				sum:   t,
			}

			t = 0
			j = i
		}

		if -sum >= h {
			return int64(i + 1)
		}
	}

	if sum >= 0 {
		return -1
	}

	bpts = bpts[:k+1]

	c := h / -sum
	r += c * int64(len(a))

	h += c * sum

	var ans int

	k = 0
	for ok := true; ok; {
		k++
		if k > 50 {
			fmt.Println(bpts)
			return h
		}

		ok = false
		for i := len(bpts) - 1; i >= 0; i-- {
			r -= bpts[i].hours
			h -= bpts[i].sum

			if h <= 0 {
				ok = true
				ans = r
			}
		}
	}

	return ans
}

func toInt(buf []byte) int32 {
	n, mul := int32(0), int32(1)
	for i, v := range buf {
		if i == 0 && v == '-' {
			mul = -1
			continue
		}
		n = n*10 + int32(v-'0')
	}

	return mul * n
}

func main() {
	var h, r int64
	fmt.Scan(&h, &r)

	a := make([]int32, r)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := range a {
		scanner.Scan()
		a[i] = toInt(scanner.Bytes())
	}

	ans := solve(h, a)
	fmt.Println(ans)
}

package main

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

type int = int64

type breakPoint struct {
	hours int
	sum   int
}

func solve(h int, a []int32) int {
	var r, sum int64

	L := len(a)

	j, t, k := -1, int64(0), -1
	bpts := make([]breakPoint, L+1)

	max := int64(-1)

	for i, n := range a {
		sum += int64(n)

		t += int64(n)

		if t < 0 || i == L-1 {
			k++
			bpts[k] = breakPoint{
				hours: int64(i - j),
				sum:   t,
			}

			t = 0
			j = i
		}

		if t > max {
			max = t
		}

		if -sum >= h {
			return int64(i + 1)
		}
	}

	if sum >= 0 {
		return -1
	}

	bpts = bpts[:k+1]

	c := h / -sum
	if max > 0 && len(a) > 100000 {
		c -= int64(max)
	}

	r += c * int64(len(a))

	h += c * sum

	//	fmt.Println(max>>1, h/-sum, c)

	ans := r

	k = 0
	for ok := true; ok; {
		k++

		ok = false
		for i := len(bpts) - 1; i >= 0; i-- {
			r -= bpts[i].hours
			h -= bpts[i].sum

			if h <= 0 {
				ok = true
				ans = r
			}
		}
	}
	//fmt.Println(k)

	return ans
}

func toInt(buf []byte) int32 {
	n, mul := int32(0), int32(1)
	for i, v := range buf {
		if i == 0 && v == '-' {
			mul = -1
			continue
		}
		n = n*10 + int32(v-'0')
	}

	return mul * n
}

func main() {
	var h, r int64
	fmt.Scan(&h, &r)

	a := make([]int32, r)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := range a {
		scanner.Scan()
		a[i] = toInt(scanner.Bytes())
	}

	ans := solve(h, a)
	fmt.Println(ans)
}

package main

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

type int = int64

type breakPoint struct {
	hours int
	sum   int
}

func solve(h int, a []int32) int {
	var r, sum int64

	L := len(a)

	j, t, k := -1, int64(0), -1
	bpts := make([]breakPoint, L+1)

	for i, n := range a {
		sum += int64(n)

		t += int64(n)

		if t < 0 || i == L-1 {
			k++
			bpts[k] = breakPoint{
				hours: int64(i - j),
				sum:   t,
			}

			t = 0
			j = i
		}

		if -sum >= h {
			return int64(i + 1)
		}
	}

	if sum >= 0 {
		return -1
	}

	bpts = bpts[:k+1]

	c := h / -sum
	r += c * int64(len(a))

	h += c * sum

	var ans int

	k = 0
	for ok := true; ok; {
		k++
		if k > 5 {
			fmt.Println(bpts)
			return h
		}

		ok = false
		for i := len(bpts) - 1; i >= 0; i-- {
			r -= bpts[i].hours
			h -= bpts[i].sum

			if h <= 0 {
				ok = true
				ans = r
			}
		}
	}

	return ans
}

func toInt(buf []byte) int32 {
	n, mul := int32(0), int32(1)
	for i, v := range buf {
		if i == 0 && v == '-' {
			mul = -1
			continue
		}
		n = n*10 + int32(v-'0')
	}

	return mul * n
}

func main() {
	var h, r int64
	fmt.Scan(&h, &r)

	a := make([]int32, r)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := range a {
		scanner.Scan()
		a[i] = toInt(scanner.Bytes())
	}

	ans := solve(h, a)
	fmt.Println(ans)
}

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

package main

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

func sum(d []int64) int64 {
	sum := int64(0)
	for _, elem := range d {
		sum += elem
	}
	return sum
}

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

func ceilDiv(x int64, y int64) int64 {
	return (x + y - 1) / y
}

func Solve(H int64, n int64, d []int64) int64 {
	sum := sum(d)
	if sum >= 0 {
		return -1
	}
	prefix := int64(0)
	for i := int64(0); i < n; i++ {
		prefix += d[i]
		if H+prefix <= 0 {
			return i + 1
		}
	}
	prefix = int64(0)
	minutes := int64(math.MaxInt64)
	for i := int64(0); i < n; i++ {
		prefix += d[i]
		cycles := ceilDiv(H+prefix, -sum)
		minutes = min(minutes, cycles*n+i+1)
	}
	return minutes
}

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

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


package main
import (
    "fmt"
    "bufio"
    "io"
    "os"
)
const N int = 2e5+10
var n, m int
var s string
var rules = [6]string{"abc", "acb", "bac", "bca", "cab", "cba"}
var dp [N][6]int
func main() {
    var input io.Reader = bufio.NewReader(os.Stdin)
    fmt.Fscan(input, &n)
    fmt.Fscan(input, &m)
    fmt.Fscan(input, &s)
    for i := 0; i < n; i++ {
        for j := 0; j < 6; j++ {
            var value int = 0
            if s[i] != rules[j][i%3] {
                value = 1
            }
            dp[i][j] = value
            if i > 0 {
                dp[i][j] += dp[i-1][j]
            }
        }
    }
    var l, r int
    for ; m > 0; m-- {
        fmt.Fscan(input, &l)
        fmt.Fscan(input, &r)
        var ans int = 1e9
        for i := 0; i < 6; i++ {
            var value int = dp[r-1][i]
            if l > 1 {
                value -= dp[l-2][i]
            }
            if value < ans {
                ans = value
            }
        }
        fmt.Println(ans)
    }
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := os.Stdout
	var n, m int
	fmt.Fscan(in,&n,&m)
	var b []byte
	fmt.Fscan(in,&b)
	var f1 []byte
	f1 = []byte("abc")

	var cst [7][300005]int
	for i:=1;i<=6;i++{
		if i==1{
			f1 = []byte("abc")
		}
		if i==2{
			f1 = []byte("cba")
		}
		if i==3{
			f1 = []byte("bca")
		}
		if i==4{
			f1 = []byte("cab")
		}
		if i==5{
			f1 = []byte("bac")
		}
		if i==6{
			f1 = []byte("acb")
		}
		for j:=0;j<n;j++{
			v:=0
			if f1[j%3] != b[j]{
				v=1
			}
			cst[i][j+1]=cst[i][j] + v
		}
	}
	for i:=1;i<=m;i++{
		var l, r int
		fmt.Fscan(in,&l,&r)
		ans := 999999999
		for j:=1;j<=6;j++{
			if ans > cst[j][r]-cst[j][l-1]{
				ans = cst[j][r]-cst[j][l-1]
			}
		}
		fmt.Fprintln(out,ans)
	}
}

package main

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

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

func minWithin(c [6]int) int {
	result := c[0]
	for i := 1; i < 6; i++ {
		if result > c[i] {
			result = c[i]
		}
	}
	return result
}

func main() {
	defer out.Flush()

	var n, m int
	fmt.Fscan(in, &n)
	fmt.Fscan(in, &m)

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

	seeds := []string{
		"abc",
		"acb",
		"bac",
		"bca",
		"cab",
		"cba",
	}

	costs := make([][6]int, n)
	for i, seed := range seeds {
		acc := 0
		for j := 0; j < n; j++ {
			if seed[j%3] != s[j] {
				acc++
			}
			costs[j][i] = acc
		}
	}

	for i := 0; i < m; i++ {
		var l, r int
		fmt.Fscan(in, &l)
		fmt.Fscan(in, &r)
		l--
		r--

		var candi [6]int
		for j := 0; j < 6; j++ {
			left := 0
			if l > 0 {
				left = costs[l-1][j]
			}
			candi[j] = costs[r][j] - left
		}
		fmt.Fprintln(out, minWithin(candi))
	}
}

package main

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

var in = bufio.NewReader(os.Stdin)

func minWithin(c [6]int) int {
	result := c[0]
	for i := 1; i < 6; i++ {
		if result > c[i] {
			result = c[i]
		}
	}
	return result
}

func main() {
	var n, m int
	fmt.Fscan(in, &n)
	fmt.Fscan(in, &m)

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

	seeds := []string{
		"abc",
		"acb",
		"bac",
		"bca",
		"cab",
		"cba",
	}

	costs := make([][6]int, n)
	for i, seed := range seeds {
		acc := 0
		for j := 0; j < n; j++ {
			if seed[j%3] != s[j] {
				acc++
			}
			costs[j][i] = acc
		}
	}

	for i := 0; i < m; i++ {
		var l, r int
		fmt.Fscan(in, &l)
		fmt.Fscan(in, &r)
		l--
		r--

		var candi [6]int
		for j := 0; j < 6; j++ {
			left := 0
			if l > 0 {
				left = costs[l-1][j]
			}
			candi[j] = costs[r][j] - left
		}
		fmt.Println(minWithin(candi))
	}
}

package main

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

func CF1555D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	perm3 := []string{"abc", "acb", "bac", "bca", "cab", "cba"}

	var n,q,l,r int
	var s []byte
	fmt.Fscan(in, &n, &q, &s)
	sum := [6][]int{}

	for i,p := range perm3 {
		sum[i] = make([]int, n+1)
		for j,b := range s{
			sum[i][j+1] = sum[i][j]
			if b != p[j%3] {
				sum[i][j+1] ++
			}
		}
	}
	for ; q>0; q-- {
		fmt.Fscan(in, &l, &r)
		ans :=n
		for _,s := range sum {
			if c:= s[r] - s[l-1]; c<ans {
				ans =c
			}
		}
		fmt.Println(ans)
	}

}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1555D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	perm3 := []string{"abc", "acb", "bac", "bca", "cab", "cba"}

	var n, q, l, r int
	var s []byte
	Fscan(in, &n, &q, &s)
	sum := [6][]int{}
	for i, p := range perm3 {
		sum[i] = make([]int, n+1)
		for j, b := range s {
			sum[i][j+1] = sum[i][j]
			if b != p[j%3] {
				sum[i][j+1]++
			}
		}
	}
	for ; q > 0; q-- {
		Fscan(in, &l, &r)
		ans := n
		for _, s := range sum {
			if c := s[r] - s[l-1]; c < ans {
				ans = c
			}
		}
		Fprintln(out, ans)
	}
}

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

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	var n, m int
	fmt.Fscan(in,&n,&m)
	var b []byte
	fmt.Fscan(in,&b)
	var f1 []byte
	f1 = []byte("abc")

	var cst [7][300005]int
	for i:=1;i<=6;i++{
		if i==1{
			f1 = []byte("abc")
		}
		if i==2{
			f1 = []byte("cba")
		}
		if i==3{
			f1 = []byte("bca")
		}
		if i==4{
			f1 = []byte("cab")
		}
		if i==5{
			f1 = []byte("bac")
		}
		if i==6{
			f1 = []byte("acb")
		}
		for j:=0;j<n;j++{
			v:=0
			if f1[j%3] != b[j]{
				v=1
			}
			cst[i][j+1]=cst[i][j] + v
		}
	}
	for i:=1;i<=m;i++{
		var l, r int
		fmt.Fscan(in,&l,&r)
		ans := 999999999
		for j:=1;j<=6;j++{
			if ans > cst[j][r]-cst[j][l-1]{
				ans = cst[j][r]-cst[j][l-1]
			}
		}
		fmt.Fprintln(out,ans)
	}
}


package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	ans := len(vs)
	if hasRoot {
		ans--
	}
	Fprintln(out, ans)

	skipOne := true
	vis := make([]int8, n+1)
	var f func(int)
	f = func(v int) {
		vis[v] = 1
		for _, e := range g[v] {
			w := e.to
			if t := vis[w]; t == 0 {
				f(w)
			} else if t == 2 || w == v {
				if t == 2 && !hasRoot {
					hasRoot = true
					a[e.i] = e.i
					continue
				}
				if w == v && skipOne {
					skipOne = false
					continue
				}
				if same(e.i, vs[0]) {
					vs[0], vs[1] = vs[1], vs[0]
				}
				merge(e.i, vs[0])
				a[e.i], vs = vs[0], vs[1:]
			}
		}
		vis[v] = 2
	}
	for i := 1; i <= n; i++ {
		if vis[i] == 0 {
			f(i)
		}
	}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	ans := len(vs)
	if hasRoot {
		ans--
	}
	Fprintln(out, ans)

	skipOne := true
	vis := make([]int8, n+1)
	var f func(int)
	f = func(v int) {
		vis[v] = 1
		for _, e := range g[v] {
			if w := e.to; vis[w] == 0 {
				f(w)
			} else if vis[w] == 2 {
				if len(vs) > 1 || !hasRoot {
					if !hasRoot {
						hasRoot = true
						a[e.i] = e.i
						continue
					}
					if same(e.i, vs[0]) {
						vs[0], vs[1] = vs[1], vs[0]
					}
					merge(e.i, vs[0]) // todo  remove this line
					a[e.i], vs = vs[0], vs[1:]
				}
			} else if w == v {
				if skipOne {
					skipOne = false
					continue
				}
				if same(e.i, vs[0]) {
					vs[0], vs[1] = vs[1], vs[0]
				}
				merge(e.i, vs[0]) // todo  remove this line
				a[e.i], vs = vs[0], vs[1:]
			}
		}
		vis[v] = 2
	}
	for i := 1; i <= n; i++ {
		if vis[i] == 0 {
			f(i)
		}
	}
	Fprint(out, a[1:]...)
}

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

package main

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

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

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

var maj, level []int

var cycles, loops []int

func dfs(node int) {
	level[node] = 1
	p := maj[node]
	switch level[p] {
	case 0:
		dfs(p)
	case 1:
		cycles = append(cycles, node)
	}
	level[node] = 2
}

func main() {
	n := readInt()
	maj = make([]int, n)
	level = make([]int, n)

	for i := range maj {
		maj[i] = readInt() - 1
		if maj[i] == i {
			loops = append(loops, i)
			level[i] = 2
		}
	}

	for i := 0; i < n; i++ {
		if level[i] == 0 {
			dfs(i)
		}
	}

	root, answer := -1, 0

	if len(loops) != 0 {
		root = loops[0]
		loops = loops[1:]
	} else {
		if len(cycles) != 0 {
			root = cycles[0]
			cycles = cycles[1:]
		} else {
			root = 0
		}
		maj[root] = root
		answer++
	}

	for _, n := range cycles {
		maj[n] = root
		answer++
	}

	for _, l := range loops {
		maj[l] = root
		answer++
	}

	fmt.Println(answer)
	for _, p := range maj {
		fmt.Printf("%d ", p+1)
	}
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	if hasRoot {
		Fprintln(out, len(vs)-1)
	} else {
		Fprintln(out, len(vs))
	}

	vis := make([]bool, n+1)
	var f func(v, p int)
	f = func(v, p int) {
		vis[v] = true
		for _, e := range g[v] {
			if w := e.to; !vis[w] {
				f(w, v)
			} else if w != p && w <= v && (len(vs) > 1 || !hasRoot) {
				if !hasRoot {
					hasRoot = true
					a[e.i] = e.i
					continue
				}
				if same(e.i, vs[0]) {
					vs[0], vs[1] = vs[1], vs[0]
				}
				merge(e.i, vs[0])
				a[e.i], vs = vs[0], vs[1:]
			}
		}
	}
	for i := 1; i <= n; i++ {
		if !vis[i] {
			f(i, 0)
		}
	}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	ans := len(vs)
	if hasRoot {
		ans--
	}
	Fprintln(out, ans)

	//modified := make([]bool, n+1)
	cnt1, cnt2 := 0, 0
	cnt3 := 0

	vis := make([]bool, n+1)
	var f func(v, p int)
	f = func(v, p int) {
		vis[v] = true
		for _, e := range g[v] {
			if w := e.to; !vis[w] {
				f(w, v)
			} else if w != p  {
				cnt3++
				if w <= v && (len(vs) > 1 || !hasRoot) {
					if !hasRoot {
						hasRoot = true
						//if a[e.i] == e.i {
						//	panic(Sprintln(1, e.i))
						//}
						a[e.i] = e.i
						//if modified[e.i] {
						//	panic(Sprintln(1, e.i))
						//}
						//modified[e.i]=true
						cnt1++
						continue
					}
					if same(e.i, vs[0]) {
						vs[0], vs[1] = vs[1], vs[0]
					}
					merge(e.i, vs[0])
					//if a[e.i] == vs[0] {
					//	panic(Sprintln(2, e.i))
					//}
					a[e.i], vs = vs[0], vs[1:]
					cnt2++
					//if modified[e.i] {
					//	panic(Sprintln(2, e.i))
					//}
					//modified[e.i]=true
				}
			}
		}
	}
	for i := 1; i <= n; i++ {
		if !vis[i] {
			f(i, 0)
		}
	}
	if cnt1+cnt2 != ans {
		Fprintln(out, cnt1, cnt2, cnt3)
		//panic(Sprintln(cnt1, cnt2, ans))
	}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	if hasRoot {
		Fprintln(out, len(vs)-1)
	} else {
		Fprintln(out, len(vs))
	}

	modified := make([]bool, n+1)

	vis := make([]bool, n+1)
	var f func(v, p int)
	f = func(v, p int) {
		vis[v] = true
		for _, e := range g[v] {
			if w := e.to; !vis[w] {
				f(w, v)
			} else if w != p && w <= v && (len(vs) > 1 || !hasRoot) {
				if !hasRoot {
					hasRoot = true
					//if a[e.i] == e.i {
					//	panic(Sprintln(1, e.i))
					//}
					a[e.i] = e.i
					if modified[e.i] {
						panic(Sprintln(1, e.i))
					}
					modified[e.i]=true
					continue
				}
				if same(e.i, vs[0]) {
					vs[0], vs[1] = vs[1], vs[0]
				}
				merge(e.i, vs[0])
				//if a[e.i] == vs[0] {
				//	panic(Sprintln(2, e.i))
				//}
				a[e.i], vs = vs[0], vs[1:]

				if modified[e.i] {
					panic(Sprintln(2, e.i))
				}
				modified[e.i]=true
			}
		}
	}
	for i := 1; i <= n; i++ {
		if !vis[i] {
			f(i, 0)
		}
	}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	if hasRoot {
		Fprintln(out, len(vs)-1)
	} else {
		Fprintln(out, len(vs))
	}

	vis := make([]bool, n+1)
	var f func(v, p int)
	f = func(v, p int) {
		vis[v] = true
		for _, e := range g[v] {
			if w := e.to; !vis[w] {
				f(w, v)
			} else if w != p && w <= v && (len(vs) > 1 || !hasRoot) {
				if !hasRoot {
					hasRoot = true
					if a[e.i] == e.i {
						panic(Sprintln(1, e.i))
					}
					a[e.i] = e.i
					continue
				}
				if same(e.i, vs[0]) {
					vs[0], vs[1] = vs[1], vs[0]
				}
				merge(e.i, vs[0])
				if a[e.i] == vs[0] {
					panic(Sprintln(2, e.i))
				}
				a[e.i], vs = vs[0], vs[1:]
			}
		}
	}
	for i := 1; i <= n; i++ {
		if !vis[i] {
			f(i, 0)
		}
	}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	ans := len(vs)
	if hasRoot {
		ans--
	}
	Fprintln(out, ans)

	//modified := make([]bool, n+1)
	//cnt1, cnt2 := 0, 0
	//cnt3 := 0
	//c1, c2, c3 := 0, 0, 0

	vis := make([]int8, n+1)
	var f func(int)
	f = func(v int) {
		vis[v] = 1
		for _, e := range g[v] {
			if w := e.to; vis[w] == 0 {
				f(w)
			} else if w == v || vis[w] == 2 {
				//cnt3++
				//if w < v {
				//	c1++
				//} else if w == v {
				//	c2++
				//} else {
				//	c3++
				//}
				if len(vs) > 1 || !hasRoot {
					if !hasRoot {
						hasRoot = true
						//if a[e.i] == e.i {
						//	panic(Sprintln(1, e.i))
						//}
						a[e.i] = e.i
						//if modified[e.i] {
						//	panic(Sprintln(1, e.i))
						//}
						//modified[e.i]=true
						//cnt1++
						continue
					}
					if same(e.i, vs[0]) {
						vs[0], vs[1] = vs[1], vs[0]
					}
					merge(e.i, vs[0])
					//if a[e.i] == vs[0] {
					//	panic(Sprintln(2, e.i))
					//}
					a[e.i], vs = vs[0], vs[1:]
					//cnt2++
					//if modified[e.i] {
					//	panic(Sprintln(2, e.i))
					//}
					//modified[e.i]=true
				}
			}
		}
		vis[v] = 2
	}
	for i := 1; i <= n; i++ {
		if vis[i] == 0 {
			f(i)
		}
	}
	//println( c1, c2, c3)
	//if cnt1+cnt2 != ans {
	//	Fprintln(out, cnt1, cnt2, cnt3)
	//
	//	//panic(Sprintln(cnt1, cnt2, ans))
	//}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	ans := len(vs)
	if hasRoot {
		ans--
	}
	Fprintln(out, ans)

	//modified := make([]bool, n+1)
	cnt1, cnt2 := 0, 0

	vis := make([]bool, n+1)
	var f func(v, p int)
	f = func(v, p int) {
		vis[v] = true
		for _, e := range g[v] {
			if w := e.to; !vis[w] {
				f(w, v)
			} else if w != p && w <= v && (len(vs) > 1 || !hasRoot) {
				if !hasRoot {
					hasRoot = true
					//if a[e.i] == e.i {
					//	panic(Sprintln(1, e.i))
					//}
					a[e.i] = e.i
					//if modified[e.i] {
					//	panic(Sprintln(1, e.i))
					//}
					//modified[e.i]=true
					cnt1++
					continue
				}
				if same(e.i, vs[0]) {
					vs[0], vs[1] = vs[1], vs[0]
				}
				merge(e.i, vs[0])
				//if a[e.i] == vs[0] {
				//	panic(Sprintln(2, e.i))
				//}
				a[e.i], vs = vs[0], vs[1:]
				cnt2++
				//if modified[e.i] {
				//	panic(Sprintln(2, e.i))
				//}
				//modified[e.i]=true
			}
		}
	}
	for i := 1; i <= n; i++ {
		if !vis[i] {
			f(i, 0)
		}
	}
	if cnt1+cnt2 != ans {
		Fprintln(out, cnt1, cnt2, ans)
		//panic(Sprintln(cnt1, cnt2, ans))
	}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	ans := len(vs)
	if hasRoot {
		ans--
	}
	Fprintln(out, ans)

	skipOne := true
	vis := make([]int8, n+1)
	var f func(int)
	f = func(v int) {
		vis[v] = 1
		for _, e := range g[v] {
			if w := e.to; vis[w] == 0 {
				f(w)
			} else if vis[w] == 2 {
				if len(vs) > 1 || !hasRoot {
					if !hasRoot {
						hasRoot = true
						a[e.i] = e.i
						continue
					}
					if same(e.i, vs[0]) {
						vs[0], vs[1] = vs[1], vs[0]
					}
					a[e.i], vs = vs[0], vs[1:]
				}
			} else if w == v {
				if skipOne {
					skipOne = false
					continue
				}
				if same(e.i, vs[0]) {
					vs[0], vs[1] = vs[1], vs[0]
				}
				a[e.i], vs = vs[0], vs[1:]
			}
		}
		vis[v] = 2
	}
	for i := 1; i <= n; i++ {
		if vis[i] == 0 {
			f(i)
		}
	}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false

	debug := false

	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == 1 && w == 8276 {
			debug = true
		}
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	ans := len(vs)
	if hasRoot {
		ans--
	}
	Fprintln(out, ans)

	//modified := make([]bool, n+1)
	cnt1, cnt2 := 0, 0
	cnt3 := 0
	//c1, c2, c3 := 0, 0, 0

	vis := make([]int8, n+1)
	var f func(int)
	f = func(v int) {
		vis[v] = 1
		for _, e := range g[v] {
			if w := e.to; vis[w] == 0 {
				f(w)
			} else if w == v || vis[w] == 2 {
				cnt3++
				if len(vs) > 1 || !hasRoot {
					if !hasRoot {
						hasRoot = true
						a[e.i] = e.i
						cnt1++
						continue
					}
					if same(e.i, vs[0]) {
						vs[0], vs[1] = vs[1], vs[0]
					}
					merge(e.i, vs[0])
					a[e.i], vs = vs[0], vs[1:]
					cnt2++
				}
			}
		}
		vis[v] = 2
	}
	for i := 1; i <= n; i++ {
		if vis[i] == 0 {
			f(i)
		}
	}
	if debug {
		Fprintln(out, hasRoot, cnt1,cnt2,cnt3)
	}

	//println( c1, c2, c3)
	//if cnt1+cnt2 != ans {
	//	Fprintln(out, cnt1, cnt2, cnt3)
	//
	//	//panic(Sprintln(cnt1, cnt2, ans))
	//}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	ans := len(vs)
	if hasRoot {
		ans--
	}
	Fprintln(out, ans)

	skipOne := true
	vis := make([]int8, n+1)
	var f func(int)
	f = func(v int) {
		vis[v] = 1
		for _, e := range g[v] {
			w := e.to
			if t := vis[w]; t == 0 {
				f(w)
			} else if t == 2 || w == v {
				if t == 2 && !hasRoot {
					hasRoot = true
					a[e.i] = e.i
					continue
				}
				if w == v && skipOne {
					skipOne = false
					continue
				}
				if same(e.i, vs[0]) {
					vs[0], vs[1] = vs[1], vs[0]
				}
				a[e.i], vs = vs[0], vs[1:]
			}
		}
		vis[v] = 2
	}
	for i := 1; i <= n; i++ {
		if vis[i] == 0 {
			f(i)
		}
	}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			g[i] = append(g[i], edge{i, i})
		} else {
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
			merge(i, w)
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	Fprintln(out, len(vs)-1)

	vis := make([]bool, n+1)
	var f func(v, p int)
	f = func(v, p int) {
		vis[v] = true
		for _, e := range g[v] {
			if w := e.to; !vis[w] {
				f(w, v)
			} else if w != p && w <= v && len(vs) > 1 {
				if same(e.i, vs[0]) {
					vs[0], vs[1] = vs[1], vs[0]
				}
				merge(e.i, vs[0])
				a[e.i], vs = vs[0], vs[1:]
			}
		}
	}
	for i := 1; i <= n; i++ {
		if !vis[i] {
			f(i, 0)
		}
	}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	ans := len(vs)
	if hasRoot {
		ans--
	}
	Fprintln(out, ans)

	//modified := make([]bool, n+1)
	//cnt1, cnt2 := 0, 0
	//cnt3 := 0
	//c1, c2, c3 := 0, 0, 0

	vis := make([]int8, n+1)
	var f func(v, p int)
	f = func(v, p int) {
		vis[v] = 1
		for _, e := range g[v] {
			if w := e.to; vis[w] == 0 {
				f(w, v)
			} else if w != p && (w == v || vis[w] == 2) {
				//cnt3++
				//if w < v {
				//	c1++
				//} else if w == v {
				//	c2++
				//} else {
				//	c3++
				//}
				if len(vs) > 1 || !hasRoot {
					if !hasRoot {
						hasRoot = true
						//if a[e.i] == e.i {
						//	panic(Sprintln(1, e.i))
						//}
						a[e.i] = e.i
						//if modified[e.i] {
						//	panic(Sprintln(1, e.i))
						//}
						//modified[e.i]=true
						//cnt1++
						continue
					}
					if same(e.i, vs[0]) {
						vs[0], vs[1] = vs[1], vs[0]
					}
					merge(e.i, vs[0])
					//if a[e.i] == vs[0] {
					//	panic(Sprintln(2, e.i))
					//}
					a[e.i], vs = vs[0], vs[1:]
					//cnt2++
					//if modified[e.i] {
					//	panic(Sprintln(2, e.i))
					//}
					//modified[e.i]=true
				}
			}
		}
		vis[v] = 2
	}
	for i := 1; i <= n; i++ {
		if vis[i] ==0 {
			f(i, 0)
		}
	}
	//println( c1, c2, c3)
	//if cnt1+cnt2 != ans {
	//	Fprintln(out, cnt1, cnt2, cnt3)
	//
	//	//panic(Sprintln(cnt1, cnt2, ans))
	//}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	rt := 1
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			rt = i
		} else {
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
			fa[find(i)] = find(w)
		}
		a[i] = w
	}
	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] && i != fa[find(rt)] {
			vs = append(vs, i)
		}
	}
	Fprintln(out, len(vs))

	vis := make([]bool, n+1)
	var f func(v, fa int)
	f = func(v, fa int) {
		vis[v] = true
		for _, e := range g[v] {
			if w := e.to; !vis[w] {
				f(w, v)
			} else if w != fa && w == e.i {
				a[w], vs = vs[0], vs[1:]
			}
		}
	}
	for i := 1; i <= n; i++ {
		if !vis[i] {
			f(i, 0)
		}
	}
	for _, v := range vs {
		a[v] = rt
	}
	Fprint(out, a[1:]...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF698B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ to, i int }

	var n, w int
	Fscan(in, &n)
	fa := make([]int, n+1)
	for i := range fa {
		fa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if fa[x] != x {
			fa[x] = find(fa[x])
		}
		return fa[x]
	}
	merge := func(x, y int) { fa[find(x)] = find(y) }
	same := func(x, y int) bool { return find(x) == find(y) }
	a := make([]interface{}, n+1)
	g := make([][]edge, n+1)
	hasRoot := false
	for i := 1; i <= n; i++ {
		Fscan(in, &w)
		if i == w {
			hasRoot = true
			g[i] = append(g[i], edge{i, i})
		} else {
			merge(i, w)
			g[i] = append(g[i], edge{w, i})
			g[w] = append(g[w], edge{i, i})
		}
		a[i] = w
	}

	vs := []int{}
	for i := 1; i <= n; i++ {
		if i == fa[find(i)] {
			vs = append(vs, i)
		}
	}
	ans := len(vs)
	if hasRoot {
		ans--
	}
	Fprintln(out, ans)

	//modified := make([]bool, n+1)
	cnt1, cnt2 := 0, 0
	cnt3 := 0
	c1, c2, c3 := 0, 0, 0

	vis := make([]bool, n+1)
	var f func(v, p int)
	f = func(v, p int) {
		vis[v] = true
		for _, e := range g[v] {
			if w := e.to; !vis[w] {
				f(w, v)
			} else if w != p {
				cnt3++
				if w < v {
					c1++
				} else if w == v {
					c2++
				} else {
					c3++
				}
				if w <= v && (len(vs) > 1 || !hasRoot) {
					if !hasRoot {
						hasRoot = true
						//if a[e.i] == e.i {
						//	panic(Sprintln(1, e.i))
						//}
						a[e.i] = e.i
						//if modified[e.i] {
						//	panic(Sprintln(1, e.i))
						//}
						//modified[e.i]=true
						cnt1++
						continue
					}
					if same(e.i, vs[0]) {
						vs[0], vs[1] = vs[1], vs[0]
					}
					merge(e.i, vs[0])
					//if a[e.i] == vs[0] {
					//	panic(Sprintln(2, e.i))
					//}
					a[e.i], vs = vs[0], vs[1:]
					cnt2++
					//if modified[e.i] {
					//	panic(Sprintln(2, e.i))
					//}
					//modified[e.i]=true
				}
			}
		}
	}
	for i := 1; i <= n; i++ {
		if !vis[i] {
			f(i, 0)
		}
	}
	if cnt1+cnt2 != ans {
		Fprintln(out, cnt1, cnt2, cnt3)
		Fprintln(out, c1, c2, c3)
		//panic(Sprintln(cnt1, cnt2, ans))
	}
	Fprint(out, a[1:]...)
}

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

package main

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

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

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

var maj, level []int

var cycles, loops []int

func dfs(node int) {
	p := maj[node]
	switch level[p] {
	case 0:
		level[p] = 1
		dfs(p)
	case 1:
		cycles = append(cycles, node)
	}
	level[node] = 2
}

func main() {
	n := readInt()
	maj = make([]int, n)
	level = make([]int, n)

	for i := range maj {
		maj[i] = readInt() - 1
		if maj[i] == i {
			loops = append(loops, i)
			level[i] = 2
		}
	}

	for i := 0; i < n; i++ {
		if level[i] == 0 {
			dfs(i)
		}
	}

	if len(loops) == 0 {
		loops = []int{0}
	}

	for _, n := range cycles {
		maj[n] = loops[0]
	}

	for i := 1; i < len(loops); i++ {
		maj[loops[i]] = loops[0]
	}

	fmt.Println(len(cycles) + len(loops) - 1)
	for _, p := range maj {
		fmt.Printf("%d ", p+1)
	}
}

package main

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

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

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

var maj, level []int

var cycles, loops []int

func dfs(node int) {
	p := maj[node]
	switch level[p] {
	case 0:
		level[p] = 1
		dfs(p)
	case 1:
		cycles = append(cycles, node)
	}
	level[node] = 2
}

func main() {
	n := readInt()
	maj = make([]int, n)
	level = make([]int, n)

	for i := range maj {
		maj[i] = readInt() - 1
		if maj[i] == i {
			loops = append(loops, i)
			level[i] = 2
		}
	}

	for i := 0; i < n; i++ {
		if level[i] == 0 {
			dfs(i)
		}
	}

	if len(loops) == 0 {
		loops = []int{1}
	}

	for _, n := range cycles {
		maj[n] = loops[0]
	}

	for i := 1; i < len(loops); i++ {
		maj[loops[i]] = loops[0]
	}

	fmt.Println(len(cycles) + len(loops) - 1)
	for _, p := range maj {
		fmt.Printf("%d ", p+1)
	}
}

package main

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

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

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

var maj, level []int

var cycles, loops []int

func dfs(node int) {
	p := maj[node]
	switch level[p] {
	case 0:
		level[p] = 1
		dfs(p)
	case 1:
		cycles = append(cycles, node)
	}
	level[node] = 2
}

func main() {
	n := readInt()
	maj = make([]int, n)
	level = make([]int, n)

	for i := range maj {
		maj[i] = readInt() - 1
		if maj[i] == i {
			loops = append(loops, i)
			level[i] = 2
		}
	}

	for i := 0; i < n; i++ {
		if level[i] == 0 {
			dfs(i)
		}
	}

	if len(loops) == 0 {
		if len(cycles) != 0 {
			loops = []int{cycles[0]}
			cycles = cycles[1:]
		} else {
			loops = []int{0}
		}
	}

	for _, n := range cycles {
		maj[n] = loops[0]
	}

	for i := 1; i < len(loops); i++ {
		maj[loops[i]] = loops[0]
	}

	fmt.Println(len(cycles) + len(loops) - 1)
	for _, p := range maj {
		fmt.Printf("%d ", p+1)
	}
}

package main

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

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

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

var maj, level []int

var cycles, loops []int

func dfs(node int) {
	p := maj[node]
	switch level[p] {
	case 0:
		level[p] = 1
		dfs(p)
	case 1:
		cycles = append(cycles, node)
	}
	level[node] = 2
}

func main() {
	n := readInt()
	maj = make([]int, n)
	level = make([]int, n)

	for i := range maj {
		maj[i] = readInt() - 1
		if maj[i] == i {
			loops = append(loops, i)
			level[i] = 2
		}
	}

	for i := 0; i < n; i++ {
		if level[i] == 0 {
			dfs(i)
		}
	}

	if len(loops) == 0 {
		loops = []int{0}
	}

	for _, n := range cycles {
		maj[n] = loops[0]
	}

	fmt.Println("loops")
	fmt.Println(loops)
	fmt.Println("cycles")
	fmt.Println(cycles)

	for i := 1; i < len(loops); i++ {
		maj[loops[i]] = loops[0]
	}

	fmt.Println(len(cycles) + len(loops) - 1)
	for _, p := range maj {
		fmt.Printf("%d ", p+1)
	}
}


package main

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

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

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

	arr := make([]int, n)
	groups := make([]int, n+1)

	for i := 0; i < n; i++ {
		fmt.Fscanf(r, "%d ", &arr[i])
		if arr[i] <= n {
			groups[arr[i]]++
		}
	}

	frees := make([]int, n+1)
	stackPointer := 0
	for i := 1; i <= n; i++ {
		if groups[i] == 0 {
			frees[stackPointer] = i
			stackPointer++
		}
	}

	for i, val := range arr {
		if val > n || groups[val] > 1 {
			stackPointer--
			firstPermute := frees[stackPointer]
			arr[i] = firstPermute
			groups[firstPermute]++
			if val <= n {
				groups[val]--
			}
		}
	}

	lastI := len(arr) - 1
	for i, val := range arr {
		if i < lastI {
			fmt.Printf("%d ", val)
		} else {
			fmt.Printf("%d", val)
		}
	}
	println()
}

func findFree(heystack []int) int {
	for i := range heystack {
		if heystack[i] == 0 {
			return i
		}
	}
	return 0
}

package main

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

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

const MAX = 100001

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

	n := nextInt()
	a := make([]int, n)
	haveNums := make([]bool, n+1)
	used := make([]bool, n+1)

	for i := 0; i < n; i++ {
		a[i] = nextInt()
		if a[i] <= n {
			haveNums[a[i]] = true
		}
	}

	nextA := 1

	for i := 0; i < n; i++ {
		if a[i] > n || used[a[i]] {
			for haveNums[nextA] || used[nextA] {
				nextA++
			}
			used[nextA] = true
			print(nextA, " ")
		} else {
			used[a[i]] = true
			print(a[i], " ")
		}
	}
	println()
}

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

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

func nextInt64() int64 {
	n, _ := strconv.ParseInt(next(), 0, 64)
	return n
}

func nextInt() int {
	n, _ := strconv.Atoi(next())
	return n
}

func nextFloat() float64 {
	n, _ := strconv.ParseFloat(next(), 64)
	return n
}

func println(a ...interface{})               { fmt.Fprintln(writer, a...) }
func print(a ...interface{})                 { fmt.Fprint(writer, a...) }
func printf(format string, a ...interface{}) { fmt.Fprintf(writer, format, a...) }


package main

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

type Piece struct {
	x, y int
	s    string
}

type Score func(p Piece) (bool, string)

func solve() {

	scoreCalcs := []Score{
		func(p Piece) (bool, string) {
			return p.y == 0, "R"
		}, func(p Piece) (bool, string) {
			return p.x == 0, "R"
		}, func(p Piece) (bool, string) {
			return p.x == p.y, "B"
		}}

	n, dx, dy := readInt(), readInt(), readInt()
	a := make([]Piece, n)
	for i := 0; i < n; i++ {
		s, x, y := readString(), readInt()-dx, readInt()-dy
		a[i] = Piece{x, y, s}
	}

	ans := "NO"
	for _, mul := range [][]int{[]int{1, 1}, []int{-1, 1}, []int{1, -1}, []int{-1, -1}} {
		for _, calc := range scoreCalcs {
			var bestP *Piece = nil
			needS := "Q"
			for _, piece := range a {
				p := Piece{piece.x * mul[0], piece.y * mul[1], piece.s}
				if p.x >= 0 && p.y >= 0 {
					ok, s := calc(p)
					needS = s
					if ok && (bestP == nil || bestP.x >= p.x && bestP.y >= p.y) {
						bestP = &p
					}
				}
			}

			if bestP != nil && (bestP.s == needS || bestP.s == "Q") {
				ans = "YES"
			}
		}
	}

	fmt.Println(ans)
}

var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)

func main() {
	const MaxTokenLength = 1024 * 1024
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)
	solve()
}

// Math
func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

func min(x, y int) int {
	return x + y - max(x, y)
}

// IO

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

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

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

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

package main

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

type Tup struct {
	typ byte
	x   int64
	y   int64
}

func main() {
	sc := NewScanner()
	N := sc.NextInt()
	x0, y0 := sc.NextInt64(), sc.NextInt64()
	tuples := make([]Tup, N)
	for i := 0; i < N; i++ {
		tuples[i] = Tup{byte(sc.Next()[0]), sc.NextInt64(), sc.NextInt64()}
	}

	checkA := func(t int, i int) bool {
		switch t {
		case 0:
			return tuples[i].x < x0 && tuples[i].x - x0 == tuples[i].y - y0
		case 1:
			return tuples[i].x > x0 && tuples[i].x - x0 == tuples[i].y - y0
		case 2:
			return tuples[i].x < x0 && tuples[i].x - x0 == -(tuples[i].y - y0)
		case 3:
			return tuples[i].x > x0 && tuples[i].x - x0 == -(tuples[i].y - y0)
		case 4:
			return tuples[i].x == x0 && tuples[i].y < y0
		case 5:
			return tuples[i].x == x0 && tuples[i].y > y0
		case 6:
			return tuples[i].y == y0 && tuples[i].x < x0
		case 7:
			return tuples[i].y == y0 && tuples[i].x > x0
		}
		return false
	}

	mmnn := func(t int, i int) int64 {
		switch t {
		case 0, 1, 2, 3:
			return tuples[i].x - x0
		case 4:
			return tuples[i].y - y0
		case 5:
			return tuples[i].y - y0
		case 6:
			return tuples[i].x - x0
		case 7:
			return tuples[i].x - x0
		}
		return 0
	}

	checks := func(t int) bool {
		mn := int64(-1)
		index := -1
		for i := 0; i < N; i++ {
			if checkA(t, i) {
				if mn == -1 || mn > abs(mmnn(t, i)) {
					mn = abs(mmnn(t, i))
					index = i
				}
			}
		}
		if index >= 0 {
			if tuples[index].typ == 'Q' {
				return true
			}
			if t < 4 {
				if tuples[index].typ == 'B' {
					return true
				}
			}
			if t >= 4 {
				if tuples[index].typ == 'R' {
					return true
				}
			}
		}
		return false
	}

	for i := 0; i < 8; i++ {
		if checks(i) {
			fmt.Println("YES")
			return
		}
	}
	fmt.Println("NO")

}

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

type Scanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewScanner() *Scanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1000)
	return &Scanner{r:rdr}
}
func (s *Scanner) Next() string {
	s.pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	result := string(s.buf[start:s.p])
	s.p++
	return result
}
func (s *Scanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *Scanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}
func (s *Scanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(s.Next(), 10, 64)
	return v
}

func (s *Scanner) NextIntArray() []int {
	s.pre()
	start := s.p
	result := []int{}
	for ; s.p < len(s.buf) + 1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 0)
			result = append(result, int(v))
			start = s.p + 1
		}
	}

	return result
}
func (s *Scanner) NextInt64Array() []int64 {
	s.pre()
	start := s.p
	result := []int64{}
	for ; s.p < len(s.buf) + 1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 64)
			result = append(result, v)
			start = s.p + 1
		}
	}
	return result
}

func (s *Scanner) NextMap() map[int]bool {
	s.pre()
	start := s.p
	mp := map[int]bool{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			mp[v] = true
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	mp[v] = true

	return mp
}

func (s *Scanner) pre() {
	if s.p >= len(s.buf) {
		s.readLine()
		s.p = 0
	}
}
func (s *Scanner) readLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, e := s.r.ReadLine()
		if e != nil {
			panic(e)
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}

package main

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

func I(i interface{}, delim string) error {
	_, err := fmt.Fscanf(r, "%v"+delim, i)
	return err
}

func O(o interface{}, delim string) {
	fmt.Fprintf(w, "%v"+delim, o)
}

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

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

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

func solve(n int) {
	var x, y, xx, yy int64
	I(&x, " ")
	I(&y, "\n")
	var res [8]string
	var re [8]int64
	for i := 0; i < 8; i++ {
		re[i] = 1e10
	}
	var s string
	for i := 0; i < n; i++ {
		I(&s, " ")
		I(&xx, " ")
		I(&yy, "\n")
		if x == xx {
			if y < yy {
				if re[0] > yy-y {
					re[0] = yy - y
					res[0] = s
				}
			} else if y > yy {
				if re[1] > y-yy {
					re[1] = y - yy
					res[1] = s
				}
			}
		}
		if y == yy {
			if x < xx {
				if re[2] > xx-x {
					re[2] = xx - x
					res[2] = s
				}
			} else if x > xx {
				if re[3] > x-xx {
					re[3] = x - xx
					res[3] = s
				}
			}
		}
		if abs(yy-y) == abs(x-xx) {
			if y < yy && x < xx {
				if re[4] > yy-y+xx-x {
					re[4] = yy - y + xx - x
					res[4] = s
				}
			} else if y > yy && x > xx {
				if re[5] > y-yy+x-xx {
					re[5] = y - yy + x - xx
					res[5] = s
				}
			} else if x > xx && y < yy {
				if re[6] > yy-y+x-xx {
					re[6] = yy - y + x - xx
					res[6] = s
				}
			} else if x < xx && y > yy {
				if re[7] > y-yy+xx-x {
					re[7] = y - yy + xx - x
					res[7] = s
				}
			}
		}
	}
	for i := 0; i < 4; i++ {
		if res[i] == "Q" || res[i] == "R" {
			O("YES", "\n")
			return
		}
	}
	for i := 4; i < 8; i++ {
		if res[i] == "Q" || res[i] == "B" {
			O("YES", "\n")
			return
		}
	}
	O("NO", "\n")
}

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

package main

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

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

const queen = 'Q'
const rook = 'R'
const bishop = 'B'

func checkRook(n, kx, ky int, p []byte, x, y []int) bool {
	imax := -1
	imin := -1

	for i := 0; i < n; i++ {
		if x[i] == kx {
			if y[i] < ky {
				if (imax == -1) || (y[imax] < y[i]) {
					imax = i
				}
			} else {
				if (imin == -1) || (y[imin] > y[i]) {
					imin = i
				}
			}
		}
	}

	if imax != -1 {
		c := p[imax]
		if (c == queen) || (c == rook) {
			return true
		}
	}

	if imin != -1 {
		c := p[imin]
		if (c == queen) || (c == rook) {
			return true
		}
	}

	return false
}

func checkBishop1(n, kx, ky int, p []byte, x, y []int) bool {
	imin := -1
	imax := -1

	for i := 0; i < n; i++ {
		if x[i]-y[i] == kx-ky {
			if x[i] < kx {
				if (imax == -1) || (y[imax] < y[i]) {
					imax = i
				}
			} else {
				if (imin == -1) || (y[imin] > y[i]) {
					imin = i
				}
			}
		}
	}

	if imax != -1 {
		c := p[imax]
		if (c == queen) || (c == bishop) {
			return true
		}
	}

	if imin != -1 {
		c := p[imin]
		if (c == queen) || (c == bishop) {
			return true
		}
	}

	return false
}

func checkBishop2(n, kx, ky int, p []byte, x, y []int) bool {
	imin := -1
	imax := -1

	for i := 0; i < n; i++ {
		if x[i]+y[i] == kx+ky {
			if x[i] > kx {
				if (imax == -1) || (y[imax] < y[i]) {
					imax = i
				}
			} else {
				if (imin == -1) || (y[imin] > y[i]) {
					imin = i
				}
			}
		}
	}

	if imax != -1 {
		c := p[imax]
		if (c == queen) || (c == bishop) {
			return true
		}
	}

	if imin != -1 {
		c := p[imin]
		if (c == queen) || (c == bishop) {
			return true
		}
	}

	return false
}

func check(n, kx, ky int, p []byte, x, y []int) bool {
	if checkRook(n, kx, ky, p, x, y) {
		return true
	}

	if checkRook(n, ky, kx, p, y, x) {
		return true
	}

	if checkBishop1(n, kx, ky, p, x, y) {
		return true
	}

	if checkBishop2(n, kx, ky, p, x, y) {
		return true
	}

	return false
}

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

	var n, kx, ky int
	fmt.Fscanf(bufin, "%d\n", &n)
	fmt.Fscanf(bufin, "%d %d\n", &kx, &ky)

	p := make([]byte, n)
	x := make([]int, n)
	y := make([]int, n)

	for i := 0; i < n; i++ {
		fmt.Fscanf(bufin, "%c %d %d\n", &p[i], &x[i], &y[i])
	}

	if check(n, kx, ky, p, x, y) {
		fmt.Fprintf(bufout, "YES\n")
	} else {
		fmt.Fprintf(bufout, "NO\n")
	}
}

package main

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

type Tup struct {
	typ byte
	x   int
	y   int
}

func main() {
	sc := NewScanner()
	N := sc.NextInt()
	x0, y0 := sc.NextInt(), sc.NextInt()
	tuples := make([]Tup, N)
	for i := 0; i < N; i++ {
		tuples[i] = Tup{byte(sc.Next()[0]), sc.NextInt(), sc.NextInt()}
	}

	checkA := func(t int, i int) bool {
		switch t {
		case 0:
			return tuples[i].x < x0 && tuples[i].x - x0 == tuples[i].y - y0
		case 1:
			return tuples[i].x > x0 && tuples[i].x - x0 == tuples[i].y - y0
		case 2:
			return tuples[i].x < x0 && tuples[i].x - x0 == -(tuples[i].y - y0)
		case 3:
			return tuples[i].x > x0 && tuples[i].x - x0 == -(tuples[i].y - y0)
		case 4:
			return tuples[i].x == x0 && tuples[i].y < y0
		case 5:
			return tuples[i].x == x0 && tuples[i].y > y0
		case 6:
			return tuples[i].x == y0 && tuples[i].x < x0
		case 7:
			return tuples[i].x == y0 && tuples[i].x > x0
		}
		return false
	}

	mmnn := func(t int, i int) int {
		switch t {
		case 0, 1, 2, 3:
			return tuples[i].x - x0
		case 4:
			return tuples[i].y - y0
		case 5:
			return tuples[i].y - y0
		case 6:
			return tuples[i].x - x0
		case 7:
			return tuples[i].x - x0
		}
		return 0
	}

	checks := func(t int) bool {
		mn := -1
		index := -1
		for i := 0; i < N; i++ {
			if checkA(t, i) {
				if mn == -1 || mn > abs(mmnn(t, i)) {
					mn = abs(mmnn(t, i))
					index = i
				}
			}
		}
		if index >= 0 {
			if t < 4 {
				if tuples[index].typ == 'B' {
					return true
				}
			}
			if t >= 4 {
				if tuples[index].typ == 'R' {
					return true
				}
			}
		}
		return false
	}

	for i := 0; i < 8; i++ {
		if checks(i) {
			fmt.Println("YES")
			return
		}
	}
	fmt.Println("NO")

}

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

type Scanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewScanner() *Scanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1000)
	return &Scanner{r:rdr}
}
func (s *Scanner) Next() string {
	s.pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	result := string(s.buf[start:s.p])
	s.p++
	return result
}
func (s *Scanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *Scanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}
func (s *Scanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(s.Next(), 10, 64)
	return v
}

func (s *Scanner) NextIntArray() []int {
	s.pre()
	start := s.p
	result := []int{}
	for ; s.p < len(s.buf) + 1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 0)
			result = append(result, int(v))
			start = s.p + 1
		}
	}

	return result
}
func (s *Scanner) NextInt64Array() []int64 {
	s.pre()
	start := s.p
	result := []int64{}
	for ; s.p < len(s.buf) + 1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 64)
			result = append(result, v)
			start = s.p + 1
		}
	}
	return result
}

func (s *Scanner) NextMap() map[int]bool {
	s.pre()
	start := s.p
	mp := map[int]bool{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			mp[v] = true
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	mp[v] = true

	return mp
}

func (s *Scanner) pre() {
	if s.p >= len(s.buf) {
		s.readLine()
		s.p = 0
	}
}
func (s *Scanner) readLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, e := s.r.ReadLine()
		if e != nil {
			panic(e)
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}

package main

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

type Tup struct {
	typ byte
	x   int64
	y   int64
}

func main() {
	sc := NewScanner()
	N := sc.NextInt()
	x0, y0 := sc.NextInt64(), sc.NextInt64()
	tuples := make([]Tup, N)
	for i := 0; i < N; i++ {
		tuples[i] = Tup{byte(sc.Next()[0]), sc.NextInt64(), sc.NextInt64()}
	}

	checkA := func(t int, i int) bool {
		switch t {
		case 0:
			return tuples[i].x < x0 && tuples[i].x - x0 == tuples[i].y - y0
		case 1:
			return tuples[i].x > x0 && tuples[i].x - x0 == tuples[i].y - y0
		case 2:
			return tuples[i].x < x0 && tuples[i].x - x0 == -(tuples[i].y - y0)
		case 3:
			return tuples[i].x > x0 && tuples[i].x - x0 == -(tuples[i].y - y0)
		case 4:
			return tuples[i].x == x0 && tuples[i].y < y0
		case 5:
			return tuples[i].x == x0 && tuples[i].y > y0
		case 6:
			return tuples[i].x == y0 && tuples[i].x < x0
		case 7:
			return tuples[i].x == y0 && tuples[i].x > x0
		}
		return false
	}

	mmnn := func(t int, i int) int64 {
		switch t {
		case 0, 1, 2, 3:
			return tuples[i].x - x0
		case 4:
			return tuples[i].y - y0
		case 5:
			return tuples[i].y - y0
		case 6:
			return tuples[i].x - x0
		case 7:
			return tuples[i].x - x0
		}
		return 0
	}

	checks := func(t int) bool {
		mn := int64(-1)
		index := -1
		for i := 0; i < N; i++ {
			if checkA(t, i) {
				if mn == -1 || mn > abs(mmnn(t, i)) {
					mn = abs(mmnn(t, i))
					index = i
				}
			}
		}
		if index >= 0 {
			if t < 4 {
				if tuples[index].typ == 'B' {
					return true
				}
			}
			if t >= 4 {
				if tuples[index].typ == 'R' {
					return true
				}
			}
		}
		return false
	}

	for i := 0; i < 8; i++ {
		if checks(i) {
			fmt.Println("YES")
			return
		}
	}
	fmt.Println("NO")

}

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

type Scanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewScanner() *Scanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1000)
	return &Scanner{r:rdr}
}
func (s *Scanner) Next() string {
	s.pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	result := string(s.buf[start:s.p])
	s.p++
	return result
}
func (s *Scanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *Scanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}
func (s *Scanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(s.Next(), 10, 64)
	return v
}

func (s *Scanner) NextIntArray() []int {
	s.pre()
	start := s.p
	result := []int{}
	for ; s.p < len(s.buf) + 1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 0)
			result = append(result, int(v))
			start = s.p + 1
		}
	}

	return result
}
func (s *Scanner) NextInt64Array() []int64 {
	s.pre()
	start := s.p
	result := []int64{}
	for ; s.p < len(s.buf) + 1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 64)
			result = append(result, v)
			start = s.p + 1
		}
	}
	return result
}

func (s *Scanner) NextMap() map[int]bool {
	s.pre()
	start := s.p
	mp := map[int]bool{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			mp[v] = true
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	mp[v] = true

	return mp
}

func (s *Scanner) pre() {
	if s.p >= len(s.buf) {
		s.readLine()
		s.p = 0
	}
}
func (s *Scanner) readLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, e := s.r.ReadLine()
		if e != nil {
			panic(e)
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}

package main

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

type Tup struct {
	typ byte
	x   int64
	y   int64
}

func main() {
	sc := NewScanner()
	N := sc.NextInt()
	x0, y0 := sc.NextInt64(), sc.NextInt64()
	tuples := make([]Tup, N)
	for i := 0; i < N; i++ {
		tuples[i] = Tup{byte(sc.Next()[0]), sc.NextInt64(), sc.NextInt64()}
	}

	checkA := func(t int, i int) bool {
		switch t {
		case 0:
			return tuples[i].x < x0 && tuples[i].x - x0 == tuples[i].y - y0
		case 1:
			return tuples[i].x > x0 && tuples[i].x - x0 == tuples[i].y - y0
		case 2:
			return tuples[i].x < x0 && tuples[i].x - x0 == -(tuples[i].y - y0)
		case 3:
			return tuples[i].x > x0 && tuples[i].x - x0 == -(tuples[i].y - y0)
		case 4:
			return tuples[i].x == x0 && tuples[i].y < y0
		case 5:
			return tuples[i].x == x0 && tuples[i].y > y0
		case 6:
			return tuples[i].y == y0 && tuples[i].x < x0
		case 7:
			return tuples[i].y == y0 && tuples[i].x > x0
		}
		return false
	}

	mmnn := func(t int, i int) int64 {
		switch t {
		case 0, 1, 2, 3:
			return tuples[i].x - x0
		case 4:
			return tuples[i].y - y0
		case 5:
			return tuples[i].y - y0
		case 6:
			return tuples[i].x - x0
		case 7:
			return tuples[i].x - x0
		}
		return 0
	}

	checks := func(t int) bool {
		mn := int64(-1)
		index := -1
		for i := 0; i < N; i++ {
			if checkA(t, i) {
				if mn == -1 || mn > abs(mmnn(t, i)) {
					mn = abs(mmnn(t, i))
					index = i
				}
			}
		}
		if index >= 0 {
			if t < 4 {
				if tuples[index].typ == 'B' {
					return true
				}
			}
			if t >= 4 {
				if tuples[index].typ == 'R' {
					return true
				}
			}
		}
		return false
	}

	for i := 0; i < 8; i++ {
		if checks(i) {
			fmt.Println("YES")
			return
		}
	}
	fmt.Println("NO")

}

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

type Scanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewScanner() *Scanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1000)
	return &Scanner{r:rdr}
}
func (s *Scanner) Next() string {
	s.pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	result := string(s.buf[start:s.p])
	s.p++
	return result
}
func (s *Scanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *Scanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}
func (s *Scanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(s.Next(), 10, 64)
	return v
}

func (s *Scanner) NextIntArray() []int {
	s.pre()
	start := s.p
	result := []int{}
	for ; s.p < len(s.buf) + 1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 0)
			result = append(result, int(v))
			start = s.p + 1
		}
	}

	return result
}
func (s *Scanner) NextInt64Array() []int64 {
	s.pre()
	start := s.p
	result := []int64{}
	for ; s.p < len(s.buf) + 1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 64)
			result = append(result, v)
			start = s.p + 1
		}
	}
	return result
}

func (s *Scanner) NextMap() map[int]bool {
	s.pre()
	start := s.p
	mp := map[int]bool{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			mp[v] = true
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	mp[v] = true

	return mp
}

func (s *Scanner) pre() {
	if s.p >= len(s.buf) {
		s.readLine()
		s.p = 0
	}
}
func (s *Scanner) readLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, e := s.r.ReadLine()
		if e != nil {
			panic(e)
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}

package main

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

func I(i interface{}, delim string) error {
	_, err := fmt.Fscanf(r, "%v"+delim, i)
	return err
}

func O(o interface{}, delim string) {
	fmt.Fprintf(w, "%v"+delim, o)
}

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

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

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

func solve(n int) {
	var x, y, xx, yy int
	I(&x, " ")
	I(&y, "\n")
	var res [8]string
	var re [8]int
	for i := 0; i < 8; i++ {
		re[i] = 1e9*2 + 1
	}
	var s string
	for i := 0; i < n; i++ {
		I(&s, " ")
		I(&xx, " ")
		I(&yy, "\n")
		if x == xx {
			if y < yy {
				if re[0] > yy-y {
					re[0] = yy - y
					res[0] = s
				}
			} else if y > yy {
				if re[1] > y-yy {
					re[1] = y - yy
					res[1] = s
				}
			}
		}
		if y == yy {
			if x < xx {
				if re[2] > xx-x {
					re[2] = xx - x
					res[2] = s
				}
			} else if x > xx {
				if re[3] > x-xx {
					re[3] = x - xx
					res[3] = s
				}
			}
		}
		if abs(yy-y) == abs(x-xx) {
			if y < yy && x < xx {
				if re[4] > yy-y+xx-x {
					re[4] = yy - y + xx - x
					res[4] = s
				}
			} else if y > yy && x > xx {
				if re[5] > y-yy+x-xx {
					re[5] = y - yy + x - xx
					res[5] = s
				}
			} else if x > xx && y < yy {
				if re[6] > yy-y+x-xx {
					re[6] = yy - y + x - xx
					res[6] = s
				}
			} else if x < xx && y > yy {
				if re[7] > y-yy+xx-x {
					re[7] = y - yy + xx - x
					res[7] = s
				}
			}
		}
	}
	for i := 0; i < 4; i++ {
		if res[i] == "Q" || res[i] == "R" {
			O("YES", "\n")
			return
		}
	}
	for i := 4; i < 8; i++ {
		if res[i] == "Q" || res[i] == "B" {
			O("YES", "\n")
			return
		}
	}
	O("NO", "\n")
}

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

package main

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

type Piece struct {
	x, y int
	s    string
}

type Score func(p Piece) (bool, string)

func solve() {

	scoreCalcs := []Score{
		func(p Piece) (bool, string) {
			return p.y == 0, "R"
		}, func(p Piece) (bool, string) {
			return p.x == 0, "R"
		}, func(p Piece) (bool, string) {
			return p.x == p.y, "B"
		}}

	n, dx, dy := readInt(), readInt(), readInt()
	a := make([]Piece, n)
	for i := 0; i < n; i++ {
		s, x, y := readString(), readInt()-dx, readInt()-dy
		a[i] = Piece{x, y, s}
	}

	ans := "NO"
	for _, mul := range [][]int{[]int{1, 1}, []int{-1, 1}, []int{1, -1}, []int{-1, -1}} {
		for _, calc := range scoreCalcs {
			var bestP *Piece = nil
			needS := "Q"
			for _, piece := range a {
				p := Piece{piece.x * mul[0], piece.y * mul[1], piece.s}
				if p.x >= 0 && p.y >= 0 {
					ok, s := calc(p)
					needS = s
					if ok && (bestP == nil || bestP.x+bestP.y > p.x+p.y) {
						bestP = &p
					}
				}
			}

			if bestP != nil && (bestP.s == needS || bestP.s == "Q") {
				ans = "YES"
			}
		}
	}

	fmt.Println(ans)
}

var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)

func main() {
	const MaxTokenLength = 1024 * 1024
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)
	solve()
}

// Math
func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

func min(x, y int) int {
	return x + y - max(x, y)
}

// IO

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

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

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

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


package main

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

var checked [][]bool
var m [][]bool

var shiftX []int
var shiftY []int

var xs, ys int
var xf, yf int

type Coord struct {
	X, Y int
}

func (c Coord) Dist(o Coord) int {
	return int((c.X-o.X)*(c.X-o.X) + (c.Y-o.Y)*(c.Y-o.Y))
}

func init() {
	in := bufio.NewReader(os.Stdin)
	// in, _ := os.Open("./542/c/4")
	// defer in.Close()
	shiftX = []int{1, 0, -1, 0}
	shiftY = []int{0, 1, 0, -1}
	n := 0
	fmt.Fscan(in, &n)
	for i := 0; i < n; i++ {
		checked = append(checked, make([]bool, n, n))
	}
	fmt.Fscan(in, &xs, &ys)
	fmt.Fscan(in, &xf, &yf)
	ys--
	xs--
	yf--
	xf--
	for i := 0; i < n; i++ {
		s := ""
		fmt.Fscan(in, &s)
		m = append(m, make([]bool, n, n))
		for j := 0; j < n; j++ {
			m[i][j] = s[j] == '0'
		}
	}
}

func dfs(x, y int) []Coord {
	checked[x][y] = true
	coords := []Coord{{x, y}}
	for i := 0; i < 4; i++ {
		if x+shiftX[i] < 0 || y+shiftY[i] < 0 || y+shiftY[i] >= len(m) || x+shiftX[i] >= len(m[0]) {
			continue
		}
		if !m[x][y] {
			panic("Fuck")
		}
		if !m[x+shiftX[i]][y+shiftY[i]] {
			continue
		}
		if checked[x+shiftX[i]][y+shiftY[i]] {
			continue
		}
		coords = append(coords, dfs(x+shiftX[i], y+shiftY[i])...)
	}
	return coords
}

func main() {
	coordsStart := dfs(xs, ys)
	coordsFinish := dfs(xf, yf)
	if len(coordsFinish) == 0 {
		fmt.Println(0)
		return
	}
	bestDist := 1000 * 1000
	for _, cS := range coordsStart {
		for _, cF := range coordsFinish {
			newDist := cS.Dist(cF)
			if bestDist > newDist {
				bestDist = newDist
			}
		}
	}
	fmt.Println(bestDist)
}

package main

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

var g [][]int
var ans []int

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n := 0
	fmt.Fscanf(in, "%d\n", &n)
	g = make([][]int, n)
	for i := 0; i < n; i++ {
		g[i] = make([]int, n)
	}
	r1, c1, r2, c2 := 0, 0, 0, 0
	fmt.Fscanf(in, "%d %d\n", &r1, &c1)
	fmt.Fscanf(in, "%d %d\n", &r2, &c2)
	r1--
	c1--
	r2--
	c2--
	for i := 0; i < n; i++ {
		tmp := ""
		fmt.Fscanf(in, "%s\n", &tmp)
		for j := 0; j < n; j++ {
			g[i][j] = int(tmp[0] - '0')
			tmp = tmp[1:]
		}
		//fmt.Println(g[i])
	}

	ans = make([]int, 0)
	find(r1, c1, n)
	if g[r2][c2] == 1 {
		fmt.Fprintf(out, "%d\n", 0)
		return
	}
	tmpAns := ans
	ans = make([]int, 0)
	find(r2, c2, n)
	finalA := (r2-r1)*(r2-r1) + (c2-c1)*(c2-c1)
	for i := 0; i < len(tmpAns); i++ {
		for j := 0; j < len(ans); j++ {
			x1, y1 := tmpAns[i]/n, tmpAns[i]%n
			x2, y2 := ans[j]/n, ans[j]%n
			if (x2-x1)*(x2-x1)+(y2-y1)*(y2-y1) < finalA {
				finalA = (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)
			}
		}
	}
	fmt.Fprintf(out, "%d\n", finalA)
	return
}

func find(x, y int, n int) {
	if x < 0 || x >= n || y < 0 || y >= n {
		return
	}
	if g[x][y] == 1 {
		return
	}
	g[x][y] = 1
	ans = append(ans, x*n+y)
	find(x-1, y, n)
	find(x+1, y, n)
	find(x, y-1, n)
	find(x, y+1, n)
}

package main

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

var g [][]int
var ans []int

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n := 0
	fmt.Fscanf(in, "%d\n", &n)
	a := make([][]int, (n+1)*(n+1))
	g = make([][]int, n)
	for i := 0; i < n; i++ {
		g[i] = make([]int, n)
	}

	for i := 0; i < (n+1)*(n+1); i++ {
		a[i] = make([]int, (n+1)*(n+1))
	}
	r1, c1, r2, c2 := 0, 0, 0, 0
	fmt.Fscanf(in, "%d %d\n", &r1, &c1)
	fmt.Fscanf(in, "%d %d\n", &r2, &c2)
	r1--
	c1--
	r2--
	c2--
	for i := 0; i < n; i++ {
		tmp := 0
		fmt.Fscanf(in, "%d\n", &tmp)
		for j := n - 1; j >= 0; j-- {
			g[i][j] = tmp % 10
			tmp /= 10
		}
	}
	//fmt.Println(g[0])
	// for i := 0; i < n*n; i++ {
	// 	x1, y1 := i/n, i%n
	// 	for j := 0; j < n*n; j++ {
	// 		a[i][j] = -1
	// 		x2, y2 := j/n, j%n
	// 		if g[x1][y1] == 1 || g[x2][y2] == 1 {
	// 			continue
	// 		}
	// 		if (x1 == x2 && (y1-y2)*(y1-y2) == 1) || (y1 == y2 && (x1-x2)*(x1-x2) == 1) {
	// 			//fmt.Println(i, j)
	// 			a[i][j] = 0
	// 		} else {
	// 			//fmt.Println(i, j)
	// 			a[i][j] = (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)
	// 		}
	// 	}
	// }
	used := make(map[int]bool)
	dis := make([]int, n*n)
	from := r1*n + c1
	//fmt.Println(r1, c1, r2, c2, from, to)
	for i := 0; i < n*n; i++ {
		dis[i] = a[from][i]
	}
	used[from] = true
	// for true {
	// 	if used[to] {
	// 		fmt.Fprintf(out, "%d\n", dis[to])
	// 		return
	// 	}
	// 	chosen := -1
	// 	for i := 0; i < n*n; i++ {
	// 		if used[i] == false && dis[i] != -1 {
	// 			if chosen == -1 || dis[i] < dis[chosen] {
	// 				chosen = i
	// 			}
	// 		}
	// 	}
	// 	fmt.Println(dis, chosen)

	// 	used[chosen] = true
	// 	for i := 0; i < n*n; i++ {
	// 		//fmt.Println(chosen, i)
	// 		if a[chosen][i] != -1 {
	// 			if dis[i] != -1 && dis[chosen]+a[chosen][i] < dis[i] {
	// 				dis[i] = dis[chosen] + a[chosen][i]
	// 			}
	// 		}
	// 	}
	// }
	ans = make([]int, 0)
	find(r1, c1, n)
	if g[r2][c2] == 1 {
		fmt.Fprintf(out, "%d\n", 0)
		return
	}
	tmpAns := ans
	ans = make([]int, 0)
	find(r2, c2, n)
	finalA := (r2-r1)*(r2-r1) + (c2-c1)*(c2-c1)
	for i := 0; i < len(tmpAns); i++ {
		for j := 0; j < len(ans); j++ {
			x1, y1 := tmpAns[i]/n, tmpAns[i]%n
			x2, y2 := ans[j]/n, ans[j]%n
			if (x2-x1)*(x2-x1)+(y2-y1)*(y2-y1) < finalA {
				finalA = (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)
			}
		}
	}
	fmt.Fprintf(out, "%d\n", finalA)
	return
}

func find(x, y int, n int) {
	if x < 0 || x >= n || y < 0 || y >= n {
		return
	}
	if g[x][y] == 1 {
		return
	}
	g[x][y] = 1
	ans = append(ans, x*n+y)
	find(x-1, y, n)
	find(x+1, y, n)
	find(x, y-1, n)
	find(x, y+1, n)
}

package main

import (
	"fmt"
)

var checked [][]bool
var m [][]bool

var shiftX []int
var shiftY []int

var xs, ys int
var xf, yf int

type Coord struct {
	X, Y int
}

func (c Coord) Dist(o Coord) int {
	return int((c.X-o.X)*(c.X-o.X) + (c.Y-o.Y)*(c.Y-o.Y))
}

func init() {
	shiftX = []int{1, 0, -1, 0}
	shiftY = []int{0, 1, 0, -1}
	n := 0
	fmt.Scan(&n)
	for i := 0; i < n; i++ {
		checked = append(checked, make([]bool, n, n))
	}
	fmt.Scan(&ys, &xs)
	fmt.Scan(&yf, &xf)
	ys--
	xs--
	yf--
	xf--
	for i := 0; i < n; i++ {
		s := ""
		fmt.Scan(&s)
		m = append(m, make([]bool, n, n))
		for j := 0; j < n; j++ {
			m[i][j] = s[j] == '0'
		}
	}
}

func dfs(x, y int) []Coord {
	checked[x][y] = true
	coords := []Coord{{x, y}}
	for i := 0; i < 4; i++ {
		if x+shiftX[i] < 0 || y+shiftY[i] < 0 || y+shiftY[i] >= len(m) || x+shiftX[i] >= len(m[0]) {
			continue
		}
		if !m[x+shiftX[i]][y+shiftY[i]] {
			continue
		}
		if checked[x+shiftX[i]][y+shiftY[i]] {
			continue
		}
		coords = append(coords, dfs(x+shiftX[i], y+shiftY[i])...)
	}
	return coords
}

func main() {
	coordsStart := dfs(xs, ys)
	coordsFinish := dfs(xf, yf)
	if len(coordsFinish) == 0 {
		fmt.Println(0)
		return
	}
	bestDist := 1000 * 1000
	for _, cS := range coordsStart {
		for _, cF := range coordsFinish {
			newDist := cS.Dist(cF)
			if bestDist > newDist {
				bestDist = newDist
			}
		}
	}
	fmt.Println(bestDist)
}


package main

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

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

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}

func getI() int {
  return int(getI64())
}

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

type Tree struct {
	tree     [524289]int
}

func (tree *Tree) change(value [18]int, delta int) {
	end_idx := 1
	for _, i := range value {
		end_idx *= 2
		if i == 1 {
			end_idx += 1
		}
	}
	tree.tree[end_idx] += delta
}

func (tree *Tree) query(value [18]int) int{
	end_idx := 1
	for _, i := range value {
		end_idx *= 2
		if i == 1 {
			end_idx += 1
		}
	}
	return tree.tree[end_idx]
}

func to01(int_string string) [18]int {
	var result [18]int
	digitCount := len(int_string)
	for idx, i := range int_string {
		if int(i) % 2 == 1 {
			result[digitCount - 1 - idx] = 1
		}
	}
	return result
}

func to01Template(int_string string) [18]int {
	var result [18]int
	digitCount := len(int_string)
	for idx, i := range int_string {
		if i == '1' {
			result[digitCount - 1 - idx] = 1
		}
	}
	return result
}

func main()  {

	scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)

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

	n := getI()

	tree := *new(Tree)

	for opNo := 0; opNo < n; opNo++ {
		command, value := getS(), getS()
		if command == "+" {
			tree.change(to01(value), 1)
		} else if command == "-" {
			tree.change(to01(value), -1)
		} else {
			writer.WriteString(strconv.Itoa(tree.query(to01Template(value))))
			writer.WriteByte('\n')
		}
	}

}

package main

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

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

type Node struct {
	val   int
	child [2]*Node
}

func create(v int) *Node {
	r := &Node{
		val:   v,
		child: [2]*Node{nil, nil},
	}
	return r
}

func add(x int64, i int, node *Node) {
	if i < 0 {
		return
	}
	bit := x & 1
	if node.child[bit] == nil {
		node.child[bit] = create(0)
	}
	node.child[bit].val++
	add(x/10, i-1, node.child[bit])
}

func del(x int64, i int, node *Node) {
	if i < 0 {
		return
	}
	bit := x & 1
	node.child[bit].val--
	del(x/10, i-1, node.child[bit])
}

func query(bits string, i int, node *Node) int {
	if i < 0 {
		return node.val
	}
	bit := bits[i] - '0'
	if node.child[bit] != nil {
		return query(bits, i-1, node.child[bit])
	}
	return 0
}

const maxbit = 30

var root *Node

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

	var n int
	var x int64
	var op, s string

	root = create(0)
	fmt.Fscanf(bufin, "%d\n", &n)

	for i := 0; i < n; i++ {
		fmt.Fscanf(bufin, "%s\n", &op)
		if op == "+" {
			fmt.Fscanf(bufin, "%d\n", &x)
			add(x, maxbit, root)
		} else if op == "-" {
			fmt.Fscanf(bufin, "%d\n", &x)
			del(x, maxbit, root)
		} else {
			fmt.Fscanf(bufin, "%s\n", &s)
			for len(s) < maxbit {
				s = "0" + s
			}
			res := query(s, maxbit-1, root)
			fmt.Fprintf(bufout, "%d\n", res)
		}
	}
}

package main

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

import "strings"

type node struct {
	count int64
	even  *node
	odd   *node
}

func addvalue(value int64, n *node) {
	r := value % 2
	d := value / 10
	if r == 0 {
		if n.even == nil {
			n.even = &node{0, nil, nil}
		}
		n = n.even
	} else {
		if n.odd == nil {
			n.odd = &node{0, nil, nil}
		}
		n = n.odd
	}
	if d == 0 {
		n.count++
		return
	}
	addvalue(d, n)
}
func delvalue(value int64, n *node) {
	r := value % 2
	d := value / 10
	if r == 0 {
		n = n.even
	} else {
		n = n.odd
	}
	if d == 0 {
		n.count--
		return
	}
	delvalue(d, n)
}

func p(n *node, s []int) {
	if n == nil {
		return
	}
	if n.count > 0 {
		fmt.Print(s)
	}
	p(n.even, append(s, 0))
	p(n.odd, append(s, 1))
}

func check(p int64, n *node, c int64) int64 {
	if n == nil {
		return c
	}
	if p == 0 {
		return check(0, n.even, c+n.count)
	}
	r := p % 2
	d := p / 10
	c += n.count
	if r == 0 {
		n = n.even
	} else {
		c = 0
		n = n.odd
	}
	return check(d, n, c)
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	text, _ := reader.ReadString('\n')
	text = strings.TrimRight(text, "\r\n")
	s := strings.Split(text, " ")

	base := node{0, nil, nil}
	c, _ := strconv.Atoi(s[0])
	//x, _ := strconv.ParseInt(s[1], 10, 64)
	for i := 0; i < c; i++ {
		text, _ := reader.ReadString('\n')
		text = strings.TrimRight(text, "\r\n")
		s := strings.Split(text, " ")
		x, _ := strconv.ParseInt(s[1], 10, 64)
		if s[0] == "?" {
			fmt.Println(check(x, &base, 0))
		} else if s[0] == "+" {
			addvalue(x, &base)
		} else if s[0] == "-" {
			delvalue(x, &base)
		}
	}
}

package main

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

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

type Node struct {
	val   int
	child [2]*Node
}

func create(v int) *Node {
	r := &Node{
		val:   0,
		child: [2]*Node{nil, nil},
	}
	return r
}

func add(x int64, i int, node *Node) {
	if i < 0 {
		return
	}
	bit := x & 1
	if node.child[bit] == nil {
		node.child[bit] = create(0)
	}
	node.child[bit].val++
	add(x/10, i-1, node.child[bit])
}

func del(x int64, i int, node *Node) {
	if i < 0 {
		return
	}
	bit := x & 1
	node.child[bit].val--
	del(x/10, i-1, node.child[bit])
}

func query(bits []byte, i int, node *Node) int {
	if i < 0 {
		return node.val
	}
	bit := bits[i] - '0'
	if node.child[bit] != nil {
		return query(bits, i-1, node.child[bit])
	}
	return 0
}

const maxbit = 20

var root *Node

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

	var n int
	var x int64
	var op, s string

	root = create(0)
	fmt.Fscanf(bufin, "%d\n", &n)

	for i := 0; i < n; i++ {
		fmt.Fscanf(bufin, "%s\n", &op)
		if op == "+" {
			fmt.Fscanf(bufin, "%d\n", &x)
			add(x, maxbit, root)
		} else if op == "-" {
			fmt.Fscanf(bufin, "%d\n", &x)
			del(x, maxbit, root)
		} else {
			fmt.Fscanf(bufin, "%s\n", &s)
			bits := []byte(s)
			res := query(bits, len(bits)-1, root)
			fmt.Fprintf(bufout, "%d\n", res)
		}
	}
}

package main

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

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

type Node struct {
	val   int
	child [2]*Node
}

func create(v int) *Node {
	r := &Node{
		val:   v,
		child: [2]*Node{nil, nil},
	}
	return r
}

func add(x int64, i int, node *Node) {
	if i < 0 {
		return
	}
	bit := x & 1
	if node.child[bit] == nil {
		node.child[bit] = create(0)
	}
	node.child[bit].val++
	add(x/10, i-1, node.child[bit])
}

func del(x int64, i int, node *Node) {
	if i < 0 {
		return
	}
	bit := x & 1
	node.child[bit].val--
	del(x/10, i-1, node.child[bit])
}

func query(bits string, i int, node *Node) int {
	if i < 0 {
		return node.val
	}
	bit := bits[i] - '0'
	if node.child[bit] != nil {
		return query(bits, i-1, node.child[bit])
	}
	return 0
}

const maxbit = 30

var root *Node

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

	var n int
	var x int64
	var op, s string

	root = create(0)
	fmt.Fscanf(bufin, "%d\n", &n)

	for i := 0; i < n; i++ {
		fmt.Fscanf(bufin, "%s\n", &op)
		if op == "+" {
			fmt.Fscanf(bufin, "%d\n", &x)
			add(x, maxbit, root)
		} else if op == "-" {
			fmt.Fscanf(bufin, "%d\n", &x)
			del(x, maxbit, root)
		} else {
			fmt.Fscanf(bufin, "%s\n", &s)
			res := query(s, len(s)-1, root)
			fmt.Fprintf(bufout, "%d\n", res)
		}
	}
}