Polycarp was presented with some sequence of integers $$$a$$$ of length $$$n$$$ ($$$1 \le a_i \le n$$$). A sequence can make Polycarp happy only if it consists of different numbers (i.e. distinct numbers).In order to make his sequence like this, Polycarp is going to make some (possibly zero) number of moves.In one move, he can:   remove the first (leftmost) element of the sequence. For example, in one move, the sequence $$$[3, 1, 4, 3]$$$ will produce the sequence $$$[1, 4, 3]$$$, which consists of different numbers.Determine the minimum number of moves he needs to make so that in the remaining sequence all elements are different. In other words, find the length of the smallest prefix of the given sequence $$$a$$$, after removing which all values in the sequence will be unique.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of two lines. The first line contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the given sequence $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — elements of the given sequence $$$a$$$. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print your answer on a separate line — the minimum number of elements that must be removed from the beginning of the sequence so that all remaining elements are different.

NoteThe following are the sequences that will remain after the removal of prefixes:  $$$[1, 4, 3]$$$;  $$$[1]$$$;  $$$[1]$$$;  $$$[6, 5, 4, 3, 2, 1]$$$;  $$$[2, 1]$$$. It is easy to see that all the remaining sequences contain only distinct elements. In each test case, the shortest matching prefix was removed.

package main
import(
    "fmt"
    "bufio"
    "os"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var n int
		fmt.Fscan(in,&n)
		list:= make([]int,n)
		for j:=0;j<n;j++{
			fmt.Fscan(in,&list[j])
		}
		mapper:= make(map[int]bool) // create a map
		for j:=n-1;j>=0;j--{ // loop through each element, starting from end
			if mapper[list[j]] { // if map coords exist, print j (position in the loop)
				fmt.Fprintln(out,j+1)
				goto out
			}
			mapper[list[j]]= true // if first time, add map coords to map
		}
		fmt.Fprintln(out,0)
		out:
	}
}

package main

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

func solve() {
	n := get()
	A := geta(n)
	occur := make([]bool, n)
	for i := n - 1; i >= 0; i-- {
		if occur[A[i]-1] {
			putln(i + 1)
			return
		}
		occur[A[i]-1] = true
	}
	putln(0)
}

const (
	once = false
)

var (
	in  *bufio.Scanner
	out *bufio.Writer
)

func main() {
	in = bufio.NewScanner(bufio.NewReader(os.Stdin))
	in.Split(bufio.ScanWords)

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

	if once {
		solve()
		return
	}

	for t := get(); t > 0; t-- {
		solve()
	}
}

func geta(n int) []int {
	a := make([]int, n)
	for i := range a {
		a[i] = get()
	}
	return a
}

func get() int {
	x, _ := strconv.Atoi(gets())
	return x
}

func gets() string {
	scan()
	return in.Text()
}

func scan() {
	in.Scan()
}

func put(x int) {
	out.WriteString(strconv.Itoa(x))
}

func putln(x int) {
	put(x)
	putc('\n')
}

func putc(c rune) {
	out.WriteRune(c)
}

package main

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

func solve() {
	A := geta(get())
	occur := make([]bool, len(A))
	for N := len(A) - 1; N >= 0; N-- {
		if occur[A[N]-1] {
			fmt.Println(N + 1)
			return
		}
		occur[A[N]-1] = true
	}
	fmt.Println(0)
}

const (
	once = false
)

var (
	in  *bufio.Scanner
	out *bufio.Writer
)

func main() {
	in = bufio.NewScanner(bufio.NewReader(os.Stdin))
	in.Split(bufio.ScanWords)

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

	if once {
		solve()
		return
	}

	for t := get(); t > 0; t-- {
		solve()
	}
}

func geta(n int) []int {
	a := make([]int, n)
	for i := range a {
		a[i] = get()
	}
	return a
}

func get() int {
	x, _ := strconv.Atoi(gets())
	return x
}

func gets() string {
	scan()
	return in.Text()
}

func scan() {
	in.Scan()
}

func put(x int) {
	out.WriteString(strconv.Itoa(x))
}

func putln(x int) {
	put(x)
	putc('\n')
}

func putc(c rune) {
	out.WriteRune(c)
}

package main

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

func solve() {
	A := geta(get())
	occur := make(map[int]bool)
	for N := len(A) - 1; N >= 0; N-- {
		if occur[A[N]] {
			fmt.Println(N + 1)
			return
		}
		occur[A[N]] = true
	}
	fmt.Println(0)
}

const (
	once = false
)

var (
	in  *bufio.Scanner
	out *bufio.Writer
)

func main() {
	in = bufio.NewScanner(bufio.NewReader(os.Stdin))
	in.Split(bufio.ScanWords)

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

	if once {
		solve()
		return
	}

	for t := get(); t > 0; t-- {
		solve()
	}
}

func geta(n int) []int {
	a := make([]int, n)
	for i := range a {
		a[i] = get()
	}
	return a
}

func get() int {
	x, _ := strconv.Atoi(gets())
	return x
}

func gets() string {
	scan()
	return in.Text()
}

func scan() {
	in.Scan()
}

package main

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

var IN = bufio.NewReader(os.Stdin)

func main() {
	var t int
	fmt.Fscan(IN, &t)
	for ; t > 0; t-- {
		testCase()
	}
}

func testCase() {
	var N int
	fmt.Fscan(IN, &N)
	A := make([]int, N)
	for i := range A {
		fmt.Fscan(IN, &A[i])
	}
	occur := make(map[int]bool)
	for N = N - 1; N >= 0; N-- {
		if occur[A[N]] {
			fmt.Println(N + 1)
			return
		}
		occur[A[N]] = true
	}
	fmt.Println(0)
}

package main

import (

	"bufio"
	"os"
	"fmt"
)

var (

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

func max(a, b int) int {

	if a > b {

		return a
	}
	return b
}

func main() {

	defer out.Flush()

	var T int
	fmt.Fscan(in, &T)
	for i := 0; i < T; i++ {

		var n int
		fmt.Fscan(in, &n)
		var ans = -1
		var mp map[int]int = map[int]int{}
		for j := 0; j < n; j++ {

			var x int
			fmt.Fscan(in, &x)
			if val, ok := mp[x]; ok {

				ans = max(val, ans)
			}
			mp[x] = j
		}
		fmt.Fprintln(out, ans + 1)
	}
}

package main

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

var IN *bufio.Reader

func cp() {
	N := readInt(IN)
	A := readArrInt(IN)
	unique := 0
	numberExists := make(map[int]bool)
	for i := N - 1; i >= 0; i-- {
		if _, exists := numberExists[A[i]]; exists {
			break
		}
		unique++
		numberExists[A[i]] = true
	}

	fmt.Println(N - unique)
}

func main() {
	t := 1
	t = readInt(IN)
	for ; t > 0; t-- {
		cp()
	}
}

func init() {
	IN = bufio.NewReader(os.Stdin)
}

func Max(x, y int) int {
	if x < y {
		return y
	}
	return x
}
func Min(x, y int) int {
	if x > y {
		return y
	}
	return x
}

func readInt(in *bufio.Reader) int {
	nStr, _ := in.ReadString('\n')
	nStr = strings.ReplaceAll(nStr, "\r", "")
	nStr = strings.ReplaceAll(nStr, "\n", "")
	n, _ := strconv.Atoi(nStr)
	return n
}

func readLineNumbs(in *bufio.Reader) []string {
	line, _ := in.ReadString('\n')
	line = strings.ReplaceAll(line, "\r", "")
	line = strings.ReplaceAll(line, "\n", "")
	numbs := strings.Split(line, " ")
	return numbs
}

func readArrInt(in *bufio.Reader) []int {
	numbs := readLineNumbs(in)
	arr := make([]int, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.Atoi(n)
		arr[i] = val
	}
	return arr
}

func readArrInt64(in *bufio.Reader) []int64 {
	numbs := readLineNumbs(in)
	arr := make([]int64, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.ParseInt(n, 10, 64)
		arr[i] = val
	}
	return arr
}

package main

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

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

	var T int
	fmt.Fscan(in, &T)
	for t := 0; t < T; t++ {
		var n int
		fmt.Fscan(in, &n)

		aa := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &aa[i])
		}
		var d int
		var f bool
		bb := make([]bool, n+1)
		for i := n - 1; i >= 0; i-- {
			if !bb[aa[i]] {
				bb[aa[i]] = true
				continue
			}
			d = i
			f = true
			break
		}
		if !f {
			fmt.Fprintln(out, 0)
		} else {
			fmt.Fprintln(out, d+1)
		}
	}
}

// B. Удали префикс
// https://codeforces.com/contest/1714/problem/B
package main

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

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

	var CountData int
	fmt.Fscan(in, &CountData)

	for t := 0; t < CountData; t++ {
		var Lenght int
		fmt.Fscan(in, &Lenght)

		MapElem := make(map[int]int)
		EndInd := -1

		for n := 0; n < Lenght; n++ {
			var Elem int
			fmt.Fscan(in, &Elem)

			if Ind, ok := MapElem[Elem]; ok {
				if EndInd < Ind {
					EndInd = Ind
				}
			}
			MapElem[Elem] = n
		}

		fmt.Fprintln(out, 1+EndInd)
	}
}

package main

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

