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


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

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


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


package main

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

const (
    LOW = -123456789
)

func Init() {
}

func Solve(io *FastIO) {
    N := io.NextInt()
    M := io.NextInt()
    D := io.NextInt()
    P := io.NextIntArray(M)

    nodes := make([]*Node, N + 1)
    for i := 1; i <= N; i++ {
        nodes[i] = NewNode()
    }

    for _, u := range P {
        nodes[u].spooky = true
    }

    for i := 1; i < N; i++ {
        U := io.NextInt()
        V := io.NextInt()

        nodes[U].next[nodes[V]] = true
        nodes[V].next[nodes[U]] = true
    }

    Rootify(nodes[1], nil)
    ComputeBests(nodes[1])
    ComputeUps(nodes[1])

    ans := CountGood(nodes[1], D)
    io.Println(ans)
}

func Rootify(u, p *Node) {
    delete(u.next, p)
    for v := range u.next {
        Rootify(v, u)
    }
}

func ComputeBests(u *Node) {
    if u.spooky {
        u.down.Add(0)
    }
    for v := range u.next {
        ComputeBests(v)
        u.down.Add(1 + v.down.Best())
    }
}

func ComputeUps(u *Node) {
    for v := range u.next {
        u.down.Remove(1 + v.down.Best())
        v.up = 1 + Max(u.up, u.down.Best())
        u.down.Add(1 + v.down.Best())
        ComputeUps(v)
    }
}

func CountGood(u *Node, d int) int {
    cnt := 0
    if u.up <= d && u.down.Best() <= d {
        cnt++
    }
    for v := range u.next {
        cnt += CountGood(v, d)
    }
    return cnt
}

type Node struct {
    next map[*Node]bool
    spooky bool
    down *BestTwo
    up int
}

func NewNode() *Node {
    return &Node{
        next: make(map[*Node]bool),
        down: MakeBestTwo(),
        up: LOW,
    }
}

type BestTwo struct {
    best []int
}

func MakeBestTwo() *BestTwo {
    return &BestTwo{
        best: []int{LOW, LOW},
    }
}

func (this *BestTwo) Add(val int) {
    sort.Ints(this.best)
    this.best[0] = Max(this.best[0], val)
}

func (this *BestTwo) Remove(val int) {
    for i, v := range this.best {
        if val == v {
            this.best[i] = LOW
            return
        }
    }
}

func (this *BestTwo) Best() int {
    return Max(this.best...)
}

func Max(args ...int) int {
	max := args[0]
	for i := 1; i < len(args); i++ {
		if args[i] > max {
			max = args[i]
		}
	}
	return max
}

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

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

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

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

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

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

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

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

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

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

func (io *FastIO) Println(args ...interface{}) {
	io.writer.WriteString(fmt.Sprintln(args...))
}

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

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

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

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

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

package main

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

var in = bufio.NewScanner(os.Stdin)

func readInt() int {
	if !in.Scan() {
		panic(in.Err())
	}
	res := int(0)
	for _, b := range in.Bytes() {
		res = res*10 + int(b-'0')
	}
	return res
}

func main() {
	in.Split(bufio.ScanWords)
	n, m, d := readInt(), readInt(), readInt()
	p := make([]int, m)
	for i := range p {
		p[i] = readInt() - 1
	}
	edges := make([][]int, n)
	for i := 1; i < n; i++ {
		a, b := readInt()-1, readInt()-1
		edges[a] = append(edges[a], b)
		edges[b] = append(edges[b], a)
	}

	bfs := func(root int) []int {
		dist := make([]int, n)
		for i := range dist {
			dist[i] = -1
		}
		dist[root] = 0
		q := []int{root}
		for len(q) > 0 {
			v := q[0]
			q = q[1:]
			for _, u := range edges[v] {
				if dist[u] >= 0 {
					continue
				}
				dist[u] = dist[v] + 1
				q = append(q, u)
			}
		}
		return dist
	}
	dist := bfs(p[0])
	far := p[0]
	for i := range p {
		if dist[p[i]] > dist[far] {
			far = p[i]
		}
	}
	dist1 := bfs(far)

	far1 := p[0]
	for i := range p {
		if dist1[p[i]] > dist1[far1] {
			far1 = p[i]
		}
	}
	dist2 := bfs(far1)

	ans := 0
	for i := range dist {
		if dist1[i] <= d && dist2[i] <= d {
			ans++
		}
	}
	fmt.Println(ans)
}

