ZS the Coder and Chris the Baboon has explored Udayland for quite some time. They realize that it consists of n towns numbered from 1 to n. There are n directed roads in the Udayland. i-th of them goes from town i to some other town ai (ai ≠ i). ZS the Coder can flip the direction of any road in Udayland, i.e. if it goes from town A to town B before the flip, it will go from town B to town A after.ZS the Coder considers the roads in the Udayland confusing, if there is a sequence of distinct towns A1, A2, ..., Ak (k > 1) such that for every 1 ≤ i < k there is a road from town Ai to town Ai + 1 and another road from town Ak to town A1. In other words, the roads are confusing if some of them form a directed cycle of some towns.Now ZS the Coder wonders how many sets of roads (there are 2n variants) in initial configuration can he choose to flip such that after flipping each road in the set exactly once, the resulting network will not be confusing.Note that it is allowed that after the flipping there are more than one directed road from some town and possibly some towns with no roads leading out of it, or multiple roads between any pair of cities.

The first line of the input contains single integer n (2 ≤ n ≤ 2·105) — the number of towns in Udayland. The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n, ai ≠ i), ai denotes a road going from town i to town ai.

Print a single integer — the number of ways to flip some set of the roads so that the resulting whole set of all roads is not confusing. Since this number may be too large, print the answer modulo 109 + 7.

NoteConsider the first sample case. There are 3 towns and 3 roads. The towns are numbered from 1 to 3 and the roads are , ,  initially. Number the roads 1 to 3 in this order. The sets of roads that ZS the Coder can flip (to make them not confusing) are {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}. Note that the empty set is invalid because if no roads are flipped, then towns 1, 2, 3 is form a directed cycle, so it is confusing. Similarly, flipping all roads is confusing too. Thus, there are a total of 6 possible sets ZS the Coder can flip.The sample image shows all possible ways of orienting the roads from the first sample such that the network is not confusing.

package main

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

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

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

	a := make([]int, n+1)
	b := make([]int, n+1)
	p := make([]int64, n+1)

	const mod = int64(1000000007)
	p[0] = 1

	for i := 1; i <= n; i++ {
		fmt.Fscanf(buf, "%d\n", &a[i])
		b[i] = -1
		p[i] = (p[i-1] * 2) % mod
	}

	result := int64(1)
	remain := n

	step := 0
	for i := 1; i <= n; i++ {
		if b[i] == -1 {
			step++
			j := i
			for b[j] == -1 {
				b[j] = step
				j = a[j]
			}

			if b[j] == step {
				cnt := 1
				for k := a[j]; k != j; k = a[k] {
					cnt++
				}
				result = result * (p[cnt] - 2) % mod
				remain -= cnt
			}
		}
	}

	result = (result * p[remain]) % mod
	fmt.Printf("%d\n", result)
}

package main

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

const (
	MOD   = 1000000007
	MAX_N = 200010
)

var A [MAX_N][]int
var deg [MAX_N]int
var num, cnt int
var done [MAX_N]bool

func dfs(v int) {
	done[v] = true
	num++
	if deg[v] >= 1 {
		cnt++
	}
	for _, next := range A[v] {
		if !done[next] {
			dfs(next)
		}
	}
}

func main() {
	fsc := NewFastScanner()
	N := fsc.NextInt()
	for i := 0; i < N; i++ {
		a := fsc.NextInt()
		a--
		A[i] = append(A[i], a)
		A[a] = append(A[a], i)
		deg[i]++
		deg[a]++
	}
	//fmt.Println(A[:N], len(A), len(A[0]))
	queue := list.New()
	for i := 0; i < N; i++ {
		if deg[i] == 1 {
			queue.PushBack(i)
			deg[i] = 0
		}
	}
	for queue.Len() > 0 {
		pos := queue.Remove(queue.Front())
		switch p := pos.(type) {
		case int:
			for _, v := range A[p] {
				if deg[v] == 0 {
					continue
				}
				deg[v]--
				if deg[v] == 1 {
					deg[v] = 0
					queue.PushBack(v)
				}
			}
		}
	}
	ans := int64(1)

	for i := 0; i < N; i++ {
		if done[i] {
			continue
		}
		num, cnt = 0, 0
		dfs(i)

		tmp := int64(1)
		for j := 0; j < num; j++ {
			tmp *= 2
			tmp %= MOD
		}
		minus := int64(1)
		for j := 0; j < num-cnt+1; j++ {
			minus *= 2
			minus %= MOD
		}
		tmp = (tmp - minus + MOD) % MOD
		ans *= tmp
		ans %= MOD
		//fmt.Println(num, cnt)
	}
	fmt.Println(ans)
}

//template
type FastScanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewFastScanner() *FastScanner {
	rdr := bufio.NewReaderSize(os.Stdin, 2028)
	return &FastScanner{r: rdr}
}

func (s *FastScanner) 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 *FastScanner) NextInt() int {
	val, err := strconv.Atoi(s.Next())
	if err != nil {
		panic(err)
	}
	return val
}
func (s *FastScanner) NextInt64() int64 {
	val, err := strconv.ParseInt(s.Next(), 10, 64)
	if err != nil {
		panic(err)
	}
	return val
}
func (s *FastScanner) Pre() {
	if s.p >= len(s.buf) {
		s.ReadLine()
		s.p = 0
	}
}

func (s *FastScanner) ReadLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, err := s.r.ReadLine()
		if err != nil {
			panic(err.Error())
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}

package main

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

const (
	MOD   = 1000000007
	MAX_N = 200010
)

var A [MAX_N][]int
var deg [MAX_N]int
var num, cnt int
var done [MAX_N]bool

func dfs(v int) {
	done[v] = true
	num++
	if deg[v] >= 1 {
		cnt++
	}
	for _, next := range A[v] {
		if !done[next] {
			dfs(next)
		}
	}
}

func main() {
	fsc := NewFastScanner()
	N := fsc.NextInt()
	for i := 0; i < N; i++ {
		a := fsc.NextInt()
		a--
		A[i] = append(A[i], a)
		A[a] = append(A[a], i)
		deg[i]++
		deg[a]++
	}
	//fmt.Println(A[:N], len(A), len(A[0]))
	queue := list.New()
	for i := 0; i < N; i++ {
		if deg[i] == 1 {
			queue.PushBack(i)
			deg[i] = 0
		}
	}
	for queue.Len() > 0 {
		pos := queue.Remove(queue.Front())
		switch p := pos.(type) {
		case int:
			for _, v := range A[p] {
				if deg[v] == 0 {
					continue
				}
				deg[v]--
				if deg[v] == 1 {
					deg[v] = 0
					queue.PushBack(v)
				}
			}
		}
	}
	ans := 1

	for i := 0; i < N; i++ {
		if done[i] {
			continue
		}
		num, cnt = 0, 0
		dfs(i)

		tmp := 1
		for j := 0; j < num; j++ {
			tmp *= 2
			tmp %= MOD
		}
		minus := 1
		for j := 0; j < num-cnt+1; j++ {
			minus *= 2
			minus %= MOD
		}
		tmp = (tmp - minus + MOD) % MOD
		ans *= tmp
		ans %= MOD
		//fmt.Println(num, cnt)
	}
	fmt.Println(ans)
}

//template
type FastScanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewFastScanner() *FastScanner {
	rdr := bufio.NewReaderSize(os.Stdin, 2028)
	return &FastScanner{r: rdr}
}

func (s *FastScanner) 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 *FastScanner) NextInt() int {
	val, err := strconv.Atoi(s.Next())
	if err != nil {
		panic(err)
	}
	return val
}
func (s *FastScanner) NextInt64() int64 {
	val, err := strconv.ParseInt(s.Next(), 10, 64)
	if err != nil {
		panic(err)
	}
	return val
}
func (s *FastScanner) Pre() {
	if s.p >= len(s.buf) {
		s.ReadLine()
		s.p = 0
	}
}

func (s *FastScanner) ReadLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, err := s.r.ReadLine()
		if err != nil {
			panic(err.Error())
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}

package main

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

const (
	MOD   = 1000000007
	MAX_N = 200010
)

var A [][]int
var visited [MAX_N]int
var src int
var cnt int
var node int
var multiCnt [MAX_N]map[int]int

func dfs(pos, pre int) {
	visited[pos] = 1
	node++
	for _, next := range A[pos] {
		if next != pre || multiCnt[pos][next] == 2 {
			if visited[next] == 1 { //find cycle
				src = next
			} else if visited[next] == 0 {
				dfs(next, pos)
			}
		}
	}
	visited[pos] = 2
	if src != -1 {
		cnt++
	}
	if src == pos {
		src = -1
	}

}
func main() {
	fsc := NewFastScanner()
	N := fsc.NextInt()
	A = make([][]int, N)
	for i := 0; i < N; i++ {
		multiCnt[i] = map[int]int{}
	}
	//fmt.Println(deg[0][0])
	//fmt.Println(deg)
	for i := 0; i < N; i++ {
		a := fsc.NextInt()
		a--
		A[i] = append(A[i], a)
		A[a] = append(A[a], i)
		multiCnt[i][a]++
		multiCnt[a][i]++
	}

	var ans int
	ans = 1
	for i := 0; i < N; i++ {
		if visited[i] == 0 {
			src = -1
			node = 0
			cnt = 0
			var res1, res2 int
			res1, res2 = 1, 1
			dfs(i, -1)
			//fmt.Println(node, cnt, src)
			for i := 0; i < node; i++ {
				res1 *= 2
				res1 %= MOD
			}
			for i := 0; i < node-cnt+1; i++ {
				res2 *= 2
				res2 %= MOD
			}
			res1 -= res2
			for res1 < 0 {
				res1 += MOD
			}
			ans *= res1
			ans %= MOD
			//fmt.Println(cnt)
		}
	}
	fmt.Println(ans)
}

//template
type FastScanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewFastScanner() *FastScanner {
	rdr := bufio.NewReaderSize(os.Stdin, 2028)
	return &FastScanner{r: rdr}
}