const MAXN = 2e5

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	a := make([]int, MAXN+7)
	rcd := make([]int, MAXN+7)
	var t, n, i, ans int
	fmt.Fscan(in, &t)
	for t != 0 {
		fmt.Fscan(in, &n)
		for i = 1; i <= n; i++ {
			fmt.Fscan(in, &a[i])
		}
		ans = 0
		for i = n; i != 0; i-- {
			if rcd[a[i]] == t {
				break
			}
			ans++
			rcd[a[i]] = t
		}
		fmt.Fprintln(out, n-ans)
		t--
	}
}

package main

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

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

func ReadInt() int{
	var i int
	fmt.Fscan(in, &i)
	return i
}

func main(){
	defer out.Flush()
	t := ReadInt()
	for ; t > 0; t--{
		n := ReadInt()
		a := make([]int, n)
		who := make([]int, n+1)
		for i:=0;i<n;i++{
			a[i] = ReadInt()
		}
		found:=false
		for i:=n-1;i>=0;i--{
			if who[a[i]]==1{
				found=true
				fmt.Fprintln(out, i+1)
				break
			}
			who[a[i]] = 1
		}
		if !found{
			fmt.Fprintln(out, 0)
		}
	}
}

package main

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

var (
  in = bufio.NewReader(os.Stdin)
  out = bufio.NewWriter(os.Stdout)
)
func scan(a ...any) {
  fmt.Fscan(in, a...)
}
func printf(f string, a ...any) {
  fmt.Fprintf(out, f, a...)
}

func solve() {
  var n int
  scan(&n)
  a := make([]int, n)
  for i := 0; i < n; i++ { scan(&a[i]) }

  cnt := make(map[int]int)
  for i := n - 1; i >= 0; i-- {
    if _, ok := cnt[a[i]]; ok {
      printf("%d\n", i + 1)
      return
    }
    cnt[a[i]] = 1
  }
  printf("%d\n", 0)
}

func main() {
  defer out.Flush()
  var t int
  scan(&t)
  for i := 0; i < t; i++ {
    solve()
  }
}

package main

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

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

func scan(a ...interface{}) {
	fmt.Fscan(in, a...)
}
func printf(f string, a ...interface{}) {
	fmt.Fprintf(out, f, a...)
}
func solve() {
	var n int
	scan(&n)
	a := make([]int, n)
	f := make([]int, n+1)
	for i := 0; i < n; i++ {
		scan(&a[i])
	}
	id := n - 1
	for ; id >= 0; id-- {
		if f[a[id]] == 0 {
			f[a[id]]++
		} else {
			break
		}
	}
	printf("%d\n", id+1)
}

func main() {
	defer out.Flush()
	n := 0
	scan(&n)
	for i := 0; i < n; i++ {
		solve()
	}
}

package main

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

func solve(in io.Reader, out io.Writer) {
	var n int
	fmt.Fscan(in, &n)
	arr := []int{}
	for i := 0; i < n; i++ {
		var num int
		fmt.Fscan(in, &num)
		arr = append(arr, num)
	}
	mp := make(map[int]bool)
	for i := n - 1; i >= 0; i-- {
		if !mp[arr[i]] {
			mp[arr[i]] = true
		} else {
			fmt.Fprintln(out, i+1)
			return
		}
	}
	fmt.Fprintln(out, 0)
}

func main() {
	in := bufio.NewReader(os.Stdin)
	// in, _ := os.Open("in.txt")
	t := 1
	fmt.Fscan(in, &t)
	for t > 0 {
		solve(in, os.Stdout)
		t--
	}
}

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

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

package main

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

var _, _, _ = main, rw, do

func main() {
	r, w := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer w.Flush()
	rw(r, w)
}

func rw(r io.Reader, w io.Writer) {
	var t int
	fmt.Fscan(r, &t)
	for ti := 0; ti < t; ti++ {
		var n int
		fmt.Fscan(r, &n)
		a := make([]int, n)
		for i := range a {
			fmt.Fscan(r, &a[i])
		}
		w1 := do(n, a)
		fmt.Fprintln(w, w1)
	}
}

func do(n int, a []int) int {
	m := make(map[int]bool)
	for i := len(a) - 1; i >= 0; i-- {
		if m[a[i]] {
			return i + 1
		}
		m[a[i]] = true
	}
	return 0
}

package main

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

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

	n := 0
	fmt.Fscan(reader, &n)
	for i := 0; i < n; i++ {
		var m int
		fmt.Fscan(reader, &m)
		am := make(map[int]bool)
		a := make([]int, m, m)
		for j := 0; j < m; j++ {
			fmt.Fscan(reader, &a[j])
		}
		max := 0
		for j := m - 1; j >= 0; j-- {
			if _, ok := am[a[j]]; ok {
				break
			} else {
				am[a[j]] = false
				max++
			}

		}

		fmt.Fprintf(writer, "%d\n", m-max)
	}
}

package main

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

var (
	reader = bufio.NewReader(os.Stdin)
	t, n   int
	a      []int
)

func solve(n int, a []int) int {
	var b, c = make([]int, n), make(map[int]int)
	for i, x := range a {
		lastRepeated, ok := c[x]
		if !ok {
			b[i] = -1
		} else {
			b[i] = lastRepeated
		}
		c[x] = i
	}
	var maxb = -1
	for i := range b {
		if b[i] > maxb {
			maxb = b[i]
		}
	}
	return maxb + 1
}

func main() {
	fmt.Fscan(reader, &t)
	for ; t > 0; t-- {
		fmt.Fscan(reader, &n)
		a = make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(reader, &a[i])
		}
		fmt.Println(solve(n, a))
	}
}

package main

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

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

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

func solve(n int, a []int) int {
    ans := n
    mp := make(map[int]int)
    for i := n-1; i >= 0; i-- {
        if _, ok := mp[a[i]]; ok {
            break
        }
        mp[a[i]]++
        ans--
    }
    return ans
}

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

    var t int
    fmt.Fscan(in, &t)
    for i := 0; i < t; i++ {
        var n int
        fmt.Fscan(in, &n)
        a := make([]int, n)
        for j := 0; j < n; j++ {
            fmt.Fscan(in, &a[j])
        }

        ans := solve(n, a)
        fmt.Fprintln(out, ans)
    }
}

package main

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

type CF1714B struct {
	sc        *bufio.Reader
	split     []string
	index     int
	separator string
}

func (in *CF1714B) GetLine() string {
	line, err := in.sc.ReadString('\n')
	if err != nil {
		fmt.Println("error line:", line, " err: ", err)
	}
	in.split = []string{}
	in.index = 0
	return line
}
func (in *CF1714B) load() {
	if len(in.split) <= in.index {
		in.split = strings.Split(in.GetLine(), in.separator)
		in.index = 0
	}
}

func (in *CF1714B) NextInt() int {
	in.load()
	val, _ := strconv.Atoi(strings.TrimSpace(in.split[in.index]))
	in.index++
	return val
}

func (in *CF1714B) NextInt64() int64 {
	in.load()
	val, _ := strconv.ParseInt(strings.TrimSpace(in.split[in.index]), 10, 64)
	in.index++
	return val
}

func (in *CF1714B) NextString() string {
	in.load()
	val := strings.TrimSpace(in.split[in.index])
	in.index++
	return val
}

/**
Run solve the problem CF1714B
Date: 3/08/22
User: pepradere
URL: https://codeforces.com/problemset/problem/1714/B
Problem: CF1714B
**/
func (in *CF1714B) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		arr := make([]int, n)

		for i := 0; i < n; i++ {
			arr[i] = in.NextInt()
		}
		mapa := make(map[int]bool)
		ans := 0
		for i := n - 1; i >= 0; i-- {
			_, e := mapa[arr[i]]
			if !e {
				mapa[arr[i]] = true
			} else {
				ans = i + 1
				break
			}
		}

		fmt.Println(ans)
	}
}

func NewCF1714B(r *bufio.Reader) *CF1714B {
	return &CF1714B{
		sc:        r,
		split:     []string{},
		index:     0,
		separator: " ",
	}
}

func main() {
	NewCF1714B(bufio.NewReader(os.Stdin)).Run()
}

package main

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

func main() {
	// START WRITING YOUR SOLUTION HERE:
	// writeLine(typeOf(readInt()))
	n := readInt()
	/*for i := 0; i < n; i++ {
		tmp := readInts()
		bedT := tmp[1]*60 + tmp[2]
		var times []int
		f := false
		for j := 0; j < tmp[0]; j++ {
			tt := readInts()
			t := tt[0]*60 + tt[1]
			times = append(times, t)
			if t == bedT {
				f = true
				break
			}
		}
		if f || len(times) == 0 {
			writeLine("0 0")
		} else {
			sort.Ints(times)
			//writeLine(times)
			if times[len(times)-1] < bedT {
				d := 1440 - bedT
				//writeLine(bedT, times[0])
				writeLine(fmt.Sprintf("%d %d", (times[0]+d)/60, (times[0]+d)%60))
			} else {
				for i := 0; i < len(times); i++ {
					if times[i] > bedT {
						writeLine(fmt.Sprintf("%d %d", (times[i]-bedT)/60, (times[i]-bedT)%60))
						break
					}
				}
			}
		}
	}*/
	for i := 0; i < n; i++ {
		m := readInt()
		seq := readInts()
		mm := make(map[int]int)
		mmm := make(map[int]struct{})
		for j := 0; j < m; j++ {
			mm[seq[j]]++
			if _, ok := mmm[seq[j]]; !ok && mm[seq[j]] > 1 {
				mmm[seq[j]] = struct{}{}
			}
		}
		if len(mmm) == 0 {
			writeLine("0")
		} else {
			for j := 0; j < m; j++ {
				mm[seq[j]]--
				if _, ok := mmm[seq[j]]; ok && mm[seq[j]] == 1 {
					delete(mmm, seq[j])
				}
				if len(mmm) == 0 {
					writeLine(fmt.Sprintf("%d", j+1))
					break
				}
			}
		}
	}
}

