The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.

The first line contains an integer n (1 ≤ n ≤ 100) — the number of boys. The second line contains sequence a1, a2, ..., an (1 ≤ ai ≤ 100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1 ≤ m ≤ 100) — the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≤ bj ≤ 100), where bj is the j-th girl's dancing skill.

Print a single number — the required maximum possible number of pairs.

// http://codeforces.com/contest/489/problem/B
package main

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

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

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

	return b
}

func main () {
	var (
		n,m int
		size int = 105
	)

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

	u := make([]int, size)
	v := make([]int, size)

	fmt.Fscan(input, &n)
	for i := 0; i < n; i++ {
		var tmp int
		fmt.Fscan(input, &tmp)
		u[tmp]++
	}

	fmt.Fscan(input, &m)
	for i := 0; i < m; i++ {
		var tmp int
		fmt.Fscan(input, &tmp)
		v[tmp]++
	}

	// Solve
	ans := 0
	for i := 0; i < size; i++ {
		d := min(u[i], v[i])

		u[i] -= d
		v[i] -= d
		ans += d

		if u[i] > 0 {
			d = min(u[i], v[i + 1])
			u[i] -= d
			v[i + 1] -= d
			ans += d
		}

		if v[i] > 0 {
			d = min(v[i], u[i + 1])
			v[i] -= d
			u[i + 1] -= d
			ans += d
		}
	}

	fmt.Println(ans)
}

package main;

import (
	"fmt"
	// "math"
)

var G [][]int;
var arr1, arr2 []int;
var n, m int;

var Rmatch []int;
var vis []bool;

func match(u int) bool {
	if (vis[u]) { return false; }
	vis[u] = true;
	for _, v := range G[u] {
		if (Rmatch[v] == -1 || match(Rmatch[v])) {
			Rmatch[v] = u;
			return true;
		}
	}
	return false;
}

func solve() int {
	var ret int = 0;
	vis = make([]bool, n)
	Rmatch = make([]int, m)
	for i := range Rmatch { Rmatch[i] = -1; }
	for i := 0; i < n; i++ {
		for j := range vis { vis[j] = false; }
		if match(i) { ret++; }
	}
	return ret;
}

func main() {
	fmt.Scanf("%d\n",&n);
	arr1 = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d",&arr1[i])
	}
	fmt.Scanf("\n%d\n",&m);
	arr2 = make([]int, m)
	for i := 0; i < m; i++ {
		fmt.Scanf("%d",&arr2[i])
	}
	G = make([][]int, n);
	for i := range arr1 {
		for j := range arr2 {
			if arr1[i] >= arr2[j] - 1 && arr1[i] <= arr2[j] + 1 {
				G[i] = append(G[i], j);
			}
		}
	}
	var matching int = solve()
	fmt.Println(matching)
}

package main

import (
            "fmt"
            "sort"
        )

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

    fmt.Scanln()

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

    sort.Ints(a)
    sort.Ints(b)

    var answer, free int

    for i := 0; i < n; i++ {
        for j := free; j < m; j++ {
            var diff int = b[j] - a[i]
            // For a[i] we dont have pair
            if diff > 1 {
                break
            }

            if diff == 1 || diff == 0 || diff == -1 {
                free = j + 1
                answer++
                break
            }
        }
    }

    fmt.Println(answer)
}

package main

import (
	"fmt"
	"sort"
)

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

	fmt.Scan(&m)
	b := make([]int, m)
	for i := 0; i < m; i++ {
		var bi int
		fmt.Scan(&bi)
		b[i] = bi
	}
	sort.Sort(sort.IntSlice(a))
	sort.Sort(sort.IntSlice(b))

	c := 0
	for i, j := 0, 0; i < n && j < m; {
		if a[i] < b[j]-1 {
			i++
			continue
		}
		if b[j] < a[i]-1 {
			j++
			continue
		}
		if a[i] == b[j] || a[i] == b[j]+1 || a[i] == b[j]-1 {
			i++
			j++
			c++
			continue
		}
	}
	fmt.Println(c)
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n, m, res int

	fmt.Scan(&n)

	a := make([]int, n)

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

	fmt.Scan(&m)

	b := make([]int, m)

	for i := 0; i < m; i++ {
		fmt.Scan(&b[i])
	}

	sort.Ints(a)
	sort.Ints(b)

	p := -1

	for i := 0; i < len(a); i++ {
		for j := p + 1; j < len(b); j++ {
			if a[i] == b[j] || a[i]+1 == b[j] || a[i]-1 == b[j] {
				p = j
				res++
				break
			}
		}
	}

	fmt.Println(res)
}

package main

import (
	"fmt"
	"math"
	"sort"
)

func main() {
	var n, m, res int

	fmt.Scan(&n)

	a := make([]int, n)

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

	fmt.Scan(&m)

	b := make([]int, m)

	for i := 0; i < m; i++ {
		fmt.Scan(&b[i])
	}

	sort.Ints(a)
	sort.Ints(b)

	p := -1

	for i := 0; i < len(a); i++ {
		for j := p + 1; j < len(b); j++ {
			if math.Abs(float64(a[i])-float64(b[j])) <= 1 {
				p = j
				res++
				break
			}
		}
	}

	fmt.Println(res)
}

package main

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

const MAXN = 100 + 10
var used ,math ,A,B  [MAXN]int
var G [MAXN][MAXN]int
var n ,m int

func abs(x int) int {

    var ret int
    if x >= 0 {

        ret = x
    }else {
        ret = -x
    }
    return ret
}

func  Find(x int)   bool {

    for i := 1;i <= m; i ++ {

        if 1 == G[x][i] && 0 == ( used[i]) {

            used[i] = 1
            if -1 == math[i] || Find(math[i]){
                math[i] = x
                return true

            }
        }
    }

    return false
}
func build() int {

    for i := 0 ;i <= n; i ++ {
        for j := 0 ;j <= m; j ++ {
            G[i][j] = 0
            math[j] = -1
            used[j] = 0
        }
    }
    for i := 1;i <= n; i ++ {

        for j := 1;j <= m; j ++ {

            if abs(A[i] - B[j]) <= 1 {
                G[i][j] = 1
            }
        }
    }
    ret := 0
    for i := 1;i <= n; i ++ {
        for j := 1;j <= m;j ++ {
            used[j] = 0
        }
        if Find(i) {
            ret ++
        }
    }
    return ret
}

func main(){

    reader := bufio.NewReader(os.Stdin)
    fmt.Fscan(reader,&n)
    for i := 1; i<= n;i ++ {
        fmt.Fscan(reader,&A[i])
    }
    fmt.Fscan(reader,&m)
    for i := 1;i <= m; i ++ {
        fmt.Fscan(reader,&B[i])
    }
    ans := build()
    fmt.Printf("%d\n",ans)

}

package main

import (
	"fmt"
	"math"
	"sort"
)

type mySlice []int

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

func main() {
	var nBoys, nGirls int
	fmt.Scan(&nBoys)
	boys := make(mySlice, nBoys)
	for i := 0; i < nBoys; i++ {
		fmt.Scan(&boys[i])
	}
	fmt.Scan(&nGirls)
	girls := make(mySlice, nGirls)
	for i := 0; i < nGirls; i++ {
		fmt.Scan(&girls[i])
	}

	cont := 0
	sort.Sort(boys)
	sort.Sort(girls)

	for _, boy := range boys {
		for j, girl := range girls {
			if math.Abs(float64(boy)-float64(girl)) < 2 {
				cont++
				girls[j] = -1000
				break
			}
		}
	}

	fmt.Print(cont)
}

package main

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

var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)
var _ = fmt.Println

type IntSorter struct {
	data []int
}
func (s *IntSorter) Len() int { return len(s.data) }
func (s *IntSorter) Swap(i, j int) { s.data[i], s.data[j] = s.data[j], s.data[i] }
func (s *IntSorter) Less(i, j int) bool { return s.data[i] < s.data[j] }

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

	N := ReadInt32()
	boys := make([]int, N)
	for i := 0; i < N; i += 1 {
		boys[i] = ReadInt32()
	}

	M := ReadInt32()
	girls := make([]int, M)
	for i := 0; i < M; i += 1 {
		girls[i] = ReadInt32()
	}

	bSorter := &IntSorter{ boys }
	gSorter := &IntSorter{ girls }
	sort.Sort(bSorter)
	sort.Sort(gSorter)
	boys, girls = bSorter.data, gSorter.data

	bi, gi := 0, 0
	matches := 0
	for bi < N && gi < M {
		if boys[bi] == girls[gi] || boys[bi] - girls[gi] == -1 || boys[bi] - girls[gi] == 1 {
			matches++
			bi++
			gi++
			continue
		}
		if boys[bi] > girls[gi] {
			gi++
		} else {
			bi++
		}
	}
	PrintInts(matches)
}