func (s *FastScanner) 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 *FastScanner) NextInt() int {
	val, err := strconv.Atoi(s.Next())
	if err != nil {
		panic(err)
	}
	return val
}
func (s *FastScanner) NextInt64() int64 {
	val, err := strconv.ParseInt(s.Next(), 10, 64)
	if err != nil {
		panic(err)
	}
	return val
}
func (s *FastScanner) Pre() {
	if s.p >= len(s.buf) {
		s.ReadLine()
		s.p = 0
	}
}

func (s *FastScanner) ReadLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, err := s.r.ReadLine()
		if err != nil {
			panic(err.Error())
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}

package main

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

const (
	MOD   = 1000000007
	MAX_N = 200010
)

var A [][]int
var visited [MAX_N]int
var src int
var cnt int
var node int
var multiCnt [MAX_N]map[int]int

func dfs(pos, pre int) {
	visited[pos] = 1
	node++
	cycle := -1
	for _, next := range A[pos] {
		if next != pre {
			if visited[next] == 1 { //find cycle
				cycle = next
			} else if visited[next] == 0 {
				dfs(next, pos)
			}
		} else if multiCnt[pos][next] == 2 {
			cnt = 2
		}
	}
	if cycle != -1 {
		src = cycle
	}
	visited[pos] = 2
	if src != -1 {
		cnt++
	}
	if src == pos {
		src = -1
	}

}
func main() {
	fsc := NewFastScanner()
	N := fsc.NextInt()
	A = make([][]int, N)
	for i := 0; i < N; i++ {
		multiCnt[i] = map[int]int{}
	}
	//fmt.Println(deg[0][0])
	//fmt.Println(deg)
	for i := 0; i < N; i++ {
		a := fsc.NextInt()
		a--
		A[i] = append(A[i], a)
		A[a] = append(A[a], i)
		multiCnt[i][a]++
		multiCnt[a][i]++
	}

	var ans int64
	ans = 1
	for i := 0; i < N; i++ {
		if visited[i] == 0 {
			src = -1
			node = 0
			cnt = 0
			var res1, res2 int64
			res1, res2 = 1, 1
			dfs(i, -1)
			//fmt.Println(node, cnt, src)
			for i := 0; i < node; i++ {
				res1 *= 2
				res1 %= MOD
			}
			for i := 0; i < node-cnt+1; i++ {
				res2 *= 2
				res2 %= MOD
			}
			res1 -= res2
			for res1 < 0 {
				res1 += MOD
			}
			ans *= res1
			ans %= MOD
			//fmt.Println(cnt)
		}
	}
	fmt.Println(ans)
}

//template
type FastScanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewFastScanner() *FastScanner {
	rdr := bufio.NewReaderSize(os.Stdin, 2028)
	return &FastScanner{r: rdr}
}

func (s *FastScanner) 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 *FastScanner) NextInt() int {
	val, err := strconv.Atoi(s.Next())
	if err != nil {
		panic(err)
	}
	return val
}
func (s *FastScanner) NextInt64() int64 {
	val, err := strconv.ParseInt(s.Next(), 10, 64)
	if err != nil {
		panic(err)
	}
	return val
}
func (s *FastScanner) Pre() {
	if s.p >= len(s.buf) {
		s.ReadLine()
		s.p = 0
	}
}

func (s *FastScanner) ReadLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, err := s.r.ReadLine()
		if err != nil {
			panic(err.Error())
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}

package main

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

const (
	MOD   = 1000000007
	MAX_N = 200010
)

var A [][]int
var visited [MAX_N]int
var src int
var cnt int

func dfs(pos, pre int) {
	visited[pos] = 1
	for _, next := range A[pos] {
		if next == pre {
			continue
		}
		if visited[next] == 1 { //find cycle
			src = next
		} else if visited[next] == 0 {
			dfs(next, pos)
		}
	}
	visited[pos] = 2
	if src != -1 {
		cnt++
	}
	if src == pos {
		src = -1
	}

}
func main() {
	fsc := NewFastScanner()
	N := fsc.NextInt()
	A = make([][]int, N)

	deg := make([]map[int]int, N)
	for i := 0; i < N; i++ {
		deg[i] = map[int]int{}
	}
	//fmt.Println(deg[0][0])
	//fmt.Println(deg)
	isMulti := false
	for i := 0; i < N; i++ {
		a := fsc.NextInt()
		a--
		A[i] = append(A[i], a)
		A[a] = append(A[a], i)
		deg[i][a]++
		deg[a][i]++
		if deg[i][a] >= 2 || deg[a][i] >= 2 {
			isMulti = true
		}
	}

	src = -1
	if !isMulti {
		dfs(0, -1)
	} else {
		cnt = 2
	}
	//fmt.Println(cnt)
	var res1, res2 int
	res1, res2 = 1, 1
	for i := 0; i < N; i++ {
		res1 *= 2
		res1 %= MOD
	}
	for i := 0; i < N-cnt+1; i++ {
		res2 *= 2
		res2 %= MOD
	}
	res1 -= res2
	for res1 < 0 {
		res1 += MOD
	}
	fmt.Println(res1)
}

//template
type FastScanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewFastScanner() *FastScanner {
	rdr := bufio.NewReaderSize(os.Stdin, 2028)
	return &FastScanner{r: rdr}
}

func (s *FastScanner) 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 *FastScanner) NextInt() int {
	val, err := strconv.Atoi(s.Next())
	if err != nil {
		panic(err)
	}
	return val
}
func (s *FastScanner) NextInt64() int64 {
	val, err := strconv.ParseInt(s.Next(), 10, 64)
	if err != nil {
		panic(err)
	}
	return val
}
func (s *FastScanner) Pre() {
	if s.p >= len(s.buf) {
		s.ReadLine()
		s.p = 0
	}
}

func (s *FastScanner) ReadLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, err := s.r.ReadLine()
		if err != nil {
			panic(err.Error())
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}

package main

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

const (
	MOD   = 1000000007
	MAX_N = 200010
)

var A [][]int
var visited [MAX_N]int
var src int
var cnt int
var node int
var multiCnt [MAX_N]map[int]int

func dfs(pos, pre int) {
	visited[pos] = 1
	node++
	cycle := -1
	for _, next := range A[pos] {
		if next != pre {
			if visited[next] == 1 { //find cycle
				cycle = next
			} else if visited[next] == 0 {
				dfs(next, pos)
			}
		} else if multiCnt[pos][next] == 2 {
			cnt = 2
		}
	}
	if cycle != -1 {
		src = cycle
	}
	visited[pos] = 2
	if src != -1 {
		cnt++
	}
	if src == pos {
		src = -1
	}

}
func main() {
	fsc := NewFastScanner()
	N := fsc.NextInt()
	A = make([][]int, N)
	for i := 0; i < N; i++ {
		multiCnt[i] = map[int]int{}
	}
	//fmt.Println(deg[0][0])
	//fmt.Println(deg)
	for i := 0; i < N; i++ {
		a := fsc.NextInt()
		a--
		A[i] = append(A[i], a)
		A[a] = append(A[a], i)
		multiCnt[i][a]++
		multiCnt[a][i]++
	}

	var ans int
	ans = 1
	for i := 0; i < N; i++ {
		if visited[i] == 0 {
			src = -1
			node = 0
			cnt = 0
			var res1, res2 int
			res1, res2 = 1, 1
			dfs(i, -1)
			//fmt.Println(node, cnt, src)
			for i := 0; i < node; i++ {
				res1 *= 2
				res1 %= MOD
			}
			for i := 0; i < node-cnt+1; i++ {
				res2 *= 2
				res2 %= MOD
			}
			res1 -= res2
			for res1 < 0 {
				res1 += MOD
			}
			ans *= res1
			ans %= MOD
			//fmt.Println(cnt)
		}
	}
	fmt.Println(ans)
}

//template
type FastScanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewFastScanner() *FastScanner {
	rdr := bufio.NewReaderSize(os.Stdin, 2028)
	return &FastScanner{r: rdr}
}

func (s *FastScanner) 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 *FastScanner) NextInt() int {
	val, err := strconv.Atoi(s.Next())
	if err != nil {
		panic(err)
	}
	return val
}
func (s *FastScanner) NextInt64() int64 {
	val, err := strconv.ParseInt(s.Next(), 10, 64)
	if err != nil {
		panic(err)
	}
	return val
}
func (s *FastScanner) Pre() {
	if s.p >= len(s.buf) {
		s.ReadLine()
		s.p = 0
	}
}

func (s *FastScanner) ReadLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, err := s.r.ReadLine()
		if err != nil {
			panic(err.Error())
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}

package main

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

const (
	MOD   = 1000000007
	MAX_N = 200010
)

var A [][]int
var visited [MAX_N]int
var src int
var cnt int
var node int
var multiCnt [MAX_N]map[int]int

func dfs(pos, pre int) {
	visited[pos] = 1
	node++
	for _, next := range A[pos] {
		if next != pre {
			if visited[next] == 1 { //find cycle
				src = next
			} else if visited[next] == 0 {
				dfs(next, pos)
			}
		} else if multiCnt[pos][next] == 2 {
			cnt = 2
		}
	}
	visited[pos] = 2
	if src != -1 {
		cnt++
	}
	if src == pos {
		src = -1
	}

}
func main() {
	fsc := NewFastScanner()
	N := fsc.NextInt()
	A = make([][]int, N)
	for i := 0; i < N; i++ {
		multiCnt[i] = map[int]int{}
	}
	//fmt.Println(deg[0][0])
	//fmt.Println(deg)
	for i := 0; i < N; i++ {
		a := fsc.NextInt()
		a--
		A[i] = append(A[i], a)
		A[a] = append(A[a], i)
		multiCnt[i][a]++
		multiCnt[a][i]++
	}

	var ans int
	ans = 1
	for i := 0; i < N; i++ {
		if visited[i] == 0 {
			src = -1
			node = 0
			cnt = 0
			var res1, res2 int
			res1, res2 = 1, 1
			dfs(i, -1)
			//fmt.Println(node, cnt, src)
			for i := 0; i < node; i++ {
				res1 *= 2
				res1 %= MOD
			}
			for i := 0; i < node-cnt+1; i++ {
				res2 *= 2
				res2 %= MOD
			}
			res1 -= res2
			for res1 < 0 {
				res1 += MOD
			}
			ans *= res1
			ans %= MOD
			//fmt.Println(cnt)
		}
	}
	fmt.Println(ans)
}