/* ~~~~~~~~~~ */
/* ~~~~~~~~~~ */
/* ~~~~~~~~~~ */

var in = bufio.NewReader(os.Stdin)

type float = float32
type double = float64
type long = int64
type ulong = uint64

func typeOf(arg interface{}) string {
	switch reflect.TypeOf(arg).Kind() {
	case reflect.Int:
		return "int"
	case reflect.Int8:
		return "int8"
	case reflect.Int16:
		return "int16"
	case reflect.Int32:
		return "int32"
	case reflect.Int64:
		return "int64"
	case reflect.Uint:
		return "uint"
	case reflect.Uint8:
		return "uint8"
	case reflect.Uint16:
		return "uint16"
	case reflect.Uint32:
		return "uint32"
	case reflect.Uint64:
		return "uint64"
	case reflect.Float32:
		return "float32"
	case reflect.Float64:
		return "float64"
	case reflect.Complex64:
		return "complex64"
	case reflect.Complex128:
		return "complex128"
	case reflect.Bool:
		return "bool"
	case reflect.String:
		return "string"
	case reflect.Chan:
		return "chan"
	case reflect.Ptr:
		return "ptr"
	case reflect.Uintptr:
		return "uintptr"
	case reflect.UnsafePointer:
		return "unsafeptr"
	case reflect.Interface:
		return "interface"
	case reflect.Array:
		return "array"
	case reflect.Slice:
		return "slice"
	case reflect.Map:
		return "map"
	case reflect.Struct:
		return "struct"
	case reflect.Func:
		return "func"
	case reflect.Invalid:
		return "invalid"
	default:
		return "nil"
	}
}

/* ~~~~~~~~~~ */

func _scln() string {
	ln, _ := in.ReadString('\n')
	return strings.Trim(ln, " \r\n")
}

func _sc(s []string) string {
	if len(s) == 0 {
		return _scln()
	}
	return s[0]
}

func readLine() string              { return _scln() }
func readString() string            { return _scln() }
func readStrings() []string         { return strings.Split(_scln(), " ") }
func readBool(s ...string) bool     { t, _ := strconv.ParseBool(_sc(s)); return t }
func readByte(s ...string) byte     { t, _ := strconv.ParseUint(_sc(s), 10, 8); return byte(t) }
func readDouble(s ...string) double { t, _ := strconv.ParseFloat(_sc(s), 64); return t }
func readFloat(s ...string) float   { t, _ := strconv.ParseFloat(_sc(s), 32); return float32(t) }
func readInt(s ...string) int       { t, _ := strconv.Atoi(_sc(s)); return t }
func readLong(s ...string) long     { t, _ := strconv.ParseInt(_sc(s), 10, 64); return t }
func readULong(s ...string) ulong   { t, _ := strconv.ParseUint(_sc(s), 10, 64); return t }

/* ~~~~~~~~~~ */

// Too much overhead with universal method using interface{}, wait for the generics,
// but for now — just don't look at the redundancy of the code after that commentary :)

func readBools() []bool {
	strs := readStrings()
	arr := make([]bool, len(strs))
	for i, s := range strs {
		arr[i] = readBool(s)
	}
	return arr
}
func readBytes() []byte {
	strs := readStrings()
	arr := make([]byte, len(strs))
	for i, s := range strs {
		arr[i] = readByte(s)
	}
	return arr
}
func readDoubles() []double {
	strs := readStrings()
	arr := make([]double, len(strs))
	for i, s := range strs {
		arr[i] = readDouble(s)
	}
	return arr
}
func readFloats() []float {
	strs := readStrings()
	arr := make([]float, len(strs))
	for i, s := range strs {
		arr[i] = readFloat(s)
	}
	return arr
}
func readInts() []int {
	strs := readStrings()
	arr := make([]int, len(strs))
	for i, s := range strs {
		arr[i] = readInt(s)
	}
	return arr
}
func readLongs() []long {
	strs := readStrings()
	arr := make([]long, len(strs))
	for i, s := range strs {
		arr[i] = readLong(s)
	}
	return arr
}
func readULongs() []ulong {
	strs := readStrings()
	arr := make([]ulong, len(strs))
	for i, s := range strs {
		arr[i] = readULong(s)
	}
	return arr
}

/* ~~~~~~~~~~ */

func write(arg ...interface{})                 { fmt.Print(arg...) }
func writeLine(arg ...interface{})             { fmt.Println(arg...) }
func writeFormat(f string, arg ...interface{}) { fmt.Printf(f, arg...) }

package main

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

var in = bufio.NewReader(os.Stdin)

func main() {
	var T int
	fmt.Fscan(in, &T)
	for i := 0; i < T; i++ {
		var n int
		fmt.Fscan(in, &n)
		a := make([]int, n)
		for k := 0; k < n; k++ {
			fmt.Fscan(in, &a[k])
		}
		mp := make(map[int]bool)
		res := n
		for k := n - 1; k >= 0; k-- {
			if !mp[a[k]] {
				res--
				mp[a[k]] = true
			} else {
				break
			}
		}
		fmt.Println(res)
	}
}

package main

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

func solve() {
	n := get()
	a := geta1(n)
	c := ints(n, 0)
	for _, v := range a {
		c[v]++
	}
	count := 0
	for _, v := range c {
		if v < 2 {
			continue
		}
		count++
	}
	i := 0
	for count > 0 {
		x := a[i]
		c[x]--
		if c[x] == 1 {
			count--
		}
		i++
	}
	putln(i)
}

const (
	once       = false
	maxBufSize = 0 //10_000_000
	YES        = "YES"
	NO         = "NO"
)

var (
	splitFunc = bufio.ScanWords //bufio.SplitFunc(nil)
)

func main() {
	in = bufio.NewScanner(bufio.NewReader(os.Stdin))
	if splitFunc != nil {
		in.Split(splitFunc)
	}
	if maxBufSize > 0 {
		in.Buffer(make([]byte, maxBufSize), maxBufSize)
	}

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

	if once {
		solve()
		return
	}

	for t := get(); t > 0; t-- {
		solve()
	}
}

var (
	in  *bufio.Scanner
	out *bufio.Writer
)

func get() int {
	x, _ := strconv.Atoi(gets())
	return x
}

func geta(n int) []int {
	a := make([]int, n)
	for i := range a {
		a[i] = get()
	}
	return a
}

func geta1(n int) []int {
	a := make([]int, n)
	for i := range a {
		a[i] = get() - 1
	}
	return a
}

func get64() int64 {
	x, _ := strconv.ParseInt(gets(), 10, 64)
	return x
}

func get64a(n int) []int64 {
	a := make([]int64, n)
	for i := range a {
		a[i] = get64()
	}
	return a
}

func get64a1(n int) []int64 {
	a := make([]int64, n)
	for i := range a {
		a[i] = get64() - 1
	}
	return a
}

func getf() float64 {
	x, _ := strconv.ParseFloat(gets(), 64)
	return x
}

func getfa(n int) []float64 {
	a := make([]float64, n)
	for i := range a {
		a[i] = getf()
	}
	return a
}

func gets() string {
	scan()
	return in.Text()
}

func scanN(n int) {
	for n > 0 {
		scan()
		n--
	}
}

func scan() {
	in.Scan()
}

func putc(c rune) {
	out.WriteRune(c)
}

func line() {
	putc('\n')
}

func space() {
	putc(' ')
}

func put(x int) {
	out.WriteString(strconv.Itoa(x))
}

func putln(i int) {
	put(i)
	line()
}

func puta(a []int) {
	for _, v := range a {
		put(v)
		space()
	}
	line()
}

func put64(x int64) {
	out.WriteString(strconv.FormatInt(x, 10))
}

func put64ln(x int64) {
	put64(x)
	line()
}

func put64a(a []int64) {
	for _, v := range a {
		put64(v)
		space()
	}
	line()
}

func puts(s string) {
	out.WriteString(s)
}

func putsln(s string) {
	puts(s)
	line()
}

func yn(y bool) {
	if y {
		yes()
		return
	}
	no()
}

func yes() {
	puts(YES)
	line()
}

func no() {
	puts(NO)
	line()
}

func putf(x float64) {
	out.WriteString(strconv.FormatFloat(x, 'f', -1, 64))
}

func putfln(x float64) {
	putf(x)
	line()
}

func putfa(a []float64) {
	for _, v := range a {
		putf(v)
		space()
	}
	line()
}

type IntTp interface {
	int | int64
}

type Tp interface {
	IntTp | float64
}

func abs[T IntTp](x T) T {
	if x < 0 {
		return -x
	}
	return x
}

func fabs(x float64) float64 {
	return math.Abs(x)
}

func max1[T Tp](x T, y T) T {
	if x > y {
		return x
	}
	return y
}

func max[T Tp](xs ...T) T {
	r := xs[0]
	for _, x := range xs[1:] {
		r = max1(r, x)
	}
	return r
}

func maxa[T Tp](a []T) (i int, val T) {
	i, val = 0, a[0]
	for j := 1; j < len(a); j++ {
		if a[j] <= val {
			continue
		}
		i = j
		val = a[j]
	}
	return
}