//http://codeforces.com/problemset/problem/337/d
package main

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

var (
	graph [][]int
)

func initDist(d []int) {
	for i := range d {
		d[i] = int(1e9 + 7)
	}
}

func dfs(start int, d int, dist []int) {
	dist[start] = d

	for i := range graph[start] {
		if dist[graph[start][i]] > d+1 {
			dfs(graph[start][i], d+1, dist)
		}
	}
}

func findFurthestNode(isAffected map[int]bool, dist []int) int {
	max, maxID := 0, 0
	for i := range dist {
		if isAffected[i] && max < dist[i] {
			max = dist[i]
			maxID = i
		}
	}

	return maxID
}

func findMax(n1 int, n2 int) int {
	if n1 > n2 {
		return n1
	}

	return n2
}

func main() {
	r := bufio.NewReader(os.Stdin)
	var n, m, d, s1, s2, first, second, res int
	fmt.Fscanf(r, "%d %d %d\n", &n, &m, &d)

	isAffected := map[int]bool{}
	for i := 0; i < m; i++ {
		fmt.Fscanf(r, "%d", &s1)
		isAffected[s1] = true
	}
	fmt.Fscanln(r)

	graph = make([][]int, n+1)
	for i := 1; i < n; i++ {
		fmt.Fscanf(r, "%d %d\n", &s1, &s2)
		graph[s1] = append(graph[s1], s2)
		graph[s2] = append(graph[s2], s1)
	}

	dist := make([]int, n+1)
	initDist(dist)
	dfs(1, 0, dist)
	first = findFurthestNode(isAffected, dist)

	//find distance from first to every node
	dist1 := make([]int, n+1)
	dist2 := make([]int, n+1)
	initDist(dist1)
	dfs(first, 0, dist1)

	if m == 1 {
		second = first
		dist2 = dist1
	} else {
		second = findFurthestNode(isAffected, dist1)
		initDist(dist2)
		dfs(second, 0, dist2)
	}

	for i := 1; i <= n; i++ {
		if findMax(dist1[i], dist2[i]) <= d {
			res++
		}
	}

	fmt.Fprintf(os.Stdout, "%d\n", res)
}

package main

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

const max = 10000000
const min = -max

type scanner struct {
	*bufio.Scanner
}

func (s *scanner) nextInt() int {
	s.Scan()
	v, _ := strconv.Atoi(s.Text())
	return v
}

func (s *scanner) nextInt64() int64 {
	s.Scan()
	v, _ := strconv.ParseInt(s.Text(), 10, 64)
	return v
}

type tree struct {
	g       map[int]map[int]bool
	d       map[int]int
	u       map[int]int
	sibling map[int]int
	p       map[int]bool
}

func (t *tree) dfsu(u, parent int) {
	if t.p[parent] {
		t.u[u] = 1
	}

	if sibling, ok := t.sibling[u]; ok && sibling+2 > t.u[u] {
		t.u[u] = t.sibling[u]+2
	}

	if parent, ok := t.u[parent]; ok && parent+1 > t.u[u] {
		t.u[u] = parent+1
	}

	for v := range t.g[u] {
		if v == parent {
			continue
		}
		t.dfsu(v, u)
	}
}

func (t *tree) dfsd(u, parent int) {
	t.d[u]=min
	max1, max2 := min, min
	for v := range t.g[u] {
		if v == parent {
			continue
		}
		t.dfsd(v, u)
		dv := t.d[v]
		if dv > max1 {
			max2, max1 = max1, dv
		} else if dv > max2 {
			max2 = dv
		}
	}

	for v := range t.g[u] {
		if v == parent {
			continue
		}
		dv := t.d[v]
		if dv == max1 {
			t.sibling[v] = max2
		} else {
			t.sibling[v] = max1
		}
	}

	if t.p[u] {
		t.d[u] = 0
	}
	if max1 != min {
		t.d[u] = max1 + 1
	}
}