//template
type FastScanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewFastScanner() *FastScanner {
	rdr := bufio.NewReaderSize(os.Stdin, 2028)
	return &FastScanner{r: rdr}
}

func (s *FastScanner) 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 *FastScanner) NextInt() int {
	val, err := strconv.Atoi(s.Next())
	if err != nil {
		panic(err)
	}
	return val
}
func (s *FastScanner) NextInt64() int64 {
	val, err := strconv.ParseInt(s.Next(), 10, 64)
	if err != nil {
		panic(err)
	}
	return val
}
func (s *FastScanner) Pre() {
	if s.p >= len(s.buf) {
		s.ReadLine()
		s.p = 0
	}
}

func (s *FastScanner) ReadLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, err := s.r.ReadLine()
		if err != nil {
			panic(err.Error())
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}


This is the easy version of the problem. The difference between versions is the constraints on $$$n$$$ and $$$a_i$$$. You can make hacks only if all versions of the problem are solved.First, Aoi came up with the following idea for the competitive programming problem:Yuzu is a girl who collecting candies. Originally, she has $$$x$$$ candies. There are also $$$n$$$ enemies numbered with integers from $$$1$$$ to $$$n$$$. Enemy $$$i$$$ has $$$a_i$$$ candies.Yuzu is going to determine a permutation $$$P$$$. A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$\{2,3,1,5,4\}$$$ is a permutation, but $$$\{1,2,2\}$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$\{1,3,4\}$$$ is also not a permutation (because $$$n=3$$$ but there is the number $$$4$$$ in the array).After that, she will do $$$n$$$ duels with the enemies with the following rules:  If Yuzu has equal or more number of candies than enemy $$$P_i$$$, she wins the duel and gets $$$1$$$ candy. Otherwise, she loses the duel and gets nothing.  The candy which Yuzu gets will be used in the next duels. Yuzu wants to win all duels. How many valid permutations $$$P$$$ exist?This problem was easy and wasn't interesting for Akari, who is a friend of Aoi. And Akari made the following problem from the above idea:Let's define $$$f(x)$$$ as the number of valid permutations for the integer $$$x$$$.You are given $$$n$$$, $$$a$$$ and a prime number $$$p \le n$$$. Let's call a positive integer $$$x$$$ good, if the value $$$f(x)$$$ is not divisible by $$$p$$$. Find all good integers $$$x$$$.Your task is to solve this problem made by Akari.

The first line contains two integers $$$n$$$, $$$p$$$ $$$(2 \le p \le n \le 2000)$$$. It is guaranteed, that the number $$$p$$$ is prime (it has exactly two divisors $$$1$$$ and $$$p$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le 2000)$$$.

In the first line, print the number of good integers $$$x$$$. In the second line, output all good integers $$$x$$$ in the ascending order. It is guaranteed that the number of good integers $$$x$$$ does not exceed $$$10^5$$$.

NoteIn the first test, $$$p=2$$$.  If $$$x \le 2$$$, there are no valid permutations for Yuzu. So $$$f(x)=0$$$ for all $$$x \le 2$$$. The number $$$0$$$ is divisible by $$$2$$$, so all integers $$$x \leq 2$$$ are not good.  If $$$x = 3$$$, $$$\{1,2,3\}$$$ is the only valid permutation for Yuzu. So $$$f(3)=1$$$, so the number $$$3$$$ is good.  If $$$x = 4$$$, $$$\{1,2,3\} , \{1,3,2\} , \{2,1,3\} , \{2,3,1\}$$$ are all valid permutations for Yuzu. So $$$f(4)=4$$$, so the number $$$4$$$ is not good.  If $$$x \ge 5$$$, all $$$6$$$ permutations are valid for Yuzu. So $$$f(x)=6$$$ for all $$$x \ge 5$$$, so all integers $$$x \ge 5$$$ are not good. So, the only good number is $$$3$$$.In the third test, for all positive integers $$$x$$$ the value $$$f(x)$$$ is divisible by $$$p = 3$$$.

package main

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

var in *bufio.Reader
var out *bufio.Writer

func printf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(out, x, a...)
}

func scanf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fscanf(in, x, a...)
}

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

type node struct {
	l, r, mid, tot int
	left, right    *node
}

func (v *node) off(le, ri int) {
	if (le <= v.l && ri >= v.r) || v.tot == 0 {
		v.tot = 0
		return
	}

	if v.left == nil {
		v.left = &node{v.l, v.mid, (v.l + v.mid) >> 1, v.mid - v.l, nil, nil}
	}
	if v.right == nil {
		v.right = &node{v.mid, v.r, (v.mid + v.r) >> 1, v.r - v.mid, nil, nil}
	}

	if le < v.mid {
		v.left.off(le, ri)
	}
	if ri > v.mid {
		v.right.off(le, ri)
	}

	v.tot = v.left.tot + v.right.tot
}

const maxLog = 30

var res = []int{}

func (v *node) find() {
	if v == nil {
		return
	}
	if v.tot == 0 {
		return
	}
	if v.l == v.r-1 {
		res = append(res, v.l)
		return
	}

	if v.left == nil {
		v.left = &node{v.l, v.mid, (v.l + v.mid) >> 1, v.mid - v.l, nil, nil}
	}
	if v.right == nil {
		v.right = &node{v.mid, v.r, (v.mid + v.r) >> 1, v.r - v.mid, nil, nil}
	}

	v.left.find()
	v.right.find()
}

func main() {
	out = bufio.NewWriterSize(os.Stdout, 8192)
	defer out.Flush()
	if false {
		file, err := os.Open("in.txt")
		if err != nil {
			log.Fatal(err)
		}
		in = bufio.NewReaderSize(file, 8192)
	} else {
		in = bufio.NewReaderSize(os.Stdin, 8192)
	}

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

	arr := make([]int, n)
	for i := range arr {
		scanf("%d", &arr[i])
	}

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

	tree := &node{0, 1 << maxLog, 1 << (maxLog - 1), 1 << maxLog, nil, nil}
	tree.off(arr[n-1]-(n-p), 1<<30)

	for i, v := range arr {
		tree.off(0, v-i)
	}

	for i := p; i < n; i++ {
		tree.off(arr[i-1]-(i-p), arr[i]-(i-p))
	}

	tree.find()
	printf("%d\n", len(res))
	for _, v := range res {
		printf("%d ", v)
	}
	printf("\n")
}

package main

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

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

	n, p := readTwoNums(reader)
	A := readNNums(reader, n)
	res := solve(n, p, A)
	fmt.Println(len(res))
	for i := 0; i < len(res); i++ {
		fmt.Printf("%d ", res[i])
	}
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func solve(n int, p int, A []int) []int {
	sort.Ints(A)
	X := A[n-1]

	// x < X - n + 1 f(x) == 0
	// x >= X, f(x) = n!, and p < n
	var res []int
	var jj int
	for x := X - n + 1; x < X; x++ {
		for jj < n && A[jj] < x {
			jj++
		}
		j := jj
		var ok = true
		v := j
		for i := x; i <= x+n-1; i++ {
			k := j
			for k < n && A[k] == i {
				k++
			}
			v += k - j
			if v%p == 0 {
				ok = false
				break
			}
			v--
			j = k
		}
		if ok {
			res = append(res, x)
		}
	}
	return res
}

/*
URL:
https://codeforces.com/contest/1371/problem/E1
*/

package main

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

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

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

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

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

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

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

const (
	// General purpose
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPHABET_NUM = 26
	INF_INT64    = math.MaxInt64
	INF_BIT60    = 1 << 60
	INF_INT32    = math.MaxInt32
	INF_BIT30    = 1 << 30
	NIL          = -1

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

func init() {
	// bufio.ScanWords <---> bufio.ScanLines
	ReadString = newReadString(os.Stdin, bufio.ScanWords)
	stdout = bufio.NewWriter(os.Stdout)
}

var (
	n, p int
	A    []int

	cnts [100000 + 50]int
	pref [100000 + 50]int
)

func main() {
	n, p = ReadInt2()
	A = ReadIntSlice(n)

	solve()
}

func solve() {
	answers := []int{}

	sort.Sort(sort.IntSlice(A))

	for i := 0; i < n; i++ {
		cnts[A[i]]++
	}
	for i := 1; i <= 10000; i++ {
		pref[i] = pref[i-1] + cnts[i]
	}
	// PrintfDebug("cnts: %v\n", cnts[:10])
	// PrintfDebug("pref: %v\n", pref[:10])

	ma := Max(A...)
	// for x := Max(ma-n+1, 0); x <= ma; x++ {
	for x := 0; x <= ma; x++ {
		if isOK(x) {
			answers = append(answers, x)
		}
	}

	fmt.Println(len(answers))
	fmt.Println(PrintIntsLine(answers...))
}

func isOK(y int) bool {
	res := 1

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

		num := pref[y]
		if num-i <= 0 {
			return false
		}

		res *= num - i
		res %= p

		y++
	}

	return res > 0
}

// Max returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Max(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

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

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

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		res = append(res, []rune(str)...)

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

	return string(res)
}

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

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

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

	return string(res)
}

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

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

package main

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

var in *bufio.Reader
var out *bufio.Writer

func printf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(out, x, a...)
}

func scanf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fscanf(in, x, a...)
}

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

type node struct {
	l, r, mid, tot int
	left, right    *node
}

func (v *node) off(le, ri int) {
	if (le <= v.l && ri >= v.r) || v.tot == 0 {
		v.tot = 0
		return
	}

	if v.left == nil {
		v.left = &node{v.l, v.mid, (v.l + v.mid) >> 1, v.mid - v.l, nil, nil}
	}
	if v.right == nil {
		v.right = &node{v.mid, v.r, (v.mid + v.r) >> 1, v.r - v.mid, nil, nil}
	}

	if le < v.mid {
		v.left.off(le, ri)
	}
	if ri > v.mid {
		v.right.off(le, ri)
	}

	v.tot = v.left.tot + v.right.tot
}