func min1[T Tp](x T, y T) T {
	if x < y {
		return x
	}
	return y
}

func min[T Tp](xs ...T) T {
	r := xs[0]
	for _, x := range xs[1:] {
		r = min1(r, x)
	}
	return r
}

func mina[T Tp](a []T) (i int, val T) {
	i, val = 0, a[0]
	for j := 1; j < len(a); j++ {
		if a[j] >= val {
			continue
		}
		i = j
		val = a[j]
	}
	return
}

func L(i int) int64 {
	return int64(i)
}

func F(i int) float64 {
	return float64(i)
}

func ints(n int, val int) (a []int) {
	a = make([]int, n)
	if val == 0 {
		return
	}
	for i := range a {
		a[i] = val
	}
	return
}

func int64s(n int, val int64) (a []int64) {
	a = make([]int64, n)
	if val == 0 {
		return
	}
	for i := range a {
		a[i] = val
	}
	return
}

func floats(n int, val float64) (a []float64) {
	a = make([]float64, n)
	if val == 0 {
		return
	}
	for i := range a {
		a[i] = val
	}
	return
}

const heapBase = 4

func children(i int) (int, int) {
	start := heapBase * i
	return start + 1, start + (1 + heapBase)
}

func parent(i int) int {
	return (i - 1) / heapBase
}

package main

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

var scanner = bufio.NewScanner(os.Stdin)
var writter = bufio.NewWriter(os.Stdout)

func scan(args ...*int) {

	for _, arg := range args {
		scanner.Scan()
		*arg, _ = strconv.Atoi(scanner.Text())
	}
}

func print(args ...interface{}) {
	writter.WriteString(fmt.Sprintln(args...))
}

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

func main() {
	scanner.Split(bufio.ScanWords)
	defer writter.Flush()
	var t int

	scan(&t)

	var n int

	for i := 0; i < t; i++ {
		scan(&n)
		a := make([]int, n, n)
		for j := 0; j < n; j++ {
			scan(&a[j])
		}

		aa := make(map[int]bool)
		for j := len(a) - 1; j >= 0; j-- {
			if aa[a[j]] == true {
				print(j + 1)
				break
			}
			aa[a[j]] = true
			if j == 0 {
				print(0)
			}
		}
	}
}

// 1714B. Remove Prefix
package main

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

func main() {
	var T int
	reader := bufio.NewReader(os.Stdin)
	fmt.Fscan(reader, &T)
	for t := 1; t <= T; t++ {
		var n int
		fmt.Fscan(reader, &n)
		a := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(reader, &a[i])
		}
		m := make(map[int]bool)
		ans := 0
		for i := n - 1; i >= 0; i-- {
			if m[a[i]] {
				ans = i + 1
				break
			} else {
				m[a[i]] = true
			}
		}
		fmt.Println(ans)
	}
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	var t,N,a,anc int

	fmt.Fscan(in, &t)
	for i := 0;i < t;i++{
		fmt.Fscan(in, &N)
		m := make(map[int]int)
		anc = -1
		for j := 0;j < N;j++{
			fmt.Fscan(in, &a)
			if _,ok := m[a];ok{
				if anc < m[a]{
					anc = m[a]
				}
				m[a] = j
			}else{
				m[a] = j
			}

		}
		if anc == -1{
			fmt.Println(0)
		}else{
			fmt.Println(anc+1)
		}

	}

}

package main

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

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

func solve() string {
	var n int
	fmt.Fscan(in, &n)
	nums := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &nums[i])
	}

	cnt := 0
	set := make(map[int]bool)
	for i := n - 1; i >= 0; i-- {
		if exists := set[nums[i]]; exists {
			break
		}
		set[nums[i]] = true
		cnt++
	}

	return strconv.FormatInt(int64(n-cnt), 10)
}

func main() {
	defer out.Flush()
	var t int
	for fmt.Fscanln(in, &t); t > 0; t-- {
		fmt.Fprintln(out, solve())
	}
}

// util functions
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
}

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

func makeMatrix(n, m int) [][]int {
	x := make([][]int, n)
	for i := range x {
		x[i] = make([]int, m)
	}
	return x
}

package main

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

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

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

func gcd(a, b int64) int64 {
	if a < b {
		a, b = b, a
	}
	if a%b == 0 {
		return b
	} else {
		return gcd(b, a%b)
	}
}

func main() {
	scanner := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var niter int
	fmt.Fscan(scanner, &niter)
	for iiter := 0; iiter < niter; iiter++ {
		var n int
		fmt.Fscan(scanner, &n)
		slc := make([]int, n)
		m := make(map[int]bool)
		l := 0
		for i := 0; i < n; i++ {
			fmt.Fscan(scanner, &slc[i])
		}
		for i := n - 1; i >= 0; i-- {
			if _, ok := m[slc[i]]; ok {
				break
			} else {
				m[slc[i]] = true
				l++
			}
		}
		fmt.Fprintln(writer, n-l)
	}
}

package main

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

func readLine() string {
	s, err := f.ReadString('\n')
	if err != nil {
		panic(err)
	}
	s = strings.ReplaceAll(s, "\n", "")
	s = strings.ReplaceAll(s, "\r", "")
	return s
}

func readInts(n int) []int {
	s := readLine()
	as := strings.SplitN(s, " ", n)
	if len(as) != n {
		panic("invalid len")
	}
	arr := make([]int, n)
	for k, a := range as {
		x, _ := strconv.ParseInt(a, 10, 64)
		arr[k] = int(x)
	}
	return arr
}

var f = bufio.NewReader(os.Stdin)

func main() {
	var t, n int

	l1 := readInts(1)
	t = l1[0]

outer:
	for i := 0; i < t; i++ {
		l1 = readInts(1)
		n = l1[0]

		arr := readInts(n)

		mp := make(map[int]bool, n)
		for j := len(arr) - 1; j >= 0; j-- {
			if mp[arr[j]] {
				fmt.Println(j + 1)
				continue outer
			}
			mp[arr[j]] = true
		}
		fmt.Println(0)
	}
}

package main
import(
    "fmt"
    "bufio"
    "os"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var n int
		fmt.Fscan(in,&n)
		list:= make([]int,n)
		for j:=0;j<n;j++{
			fmt.Fscan(in,&list[j])
		}
		for j:=n-1;j>n-len(list);j--{
			for k:=j-1;k>=0;k--{
				if list[j] == list[k] {
					list = list[k+1:]
					j-=k
					break
				}
			}
		}
		fmt.Fprintln(out,n-len(list))
	}
}

package main
import(
    "fmt"
    "bufio"
    "os"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var n int
		fmt.Fscan(in,&n)
		list:= make([]int,n)
		for j:=0;j<n;j++{
			fmt.Fscan(in,&list[j])
		}
		for j:=n-1;j>0;j--{
			for k:=j-1;k>=0;k--{
				if list[j] == list[k] {
					list=list[k+1:]
					goto out
				}
			}
		}
		out:
		fmt.Fprintln(out,n-len(list))
	}
}

package main

import (

	"bufio"
	"os"
	"fmt"
)

var (

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

func main() {

	defer out.Flush()

	var T int
	fmt.Fscan(in, &T)
	for i := 0; i < T; i++ {

		var n int64
		fmt.Fscan(in, &n)
		var ans = int64(-1)
		var mp map[int64]int64 = map[int64]int64{}
		for j := 0; int64(j) < n; j++ {

			var x int64
			fmt.Fscan(in, &x)
			if val, ok := mp[x]; ok {

				ans = val
			}
			mp[x] = int64(j)
		}
		fmt.Fprintln(out, ans + 1)
	}
}

package main

import (

	"bufio"
	"os"
	"fmt"
)

var (

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

func main() {

	defer out.Flush()

	var T int
	fmt.Fscan(in, &T)
	for i := 0; i < T; i++ {

		var n int
		fmt.Fscan(in, &n)
		var ans = -1
		var mp map[int]int = map[int]int{}
		for j := 0; j < n; j++ {

			var x int
			fmt.Fscan(in, &x)
			if val, ok := mp[x]; ok {

				ans = val
			}
			mp[x] = j
		}
		fmt.Fprintln(out, ans + 1)
	}
}

package main

import (

	"bufio"
	"os"
	"fmt"
)

var (

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

func main() {

	defer out.Flush()

	var T, n int
	fmt.Fscan(in, &T)
	for i := 0; i < T; i++ {

		fmt.Fscan(in, &n)
		var ans = -1
		var mp map[int]int = map[int]int{}
		for j := 0; j < n; j++ {

			var x int
			fmt.Fscan(in, &x)
			if val, ok := mp[x]; ok {

				ans = val
			}
			mp[x] = j
		}
		fmt.Fprintln(out, ans + 1)
	}
}

package main

import (
	"fmt"
)

func Max(x, y int) int {
	if x < y {
		return y
	}
	return x
}
func Min(x, y int) int {
	if x > y {
		return y
	}
	return x
}

func cp() {
	var N int
	fmt.Scanf("%d\n", &N)
	var A []int = make([]int, N)
	for i := range A {
		fmt.Scanf("%d", &A[i])
	}
	unique := 0
	numberExists := make(map[int]bool)
	for i := N - 1; i >= 0; i-- {
		if _, exists := numberExists[A[i]]; exists {
			break
		}
		unique++
		numberExists[A[i]] = true
	}

	fmt.Println(N - unique)
}

func main() {
	t := 1
	fmt.Scanf("%d\n", &t)
	for ; t > 0; t-- {
		cp()
	}
}

package main

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

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

	var T int
	fmt.Fscan(in, &T)
	for t := 0; t < T; t++ {
		var n int
		fmt.Fscan(in, &n)

		aa := make([]int, n+1)
		for i := 0; i < n+1; i++ {
			aa[i] = -1
		}
		var d int
		var f bool
		for i := 0; i < n; i++ {
			var v int
			fmt.Fscan(in, &v)
			if aa[v] >= 0 {
				d = aa[v]
				f = true
			}
			aa[v] = i
		}
		if !f {
			fmt.Fprintln(out, 0)
		} else {
			fmt.Fprintln(out, d+1)
		}
	}
}

package main

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

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

	var T int
	fmt.Fscan(in, &T)
	for t := 0; t < T; t++ {
		var n int
		fmt.Fscan(in, &n)

		aa := make([]int, n+1)
		for i := 0; i < n+1; i++ {
			aa[i] = -1
		}
		d := -1
		for i := 0; i < n; i++ {
			var v int
			fmt.Fscan(in, &v)
			if aa[v] >= 0 {
				d = aa[v]
			}
			aa[v] = i
		}
		if d < 0 {
			d = 0
		} else {
			d++
		}
		fmt.Fprintln(out, d)
	}
}

// B. Удали префикс
// https://codeforces.com/contest/1714/problem/B
package main

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

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

	var CountData int
	fmt.Fscan(in, &CountData)

	for t := 0; t < CountData; t++ {
		var Lenght int
		fmt.Fscan(in, &Lenght)

		MapElem := make(map[int]int)
		EndInd := -1

		for n := 0; n < Lenght; n++ {
			var Elem int
			fmt.Fscan(in, &Elem)

			if Ind, ok := MapElem[Elem]; ok {
				EndInd = Ind
			}
			MapElem[Elem] = n
		}

		fmt.Fprintln(out, 1+EndInd)
	}
}


