Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent.Let's call a rooted tree a spruce if its every non-leaf vertex has at least 3 leaf children. You are given a rooted tree, check whether it's a spruce.The definition of a rooted tree can be found here.

The first line contains one integer n — the number of vertices in the tree (3 ≤ n ≤ 1 000). Each of the next n - 1 lines contains one integer pi (1 ≤ i ≤ n - 1) — the index of the parent of the i + 1-th vertex (1 ≤ pi ≤ i). Vertex 1 is the root. It's guaranteed that the root has at least 2 children.

Print "Yes" if the tree is a spruce and "No" otherwise.

NoteThe first example:The second example:It is not a spruce, because the non-leaf vertex 1 has only 2 leaf children.The third example:

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	children := make([][]int, n)
	isLeaf := func(v int) bool {
		return len(children[v]) == 0 && v != 0
	}
	for c := 1; c < n; c++ {
		var p int
		fmt.Scan(&p)
		p--
		children[p] = append(children[p], c)
	}
	for v, ch := range children {
		if !isLeaf(v) {
			lc := 0
			for _, c := range ch {
				if isLeaf(c) {
					lc++
				}
			}
			if lc < 3 {
				fmt.Println("No")
				return
			}
		}
	}
	fmt.Println("Yes")
}

package main

import "fmt"

func is3Node(node int, tree [][]int) (bool, bool) {
	var leafCount int
	if len(tree[node]) == 0 {
		return true, true
	}

	for _, n := range tree[node] {
		is3, isLeaf := is3Node(n, tree)
		if !is3 {
			return false, false
		}
		if isLeaf {
			leafCount++
		}
	}

	if leafCount >= 3 {
		return true, false
	}
	return false, false
}

func is3Tree(tree [][]int) string {
	is3, isLeaf := is3Node(0, tree)
	if is3 && !isLeaf {
		return "Yes"
	} else {
		return "No"
	}
}

func main() {
	var n int
	fmt.Scan(&n)

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

	for i := 1; i < n; i++ {
		var node int
		fmt.Scan(&node)
		tree[node-1] = append(tree[node-1], i)
	}

	fmt.Println(is3Tree(tree))
}

package main

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

func main() {
	var n, x int
	stdin := bufio.NewReader(os.Stdin)
	fmt.Fscanf(stdin, "%d\n", &n)

	children := make([]int, n)
	parent := make([]int, n)
	for i := 1; i < n; i++ {
		fmt.Fscanf(stdin, "%d\n", &x)
		x--
		parent[i] = x
		children[parent[i]]++
	}

	sonsLeaves := make([]int, n)
	for i := 0; i < n; i++ {
		if children[i] == 0 {
			sonsLeaves[parent[i]]++
		}
	}
	for i := 0; i < n; i++ {
		if children[i] > 0 && sonsLeaves[i] < 3 {
			fmt.Println("No")
			return
		}
	}
	fmt.Println("Yes")
}

package main

import "fmt"

// 1200
// 26.05.2020
// https://codeforces.com/problemset/problem/913/B

func main() {
	var n int
	fmt.Scanln(&n)
	parents := make([]int, n)
	count := make([]int, n)
	for i := 1; i < n; i++ {
		var parent int
		fmt.Scanln(&parent)
		parent--
		parents[i] = parent
		count[parent]++
	}

	count2 := make([]int, n)
	for i, c := range count {
		if c == 0 {
			count2[parents[i]]++
		}
	}
	for i, c := range count2 {
		if count[i] != 0 && c < 3 {
			fmt.Println("No")
			return
		}
	}
	fmt.Println("Yes")
}

package main

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

var to = [1111][]int{}
var ans = true

func dp(pos int) int {
	var cnt = 0
	for i := 0; i < len(to[pos]); i++ {
		cnt += dp(to[pos][i])
	}
	// fmt.Println(pos, cnt)
	if len(to[pos]) != 0 && cnt < 3 {
		// fmt.Println(ans)
		ans = false
	}
	if cnt == 0 {
		return 1
	} else {
		return 0
	}
}

func main() {
	var n, x int
	cin := bufio.NewReader(os.Stdin)
	fmt.Fscanf(cin, "%d\n", &n)

	for i := 0; i < n-1; i++ {
		fmt.Fscanf(cin, "%d\n", &x)
		to[x-1] = append(to[x-1], i+1)
	}
	dp(0)
	if ans {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

package main

import "fmt"

func main(){
	var b[3300] int
	var a[3300] int
	var c[3300] int
	var n,x int

	fmt.Scan(&n)

	for i:=2;i<=n;i++{
		fmt.Scan(&x)
		a[i]=x
		if b[x]==0{
			b[x]=1
		}
	}

	for i:=2;i<=n;i++{
		if b[i]==0{
			c[a[i]]++
		}
	}

	for i:=1;i<=n;i++{
		if b[i]==0 {
			continue;
		}
		if c[i]<3 {
			fmt.Println("No")
			return
		}
	}
	fmt.Println("Yes")

}

package main

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

type Graph struct {
	Adj     map[int][]int
	Visited map[int]bool
	Leaves  map[int]int
}

func explore(g *Graph, u, p int) {
	g.Visited[u] = true
	if edges, ok := g.Adj[u]; ok {
		for _, v := range edges {
			if _, ok := g.Visited[v]; !ok {
				explore(g, v, u)
			}
		}

	} else {
		if _, ok := g.Leaves[p]; !ok {
			g.Leaves[p] = 1
		} else {
			g.Leaves[p] = g.Leaves[p] + 1
		}
	}
}

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

	var n, parent int
	fmt.Fscanf(reader, "%d\n", &n)
	g := Graph{Adj: make(map[int][]int), Leaves: make(map[int]int), Visited: make(map[int]bool)}
	for i := 1; i < n; i++ {
		fmt.Fscanf(reader, "%d\n", &parent)
		if _, ok := g.Adj[parent]; !ok {
			g.Adj[parent] = make([]int, 0)
		}
		g.Adj[parent] = append(g.Adj[parent], i+1)
	}
	for i := 1; i <= n; i++ {
		if _, ok := g.Visited[i]; !ok {
			explore(&g, i, 0)
		}
	}
	flag := true
	for i := 1; i <= n; i++ {
		if _, ok := g.Adj[i]; ok {
			if _, yes := g.Leaves[i]; (yes && g.Leaves[i] < 3) || !yes {
				flag = false
				break
			}
		}
	}
	if flag {
		fmt.Fprintf(writer, "Yes\n")
	} else {
		fmt.Fprintf(writer, "No\n")
	}
}

package main

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

type Graph struct {
	Adj     map[int][]int
	Visited map[int]bool
	Leaves  map[int]int
	Spruce  bool
}

func explore(g *Graph, u, p int) {
	g.Visited[u] = true
	if edges, ok := g.Adj[u]; ok {
		for _, v := range edges {
			if _, ok := g.Visited[v]; !ok {
				explore(g, v, u)
			}
		}
		if count, ok := g.Leaves[u]; (ok && count < 3) || !ok {
			g.Spruce = false
		}

	} else {
		if _, ok := g.Leaves[p]; !ok {
			g.Leaves[p] = 1
		} else {
			g.Leaves[p] = g.Leaves[p] + 1
		}
	}
}

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

	var n, parent int
	fmt.Fscanf(reader, "%d\n", &n)
	g := Graph{Adj: make(map[int][]int), Leaves: make(map[int]int), Visited: make(map[int]bool), Spruce: true}
	for i := 1; i < n; i++ {
		fmt.Fscanf(reader, "%d\n", &parent)
		if _, ok := g.Adj[parent]; !ok {
			g.Adj[parent] = make([]int, 0)
		}
		g.Adj[parent] = append(g.Adj[parent], i+1)
	}
	for i := 1; i <= n; i++ {
		if _, ok := g.Visited[i]; !ok {
			explore(&g, i, 0)
		}
	}
	if g.Spruce {
		fmt.Fprintf(writer, "Yes\n")
	} else {
		fmt.Fprintf(writer, "No\n")
	}
}