var res = []int{}

func (v *node) find() {
	if v == nil {
		return
	}
	if v.tot == 0 {
		return
	}
	if v.l == v.r-1 {
		res = append(res, v.l)
		return
	}

	v.left.find()
	v.right.find()
}

func main() {
	out = bufio.NewWriterSize(os.Stdout, 8192)
	defer out.Flush()
	if false {
		file, err := os.Open("in.txt")
		if err != nil {
			log.Fatal(err)
		}
		in = bufio.NewReaderSize(file, 8192)
	} else {
		in = bufio.NewReaderSize(os.Stdin, 8192)
	}

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

	arr := make([]int, n)
	for i := range arr {
		scanf("%d", &arr[i])
	}

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

	tree := &node{0, 1 << 30, 1 << 29, 1 << 30, nil, nil}
	tree.off(arr[n-1]-(n-p), 1<<30)

	for i, v := range arr {
		tree.off(0, v-i)
	}

	for i := p; i < n; i++ {
		tree.off(arr[i-1]-(i-p), arr[i]-(i-p))
	}

	tree.find()
	printf("%d\n", len(res))
	for _, v := range res {
		printf("%d ", v)
	}
	printf("\n")
}

/*
URL:
https://codeforces.com/contest/1371/problem/E1
*/

package main

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

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

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

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

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

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

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

const (
	// General purpose
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPHABET_NUM = 26
	INF_INT64    = math.MaxInt64
	INF_BIT60    = 1 << 60
	INF_INT32    = math.MaxInt32
	INF_BIT30    = 1 << 30
	NIL          = -1

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

func init() {
	// bufio.ScanWords <---> bufio.ScanLines
	ReadString = newReadString(os.Stdin, bufio.ScanWords)
	stdout = bufio.NewWriter(os.Stdout)
}

var (
	n, p int
	A    []int

	cnts [100000 + 50]int
	pref [100000 + 50]int
)

func main() {
	n, p = ReadInt2()
	A = ReadIntSlice(n)

	solve()
}

func solve() {
	answers := []int{}

	sort.Sort(sort.IntSlice(A))

	for i := 0; i < n; i++ {
		cnts[A[i]]++
	}
	for i := 1; i <= 2000; i++ {
		pref[i] = pref[i-1] + cnts[i]
	}
	// PrintfDebug("cnts: %v\n", cnts[:10])
	// PrintfDebug("pref: %v\n", pref[:10])

	ma := Max(A...)
	for x := Max(ma-n+1, 0); x <= ma; x++ {
		if isOK(x) {
			answers = append(answers, x)
		}
	}

	fmt.Println(len(answers))
	fmt.Println(PrintIntsLine(answers...))
}

func isOK(y int) bool {
	res := 1

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

		num := pref[y]
		res *= num - i
		res %= p

		y++
	}

	return res > 0
}

// Max returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Max(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

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

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

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		res = append(res, []rune(str)...)

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

	return string(res)
}

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

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

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

	return string(res)
}

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

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

/*
URL:
https://codeforces.com/contest/1371/problem/E1
*/

package main

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

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

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

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

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

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

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

const (
	// General purpose
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPHABET_NUM = 26
	INF_INT64    = math.MaxInt64
	INF_BIT60    = 1 << 60
	INF_INT32    = math.MaxInt32
	INF_BIT30    = 1 << 30
	NIL          = -1

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

func init() {
	// bufio.ScanWords <---> bufio.ScanLines
	ReadString = newReadString(os.Stdin, bufio.ScanWords)
	stdout = bufio.NewWriter(os.Stdout)
}

var (
	n, p int
	A    []int

	cnts [100000 + 50]int
	pref [100000 + 50]int
)

func main() {
	n, p = ReadInt2()
	A = ReadIntSlice(n)

	solve()
}

func solve() {
	answers := []int{}

	sort.Sort(sort.IntSlice(A))

	for i := 0; i < n; i++ {
		cnts[A[i]]++
	}
	for i := 1; i <= 2000; i++ {
		pref[i] = pref[i-1] + cnts[i]
	}
	// PrintfDebug("cnts: %v\n", cnts[:10])
	// PrintfDebug("pref: %v\n", pref[:10])

	ma := Max(A...)
	// for x := Max(ma-n+1, 0); x <= ma; x++ {
	for x := 0; x <= ma; x++ {
		if isOK(x) {
			answers = append(answers, x)
		}
	}

	fmt.Println(len(answers))
	fmt.Println(PrintIntsLine(answers...))
}

func isOK(y int) bool {
	res := 1

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

		num := pref[y]
		if num-i <= 0 {
			return false
		}

		res *= num - i
		res %= p

		y++
	}

	return res > 0
}

// Max returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Max(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

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

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

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		res = append(res, []rune(str)...)

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

	return string(res)
}

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

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

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

	return string(res)
}

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

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

/*
URL:
https://codeforces.com/contest/1371/problem/E1
*/

package main

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

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

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

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

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

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

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

const (
	// General purpose
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPHABET_NUM = 26
	INF_INT64    = math.MaxInt64
	INF_BIT60    = 1 << 60
	INF_INT32    = math.MaxInt32
	INF_BIT30    = 1 << 30
	NIL          = -1

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

func init() {
	// bufio.ScanWords <---> bufio.ScanLines
	ReadString = newReadString(os.Stdin, bufio.ScanWords)
	stdout = bufio.NewWriter(os.Stdout)
}

var (
	n, p int
	A    []int

	cnts [100000 + 50]int
	pref [100000 + 50]int
)

func main() {
	n, p = ReadInt2()
	A = ReadIntSlice(n)

	solve()
}

func solve() {
	answers := []int{}

	sort.Sort(sort.IntSlice(A))

	for i := 0; i < n; i++ {
		cnts[A[i]]++
	}
	for i := 1; i <= 2000; i++ {
		pref[i] = pref[i-1] + cnts[i]
	}
	// PrintfDebug("cnts: %v\n", cnts[:10])
	// PrintfDebug("pref: %v\n", pref[:10])

	ma := Max(A...)
	for x := Max(ma-n+1, 0); x <= ma; x++ {
		if isOK(x) {
			answers = append(answers, x)
		}
	}

	fmt.Println(len(answers))
	fmt.Println(PrintIntsLine(answers...))
}

func isOK(y int) bool {
	res := 1

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

		num := pref[y]
		if num-i <= 0 {
			return false
		}

		res *= num - i
		res %= p

		y++
	}

	return res > 0
}

// Max returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Max(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

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

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

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		res = append(res, []rune(str)...)

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

	return string(res)
}

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

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

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

	return string(res)
}

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

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


You are given an undirected connected weighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges. Let's denote the length of the shortest path from vertex $$$1$$$ to vertex $$$i$$$ as $$$d_i$$$. You have to erase some edges of the graph so that at most $$$k$$$ edges remain. Let's call a vertex $$$i$$$ good if there still exists a path from $$$1$$$ to $$$i$$$ with length $$$d_i$$$ after erasing the edges.Your goal is to erase the edges in such a way that the number of good vertices is maximized.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 3 \cdot 10^5$$$, $$$1 \le m \le 3 \cdot 10^5$$$, $$$n - 1 \le m$$$, $$$0 \le k \le m$$$) — the number of vertices and edges in the graph, and the maximum number of edges that can be retained in the graph, respectively. Then $$$m$$$ lines follow, each containing three integers $$$x$$$, $$$y$$$, $$$w$$$ ($$$1 \le x, y \le n$$$, $$$x \ne y$$$, $$$1 \le w \le 10^9$$$), denoting an edge connecting vertices $$$x$$$ and $$$y$$$ and having weight $$$w$$$. The given graph is connected (any vertex can be reached from any other vertex) and simple (there are no self-loops, and for each unordered pair of vertices there exists at most one edge connecting these vertices).

In the first line print $$$e$$$ — the number of edges that should remain in the graph ($$$0 \le e \le k$$$). In the second line print $$$e$$$ distinct integers from $$$1$$$ to $$$m$$$ — the indices of edges that should remain in the graph. Edges are numbered in the same order they are given in the input. The number of good vertices should be as large as possible.

package main

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

// github.com/EndlessCheng/codeforces-go
type pr struct {
	v int
	d int64
}
type hp []pr

func (h hp) Len() int              { return len(h) }
func (h hp) Less(i, j int) bool    { return h[i].d < h[j].d }
func (h hp) Swap(i, j int)         { h[i], h[j] = h[j], h[i] }
func (h *hp) Push(v interface{})   { *h = append(*h, v.(pr)) }
func (h *hp) Pop() (v interface{}) { a := *h; *h, v = a[:len(a)-1], a[len(a)-1]; return }
func (h *hp) push(v pr)            { heap.Push(h, v) }
func (h *hp) pop() pr              { return heap.Pop(h).(pr) }