At first, there was a legend related to the name of the problem, but now it's just a formal statement.You are given $$$n$$$ points $$$a_1, a_2, \dots, a_n$$$ on the $$$OX$$$ axis. Now you are asked to find such an integer point $$$x$$$ on $$$OX$$$ axis that $$$f_k(x)$$$ is minimal possible.The function $$$f_k(x)$$$ can be described in the following way:   form a list of distances $$$d_1, d_2, \dots, d_n$$$ where $$$d_i = |a_i - x|$$$ (distance between $$$a_i$$$ and $$$x$$$);  sort list $$$d$$$ in non-descending order;  take $$$d_{k + 1}$$$ as a result. If there are multiple optimal answers you can print any of them.

The first line contains single integer $$$T$$$ ($$$ 1 \le T \le 2 \cdot 10^5$$$) — number of queries. Next $$$2 \cdot T$$$ lines contain descriptions of queries. All queries are independent.  The first line of each query contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le k < n$$$) — the number of points and constant $$$k$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_1 < a_2 < \dots < a_n \le 10^9$$$) — points in ascending order. It's guaranteed that $$$\sum{n}$$$ doesn't exceed $$$2 \cdot 10^5$$$.

Print $$$T$$$ integers — corresponding points $$$x$$$ which have minimal possible value of $$$f_k(x)$$$. If there are multiple answers you can print any of them.

package main

import (
	"os"
	"runtime/debug"
	"strconv"
)

var stdout []byte

func readnumbers() (nums []int) {
	fileInfo, _ := os.Stdin.Stat()
	p := make([]byte, fileInfo.Size())
	os.Stdin.Read(p)

	num, neg := 0, 1
	for i := 0; i < len(p); i++ {
		if p[i] >= '0' {
			num = 10*num + int(p[i]-'0')
		} else if p[i] == '-' {
			neg = -1
		} else if p[i] != '\r' {
			nums = append(nums, neg*num)
			num, neg = 0, 1
		}
	}

	if len(p) > 0 && p[len(p)-1] >= '0' {
		nums = append(nums, neg*num)
	}

	return
}

func print(b []byte) {
	stdout = append(stdout, b...)
	stdout = append(stdout, '\n')
}

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

func main() {
	debug.SetGCPercent(-1)
	nums := readnumbers()
	idx := 0

	t := nums[idx]
	idx++
	for i := 0; i < t; i++ {
		n, k := nums[idx], nums[idx+1]
		idx += 2

		fxk, res := int(1e9), 0
		for j := 0; j < n-k; j++ {
			x := (nums[idx+j] + nums[idx+j+k]) / 2
			fik := max(x-nums[idx+j], nums[idx+j+k]-x)
			if fik < fxk {
				fxk = fik
				res = x
			}
		}

		idx += n
		print([]byte(strconv.Itoa(res)))
	}

	os.Stdout.Write(stdout)
}

package main

import (
	"fmt"
	"os"
)

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

func pow(n int64, x int) int64 {
	y := int64(1)
	if x == 0 {
		return y
	}

	for x > 1 {
		if x&1 == 1 {
			y *= n
		}

		n *= n
		x >>= 1
	}

	return y * n

}

func readnumbers() (nums []int) {
	fileInfo, _ := os.Stdin.Stat()
	p := make([]byte, fileInfo.Size())
	os.Stdin.Read(p)

	num, neg := 0, 1
	for i := 0; i < len(p); i++ {
		if p[i] >= '0' {
			num = 10*num + int(p[i]) - 48
		} else if p[i] == '-' {
			neg = -1
		} else if p[i] != '\r' {
			nums = append(nums, neg*num)
			num, neg = 0, 1
		}
	}

	if len(p) > 0 && p[len(p)-1] >= '0' {
		nums = append(nums, neg*num)
	}

	return
}

func main() {
	nums := readnumbers()
	idx := 0

	t := nums[idx]
	idx++
	for i := 0; i < t; i++ {
		n, k := nums[idx], nums[idx+1]
		idx += 2

		a := nums[idx : idx+n]
		idx += n

		fxk, res := int(1e9), 0
		for j := 0; j < n-k; j++ {
			x := (a[j] + a[j+k]) / 2
			fik := max(x-a[j], a[j+k]-x)
			if fik < fxk {
				fxk = fik
				res = x
			}
		}

		fmt.Println(res)
	}
}

package main

import (
	"fmt"
	"os"
)

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

func main() {
	var nums []int

	fileInfo, _ := os.Stdin.Stat()
	p := make([]byte, fileInfo.Size())
	os.Stdin.Read(p)

	num, neg := 0, 1
	for i := 0; i < len(p); i++ {
		if p[i] >= '0' {
			num = 10*num + int(p[i]) - 48
		} else if p[i] == '-' {
			neg = -1
		} else if p[i] != '\r' {
			nums = append(nums, neg*num)
			num, neg = 0, 1
		}
	}

	if len(p) > 0 && p[len(p)-1] >= '0' {
		nums = append(nums, neg*num)
	}

	idx := 0
	t := nums[idx]
	idx++
	for i := 0; i < t; i++ {
		n, k := nums[idx], nums[idx+1]
		idx += 2

		fxk, res := int(1e9), 0
		for j := 0; j < n-k; j++ {
			x := (nums[idx+j] + nums[idx+j+k]) / 2
			fik := max(x-nums[idx+j], nums[idx+j+k]-x)
			if fik < fxk {
				fxk = fik
				res = x
			}
		}

		idx += n
		fmt.Println(res)
	}
}

package main

import (
	"os"
	"strconv"
)

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

func main() {
	var nums []int

	fileInfo, _ := os.Stdin.Stat()
	p := make([]byte, fileInfo.Size())
	os.Stdin.Read(p)

	num, neg := 0, 1
	for i := 0; i < len(p); i++ {
		if p[i] >= '0' {
			num = 10*num + int(p[i]-'0')
		} else if p[i] == '-' {
			neg = -1
		} else if p[i] != '\r' {
			nums = append(nums, neg*num)
			num, neg = 0, 1
		}
	}

	if len(p) > 0 && p[len(p)-1] >= '0' {
		nums = append(nums, neg*num)
	}

	idx := 0
	t := nums[idx]
	idx++

	var toPrint []byte
	for i := 0; i < t; i++ {
		n, k := nums[idx], nums[idx+1]
		idx += 2

		fxk, res := int(1e9), 0
		for j := 0; j < n-k; j++ {
			x := (nums[idx+j] + nums[idx+j+k]) / 2
			fik := max(x-nums[idx+j], nums[idx+j+k]-x)
			if fik < fxk {
				fxk = fik
				res = x
			}
		}

		idx += n
		toPrint = append(toPrint, []byte(strconv.Itoa(res))...)
		toPrint = append(toPrint, '\n')
	}

	os.Stdout.Write(toPrint)
}

package main

import (
	"fmt"
	"os"
)

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

func readnumbers() (nums []int) {
	fileInfo, _ := os.Stdin.Stat()
	p := make([]byte, fileInfo.Size())
	os.Stdin.Read(p)

	num, neg := 0, 1
	for i := 0; i < len(p); i++ {
		if p[i] >= '0' {
			num = 10*num + int(p[i]) - 48
		} else if p[i] == '-' {
			neg = -1
		} else if p[i] != '\r' {
			nums = append(nums, neg*num)
			num, neg = 0, 1
		}
	}

	if len(p) > 0 && p[len(p)-1] >= '0' {
		nums = append(nums, neg*num)
	}

	return
}

