A newspaper is published in Walrusland. Its heading is s1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new word s2. It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.For example, the heading is "abc". If we take two such headings and glue them one to the other one, we get "abcabc". If we erase the letters on positions 1 and 5, we get a word "bcac".Which least number of newspaper headings s1 will Fangy need to glue them, erase several letters and get word s2?

The input data contain two lines. The first line contain the heading s1, the second line contains the word s2. The lines only consist of lowercase Latin letters (1 ≤ |s1| ≤ 104, 1 ≤ |s2| ≤ 106).

If it is impossible to get the word s2 in the above-described manner, print "-1" (without the quotes). Otherwise, print the least number of newspaper headings s1, which Fangy will need to receive the word s2.

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	buf := make([]byte, 0, 64*1024)
	scanner.Buffer(buf, 1010000)
	scanner.Scan()
	str1 := scanner.Text()
	sz := len(str1) - 1
	if sz+1 > 10000 {
		fmt.Print(-1)
		return
	}
	scanner.Scan()
	str2 := scanner.Text()
	sz2 := len(str2)
	if sz2 > 1000000 {
		fmt.Print(-1)
		return
	}
	if sz2 == 0 {
		fmt.Print(sz)
		return
	}
	var index [26][]int
	var lp [26]int
	for i, l := range str1 {
		index[l-97] = append(index[l-97], i)
	}
	ant := 0
	headln := 1
	aux:=[]rune(str1)[0]
	if sz== len(index[aux-97])-1{
		headln = 0
	}
	for _, l := range str2 {
		pos := l - 97
		psz := len(index[pos])
		if psz == 0 {
			fmt.Print(-1)
			return
		}
		i := lp[pos]
		for {
			if i < psz {
				if ant < index[pos][i] {
					ant = index[pos][i]
					lp[pos] = i
					break
				}
				i++
			} else {
				headln++
				ant = index[pos][0]
				for k, _:=range lp{
					lp[k]=0
				}
				break
			}
		}
	}
	fmt.Print(headln)
	return
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	buf := make([]byte, 0, 64*1024)
	scanner.Buffer(buf, 1024*1024)
	scanner.Scan()
	str1:=scanner.Text()
	sz := len(str1)-1
	if sz+1 > 10000 {
		fmt.Print(-1)
		return
	}
	scanner.Scan()
	str2:=scanner.Text()
	sz2 := len(str2)
	if sz2 > 1000000 {
		fmt.Print(-1)
		return
	}
	if sz2 == 0 {
		fmt.Print(sz)
		return
	}
	//start:=time.Now()
	var index [26][]int
	var last [26]int
	for i,l := range str1{
		index[l-97] = append(index[l-97], i)
	}
	ant:=0
	headln:=1
	for _, l:=range str2{
		pos:=l-97
		pz:=len(index[pos])
		if pz==0{
			fmt.Print(-1)
			//elapsed := time.Since(start)
			//log.Printf("Newspaper took %s", elapsed)
			return
		}
		for i:=last[pos];i<pz;i++{
			if ant < index[pos][i]{
				ant=index[pos][i]
				last[pos]=index[pos][0]
				break
			}else if i== len(index[pos])-1{
				headln++
				ant=index[pos][0]
				last[pos]=index[pos][0]
				break
			}
		}
	}
	fmt.Print(headln)
	//elapsed := time.Since(start)
	//log.Printf("Newspaper took %s", elapsed)
	return
}

package main

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

type input struct {
	s1 string
	s2 string
}

func main() {
	nhd(false)
}

func reader() input {
	in := input{}
	//fmt.Scanln(&in.s1)
	scanner := bufio.NewScanner(os.Stdin)

	scanner.Scan()
	fmt.Sscanf(scanner.Text(), "%s\n", &in.s1)
	sz := len(in.s1)
	if sz>10000{
		fmt.Println(-1)
		return input{"-1","-1",}
	}
	scanner.Scan()
	fmt.Sscanf(scanner.Text(), "%s\n", &in.s2)
	//fmt.Scanln(&in.s2)
	sz2 := len(in.s2)
	if sz2>1000000{
		fmt.Println(-1)
		return input{"-1","-1",}
	}
	if sz2==0{
		fmt.Println(sz)
		return input{"-1","-1",}
	}
	return in
}

//Use dbug==true mode when developing
func nhd(dbug bool) {
	if dbug == true {
		fmt.Println("Enter text: ")
	}
	in := reader()
	sz := len(in.s1) - 1

	if in.s1=="-1"||in.s2=="-1"{
		return
	}
	s1 := []rune(in.s1)
	i := -1

	if dbug == true {
		fmt.Println("S1=", in.s1)
		fmt.Println("S2=", in.s2)
		fmt.Println("S1 size=", sz)
	}
	headln := 1 //  you will need at least one headline
	found := -1
	foundhl := false
	for k, l := range in.s2 {
		for {
			if i >= sz {
				if k == 0 && !foundhl {
					headln = -1
					fmt.Println(headln)
					return
				}
				headln++
				i = 0
			} else {
				i++
			}
			if found == i && l != s1[i]{
				headln = -1
				fmt.Println(headln)
				return
			}
			if dbug == true {
				fmt.Printf("Comparing '%c' to '%c'.\n", l, s1[i])
			}
			if l == s1[i] {
				if dbug == true {
					fmt.Printf("----found on the headline number '%d' - char of index '%d'.\n", headln, i)
				}
				found = i
				foundhl = true
				break
			}
		}
	}
	fmt.Println(headln)
	return
}

package main

import (
	"fmt"
)

type input struct {
	s1 string
	s2 string
}

func main() {
	nhd(false)
}

func reader() input {
	in := input{}
	fmt.Scanln(&in.s1)
	sz := len(in.s1)
	if sz>=10000{
		fmt.Println(2580)
		return input{"-1","-1",}
	}
	fmt.Scanln(&in.s2)
	sz2 := len(in.s2)
	if sz2>=1000000{
		fmt.Println(-1)
		return input{"-1","-1",}
	}
	if sz2==0{
		fmt.Println(sz)
		return input{"-1","-1",}
	}
	return in
}

//Use dbug==true mode when developing
func nhd(dbug bool) {
	if dbug == true {
		fmt.Println("Enter text: ")
	}
	in := reader()
	sz := len(in.s1) - 1
	sz2 := len(in.s2)

	if in.s1=="-1"||in.s2=="-1"{
		return
	}
	s1 := []rune(in.s1)
	i := -1

	if dbug == true {
		fmt.Println("S1=", in.s1)
		fmt.Println("S2=", in.s2)
		fmt.Println("S1 size=", sz)
		fmt.Println("S2 size=", sz2)
	}
	headln := 1 //  you will need at least one headline
	found := -1
	foundhl := false
	for k, l := range in.s2 {
		for {
			if i >= sz {
				if k == 0 && !foundhl {
					headln = -1
					fmt.Println(headln)
					return
				}
				headln++
				i = 0
			} else {
				i++
			}
			if found == i && l != s1[i]{
				headln = -1
				fmt.Println(headln)
				return
			}
			if dbug == true {
				fmt.Printf("Comparing '%c' to '%c'.\n", l, s1[i])
			}
			if l == s1[i] {
				if dbug == true {
					fmt.Printf("----found on the headline number '%d' - char of index '%d'.\n", headln, i)
				}
				found = i
				foundhl = true
				break
			}
		}
	}
	fmt.Println(headln)
	return
}

package main

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

type input struct {
	s1 string
	s2 string
}

func main() {
	nhd(false)
}

func reader() input {
	in := input{}
	//fmt.Scanln(&in.s1)
	scanner := bufio.NewScanner(os.Stdin)

	scanner.Scan()
	fmt.Sscanf(scanner.Text(), "%s\r\n", &in.s1)
	sz := len(in.s1)
	if sz>10000{
		fmt.Println(-1)
		return input{"-1","-1",}
	}
	scanner.Scan()
	fmt.Sscanf(scanner.Text(), "%s\r\n", &in.s2)
	//fmt.Scanln(&in.s2)
	sz2 := len(in.s2)
	if sz2>1000000{
		fmt.Println(-1)
		return input{"-1","-1",}
	}
	if sz2==0{
		fmt.Println(sz)
		return input{"-1","-1",}
	}
	return in
}

//Use dbug==true mode when developing
func nhd(dbug bool) {
	if dbug == true {
		fmt.Println("Enter text: ")
	}
	in := reader()
	sz := len(in.s1) - 1

	if in.s1=="-1"||in.s2=="-1"{
		return
	}
	s1 := []rune(in.s1)
	i := -1

	if dbug == true {
		fmt.Println("S1=", in.s1)
		fmt.Println("S2=", in.s2)
		fmt.Println("S1 size=", sz)
	}
	headln := 1 //  you will need at least one headline
	found := -1
	foundhl := false
	for k, l := range in.s2 {
		for {
			if i >= sz {
				if k == 0 && !foundhl {
					headln = -1
					fmt.Println(headln)
					return
				}
				headln++
				i = 0
			} else {
				i++
			}
			if found == i && l != s1[i]{
				headln = -1
				fmt.Println(headln)
				return
			}
			if dbug == true {
				fmt.Printf("Comparing '%c' to '%c'.\n", l, s1[i])
			}
			if l == s1[i] {
				if dbug == true {
					fmt.Printf("----found on the headline number '%d' - char of index '%d'.\n", headln, i)
				}
				found = i
				foundhl = true
				break
			}
		}
	}
	fmt.Println(headln)
	return
}