func ReadInt32() int {
	scanner.Scan()
	ans, _ := strconv.Atoi(scanner.Text())
	return ans
}

func PrintInts(ints ...int) {
	for _, value := range ints {
		writer.WriteString(strconv.Itoa(value))
		writer.WriteByte(' ')
	}
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n, m int
	fmt.Scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}
	fmt.Scan(&m)
	b := make([]int, m)
	for i := 0; i < m; i++ {
		fmt.Scan(&b[i])
	}
	sort.Ints(a)
	sort.Ints(b)
	res := 0
	for i, j := 0, 0; i < n && j < m; {
		switch {
		case a[i]+1 < b[j]:
			i++
		case b[j]+1 < a[i]:
			j++
		default:
			res++
			i++
			j++
		}
	}
	fmt.Println(res)
}

package main

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

var reader *bufio.Reader

func init() {
	stdin := os.Stdin
	// stdin, _ = os.Open("1.in")
	reader = bufio.NewReaderSize(stdin, 1<<20)
}

var n, m int
var a, b []int

func main() {
	fmt.Fscan(reader, &n)
	a = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &a[i])
	}
	fmt.Fscan(reader, &m)
	b = make([]int, m)
	for i := 0; i < m; i++ {
		fmt.Fscan(reader, &b[i])
	}
	var bipartite Bipartite
	bipartite.Init(n + m)
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			if math.Abs(float64(a[i]-b[j])) <= 1 {
				bipartite.AddEdge(i, n+j)
			}
		}
	}
	fmt.Println(bipartite.BipartiteMatching())
}

// Bipartite 二分图
type Bipartite struct {
	V     int
	G     [][]int
	Match []int
	Used  []bool
}

// Init 初始化数组
func (r *Bipartite) Init(n int) {
	r.V = n
	r.G = make([][]int, n)
	r.Match = make([]int, n)
	r.Used = make([]bool, n)
}

// AddEdge 向图中添加一条连接u，v的边
func (r *Bipartite) AddEdge(u, v int) {
	r.G[u] = append(r.G[u], v)
	r.G[v] = append(r.G[v], u)
}

// DFS 通过DFS寻找增广路
func (r *Bipartite) DFS(v int) bool {
	r.Used[v] = true
	for i := 0; i < len(r.G[v]); i++ {
		u := r.G[v][i]
		w := r.Match[u]
		if w < 0 || !r.Used[w] && r.DFS(w) {
			r.Match[v] = u
			r.Match[u] = v
			return true
		}
	}
	return false
}

// BipartiteMatching 求解二分图的最大匹配
func (r *Bipartite) BipartiteMatching() (res int) {
	for i := 0; i < len(r.Match); i++ {
		r.Match[i] = -1
	}
	for v := 0; v < r.V; v++ {
		if r.Match[v] < 0 {
			for i := 0; i < len(r.Used); i++ {
				r.Used[i] = false
			}
			if r.DFS(v) {
				res++
			}
		}
	}
	return
}

package main

import (
    "fmt"
    "sort"
    )

func main() {
    var n, m int

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

    fmt.Scan(&m)
    girls := make([]int, m, m)
    for i := 0; i < m; i++ {
        fmt.Scan(&girls[i])
    }
    sort.Sort(sort.IntSlice(girls))

    i := 0
    j := 0
    result := 0
    for i < n && j < m {
        if girls[j] - boys[i] <= 1 && girls[j] - boys[i] >= -1 {
            result++
            i++
            j++
        } else if girls[j] > boys[i] {
            i++
        } else {
            j++
        }
    }

    fmt.Println(result)
}

package main

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

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 readIntArray(line string) []int {

	numStrings := strings.Split(strings.TrimSpace(string(line)), " ")

	numbers := make([]int, 0)

	for _, v := range numStrings {
		var converted int

		fmt.Sscanf(v, "%d", &converted)
		numbers = append(numbers, converted)
	}

	return numbers
}

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

	Readln(reader)
	line, _ := Readln(reader)
	boys := readIntArray(line)

	Readln(reader)
	line, _ = Readln(reader)
	girls := readIntArray(line)

	count := 0
	sort.Ints(boys)
	sort.Ints(girls)
	for i := 0; i < len(boys); i++ {
		for j := 0; j < len(girls); j++ {
			if int(math.Abs(float64(boys[i] - girls[j]))) <= 1 {
				girls[j] = math.MaxInt32
				count++
				break
			}
		}
	}

	fmt.Println(count)
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n, m, res int

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

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

	sort.Ints(a)
	sort.Ints(b)

	p := -1

	for i := 0; i < len(a); i++ {
		for j := p + 1; j < len(b); j++ {
			difference := Abs(a[i] - b[j])
			if difference <= 1 {
				p = j
				res++
				break
			}
		}
	}
	fmt.Print(res)
}

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

package main

import (
	"fmt"
	"sort"
)

const paired = 10e3 // > problem upper bound value

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

func main() {
	n, m := 0, 0
	ans := 0
	fmt.Scanf("%d\n", &n)
	as := make([]int, n)
	for i := range as {
		fmt.Scanf("%d", &as[i])
	}
	fmt.Scanf("\n%d\n", &m)
	bs := make([]int, m)
	for i := range bs {
		fmt.Scanf("%d", &bs[i])
	}
	sort.Ints(as)
	sort.Ints(bs)
	for _, a := range as {
		for j, b := range bs {
			// skill gap
			if abs(a-b) <= 1 {
				bs[j] = paired
				ans++
				// pair formed -> next
				break
			}
		}
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
	"sort"
)

const paired = 10e3 // > problem upper bound value

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

func main() {
	n, m := 0, 0
	ans := 0
	fmt.Scan(&n)
	as := make([]int, n)
	for i := range as {
		fmt.Scan(&as[i])
	}
	fmt.Scan(&m)
	bs := make([]int, m)
	for i := range bs {
		fmt.Scan(&bs[i])
	}
	sort.Ints(as)
	sort.Ints(bs)
	for _, a := range as {
		for j, b := range bs {
			// skill gap
			if abs(a-b) <= 1 {
				bs[j] = paired
				ans++
				// pair formed -> next
				break
			}
		}
	}
	fmt.Println(ans)
}

package main

import (
  "fmt"
  "sort"
  "math"
  )

func main(){
  var m,d,p int
  fmt.Scan(&m)
  mt := make([]int,m)
  for i:=0;i<m;i++{
    fmt.Scan(&mt[i])
    }
  sort.Ints(mt)
fmt.Scan(&d)
  dt := make([]int,d)
  for i:=0;i<d;i++{
    fmt.Scan(&dt[i])
    }
  sort.Ints(dt)
  for a,b := 0,0; a<m && b<d; {
    if math.Abs(float64(mt[a]-dt[b])) <=1 {
      p++
      a++
      b++
    } else if mt[a]>dt[b] {
      b++
     } else {
      a++
      }
  }
  fmt.Println(p)
  }

package main

import "fmt"
import "sort"

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

func main() {
	var n, m, x, ans int
	var a1 []int
	var a2 []int
	fmt.Scan(&n)
	for i := 0; i < n; i++ {
		fmt.Scan(&x)
		a1 = append(a1, x)
	}
	sort.Ints(a1)
	fmt.Scan(&m)
	for i := 0; i < m; i++ {
		fmt.Scan(&x)
		a2 = append(a2, x)
	}
	sort.Ints(a2)
	id1 := 0
	id2 := 0
	for id1 < n && id2 < m {
		if abs(a1[id1], a2[id2]) <= 1 {
			id1++
			id2++
			ans++
			continue
		}
		if a1[id1] < a2[id2] {
			id1++
			continue
		}
		if a2[id2] < a1[id1] {
			id2++
			continue
		}
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
	"math"
	"sort"
)

func main() {
	var nb, ng int

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

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

	sort.Ints(bs)
	sort.Ints(gs)

	s := 0
	ans := 0
	for i := 0; i < nb; i++ {
		for j := s; j < ng; j++ {
			if math.Abs(float64(bs[i])-float64(gs[j])) < 2 {
				ans++
				s = j + 1
				break
			}
		}
	}

	fmt.Println(ans)
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n, m, res int

	fmt.Scan(&n)

	a := make([]int, n)

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

	fmt.Scan(&m)

	b := make([]int, m)

	for i := 0; i < m; i++ {
		fmt.Scan(&b[i])
	}

	sort.Ints(a)
	sort.Ints(b)

	var p int

	for i := 0; i < len(a); i++ {
		for j := p + 1; j < len(b); j++ {
			if a[i] == b[j] || a[i]+1 == b[j] || a[i]-1 == b[j] {
				p = j
				res++
				break
			}
		}
	}

	fmt.Println(res)
}

package main

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

var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)
var _ = fmt.Println

type IntSorter struct {
	data []int
}
func (s *IntSorter) Len() int { return len(s.data) }
func (s *IntSorter) Swap(i, j int) { s.data[i], s.data[j] = s.data[j], s.data[i] }
func (s *IntSorter) Less(i, j int) bool { return s.data[i] < s.data[j] }

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

	N := ReadInt32()
	boys := make([]int, N)
	for i := 0; i < N; i += 1 {
		boys[i] = ReadInt32()
	}

	M := ReadInt32()
	girls := make([]int, M)
	for i := 0; i < M; i += 1 {
		girls[i] = ReadInt32()
	}

	bSorter := &IntSorter{ boys }
	gSorter := &IntSorter{ girls }
	sort.Sort(bSorter)
	sort.Sort(gSorter)
	boys, girls = bSorter.data, gSorter.data

	bi, gi := 0, 0
	matches := 0
	for bi < N && gi < M {
		if boys[bi] == girls[gi] || boys[bi] - girls[gi] == -1 || boys[bi] - girls[gi] == -1 {
			matches++
			bi++
			gi++
			continue
		}
		if boys[bi] > girls[gi] {
			gi++
		} else {
			bi++
		}
	}
	PrintInts(matches)
}