package main

import "fmt"

func is3Node(node int, tree [][]int) (bool, bool) {
	var leafCount int
	if len(tree[node]) == 0 {
		return true, true
	}

	for _, n := range tree[node] {
		is3, isLeaf := is3Node(n, tree)
		if !is3 {
			return false, false
		}
		if isLeaf {
			leafCount++
		}
	}

	if leafCount == 3 {
		return true, false
	}
	return false, false
}

func is3Tree(tree [][]int) string {
	is3, isLeaf := is3Node(0, tree)
	if is3 && !isLeaf {
		return "Yes"
	} else {
		return "No"
	}
}

func main() {
	var n int
	fmt.Scan(&n)

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

	for i := 1; i < n; i++ {
		var node int
		fmt.Scan(&node)
		tree[node-1] = append(tree[node-1], i)
	}

	fmt.Println(is3Tree(tree))
}

package main

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

func main() {
	var n, x int
	stdin := bufio.NewReader(os.Stdin)
	fmt.Fscanf(stdin, "%d\n", &n)

	children := make(map[int]int)
	nonLeaf := make(map[int]bool)
	parent := make([]int, n)

	// count all children for non-leaf children
	for i := 1; i < n; i++ {
		fmt.Fscanf(stdin, "%d\n", &x)
		x-- // since we use root = 0 instead of 1
		parent[i] = x
		nonLeaf[x] = true
		children[x]++
	}
	// subtract non-leaf children from all children
	for x = range nonLeaf {
		if x > 0 { // skip root
			children[parent[x]]--
		}
		if children[parent[x]] < 3 {
			fmt.Println("No")
			return
		}
	}
	fmt.Println("Yes")
}

package main

import "fmt"

// 1200
// 26.05.2020
// https://codeforces.com/problemset/problem/913/B

func main() {
	var n int
	fmt.Scanln(&n)
	parents := make([]int, n)
	count := make([]int, n)
	for i := 1; i < n; i++ {
		var parent int
		fmt.Scanln(&parent)
		parent--
		parents[i] = parent
		count[parent]++
	}

	count2 := make([]int, n)
	for i, c := range count {
		if c == 0 {
			count2[parents[i]]++
		}
	}
	for _, c := range count2 {
		if c != 0 && c < 3 {
			fmt.Println("No")
			return
		}
	}
	fmt.Println("Yes")
}

package main

import "fmt"

// 1200
// 26.05.2020
// https://codeforces.com/problemset/problem/913/B

func main() {
	var n int
	fmt.Scanln(&n)
	parents := make([]int, n)
	count := make([]map[int]struct{}, n)
	for i := 1; i < n; i++ {
		var parent int
		fmt.Scanln(&parent)
		parent--
		parents[i] = parent
		if count[parent] == nil {
			count[parent] = make(map[int]struct{})
		}
		count[parent][i] = struct{}{}
		if parent != 0 {
			delete(count[parents[parent]], parent)
		}
	}
	for _, c := range count {
		if len(c) != 0 && len(c) != 3 {
			fmt.Println("No")
			return
		}
	}
	fmt.Println("Yes")
}

package main

import "fmt"

// 1200
// 26.05.2020
// https://codeforces.com/problemset/problem/913/B

func main() {
	var n int
	fmt.Scanln(&n)
	parents := make([]int, n)
	count := make([]int, n)
	for i := 1; i < n; i++ {
		var parent int
		fmt.Scanln(&parent)
		parent--
		parents[i] = parent
		count[parent]++
	}

	count2 := make([]int, n)
	for i, c := range count {
		if c == 0 {
			count2[parents[i]]++
		}
	}
	for _, c := range count2 {
		if c != 0 && c != 3 {
			fmt.Println("No")
			return
		}
	}
	fmt.Println("Yes")
}

package main

import "fmt"

// 1200
// 26.05.2020
// https://codeforces.com/problemset/problem/913/B

func main() {
	var n int
	fmt.Scanln(&n)
	parents := make([]int, n)
	count := make([]map[int]bool, n)
	for i := 1; i < n; i++ {
		var parent int
		fmt.Scanln(&parent)
		parent--
		parents[i] = parent
		if count[parent] == nil {
			count[parent] = make(map[int]bool)
		}
		if _, ok := count[parent][i]; !ok {
			count[parent][i] = true
		}
		if parent != 0 {
			count[parents[parent]][parent] = false
		}
	}
	for _, c := range count {
		var cnt int
		for _, v := range c {
			if v {
				cnt++
			}
		}
		if cnt != 0 && cnt != 3 {
			fmt.Println("No")
			return
		}
	}
	fmt.Println("Yes")
}

package main

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

type Graph struct {
	Adj     map[int][]int
	Visited map[int]bool
	Leaves  map[int]int
}

func explore(g *Graph, u, p int) {
	g.Visited[u] = true
	if edges, ok := g.Adj[u]; ok {
		for _, v := range edges {
			if _, ok := g.Visited[v]; !ok {
				explore(g, v, u)
			}
		}

	} else {
		if _, ok := g.Leaves[p]; !ok {
			g.Leaves[p] = 1
		} else {
			g.Leaves[p] = g.Leaves[p] + 1
		}
	}
}

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

	var n, parent int
	fmt.Fscanf(reader, "%d\n", &n)
	g := Graph{Adj: make(map[int][]int), Leaves: make(map[int]int), Visited: make(map[int]bool)}
	for i := 1; i < n; i++ {
		fmt.Fscanf(reader, "%d\n", &parent)
		if _, ok := g.Adj[parent]; !ok {
			g.Adj[parent] = make([]int, 0)
		}
		g.Adj[parent] = append(g.Adj[parent], i+1)
	}
	for i := 1; i <= n; i++ {
		if _, ok := g.Visited[i]; !ok {
			explore(&g, i, -1)
		}
	}
	flag := true
	for _, count := range g.Leaves {
		if count < 3 {
			flag = false
			break
		}
	}
	if flag {
		fmt.Fprintf(writer, "Yes\n")
	} else {
		fmt.Fprintf(writer, "No\n")
	}
}