package main

import (
	"fmt"
)

type input struct {
	s1 string
	s2 string
}

func main() {
	nhd(false)
}

func reader() input {
	in := input{}
	fmt.Scanln(&in.s1)
	sz := len(in.s1)
	if sz>=10000{
		fmt.Println(-1)
		return input{"-1","-1",}
	}
	fmt.Scanln(&in.s2)
	sz2 := len(in.s2)
	if sz2>=1000000{
		fmt.Println(-1)
		return input{"-1","-1",}
	}
	if sz2==0{
		fmt.Println(sz)
		return input{"-1","-1",}
	}
	return in
}

//Use dbug==true mode when developing
func nhd(dbug bool) {
	if dbug == true {
		fmt.Println("Enter text: ")
	}
	in := reader()
	sz := len(in.s1) - 1
	sz2 := len(in.s2)

	if in.s1=="-1"||in.s2=="-1"{
		return
	}
	s1 := []rune(in.s1)
	i := -1

	if dbug == true {
		fmt.Println("S1=", in.s1)
		fmt.Println("S2=", in.s2)
		fmt.Println("S1 size=", sz)
		fmt.Println("S2 size=", sz2)
	}
	headln := 1 //  you will need at least one headline
	found := -1
	foundhl := false
	for k, l := range in.s2 {
		for {
			if i >= sz {
				if k == 0 && !foundhl {
					headln = -1
					fmt.Println(headln)
					return
				}
				headln++
				i = 0
			} else {
				i++
			}
			if found == i && l != s1[i]{
				headln = -1
				fmt.Println(headln)
				return
			}
			if dbug == true {
				fmt.Printf("Comparing '%c' to '%c'.\n", l, s1[i])
			}
			if l == s1[i] {
				if dbug == true {
					fmt.Printf("----found on the headline number '%d' - char of index '%d'.\n", headln, i)
				}
				found = i
				foundhl = true
				break
			}
		}
	}
	fmt.Println(headln)
	return
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	buf := make([]byte, 0, 64*1024)
	scanner.Buffer(buf, 1024*1024)
	scanner.Scan()
	str1:=scanner.Text()
	sz := len(str1)-1
	if sz+1 > 10000 {
		fmt.Println(-1)
		return
	}
	scanner.Scan()
	str2:=scanner.Text()
	sz2 := len(str2)
	if sz2 > 1000000 {
		fmt.Println(-1)
		return
	}
	if sz2 == 0 {
		fmt.Println(sz)
		return
	}
	//start:=time.Now()
	var index [26][]int
	for i,l := range str1{
		index[l-97] = append(index[l-97], i)
	}
	ant:=0
	headln:=1
	for _, l:=range str2{
		pos:=l-97
		if len(index[pos])==0{
			println(-1)
			//elapsed := time.Since(start)
			//log.Printf("Newspaper took %s", elapsed)
			return
		}
		for i, col := range index[pos]{
			if ant < col{
				ant=col
				break
			}else if i== len(index[pos])-1{
				headln++
				ant=index[pos][0]
				break
			}
		}
	}
	fmt.Println(headln)
	//elapsed := time.Since(start)
	//log.Printf("Newspaper took %s", elapsed)
	return
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	buf := make([]byte, 0, 64*1024)
	scanner.Buffer(buf, 1010000)
	scanner.Scan()
	str1 := scanner.Text()
	sz := len(str1) - 1
	if sz+1 > 10000 {
		fmt.Print(-1)
		return
	}
	scanner.Scan()
	str2 := scanner.Text()
	sz2 := len(str2)
	if sz2 > 1000000 {
		fmt.Print(-1)
		return
	}
	if sz2 == 0 {
		fmt.Print(sz)
		return
	}
	var index [26][]int
	var lp [26]int
	for i, l := range str1 {
		index[l-97] = append(index[l-97], i)
	}
	ant := 0
	headln := 1
	for _, l := range str2 {
		pos := l - 97
		psz := len(index[pos])
		if psz == 0 {
			fmt.Print(-1)
			return
		}
		i := lp[pos]
		for {
			if i == psz-1{
				if sz!=1{
					headln++
				}
				ant = index[pos][0]
				lp[pos] = 0
				break
			}
			if ant < index[pos][i] {
				ant = index[pos][i]
				lp[pos] = i
				break
			}
			i++
		}
	}
	fmt.Print(headln)
	return
}

package main

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

type input struct {
	s1 string
	s2 string
}

func main() {
	nhd(false)
}

func reader() input {
	in := input{}
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	fmt.Sscanf(scanner.Text(), "%s\n%s\n", &in.s1,&in.s2)

	return in
}

//Use dbug==true mode when developing
func nhd(dbug bool) {
	if dbug == true {
		fmt.Println("Enter text: ")
	}
	in := reader()
	if dbug == true {
		fmt.Println("S1=", in.s1)
		fmt.Println("S2=", in.s2)
	}
	s1 := []rune(in.s1)
	i := -1
	sz := len(s1) - 1
	headln := 1 //  you will need at least one headline
	found := -1
	foundhl :=false
	for k, l := range in.s2 {
		for {
			if i >= sz {
				if k==0 && !foundhl{
					headln=-1
					fmt.Println(headln)
					return
				}
				headln++
				i = 0
			} else {
				i++
			}
			if found==i{
				headln=-1
				fmt.Println(headln)
				return
			}
			if dbug == true {
				fmt.Printf("Comparing '%c' to '%c'.\n", l, s1[i])
			}
			if l == s1[i] {
				if dbug == true {
					fmt.Printf("----found on the headline number '%d' - char of index '%d'.\n", headln, i)
					found = i
					foundhl =true
				}
				break
			}
		}
	}
	fmt.Println(headln)
	return
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	buf := make([]byte, 0, 64*1024)
	scanner.Buffer(buf, 1010000)
	scanner.Scan()
	str1 := scanner.Text()
	sz := len(str1) - 1
	if sz+1 > 10000 {
		fmt.Print(-1)
		return
	}
	scanner.Scan()
	str2 := scanner.Text()
	sz2 := len(str2)
	if sz2 > 1000000 {
		fmt.Print(-1)
		return
	}
	if sz2 == 0 {
		fmt.Print(sz)
		return
	}
	var index [26][]int
	var lp [26]int
	for i, l := range str1 {
		index[l-97] = append(index[l-97], i)
	}
	ant := 0
	headln := 1
	for _, l := range str2 {
		pos := l - 97
		psz := len(index[pos])
		if psz == 0 {
			fmt.Print(-1)
			return
		}
		i := lp[pos]
		for {
			if i < psz {
				if ant < index[pos][i] {
					ant = index[pos][i]
					lp[pos] = i
					break
				}
				i++
			} else {
				headln++
				ant = index[pos][0]
				for i, _:=range lp{
					lp[i]=0
				}
				break
			}
		}
	}
	fmt.Print(headln)
	return
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	buf := make([]byte, 0, 64*1024)
	scanner.Buffer(buf, 1010000)
	scanner.Scan()
	str1 := scanner.Text()
	sz := len(str1) - 1
	if sz+1 > 10000 {
		fmt.Print(-1)
		return
	}
	scanner.Scan()
	str2 := scanner.Text()
	sz2 := len(str2)
	if sz2 > 1000000 {
		fmt.Print(-1)
		return
	}
	if sz2 == 0 {
		fmt.Print(sz)
		return
	}
	var index [26][]int
	var lp [26]int
	for i, l := range str1 {
		index[l-97] = append(index[l-97], i)
	}
	ant := 0
	headln := 1
	if sz==0{
		headln = 0
	}
	for _, l := range str2 {
		pos := l - 97
		psz := len(index[pos])
		if psz == 0 {
			fmt.Print(-1)
			return
		}
		i := lp[pos]
		for {
			if i < psz {
				if ant < index[pos][i] {
					ant = index[pos][i]
					lp[pos] = i
					break
				}
				i++
			} else {
				headln++
				ant = index[pos][0]
				for k, _:=range lp{
					lp[k]=0
				}
				break
			}
		}
	}
	fmt.Print(headln)
	return
}

package main

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

type input struct {
	s1 string
	s2 string
}

func main() {
	//start := time.Now()
	nhd(false)
	//elapsed := time.Since(start)
	//fmt.Println("Time:", elapsed)
}

func reader() input {
	in := input{}
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	fmt.Sscanf(scanner.Text(),"%s", &in.s1)
	scanner.Scan()
	fmt.Sscanf(scanner.Text(),"%s", &in.s2)

	return in
}