func ReadInt32() int {
	scanner.Scan()
	ans, _ := strconv.Atoi(scanner.Text())
	return ans
}

func PrintInts(ints ...int) {
	for _, value := range ints {
		writer.WriteString(strconv.Itoa(value))
		writer.WriteByte(' ')
	}
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n, m int
	fmt.Scanf("%d\n", &n)
	a := intArray(n)
	sort.Ints(a[:])
	fmt.Scanf("%d\n", &m)
	b := intArray(m)
	sort.Ints(b[:])
	c := 0
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			difference := Abs(a[i] - b[j])
			if difference <= 1 {
				b[j] = 1000
				c++
				break
			}
		}
	}
	fmt.Println(c)
}

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

func intArray(n int) []int {
	b := make([]int, n)
	for iter := 0; iter < n; iter++ {
		fmt.Scanf("%d", &b[iter])
	}
	return b
}

package main

import (
	"fmt"
	"sort"
)

const paired = 10e3 // > problem upper bound value

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

func main() {
	n, m := 0, 0
	ans := 0
	fmt.Scan(&n)
	as := make([]int, n)
	for i := range as {
		fmt.Scanf("%d", &as[i])
	}
	fmt.Scan(&m)
	bs := make([]int, m)
	for i := range bs {
		fmt.Scanf("%d", &bs[i])
	}
	sort.Ints(as)
	sort.Ints(bs)
	for _, a := range as {
		for j, b := range bs {
			// skill gap
			if abs(a-b) <= 1 {
				bs[j] = paired
				ans++
				// pair formed -> next
				break
			}
		}
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
	"sort"
)

const paired = 10e3 // > problem upper bound value

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

func main() {
	n, m := 0, 0
	ans := 0
	fmt.Scanf("%d", &n)
	as := make([]int, n)
	for i := range as {
		fmt.Scanf("%d", &as[i])
	}
	fmt.Scanf("%d", &m)
	bs := make([]int, m)
	for i := range bs {
		fmt.Scanf("%d", &bs[i])
	}
	sort.Ints(as)
	sort.Ints(bs)
	for _, a := range as {
		for j, b := range bs {
			// skill gap
			if abs(a-b) <= 1 {
				bs[j] = paired
				ans++
				// pair formed -> next
				break
			}
		}
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
)

const paired = 10e3 // > problem upper bound value

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

func main() {
	n, m := 0, 0
	ans := 0
	fmt.Scanf("%d\n", &n)
	as := make([]int, n)
	for i := range as {
		fmt.Scanf("%d", &as[i])
	}
	fmt.Scanf("\n%d\n", &m)
	bs := make([]int, m)
	for i := range bs {
		fmt.Scanf("%d", &bs[i])
	}
	fmt.Println(n, m, as, bs)
	for _, a := range as {
		for j, b := range bs {
			// skill gap
			if abs(a-b) <= 1 {
				bs[j] = paired
				ans++
				// pair formed -> next
				break
			}
		}
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
	"sort"
)

const paired = 10e3 // > problem upper bound value

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

func main() {
	n, m := 0, 0
	ans := 0
	fmt.Scan(&n)
	as := make([]int, n)
	for i := range as {
		fmt.Scanf("%d", &as[i])
	}
	fmt.Scan(&m)
	bs := make([]int, m)
	for i := range bs {
		fmt.Scanf("%d", &bs[i])
	}
	fmt.Println(n, m, as, bs)
	sort.Ints(as)
	sort.Ints(bs)
	for _, a := range as {
		for j, b := range bs {
			// skill gap
			if abs(a-b) <= 1 {
				bs[j] = paired
				ans++
				// pair formed -> next
				break
			}
		}
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
	"sort"
)

const paired = 10e3 // > problem upper bound value

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

func main() {
	n, m := 0, 0
	ans := 0
	fmt.Scanf("%d\n", &n)
	as := make([]int, n)
	for i := range as {
		fmt.Scanf("%d", &as[i])
	}
	fmt.Scanf("%d\n", &m)
	bs := make([]int, m)
	for i := range bs {
		fmt.Scanf("%d", &bs[i])
	}
	sort.Ints(as)
	sort.Ints(bs)
	for _, a := range as {
		for j, b := range bs {
			// skill gap
			if abs(a-b) <= 1 {
				bs[j] = paired
				ans++
				// pair formed -> next
				break
			}
		}
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
)

const paired = 10e3 // > problem upper bound value

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

func main() {
	n, m := 0, 0
	ans := 0
	fmt.Scanf("%d\n", &n)
	as := make([]int, n)
	for i := range as {
		fmt.Scanf("%d\n", &as[i])
	}
	fmt.Scanf("%d\n", &m)
	bs := make([]int, m)
	for i := range bs {
		fmt.Scanf("%d\n", &bs[i])
	}
	for _, a := range as {
		for j, b := range bs {
			// skill gap
			if abs(a-b) <= 1 {
				bs[j] = paired
				ans++
				// pair formed -> next
				break
			}
		}
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
)

const paired = 10e3 // > problem upper bound value

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

func main() {
	n, m := 0, 0
	ans := 0
	fmt.Scanf("%d\n", &n)
	as := make([]int, n)
	for i := range as {
		fmt.Scanf("%d", &as[i])
	}
	fmt.Scanf("%d\n", &m)
	bs := make([]int, m)
	for i := range bs {
		fmt.Scanf("%d", &bs[i])
	}
	for _, a := range as {
		for j, b := range bs {
			// skill gap
			if abs(a-b) <= 1 {
				bs[j] = paired
				// pair formed -> next
				ans++
				break
			}
		}
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
)

const paired = 10e3 // > problem upper bound value

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

func main() {
	n, m := 0, 0
	ans := 0
	fmt.Scanf("%d\n", &n)
	as := make([]int, n)
	for i := range as {
		fmt.Scanf("%d", &as[i])
	}
	fmt.Scanf("\n%d\n", &m)
	bs := make([]int, m)
	for i := range bs {
		fmt.Scanf("%d", &bs[i])
	}
	for _, a := range as {
		for j, b := range bs {
			// skill gap
			if abs(a-b) <= 1 {
				bs[j] = paired
				ans++
				// pair formed -> next
				break
			}
		}
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
)

const paired = 10e3 // > problem upper bound value

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

func main() {
	n, m := 0, 0
	ans := 0
	fmt.Scanf("%d\n", &n)
	as := make([]int, n)
	for i := range as {
		fmt.Scanf("%d", &as[i])
	}
	fmt.Scanf("%d\n", &m)
	bs := make([]int, m)
	for i := range bs {
		fmt.Scanf("%d", &bs[i])
	}
	for _, a := range as {
		for j, b := range bs {
			// skill gap
			if abs(a-b) <= 1 {
				bs[j] = paired
				ans++
				// pair formed -> next
				break
			}
		}
	}
	fmt.Println(ans)
}


ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most k bills from it, and the bills may be of at most two distinct denominations.For example, if a country uses bills with denominations 10, 50, 100, 500, 1000 and 5000 burles, then at k = 20 such ATM can give sums 100 000 burles and 96 000 burles, but it cannot give sums 99 000 and 101 000 burles.Let's suppose that the country uses bills of n distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash q times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the q of requests for cash withdrawal.

The first line contains two integers n, k (1 ≤ n ≤ 5000, 1 ≤ k ≤ 20). The next line contains n space-separated integers ai (1 ≤ ai ≤ 107) — the denominations of the bills that are used in the country. Numbers ai follow in the strictly increasing order. The next line contains integer q (1 ≤ q ≤ 20) — the number of requests for cash withdrawal that you will make. The next q lines contain numbers xi (1 ≤ xi ≤ 2·108) — the sums of money in burles that you are going to withdraw from the ATM.

For each request for cash withdrawal print on a single line the minimum number of bills it can be done, or print  - 1, if it is impossible to get the corresponding sum.

package main

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

func getString(scanner *bufio.Scanner) string {
	scanner.Scan()
	return scanner.Text()
}

func getInt64(scanner *bufio.Scanner) int64 {
	x, _ := strconv.ParseInt(getString(scanner), 10, 64)
	return x
}

func getInt(scanner *bufio.Scanner) int {
	x, _ := strconv.ParseInt(getString(scanner), 10, 32)
	return int(x)
}

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	n := getInt(scanner)
	k := getInt(scanner)
	a := []int{}
	for i := 0; i < n; i++ {
		a = append(a, getInt(scanner))
	}
	minCnt := make(map[int]int)
	minCnt[0] = 0
	for _, denom := range a {
		for i := 1; i <= k; i++ {
			val := denom * i
			if cnt, ok := minCnt[val]; !ok {
				minCnt[val] = i
			} else if i < cnt {
				minCnt[val] = i
			}
		}
	}
	qu := getInt(scanner)
	for qu > 0 {
		tot := getInt(scanner)
		ans := k + 1
		for _, denom := range a {
			for i := 1; i <= k; i++ {
				val := denom * i
				if val > tot {
					continue
				}
				if cnt, ok := minCnt[tot - val]; !ok {
					continue
				} else if i + cnt > k {
					continue
				} else {
					ans = minInt(ans, i + cnt)
				}
			}
		}
		if ans < k + 1 {
			fmt.Printf("%d\n", ans)
		} else {
			fmt.Printf("-1\n")
		}
		qu--
	}
}


There are quite a lot of ways to have fun with inflatable balloons. For example, you can fill them with water and see what happens.Grigory and Andrew have the same opinion. So, once upon a time, they went to the shop and bought $$$n$$$ packets with inflatable balloons, where $$$i$$$-th of them has exactly $$$a_i$$$ balloons inside.They want to divide the balloons among themselves. In addition, there are several conditions to hold:  Do not rip the packets (both Grigory and Andrew should get unbroken packets);  Distribute all packets (every packet should be given to someone);  Give both Grigory and Andrew at least one packet;  To provide more fun, the total number of balloons in Grigory's packets should not be equal to the total number of balloons in Andrew's packets. Help them to divide the balloons or determine that it's impossible under these conditions.

The first line of input contains a single integer $$$n$$$ ($$$1 \le n \le 10$$$) — the number of packets with balloons. The second line contains $$$n$$$ integers: $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_n$$$ ($$$1 \le a_i \le 1000$$$) — the number of balloons inside the corresponding packet.

If it's impossible to divide the balloons satisfying the conditions above, print $$$-1$$$. Otherwise, print an integer $$$k$$$ — the number of packets to give to Grigory followed by $$$k$$$ distinct integers from $$$1$$$ to $$$n$$$ — the indices of those. The order of packets doesn't matter. If there are multiple ways to divide balloons, output any of them.

NoteIn the first test Grigory gets $$$3$$$ balloons in total while Andrey gets $$$1$$$.In the second test there's only one way to divide the packets which leads to equal numbers of balloons.In the third test one of the boys won't get a packet at all.

package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scan(&n)
	arr := make([]int, n)
	sum := 0
	for i := range arr {
		fmt.Scan(&arr[i])
		sum += arr[i]
	}
	ok := -1
	for i, v := range arr {
		if sum-v != v {
			ok = i
			break
		}
	}
	if n > 1 && ok != -1 {
		fmt.Printf("%d\n%d", 1, ok+1)
	} else {
		fmt.Println(-1)
	}
}


The Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.

The single line contains three integers r, s and p (1 ≤ r, s, p ≤ 100) — the original number of individuals in the species of rock, scissors and paper, respectively.

Print three space-separated real numbers: the probabilities, at which the rocks, the scissors and the paper will be the only surviving species, respectively. The answer will be considered correct if the relative or absolute error of each number doesn't exceed 10 - 9.

package main

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

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

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer = bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  r, s, p := getI(), getI(), getI()
  g := make([][][]float64, r+1)
  m := make([][][]bool, r+1)
  for i := 0; i <= r; i++ {
    g[i] = make([][]float64, s+1)
    m[i] = make([][]bool, s+1)
    for j := 0; j <= s; j++ {
      g[i][j] = make([]float64, p+1)
      m[i][j] = make([]bool, p+1)
    }
  }
  g[r][s][p] = 1
  queue := [][]int{ []int{ r, s, p } }
  tail := 0
  for tail != len(queue) {
    r, s, p := queue[tail][0], queue[tail][1], queue[tail][2]
    tail++
    curr := g[r][s][p]
    space := float64(r*s + s*p + p*r)
    if space == 0.0 {
      continue
    }
    if r > 0 {
      g[r-1][s][p] += curr * float64(p*r)/space
      if !m[r-1][s][p] {
        m[r-1][s][p] = true
        queue = append(queue, []int{ r-1, s, p })
      }
    }
    if s > 0 {
      g[r][s-1][p] += curr * float64(r*s)/space
      if !m[r][s-1][p] {
        m[r][s-1][p] = true
        queue = append(queue, []int{ r, s-1, p })
      }
    }
    if p > 0 {
      g[r][s][p-1] += curr * float64(s*p)/space
      if !m[r][s][p-1] {
        m[r][s][p-1] = true
        queue = append(queue, []int{ r, s, p-1 })
      }
    }
  }
  R, S, P := 0.0, 0.0, 0.0
  for i := 1; i <= r; i++ {
    R += g[i][0][0]
  }
  for i := 1; i <= s; i++ {
    S += g[0][i][0]
  }
  for i := 1; i <= p; i++ {
    P += g[0][0][i]
  }
  writer.WriteString(fmt.Sprintf("%.12f %.12f %.12f\n", R, S, P))
}

package main

import "fmt"

func main() {
	var r, s, p int
	fmt.Scanf("%d %d %d", &r, &s, &p)

	var prob = make([]float64, (r+1) * (s+1) * (p+1))

	var set = func (rx int, sx int, px int, val float64) {
		prob[rx * (s+1) * (p+1) + sx * (p+1) + px] = val
	}
	var get = func (rx int, sx int, px int) float64 {
		return prob[rx * (s+1) * (p+1) + sx * (p+1) + px]
	}

	for i := r; i >= 0; i-- {
		for j := s; j >= 0; j-- {
			for k := p; k >= 0; k-- {
				if i == r && j == s && k == p {
					// Initial condition - the probability is 1.
					set(i, j, k, 1.0)
				} else {
					// The probability of getting into state (i, j, k) is the sum of
					// 1) P(i+1, j, k) * (P(an "i" loses)
					//    where
					//      P(an "i" loses) is (i+1)/(i+1+j+k))
					// 2) and 3) symmetrically for j and k.
					pp := 0.0
					if i != r && (j != 0 || k != 0) {
						pp += get(i+1, j, k) * float64((i+1) * k) / float64((i+1) * j + j * k + k * (i+1))
					}
					if j != s && (i != 0 || k != 0) {
						pp += get(i, j+1, k) * float64(i * (j+1)) / float64(i * (j+1) + (j+1) * k + k * i)
					}
					if k != p && (i != 0 || j != 0) {
						pp += get(i, j, k+1) * float64(j * (k+1)) / float64(i * j + j * (k+1) + (k+1) * i)
					}
					set(i, j, k, pp)
				}
	//			fmt.Printf("%02d %02d %02d %12.5f\n", i, j, k, get(i, j, k))
			}
		}
	}
	var ans_r = 0.0
	for i := r; i >= 1; i-- {
		ans_r += get(i, 0, 0)
	}
	var ans_s = 0.0
	for i := s; i >= 1; i-- {
		ans_s += get(0, i, 0)
	}
	var ans_p = 0.0
	for i := p; i >= 1; i-- {
		ans_p += get(0, 0, i)
	}
	fmt.Printf("%14.12g %14.12g %14.12g\n", ans_r, ans_s, ans_p)
}

package main

import "fmt"

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

	dp := make([][][]float64, n+1)
	for i, _ := range dp {
		dp[i] = make([][]float64, m+1)
		for j, _ := range dp[i] {
			dp[i][j] = make([]float64, k+1)
		}
	}

	dp[n][m][k] = 1

	for r := n; r >= 0; r-- {
		for p := m; p >= 0; p-- {
			for s := k; s >= 0; s-- {
				deno := float64(r*p + p*s + r*s)

				if deno == 0 {
					continue
				}

				if r > 0 {
					dp[r-1][p][s] += dp[r][p][s] * float64(r*p) / deno
				}
				if p > 0 {
					dp[r][p-1][s] += dp[r][p][s] * float64(s*p) / deno
				}
				if s > 0 {
					dp[r][p][s-1] += dp[r][p][s] * float64(r*s) / deno
				}
			}
		}
	}

	var proba1, proba2, proba3 float64
	for i := 0; i <= n; i++ {
		proba1 += dp[i][0][0]
	}

	for i := 0; i <= m; i++ {
		proba2 += dp[0][i][0]
	}

	for i := 0; i <= k; i++ {
		proba3 += dp[0][0][i]
	}

	fmt.Printf("%.15f %.15f %.15f", proba1, proba3, proba2)
}

package main

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

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

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer = bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  r, s, p := getI(), getI(), getI()
  g := make([][][]float64, r+1)
  m := make([][][]bool, r+1)
  for i := 0; i <= r; i++ {
    g[i] = make([][]float64, s+1)
    m[i] = make([][]bool, s+1)
    for j := 0; j <= s; j++ {
      g[i][j] = make([]float64, p+1)
      m[i][j] = make([]bool, p+1)
    }
  }
  g[r][s][p] = 1
  queue := [][]int{ []int{ r, s, p } }
  tail := 0
  for tail != len(queue) {
    r, s, p := queue[tail][0], queue[tail][1], queue[tail][2]
    tail++
    curr := g[r][s][p]
    space := float64(r*s + s*p + p*r)
    if space == 0.0 {
      continue
    }
    if r > 0 {
      g[r-1][s][p] += curr * float64(p*r)/space
      if !m[r-1][s][p] {
        m[r-1][s][p] = true
        queue = append(queue, []int{ r-1, s, p })
      }
    }
    if s > 0 {
      g[r][s-1][p] += curr * float64(r*s)/space
      if !m[r][s-1][p] {
        m[r][s-1][p] = true
        queue = append(queue, []int{ r, s-1, p })
      }
    }
    if p > 0 {
      g[r][s][p-1] += curr * float64(s*p)/space
      if !m[r][s][p-1] {
        m[r][s][p-1] = true
        queue = append(queue, []int{ r, s, p-1 })
      }
    }
  }
  R, S, P := 0.0, 0.0, 0.0
  for i := 1; i <= r; i++ {
    R += g[i][0][0]
  }
  for i := 1; i <= s; i++ {
    S += g[0][i][0]
  }
  for i := 1; i <= p; i++ {
    P += g[0][0][i]
  }
  writer.WriteString(fmt.Sprintf("%f %f %f\n", R, S, P))
}

package main

import "fmt"

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

	dp := make([][][]float32, n+1)
	for i, _ := range dp {
		dp[i] = make([][]float32, m+1)
		for j, _ := range dp {
			dp[i][j] = make([]float32, k+1)
		}
	}

	dp[n][m][k] = 1

	for r := n; r >= 0; r-- {
		for p := m; p >= 0; p-- {
			for s := k; s >= 0; s-- {
				deno := float32(r*p + p*s + r*s)

				if deno == 0 {
					continue
				}

				if r > 0 {
					dp[r-1][p][s] += dp[r][p][s] * float32(r*p) / deno
				}
				if p > 0 {
					dp[r][p-1][s] += dp[r][p][s] * float32(s*p) / deno
				}
				if s > 0 {
					dp[r][p][s-1] += dp[r][p][s] * float32(r*s) / deno
				}
			}
		}
	}

	var proba1, proba2, proba3 float32
	for i := 0; i <= n; i++ {
		proba1 += dp[i][0][0]
	}

	for i := 0; i <= m; i++ {
		proba2 += dp[0][i][0]
	}

	for i := 0; i <= k; i++ {
		proba3 += dp[0][0][i]
	}

	fmt.Printf("%.9f %.9f %.9f", proba1, proba3, proba2)
}


You are given an array $$$a$$$ consisting of $$$n$$$ integers. We denote the subarray $$$a[l..r]$$$ as the array $$$[a_l, a_{l + 1}, \dots, a_r]$$$ ($$$1 \le l \le r \le n$$$).A subarray is considered good if every integer that occurs in this subarray occurs there exactly thrice. For example, the array $$$[1, 2, 2, 2, 1, 1, 2, 2, 2]$$$ has three good subarrays:  $$$a[1..6] = [1, 2, 2, 2, 1, 1]$$$;  $$$a[2..4] = [2, 2, 2]$$$;  $$$a[7..9] = [2, 2, 2]$$$. Calculate the number of good subarrays of the given array $$$a$$$.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$).

Print one integer — the number of good subarrays of the array $$$a$$$.

package main

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

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

	n := readNum(reader)

	A := readNNums(reader, n)

	fmt.Println(solve(n, A))
}

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
}