Suppose you are given a string $$$s$$$ of length $$$n$$$ consisting of lowercase English letters. You need to compress it using the smallest possible number of coins.To compress the string, you have to represent $$$s$$$ as a concatenation of several non-empty strings: $$$s = t_{1} t_{2} \ldots t_{k}$$$. The $$$i$$$-th of these strings should be encoded with one of the two ways:  if $$$|t_{i}| = 1$$$, meaning that the current string consists of a single character, you can encode it paying $$$a$$$ coins;  if $$$t_{i}$$$ is a substring of $$$t_{1} t_{2} \ldots t_{i - 1}$$$, then you can encode it paying $$$b$$$ coins. A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.So your task is to calculate the minimum possible number of coins you need to spend in order to compress the given string $$$s$$$.

The first line contains three positive integers, separated by spaces: $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \leq n, a, b \leq 5000$$$) — the length of the string, the cost to compress a one-character string and the cost to compress a string that appeared before. The second line contains a single string $$$s$$$, consisting of $$$n$$$ lowercase English letters.

Output a single integer — the smallest possible number of coins you need to spend to compress $$$s$$$.

NoteIn the first sample case, you can set $$$t_{1} =$$$ 'a', $$$t_{2} =$$$ 'b', $$$t_{3} =$$$ 'a' and pay $$$3 + 3 + 1 = 7$$$ coins, since $$$t_{3}$$$ is a substring of $$$t_{1}t_{2}$$$.In the second sample, you just need to compress every character by itself.In the third sample, you set $$$t_{1} = t_{2} =$$$ 'a', $$$t_{3} =$$$ 'aa' and pay $$$10 + 1 + 1 = 12$$$ coins, since $$$t_{2}$$$ is a substring of $$$t_{1}$$$ and $$$t_{3}$$$ is a substring of $$$t_{1} t_{2}$$$.

package main

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

var suffix [5000][5000]int
var dp [5000]int

func main() {
	var n, a, b int
	var s string
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)
	fmt.Fscanf(reader, "%d %d %d\n", &n, &a, &b)
	fmt.Fscanf(reader, "%s", &s)

	for i := 0;i < n;i ++ {
		for j := i + 1;j < n;j ++ {
			if s[i] == s[j] {
				if i == 0 {
					suffix[i][j] = 1
				} else {
					suffix[i][j] = suffix[i - 1][j - 1] + 1
				}
			}
		}
	}
	dp[0] = a
	for i := 1;i < n;i ++ {
		dp[i] = dp[i - 1] + a
		min := i + 1
		for j := 0;j < i;j ++ {
			if suffix[j][i] != 0 {
				if i - suffix[j][i] >= j && min > i - suffix[j][i] {
					min = i - suffix[j][i]
				}
				if i - suffix[j][i] < j && min > j {
					min = j
				}
			}
		}
		for j := min;j < i;j ++ {
			if dp[j] + b < dp[i] {
				dp[i] = dp[j] + b
			}
		}
	}
	fmt.Printf("%d", dp[n - 1])
}

package main

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

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

	return y
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	var n, a, b int
	var s string

	fmt.Fscanf(reader, "%d %d %d\n%s\n", &n, &a, &b, &s)

	var v [5002][5002]int
	ans := make([]int, n+1)

	for i := 1; i <= n; i++ {
		for j := i; j <= n; j++ {
			if s[i-1] == s[j-1] {
				v[i][j] = v[i-1][j-1] + 1
			}
		}
	}

	for i := 1; i <= n; i++ {
		ans[i] = ans[i-1] + a

		for j := 1; j < i; j++ {
			if t := min(i-j, v[j][i]); t > 0 {
				ans[i] = min(ans[i], ans[i-t]+b)
			}
		}
		//fmt.Println(i, ans[i])
	}

	fmt.Println(ans[n])
}

package main

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

var sub [5000][5000]bool
var dp [5000]int

func main() {
	var n, a, b int
	var s string
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)
	fmt.Fscanf(reader, "%d %d %d\n", &n, &a, &b)
	fmt.Fscanf(reader, "%s", &s)
	for i := 0;i < len(s);i ++ {
		matchPos := i
		for j := 0;j < i && matchPos < len(s);j ++ {
			if s[j] == s[matchPos] {
				sub[i][matchPos] = true
				matchPos ++
			}
		}
	}
	dp[0] = a
	for i := 1;i < len(s);i ++ {
		dp[i] = dp[i - 1] + a
		for j := i;j > 0;j -- {
			if sub[j][i] && dp[j - 1] + b < dp[i] {
				dp[i] = dp[j - 1] + b
			}
		}
	}
	fmt.Printf("%d", dp[len(s) - 1])
}

package main

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

var sub [5000][5000]bool
var dp [5000]int

func main() {
	var n, a, b int
	var s string
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)
	fmt.Fscanf(reader, "%d %d %d\n", &n, &a, &b)
	fmt.Fscanf(reader, "%s", &s)
	for i := 0;i < len(s);i ++ {
		matchPos := i
		for j := 0;j < i && matchPos < len(s);j ++ {
			if s[j] == s[matchPos] {
				sub[i][matchPos] = true
				matchPos ++
			} else {
				matchPos = i
			}
		}
	}
	dp[0] = a
	for i := 1;i < len(s);i ++ {
		dp[i] = dp[i - 1] + a
		for j := i;j > 0;j -- {
			if sub[j][i] && dp[j - 1] + b < dp[i] {
				dp[i] = dp[j - 1] + b
			}
		}
	}
	fmt.Printf("%d", dp[len(s) - 1])
}

package main

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

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

	return y
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	var n, a, b int
	var s string

	fmt.Fscanf(reader, "%d %d %d\n%s\n", &n, &a, &b, &s)

	ans := a
	temp := 0

	for i := 1; i < n; {
		ss := s[:i]
		for j := i; j < n; j++ {
			if ok := strings.Contains(ss, s[i:j+1]); !ok || j == n-1 {
				if ok {
					temp = min((j+1-i)*a, b)
					//fmt.Println(ss, s[i:j+1], temp)
					i = j + 1
				} else if i == j {
					temp = a
					//fmt.Println(ss, s[i:j+1], temp)
					i = j + 1
				} else {
					temp = min((j-i)*a, b)
					//fmt.Println(ss, s[i:j+1], temp)
					i = j
				}

				ans += temp

				break
			}
		}
	}

	fmt.Println(ans)
}