func CF1076D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var n, m, up, v, w, wt int
	Fscan(in, &n, &m, &up)
	type neighbor struct{ to, wt, i int }
	g := make([][]neighbor, n)
	for i := 1; i <= m; i++ {
		Fscan(in, &v, &w, &wt)
		v--
		w--
		g[v] = append(g[v], neighbor{w, wt, i})
		g[w] = append(g[w], neighbor{v, wt, i})
	}

	type pair struct{ f, i int }
	fa := make([]pair, n)
	const inf int64 = 1e18
	dist := make([]int64, n)
	for i := range dist {
		dist[i] = inf
	}
	dist[0] = 0
	q := hp{{}}
	for len(q) > 0 {
		p := q.pop()
		v := p.v
		if dist[v] < p.d {
			continue
		}
		for _, e := range g[v] {
			w := e.to
			if newD := dist[v] + int64(e.wt); newD < dist[w] {
				dist[w] = newD
				fa[w] = pair{v, e.i}
				q.push(pr{w, newD})
			}
		}
	}

	deg := make([]int, n)
	for _, p := range fa {
		deg[p.f]++
	}
	ans := []interface{}{}
	q2 := []int{}
	for i, d := range deg {
		if d == 0 {
			q2 = append(q2, i)
		}
	}
	for len(q2) > 0 {
		p := fa[q2[0]]
		q2 = q2[1:]
		ans = append(ans, p.i)
		if p.f == 0 {
			continue
		}
		w := p.f
		if deg[w]--; deg[w] == 0 {
			q2 = append(q2, w)
		}
	}
	if len(ans) > up {
		ans = ans[len(ans)-up:]
	}
	Fprintln(out, len(ans))
	Fprintln(out, ans...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
type pr struct {
	v int
	d int64
}
type hp []pr

func (h hp) Len() int              { return len(h) }
func (h hp) Less(i, j int) bool    { return h[i].d < h[j].d }
func (h hp) Swap(i, j int)         { h[i], h[j] = h[j], h[i] }
func (h *hp) Push(v interface{})   { *h = append(*h, v.(pr)) }
func (h *hp) Pop() (v interface{}) { a := *h; *h, v = a[:len(a)-1], a[len(a)-1]; return }
func (h *hp) push(v pr)            { heap.Push(h, v) }
func (h *hp) pop() pr              { return heap.Pop(h).(pr) }

func CF1076D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var n, m, up, v, w, wt int
	Fscan(in, &n, &m, &up)
	type neighbor struct{ to, wt, i int }
	g := make([][]neighbor, n)
	for i := 1; i <= m; i++ {
		Fscan(in, &v, &w, &wt)
		v--
		w--
		g[v] = append(g[v], neighbor{w, wt, i})
		g[w] = append(g[w], neighbor{v, wt, i})
	}

	type pair struct{ f, i int }
	fa := make([]pair, n)
	const inf int64 = 1e18
	dist := make([]int64, n)
	for i := range dist {
		dist[i] = inf
	}
	dist[0] = 0
	q := hp{{}}
	for len(q) > 0 {
		p := q.pop()
		v := p.v
		if dist[v] < p.d {
			continue
		}
		for _, e := range g[v] {
			w := e.to
			if newD := dist[v] + int64(e.wt); newD < dist[w] {
				dist[w] = newD
				fa[w] = pair{v, e.i}
				q.push(pr{w, newD})
			}
		}
	}

	deg := make([]int, n)
	for _, p := range fa {
		if p.f > 0 {
			deg[p.f]++
		}
	}
	ans := []interface{}{}
	q2 := []int{}
	for i, d := range deg {
		if d == 0 {
			q2 = append(q2, i)
		}
	}
	for len(q2) > 0 {
		p := fa[q2[0]]
		q2 = q2[1:]
		ans = append(ans, p.i)
		if p.f == 0 {
			continue
		}
		w := p.f
		if deg[w]--; deg[w] == 0 {
			q2 = append(q2, w)
		}
	}
	if len(ans) > up {
		ans = ans[len(ans)-up:]
	}
	Fprintln(out, len(ans))
	Fprintln(out, ans...)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
type pr struct {
	v int
	d int64
}
type hp []pr

func (h hp) Len() int              { return len(h) }
func (h hp) Less(i, j int) bool    { return h[i].d < h[j].d }
func (h hp) Swap(i, j int)         { h[i], h[j] = h[j], h[i] }
func (h *hp) Push(v interface{})   { *h = append(*h, v.(pr)) }
func (h *hp) Pop() (v interface{}) { a := *h; *h, v = a[:len(a)-1], a[len(a)-1]; return }
func (h *hp) push(v pr)            { heap.Push(h, v) }
func (h *hp) pop() pr              { return heap.Pop(h).(pr) }

func CF1076D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var n, m, up, v, w, wt int
	Fscan(in, &n, &m, &up)
	type neighbor struct{ to, wt, i int }
	g := make([][]neighbor, n)
	for i := 1; i <= m; i++ {
		Fscan(in, &v, &w, &wt)
		v--
		w--
		g[v] = append(g[v], neighbor{w, wt, i})
		g[w] = append(g[w], neighbor{v, wt, i})
	}

	type pair struct{ f, i int }
	fa := make([]pair, n)
	deg := make([]int, n)
	const inf int64 = 1e18
	dist := make([]int64, n)
	for i := range dist {
		dist[i] = inf
	}
	dist[0] = 0
	q := hp{{}}
	for len(q) > 0 {
		p := q.pop()
		v := p.v
		if dist[v] < p.d {
			continue
		}
		for _, e := range g[v] {
			w := e.to
			if newD := dist[v] + int64(e.wt); newD < dist[w] {
				dist[w] = newD
				fa[w] = pair{v, e.i}
				deg[v]++
				q.push(pr{w, newD})
			}
		}
	}

	ans := []interface{}{}
	q2 := []int{}
	for i, d := range deg {
		if d == 0 {
			q2 = append(q2, i)
		}
	}
	for len(q2) > 0 {
		p := fa[q2[0]]
		q2 = q2[1:]
		ans = append(ans, p.i)
		if p.f == 0 {
			continue
		}
		w := p.f
		if deg[w]--; deg[w] == 0 {
			q2 = append(q2, w)
		}
	}
	if len(ans) > up {
		ans = ans[len(ans)-up:]
	}
	Fprintln(out, len(ans))
	Fprintln(out, ans...)
}

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


Все готовятся к VK Fest 2021! Для того, чтобы зрителям была лучше видна главная сцена, планируется построить амфитеатр. В этой задаче мы будем рассматривать его сбоку — схематично он будет иметь форму лестницы из $$$n$$$ одинаковых квадратов. Лестница — это одна или более башен квадратов, выстроенных в ряд, где высоты башен невозрастают слева направо.На следующем рисунке можно видеть три разные фигуры из $$$12$$$ квадратов. Первые две фигуры — лестницы, а третья — нет.  Из эстетических соображений было решено, что амфитеатр должен быть симметричным. Формально, амфитеатр называется симметричным, если при отражении его схемы относительно прямой $$$x = y$$$ получается тот же самый рисунок (где ось $$$x$$$ направлена слева направо, а ось $$$y$$$ — снизу вверх). Например, первая лестница на рисунке выше — симметричная, а вторая — нет.  Кроме того, амфитеатр должен быть максимально компактным — а именно, сторона минимального квадрата, внутрь которого можно его поместить, должна быть как можно меньше.По заданному числу $$$n$$$ нарисуйте схему амфитеатра из ровно $$$n$$$ квадратов, удовлетворяющую всем условиям.

В единственной строке задано одно целое число $$$n$$$ ($$$1 \le n \le 100$$$) — число квадратов, из которых нужно составить схему амфитеатра.

Если не существует схемы амфитеатра из $$$n$$$ квадратов, выведите единственное число $$$-1$$$. Иначе в первой строке выведите целое число $$$m$$$ — минимальное возможное число строк и столбцов в схеме амфитеатра. Далее выведите $$$m$$$ строк, описывающих схему. Каждая строка должна содержать ровно $$$m$$$ символов 'o' (строчная латинская буква) или '.', где 'o' описывает построенный квадрат, а '.' — пустое место. Схема амфитеатра должна состоять ровно из $$$n$$$ символов 'o'. Ячейка в левом нижнем углу должна содержать квадрат. Если возможных ответов с минимальным $$$m$$$ несколько, выведите любой из них.

package main

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

type IO struct {
	in  io.Reader
	out io.Writer
}

func NewIO(in io.Reader, out io.Writer) *IO {
	return &IO{in: bufio.NewReader(in), out: bufio.NewWriter(out)}
}

func (io *IO) ReadInt64() int64 {
	var res int64
	fmt.Fscanf(io.in, "%d\n", &res)
	return res
}

func (io *IO) ReadInt() int {
	var res int
	fmt.Fscanf(io.in, "%d\n", &res)
	return res
}

func (io *IO) ReadPairInt64() (int64, int64) {
	var a, b int64
	fmt.Fscanf(io.in, "%d %d\n", &a, &b)
	return a, b
}

func (io *IO) ReadPairInt() (int, int) {
	var a, b int
	fmt.Fscanf(io.in, "%d %d\n", &a, &b)
	return a, b
}

func (io *IO) ReadString() string {
	var res string
	fmt.Fscanf(io.in, "%s\n", &res)
	return res
}

func (io *IO) ReadIntSlice(n int) []int64 {
	var t int64
	res := make([]int64, 0, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(io.in, "%d", &t)
		res = append(res, t)
	}
	fmt.Fscanf(io.in, "\n")
	return res
}

type pair struct{a, b int}

func main() {
	io := NewIO(os.Stdin, os.Stdout)

	n := io.ReadInt()

	if n == 2 {
		fmt.Println(-1)
		return
	}

	size := int(math.Ceil(math.Sqrt(float64(n))))
	toDelete := size * size - n
	deleteFrom := size - (toDelete + 1) / 2

	if toDelete == 2 {
		size++
		toDelete = size * size - n - 4
		deleteFrom = size - (toDelete + 1) / 2

		fmt.Println(size)

		for i := 0; i < size; i++ {
			for j := 0; j < size; j++ {
				if i == 0 && j >= deleteFrom || j == size - 1 && i < size - deleteFrom {
					fmt.Printf(".")
				} else if i == 1 && j >= size - 3 || i == 2 && j >= size - 3 {
					fmt.Printf(".")
				} else {
					fmt.Printf("o")
				}
			}
			fmt.Printf("\n")
		}

		return
	}

	fmt.Println(size)

	for i := 0; i < size; i++ {
		for j := 0; j < size; j++ {
			if i == 0 && j >= deleteFrom || j == size - 1 && i < size - deleteFrom {
				fmt.Printf(".")
			} else if i == 1 && j == size - 2 && (toDelete != 0 && toDelete % 2 == 0) {
				fmt.Printf(".")
			} else {
				fmt.Printf("o")
			}
		}
		fmt.Printf("\n")
	}
}