var r *rand.Rand

func init() {
	r = rand.New(rand.NewSource(99))
}

func solve(n int, A []int) int64 {
	hashes := make([]uint64, n+1)
	indices := make([][]int, n+1)
	freq := make([]uint64, n+1)
	hashValues := make([]uint64, n+1)
	hashFreq := make(map[uint64]int)
	for i := 1; i <= n; i++ {
		hashValues[i] = r.Uint64()
		indices[i] = make([]int, 0, 4)
	}
	hashFreq[0]++
	var start int
	var ans int64
	for i := 0; i < n; i++ {
		cur := A[i]
		if len(indices[cur]) >= 3 {
			remove := indices[cur][0]
			indices[cur] = indices[cur][1:]
			for start <= remove {
				hashFreq[hashes[start]]--
				start++
			}
		}
		before := freq[cur]
		freq[cur] = (before + 1) % 3
		hashes[i+1] = hashes[i] + (freq[cur]-before)*hashValues[cur]
		ans += int64(hashFreq[hashes[i+1]])
		hashFreq[hashes[i+1]]++
		indices[cur] = append(indices[cur], i)
	}

	return ans
}

package main

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

var rw = NewFastIO(os.Stdin, os.Stdout)

func main() {
	defer rw.Flush()

	n := rw.NextInt()
	a := rw.NextInts(n)
	var nums [3][]uint64
	for j := 0; j < n; j++ {
		nums[0] = append(nums[0], rand.Uint64())
		nums[1] = append(nums[1], rand.Uint64())
		nums[2] = append(nums[2], nums[0][j]^nums[1][j])
	}
	cnts := map[uint64]int{0: 1}
	pref := make([]uint64, n+1)
	ctr := make([]int, n)
	frq := make([]int, n)
	var ans int64
	for i, j := 0, 0; i < n; i++ {
		a[i]--
		pref[i+1] = pref[i] ^ nums[ctr[a[i]]%3][a[i]]
		ctr[a[i]]++
		frq[a[i]]++
		for frq[a[i]] > 3 {
			frq[a[j]]--
			cnts[pref[j]]--
			j++
		}
		ans += int64(cnts[pref[i+1]])
		cnts[pref[i+1]]++
	}
	rw.Println(ans)
}