package main

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

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

	return y
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	var n, a, b int
	var s string

	fmt.Fscanf(reader, "%d %d %d\n%s\n", &n, &a, &b, &s)

	ans := a

	for i := 1; i < n; {
		ss := s[:i]
		for j := i; j < n; j++ {
			if ok := strings.Contains(ss, s[i:j+1]); !ok || j == n-1 {
				if i == j && !ok {
					ans += a
				} else if ok {
					ans += min((j+1-i)*a, b)
				} else {
					ans += min((j-i)*a, b)
				}

				//fmt.Println(i, j+1, ans)
				i = j + 1
				break
			}
		}
	}

	fmt.Println(ans)
}


This is the easy version of this problem. The only difference is the constraint on $$$k$$$ — the number of gifts in the offer. In this version: $$$k=2$$$.Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky — today the offer "$$$k$$$ of goods for the price of one" is held in store. Remember, that in this problem $$$k=2$$$.Using this offer, Vasya can buy exactly $$$k$$$ of any goods, paying only for the most expensive of them. Vasya decided to take this opportunity and buy as many goods as possible for his friends with the money he has.More formally, for each good, its price is determined by $$$a_i$$$ — the number of coins it costs. Initially, Vasya has $$$p$$$ coins. He wants to buy the maximum number of goods. Vasya can perform one of the following operations as many times as necessary:  Vasya can buy one good with the index $$$i$$$ if he currently has enough coins (i.e $$$p \ge a_i$$$). After buying this good, the number of Vasya's coins will decrease by $$$a_i$$$, (i.e it becomes $$$p := p - a_i$$$).  Vasya can buy a good with the index $$$i$$$, and also choose exactly $$$k-1$$$ goods, the price of which does not exceed $$$a_i$$$, if he currently has enough coins (i.e $$$p \ge a_i$$$). Thus, he buys all these $$$k$$$ goods, and his number of coins decreases by $$$a_i$$$ (i.e it becomes $$$p := p - a_i$$$). Please note that each good can be bought no more than once.For example, if the store now has $$$n=5$$$ goods worth $$$a_1=2, a_2=4, a_3=3, a_4=5, a_5=7$$$, respectively, $$$k=2$$$, and Vasya has $$$6$$$ coins, then he can buy $$$3$$$ goods. A good with the index $$$1$$$ will be bought by Vasya without using the offer and he will pay $$$2$$$ coins. Goods with the indices $$$2$$$ and $$$3$$$ Vasya will buy using the offer and he will pay $$$4$$$ coins. It can be proved that Vasya can not buy more goods with six coins.Help Vasya to find out the maximum number of goods he can buy.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The next lines contain a description of $$$t$$$ test cases.  The first line of each test case contains three integers $$$n, p, k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le p \le 2\cdot10^9$$$, $$$k=2$$$) — the number of goods in the store, the number of coins Vasya has and the number of goods that can be bought by the price of the most expensive of them. The second line of each test case contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^4$$$) — the prices of goods. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$. It is guaranteed that in this version of the problem $$$k=2$$$ for all test cases.

For each test case in a separate line print one integer $$$m$$$ — the maximum number of goods that Vasya can buy.

package main

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

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

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

func init() {
	ReadString = newReadString(os.Stdin)
	stdout = bufio.NewWriter(os.Stdout)
}

func newReadString(ior io.Reader) func() string {
	r := bufio.NewScanner(ior)
	// r.Buffer(make([]byte, 1024), int(1e+11)) // for AtCoder
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	// Split sets the split function for the Scanner. The default split function is ScanLines.
	// Split panics if it is called after scanning has started.
	r.Split(bufio.ScanWords)

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

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

/********** 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 MOD = 1000000000 + 7
const ALPHABET_NUM = 26
const INF_INT64 = math.MaxInt64
const INF_BIT60 = 1 << 60
const INF_INT32 = math.MaxInt32
const INF_BIT30 = 1 << 30

var t int
var n, p, k int64
var A []int64

func main() {
	t = ReadInt()

	for tc := 0; tc < t; tc++ {
		n, p, k = ReadInt64_3()
		A = ReadInt64Slice(int(n))

		solve()
	}
}

func solve() {
	sort.Sort(Int64List(A))

	// m は中央を意味する何らかの値
	isOK := func(m int) bool {
		val := int64(0)

		tmp := int64(m) % k
		for i := 0; i < int(tmp); i++ {
			val += A[i]
		}
		num := int64(m) / k
		i := m-1
		for num > 0 {
			val += A[i]
			i -= int(k)

			num--
		}

		pp := p - val
		if pp >= 0 {
			return true
		}
		return false
	}

	ng, ok := int(n+1), 0
	for int(math.Abs(float64(ok-ng))) > 1 {
		mid := (ok + ng) / 2
		if isOK(mid) {
			ok = mid
		} else {
			ng = mid
		}
	}

	fmt.Println(ok)
}

type Int64List []int64

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

// S := Int64List{'a', 'b', 'c'}
// sort.Sort(S) or sort.Sort(sort.Reverse(S))

/*
- まずは全探索を検討しましょう
- MODは最後にとりましたか？
- ループを抜けた後も処理が必要じゃありませんか？
- 和・積・あまりを求められたらint64が必要ではありませんか？
- いきなりオーバーフローはしていませんか？
- MOD取る系はint64必須ですよ？
*/

/*
ASCII code

ASCII   10進数  ASCII   10進数  ASCII   10進数
!       33      "       34      #       35
$       36      %       37      &       38
'       39      (       40      )       41
*       42      +       43      ,       44
-       45      .       46      /       47
0       48      1       49      2       50
3       51      4       52      5       53
6       54      7       55      8       56
9       57      :       58      ;       59
<       60      =       61      >       62
?       63      @       64      A       65
B       66      C       67      D       68
E       69      F       70      G       71
H       72      I       73      J       74
K       75      L       76      M       77
N       78      O       79      P       80
Q       81      R       82      S       83
T       84      U       85      V       86
W       87      X       88      Y       89
Z       90      [       91      \       92
]       93      ^       94      _       95
`       96      a       97      b       98
c       99      d       100     e       101
f       102     g       103     h       104
i       105     j       106     k       107
l       108     m       109     n       110
o       111     p       112     q       113
r       114     s       115     t       116
u       117     v       118     w       119
x       120     y       121     z       122
{       123     |       124     }       125
~       126             127
*/

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

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := int64(1)
	fmt.Fscanf(in, "%d\n", &t)
	for tt := int64(0); tt < t; tt++ {
		n, p, k := 0, 0, 0
		fmt.Fscanf(in, "%d %d %d\n", &n, &p, &k)
		a := make([]int, n)
		f := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscanf(in, "%d", &a[i])
		}
		sort.Ints(a)
		fmt.Fscanf(in, "\n")
		f[0] = a[0]
		ans := 0
		if f[0] <= p {
			ans = 1
		}
		for i := 1; i < n; i++ {
			if (i + 1) < k {
				f[i] = f[i-1] + a[i]
			} else if (i + 1) == k {
				f[i] = a[i]
			} else {
				f[i] = f[i-k] + a[i]
			}
			if f[i] <= p {
				ans = i + 1
			}
		}
		// l := 0
		// r := n
		// for l < r {
		// 	mid := (l + r + 1) / 2
		// 	cost := 0
		// 	need := mid / k
		// 	if mid%k != 0 {
		// 		need++
		// 	}
		// 	cur := mid%k - 1
		// 	if cur < 0 {
		// 		cur += k
		// 	}
		// 	for i := 0; i < need; i++ {
		// 		cost += a[cur]
		// 		cur += k
		// 	}
		// 	if cost > p {
		// 		r = mid - 1
		// 	} else {
		// 		l = mid
		// 	}
		// }
		fmt.Fprintf(out, "%d\n", ans)
	}
	return
}