func (t *tree) bfs(root, deg int) map[int]int {
	var q []int
	var d []int
	v := map[int]int{}
	q = append(q, root)
	d = append(d, 0)
	for len(q) > 0 {
		u := q[0]
		du := d[0]
		q = q[1:]
		d = d[1:]
		if du > deg {
			break
		}
		if _, ok := v[u]; ok {
			continue
		}
		v[u] = du
		// fmt.Print(u, " ")
		for v := range t.g[u] {
			q = append(q, v)
			d = append(d, du+1)
		}
	}
	// fmt.Println()
	return v
}

func main() {
	in := &scanner{bufio.NewScanner(os.Stdin)}
	in.Split(bufio.ScanWords)

	n, m, d := in.nextInt(), in.nextInt(), in.nextInt()
	_ = d

	p := map[int]bool{}
	g := map[int]map[int]bool{}
	for i := 1; i <= n; i++ {
		g[i] = map[int]bool{}
	}

	for i := 0; i < m; i++ {
		v := in.nextInt()
		p[v] = true
	}

	for i := 1; i < n; i++ {
		u, v := in.nextInt(), in.nextInt()
		g[u][v] = true
		g[v][u] = true
	}

	t := tree{
		g:       g,
		d:       map[int]int{},
		u:       map[int]int{},
		sibling: map[int]int{},
		p:       p,
	}

	// for i := 1; i <= n; i++ {
		// fmt.Print(i, " ")
		// for v := range g[i] {
			// fmt.Print(v, " ")
		// }
		// fmt.Println()
	// }

	// a := t.bfs(9, d)
	// for u, d := range a {
		// fmt.Println("9", u, d)
	// }
	// b := t.bfs(14, d)
	// for u, d := range b {
		// fmt.Println("14", u, d)
	// }
	// c := map[int]int{}
	// for i := 1; i <= n; i++ {
		// if a[i] != 0 && b[i] != 0 {
			// if a[i] > b[i] {
				// c[i] = a[i]
			// } else {
				// c[i] = b[i]
			// }
			// fmt.Print(i, " ")
		// }
	// }
	// fmt.Println()

	t.dfsd(1, -1)
	t.dfsu(1, -1)
	// for u := range c {
		// fmt.Println(u, ":", t.d[u], t.u[u], t.sibling[u], c[u])
	// }
	// fmt.Println(t.d)
	// fmt.Println(t.u)
	// fmt.Println(t.sibling)
	var cnt int
	for i := 1; i <= n; i++ {
		if t.u[i] <= d && t.d[i] <= d {
			// fmt.Println("HIHI", i, t.u[i], t.d[i])
			cnt++
		}
	}
	fmt.Println(cnt)
}

package main

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

var (
    n,m,d int
    marked []bool
    h [][]int
    dd, du []int
)

func main() {
    Scanf("%d %d %d", &n, &m, &d)
    marked = make([]bool, n+1)

    sc := bufio.NewScanner(os.Stdin)
    sc.Split(bufio.ScanWords)

    for i := 0; i < m; i++ {
        sc.Scan()
        v, _ := strconv.Atoi(sc.Text())
        marked[v] = true
    }

    h = make([][]int, n+1)
    for i := 0; i < n+1; i++ {
        h[i] = make([]int, 0, 10)
    }

    for i := 1; i < n; i++ {
        sc.Scan()
        a, _ := strconv.Atoi(sc.Text())
        sc.Scan()
        b, _ := strconv.Atoi(sc.Text())
        h[a] = append(h[a], b)
        h[b] = append(h[b], a)
    }

    dd = make ([]int, n+1)
    du = make ([]int, n+1)
    for i := 0; i < n+1; i++ {
        dd[i] = -1
        du[i] = -1
    }
    if marked[1] {
        du[1] = 0
    }

    dist_down(1, -1)
    dist_up(1, -1)

    sum := 0
    for i := 1; i < n+1; i++ {
        if dd[i] <= d && du[i] <= d {
            sum = sum + 1
        }
    }
    Println(sum)
}