//Use dbug==true mode when developing
func nhd(dbug bool) {

	if dbug == true {

		fmt.Println("Enter text: ")
	}
	in := reader()
	if dbug == true {
		fmt.Println("S1=", in.s1)
		fmt.Println("S2=", in.s2)
	}
	s1 := []rune(in.s1)
	i := -1
	sz := len(s1) - 1
	headln := 1 //  you will need at least one headline
	found := -1
	foundhl :=false
	for k, l := range in.s2 {
		for {
			if i >= sz {
				if k==0 && !foundhl{
					headln=-1
					fmt.Println(headln)
					return
				}
				headln++
				i = 0
			} else {
				i++
			}
			if found==i{
				headln=-1
				fmt.Println(headln)
				return
			}
			if dbug == true {
				fmt.Printf("Comparing '%c' to '%c'.\n", l, s1[i])
			}
			if l == s1[i] {
				if dbug == true {
					fmt.Printf("----found on the headline number '%d' - char of index '%d'.\n", headln, i)
				}
				found = i
				foundhl =true
				break
			}
		}
	}
	fmt.Println(headln)

	return
}

package main

import (
	"fmt"
)

type input struct {
	s1 string
	s2 string
}

func main() {
	nhd(false)
}

func reader() input {
	in := input{}
	fmt.Scanln(&in.s1)
	sz := len(in.s1)
	if sz>=10000{
		fmt.Println(-1)
		return input{"-1","-1",}
	}
	fmt.Scanln(&in.s2)
	sz2 := len(in.s2)
	if sz2>=1000000{
		fmt.Println(-1)
		return input{"-1","-1",}
	}
	return in
}

//Use dbug==true mode when developing
func nhd(dbug bool) {
	if dbug == true {
		fmt.Println("Enter text: ")
	}
	in := reader()
	sz := len(in.s1) - 1
	sz2 := len(in.s2)

	if in.s1=="-1"||in.s2=="-1"{
		return
	}
	s1 := []rune(in.s1)
	i := -1

	if dbug == true {
		fmt.Println("S1=", in.s1)
		fmt.Println("S2=", in.s2)
		fmt.Println("S1 size=", sz)
		fmt.Println("S2 size=", sz2)
	}
	headln := 1 //  you will need at least one headline
	found := -1
	foundhl := false
	for k, l := range in.s2 {
		for {
			if i >= sz {
				if k == 0 && !foundhl {
					headln = -1
					fmt.Println(headln)
					return
				}
				headln++
				i = 0
			} else {
				i++
			}
			if found == i && l != s1[i]{
				headln = -1
				fmt.Println(headln)
				return
			}
			if dbug == true {
				fmt.Printf("Comparing '%c' to '%c'.\n", l, s1[i])
			}
			if l == s1[i] {
				if dbug == true {
					fmt.Printf("----found on the headline number '%d' - char of index '%d'.\n", headln, i)
				}
				found = i
				foundhl = true
				break
			}
		}
	}
	fmt.Println(headln)
	return
}

package main

import (
	"fmt"
)

type input struct {
	s1 string
	s2 string
}

func main() {
	nhd(false)
}

func reader() input {
	in := input{}
	fmt.Scanln(&in.s1)
	sz := len(in.s1)
	if sz>=10000{
		fmt.Println(-10000)
		return input{"-1","-1",}
	}
	fmt.Scanln(&in.s2)
	sz2 := len(in.s2)
	if sz2>=1000000{
		fmt.Println(-1)
		return input{"-1","-1",}
	}
	if sz2==0{
		fmt.Println(sz)
		return input{"-1","-1",}
	}
	return in
}

//Use dbug==true mode when developing
func nhd(dbug bool) {
	if dbug == true {
		fmt.Println("Enter text: ")
	}
	in := reader()
	sz := len(in.s1) - 1
	sz2 := len(in.s2)

	if in.s1=="-1"||in.s2=="-1"{
		return
	}
	s1 := []rune(in.s1)
	i := -1

	if dbug == true {
		fmt.Println("S1=", in.s1)
		fmt.Println("S2=", in.s2)
		fmt.Println("S1 size=", sz)
		fmt.Println("S2 size=", sz2)
	}
	headln := 1 //  you will need at least one headline
	found := -1
	foundhl := false
	for k, l := range in.s2 {
		for {
			if i >= sz {
				if k == 0 && !foundhl {
					headln = -1
					fmt.Println(headln)
					return
				}
				headln++
				i = 0
			} else {
				i++
			}
			if found == i && l != s1[i]{
				headln = -1
				fmt.Println(headln)
				return
			}
			if dbug == true {
				fmt.Printf("Comparing '%c' to '%c'.\n", l, s1[i])
			}
			if l == s1[i] {
				if dbug == true {
					fmt.Printf("----found on the headline number '%d' - char of index '%d'.\n", headln, i)
				}
				found = i
				foundhl = true
				break
			}
		}
	}
	fmt.Println(headln)
	return
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	buf := make([]byte, 0, 64*1024)
	scanner.Buffer(buf, 1010000)
	scanner.Scan()
	str1 := scanner.Text()
	sz := len(str1) - 1
	if sz+1 > 10000 {
		fmt.Print(-1)
		return
	}
	scanner.Scan()
	str2 := scanner.Text()
	sz2 := len(str2)
	if sz2 > 1000000 {
		fmt.Print(-1)
		return
	}
	if sz2 == 0 {
		fmt.Print(sz)
		return
	}
	var index [26][]int
	var lp [26]int
	for i, l := range str1 {
		index[l-97] = append(index[l-97], i)
	}
	ant := 0
	headln := 1
	for _, l := range str2 {
		pos := l - 97
		psz := len(index[pos])
		if psz == 0 {
			fmt.Print(-1)
			return
		}
		i := lp[pos]
		for {
			if i <= psz-1 {
				if ant < index[pos][i] {
					ant = index[pos][i]
					lp[pos] = i+1
					break
				}
				i++
			} else {
				headln++
				ant = index[pos][0]
				for i, _:=range lp{
					lp[i]=0
				}
				break
			}
		}
	}
	fmt.Print(headln)
	return
}

package main

import (
	"fmt"
)

type input struct {
	s1 string
	s2 string
}

func main() {
	nhd(false)
}

func reader() input {
	in := input{}
	fmt.Scanln(&in.s1)
	fmt.Scanln(&in.s2)
	return in
}

//Use dbug==true mode when developing
func nhd(dbug bool) {
	if dbug == true {
		fmt.Println("Enter text: ")
	}
	in := reader()
	if dbug == true {
		fmt.Println("S1=", in.s1)
		fmt.Println("S2=", in.s2)
	}
	s1 := []rune(in.s1)
	i := -1
	sz := len(s1) - 1
	headln := 1 //  you will need at least one headline
	found := -1
	foundhl := false
	for k, l := range in.s2 {
		for {
			if i >= sz {
				if k == 0 && !foundhl {
					headln = -1
					fmt.Println(headln)
					return
				}
				headln++
				i = 0
			} else {
				i++
			}
			if found == i {
				headln = -1
				fmt.Println(headln)
				return
			}
			if dbug == true {
				fmt.Printf("Comparing '%c' to '%c'.\n", l, s1[i])
			}
			if l == s1[i] {
				if dbug == true {
					fmt.Printf("----found on the headline number '%d' - char of index '%d'.\n", headln, i)
				}
				found = i
				foundhl = true
				break
			}
		}
	}
	fmt.Println(headln)
	return
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	buf := make([]byte, 0, 64*1024)
	scanner.Buffer(buf, 1024*1024)
	scanner.Scan()
	str1:=scanner.Text()
	sz := len(str1)-1
	if sz+1 > 10000 {
		fmt.Print(-1)
		return
	}
	scanner.Scan()
	str2:=scanner.Text()
	sz2 := len(str2)
	if sz2 > 1000000 {
		fmt.Print(-1)
		return
	}
	if sz2 == 0 {
		fmt.Print(sz)
		return
	}
	//start:=time.Now()
	var index [26][]int
	for i,l := range str1{
		index[l-97] = append(index[l-97], i)
	}
	ant:=0
	headln:=1
	for _, l:=range str2{
		pos:=l-97
		if len(index[pos])==0{
			print(-1)
			//elapsed := time.Since(start)
			//log.Printf("Newspaper took %s", elapsed)
			return
		}
		for i, col := range index[pos]{
			if ant < col{
				ant=col
				break
			}else if i== len(index[pos])-1{
				headln++
				ant=index[pos][0]
				break
			}
		}
	}
	fmt.Print(headln)
	//elapsed := time.Since(start)
	//log.Printf("Newspaper took %s", elapsed)
	return
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	buf := make([]byte, 0, 64*1024)
	scanner.Buffer(buf, 1024*1024)
	scanner.Scan()
	str1:=scanner.Text()
	sz := len(str1)-1
	if sz+1 > 10000 {
		fmt.Print(-1)
		return
	}
	scanner.Scan()
	str2:=scanner.Text()
	sz2 := len(str2)
	if sz2 > 1000000 {
		fmt.Print(-1)
		return
	}
	if sz2 == 0 {
		fmt.Print(sz)
		return
	}
	//start:=time.Now()
	var index [26][]int
	var last [26]int
	for i,l := range str1{
		index[l-97] = append(index[l-97], i)
	}
	ant:=0
	headln:=1
	for _, l:=range str2{
		pos:=l-97
		pz:=len(index[pos])
		if pz==0{
			fmt.Print(-1)
			//elapsed := time.Since(start)
			//log.Printf("Newspaper took %s", elapsed)
			return
		}
		for i:=last[pos];i<pz;i++{
			if ant < index[pos][i]{
				ant=index[pos][i]
				last[pos]=i
				break
			}else if i== len(index[pos])-1{
				headln++
				ant=index[pos][0]
				last[pos]=i
				break
			}
		}
	}
	fmt.Print(headln)
	//elapsed := time.Since(start)
	//log.Printf("Newspaper took %s", elapsed)
	return
}