// @meooow template uwu
type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{r: r, Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

func (f *FastIO) Next() string {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	var s []byte
	for ; c > ' '; c = f.readC() {
		s = append(s, c)
	}
	return string(s)
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}
func (f *FastIO) NextInt64() int64 {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := int64(0)
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int64(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) NextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt()
	}
	return a
}
func (f *FastIO) NextInt64s(n int) []int64 {
	a := make([]int64, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt64()
	}
	return a
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f, a...)
}

func (f *FastIO) Print(a ...interface{}) {
	fmt.Fprint(f, a...)
}
func (f *FastIO) PrintInts(a ...int) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInts(a ...int) {
	f.PrintInts(a...)
	f.Println()
}
func (f *FastIO) PrintInt64s(a ...int64) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInt64s(a ...int64) {
	f.PrintInt64s(a...)
	f.Println()
}

package main

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

var rw = NewFastIO(os.Stdin, os.Stdout)

const M = 1

func main() {
	defer rw.Flush()

	n := rw.NextInt()
	a := rw.NextInts(n)
	var cnts [M]map[uint64]int
	var nums [M][3][]uint64
	for i := range cnts {
		cnts[i] = make(map[uint64]int)
		cnts[i][0] = 1
		for j := 0; j < n; j++ {
			nums[i][0] = append(nums[i][0], rand.Uint64())
			nums[i][1] = append(nums[i][1], rand.Uint64())
			nums[i][2] = append(nums[i][2], nums[i][0][j]^nums[i][1][j])
		}
	}
	pref := make([]uint64, n+1)
	ctr := make([]int, n)
	frq := make([]int, n)
	var ans int64
	for i, j := 0, 0; i < n; i++ {
		a[i]--
		pref[i+1] = pref[i] ^ nums[0][ctr[a[i]]%3][a[i]]
		ctr[a[i]]++
		frq[a[i]]++
		for frq[a[i]] > 3 {
			frq[a[j]]--
			cnts[0][pref[j]]--
			j++
		}
		ans += int64(cnts[0][pref[i+1]])
		cnts[0][pref[i+1]]++
	}
	rw.Println(ans)
}