func same(s string, ss string) bool {
	a := make([]int, 26)
	for i := 0; i < len(s); i++ {
		b := int(s[i] - 'a')
		a[b]++
	}
	for i := 0; i < len(ss); i++ {
		b := int(ss[i] - 'a')
		a[b]--
		if a[b] == -1 {
			return false
		}
	}
	for i := 0; i < 26; i++ {
		if a[i] != 0 {
			return false
		}
	}
	return true
}

package main

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

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

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

func init() {
	ReadString = newReadString(os.Stdin)
	stdout = bufio.NewWriter(os.Stdout)
}

func newReadString(ior io.Reader) func() string {
	r := bufio.NewScanner(ior)
	// r.Buffer(make([]byte, 1024), int(1e+11)) // for AtCoder
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	// Split sets the split function for the Scanner. The default split function is ScanLines.
	// Split panics if it is called after scanning has started.
	r.Split(bufio.ScanWords)

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

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

/********** 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 MOD = 1000000000 + 7
const ALPHABET_NUM = 26
const INF_INT64 = math.MaxInt64
const INF_BIT60 = 1 << 60
const INF_INT32 = math.MaxInt32
const INF_BIT30 = 1 << 30

var t int
var n, p, k int64
var A []int64

func main() {
	t = ReadInt()

	for tc := 0; tc < t; tc++ {
		n, p, k = ReadInt64_3()
		A = ReadInt64Slice(int(n))

		solve()
	}
}

func solve() {
	sort.Sort(Int64List(A))

	// m は中央を意味する何らかの値
	isOK := func(m int) bool {
		val := int64(0)
		for i := 0; i < m-2; i++ {
			val += A[i]
		}
		pp := p - val

		if pp >= A[m-1] {
			return true
		}
		return false
	}

	ng, ok := int(n+1), 0
	for int(math.Abs(float64(ok-ng))) > 1 {
		mid := (ok + ng) / 2
		if isOK(mid) {
			ok = mid
		} else {
			ng = mid
		}
	}

	fmt.Println(ok)
}

type Int64List []int64

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

// S := Int64List{'a', 'b', 'c'}
// sort.Sort(S) or sort.Sort(sort.Reverse(S))

/*
- まずは全探索を検討しましょう
- MODは最後にとりましたか？
- ループを抜けた後も処理が必要じゃありませんか？
- 和・積・あまりを求められたらint64が必要ではありませんか？
- いきなりオーバーフローはしていませんか？
- MOD取る系はint64必須ですよ？
*/

/*
ASCII code

ASCII   10進数  ASCII   10進数  ASCII   10進数
!       33      "       34      #       35
$       36      %       37      &       38
'       39      (       40      )       41
*       42      +       43      ,       44
-       45      .       46      /       47
0       48      1       49      2       50
3       51      4       52      5       53
6       54      7       55      8       56
9       57      :       58      ;       59
<       60      =       61      >       62
?       63      @       64      A       65
B       66      C       67      D       68
E       69      F       70      G       71
H       72      I       73      J       74
K       75      L       76      M       77
N       78      O       79      P       80
Q       81      R       82      S       83
T       84      U       85      V       86
W       87      X       88      Y       89
Z       90      [       91      \       92
]       93      ^       94      _       95
`       96      a       97      b       98
c       99      d       100     e       101
f       102     g       103     h       104
i       105     j       106     k       107
l       108     m       109     n       110
o       111     p       112     q       113
r       114     s       115     t       116
u       117     v       118     w       119
x       120     y       121     z       122
{       123     |       124     }       125
~       126             127
*/

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


The winter in Berland lasts n days. For each day we know the forecast for the average air temperature that day. Vasya has a new set of winter tires which allows him to drive safely no more than k days at any average air temperature. After k days of using it (regardless of the temperature of these days) the set of winter tires wears down and cannot be used more. It is not necessary that these k days form a continuous segment of days.Before the first winter day Vasya still uses summer tires. It is possible to drive safely on summer tires any number of days when the average air temperature is non-negative. It is impossible to drive on summer tires at days when the average air temperature is negative. Vasya can change summer tires to winter tires and vice versa at the beginning of any day.Find the minimum number of times Vasya needs to change summer tires to winter tires and vice versa to drive safely during the winter. At the end of the winter the car can be with any set of tires.

The first line contains two positive integers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — the number of winter days and the number of days winter tires can be used. It is allowed to drive on winter tires at any temperature, but no more than k days in total. The second line contains a sequence of n integers t1, t2, ..., tn ( - 20 ≤ ti ≤ 20) — the average air temperature in the i-th winter day.

Print the minimum number of times Vasya has to change summer tires to winter tires and vice versa to drive safely during all winter. If it is impossible, print -1.

NoteIn the first example before the first winter day Vasya should change summer tires to winter tires, use it for three days, and then change winter tires to summer tires because he can drive safely with the winter tires for just three days. Thus, the total number of tires' changes equals two. In the second example before the first winter day Vasya should change summer tires to winter tires, and then after the first winter day change winter tires to summer tires. After the second day it is necessary to change summer tires to winter tires again, and after the third day it is necessary to change winter tires to summer tires. Thus, the total number of tires' changes equals four.

package main

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

func calc(pos []int, k int) (int, bool) {
    res, ok := 2*len(pos)+1, k >= 0
    for _, v := range pos {
        if v <= k {
            res -= 2
            k -= v
        }
    }
    return res, ok
}

func solve() {
    n, k := readInt(), readInt()
    a := []int{}
    start, negCnt := -1, 0
    for i, v := range readIntArray(n) {
        if v < 0 {
            negCnt++
            if i > start && start > 0 {
                a = append(a, i-start)
            }
            start = i+1
        }
    }
    sort.Ints(a)
    k -= negCnt
    last := n-start
    ans := -1
    if negCnt == 0 && k >= 0 {
        ans = 0
    }
    if cnt, ok := calc(a, k-last); ok {
        ans = cnt
    }
    if cnt, ok := calc(a, k); ok && (ans == -1 || cnt+1 < ans) {
        ans = cnt+1
    }
    fmt.Println(ans)
}

// Helpers

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

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

// Math

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

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

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

// IO

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

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

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

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

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

// Sort

type Ints64 []int64

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

/* Sort template
func (a ) Len() int           { return len(a) }
func (a ) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ) Less(i, j int) bool { return  }
*/

package main

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

func calc(pos []int, k int) (int, bool) {
    res, ok := 2*len(pos)+1, k >= 0
    for _, v := range pos {
        if v <= k {
            res -= 2
            k -= v
        }
    }
    return res, ok
}

func solve() {
    n, k := readInt(), readInt()
    a := make([]int, n)
    start, negCnt := -1, 0
    for i, v := range readIntArray(n) {
        if v < 0 {
            negCnt++
            if i > start && start > 0 {
                a = append(a, i-start)
            }
            start = i+1
        }
    }
    sort.Ints(a)
    k -= negCnt
    last := n-start
    ans := -1
    if cnt, ok := calc(a, k-last); ok {
        ans = cnt
    }
    if cnt, ok := calc(a, k); ok && (ans == -1 || cnt+1 < ans) {
        ans = cnt+1
    }
    fmt.Println(ans)
}

// Helpers

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

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

// Math

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

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

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

// IO

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

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

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

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

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

// Sort

type Ints64 []int64

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

/* Sort template
func (a ) Len() int           { return len(a) }
func (a ) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ) Less(i, j int) bool { return  }
*/

package main

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

func calc(pos []int, k int) (int, bool) {
    res, ok := 2*len(pos)+1, k >= 0
    if len(pos) == 0 {
        res = 0
    }
    for _, v := range pos {
        if v <= k {
            res -= 2
            k -= v
        }
    }
    return res, ok
}

func solve() {
    n, k := readInt(), readInt()
    a := []int{}
    start, negCnt := -1, 0
    for i, v := range readIntArray(n) {
        if v < 0 {
            negCnt++
            if i > start && start > 0 {
                a = append(a, i-start)
            }
            start = i+1
        }
    }
    sort.Ints(a)
    k -= negCnt
    last := n-start
    ans := -1
    if cnt, ok := calc(a, k-last); ok {
        ans = cnt
    }
    if cnt, ok := calc(a, k); ok && (ans == -1 || cnt+1 < ans) {
        ans = cnt+1
    }
    fmt.Println(ans)
}

// Helpers

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

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

// Math

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

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

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

// IO

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

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

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

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

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

// Sort

type Ints64 []int64

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

/* Sort template
func (a ) Len() int           { return len(a) }
func (a ) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ) Less(i, j int) bool { return  }
*/

package main

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

func calc(pos []int, k int) (int, bool) {
    if len(pos) == 0 {
        return 0, true
    }
    res, ok := 2*len(pos)+1, k >= 0
    for _, v := range pos {
        if v <= k {
            res -= 2
            k -= v
        }
    }
    return res, ok
}

func solve() {
    n, k := readInt(), readInt()
    a := []int{}
    start, negCnt := -1, 0
    for i, v := range readIntArray(n) {
        if v < 0 {
            negCnt++
            if i > start && start > 0 {
                a = append(a, i-start)
            }
            start = i+1
        }
    }
    sort.Ints(a)
    k -= negCnt
    last := n-start
    ans := -1
    if cnt, ok := calc(a, k-last); ok {
        ans = cnt
    }
    if cnt, ok := calc(a, k); ok && (ans == -1 || cnt+1 < ans) {
        ans = cnt+1
    }
    fmt.Println(ans)
}

// Helpers

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

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

// Math

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

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

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

// IO

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

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

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

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

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

// Sort

type Ints64 []int64

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

/* Sort template
func (a ) Len() int           { return len(a) }
func (a ) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ) Less(i, j int) bool { return  }
*/


There are some beautiful girls in Arpa’s land as mentioned before.Once Arpa came up with an obvious problem:Given an array and a number x, count the number of pairs of indices i, j (1 ≤ i < j ≤ n) such that , where  is bitwise xor operation (see notes for explanation).  Immediately, Mehrdad discovered a terrible solution that nobody trusted. Now Arpa needs your help to implement the solution to that problem.

First line contains two integers n and x (1 ≤ n ≤ 105, 0 ≤ x ≤ 105) — the number of elements in the array and the integer x. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the elements of the array.

Print a single integer: the answer to the problem.

NoteIn the first sample there is only one pair of i = 1 and j = 2.  so the answer is 1.In the second sample the only two pairs are i = 3, j = 4 (since ) and i = 1, j = 5 (since ).A bitwise xor takes two bit integers of equal length and performs the logical xor operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. You can read more about bitwise xor operation here: https://en.wikipedia.org/wiki/Bitwise_operation#XOR.

package main

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

func main() {
	reader := bufio.NewReaderSize(os.Stdin, 1<<13)
	writer := bufio.NewWriterSize(os.Stdout, 1<<13)
	n, x := ReadInt(reader), ReadInt(reader)
	count := make([]int64, 2e5)
	res := int64(0)
	for i := 0; i < n; i++ {
		a := ReadInt(reader)
		wanted := a ^ x
		if wanted < len(count) {
			res += count[wanted]
		}
		count[a]++
	}
	fmt.Fprintln(writer, res)
	writer.Flush()
}

func ReadInt(reader *bufio.Reader) int {
	return int(ReadInt64(reader))
}

func ReadInt64(reader *bufio.Reader) int64 {
	b, err := reader.ReadByte()
	for !isValid(b, err) {
		b, err = reader.ReadByte()
	}
	sign := int64(1)
	if b == '-' {
		sign *= -1
		b, err = reader.ReadByte()
	}
	res := int64(0)
	for isValid(b, err) {
		res = res*10 + int64(b-'0')
		b, err = reader.ReadByte()
	}
	return res * sign
}

func isValid(b byte, err error) bool {
	return err == nil && (('0' <= b && b <= '9') || b == '-')
}

package main

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

func solve() {
    n, x := readInt(), readInt()
    a := readIntArray(n)
    cnts := make(map[int]int)
    for _, v := range a {
        cnts[v]++
    }
    ans := int64(0)
    for _, v := range a {
        b := v^x
        cnt := cnts[b]
        if b == v {
            cnt--
        }
        ans += int64(cnt)
    }
    fmt.Println(ans/2)
}

// Helpers

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

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

// Math

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

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

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

// IO

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

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

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

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

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

// Sort

type Ints64 []int64

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

/* Sort tempalte
func (a ) Len() int           { return len(a) }
func (a ) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ) Less(i, j int) bool { return  }
*/

package main

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

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

const maxa = 300000

var n, x, a int
var cnt []int

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

	fmt.Fscanf(bufin, "%d %d\n", &n, &x)

	cnt = make([]int, maxa+1)
	r := int64(0)

	for i := 1; i <= n; i++ {
		fmt.Fscanf(bufin, "%d\n", &a)
		b := x ^ a
		if b <= maxa {
			r += int64(cnt[b])
		}
		cnt[a]++
	}

	fmt.Fprintf(bufout, "%d\n", r)
}

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"runtime"
	"strings"
)