func main() {
	nums := readnumbers()
	idx := 0

	t := nums[idx]
	idx++
	for i := 0; i < t; i++ {
		n, k := nums[idx], nums[idx+1]
		idx += 2

		fxk, res := int(1e9), 0
		for j := 0; j < n-k; j++ {
			x := (nums[idx+j] + nums[idx+j+k]) / 2
			fik := max(x-nums[idx+j], nums[idx+j+k]-x)
			if fik < fxk {
				fxk = fik
				res = x
			}
		}

		idx += n
		fmt.Println(res)
	}
}

package main

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

type inputReader struct {
    *bufio.Scanner
}

func newInputReader() *inputReader {
    input := inputReader{ bufio.NewScanner(os.Stdin) }
    input.Split(bufio.ScanWords)
    return &input
}

func (input *inputReader) readInt() int {
    input.Scan()
    result, _ := strconv.Atoi(input.Text())
    return result
}

func main() {
    input := newInputReader()
    t := input.readInt()

    a := make([]int, 200000, 200000)
    for kase := 1; kase <= t; kase++ {
        n := input.readInt()
        k := input.readInt()
        for i := 0; i < n; i++ {
            a[i] = input.readInt()
        }

        pos := 0
        mindiff := math.MaxInt32
        for i := 0; i < n - k; i++ {
            diff := a[i + k] - a[i]
            if diff < mindiff {
                mindiff = diff
                pos = i
            }
        }

        fmt.Println((a[pos] + a[pos + k]) / 2)
    }
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1175C(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var T, n, k, x int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &k)
		a := make([]int, n)
		for i := range a {
			Fscan(in, &a[i])
		}
		if k == 0 {
			Fprintln(out, a[0])
			continue
		}
		min := int(1e9)
		for i, v := range a[k:] {
			if d := (v - a[i] + 1) / 2; d < min {
				min = d
				x = (v + a[i]) / 2
			}
		}
		Fprintln(out, x)
	}
}

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

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := 0
	fmt.Fscanf(in, "%d\n", &t)
	for tt := 0; tt < t; tt++ {
		n, k := 0, 0
		fmt.Fscanf(in, "%d %d\n", &n, &k)
		a := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscanf(in, "%d", &a[i])
		}
		//fmt.Println(a)
		fmt.Fscanf(in, "\n")
		min := a[n-1] - a[0]
		ans := (a[0] + a[n-1]) / 2
		for i := 0; i < n; i++ {
			till := i + k
			if till >= n {
				break
			}
			if a[till]-a[i] < min {
				min = a[till] - a[i]
				ans = (a[till] + a[i]) / 2
			}
		}
		fmt.Fprintf(out, "%d\n", ans)
	}
	return
}

package main

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

var a [200100]int

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

	var t int
	fmt.Fscan(in, &t)
	for t > 0 {
		var n, k int
		fmt.Fscan(in, &n)
		fmt.Fscan(in, &k)
		k++
		for i := 1; i <= n; i++ {
			fmt.Fscan(in, &a[i])
		}

		if k == 1 {
			fmt.Println(a[1])
			t--
			continue
		}

		mn := 2000000000
		_ = mn
		x := -1

		for i := k; i <= n; i++ {
			l := i - k + 1
			r := i
			dist := a[r] - a[l]
			md := dist % 2
			dist /= 2
			dist += md
			if dist < mn {
				mn = dist
				x = (a[l] + a[r]) / 2
			}
		}

		fmt.Println(x)
		t--
	}
}

package main

import (
	"fmt"
)

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

func pow(n int64, x int) int64 {
	y := int64(1)
	if x == 0 {
		return y
	}

	for x > 1 {
		if x&1 == 1 {
			y *= n
		}

		n *= n
		x >>= 1
	}

	return y * n

}

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

		fxk := pow(int64(10), 18)
		res := int64(0)
		for j := 0; j < n-k; j++ {
			x := (a[j] + a[j+k]) / 2
			fik := max(x-a[j], a[j+k]-x)
			if fik < fxk {
				fxk = fik
				res = x
			}
		}

		fmt.Println(res)
	}
}

package main

import (
	"fmt"
)

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

func pow(n int64, x int) int64 {
	y := int64(1)
	if x == 0 {
		return y
	}

	for x > 1 {
		if x&1 == 1 {
			y *= n
		}

		n *= n
		x >>= 1
	}

	return y * n

}

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

		fxk := pow(int64(10), 18)
		res := int64(0)
		for j := 0; j < n-k; j++ {
			x := (a[j] + a[j+k]) / 2
			fik := max(x-a[j], a[j+k]-x)
			if fik < fxk {
				fxk = fik
				res = x
			}
		}

		fmt.Println(res)
	}
}

package main

import (
	"fmt"
)

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

func pow(n int64, x int) int64 {
	y := int64(1)
	if x == 0 {
		return y
	}

	for x > 1 {
		if x&1 == 1 {
			y *= n
		}

		n *= n
		x >>= 1
	}

	return y * n

}

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

		fxk := pow(int64(10), 18)
		res := int64(0)
		for j := 0; j < n-k; j++ {
			x := (a[j] + a[j+k]) / 2
			fik := max(x-a[j], a[j+k]-x)
			if fik < fxk {
				fxk = fik
				res = x
			}
		}

		fmt.Println(res)
	}
}


You play a computer game. In this game, you lead a party of $$$m$$$ heroes, and you have to clear a dungeon with $$$n$$$ monsters. Each monster is characterized by its power $$$a_i$$$. Each hero is characterized by his power $$$p_i$$$ and endurance $$$s_i$$$.The heroes clear the dungeon day by day. In the beginning of each day, you choose a hero (exactly one) who is going to enter the dungeon this day.When the hero enters the dungeon, he is challenged by the first monster which was not defeated during the previous days (so, if the heroes have already defeated $$$k$$$ monsters, the hero fights with the monster $$$k + 1$$$). When the hero fights the monster, there are two possible outcomes:  if the monster's power is strictly greater than the hero's power, the hero retreats from the dungeon. The current day ends;  otherwise, the monster is defeated. After defeating a monster, the hero either continues fighting with the next monster or leaves the dungeon. He leaves the dungeon either if he has already defeated the number of monsters equal to his endurance during this day (so, the $$$i$$$-th hero cannot defeat more than $$$s_i$$$ monsters during each day), or if all monsters are defeated — otherwise, he fights with the next monster. When the hero leaves the dungeon, the current day ends.Your goal is to defeat the last monster. What is the minimum number of days that you need to achieve your goal? Each day you have to use exactly one hero; it is possible that some heroes don't fight the monsters at all. Each hero can be used arbitrary number of times.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Then the test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of monsters in the dungeon. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the power of the $$$i$$$-th monster. The third line contains one integer $$$m$$$ ($$$1 \le m \le 2 \cdot 10^5$$$) — the number of heroes in your party. Then $$$m$$$ lines follow, each describing a hero. Each line contains two integers $$$p_i$$$ and $$$s_i$$$ ($$$1 \le p_i \le 10^9$$$, $$$1 \le s_i \le n$$$) — the power and the endurance of the $$$i$$$-th hero. It is guaranteed that the sum of $$$n + m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print one integer — the minimum number of days you have to spend to defeat all of the monsters (or $$$-1$$$ if it is impossible).

package main

import (
	"bufio"
	"container/heap"
	"os"
	"runtime"
	"sort"
	"strconv"
)

/* solution */

// Hero ...
type Hero struct {
	i int
	p int
	s int
}

// StaminaList ...
type StaminaList []Hero

func (h StaminaList) Len() int           { return len(h) }
func (h StaminaList) Less(i, j int) bool { return h[i].s < h[j].s }
func (h StaminaList) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

// PowerHeap ...
type PowerHeap struct {
	pointer map[int]int
	heap    []Hero
}

func (h PowerHeap) Len() int           { return len(h.heap) }
func (h PowerHeap) Less(i, j int) bool { return h.heap[i].p > h.heap[j].p }
func (h PowerHeap) Swap(i, j int) {
	h.heap[i], h.heap[j] = h.heap[j], h.heap[i]
	h.pointer[h.heap[i].i], h.pointer[h.heap[j].i] = i, j
}

// Push ...
func (h *PowerHeap) Push(x interface{}) {
	h.heap = append(h.heap, x.(Hero))
	h.pointer[x.(Hero).i] = len(h.heap) - 1
}

// Pop ...
func (h *PowerHeap) Pop() interface{} {
	old := h.heap
	n := len(old)
	x := old[n-1]
	h.heap = old[0 : n-1]
	return x
}

func solve() {
	t := readInt()
	for i := 0; i < t; i++ {
		printInt(solveOne())
	}
}

func solveOne() int {

	n := readInt()
	beasts := make([]int, n)
	maxBeast := 0
	for i := 0; i < n; i++ {
		p := readInt()
		beasts[i] = p
		if p > maxBeast {
			maxBeast = p
		}
	}

	m := readInt()
	stamina := make(StaminaList, m)
	power := PowerHeap{make(map[int]int), make([]Hero, 0)}
	for i := 0; i < m; i++ {
		hero := Hero{i, readInt(), readInt()}
		stamina[i] = hero
		heap.Push(&power, hero)
	}

	if maxBeast > power.heap[0].p {
		return -1
	}

	sort.Sort(stamina)

	d := make([]int, n+1)
	i := 0
	for s := 1; s <= n; s++ {
		for i < m && stamina[i].s < s && len(power.heap) > 0 {
			heap.Remove(&power, power.pointer[stamina[i].i])
			i++
		}
		if len(power.heap) == 0 {
			break
		}
		d[s] = power.heap[0].p
	}

	ans := 1
	s := 1
	giant := -1
	for i := 0; i < n; {
		if beasts[i] > giant {
			giant = beasts[i]
		}
		if d[s] >= giant {
			i++
			s++
		} else {
			s = 1
			giant = -1
			ans++
		}
	}

	return ans

}