func dist_down(to, from int) (int) {
    if marked[to] {
        dd[to] = 0
    }

    for _, ch := range h[to] {
        if ch != from {
            d := dist_down(ch, to)
            if d != -1 {
    	        if dd[to] < d + 1 {
                    dd[to] = d + 1
                }
            }
        }
    }
    return dd[to]
}

func dist_up(to, from int) {
    max1 := -1
    max2 := -1

    for _, ch := range h[to] {
        if ch != from {
            if dd[ch] > max1 {
    	        max2 = max1
    	        max1 = dd[ch]
            } else if dd[ch] > max2 {
    	        max2 = dd[ch]
            }
        }
    }

    for _, ch := range h[to] {
        if ch != from {
            sibling := max1
            if dd[ch] == max1 {
                sibling = max2
            }

            if sibling != -1 {
                du[ch] = sibling + 2
            }

            if du[to] != -1 {
    	        if du[to] + 1 > du[ch] {
                    du[ch] = du[to] + 1
                }
            }

            if marked[ch] {
    	        if 0 > du[ch] {
                    du[ch] = 0
                }
            }

            dist_up(ch, to)
        }
    }
}

package main

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

const (
    LOW = -123456789
)

func Init() {
}

func Solve(io *FastIO) {
    N := io.NextInt()
    M := io.NextInt()
    D := io.NextInt()
    P := io.NextIntArray(M)

    nodes := make([]*Node, N + 1)
    for i := 1; i <= N; i++ {
        nodes[i] = NewNode()
    }

    for _, u := range P {
        nodes[u].spooky = true
    }

    for i := 1; i < N; i++ {
        U := io.NextInt()
        V := io.NextInt()

        nodes[U].next[nodes[V]] = true
        nodes[V].next[nodes[U]] = true
    }

    Rootify(nodes[1], nil)
    ComputeBests(nodes[1])
    ComputeUps(nodes[1])

    // for i := 1; i <= N; i++ {
    //     fmt.Printf("i = %d: %+v, %+v\n", i, nodes[i], nodes[i].down)
    // }

    ans := CountGood(nodes[1], D)
    io.Println(ans)
}

func Rootify(u, p *Node) {
    delete(u.next, p)
    for v := range u.next {
        Rootify(v, u)
    }
}

func ComputeBests(u *Node) {
    if u.spooky {
        u.down.Add(0)
    }
    for v := range u.next {
        ComputeBests(v)
        u.down.Add(1 + v.down.Best())
    }
}

func ComputeUps(u *Node) {
    for v := range u.next {
        u.down.Remove(1 + v.down.Best())
        v.up = 1 + Max(u.up, u.down.Best())
        u.down.Add(1 + v.down.Best())
        ComputeUps(v)
    }
}

func CountGood(u *Node, d int) int {
    cnt := 0
    if u.up <= d && u.down.Best() <= d {
        cnt++
    }
    for v := range u.next {
        cnt += CountGood(v, d)
    }
    return cnt
}

type Node struct {
    next map[*Node]bool
    spooky bool
    down *BestTwo
    up int
}

func NewNode() *Node {
    return &Node{
        next: make(map[*Node]bool),
        down: MakeBestTwo(),
        up: LOW,
    }
}

type BestTwo struct {
    best []int
}

func MakeBestTwo() *BestTwo {
    return &BestTwo{
        best: []int{LOW, LOW},
    }
}

func (this *BestTwo) Add(val int) {
    sort.Ints(this.best)
    this.best[0] = Max(this.best[0], val)
}

func (this *BestTwo) Remove(val int) {
    for i, v := range this.best {
        if val == v {
            this.best[i] = LOW
            return
        }
    }
}

func (this *BestTwo) Best() int {
    return Max(this.best...)
}

func Max(args ...int) int {
	max := args[0]
	for i := 1; i < len(args); i++ {
		if args[i] > max {
			max = args[i]
		}
	}
	return max
}

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

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

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

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

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

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

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

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

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

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

func (io *FastIO) Println(args ...interface{}) {
	io.writer.WriteString(fmt.Sprintln(args...))
}

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

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

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

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

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