// @meooow template uwu
type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{r: r, Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

func (f *FastIO) Next() string {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	var s []byte
	for ; c > ' '; c = f.readC() {
		s = append(s, c)
	}
	return string(s)
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}
func (f *FastIO) NextInt64() int64 {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := int64(0)
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int64(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) NextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt()
	}
	return a
}
func (f *FastIO) NextInt64s(n int) []int64 {
	a := make([]int64, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt64()
	}
	return a
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f, a...)
}

func (f *FastIO) Print(a ...interface{}) {
	fmt.Fprint(f, a...)
}
func (f *FastIO) PrintInts(a ...int) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInts(a ...int) {
	f.PrintInts(a...)
	f.Println()
}
func (f *FastIO) PrintInt64s(a ...int64) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInt64s(a ...int64) {
	f.PrintInt64s(a...)
	f.Println()
}

package main

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

var rw = NewFastIO(os.Stdin, os.Stdout)

func main() {
	defer rw.Flush()
	n := rw.NextInt()
	a := rw.NextInts(n)
	var nums [3][]uint32
	for j := 0; j < n; j++ {
		nums[0] = append(nums[0], rand.Uint32())
		nums[1] = append(nums[1], rand.Uint32())
		nums[2] = append(nums[2], nums[0][j]^nums[1][j])
	}
	cnts := map[uint32]int{0: 1}
	pref := make([]uint32, n+1)
	ctr := make([]int, n)
	frq := make([]int, n)
	var ans int64
	for i, j := 0, 0; i < n; i++ {
		a[i]--
		pref[i+1] = pref[i] ^ nums[ctr[a[i]]%3][a[i]]
		ctr[a[i]]++
		frq[a[i]]++
		for frq[a[i]] > 3 {
			frq[a[j]]--
			cnts[pref[j]]--
			j++
		}
		ans += int64(cnts[pref[i+1]])
		cnts[pref[i+1]]++
	}
	rw.Println(ans)
}

// @meooow template uwu
type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{r: r, Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

func (f *FastIO) Next() string {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	var s []byte
	for ; c > ' '; c = f.readC() {
		s = append(s, c)
	}
	return string(s)
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}
func (f *FastIO) NextInt64() int64 {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := int64(0)
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int64(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) NextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt()
	}
	return a
}
func (f *FastIO) NextInt64s(n int) []int64 {
	a := make([]int64, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt64()
	}
	return a
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f, a...)
}

func (f *FastIO) Print(a ...interface{}) {
	fmt.Fprint(f, a...)
}
func (f *FastIO) PrintInts(a ...int) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInts(a ...int) {
	f.PrintInts(a...)
	f.Println()
}
func (f *FastIO) PrintInt64s(a ...int64) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInt64s(a ...int64) {
	f.PrintInt64s(a...)
	f.Println()
}


Vasya is pressing the keys on the keyboard reluctantly, squeezing out his ideas on the classical epos depicted in Homer's Odysseus... How can he explain to his literature teacher that he isn't going to become a writer? In fact, he is going to become a programmer. So, he would take great pleasure in writing a program, but none — in writing a composition.As Vasya was fishing for a sentence in the dark pond of his imagination, he suddenly wondered: what is the least number of times he should push a key to shift the cursor from one position to another one?Let's describe his question more formally: to type a text, Vasya is using the text editor. He has already written n lines, the i-th line contains ai characters (including spaces). If some line contains k characters, then this line overall contains (k + 1) positions where the cursor can stand: before some character or after all characters (at the end of the line). Thus, the cursor's position is determined by a pair of integers (r, c), where r is the number of the line and c is the cursor's position in the line (the positions are indexed starting from one from the beginning of the line).Vasya doesn't use the mouse to move the cursor. He uses keys "Up", "Down", "Right" and "Left". When he pushes each of these keys, the cursor shifts in the needed direction. Let's assume that before the corresponding key is pressed, the cursor was located in the position (r, c), then Vasya pushed key: "Up": if the cursor was located in the first line (r = 1), then it does not move. Otherwise, it moves to the previous line (with number r - 1), to the same position. At that, if the previous line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r - 1; "Down": if the cursor was located in the last line (r = n), then it does not move. Otherwise, it moves to the next line (with number r + 1), to the same position. At that, if the next line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r + 1; "Right": if the cursor can move to the right in this line (c < ar + 1), then it moves to the right (to position c + 1). Otherwise, it is located at the end of the line and doesn't move anywhere when Vasya presses the "Right" key; "Left": if the cursor can move to the left in this line (c > 1), then it moves to the left (to position c - 1). Otherwise, it is located at the beginning of the line and doesn't move anywhere when Vasya presses the "Left" key.You've got the number of lines in the text file and the number of characters, written in each line of this file. Find the least number of times Vasya should push the keys, described above, to shift the cursor from position (r1, c1) to position (r2, c2).

The first line of the input contains an integer n (1 ≤ n ≤ 100) — the number of lines in the file. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 105), separated by single spaces. The third line contains four integers r1, c1, r2, c2 (1 ≤ r1, r2 ≤ n, 1 ≤ c1 ≤ ar1 + 1, 1 ≤ c2 ≤ ar2 + 1).

Print a single integer — the minimum number of times Vasya should push a key to move the cursor from position (r1, c1) to position (r2, c2).

NoteIn the first sample the editor contains four lines. Let's represent the cursor's possible positions in the line as numbers. Letter s represents the cursor's initial position, letter t represents the last one. Then all possible positions of the cursor in the text editor are described by the following table.12312123s5671t345One of the possible answers in the given sample is: "Left", "Down", "Left".

// Author: sighduck
// URL: https://codeforces.com/problemset/problem/253/C

package main

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

type Path struct {
	Moves int
	R     int
	C     int
}

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

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

func moveToRow(row int, column int, endRow int, a []int, moves int) Path {
	if row == endRow {
		return Path{
			Moves: moves,
			R:     row,
			C:     column,
		}
	}
	if row > endRow {
		return moveToRow(row-1, min(a[row-1]+1, column), endRow, a, moves+1)
	}
	return moveToRow(row+1, min(a[row+1]+1, column), endRow, a, moves+1)
}

func Solve(n int, a []int, r1, c1, r2, c2 int) int {
	paths := []Path{}
	for i := 1; i <= n; i++ {
		p := moveToRow(r1, c1, i, a, 0)
		paths = append(paths, p)
	}
	minMoves := math.MaxInt32
	for _, path := range paths {
		p := moveToRow(path.R, path.C, r2, a, path.Moves)
		minMoves = min(minMoves, p.Moves+abs(c2-p.C))
	}
	return minMoves
}

func main() {
	inputFile, _ := os.Open("input.txt")
	outputFile, _ := os.Create("output.txt")
	reader := bufio.NewReader(inputFile)
	writer := bufio.NewWriter(outputFile)
	defer writer.Flush()

	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	a := make([]int, n+1)
	for i := 1; i <= n; i++ {
		fmt.Fscan(reader, &a[i])
	}
	fmt.Fscanf(reader, "\n")
	var r1, c1, r2, c2 int
	fmt.Fscanf(reader, "%d %d %d %d\n", &r1, &c1, &r2, &c2)

	fmt.Fprintf(writer, "%d\n", Solve(n, a, r1, c1, r2, c2))
}

// Author: sighduck
// URL: https://codeforces.com/problemset/problem/253/C

package main

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

type Node struct {
	R int
	C int
}

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

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

func getNearestNeighbor(n int, a []int, currentNode Node, finalNode Node) Node {
	neighbors := []Node{}
	if currentNode.R-1 >= 1 {
		nextColumn := min(a[currentNode.R-2]+1, currentNode.C)
		neighbors = append(neighbors, Node{R: currentNode.R - 1, C: nextColumn})
	}
	if currentNode.R+1 <= n {
		nextColumn := min(a[currentNode.R]+1, currentNode.C)
		neighbors = append(neighbors, Node{R: currentNode.R + 1, C: nextColumn})
	}
	if currentNode.C-1 >= 1 {
		neighbors = append(neighbors, Node{R: currentNode.R, C: currentNode.C - 1})
	}
	if currentNode.C+1 <= n {
		neighbors = append(neighbors, Node{R: currentNode.R, C: currentNode.C + 1})
	}
	minDistance := 1000000
	var nearestNeighbor Node
	for _, neighbor := range neighbors {
		d := abs(neighbor.R-finalNode.R) + abs(neighbor.C-finalNode.C)
		if d < minDistance {
			minDistance = d
			nearestNeighbor = neighbor
		}
	}
	return nearestNeighbor
}