package main

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

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

	var n int

	fmt.Fscan(r, &n)

	/*for n := 1; n <= 100; n++ {
		fmt.Println(n)
		solve(n)
	}*/

	solve(n)
}

func solve(n int) {
	if n == 1 {
		fmt.Println(1)
		fmt.Println("o")
		return
	}
	if n == 2 {
		fmt.Println(-1)
		return
	}

	can := make(map[int]bool)
	can[2] = false
	can[1] = true

	grids := make(map[int][][]int)
	grids[1] = [][]int{{1}}

	for k := 1; k <= 100; k++ {

		yes := false

		for i := 1; i <= 11; i++ {
			sqr := i * i
			if sqr >= k {
				d := i + i - 1

				if d > k {
					break
				}

				grid := make([][]int, i)
				for j := 0; j < i; j++ {
					grid[j] = make([]int, i)
				}

				diff := k - d
				if diff == 0 {
					can[k] = true

					for j := 0; j < i; j++ {
						grid[j][0] = 1
					}
					for j := 0; j < i; j++ {
						grid[i - 1][j] = 1
					}

					grids[k] = grid
					yes = true
					break

				} else {
					if can[diff] {
						gr := grids[diff]

						if len(gr) > len(grid) - 1 {
							continue
						}

						can[k] = true

						for j := 0; j < i; j++ {
							grid[j][0] = 1
						}
						for j := 0; j < i; j++ {
							grid[i - 1][j] = 1
						}

						r := i - 2

						for  j := len(gr) - 1; j >= 0; j-- {
							c := 1

							for k := 0; k < len(gr); k++ {
								if gr[j][k] == 1 {
									grid[r][c] = 1
								}

								c++
							}
							r--
						}

						grids[k] = grid
						yes = true
						break

					} else {
						continue
					}
				}
			}
		}

		if !yes {
			can[k] = false
		}
	}

	if can[n] {
		g := grids[n]

		fmt.Println(len(g))

		for j := 0; j < len(g); j++ {
			for k := 0; k < len(g); k++ {
				if g[j][k] == 1 {
					fmt.Print("o")
				} else {
					fmt.Print(".")
				}
			}
			fmt.Println()
		}

	} else {
		fmt.Println(-1)
	}
}

package main

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

type IO struct {
	in  io.Reader
	out io.Writer
}

func NewIO(in io.Reader, out io.Writer) *IO {
	return &IO{in: bufio.NewReader(in), out: bufio.NewWriter(out)}
}

func (io *IO) ReadInt64() int64 {
	var res int64
	fmt.Fscanf(io.in, "%d\n", &res)
	return res
}

func (io *IO) ReadInt() int {
	var res int
	fmt.Fscanf(io.in, "%d\n", &res)
	return res
}

func (io *IO) ReadPairInt64() (int64, int64) {
	var a, b int64
	fmt.Fscanf(io.in, "%d %d\n", &a, &b)
	return a, b
}

func (io *IO) ReadPairInt() (int, int) {
	var a, b int
	fmt.Fscanf(io.in, "%d %d\n", &a, &b)
	return a, b
}

func (io *IO) ReadString() string {
	var res string
	fmt.Fscanf(io.in, "%s\n", &res)
	return res
}

func (io *IO) ReadIntSlice(n int) []int64 {
	var t int64
	res := make([]int64, 0, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(io.in, "%d", &t)
		res = append(res, t)
	}
	fmt.Fscanf(io.in, "\n")
	return res
}

type pair struct{a, b int}

func main() {
	io := NewIO(os.Stdin, os.Stdout)

	n := io.ReadInt()
	size := int(math.Ceil(math.Sqrt(float64(n))))
	toDelete := size * size - n
	deleteFrom := size - (toDelete + 1) / 2

	if toDelete == 2 {
		fmt.Println(-1)
		return
	}

	fmt.Println(size)

	for i := 0; i < size; i++ {
		for j := 0; j < size; j++ {
			if i == 0 && j >= deleteFrom || j == size - 1 && i < size - deleteFrom {
				fmt.Printf(".")
			} else if i == 1 && j == size - 2 && (toDelete != 0 && toDelete % 2 == 0) {
				fmt.Printf(".")
			} else {
				fmt.Printf("o")
			}
		}
		fmt.Printf("\n")
	}
}

package main

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

type IO struct {
	in  io.Reader
	out io.Writer
}

func NewIO(in io.Reader, out io.Writer) *IO {
	return &IO{in: bufio.NewReader(in), out: bufio.NewWriter(out)}
}

func (io *IO) ReadInt64() int64 {
	var res int64
	fmt.Fscanf(io.in, "%d\n", &res)
	return res
}

func (io *IO) ReadInt() int {
	var res int
	fmt.Fscanf(io.in, "%d\n", &res)
	return res
}

func (io *IO) ReadPairInt64() (int64, int64) {
	var a, b int64
	fmt.Fscanf(io.in, "%d %d\n", &a, &b)
	return a, b
}

func (io *IO) ReadPairInt() (int, int) {
	var a, b int
	fmt.Fscanf(io.in, "%d %d\n", &a, &b)
	return a, b
}

func (io *IO) ReadString() string {
	var res string
	fmt.Fscanf(io.in, "%s\n", &res)
	return res
}

func (io *IO) ReadIntSlice(n int) []int64 {
	var t int64
	res := make([]int64, 0, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(io.in, "%d", &t)
		res = append(res, t)
	}
	fmt.Fscanf(io.in, "\n")
	return res
}

type pair struct{a, b int}

func main() {
	io := NewIO(os.Stdin, os.Stdout)

	n := io.ReadInt()
	size := int(math.Ceil(math.Sqrt(float64(n))))
	toDelete := size * size - n
	deleteFrom := size - (toDelete + 1) / 2

	if toDelete == 2 {
		fmt.Println(-1)
		return
	}

	fmt.Println(size)

	for i := 0; i < size; i++ {
		for j := 0; j < size; j++ {
			if i == 0 && j >= deleteFrom || j == size - 1 && i < size - deleteFrom {
				fmt.Printf(".")
			} else if i == 1 && j == size - 2 && toDelete % 2 == 0 {
				fmt.Printf(".")
			} else {
				fmt.Printf("o")
			}
		}
		fmt.Printf("\n")
	}
}

package main

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

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

	var n int

	fmt.Fscan(r, &n)

	if n == 1 {
		fmt.Println(1)
		fmt.Println("o")
		return
	}
	if n == 2 {
		fmt.Println(-1)
		return
	}

	can := make(map[int]bool)
	can[2] = false
	can[1] = true

	grids := make(map[int][][]int)
	grids[1] = [][]int{{1}}

	for k := 1; k <= 100; k++ {

		yes := false

		for i := 1; i <= 10; i++ {
			sqr := i * i
			if sqr >= k {
				d := i + i - 1

				if d > k {
					break
				}

				grid := make([][]int, i)
				for j := 0; j < i; j++ {
					grid[j] = make([]int, i)
				}

				diff := k - d
				if diff == 0 {
					can[k] = true

					for j := 0; j < i; j++ {
						grid[j][0] = 1
					}
					for j := 0; j < i; j++ {
						grid[i - 1][j] = 1
					}

					grids[k] = grid
					yes = true
					break

				} else {
					if can[diff] {
						gr := grids[diff]

						if len(gr) > len(grid) - 1 {
							continue
						}

						can[k] = true

						for j := 0; j < i; j++ {
							grid[j][0] = 1
						}
						for j := 0; j < i; j++ {
							grid[i - 1][j] = 1
						}

						r := i - 2

						for  j := len(gr) - 1; j >= 0; j-- {
							c := 1

							for k := 0; k < len(gr); k++ {
								if gr[j][k] == 1 {
									grid[r][c] = 1
								}

								c++
							}
							r--
						}

						grids[k] = grid
						yes = true
						break

					} else {
						continue
					}
				}
			}
		}

		if !yes {
			can[k] = false
		}
	}

	if can[n] {
		g := grids[n]
		fmt.Println(len(g))

		for j := 0; j < len(g); j++ {
			for k := 0; k < len(g); k++ {
				if g[j][k] == 1 {
					fmt.Print("o")
				} else {
					fmt.Print(".")
				}
			}
			fmt.Println()
		}

	} else {
		fmt.Println(-1)
	}
}


You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).

The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters.

Print "YES" (without the quotes), if string s contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise.

NoteIn the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO".In the second sample test there are the following occurrences of the substrings: BACFAB.In the third sample test there is no substring "AB" nor substring "BA".

package main

import (
	"fmt"
)

func old_solution() {
	var word []byte
	fmt.Scan(&word)

	ab := make([]int, 0)
	ba := make([]int, 0)

	for i := 0; i < len(word); i++ {
		if word[i] == 'B' && i < len(word) - 1 && word[i+1] == 'A' {
			ba = append(ba, i)
		}
		if word[i] == 'A' && i < len(word) - 1 && word[i+1] == 'B' {
			ab = append(ab, i)
		}
	}

	for _, ab_i := range ab {
		for _, ba_i := range ba {
			if (ab_i ^ ba_i) != 1 {
				fmt.Println("YES")
				return
			}
		}
	}
	fmt.Println("NO")
}

func findInWord(s []byte, x byte, y byte) bool {
	firstFound := false

	for i := 0; i < len(s) - 1; i++ {
		if !firstFound {
			if s[i] == x && s[i+1] == y {
				firstFound = true
				i++
			}
		} else {
			if s[i] == y && s[i+1] == x {
				return true
			}
		}
	}
	return false
}

func main() {
	var word []byte
	fmt.Scan(&word)

	if findInWord(word, 'A', 'B') || findInWord(word, 'B', 'A') {
		fmt.Println("YES")
		return
	}

	fmt.Println("NO")
}

package main

import (
	"fmt"
)