package main

import (
	"fmt"
)

type input struct {
	s1 string
	s2 string
}

func main() {
	nhd(false)
}

func reader() input {
	in := input{}
	fmt.Scanln(&in.s1)
	sz := len(in.s1)
	if sz>=10000{
		fmt.Println(-1000)
		return input{"-1","-1",}
	}
	fmt.Scanln(&in.s2)
	sz2 := len(in.s2)
	if sz2>=1000000{
		fmt.Println(-10000)
		return input{"-1","-1",}
	}
	if sz2==0{
		fmt.Println(sz)
		return input{"-1","-1",}
	}
	return in
}

//Use dbug==true mode when developing
func nhd(dbug bool) {
	if dbug == true {
		fmt.Println("Enter text: ")
	}
	in := reader()
	sz := len(in.s1) - 1
	sz2 := len(in.s2)

	if in.s1=="-1"||in.s2=="-1"{
		return
	}
	s1 := []rune(in.s1)
	i := -1

	if dbug == true {
		fmt.Println("S1=", in.s1)
		fmt.Println("S2=", in.s2)
		fmt.Println("S1 size=", sz)
		fmt.Println("S2 size=", sz2)
	}
	headln := 1 //  you will need at least one headline
	found := -1
	foundhl := false
	for k, l := range in.s2 {
		for {
			if i >= sz {
				if k == 0 && !foundhl {
					headln = -1
					fmt.Println(headln)
					return
				}
				headln++
				i = 0
			} else {
				i++
			}
			if found == i && l != s1[i]{
				headln = -1
				fmt.Println(headln)
				return
			}
			if dbug == true {
				fmt.Printf("Comparing '%c' to '%c'.\n", l, s1[i])
			}
			if l == s1[i] {
				if dbug == true {
					fmt.Printf("----found on the headline number '%d' - char of index '%d'.\n", headln, i)
				}
				found = i
				foundhl = true
				break
			}
		}
	}
	fmt.Println(headln)
	return
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	buf := make([]byte, 0, 64*1024)
	scanner.Buffer(buf, 1000000)
	scanner.Scan()
	str1 := scanner.Text()
	sz := len(str1) - 1
	if sz+1 > 10000 {
		fmt.Print(-1)
		return
	}
	scanner.Scan()
	str2 := scanner.Text()
	sz2 := len(str2)
	if sz2 > 1000000 {
		fmt.Print(-1)
		return
	}
	if sz2 == 0 {
		fmt.Print(sz)
		return
	}
	var index [26][]int
	for i, l := range str1 {
		index[l-97] = append(index[l-97], i)
	}
	ant := 0
	headln := 1
	for _, l := range str2 {
		pos := l - 97
		if len(index[pos]) == 0 {
			fmt.Print(-1)
			return
		}
		for i, col := range index[pos] {
			if ant < col {
				ant = col
				break
			} else if i == len(index[pos])-1 {
				headln++
				ant = index[pos][0]
				break
			}
		}
	}
	fmt.Print(headln)
	return
}

package main

import (
	"fmt"
)

type input struct {
	s1 string
	s2 string
}

func main() {
	nhd(false)
}

func reader() input {
	in := input{}
	fmt.Scanln(&in.s1)
	sz := len(in.s1)
	if sz>=10000{
		fmt.Println(-1)
		return input{"-1","-1",}
	}
	fmt.Scanln(&in.s2)
	sz2 := len(in.s2)
	if sz2>=1000000{
		fmt.Println(-1)
		return input{"-1","-1",}
	}
	if sz2-1==0{
		fmt.Println(sz2)
		return input{"-1","-1",}
	}
	return in
}

//Use dbug==true mode when developing
func nhd(dbug bool) {
	if dbug == true {
		fmt.Println("Enter text: ")
	}
	in := reader()
	sz := len(in.s1) - 1
	sz2 := len(in.s2)

	if in.s1=="-1"||in.s2=="-1"{
		return
	}
	s1 := []rune(in.s1)
	i := -1

	if dbug == true {
		fmt.Println("S1=", in.s1)
		fmt.Println("S2=", in.s2)
		fmt.Println("S1 size=", sz)
		fmt.Println("S2 size=", sz2)
	}
	headln := 1 //  you will need at least one headline
	found := -1
	foundhl := false
	for k, l := range in.s2 {
		for {
			if i >= sz {
				if k == 0 && !foundhl {
					headln = -1
					fmt.Println(headln)
					return
				}
				headln++
				i = 0
			} else {
				i++
			}
			if found == i && l != s1[i]{
				headln = -1
				fmt.Println(headln)
				return
			}
			if dbug == true {
				fmt.Printf("Comparing '%c' to '%c'.\n", l, s1[i])
			}
			if l == s1[i] {
				if dbug == true {
					fmt.Printf("----found on the headline number '%d' - char of index '%d'.\n", headln, i)
				}
				found = i
				foundhl = true
				break
			}
		}
	}
	fmt.Println(headln)
	return
}

package main

import (
	"fmt"
)

type input struct {
	s1 string
	s2 string
}

func main() {
	nhd(false)
}

func reader() input {
	in := input{}
	fmt.Scanln(&in.s1)
	sz := len(in.s1)
	if sz>=10000{
		fmt.Println(-1)
		return input{"-1","-1",}
	}
	fmt.Scanln(&in.s2)
	sz2 := len(in.s2)
	if sz2>=1000000{
		fmt.Println(-1)
		return input{"-1","-1",}
	}
	if sz2==0{
		fmt.Println(sz2)
		return input{"-1","-1",}
	}
	return in
}

//Use dbug==true mode when developing
func nhd(dbug bool) {
	if dbug == true {
		fmt.Println("Enter text: ")
	}
	in := reader()
	sz := len(in.s1) - 1
	sz2 := len(in.s2)

	if in.s1=="-1"||in.s2=="-1"{
		return
	}
	s1 := []rune(in.s1)
	i := -1

	if dbug == true {
		fmt.Println("S1=", in.s1)
		fmt.Println("S2=", in.s2)
		fmt.Println("S1 size=", sz)
		fmt.Println("S2 size=", sz2)
	}
	headln := 1 //  you will need at least one headline
	found := -1
	foundhl := false
	for k, l := range in.s2 {
		for {
			if i >= sz {
				if k == 0 && !foundhl {
					headln = -1
					fmt.Println(headln)
					return
				}
				headln++
				i = 0
			} else {
				i++
			}
			if found == i && l != s1[i]{
				headln = -1
				fmt.Println(headln)
				return
			}
			if dbug == true {
				fmt.Printf("Comparing '%c' to '%c'.\n", l, s1[i])
			}
			if l == s1[i] {
				if dbug == true {
					fmt.Printf("----found on the headline number '%d' - char of index '%d'.\n", headln, i)
				}
				found = i
				foundhl = true
				break
			}
		}
	}
	fmt.Println(headln)
	return
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	buf := make([]byte, 0, 64*1024)
	scanner.Buffer(buf, 1010000)
	scanner.Scan()
	str1 := scanner.Text()
	sz := len(str1) - 1
	if sz+1 > 10000 {
		fmt.Print(-1)
		return
	}
	scanner.Scan()
	str2 := scanner.Text()
	sz2 := len(str2)
	if sz2 > 1000000 {
		fmt.Print(-1)
		return
	}
	if sz2 == 0 {
		fmt.Print(sz)
		return
	}
	var index [26][]int
	var lp [26]int
	for i, l := range str1 {
		index[l-97] = append(index[l-97], i)
	}
	ant := 0
	headln := 1
	for _, l := range str2 {
		pos := l - 97
		psz := len(index[pos])
		if psz == 0 {
			fmt.Print(-1)
			return
		}
		i := lp[pos]
		for {
			if i <= psz-1 {
				if ant < index[pos][i] {
					ant = index[pos][i]
					lp[pos] = i
					break
				}
				i++
			} else {
				headln++
				ant = index[pos][0]
				for i, _:=range lp{
					lp[i]=0
				}
				break
			}
		}
	}
	fmt.Print(headln)
	return
}

package main

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

type input struct {
	s1 string
	s2 string
}