func Solve(n int, a []int, r1, c1, r2, c2 int) int {
	currentNode := Node{R: r1, C: c1}
	finalNode := Node{R: r2, C: c2}
	moves := 0
	for currentNode != finalNode {
		currentNode = getNearestNeighbor(n, a, currentNode, finalNode)
		moves += 1
	}
	return moves
}

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

	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &a[i])
	}
	fmt.Fscanf(reader, "\n")
	var r1, c1, r2, c2 int
	fmt.Fscanf(reader, "%d %d %d %d\n", &r1, &c1, &r2, &c2)

	fmt.Fprintf(writer, "%d\n", Solve(n, a, r1, c1, r2, c2))
}


You are given a tree, which consists of $$$n$$$ vertices. Recall that a tree is a connected undirected graph without cycles.     Example of a tree. Vertices are numbered from $$$1$$$ to $$$n$$$. All vertices have weights, the weight of the vertex $$$v$$$ is $$$a_v$$$.Recall that the distance between two vertices in the tree is the number of edges on a simple path between them.Your task is to find the subset of vertices with the maximum total weight (the weight of the subset is the sum of weights of all vertices in it) such that there is no pair of vertices with the distance $$$k$$$ or less between them in this subset.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 200$$$) — the number of vertices in the tree and the distance restriction, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$), where $$$a_i$$$ is the weight of the vertex $$$i$$$. The next $$$n - 1$$$ lines contain edges of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$ — the labels of vertices it connects ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$). It is guaranteed that the given edges form a tree.

Print one integer — the maximum total weight of the subset in which all pairs of vertices have distance more than $$$k$$$.

package main

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

var (
	reader *bufio.Reader = bufio.NewReader(os.Stdin)
	writer *bufio.Writer = bufio.NewWriter(os.Stdout)
	Debug                = true
)

func Printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func Scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }

func Dprint(format string, a ...interface{}) {
	if Debug {
		fmt.Fprintf(os.Stderr, format+"\n", a...)
	}
}

var (
	n, k int
	a    []int
	adj  [][]int

	mem [][]int64
)

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

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

func dp(vert int, dep int, prevVert int) (fRet int64) {
	if m := mem[vert][dep]; m != -1 {
		return m
	}
	defer func() {
		mem[vert][dep] = fRet
	}()

	var ret int64

	var chi []int
	for _, ch := range adj[vert] {
		if ch != prevVert {
			chi = append(chi, ch)
		}
	}

	if dep == 0 {
		ret = int64(a[vert])
		for _, ch := range chi {
			ret += dp(ch, k-1, vert)
		}
	} else {
		// We are calculating max(dp(ch0, b) + dp(ch1, a) + dp(ch2, a) + dp(ch3, a)) for all ch0, ch1, ...; ch0 != ch1 != ch2 ...
		var cSum int64
		for _, ch := range chi {
			cSum += dp(ch, maxI(dep-1, k-dep-1), vert)
		}

		for _, ch := range chi {
			ret = maxI64(ret,
				cSum-
					dp(ch, maxI(dep-1, k-dep-1), vert)+
					dp(ch, dep-1, vert),
			)
		}
	}

	for nDep := dep + 1; nDep <= k; nDep++ {
		ret = maxI64(ret, dp(vert, nDep, prevVert))
	}
	return ret
}

func main() {
	defer writer.Flush()

	Scanf("%d %d\n", &n, &k)
	k++

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

	adj = make([][]int, n)
	for i := 0; i < n-1; i++ {
		var from, to int
		Scanf("%d %d\n", &from, &to)
		from--
		to--
		adj[from] = append(adj[from], to)
		adj[to] = append(adj[to], from)
	}

	mem = make([][]int64, n)
	for i := 0; i < n; i++ {
		mem[i] = make([]int64, k+1)
		for j := 0; j <= k; j++ {
			mem[i][j] = -1
		}
	}

	Printf("%d\n", dp(0, 0, 0))
}

package main

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

var (
	reader *bufio.Reader = bufio.NewReader(os.Stdin)
	writer *bufio.Writer = bufio.NewWriter(os.Stdout)
	Debug                = true
)

func Printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func Scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }

func Dprint(format string, a ...interface{}) {
	if Debug {
		fmt.Fprintf(os.Stderr, format+"\n", a...)
	}
}

var (
	n, k int
	a    []int
	adj  [][]int

	mem [][]int64
)

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

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

func dp(vert int, dep int, prevVert int) (fRet int64) {
	if m := mem[vert][dep]; m != -1 {
		return m
	}
	defer func() {
		mem[vert][dep] = fRet
	}()

	var ret int64

	var chi []int
	for _, ch := range adj[vert] {
		if ch != prevVert {
			chi = append(chi, ch)
		}
	}

	if dep == 0 {
		ret = int64(a[vert])
		for _, ch := range chi {
			ret += dp(ch, k-1, vert)
		}
	} else {
		for _, ch1 := range chi {
			iRet := int64(dp(ch1, dep-1, vert))
			for _, ch2 := range chi {
				if ch2 == ch1 {
					continue
				}
				iRet += dp(ch2, maxI(dep-1, k-dep-1), vert)
			}
			ret = maxI64(ret, iRet)
		}
	}

	for nDep := dep + 1; nDep <= k; nDep++ {
		ret = maxI64(ret, dp(vert, nDep, prevVert))
	}
	return ret
}

func main() {
	defer writer.Flush()

	Scanf("%d %d\n", &n, &k)
	k++

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

	adj = make([][]int, n)
	for i := 0; i < n-1; i++ {
		var from, to int
		Scanf("%d %d\n", &from, &to)
		from--
		to--
		adj[from] = append(adj[from], to)
		adj[to] = append(adj[to], from)
	}

	Dprint("adj=%v", adj)

	mem = make([][]int64, n)
	for i := 0; i < n; i++ {
		mem[i] = make([]int64, k+1)
		for j := 0; j <= k; j++ {
			mem[i][j] = -1
		}
	}

	Printf("%d\n", dp(0, 0, 0))
	Dprint("mem=%v", mem)
}

package main

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

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

	return y
}

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

	return y
}

func dfs(c, p, k int) {
	if g[c] == nil {
		return
	}

	for e := g[c].Front(); e != nil; e = e.Next() {
		next := e.Value.(int)
		if next == p {
			continue
		}

		dfs(next, c, k)

		//fmt.Println(c, next, "before", dp[c][:k+1])

		for i := 0; i <= k; i++ {
			temp[i] = dp[c][i]
		}

		for i := 0; i <= k; i++ {
			for j := 0; j <= k; j++ {
				if i+j+1 > k {
					m := min(i, j+1)
					temp[m] = max(temp[m], dp[c][i]+dp[next][j])
				}
			}
		}

		for i := 0; i <= k; i++ {
			dp[c][i] = temp[i]
		}

		//fmt.Println(c, next, "after", dp[c][:k+1])
	}
}

var g [201]*list.List
var dp [201][201]int
var temp [201]int

func main() {

	reader := bufio.NewReader(os.Stdin)
	var n, k int

	fmt.Fscanf(reader, "%d %d\n", &n, &k)

	for i := 1; i <= n; i++ {
		if i != n {
			fmt.Fscanf(reader, "%d", &dp[i][0])
		} else {
			fmt.Fscanf(reader, "%d\n", &dp[i][0])
		}
	}

	x, y := 0, 0
	for i := 1; i < n; i++ {
		fmt.Fscanf(reader, "%d %d\n", &x, &y)

		if g[x] == nil {
			g[x] = list.New()
		}

		if g[y] == nil {
			g[y] = list.New()
		}

		g[x].PushBack(y)
		g[y].PushBack(x)
	}

	dfs(1, 0, k)

	for i := 1; i <= k; i++ {
		if dp[1][i] > dp[1][0] {
			dp[1][0] = dp[1][i]
		}
	}

	fmt.Println(dp[1][0])
}


This is the hard version of this problem. The only difference is the constraint on $$$k$$$ — the number of gifts in the offer. In this version: $$$2 \le k \le n$$$.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.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$$$, $$$2 \le k \le n$$$) — 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$$$.

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

	ans := 0
	prefVal := int64(0)
	for i := 0; i < int(k); i++ {
		// iは素直に買う品物の個数
		if i > 0 {
			prefVal += A[i-1]
		}
		num := i

		if prefVal <= p {
			ChMax(&ans, num)
		}

		offerVal := int64(0)
		for j := i-1+int(k); j < int(n); j += int(k) {
			offerVal += A[j]
			num += int(k)
			if prefVal + offerVal <= p {
				ChMax(&ans, num)
			} else {
				break
			}
		}
	}

	fmt.Println(ans)
}

// ChMax accepts a pointer of integer and a target value.
// If target value is LARGER than the first argument,
//	then the first argument will be updated by the second argument.
func ChMax(updatedValue *int, target int) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

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
}

// Author: sighduck
// URL: https://codeforces.com/problemset/problem/1282/B2

package main

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