func main() {
	var word []byte
	fmt.Scan(&word)

	ab := make([]int, 0)
	ba := make([]int, 0)

	for i := 0; i < len(word) - 1; i++ {
		if word[i] == 'B' && word[i+1] == 'A' {
			ba = append(ba, i)
		}
		if word[i] == 'A' && word[i+1] == 'B' {
			ab = append(ab, i)
		}
	}

	for _, ab_i := range ab {
		for _, ba_i := range ba {
			// If ab_i and ba_i are consecutive
			if ((ab_i - ba_i) + 1) & -3 != 0 {
				fmt.Println("YES")
				return
			}
		}
	}
	fmt.Println("NO")
}

func findInWord(s []byte, x byte, y byte) bool {
	firstFound := false

	for i := 0; i < len(s) - 1; i++ {
		if !firstFound {
			if s[i] == x && s[i+1] == y {
				firstFound = true
				i++
			}
		} else {
			if s[i] == y && s[i+1] == x {
				return true
			}
		}
	}
	return false
}

func next_solution() {
	var word []byte
	fmt.Scan(&word)

	if findInWord(word, 'A', 'B') || findInWord(word, 'B', 'A') {
		fmt.Println("YES")
		return
	}

	fmt.Println("NO")
}

package main

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

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

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

	var s string
	scan(&s)
	n := len(s)
	checked := make([]bool, n+2)
	cntAB := 0

	for i := 0; i < n-1; i++ {
		if s[i:i+2] == "AB" {
			checked[i+1] = true
			cntAB++
		}
	}

	for i := 0; i < n-1; i++ {
		if s[i:i+2] == "BA" {
			ok := false

			if !checked[i] && !checked[i+2] && cntAB > 0 {
				ok = true
			} else if (!checked[i] || !checked[i+2]) && cntAB > 1 {
				ok = true
			} else if checked[i] && checked[i+2] && cntAB > 2 {
				ok = true
			}

			if ok {
				println("YES")
				return
			}
		}
	}

	println("NO")
}

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"
	"math"
	"os"
	"strings"
)

func main() {
	r := bufio.NewReader(os.Stdin)
	s, _ := r.ReadString('\n')
	i := strings.Index(s, "BA")
	j := strings.Index(s, "AB")
	k := strings.LastIndex(s, "AB")
	l := strings.LastIndex(s, "BA")
	if i == -1 || j == -1 || k == -1 || l == -1 {
		fmt.Println("NO")
		return
	}
	if math.Abs(float64(i-k)) >= 2 || math.Abs(float64((j-l))) >= 2 {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

package main

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

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

  line, _ := reader.ReadString('\n')
  s := strings.TrimSpace(line)
  matched, _ := regexp.MatchString("AB.*BA|BA.*AB", s)
  result := "NO"
  if matched {
    result = "YES"
  }
  writer.WriteString(fmt.Sprintf("%s\n", result))
}

// http://codeforces.com/problemset/problem/550/A
package main

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

func main () {
	var (
		str string
	)

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)

	fmt.Fscanln(input, &str)

	ab, ba := -1, -1

	for i := 0; i < len(str) - 1; i++ {
		if ab < 0 && str[i:i + 2] == "AB" {
			ab = i
		}

		if ba < 0 && str[i:i + 2] == "BA" {
			ba = i
		}

		if ba >= 0 && (ba < i - 1 || ba > i + 1) && str[i:i + 2] == "AB" {
			fmt.Println("YES")
			return
		}

		if  ab >= 0 && (ab < i - 1 || ab > i + 1) && str[i:i + 2] == "BA" {
			fmt.Println("YES")
			return
		}
	}

	fmt.Println("NO")
}

package main

import (
	"fmt"
	"os"
	"regexp"
)

var (
	abbaReg = regexp.MustCompile(`[A-Z]{0,}AB[A-Z]{0,}BA[A-Z]{0,}`)
	baabReg = regexp.MustCompile(`[A-Z]{0,}BA[A-Z]{0,}AB[A-Z]{0,}`)
)

func main() {
	var ss string
	fmt.Fscanf(os.Stdin, "%s\n", &ss)
	if abbaReg.MatchString(ss) || baabReg.MatchString(ss) {
		fmt.Println("YES")
		return
	}
	fmt.Println("NO")
}

package main

import "fmt"