/* stubs */

func main() {

	var f *os.File
	if runtime.GOROOT() == "C:\\Soft\\Go" {
		f, _ = os.Open("input.txt")
		defer f.Close()
	} else {
		f = os.Stdin
	}

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

	reader = bufio.NewScanner(f)

	const maxCapacity = 1024 * 1024
	buf := make([]byte, maxCapacity)
	reader.Buffer(buf, maxCapacity)

	reader.Split(bufio.ScanWords)

	solve()

}

var reader *bufio.Scanner
var writer *bufio.Writer

func read() string {
	reader.Scan()
	return reader.Text()
}

func readInt() int {
	reader.Scan()
	ret, _ := strconv.Atoi(reader.Text())
	return ret
}

func print(s string) {
	writer.WriteString(s)
	writer.WriteString("\n")
}

func printInt(i int) {
	print(strconv.Itoa(i))
}

func printInt64(i int64) {
	print(strconv.FormatInt(i, 10))
}

func readInt64() int64 {
	reader.Scan()
	ret, _ := strconv.ParseInt(reader.Text(), 10, 64)
	return ret
}

package main

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

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

type hero struct {
	pow int
	end int
}

// findHero will find the weakest hero with pow >= pow.
func findHero(pow int, he []hero, start int, end int) int {
	if start == end {
		if he[start].pow < pow {
			// not found
			return -1
		}
		return start
	}

	mid := (start + end) / 2
	if he[mid].pow >= pow {
		return findHero(pow, he, start, mid)
	} else {
		return findHero(pow, he, mid+1, end)
	}
}

func calc(a []int, he []hero) int {
	// Sort heroes by power, low to high.
	sort.Slice(he, func(i, j int) bool {
		return he[i].pow < he[j].pow
	})

	{
		// Modify heroes list so that when i<j, he[i].end > he[j].end.
		var he2 []hero
		// Invariant: if i<j, then he[i].end > he[j].end
		for _, h := range he {
			for len(he2) > 0 {
				if he2[len(he2)-1].end > h.end {
					break
				}
				he2 = he2[0 : len(he2)-1]
			}
			he2 = append(he2, h)
		}
		he = he2
	}

	// Start killing monsters with the weakest hero (that has highest endurance).
	nKills := 0 // how many monsters have we killed in this iteration
	iters := 0  // total number of iterations
	hStart := 0 // the weakest hero that can be used in the current iteration.

	for i := 0; i < len(a); {
		ai := a[i]
		hIdx := findHero(ai, he, hStart, len(he)-1) // find the weakest hero (with biggest endurance) that can kill monster ai.
		if hIdx == -1 {
			// No hero (beginning with hStart) can kill this monster. We always have the strongest hero available.
			return -1
		}

		if he[hIdx].end < nKills+1 {
			// This hero can't kill a monster because there is not enough endurance. Next round.
			iters++
			nKills = 0
			hStart = 0
			continue
		}

		// This hero can kill our monster.
		nKills++
		hStart = hIdx
		i++
	}

	return iters + 1
}

func main() {
	defer writer.Flush()

	var t int
	Scanf("%d\n", &t)
	for i := 0; i < t; i++ {
		var n int
		Scanf("%d\n", &n)

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

		var m int
		Scanf("%d\n", &m)

		he := make([]hero, m)
		for j := 0; j < m; j++ {
			Scanf("%d %d\n", &he[j].pow, &he[j].end)
		}

		Printf("%d\n", calc(a, he))
	}
}

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
}

/*********** DP sub-functions ***********/

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

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

// NthBit returns nth bit value of an argument.
// n starts from 0.
func NthBit(num, nth int) int {
	return num >> uint(nth) & 1
}

// OnBit returns the integer that has nth ON bit.
// If an argument has nth ON bit, OnBit returns the argument.
func OnBit(num, nth int) int {
	return num | (1 << uint(nth))
}

// OffBit returns the integer that has nth OFF bit.
// If an argument has nth OFF bit, OffBit returns the argument.
func OffBit(num, nth int) int {
	return num & ^(1 << uint(nth))
}

// PopCount returns the number of ON bit of an argument.
func PopCount(num int) int {
	res := 0

	for i := 0; i < 70; i++ {
		if ((num >> uint(i)) & 1) == 1 {
			res++
		}
	}

	return res
}

/*********** Arithmetic ***********/

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

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

// Sum returns multiple integers sum.
func Sum(integers ...int) int {
	s := 0

	for _, i := range integers {
		s += i
	}

	return s
}

// PowInt is integer version of math.Pow
// PowInt calculate a power by Binary Power (二分累乗法(O(log e))).
func PowInt(a, e int) int {
	if a < 0 || e < 0 {
		panic(errors.New("[argument error]: PowInt does not accept negative integers"))
	}

	if e == 0 {
		return 1
	}

	if e%2 == 0 {
		halfE := e / 2
		half := PowInt(a, halfE)
		return half * half
	}

	return a * PowInt(a, e-1)
}

// AbsInt is integer version of math.Abs
func AbsInt(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

// Gcd returns the Greatest Common Divisor of two natural numbers.
// Gcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Gcd uses the Euclidean Algorithm.
func Gcd(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}
	if a < b {
		a, b = b, a
	}

	// Euclidean Algorithm
	for b > 0 {
		div := a % b
		a, b = b, div
	}

	return a
}

// Lcm returns the Least Common Multiple of two natural numbers.
// Lcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Lcd uses the Euclidean Algorithm indirectly.
func Lcm(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2
	// a' and b' are relatively prime numbers
	// gcd consists of prime numbers, that are included in a and b
	gcd := Gcd(a, b)

	// not (a * b / gcd), because of reducing a probability of overflow
	return (a / gcd) * b
}

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

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

type Hero struct {
	key  int
	p, s int
}
type HeroList []*Hero
type byKey struct {
	HeroList
}

func (l HeroList) Len() int {
	return len(l)
}
func (l HeroList) Swap(i, j int) {
	l[i], l[j] = l[j], l[i]
}

func (l byKey) Less(i, j int) bool {
	return l.HeroList[i].key < l.HeroList[j].key
}

// how to use
// L := make(HeroList, 0, 200000+5)
// L = append(L, &Hero{key: intValue})
// sort.Stable(byKey{ L })                // Stable ASC
// sort.Stable(sort.Reverse(byKey{ L }))  // Stable DESC

var t int
var n, m int
var A, P, S []int
var L HeroList // ヒーロー構造体の配列
var M []int    // [idx, m-1] のヒーロー区間におけるpowerの最大値を記憶

func main() {
	t = ReadInt()

	for tc := 0; tc < t; tc++ {
		n = ReadInt()
		A = ReadIntSlice(n)
		m = ReadInt()
		P, S = make([]int, m), make([]int, m)
		for i := 0; i < m; i++ {
			p, s := ReadInt2()
			P[i], S[i] = p, s
		}

		solve()
	}
}

func solve() {
	L = make(HeroList, 0)
	for i := 0; i < m; i++ {
		p, s := P[i], S[i]
		L = append(L, &Hero{key: s, p: p, s: s})
	}
	sort.Stable(byKey{L}) // endurance順に昇順ソートする

	// 後半部分のpowerに関する累積Maxを計算しておく
	M = make([]int, m)
	M[m-1] = L[m-1].p
	for i := m - 2; i >= 0; i-- {
		M[i] = Max(M[i+1], L[i].p)
	}

	l := 0
	ans := 0
	for l < n {
		length := sub(l)
		if length == -1 {
			fmt.Println(-1)
			return
		} else {
			l += length
			ans++
		}
	}

	fmt.Println(ans)
}

// モンスターの配列に対して、A[s]から数えて何体倒せるかを計算する関数
// -1を返したら1体も倒せない（=失敗）
func sub(s int) int {
	maxMP := A[s]
	length := -1
	for l := 0; s+l < n; l++ {
		maxMP = Max(maxMP, A[s+l]) // A[s]から現在見ているところまでのモンスターのpowerの最大値
		idx := sub2(l + 1)
		if idx == m {
			break
		}

		maxHP := M[idx] // l+1以上のenduranceを持つヒーローの中のpowerの最大値
		if maxHP >= maxMP {
			length = l + 1
		} else {
			break
		}
	}

	return length
}

// enduranceがl以上となるギリギリのインデックスを二分探索で計算
// mを返したらそのようなヒーローは存在しない
func sub2(l int) int {
	// m は中央を意味する何らかの値
	isOK := func(mid int) bool {
		if L[mid].s >= l {
			return true
		}
		return false
	}

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

	return ok
}

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

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
}

/*********** DP sub-functions ***********/

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

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

// NthBit returns nth bit value of an argument.
// n starts from 0.
func NthBit(num, nth int) int {
	return num >> uint(nth) & 1
}