package main

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

var (
	sc *bufio.Scanner = bufio.NewScanner(os.Stdin)
	n, m, d int
	marked  []bool
	kids    [][]int
	mxdown  []int
	mxup    []int
	mxkids  [][]int
)

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

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

func calcMxDown(a, par int) int {
	mxdown[a] = -1e9
	if marked[a] {
		mxdown[a] = 0
	}
	for _, b := range kids[a] {
		if b != par {
			mxdown[a] = max(mxdown[a], calcMxDown(b, a)+1)
		}
	}
	return mxdown[a]
}

func calcMxKids(a, par int) {
	var m1, m2 int = -1e9, -1e9
	for _, b := range kids[a] {
		if b != par {
			calcMxKids(b, a)
			if m1 <= mxdown[b] {
				m1, m2 = mxdown[b], m1
			} else if m2 < mxdown[b] {
				m2 = mxdown[b]
			}
		}
	}
	mxkids[a] = []int{m1, m2}
}

func calcMxUp(a, par int) {
	mxup[a] = -1e9
	if marked[a] {
		mxup[a] = 0
	}
	if par != 0 {
		mxup[a] = max(mxup[a], mxup[par]+1)
		if mxdown[a] == mxkids[par][0] {
			mxup[a] = max(mxup[a], mxkids[par][1]+2)
		} else { // <
			mxup[a] = max(mxup[a], mxkids[par][0]+2)
		}
	}
	for _, b := range kids[a] {
		if b != par {
			calcMxUp(b, a)
		}
	}
}

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

func main() {
	sc.Split(bufio.ScanWords)
	n, m, d = nextInt(), nextInt(), nextInt()
	marked = make([]bool, n+1)
	kids = make([][]int, n+1)
	for i := 1; i <= n; i++ {
		kids[i] = make([]int, 0, 10)
	}
	for i := 0; i < m; i++ {
		marked[nextInt()] = true
	}
	for i := 0; i < n-1; i++ {
		a, b := nextInt(), nextInt()
		kids[a] = append(kids[a], b)
		kids[b] = append(kids[b], a)
	}

	mxdown = make([]int, n+1)
	calcMxDown(1, 0)

	mxkids = make([][]int, n+1)
	calcMxKids(1, 0)
	mxup = make([]int, n+1)
	calcMxUp(1, 0)

	ans := 0
	for a := 1; a <= n; a++ {
		//fmt.Println(a, " : ", mxdown[a], " ", mxup[a], " ", mxkids[a])
		if mxdown[a] <= d && mxup[a] <= d {
			ans++
		}
	}
	fmt.Println(ans)
}

package main

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

var (
	sc      *bufio.Scanner = bufio.NewScanner(os.Stdin)
	n, m, d int
	marked  []bool
	kids    [][]int
	mxdown  []int
	mxup    []int
	mxkids  [][]int
)

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

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

func calcMxDown(a, par int) int {
	mxdown[a] = -1e9
	if marked[a] {
		mxdown[a] = 0
	}
	for _, b := range kids[a] {
		if b != par {
			mxdown[a] = max(mxdown[a], calcMxDown(b, a)+1)
		}
	}
	return mxdown[a]
}

func calcMxKids(a, par int) {
	var m1, m2 int = -1e9, -1e9
	for _, b := range kids[a] {
		if b != par {
			calcMxKids(b, a)
			if m1 <= mxdown[b] {
				m1, m2 = mxdown[b], m1
			} else if m2 < mxdown[b] {
				m2 = mxdown[b]
			}
		}
	}
	mxkids[a] = []int{m1, m2}
}

func calcMxUp(a, par int) {
	mxup[a] = -1e9
	if marked[a] {
		mxup[a] = 0
	}
	if par != 0 {
		mxup[a] = max(mxup[a], mxup[par]+1)
		if mxdown[a] == mxkids[par][0] {
			mxup[a] = max(mxup[a], mxkids[par][1]+2)
		} else { // <
			mxup[a] = max(mxup[a], mxkids[par][0]+2)
		}
	}
	for _, b := range kids[a] {
		if b != par {
			calcMxUp(b, a)
		}
	}
}

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