func Solve(n, p, k int, a []int) int {
	sort.Ints(a)
	dp := make([]int, n+1)
	for i := 1; i < k; i++ {
		dp[i] = a[i-1] + dp[i-1]
	}
	for i := k; i <= n; i++ {
		dp[i] = dp[i-k] + a[i-1]
	}
	ans := 0
	for i, elem := range dp {
		if elem <= p {
			ans = i
		}
	}
	return ans
}

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

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

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
*/

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


There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi < bi + 1 for all i < n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i < n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.

The first line of the input contains an integer n (1 ≤ n ≤ 200 000) — the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≤ ai ≤ n, 1 ≤ bi ≤ 109, bi < bi + 1) — the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≤ q ≤ 200 000) — the number of question you have in mind. Each of next q lines contains an integer k (1 ≤ k ≤ n), followed by k integers lj (1 ≤ lj ≤ n) — the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.

For each question print two integer — the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.

NoteConsider the first sample:   In the first question participant number 3 is absent so the sequence of bids looks as follows:   1 10  2 100  1 10 000  2 100 000  Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks:   1 10  1 10 000  The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem).  In the third question participants 1 and 2 are absent and the sequence is:   3 1 000  3 1 000 000  The winner is participant 3 with the bid 1 000.

package main

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

const (
	N = 200000
)

type Bid struct {
	a int
	b int
}
type Bids []Bid

func (bids Bids) Len() int {
	return len(bids)
}
func (bids Bids) Less(i, j int) bool {
	return bids[i].b < bids[j].b
}
func (bids Bids) Swap(i, j int) {
	bids[i], bids[j] = bids[j], bids[i]
}

func last(arr []int) int {
	return arr[len(arr)-1]
}
func first(arr []int) int {
	return arr[0]
}

func main() {
	r := bufio.NewReader(os.Stdin)
	var n int
	bidTable := map[int][]int{}
	fmt.Fscanf(r, "%d\n", &n)
	for i := 1; i <= n; i++ {
		var a, b int
		fmt.Fscanf(r, "%d %d\n", &a, &b)
		bidTable[a] = append(bidTable[a], b)
	}
	// fmt.Printf("%v\n", bidTable)

	lastBids := Bids{}
	for a, bids := range bidTable {
		lastBids = append(lastBids, Bid{a, last(bids)})
	}
	sort.Sort(lastBids)
	hash := map[int]int{}
	for i, bid := range lastBids {
		hash[bid.a] = i
	}
	// fmt.Printf("%v\n", hash)

	w := bufio.NewWriter(os.Stdout)

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

	for q > 0 {
		q--
		var m int
		fmt.Fscanf(r, "%d", &m)
		absents := []int{len(hash)}
		for m > 0 {
			m--
			var v int
			fmt.Fscanf(r, "%d", &v)
			h, exists := hash[v]
			if exists {
				absents = append(absents, h)
			}
		}
		fmt.Fscanln(r)
		absents = append(absents, -1)
		sort.Sort(sort.Reverse(sort.IntSlice(absents)))

		// fmt.Printf("%v\n", absents)
		var winner, next *Bid
		for i := 0; i < len(absents)-1; i++ {
			presents := absents[i] - absents[i+1] - 1
			if presents == 0 {
				continue
			}
			offset := 1
			if winner == nil {
				winner = &lastBids[absents[i]-offset]
				presents--
				offset++
			}
			if presents > 0 {
				next = &lastBids[absents[i]-offset]
				break
			}
		}
		// fmt.Printf("%v\n", *winner)
		// fmt.Printf("%v\n", *next)
		if winner == nil {
			fmt.Fprintf(w, "0 0\n")
		} else {
			bid := first(bidTable[winner.a])
			if next != nil {
				bid = bidTable[winner.a][sort.SearchInts(bidTable[winner.a], next.b)]
			}
			fmt.Fprintf(w, "%d %d\n", winner.a, bid)
		}
	}
	w.Flush()
}

package main

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

// We require that bs is always non-empty.
type Participant struct {
	a  int
	bs []int
}

func (p *Participant) maxBid() int {
	return p.bs[len(p.bs)-1]
}

// Preconditions:
// - There exists a bid in p.bs exceeding b
// - No bid in p.bs equals b
func (p *Participant) minBidExceeding(b int) int {
	return p.bs[sort.SearchInts(p.bs, b)]
}

// We sort the participants by their max bids in descending order.
type Auction []Participant

func (a Auction) Len() int           { return len(a) }
func (a Auction) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a Auction) Less(i, j int) bool { return a[i].maxBid() > a[j].maxBid() }

func (a Auction) winner(absent []int) (int, int) {
	isAbsent := make(map[int]bool)
	for _, a := range absent {
		isAbsent[a] = true
	}

	var top, second Participant

	// Find the participant with the top bid among those remaining.
	i := 0
	for i < len(a) && isAbsent[a[i].a] {
		i++
	}
	if i == len(a) {
		// Every participant was absent.
		return 0, 0
	}
	top = a[i]

	// Find the participant with the second-highest bid among those remaining.
	i++
	for i < len(a) && isAbsent[a[i].a] {
		i++
	}
	if i == len(a) {
		// Only one participant was not absent.  The first (lowest) bid made by
		// that participant wins the auction.
		return top.a, top.bs[0]
	}
	second = a[i]

	return top.a, top.minBidExceeding(second.maxBid())
}

// scanner.Split(bufio.ScanWords) must have been called on the given scanner.
func mustScanInt(scanner *bufio.Scanner) int {
	scanner.Scan()
	n, err := strconv.Atoi(scanner.Text())
	if err != nil {
		panic(err)
	}
	return n
}

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

	n := mustScanInt(scanner)
	participantToBids := make(map[int][]int)
	for i := 0; i < n; i++ {
		a := mustScanInt(scanner)
		b := mustScanInt(scanner)
		participantToBids[a] = append(participantToBids[a], b)
	}
	auction := make(Auction, 0, len(participantToBids))
	for a, bs := range participantToBids {
		p := Participant{
			a:  a,
			bs: bs,
		}
		auction = append(auction, p)
	}
	sort.Sort(auction)

	q := mustScanInt(scanner)
	for i := 0; i < q; i++ {
		k := mustScanInt(scanner)
		absent := make([]int, k)
		for j := 0; j < k; j++ {
			absent[j] = mustScanInt(scanner)
		}
		fmt.Println(auction.winner(absent))
	}
}

package main

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

const (
	N = 200000
)

type Bid struct {
	a int
	b int
}
type Bids []Bid

func (bids Bids) Len() int {
	return len(bids)
}
func (bids Bids) Less(i, j int) bool {
	return bids[i].b < bids[j].b
}
func (bids Bids) Swap(i, j int) {
	bids[i], bids[j] = bids[j], bids[i]
}

func last(arr []int) int {
	return arr[len(arr)-1]
}
func first(arr []int) int {
	return arr[0]
}

func main() {
	r := bufio.NewReader(os.Stdin)
	var n int
	bidTable := map[int][]int{}
	fmt.Fscanf(r, "%d\n", &n)
	for i := 1; i <= n; i++ {
		var a, b int
		fmt.Fscanf(r, "%d %d\n", &a, &b)
		bidTable[a] = append(bidTable[a], b)
	}
	// fmt.Printf("%v\n", bidTable)

	lastBids := Bids{}
	for a, bids := range bidTable {
		lastBids = append(lastBids, Bid{a, last(bids)})
	}
	sort.Sort(lastBids)
	hash := map[int]int{}
	for i, bid := range lastBids {
		hash[bid.a] = i
	}
	// fmt.Printf("%v\n", hash)

	w := bufio.NewWriter(os.Stdout)

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

	for q > 0 {
		q--
		var m int
		fmt.Fscanf(r, "%d", &m)
		absents := []int{len(hash)}
		for m > 0 {
			m--
			var v int
			fmt.Fscanf(r, "%d", &v)
			h, exists := hash[v]
			if exists {
				absents = append(absents, h)
			}
		}
		fmt.Fscanln(r)
		absents = append(absents, -1)
		sort.Sort(sort.Reverse(sort.IntSlice(absents)))

		// fmt.Printf("%v\n", absents)
		var winner, next *Bid
		for i := 0; i < len(absents)-1; i++ {
			presents := absents[i] - absents[i+1] - 1
			if presents == 0 {
				continue
			}
			if winner == nil {
				winner = &lastBids[absents[i]-1]
				presents--
			}
			if presents > 0 {
				next = &lastBids[absents[i]-1]
				break
			}
		}
		if winner == nil {
			fmt.Fprintf(w, "0 0\n")
		} else {
			bid := first(bidTable[winner.a])
			if next != nil {
				bid = bidTable[winner.a][sort.SearchInts(bidTable[winner.a], next.b)]
			}
			fmt.Fprintf(w, "%d %d\n", winner.a, bid)
		}
	}
	w.Flush()
}