func main() {
	b, _ := ioutil.ReadAll(os.Stdin)
	if len(b) == 0 {
		test()
	} else {
		solve(bytes.NewReader(b), os.Stdout)
	}
}

func solve(r io.Reader, w io.Writer) {
	var n, x int
	fmt.Fscanln(r, &n, &x)

	ans := uint64(0)
	am := make(map[int]int, n) // a -> cnt
	for i := 0; i < n; i++ {
		var a int
		fmt.Fscan(r, &a)
		want := a ^ x
		if cnt, ok := am[want]; ok && cnt > 0 {
			ans += uint64(cnt)
		}
		am[a]++
	}

	fmt.Fprintln(w, ans)
}

func test() {
	tests := []struct {
		in   string
		want string
	}{
		{
			in: `
2 3
1 2
`,
			want: `1`,
		},
		{
			in: `
6 1
5 1 2 3 4 1
`,
			want: `2`,
		},
		{
			in: `
6 0
5 1 2 2 5 1
`,
			want: `3`,
		},
		{
			in: `
4 0
1 1 1 1
`,
			want: `6`,
		},
	}
	for i, tt := range tests {
		fmt.Printf("=== TEST %d\n", i)
		buf := new(bytes.Buffer)
		solve(strings.NewReader(chomp(tt.in)), buf)
		if got, want := chomp(buf.String()), chomp(tt.want); got != want {
			fmt.Printf("%d: got %v, want %v\n", i, got, want)
		}
	}
}