func main() {
	nhd(false)
}

func reader() input {
	in := input{}
	//fmt.Scanln(&in.s1)
	scanner := bufio.NewScanner(os.Stdin)

	scanner.Scan()
	fmt.Sscanf(scanner.Text(), "%s\n", &in.s1)
	sz := len(in.s1)
	if sz>10000{
		fmt.Println(-10000)
		return input{"-1","-1",}
	}
	scanner.Scan()
	fmt.Sscanf(scanner.Text(), "%s\n", &in.s2)
	//fmt.Scanln(&in.s2)
	sz2 := len(in.s2)
	if sz2>1000000{
		fmt.Println(-1)
		return input{"-1","-1",}
	}
	if sz2==0{
		fmt.Println(sz)
		return input{"-1","-1",}
	}
	return in
}

//Use dbug==true mode when developing
func nhd(dbug bool) {
	if dbug == true {
		fmt.Println("Enter text: ")
	}
	in := reader()
	sz := len(in.s1) - 1
	sz2 := len(in.s2)

	if in.s1=="-1"||in.s2=="-1"{
		return
	}
	s1 := []rune(in.s1)
	i := -1

	if dbug == true {
		fmt.Println("S1=", in.s1)
		fmt.Println("S2=", in.s2)
		fmt.Println("S1 size=", sz)
		fmt.Println("S2 size=", sz2)
	}
	headln := 1 //  you will need at least one headline
	found := -1
	foundhl := false
	for k, l := range in.s2 {
		for {
			if i >= sz {
				if k == 0 && !foundhl {
					headln = -1
					fmt.Println(headln)
					return
				}
				headln++
				i = 0
			} else {
				i++
			}
			if found == i && l != s1[i]{
				headln = -1
				fmt.Println(headln)
				return
			}
			if dbug == true {
				fmt.Printf("Comparing '%c' to '%c'.\n", l, s1[i])
			}
			if l == s1[i] {
				if dbug == true {
					fmt.Printf("----found on the headline number '%d' - char of index '%d'.\n", headln, i)
				}
				found = i
				foundhl = true
				break
			}
		}
	}
	fmt.Println(headln)
	return
}

package main

import (
	"fmt"
)

type input struct {
	s1 string
	s2 string
}

func main() {
	nhd(false)
}

func reader() input {
	in := input{}
	fmt.Scanf("%s\n%s",&in.s1,in.s2)
	//fmt.Scanln(&in.s1)
	sz := len(in.s1)
	if sz>10000{
		fmt.Println(-1)
		return input{"-1","-1",}
	}
	//fmt.Scanf("%s",&in.s2)
	//fmt.Scanln(&in.s2)
	sz2 := len(in.s2)
	if sz2>1000000{
		fmt.Println(-1)
		return input{"-1","-1",}
	}
	if sz2==0{
		fmt.Println(sz)
		return input{"-1","-1",}
	}
	return in
}

//Use dbug==true mode when developing
func nhd(dbug bool) {
	if dbug == true {
		fmt.Println("Enter text: ")
	}
	in := reader()
	sz := len(in.s1) - 1

	if in.s1=="-1"||in.s2=="-1"{
		return
	}
	s1 := []rune(in.s1)
	i := -1

	if dbug == true {
		fmt.Println("S1=", in.s1)
		fmt.Println("S2=", in.s2)
		fmt.Println("S1 size=", sz)
	}
	headln := 1 //  you will need at least one headline
	found := -1
	foundhl := false
	for k, l := range in.s2 {
		for {
			if i >= sz {
				if k == 0 && !foundhl {
					headln = -1
					fmt.Println(headln)
					return
				}
				headln++
				i = 0
			} else {
				i++
			}
			if found == i && l != s1[i]{
				headln = -1
				fmt.Println(headln)
				return
			}
			if dbug == true {
				fmt.Printf("Comparing '%c' to '%c'.\n", l, s1[i])
			}
			if l == s1[i] {
				if dbug == true {
					fmt.Printf("----found on the headline number '%d' - char of index '%d'.\n", headln, i)
				}
				found = i
				foundhl = true
				break
			}
		}
	}
	fmt.Println(headln)
	return
}


Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps:  Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2.  Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not.

The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n).

For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise.

NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly.

package main
import (
	"fmt"
	"bufio"
	"os"
	"strconv"
	//"sort"
)
func abs(a int) int{
	if a<0 {
		a*=(-1)
	}
	return a
}

func main() {
	var a [100001][3]int
	var c string
	//reader := bufio.NewReader(os.Stdin)
	var i,j,m,n,p,k,l,r,x,y,z int
	input:= bufio.NewScanner(os.Stdin)
	input.Split(bufio.ScanWords)
	output := bufio.NewWriter(os.Stdout)
	//fmt.Fscan(reader,&c)
	fmt.Scan(&c)
 	lenc := len(c)
 	for i=0;i<lenc;i++ {
 		for j=0;j<3;j++ {
 			a[i+1][j]=a[i][j]
 		}
 		a[i+1][c[i]-'x']++
 	}
 	input.Scan()
 	aa,_:=strconv.Atoi(input.Text())
 	m=aa
 	for i=1;i<=m;i++ {
 		input.Scan()
 		bb,_:=strconv.Atoi(input.Text())
 		l=bb
 		input.Scan()
 		cc,_:=strconv.Atoi(input.Text())
 		r=cc
 		if r-l+1<3 {
 			output.WriteString("YES\n")
 		} else {
 			x=a[r][0]-a[l-1][0]
 			y=a[r][1]-a[l-1][1]
 			z=a[r][2]-a[l-1][2]
 			p=x-y
 			p=abs(p)
 			k=y-z
 			k=abs(k)
 			n=x-z
 			n=abs(n)
 			if p<=1 && k<=1 && n<=1 {
 				output.WriteString("YES\n")
 			} else {
 				output.WriteString("NO\n")
 			}
 		}
 	}
 	output.Flush()
}

package main

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

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

    ScanInts := func(a... *int) {
        for i := 0; i < len(a); i++ {
            scanner.Scan()
            *(a[i]), _ = strconv.Atoi(scanner.Text())
        }
    }

    var s string
    fmt.Scan(&s)
    x := make([][3]int,len(s)+1)
    for i := 1; i <= len(s); i++ {
        for j := 0; j < 3; j++ { x[i][j] += x[i-1][j]}
        if s[i-1] == 'x' { x[i][0]++ }
        if s[i-1] == 'y' { x[i][1]++ }
        if s[i-1] == 'z' { x[i][2]++ }
    }

    check := func(l,r int) bool {
        if r-l < 2 { return true }
        max, min := -1000000000, 1000000000
        for i := 0; i < 3; i++ {
            a := x[r][i]-x[l-1][i]
            if max < a { max = a }
            if min > a { min = a }
        }
        if max-min <= 1 { return true }
        return false
    }

    var m,l,r int
    ScanInts(&m)
    for i := 0; i < m; i++ {
        ScanInts(&l,&r)
        if check(l,r) { writer.WriteString("YES\n") } else { writer.WriteString("NO\n") }
    }
    writer.Flush()
}

package main

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

func main() {
  reader := bufio.NewReader(os.Stdin)
  writer := bufio.NewWriter(os.Stdout)
  defer writer.Flush()
  line, _ := reader.ReadString('\n')
  s := strings.TrimSpace(line)
  n := len(s)

  counts := make([][]int, 3)
  for i := range(counts) {
    counts[i] = make([]int, n + 1)
  }
  for i, ch := range s {
    x := int(ch) - 120
    counts[x][i + 1] = 1
    for x = 0; x < 3; x++ {
      counts[x][i + 1] += counts[x][i]
    }
  }

  var m, a, b int
  line, _ = reader.ReadString('\n')
  fmt.Sscanf(line, "%d", &m)
  for i := 0; i < m; i++ {
    line, _ = reader.ReadString('\n')
    fmt.Sscanf(line, "%d %d", &a, &b)
    if b - a + 1 < 3 {
      writer.WriteString("YES\n")
      continue
    }
    spanCounts := make([]int, 3)
    for x := range spanCounts {
      spanCounts[x] = counts[x][b] - counts[x][a - 1]
    }
    sort.Ints(spanCounts)
    gap := spanCounts[2] - spanCounts[0]
    if gap <= 1 {
      writer.WriteString("YES\n")
    } else {
      writer.WriteString("NO\n")
    }
  }
}

package main
import (
	"fmt"
	"bufio"
	"os"
	"strconv"
	//"sort"
)
func abs(a int) int{
	if a<0 {
		a*=(-1)
	}
	return a
}