func main() {
	s:=""
	ab,ba := false, false
	fmt.Scanf("%s",&s)
	for i:=0; i<len(s)-1;i++ {
		if ab && ba {
			break
		}
		if i >= len(s)-1 {
			break
		}
		if ab == false && s[i] == 'A' && s[i+1] == 'B' {
			ab = true
			i++
		} else if ba == false && s[i] == 'B' && s[i+1] == 'A' {
			ba = true
			i++
		}
	}

	if ! (ab && ba)  {
		ab,ba = false, false
		for i:=len(s)-1; i>0;i-- {
			if ab && ba {
				break
			}
			if i <= 0 {
				break
			}
			if ab == false && s[i-1] == 'A' && s[i] == 'B' {
				ab = true
				i--
			} else if ba == false && s[i-1] == 'B' && s[i] == 'A' {
				ba = true
				i--
			}
		}
	}

	if ab && ba {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

package main

import (
            "fmt"
        )

func main() {
    var s string
    fmt.Scanln(&s)

    var result bool = false

    var wAB, wBA []int
    var last string = string(s[0])
    for i := 1; i < len(s); i++ {
        var char string = string(s[i])
        if char == "B" && last == "A" {
            wAB = append(wAB, i)
        }

        if char == "A" && last == "B" {
            wBA = append(wBA, i)
        }

        last = char
    }

    for i := 0; i < len(wAB); i++ {
        if result {
            break
        }

        for j := 0; j < len(wBA); j++ {
            var diff int = wAB[i] - wBA[j]
            if diff < -1 || diff > 1 {
                result = true
                break
            }
        }
    }

    var answer string = "NO"
    if result {
        answer = "YES"
    }

    fmt.Println(answer)
}

package main

import (
	"fmt"
	"strings"
)

func main() {
	var s string
	fmt.Scan(&s)
	var iAB, iBA []int
	for i := 0; i < len(s); i++ {
		if strings.HasPrefix(s[i:], "AB") {
			iAB = append(iAB, i)
		}
		if strings.HasPrefix(s[i:], "BA") {
			iBA = append(iBA, i)
		}
	}
	for i := 0; i < len(iAB); i++ {
		for j := 0; j < len(iBA); j++ {
			if iAB[i]-iBA[j] >= 2 || iBA[j]-iAB[i] >= 2 {
				fmt.Println("YES")
				return
			}
		}
	}
	fmt.Println("NO")
}

package main
import (
  "fmt"
  "strings"
)

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

func main() {
  var s string
  fmt.Scanf("%s", &s)
  if (strings.Contains(s, "AB") && strings.Contains(s, "BA")) {
    if (abs(strings.LastIndex(s, "AB") - strings.Index(s, "BA")) > 1 || abs(strings.LastIndex(s, "BA") - strings.Index(s, "AB")) > 1) {
      fmt.Println("YES")
    } else {
      fmt.Println("NO")
    }
  } else {
    fmt.Println("NO")
  }
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF550A(r io.Reader, w io.Writer) {
	var s string
	Fscan(r, &s)
	l1, l2, r1, r2 := Index(s, "AB"), Index(s, "BA"), LastIndex(s, "AB"), LastIndex(s, "BA")
	if l1 != -1 && l1+1 < r2 || l2 != -1 && l2+1 < r1 {
		Fprint(w, "YES")
	} else {
		Fprint(w, "NO")
	}
}

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

package main

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

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

	// read string
	var s string
	fmt.Fscanf(inp, "%s", &s)

	// solve
	minA, maxA := -1, -1
	minB, maxB := -1, -1
	for i := 0; i < len(s)-1; i++ {
		if s[i] == 'A' && s[i+1] == 'B' {
			if minA == -1 {
				minA = i
			}
			maxA = i
		}
		if s[i] == 'B' && s[i+1] == 'A' {
			if minB == -1 {
				minB = i
			}
			maxB = i
		}
	}

	// write output
	if minA == -1 || minB == -1 {
		fmt.Println("NO")
	} else if diffAbs(minA, maxB) > 1 || diffAbs(minB, maxA) > 1 {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

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

package main

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

func Readln(r *bufio.Reader) (string, error) {
	var (
		isPrefix bool  = true
		err      error = nil
		line, ln []byte
	)
	for isPrefix && err == nil {
		line, isPrefix, err = r.ReadLine()
		ln = append(ln, line...)
	}
	return string(ln), err
}

func main() {

	reader := bufio.NewReader(os.Stdin)
	line, _ := Readln(reader)

	if Contains2(line, "AB", "BA") ||
		Contains2(line, "BA", "AB") {
		fmt.Println("YES")
		return
	}

	fmt.Println("NO")
}

func Contains2(str string, subStr1 string, subStr2 string) bool {
	if idx := strings.Index(str, subStr1); idx != -1 {
		if idx2 := strings.Index(str[idx + 2:], subStr2); idx2 != -1 {
			return true
		}
	}

	return false
}

package main

import (
	"fmt"
)

func main() {
	var str string
	fmt.Scanf("%s\n", &str)
	var abixs, baixs []int
	bstr := []byte(str)
	l := len(bstr)
	for ix, b := range bstr {
		if b == 'A' && ix+1 < l && bstr[ix+1] == 'B' {
			abixs = append(abixs, ix)
		}
		if b == 'B' && ix+1 < l && bstr[ix+1] == 'A' {
			baixs = append(baixs, ix)
		}
	}
	flag := false
	for _, ab := range abixs {
		for _, ba := range baixs {
			v := ab - ba
			if v > 1 || v < (-1) {
				flag = true
				break
			}
		}
		if flag {
			fmt.Println("YES")
			return
		}
	}
	fmt.Println("NO")
}

package main

import (
	"fmt"
)

func main() {
	var word []byte
	fmt.Scan(&word)

	ab := make([]int, 0)
	ba := make([]int, 0)

	for i := 0; i < len(word) - 1; i++ {
		if word[i] == 'B' && word[i+1] == 'A' {
			ba = append(ba, i)
		}
		if word[i] == 'A' && word[i+1] == 'B' {
			ab = append(ab, i)
		}
	}

	for _, ab_i := range ab {
		for _, ba_i := range ba {
			if (ab_i ^ ba_i) != 1 {
				fmt.Println("YES")
				return
			}
		}
	}
	fmt.Println("NO")
}

func findInWord(s []byte, x byte, y byte) bool {
	firstFound := false

	for i := 0; i < len(s) - 1; i++ {
		if !firstFound {
			if s[i] == x && s[i+1] == y {
				firstFound = true
				i++
			}
		} else {
			if s[i] == y && s[i+1] == x {
				return true
			}
		}
	}
	return false
}

func next_solution() {
	var word []byte
	fmt.Scan(&word)

	if findInWord(word, 'A', 'B') || findInWord(word, 'B', 'A') {
		fmt.Println("YES")
		return
	}

	fmt.Println("NO")
}

package main

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

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

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

	var s string
	scan(&s)
	n := len(s)
	checked := make([]bool, n)

	for i := 0; i < n-1; i++ {
		if s[i:i+2] == "AB" {
			checked[i] = true
		}
	}

	for i := 0; i < n-1; i++ {
		if s[i:i+2] == "BA" {
			if (i > 0 && checked[i-1]) || checked[i+1] {
				continue
			}

			println("YES")
			return
		}
	}

	println("NO")
}

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"
	"math"
	"os"
	"strings"
)

func main() {
	r := bufio.NewReader(os.Stdin)
	s, _ := r.ReadString('\n')
	i := strings.Index(s, "BA")
	j := strings.Index(s, "AB")
	k := strings.LastIndex(s, "AB")
	l := strings.LastIndex(s, "BA")
	if i == -1 || j == -1 || k == -1 || l == -1 {
		fmt.Println("NO")
		return
	}
	fmt.Println(i, j, k, l)
	if math.Abs(float64(i-k)) >= 2 || math.Abs(float64((j-l))) >= 2 {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

package main

import (
	"fmt"
	"os"
)

func main() {
	var ss string
	fmt.Fscanf(os.Stdin, "%s\n", &ss)
	var hasAB, hasBA bool
	for i := 1; i < len(ss); i++ {
		if hasAB && hasBA {
			fmt.Println("YES")
			return
		}
		if !hasAB && ss[i-1] == 'A' && ss[i] == 'B' {
			hasAB = true
			i++
			continue
		}
		if !hasBA && ss[i-1] == 'B' && ss[i] == 'A' {
			hasBA = true
			i++
			continue
		}
	}
	fmt.Println("NO")
}

package main

import (
	"fmt"
	"os"
)

func main() {
	var ss string
	fmt.Fscanf(os.Stdin, "%s\n", &ss)
	var hasAB, hasBA bool
	for i := 1; i < len(ss); i++ {
		if !hasAB && ss[i-1] == 'A' && ss[i] == 'B' {
			hasAB = true
			i++
			continue
		}
		if !hasBA && ss[i-1] == 'B' && ss[i] == 'A' {
			hasBA = true
			i++
			continue
		}
	}
	if hasAB && hasBA {
		fmt.Println("YES")
		return
	}
	fmt.Println("NO")
}

package main

import (
	"fmt"
	"os"
	"regexp"
)

var (
	abbaReg = regexp.MustCompile(`.+AB.+BA.+`)
	baabReg = regexp.MustCompile(`.+BA.+AB.+`)
)

func main() {
	var ss string
	fmt.Fscanf(os.Stdin, "%s\n", &ss)
	if abbaReg.MatchString(ss) || baabReg.MatchString(ss) {
		fmt.Println("YES")
		return
	}
	fmt.Println("NO")
}

package main

import (
	"fmt"
	"os"
)

func main() {
	var ss string
	fmt.Fscanf(os.Stdin, "%s\n", &ss)
	var hasAB, hasBA bool
	for i := 1; i < len(ss); i++ {
		if ss[i-1] == 'A' && ss[i] == 'B' {
			hasAB = true
			i++
			continue
		}
		if ss[i-1] == 'B' && ss[i] == 'A' {
			hasBA = true
			i++
			continue
		}
	}
	if hasAB && hasBA {
		fmt.Println("YES")
		return
	}
	fmt.Println("NO")
}

package main

import "fmt"

func main() {
	s:=""
	ab,ba := false, false
	fmt.Scanf("%s",&s)
	for i:=0; i<len(s)-1;i++  {
		if ab && ba {break}
		if (i>=len(s)-1) {break}
		if ab==false && s[i]=='A'&& s[i+1]=='B' {
			ab=true
			i++
		} else if ba==false && s[i]=='B'&& s[i+1]=='A' {
				ba=true; i++
		}
	}
	if ab && ba {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

package main

import "fmt"

func main() {
	s:=""
	ab,ba := false, false
	fmt.Scanf("%s",&s)
	for i:=0; i<len(s)-1;i++  {
		if ab && ba {break}
		if (i>=len(s)-1) {break}
		if s[i]=='A'&& s[i+1]=='B' {
			ab=true
			i++
			} else if s[i]=='B'&& s[i+1]=='A' {
				ba=true; i++
				}
	}
	if ab && ba {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

package main

import "fmt"

func main() {
	s:=""
	ab,ba := false, false
	fmt.Scanf("%s",&s)
	for i:=0; i<len(s)-1;i++ {
		if ab && ba {
			break
		}
		if (i >= len(s)-1) {
			break
		}
		if ab == false && s[i] == 'A' && s[i+1] == 'B' {
			ab = true
			i++
		} else if ba == false && s[i] == 'B' && s[i+1] == 'A' {
			ba = true
			i++
		}
	}

	if ! (ab && ba)  {
		ab,ba = false, false
		for i:=len(s)-1; i>0;i-- {
			if ab && ba {
				break
			}
			if (i >= 0) {
				break
			}
			if ab == false && s[i-1] == 'A' && s[i] == 'B' {
				ab = true
				i--
			} else if ba == false && s[i-1] == 'B' && s[i] == 'A' {
				ba = true;
				i--
			}
		}
	}

	if ab && ba {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

package main

import "fmt"

func main() {
	var s string
	fmt.Scan(&s)
	var AB, BA bool
	for i := 0; i < len(s)-1; i++ {
		if i < len(s)-2 {
			if s[i:i+3] == "BAB" || s[i:i+3] == "ABA" {
				continue
			}
		}
		if s[i:i+2] == "AB" {
			AB = true
			continue
		}
		if s[i:i+2] == "BA" {
			BA = true
			continue
		}
	}
	if AB && BA {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

package main

import (
	"fmt"
	"strings"
)

func main() {
	var s string
	fmt.Scan(&s)
	var iAB, iBA []int
	for i := 0; i < len(s); i++ {
		if strings.HasPrefix(s[i:], "AB") {
			iAB = append(iAB, i)
		}
		if strings.HasPrefix(s[i:], "BA") {
			iBA = append(iBA, i)
		}
	}
	for i := 0; i < len(iAB); i++ {
		for j := 0; j < len(iBA); j++ {
			if iAB[i]+1 > iBA[j] || iAB[i]-1 < iBA[j] {
				fmt.Println("YES")
				return
			}
		}
	}
	fmt.Println("NO")
}

package main

import (
	"fmt"
	"strings"
)

func main() {
	var s string
	fmt.Scan(&s)
	var iAB, iBA []int
	for i := 0; i < len(s); i++ {
		if strings.HasPrefix(s[i:], "AB") {
			iAB = append(iAB, i)
		}
		if strings.HasPrefix(s[i:], "BA") {
			iBA = append(iBA, i)
		}
	}
	for i := 0; i < len(iAB); i++ {
		for j := 0; j < len(iBA); j++ {
			if iAB[i]+1 > iBA[j] || iAB[i]-1 > iBA[j] {
				fmt.Println("YES")
				return
			}
		}
	}
	fmt.Println("NO")
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF550A(r io.Reader, w io.Writer) {
	var s string
	Fscan(r, &s)
	l1, l2, r1, r2 := Index(s, "AB"), Index(s, "BA"), LastIndex(s, "AB"), Index(s, "BA")
	if l1 != -1 && l1+1 < r2 || l2 != -1 && l2+1 < r1 {
		Fprint(w, "YES")
	} else {
		Fprint(w, "NO")
	}
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF550A(r io.Reader, w io.Writer) {
	var s string
	Fscan(r, &s)
	l1, l2, r1, r2 := Index(s, "AB"), Index(s, "BA"), LastIndex(s, "AB"), Index(s, "BA")
	if l1+1 < r2 || l2+1 < r1 {
		Fprint(w, "YES")
	} else {
		Fprint(w, "NO")
	}
}

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

package main

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

func Readln(r *bufio.Reader) (string, error) {
	var (
		isPrefix bool  = true
		err      error = nil
		line, ln []byte
	)
	for isPrefix && err == nil {
		line, isPrefix, err = r.ReadLine()
		ln = append(ln, line...)
	}
	return string(ln), err
}

func main() {

	reader := bufio.NewReader(os.Stdin)
	line, _ := Readln(reader)

	separated := strings.Split(line, "AB")
	for _, subStr := range separated {
		if strings.Index(subStr, "BA") != -1 {
			fmt.Println("YES")
			return
		}
	}

	fmt.Println("NO")
}

package main

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

func Readln(r *bufio.Reader) (string, error) {
	var (
		isPrefix bool  = true
		err      error = nil
		line, ln []byte
	)
	for isPrefix && err == nil {
		line, isPrefix, err = r.ReadLine()
		ln = append(ln, line...)
	}
	return string(ln), err
}

func main() {

	reader := bufio.NewReader(os.Stdin)
	line, _ := Readln(reader)

	if Contains2(line, "AB", "BA") ||
		Contains2(line, "BA", "AB") {
		fmt.Println("YES")
		return
	}

	fmt.Println("NO")
}

func Contains2(str string, subStr1 string, subStr2 string) bool {
	if idx := strings.Index(str, subStr1); idx != -1 {
		if idx2 := strings.Index(str[idx + 1:], subStr2); idx2 != -1 {
			return true
		}
	}

	return false
}