func chomp(s string) string {
	return strings.Trim(s, "\n")
}

func assert(b bool) {
	if !b {
		_, file, line, ok := runtime.Caller(1)
		if ok {
			f, _ := os.Open(file)
			defer f.Close()
			s := bufio.NewScanner(f)
			lnum := 0
			for s.Scan() {
				lnum++
				if lnum == line {
					wd, _ := os.Getwd()
					fname, _ := filepath.Rel(wd, file)
					fmt.Printf("assertion fails: %s:%d: %v\n", fname, line, s.Text())
					break
				}
			}
		}
	}
}

func pow(a, b int) int {
	r := 1
	for i := 0; i < b; i++ {
		r *= a
	}
	return r
}

/*
URL:
https://codeforces.com/problemset/problem/742/B
*/

package main

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"math"
	"os"
	"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
	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, x int
	A    []int

	memo [1000000 + 50]int
)

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

	for i := 0; i < n; i++ {
		val := A[i] ^ x
		memo[val]++
	}

	ans := int64(0)
	for i := 0; i < n; i++ {
		if A[i]^x != A[i] {
			ans += int64(memo[A[i]])
		} else {
			ans += int64(memo[A[i]] - 1)
		}

		memo[A[i]^x]--
	}
	fmt.Println(ans)
}

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