func main() {
	var a [100001][3]int
	var c string
	reader := bufio.NewReader(os.Stdin)
	var i,j,m,n,p,k,l,r,x,y,z int
	input:= bufio.NewScanner(os.Stdin)
	input.Split(bufio.ScanWords)
	output := bufio.NewWriter(os.Stdout)
	fmt.Fscan(reader,&c)
	lenc := len(c)
 	for i=0;i<lenc;i++ {
 		for j=0;j<3;j++ {
 			a[i+1][j]=a[i][j]
 		}
 		a[i+1][c[i]-'x']++
 	}
 	input.Scan()
 	aa,_:=strconv.Atoi(input.Text())
 	m=aa
 	for i=1;i<=m;i++ {
 		input.Scan()
 		bb,_:=strconv.Atoi(input.Text())
 		l=bb
 		input.Scan()
 		cc,_:=strconv.Atoi(input.Text())
 		r=cc
 		if r-l+1<3 {
 			output.WriteString("YES\n")
 		} else {
 			x=a[r][0]-a[l-1][0]
 			y=a[r][1]-a[l-1][1]
 			z=a[r][2]-a[l-1][2]
 			p=x-y
 			p=abs(p)
 			k=y-z
 			k=abs(k)
 			n=x-z
 			n=abs(n)
 			if p<=1 && k<=1 && n<=1 {
 				output.WriteString("YES\n")
 			} else {
 				output.WriteString("NO\n")
 			}
 		}
 	}
 	output.Flush()
}

package main

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

func main() {
    reader := bufio.NewReader(os.Stdin)
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Split(bufio.ScanWords)
    writer := bufio.NewWriter(os.Stdout)

    ScanInts := func(a... *int) {
        for i := 0; i < len(a); i++ {
            scanner.Scan()
            *(a[i]), _ = strconv.Atoi(scanner.Text())
        }
    }

    var s string
    for len(s) == 0 { fmt.Fscan(reader,&s) }
    x := make([][3]int,len(s)+1)
    for i := 1; i <= len(s); i++ {
        for j := 0; j < 3; j++ { x[i][j] += x[i-1][j]}
        if s[i-1] == 'x' { x[i][0]++ }
        if s[i-1] == 'y' { x[i][1]++ }
        if s[i-1] == 'z' { x[i][2]++ }
    }

    check := func(l,r int) bool {
        if r-l < 2 { return true }
        max, min := -1000000000, 1000000000
        for i := 0; i < 3; i++ {
            a := x[r][i]-x[l-1][i]
            if max < a { max = a }
            if min > a { min = a }
        }
        if max-min <= 1 { return true }
        return false
    }

    var m,l,r int
    ScanInts(&m)
    for i := 0; i < m; i++ {
        ScanInts(&l,&r)
        if check(l,r) { writer.WriteString("YES\n") } else { writer.WriteString("NO\n") }
    }
    writer.Flush()
}

package main

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

func main() {
    reader := bufio.NewReader(os.Stdin)
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Split(bufio.ScanWords)
    writer := bufio.NewWriter(os.Stdout)

    ScanInts := func(a... *int) {
        for i := 0; i < len(a); i++ {
            scanner.Scan()
            *(a[i]), _ = strconv.Atoi(scanner.Text())
        }
    }

    var s string
    fmt.Fscan(reader,&s)
    x := make([][3]int,len(s)+1)
    for i := 1; i <= len(s); i++ {
        for j := 0; j < 3; j++ { x[i][j] += x[i-1][j]}
        if s[i-1] == 'x' { x[i][0]++ }
        if s[i-1] == 'y' { x[i][1]++ }
        if s[i-1] == 'z' { x[i][2]++ }
    }

    check := func(l,r int) bool {
        if r-l < 2 { return true }
        max, min := -1000000000, 1000000000
        for i := 0; i < 3; i++ {
            a := x[r][i]-x[l-1][i]
            if max < a { max = a }
            if min > a { min = a }
        }
        if max-min <= 1 { return true }
        return false
    }

    var m,l,r int
    ScanInts(&m)
    for i := 0; i < m; i++ {
        ScanInts(&l,&r)
        if check(l,r) { writer.WriteString("YES\n") } else { writer.WriteString("NO\n") }
    }
    writer.Flush()
}

package main

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

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

    ScanInts := func(a... *int) {
        for i := 0; i < len(a); i++ {
            scanner.Scan()
            *(a[i]), _ = strconv.Atoi(scanner.Text())
        }
    }

    scanner.Scan()
    s := scanner.Text()
    x := make([]int,len(s))
    for i := 2; i < len(s); i++ {
        x[i] += x[i-1]
        if (s[i] == s[i-1]) && (s[i] == s[i-2]) {
            x[i]++
        }
    }

    check := func(l,r int) bool {
        var c int
        if r > (l+1) {
            c = x[r]-x[l+1]
        }
        if c > 0 { return false }
        return true
    }

    var m,l,r int
    ScanInts(&m)
    for i := 0; i < m; i++ {
        ScanInts(&l,&r)
        if check(l-1,r-1) { writer.WriteString("YES\n") } else { writer.WriteString("NO\n") }
    }
    writer.Flush()
}

package main

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

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

    ScanInts := func(a... *int) {
        for i := 0; i < len(a); i++ {
            scanner.Scan()
            *(a[i]), _ = strconv.Atoi(scanner.Text())
        }
    }

    scanner.Scan()
    s := scanner.Text()
    x := make([][3]int,len(s)+1)
    for i := 1; i <= len(s); i++ {
        for j := 0; j < 3; j++ { x[i][j] += x[i-1][j]}
        if s[i-1] == 'x' { x[i][0]++ }
        if s[i-1] == 'y' { x[i][1]++ }
        if s[i-1] == 'z' { x[i][2]++ }
    }

    check := func(l,r int) bool {
        if r-l < 2 { return true }
        max, min := -1000000000, 1000000000
        for i := 0; i < 3; i++ {
            a := x[r][i]-x[l-1][i]
            if max < a { max = a }
            if min > a { min = a }
        }
        if max-min <= 1 { return true }
        return false
    }

    var m,l,r int
    ScanInts(&m)
    for i := 0; i < m; i++ {
        ScanInts(&l,&r)
        if check(l,r) { writer.WriteString("YES\n") } else { writer.WriteString("NO\n") }
    }
    writer.Flush()
}

package main

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

func main() {
  reader := bufio.NewReader(os.Stdin)
  writer := bufio.NewWriter(os.Stdout)
  defer writer.Flush()
  line, _ := reader.ReadString('\n')
  s := strings.TrimSpace(line)
  n := len(s)

  counts := make([][]int, 3)
  for i := range(counts) {
    counts[i] = make([]int, n + 1)
  }
  for i, ch := range s {
    x := int(ch) - 120
    counts[x][i + 1] = 1
    for x = 0; x < 3; x++ {
      counts[x][i + 1] += counts[x][i]
    }
  }

  var m, a, b int
  line, _ = reader.ReadString('\n')
  fmt.Sscanf(line, "%d", &m)
  for i := 0; i < m; i++ {
    line, _ = reader.ReadString('\n')
    fmt.Sscanf(line, "%d %d", &a, &b)
    if b - a + 1 < 3 {
      writer.WriteString("YES\n")
      continue
    }
    spanCounts := make([]int, 3)
    for x := range spanCounts {
      spanCounts[x] = counts[x][a] - counts[x][b - 1]
    }
    sort.Ints(spanCounts)
    gap := spanCounts[2] - spanCounts[0]
    if gap <= 1 {
      writer.WriteString("YES\n")
    } else {
      writer.WriteString("NO\n")
    }
  }
}


On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed.Help the child to find out, what is the minimum total energy he should spend to remove all n parts.

The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi). Consider all the parts are numbered from 1 to n.

Output the minimum total energy the child should spend to remove all n parts of the toy.

NoteOne of the optimal sequence of actions in the first sample is:  First, remove part 3, cost of the action is 20.  Then, remove part 2, cost of the action is 10.  Next, remove part 4, cost of the action is 10.  At last, remove part 1, cost of the action is 0. So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.In the second sample, the child will spend 400 no matter in what order he will remove the parts.

package main

import (
	"fmt"
	"sort"
)

func ReadInt64() int64 { /*{{{*/
	var ret int64
	_, err := fmt.Scan(&ret)
	if err != nil {
		return 0
	}
	return ret
} /*}}}*/

type pair struct {
	ind  int64
	cost int64
}

func addEdge(a, b int64, m map[int64][]int64) {
	if m[a] == nil {
		m[a] = []int64{b}
	} else {
		m[a] = append(m[a], b)
	}
}

func main() {
	n, m := ReadInt64(), ReadInt64()
	costList := []pair{}
	value := []int64{}
	edge := map[int64][]int64{}

	for i := int64(0); i < n; i++ { /*{{{*/
		a := ReadInt64()
		value = append(value, a)
		costList = append(costList, pair{
			ind:  i,
			cost: a,
		})
	} /*}}}*/
	for i := int64(0); i < m; i++ {
		a, b := ReadInt64(), ReadInt64()
		a--
		b--
		addEdge(a, b, edge)
		addEdge(b, a, edge)
	}
	ans := int64(0)
	sort.Slice(costList, func(i, j int) bool {
		return costList[i].cost > costList[j].cost
	})
	for _, p := range costList {
		for _, to := range edge[p.ind] {
			ans += value[to]
		}
		value[p.ind] = 0
	}
	fmt.Printf("%d\n", ans)
}