func main() {
	sc.Split(bufio.ScanWords)
	n, m, d = nextInt(), nextInt(), nextInt()
	marked = make([]bool, n+1)
	kids = make([][]int, n+1)
	for i := 1; i <= n; i++ {
		kids[i] = make([]int, 0, 10)
	}
	for i := 0; i < m; i++ {
		marked[nextInt()] = true
	}
	for i := 0; i < n-1; i++ {
		a, b := nextInt(), nextInt()
		kids[a] = append(kids[a], b)
		kids[b] = append(kids[b], a)
	}

	mxdown = make([]int, n+1)
	calcMxDown(1, 0)

	mxkids = make([][]int, n+1)
	calcMxKids(1, 0)
	mxup = make([]int, n+1)
	calcMxUp(1, 0)

	ans := 0
	for a := 1; a <= n; a++ {
		if mxdown[a] <= d && mxup[a] <= d {
			ans++
		}
	}
	fmt.Println(ans)
}

package main

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

var in = bufio.NewScanner(os.Stdin)

func readInt() int {
	if !in.Scan() {
		panic(in.Err())
	}
	res := int(0)
	for _, b := range in.Bytes() {
		res = res*10 + int(b-'0')
	}
	return res
}

func main() {
	in.Split(bufio.ScanWords)
	n, m, d := readInt(), readInt(), readInt()
	p := make([]int, m)
	for i := range p {
		p[i] = readInt() - 1
	}
	edges := make([][]int, n)
	for i := 1; i < n; i++ {
		a, b := readInt()-1, readInt()-1
		edges[a] = append(edges[a], b)
		edges[b] = append(edges[b], a)
	}

	bfs := func(root int) []int {
		dist := make([]int, n)
		for i := range dist {
			dist[i] = -1
		}
		dist[root] = 0
		q := []int{root}
		for len(q) > 0 {
			v := q[0]
			q = q[1:]
			for _, u := range edges[v] {
				if dist[u] >= 0 {
					continue
				}
				dist[u] = dist[v] + 1
				q = append(q, u)
			}
		}
		return dist
	}
	dist := bfs(p[0])
	far := p[0]
	for i := range p {
		if dist[p[i]] > dist[far] {
			far = p[i]
		}
	}
	dist2 := bfs(far)
	ans := 0
	for i := range dist {
		if dist[i] <= d && dist2[i] <= d {
			ans++
		}
	}
	fmt.Println(ans)
}

package main

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

const max = 10000000
const min = -max

type scanner struct {
	*bufio.Scanner
}

func (s *scanner) nextInt() int {
	s.Scan()
	v, _ := strconv.Atoi(s.Text())
	return v
}

func (s *scanner) nextInt64() int64 {
	s.Scan()
	v, _ := strconv.ParseInt(s.Text(), 10, 64)
	return v
}

type tree struct {
	g       map[int]map[int]bool
	d       map[int]int
	u       map[int]int
	sibling map[int]int
	p       map[int]bool
}

func (t *tree) dfsu(u, parent int) {
	if t.p[parent] {
		t.u[u] = 1
	}

		if sibling, ok := t.sibling[u]; ok && sibling+2 > t.u[u] {
			t.u[u] = t.sibling[u]+2
		}

		if parent, ok := t.u[parent]; ok && parent+1 > t.u[u] {
			t.u[u] = parent+1
		}

	for v := range t.g[u] {
		if v == parent {
			continue
		}
		t.dfsu(v, u)
	}
}

func (t *tree) dfsd(u, parent int) {
	t.d[u]=min
	max1, max2 := min, min
	for v := range t.g[u] {
		if v == parent {
			continue
		}
		t.dfsd(v, u)
		dv := t.d[v]
		if dv > max1 {
			max2, max1 = max1, dv
		} else if dv > max2 {
			max2 = dv
		}
	}

	for v := range t.g[u] {
		if v == parent {
			continue
		}
		dv := t.d[v]
		if dv == max1 {
			t.sibling[v] = max2
		} else {
			t.sibling[v] = max1
		}
	}

	if t.p[u] {
		t.d[u] = 0
	} else if max1 != min {
		t.d[u] = max1 + 1
	}

	// if u == 24 {
		// fmt.Println("HI:", t.d[u], t.p[u], max1)
	// }
}