/*********** 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 (
	"strconv"
	"bufio"
	"os"
	"sort"
	"fmt"
)

func main() {
	sc := NewScanner()
	_, x := sc.NextInt(), sc.NextInt()
	mp := map[int]int{}

	a := sc.NextIntArray()
	for _, v := range a {
		mp[v] += 1
	}
	b := make([]int, 0, len(mp))
	count := int64(0)
	for k, _ := range mp {
		b = append(b, k)
		if k ^ k == x {
			count += int64(mp[k]) * int64(mp[k] - 1) / 2
		}
	}
	sort.Ints(b)

	for i := 0; i < len(b) - 1; i++ {
		c := b[i + 1:]
		k := sort.SearchInts(c, b[i] ^ x)
		if k < len(c) && c[k] == b[i] ^ x {
			count += int64(mp[b[i]]) * int64(mp[c[k]])
		}
	}
	fmt.Println(count)

}

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

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

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

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

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

	return mp
}

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

package main

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

func main() {
	b, _ := ioutil.ReadAll(os.Stdin)
	r := bytes.NewReader(b)

	var n, x int
	fmt.Fscanf(r, "%d %d\n", &n, &x)
	a := make([]int64, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(r, "%d", &a[i])
	}

	cnt := make(map[int64]int64)
	ans := int64(0)
	for j, _ := range a {
		ans += cnt[int64(x)^a[j]]
		cnt[a[j]]++
	}
	fmt.Println(ans)
}

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"runtime"
	"strings"
)

func main() {
	b, _ := ioutil.ReadAll(os.Stdin)
	if len(b) == 0 {
		test()
	} else {
		solve(bytes.NewReader(b), os.Stdout)
	}
}

func solve(r io.Reader, w io.Writer) {
	var n, x int
	fmt.Fscanln(r, &n, &x)
	am := make(map[int]int, n)
	for i := 0; i < n; i++ {
		var a int
		fmt.Fscan(r, &a)
		am[a]++
	}

	ans := 0

	isZero := 0
	if x == 0 {
		isZero = 1
	}

	for a, cnta := range am {
		if cnta < 1 {
			continue
		}
		want := a ^ x
		if cntw, ok := am[want]; ok && cntw > isZero {
			ans++
			am[want]--
			am[a]--
		}
	}

	fmt.Fprintln(w, ans)
}

func test() {
	tests := []struct {
		in   string
		want string
	}{
		{
			in: `
2 3
1 2
`,
			want: `1`,
		},
		{
			in: `
6 1
5 1 2 3 4 1
`,
			want: `2`,
		},
		{
			in: `
6 0
5 1 2 2 5 1
`,
			want: `3`,
		},
	}
	for i, tt := range tests {
		fmt.Printf("=== TEST %d\n", i)
		buf := new(bytes.Buffer)
		solve(strings.NewReader(chomp(tt.in)), buf)
		if got, want := chomp(buf.String()), chomp(tt.want); got != want {
			fmt.Printf("%d: got %v, want %v\n", i, got, want)
		}
	}
}

func chomp(s string) string {
	return strings.Trim(s, "\n")
}

func assert(b bool) {
	if !b {
		_, file, line, ok := runtime.Caller(1)
		if ok {
			f, _ := os.Open(file)
			defer f.Close()
			s := bufio.NewScanner(f)
			lnum := 0
			for s.Scan() {
				lnum++
				if lnum == line {
					wd, _ := os.Getwd()
					fname, _ := filepath.Rel(wd, file)
					fmt.Printf("assertion fails: %s:%d: %v\n", fname, line, s.Text())
					break
				}
			}
		}
	}
}

func pow(a, b int) int {
	r := 1
	for i := 0; i < b; i++ {
		r *= a
	}
	return r
}

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"runtime"
	"strings"
)

func main() {
	b, _ := ioutil.ReadAll(os.Stdin)
	if len(b) == 0 {
		test()
	} else {
		solve(bytes.NewReader(b), os.Stdout)
	}
}

func solve(r io.Reader, w io.Writer) {
	var n, x int
	fmt.Fscanln(r, &n, &x)

	ans := 0
	am := make(map[int]int, n) // a -> cnt
	for i := 0; i < n; i++ {
		var a int
		fmt.Fscan(r, &a)
		want := a ^ x
		if cnt, ok := am[want]; ok && cnt > 0 {
			ans += cnt
		}
		am[a]++
	}

	fmt.Fprintln(w, ans)
}

func test() {
	tests := []struct {
		in   string
		want string
	}{
		{
			in: `
2 3
1 2
`,
			want: `1`,
		},
		{
			in: `
6 1
5 1 2 3 4 1
`,
			want: `2`,
		},
		{
			in: `
6 0
5 1 2 2 5 1
`,
			want: `3`,
		},
		{
			in: `
4 0
1 1 1 1
`,
			want: `6`,
		},
	}
	for i, tt := range tests {
		fmt.Printf("=== TEST %d\n", i)
		buf := new(bytes.Buffer)
		solve(strings.NewReader(chomp(tt.in)), buf)
		if got, want := chomp(buf.String()), chomp(tt.want); got != want {
			fmt.Printf("%d: got %v, want %v\n", i, got, want)
		}
	}
}

func chomp(s string) string {
	return strings.Trim(s, "\n")
}

func assert(b bool) {
	if !b {
		_, file, line, ok := runtime.Caller(1)
		if ok {
			f, _ := os.Open(file)
			defer f.Close()
			s := bufio.NewScanner(f)
			lnum := 0
			for s.Scan() {
				lnum++
				if lnum == line {
					wd, _ := os.Getwd()
					fname, _ := filepath.Rel(wd, file)
					fmt.Printf("assertion fails: %s:%d: %v\n", fname, line, s.Text())
					break
				}
			}
		}
	}
}

func pow(a, b int) int {
	r := 1
	for i := 0; i < b; i++ {
		r *= a
	}
	return r
}

/*
URL:
https://codeforces.com/problemset/problem/742/B
*/

package main

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"math"
	"os"
	"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
	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, x int
	A    []int

	memo [1000000 + 50]int
)

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

	for i := 0; i < n; i++ {
		val := A[i] ^ x
		memo[val]++
	}

	ans := int64(0)
	for i := 0; i < n; i++ {
		ans += int64(memo[A[i]])

		memo[A[i]^x]--
	}
	fmt.Println(ans)
}

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

/*********** 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 (
	"strconv"
	"bufio"
	"os"
	"sort"
	"fmt"
)

func main() {
	sc := NewScanner()
	_, x := sc.NextInt(), sc.NextInt()
	mp := map[int]int{}

	a := sc.NextIntArray()
	for _, v := range a {
		mp[v] += 1
	}
	b := make([]int, 0, len(mp))
	count := int64(0)
	for k, _ := range mp {
		b = append(b, k)
		if k ^ k == x {
			count += int64(mp[k]) * int64(mp[k] - 1) / 2
		}
	}
	for i := 0; i < len(b) - 1; i++ {
		c := b[i + 1:]
		k := sort.SearchInts(c, b[i] ^ x)
		if k < len(c) && c[k] == b[i] ^ x {
			count += int64(mp[b[i]]) * int64(mp[c[k]])
		}
	}
	fmt.Println(count)

}

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

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

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

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

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

	return mp
}

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

package main

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

func main() {
	sc := NewScanner()
	_, x := sc.NextInt(), sc.NextInt()
	mp := map[int]int{}

	a := sc.NextIntArray()
	for _, v := range a {
		mp[v] += 1
	}
	b := make([]int, 0, len(mp))
	count := 0
	for k, _ := range mp {
		b = append(b, k)
		if k ^ k == x {
			count += mp[k] * (mp[k] + 1) / 2
		}
	}
	for i := 0; i < len(b) - 1; i++ {
		c := b[i + 1:]
		k := sort.SearchInts(c, b[i] ^ x)
		if k < len(c) && c[k] == b[i] ^ x {
			count += mp[b[i]] * mp[c[k]]
		}
	}
	fmt.Println(count)

}

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

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

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

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

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

	return mp
}

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

package main

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

func main() {
	sc := NewScanner()
	_, x := sc.NextInt(), sc.NextInt()
	mp := map[int]int{}

	a := sc.NextIntArray()
	for _, v := range a {
		mp[v] += 1
	}
	b := make([]int, 0, len(mp))
	count := 0
	for k, _ := range mp {
		b = append(b, k)
		if k ^ k == x {
			count += mp[k] * (mp[k] - 1) / 2
		}
	}
	for i := 0; i < len(b) - 1; i++ {
		c := b[i + 1:]
		k := sort.SearchInts(c, b[i] ^ x)
		if k < len(c) && c[k] == b[i] ^ x {
			count += mp[b[i]] * mp[c[k]]
		}
	}
	fmt.Println(count)

}

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

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

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

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

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

	return mp
}

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

package main

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

func main() {
	sc := NewScanner()
	n, x := sc.NextInt(), sc.NextInt()
	a := sc.NextIntArray()
	sort.Ints(a)

	count := 0
	for i := 0; i < n; i++ {
		k := sort.SearchInts(a, a[i] ^ x)
		if i < k && k < n&& a[k] == a[i] ^ x {
			count++
		}
	}
	fmt.Println(count)

}

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

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

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

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

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

	return mp
}

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

package main

import "fmt"

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

	cnt := make(map[int]int)
	ans := 0
	for j, _ := range a {
		ans += cnt[x^a[j]]
		cnt[a[j]]++
	}
	fmt.Println(ans)
}