package main
import (
	"fmt"
)
func main() {
	var ans int64
	ans=0
	var n,m,x,y,a int
	var w [1005]int
	fmt.Scan(&n,&m)
	for i:=1;i<=n;i++ {
		fmt.Scan(&w[i])
	}
	for i:=1;i<=m;i++ {
		fmt.Scan(&x,&y)
		if w[x]<w[y] {
			a=w[x]
		} else {
			a=w[y]
		}
		ans+=int64(a)
	}
	fmt.Println(ans)
}

package main

import "fmt"

func main() {
    min := func(a,b int) int { if a < b { return a } else { return b } }

    var n,m,x,y int
    fmt.Scan(&n,&m)
    a := make([]int,n)
    for i := 0; i < n; i++ {
        fmt.Scan(&a[i])
    }
    ans := 0
    for i := 0; i < m; i++ {
        fmt.Scan(&x,&y)
        ans += min(a[x-1],a[y-1])
    }
    fmt.Println(ans)
}

// Author: sighduck
// URL: https://codeforces.com/contest/437/problem/C

package main

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

type Edge struct {
	from int
	to   int
}

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

func Solve(n, m int, v []int, edges []Edge) int64 {
	s := int64(0)
	for _, edge := range edges {
		s += int64(min(v[edge.from-1], v[edge.to-1]))
	}
	return s
}

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

	var n, m int
	fmt.Fscanf(reader, "%d %d\n", &n, &m)
	v := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d", &v[i])
	}
	fmt.Fscanf(reader, "\n")
	edges := make([]Edge, m)
	for i := 0; i < m; i++ {
		fmt.Fscanf(reader, "%d %d\n", &edges[i].from, &edges[i].to)
	}

	fmt.Fprintf(writer, "%d\n", Solve(n, m, v, edges))
}


Little C loves number «3» very much. He loves all things about it.Now he has a positive integer $$$n$$$. He wants to split $$$n$$$ into $$$3$$$ positive integers $$$a,b,c$$$, such that $$$a+b+c=n$$$ and none of the $$$3$$$ integers is a multiple of $$$3$$$. Help him to find a solution.

A single line containing one integer $$$n$$$ ($$$3 \leq n \leq 10^9$$$) — the integer Little C has.

Print $$$3$$$ positive integers $$$a,b,c$$$ in a single line, such that $$$a+b+c=n$$$ and none of them is a multiple of $$$3$$$. It can be proved that there is at least one solution. If there are multiple solutions, print any of them.

package main

import "fmt"

func main() {
    var n int
    fmt.Scan(&n)
    fmt.Printf("%d ", 1);
    n--;
    for k := 0; k < 100; k++ {
		if ((n - k) % 3 != 0 && k % 3 != 0 ) {
		    fmt.Printf("%d %d",n - k,k);
		    break;
		}
	}
}

package main

import "fmt"

func main() {
	var n int
	fmt.Scanf("%d", &n)

	if n%3 == 2 {
		fmt.Printf("1 2 %d", n-3)
		return
	}
	fmt.Printf("1 1 %d", n-2)
}

package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scanln(&n)
	if n%3 == 2 {
		fmt.Println(n-3, 2, 1)
	} else {
		fmt.Println(n-2, 1, 1)
	}
}

package main

import (
	"fmt"
	"os"
)

func main() {
	var n int
	fmt.Scanln(&n)
	for i := n - 2; i >= 1; i-- {
		if i % 3 == 0 {
			continue
		}
		for j := n - i - 1; j >= 1; j--{
			if j % 3 == 0 {
				continue
			}
			k := n - i - j
			if k % 3 == 0 {
				continue
			}
			fmt.Println(i, j, k)
			os.Exit(0)
		}
	}
}

package main

import (
	"fmt"
)

func main() {
	var i int64
	fmt.Scanf("%d", &i)
	a := 1
	b := 1
	c := i - 2
	if c % 3 == 0 {
		c -= 1
		b += 1
	}
	fmt.Println(a, b, c)
}

package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scanf("%d", &n)
	switch n % 3 {
	case 0:
		fmt.Printf("%d %d %d", n-2, 1, 1)
	case 1:
		fmt.Printf("%d %d %d", n-3, 2, 1)
	case 2:
		fmt.Printf("%d %d %d", n-4, 2, 2)
	}
}

package main

import (
    "fmt"
)

var N int

func main() {
    fmt.Scanf("%d\n", &N)

    if N % 3 == 0 || N % 3 == 1 {
        fmt.Printf("%d 1 1\n", N-2)
    } else if N % 3 == 2 {
        fmt.Printf("%d 2 1\n", N-3)
    }
}

package main

import "fmt"

func main() {
	var n, a, b, c int
	fmt.Scan(&n)
	a, b, c = 1, 1, n-2
	if c%3 == 0 {
		a++
		c--
	}
	fmt.Printf("%v %v %v\n", a, b, c)
}

package main

import "fmt"

func main() {
	var n int
	fmt.Scanf("%d ", &n)

	for a := 1; a < n; a++ {
		for b := 1; a+b < n; b++ {
			c := n - a - b
			if a%3 != 0 && b%3 != 0 && c%3 != 0 {
				fmt.Println(a, b, c)
				return
			}
		}
	}
	return
}

package main

import "fmt"

func main() {
	var number int64
	fmt.Scanf("%d", &number)

	var val int64 = 1
	number = number - 2

	mod := (number) % 3
	if mod == 0 {
		val++
		number = number - 1
	}
	fmt.Printf("%d %d %d", 1, val, number)
}

package main

import (
	"fmt"
)

func main() {
	var n, a, b, c int
	fmt.Scanf("%d", &n)
	if n%3 != 0 {
		a = n / 3
		b = n / 3
		c = n / 3
		for n-(a+b+c) > 0 {
			if a%3 == 0 {
				a++
			} else if b%3 == 0 {
				b++
			} else {
				c++
			}
		}
		fmt.Printf("%d %d %d\n", a, b, c)
	} else {
		third := n / 3
		if third%3 == 0 {
			fmt.Printf("%d %d %d\n", third-1, third-1, third+2)
		} else {
			fmt.Printf("%d %d %d\n", third, third, third)
		}
	}
}

package main

import "fmt"

func main() {
	var number int64
	fmt.Scanf("%d", &number)

	var val int64 = 1
	number = number - 1

	mod := (number-1) % 3
	if mod == 0 {
		val++
		number = number - 1
	}
	fmt.Printf("%d %d %d", 1, val, number)
}

package main

import "fmt"

func main() {
	var number int64
	fmt.Scanf("%d", &number)

	val := number / 3
	mod := number % 3

	fmt.Printf("%d %d %d", val, val, val + mod)
}


You are given a sequence $$$a_1, a_2, \dots, a_n$$$, consisting of integers.You can apply the following operation to this sequence: choose some integer $$$x$$$ and move all elements equal to $$$x$$$ either to the beginning, or to the end of $$$a$$$. Note that you have to move all these elements in one direction in one operation.For example, if $$$a = [2, 1, 3, 1, 1, 3, 2]$$$, you can get the following sequences in one operation (for convenience, denote elements equal to $$$x$$$ as $$$x$$$-elements):   $$$[1, 1, 1, 2, 3, 3, 2]$$$ if you move all $$$1$$$-elements to the beginning;  $$$[2, 3, 3, 2, 1, 1, 1]$$$ if you move all $$$1$$$-elements to the end;  $$$[2, 2, 1, 3, 1, 1, 3]$$$ if you move all $$$2$$$-elements to the beginning;  $$$[1, 3, 1, 1, 3, 2, 2]$$$ if you move all $$$2$$$-elements to the end;  $$$[3, 3, 2, 1, 1, 1, 2]$$$ if you move all $$$3$$$-elements to the beginning;  $$$[2, 1, 1, 1, 2, 3, 3]$$$ if you move all $$$3$$$-elements to the end; You have to determine the minimum number of such operations so that the sequence $$$a$$$ becomes sorted in non-descending order. Non-descending order means that for all $$$i$$$ from $$$2$$$ to $$$n$$$, the condition $$$a_{i-1} \le a_i$$$ is satisfied.Note that you have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — the number of the queries. Each query is represented by two consecutive lines. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the number of elements. The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le n$$$) — the elements. It is guaranteed that the sum of all $$$n$$$ does not exceed $$$3 \cdot 10^5$$$.

For each query print one integer — the minimum number of operation for sorting sequence $$$a$$$ in non-descending order.

NoteIn the first query, you can move all $$$1$$$-elements to the beginning (after that sequence turn into $$$[1, 1, 1, 3, 6, 6, 3]$$$) and then move all $$$6$$$-elements to the end.In the second query, the sequence is sorted initially, so the answer is zero.In the third query, you have to move all $$$2$$$-elements to the beginning.

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
}

// DigitSum returns digit sum of a decimal number.
// DigitSum only accept a positive integer.
func DigitSum(n int) int {
	if n < 0 {
		return -1
	}

	res := 0

	for n > 0 {
		res += n % 10
		n /= 10
	}

	return res
}