func (t *tree) bfs(root, deg int) map[int]int {
	var q []int
	var d []int
	v := map[int]int{}
	q = append(q, root)
	d = append(d, 0)
	for len(q) > 0 {
		u := q[0]
		du := d[0]
		q = q[1:]
		d = d[1:]
		if du > deg {
			break
		}
		if _, ok := v[u]; ok {
			continue
		}
		v[u] = du
		// fmt.Print(u, " ")
		for v := range t.g[u] {
			q = append(q, v)
			d = append(d, du+1)
		}
	}
	// fmt.Println()
	return v
}

func main() {
	in := &scanner{bufio.NewScanner(os.Stdin)}
	in.Split(bufio.ScanWords)

	n, m, d := in.nextInt(), in.nextInt(), in.nextInt()
	_ = d

	p := map[int]bool{}
	g := map[int]map[int]bool{}
	for i := 1; i <= n; i++ {
		g[i] = map[int]bool{}
	}

	for i := 0; i < m; i++ {
		v := in.nextInt()
		p[v] = true
	}

	for i := 1; i < n; i++ {
		u, v := in.nextInt(), in.nextInt()
		g[u][v] = true
		g[v][u] = true
	}

	t := tree{
		g:       g,
		d:       map[int]int{},
		u:       map[int]int{},
		sibling: map[int]int{},
		p:       p,
	}

	// for i := 1; i <= n; i++ {
		// fmt.Print(i, " ")
		// for v := range g[i] {
			// fmt.Print(v, " ")
		// }
		// fmt.Println()
	// }

	// a := t.bfs(9, d)
	// for u, d := range a {
		// fmt.Println("9", u, d)
	// }
	// b := t.bfs(14, d)
	// for u, d := range b {
		// fmt.Println("14", u, d)
	// }
	// c := map[int]int{}
	// for i := 1; i <= n; i++ {
		// if a[i] != 0 && b[i] != 0 {
			// if a[i] > b[i] {
				// c[i] = a[i]
			// } else {
				// c[i] = b[i]
			// }
			// fmt.Print(i, " ")
		// }
	// }
	// fmt.Println()

	t.dfsd(1, -1)
	t.dfsu(1, -1)
	// for u := range c {
		// fmt.Println(u, ":", t.d[u], t.u[u], t.sibling[u], c[u])
	// }
	// fmt.Println(t.d)
	// fmt.Println(t.u)
	// fmt.Println(t.sibling)
	var cnt int
	for i := 1; i <= n; i++ {
		if t.u[i] <= d && t.d[i] <= d {
			// fmt.Println("HIHI", i, t.u[i], t.d[i])
			cnt++
		}
	}
	fmt.Println(cnt)
}

package main

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

var (
    n,m,d int
    marked []bool
    h []*list.List
    dd, du []int
)

func main() {
    fmt.Scanf("%d %d %d", &n, &m, &d)
    marked = make([]bool, n+1)

    sc := bufio.NewScanner(os.Stdin)
    sc.Split(bufio.ScanWords)

    for i := 0; i < m; i++ {
        sc.Scan()
        v,_ := strconv.Atoi(sc.Text())
        marked[v] = true
    }

    h = make([]*list.List, n+1)

    for i := 0; i < n+1; i++ {
        h[i] = list.New()
    }

    for i := 1; i < n; i++ {
        var a, b int
        fmt.Scanf("%d %d", &a, &b)
        h[a].PushBack(b)
        h[b].PushBack(a)
    }

    dd = make ([]int, n+1)
    du = make ([]int, n+1)
    for i := 0; i < n+1; i++ {
        dd[i] = -1
        du[i] = -1
    }
    if marked[1] {
        du[1] = 0
    }

    dist_down(1, -1)
    dist_up(1, -1)

    sum := 0
    for i := 1; i < n+1; i++ {
        if dd[i] <= d && du[i] <= d {
            sum = sum + 1
        }
    }
    fmt.Println(sum)
}