// OnBit returns the integer that has nth ON bit.
// If an argument has nth ON bit, OnBit returns the argument.
func OnBit(num, nth int) int {
	return num | (1 << uint(nth))
}

// OffBit returns the integer that has nth OFF bit.
// If an argument has nth OFF bit, OffBit returns the argument.
func OffBit(num, nth int) int {
	return num & ^(1 << uint(nth))
}

// PopCount returns the number of ON bit of an argument.
func PopCount(num int) int {
	res := 0

	for i := 0; i < 70; i++ {
		if ((num >> uint(i)) & 1) == 1 {
			res++
		}
	}

	return res
}

/*********** Arithmetic ***********/

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

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

// Sum returns multiple integers sum.
func Sum(integers ...int) int {
	s := 0

	for _, i := range integers {
		s += i
	}

	return s
}

// PowInt is integer version of math.Pow
// PowInt calculate a power by Binary Power (二分累乗法(O(log e))).
func PowInt(a, e int) int {
	if a < 0 || e < 0 {
		panic(errors.New("[argument error]: PowInt does not accept negative integers"))
	}

	if e == 0 {
		return 1
	}

	if e%2 == 0 {
		halfE := e / 2
		half := PowInt(a, halfE)
		return half * half
	}

	return a * PowInt(a, e-1)
}

// AbsInt is integer version of math.Abs
func AbsInt(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

// Gcd returns the Greatest Common Divisor of two natural numbers.
// Gcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Gcd uses the Euclidean Algorithm.
func Gcd(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}
	if a < b {
		a, b = b, a
	}

	// Euclidean Algorithm
	for b > 0 {
		div := a % b
		a, b = b, div
	}

	return a
}

// Lcm returns the Least Common Multiple of two natural numbers.
// Lcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Lcd uses the Euclidean Algorithm indirectly.
func Lcm(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2
	// a' and b' are relatively prime numbers
	// gcd consists of prime numbers, that are included in a and b
	gcd := Gcd(a, b)

	// not (a * b / gcd), because of reducing a probability of overflow
	return (a / gcd) * b
}

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

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

type Hero struct {
	key  int
	p, s int
}
type HeroList []*Hero
type byKey struct {
	HeroList
}

func (l HeroList) Len() int {
	return len(l)
}
func (l HeroList) Swap(i, j int) {
	l[i], l[j] = l[j], l[i]
}

func (l byKey) Less(i, j int) bool {
	return l.HeroList[i].key < l.HeroList[j].key
}

// how to use
// L := make(HeroList, 0, 200000+5)
// L = append(L, &Hero{key: intValue})
// sort.Stable(byKey{ L })                // Stable ASC
// sort.Stable(sort.Reverse(byKey{ L }))  // Stable DESC

var t int
var n, m int
var A, P, S []int
var st *SegTreeRMQ

func main() {
	t = ReadInt()

	for tc := 0; tc < t; tc++ {
		n = ReadInt()
		A = ReadIntSlice(n)
		m = ReadInt()
		P, S = make([]int, m), make([]int, m)
		for i := 0; i < m; i++ {
			p, s := ReadInt2()
			P[i], S[i] = p, s
		}

		solve()
	}
}

func solve() {
	L := make(HeroList, 0)
	for i := 0; i < m; i++ {
		p, s := P[i], S[i]
		L = append(L, &Hero{key: s, p: p, s: s})
	}
	sort.Stable(byKey{L})

	// enduranceでソートされたヒーロー列
	SS := make([]int, m)
	for i := 0; i < m; i++ {
		SS[i] = L[i].s
	}
	// enduranceのソート列に従ってpowerをセグメントツリーに放り込む
	st = NewSegTreeRMQ(m, 0)
	for i := 0; i < m; i++ {
		st.Update(i, L[i].p)
	}

	l := 0
	ans := 0
	for l < n {
		length := sub2(l, SS)
		if length == -1 {
			fmt.Println(-1)
			return
		} else {
			l += length
			ans++
		}
	}

	fmt.Println(ans)
}

func sub(l int, H []int) int {
	// m は中央を意味する何らかの値
	isOK := func(m int) bool {
		if H[m] >= l {
			return true
		}
		return false
	}

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

	return ok
}

func sub2(s int, H []int) int {
	maxMP := A[s]
	length := -1
	for l := 0; s+l < n; l++ {
		maxMP = Max(maxMP, A[s+l])
		idx := sub(l+1, H)
		if idx == len(H) {
			break
		}

		maxHP := st.Query(idx, len(H))
		if maxHP >= maxMP {
			length = l + 1
		} else {
			break
		}
	}

	return length
}

// RMQを高速で処理するセグメントツリー構造体
type SegTreeRMQ struct {
	ElemNum int // 配列の要素数
	// Dat     [2*200005 - 1]int // セグメント木のノード集合
	Dat        []int // セグメント木のノード集合
	INIT_VALUE int   // 初期化用の値
}

// 配列の要素数と初期化用の値を渡す
func NewSegTreeRMQ(elemNum, initValue int) *SegTreeRMQ {
	st := new(SegTreeRMQ)
	st.INIT_VALUE = initValue
	// st.Dat = make([]int, 4*elemNum+10)

	// 要素数を2べきの数に補正する
	st.ElemNum = 1
	for st.ElemNum < elemNum {
		st.ElemNum *= 2
	}
	st.Dat = make([]int, 2*st.ElemNum)

	// すべての節点を初期化する
	for i := 0; i < 2*st.ElemNum-1; i++ {
		st.Dat[i] = st.INIT_VALUE
	}

	return st
}

// k番目の値（0-based）をaに変更する
func (st *SegTreeRMQ) Update(k, a int) {
	// 葉の節点を変更
	k += st.ElemNum - 1
	st.Dat[k] = a

	// 登りながら各節点を変更
	for k > 0 {
		k = (k - 1) / 2
		st.Dat[k] = int(math.Max(float64(st.Dat[2*k+1]), float64(st.Dat[2*k+2])))
	}
}

// [a, b)の区間の最小値を返す
// 再帰関数のラッパー関数
func (st *SegTreeRMQ) Query(a, b int) int {
	return st.subQuery(a, b, 0, 0, st.ElemNum)
}

// [a, b)の区間の最小値を返す
// k: 検索先のセグメントツリーのノード番号(0-based)
// l, r: k番目のセグメントツリーノードの半開区間の左端と右端, [l, r)
func (st *SegTreeRMQ) subQuery(a, b, k, l, r int) int {
	if r <= a || b <= l {
		return st.INIT_VALUE
	}

	if a <= l && r <= b {
		return st.Dat[k]
	}

	vl, vr := st.subQuery(a, b, 2*k+1, l, (l+r)/2), st.subQuery(a, b, 2*k+2, (l+r)/2, r)
	return int(math.Max(float64(vl), float64(vr)))
}

// MODはとったか？
// 遷移だけじゃなくて最後の最後でちゃんと取れよ？

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

package main

import (
	"bufio"
	. "fmt"
	"io"
	"math/bits"
	"os"
	"sort"
)

// github.com/EndlessCheng/codeforces-go
func Sol1257D(reader io.Reader, writer io.Writer) {
	in := bufio.NewReader(reader)
	out := bufio.NewWriter(writer)
	defer out.Flush()

	max := func(a, b int) int {
		if a > b {
			return a
		}
		return b
	}
	var st [][18]int
	stInit := func(a []int) {
		n := len(a)
		st = make([][18]int, n)
		for i := range st {
			st[i][0] = a[i]
		}
		for j := uint(1); 1<<j <= n; j++ {
			for i := 0; i+(1<<j)-1 < n; i++ {
				st[i][j] = max(st[i][j-1], st[i+(1<<(j-1))][j-1])
			}
		}
	}
	stQuery := func(l, r int) int {
		k := uint(bits.Len(uint(r-l+1)) - 1)
		return max(st[l][k], st[r-(1<<k)+1][k])
	}
	type hero struct{ power, endurance int }

	var t int
	for Fscan(in, &t); t > 0; t-- {
		var n, m int
		Fscan(in, &n)
		a := make([]int, n)
		for i := range a {
			Fscan(in, &a[i])
		}
		stInit(a)
		Fscan(in, &m)
		heroes := make([]hero, m)
		for i := range heroes {
			Fscan(in, &heroes[i].power, &heroes[i].endurance)
		}
		sort.Slice(heroes, func(i, j int) bool {
			return heroes[i].endurance > heroes[j].endurance || heroes[i].endurance == heroes[j].endurance && heroes[i].power > heroes[j].power
		})

		maxPowers := make([]int, n+1)
		maxPower := 0
		for i := 0; i < m; {
			hi := heroes[i]
			maxPower = max(maxPower, hi.power)
			j := i + 1
			for ; j < m && heroes[j].endurance == hi.endurance; j++ {
			}
			nextEndurance := 0
			if j < m {
				nextEndurance = heroes[j].endurance
			}
			for k := hi.endurance; k > nextEndurance; k-- {
				maxPowers[k] = maxPower
			}
			i = j
		}
		ans := 0
		for l := 0; l < n; ans++ {
			maxKills := sort.Search(n-l+1, func(kills int) bool {
				if kills == 0 {
					return !true
				}
				maxMonsterPower := stQuery(l, l+kills-1)
				return !(maxMonsterPower <= maxPowers[kills])
			}) - 1
			if maxKills == 0 {
				ans = -1
				break
			}
			l += maxKills
		}
		Fprintln(out, ans)
	}
}

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