// DigitNumOfDecimal returns digits number of n.
// n is non negative number.
func DigitNumOfDecimal(n int) int {
	res := 0

	for n > 0 {
		n /= 10
		res++
	}

	return res
}

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

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

	return s
}

// Kiriage returns Ceil(a/b)
// a >= 0, b > 0
func Kiriage(a, b int) int {
	return (a + (b - 1)) / b
}

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

var q int

func main() {
	q = ReadInt()

	for i := 0; i < q; i++ {
		n := ReadInt()
		A := ReadIntSlice(n)
		maxIds, minIds := make(map[int]int), make(map[int]int)

		// A[j]の最後尾のidxを記録
		for j := 0; j < n; j++ {
			maxIds[A[j]] = j
		}
		for j := n - 1; j >= 0; j-- {
			minIds[A[j]] = j
		}

		// A[j]についてuniq | sortする
		uniqs := []int{}
		for k := range maxIds {
			uniqs = append(uniqs, k)
		}
		sort.Sort(sort.IntSlice(uniqs))

		ans := 1
		tmpAns := 1
		for j := 0; j < len(uniqs)-1; j++ {
			l, r := uniqs[j], uniqs[j+1]
			if maxIds[l] < minIds[r] {
				tmpAns++
			} else {
				ChMax(&ans, tmpAns)
				tmpAns = 1
			}
		}
		ChMax(&ans, tmpAns)
		fmt.Println(len(uniqs) - ans)
	}
}

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

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

package main

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

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

	var T, n, v int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		pos := make([][2]int, n+1)
		for i := 1; i <= n; i++ {
			Fscan(in, &v)
			if pos[v][0] == 0 {
				pos[v] = [2]int{i, i}
			} else {
				pos[v][1] = i
			}
		}
		var tot, cnt, mxCnt, prev int
		for i := 1; i <= n; i++ {
			if pos[i][0] == 0 {
				continue
			}
			tot++
			if prev == 0 || pos[i][0] < pos[prev][1] {
				cnt = 1
			} else {
				cnt++
			}
			if cnt > mxCnt {
				mxCnt = cnt
			}
			prev = i
		}
		Fprintln(out, tot-mxCnt)
	}
}

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

package main

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

var (
	inn = bufio.NewScanner(os.Stdin)
	out = bufio.NewWriter(os.Stdout)
)

func main() {
	defer out.Flush()
	inn.Buffer([]byte{}, 1000000)
	inn.Split(bufio.ScanWords)

	const INF = int(1e9)
	for tt := rd(); tt > 0; tt-- {
		n := rd()
		l, r, dp := make([]int, n), make([]int, n), make([]int, n)
		for i := 0; i < n; i++ {
			l[i] = INF
			r[i] = -INF
			dp[i] = 0
		}
		mp := map[int]int{}
		for i := 0; i < n; i++ {
			x := rd() - 1
			l[x] = min(l[x], i)
			r[x] = max(r[x], i)
			mp[x] = 1
		}
		v := []int{}
		for key := range mp {
			v = append(v, key)
		}
		sort.Ints(v)
		ans := n
		for i := len(v) - 1; i >= 0; i-- {
			if i == len(v)-1 || r[v[i]] >= l[v[i+1]] {
				dp[i] = 1
			} else {
				dp[i] = dp[i+1] + 1
			}
			ans = min(ans, len(v)-dp[i])
		}
		Fprintln(out, ans)
	}
}
func change(v []int) {
	v[0]++
}

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
}
func rd() (x int) {
	inn.Scan()
	data := inn.Bytes()
	x, _ = strconv.Atoi(string(data))
	return x
}
func rdll() (x int64) {
	inn.Scan()
	data := inn.Bytes()
	x, _ = strconv.ParseInt(string(data), 10, 0)
	return x
}
func rds() string {
	inn.Scan()
	return string(inn.Bytes())
}

package main

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"math"
	"os"
	"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
}

// DigitSum returns digit sum of a decimal number.
// DigitSum only accept a positive integer.
func DigitSum(n int) int {
	if n < 0 {
		return -1
	}

	res := 0

	for n > 0 {
		res += n % 10
		n /= 10
	}

	return res
}

// DigitNumOfDecimal returns digits number of n.
// n is non negative number.
func DigitNumOfDecimal(n int) int {
	res := 0

	for n > 0 {
		n /= 10
		res++
	}

	return res
}

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

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

	return s
}

// Kiriage returns Ceil(a/b)
// a >= 0, b > 0
func Kiriage(a, b int) int {
	return (a + (b - 1)) / b
}

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

var q int

func main() {
	q = ReadInt()

	for i := 0; i < q; i++ {
		n := ReadInt()
		A := ReadIntSlice(n)
		memo := make([]int, n+1)

		for j := 0; j < n; j++ {
			memo[A[j]] = j
		}

		ans := 1
		tmpAns := 1
		for j := 1; j < n; j++ {
			if memo[j] < memo[j+1] {
				tmpAns++
			} else {
				ChMax(&ans, tmpAns)
				tmpAns = 1
			}
		}
		fmt.Println(n - ans)
	}
}

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

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

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
}

// DigitSum returns digit sum of a decimal number.
// DigitSum only accept a positive integer.
func DigitSum(n int) int {
	if n < 0 {
		return -1
	}

	res := 0

	for n > 0 {
		res += n % 10
		n /= 10
	}

	return res
}

// DigitNumOfDecimal returns digits number of n.
// n is non negative number.
func DigitNumOfDecimal(n int) int {
	res := 0

	for n > 0 {
		n /= 10
		res++
	}

	return res
}

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

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

	return s
}

// Kiriage returns Ceil(a/b)
// a >= 0, b > 0
func Kiriage(a, b int) int {
	return (a + (b - 1)) / b
}

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

var q int

func main() {
	q = ReadInt()

	for i := 0; i < q; i++ {
		n := ReadInt()
		A := ReadIntSlice(n)
		memo := make(map[int]int)

		// A[j]の最後尾のidxを記録
		for j := 0; j < n; j++ {
			memo[A[j]] = j
		}

		// A[j]についてuniq | sortする
		uniqs := []int{}
		for k := range memo {
			uniqs = append(uniqs, k)
		}
		sort.Sort(sort.IntSlice(uniqs))

		ans := 1
		tmpAns := 1
		for j := 0; j < len(uniqs)-1; j++ {
			l, r := uniqs[j], uniqs[j+1]
			if memo[l] < memo[r] {
				tmpAns++
			} else {
				ChMax(&ans, tmpAns)
				tmpAns = 1
			}
		}
		ChMax(&ans, tmpAns)
		fmt.Println(len(uniqs) - ans)
	}
}

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

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

package main

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"math"
	"os"
	"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
}

// DigitSum returns digit sum of a decimal number.
// DigitSum only accept a positive integer.
func DigitSum(n int) int {
	if n < 0 {
		return -1
	}

	res := 0

	for n > 0 {
		res += n % 10
		n /= 10
	}

	return res
}

// DigitNumOfDecimal returns digits number of n.
// n is non negative number.
func DigitNumOfDecimal(n int) int {
	res := 0

	for n > 0 {
		n /= 10
		res++
	}

	return res
}

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

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

	return s
}

// Kiriage returns Ceil(a/b)
// a >= 0, b > 0
func Kiriage(a, b int) int {
	return (a + (b - 1)) / b
}

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

var q int

func main() {
	q = ReadInt()

	for i := 0; i < q; i++ {
		n := ReadInt()
		A := ReadIntSlice(n)

		memo := make([]int, n+1)
		for i := 0; i < n-1; i++ {
			if A[i] > A[i+1] {
				memo[A[i+1]]++
			}
		}

		ans := 0
		for a := 1; a <= n; a++ {
			if memo[a] > 0 {
				ans++
			}
		}

		fmt.Println(ans)
	}
}

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

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


Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them.

The first line of the input contains a single integer n (1 ≤ n ≤ 500 000) — the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500 000.

Print the resulting hashtags in any of the optimal solutions.

NoteWord a1, a2, ..., am of length m is lexicographically not greater than word b1, b2, ..., bk of length k, if one of two conditions hold:   at first position i, such that ai ≠ bi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ;  if there is no such position i and m ≤ k, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two.

package main

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

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

	var n int
	Fscan(in, &n)
	tags := make([]string, n)
	for i := range tags {
		Fscan(in, &tags[i])
	}

	for i := len(tags) - 2; i >= 0; i-- {
		t0, t1 := tags[i], tags[i+1]
		l := len(t0)
		if len(t1) < l {
			l = len(t1)
		}
		if t0[:l] == t1[:l] {
			tags[i] = t0[:l]
			continue
		}
		j := 1
		for ; j < l; j++ {
			if t0[j] < t1[j] {
				break
			}
			if t0[j] > t1[j] {
				tags[i] = tags[i][:j]
				break
			}
		}
	}
	for _, tag := range tags {
		Fprintln(out, tag)
	}
}

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