func dist_down(to, from int) (int) {
    if marked[to] {
        dd[to] = 0
    }

    child := h[to].Front()
    for child != nil {
        ch := child.Value.(int)

        if ch != from {
            d := dist_down(ch, to)
            if d != -1 {
    	        if dd[to] < d + 1 {
                    dd[to] = d + 1
                }
            }
        }
        child = child.Next()
    }
    return dd[to]
}

func dist_up(to, from int) {
    max1 := -1
    max2 := -1

    child := h[to].Front()
    for child != nil {
        ch := child.Value.(int)
        if ch != from {
            if dd[ch] > max1 {
    	        max2 = max1
    	        max1 = dd[ch]
            } else if dd[ch] > max2 {
    	        max2 = dd[ch]
            }
        }
        child = child.Next()
    }

    child = h[to].Front()
    for child != nil {
        ch := child.Value.(int)
        if ch != from {
            sibling := max1
            if dd[ch] == max1 {
                sibling = max2
            }

            if sibling != -1 {
                du[ch] = sibling + 2
            }

            if du[to] != -1 {
    	        if du[to] + 1 > du[ch] {
                    du[ch] = du[to] + 1
                }
            }

            if marked[ch] {
    	        if 0 > du[ch] {
                    du[ch] = 0
                }
            }

            dist_up(ch, to)
        }
        child = child.Next()
    }
}

package main

import (
	"fmt"
	"os"
)

var (
	n, m, d int
	marked  []bool
	kids    [][]int
	mxdown  []int
	mxup    []int
	mxkids  [][]int
)

func init() {
	_ = os.Open
	//os.Stdin, _ = os.Open("337D.in")
}

func calcMxDown(a, par int) int {
	mxdown[a] = -1e9
	if marked[a] {
		mxdown[a] = 0
	}
	for _, b := range kids[a] {
		if b != par {
			kidVal := calcMxDown(b, a)
			if mxdown[a] < kidVal+1 {
				mxdown[a] = kidVal + 1
			}
		}
	}
	return mxdown[a]
}

func calcMxKids(a, par int) {
	var m1, m2 int = -1e9, -1e9
	for _, b := range kids[a] {
		if b != par {
			calcMxKids(b, a)
			if m1 <= mxdown[b] {
				m1, m2 = mxdown[b], m1
			} else if m2 < mxdown[b] {
				m2 = mxdown[b]
			}
		}
	}
	mxkids[a] = []int{m1, m2}
}

func calcMxUp(a, par int) {
	mxup[a] = -1e9
	if marked[a] {
		mxup[a] = 0
	}
	if par != 0 {
		mxup[a] = mxup[par] + 1
		if mxdown[a] == mxkids[par][0] {
			mxup[a] = max(mxup[a], mxkids[par][1]+2)
		} else { // <
			mxup[a] = max(mxup[a], mxkids[par][0]+2)
		}
	}
	for _, b := range kids[a] {
		if b != par {
			calcMxUp(b, a)
		}
	}
}

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

func main() {
	fmt.Scan(&n, &m, &d)
	marked = make([]bool, n+1)
	kids = make([][]int, n+1)
	for i := 1; i <= n; i++ {
		kids[i] = make([]int, 0, 10)
	}
	for i := 0; i < m; i++ {
		var v int
		fmt.Scan(&v)
		marked[v] = true
	}
	for i := 0; i < n-1; i++ {
		var a, b int
		fmt.Scan(&a, &b)
		kids[a] = append(kids[a], b)
		kids[b] = append(kids[b], a)
	}

	mxdown = make([]int, n+1)
	calcMxDown(1, 0)

	mxkids = make([][]int, n+1)
	calcMxKids(1, 0)
	mxup = make([]int, n+1)
	calcMxUp(1, 0)

	ans := 0
	for a := 1; a <= n; a++ {
		//fmt.Println(a, " : ", mxdown[a], " ", mxup[a], " ", mxkids[a])
		if mxdown[a] <= d && mxup[a] <= d {
			ans++
		}
	}
	fmt.Println(ans)
}