Kolya got an integer array $$$a_1, a_2, \dots, a_n$$$. The array can contain both positive and negative integers, but Kolya doesn't like $$$0$$$, so the array doesn't contain any zeros.Kolya doesn't like that the sum of some subsegments of his array can be $$$0$$$. The subsegment is some consecutive segment of elements of the array. You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum $$$0$$$. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, $$$0$$$, any by absolute value, even such a huge that they can't be represented in most standard programming languages).Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum $$$0$$$.

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 200\,000$$$) — the number of elements in Kolya's array. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^{9} \le a_i \le 10^{9}, a_i \neq 0$$$) — the description of Kolya's array.

Print the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum $$$0$$$.

NoteConsider the first example. There is only one subsegment with the sum $$$0$$$. It starts in the second element and ends in the fourth element. It's enough to insert one element so the array doesn't contain any subsegments with the sum equal to zero. For example, it is possible to insert the integer $$$1$$$ between second and third elements of the array.There are no subsegments having sum $$$0$$$ in the second example so you don't need to do anything.

package main

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

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

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

/*program starts here*/
func main() {
	defer writer.Flush()

	var n int
	scanf("%d\n", &n)
	ar := make([]int64, n)
	for i := range ar {
		scanf("%v", &ar[i])
	}

	mp := make(map[int64]bool)
	res := 0
	mp[ar[0]] = true

	for i := 1; i < n; i++ {
		sum := ar[i] + ar[i-1]

		if sum == 0 || mp[sum] {
			//printf("%d: %d \n", i, sum)
			res++
			mp = make(map[int64]bool)
			mp[ar[i]] = true
			sum = ar[i]
		} else {
			mp[sum] = true
		}
		ar[i] = sum
	}
	printf("%v\n", res)
}

package main

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

func main() {
	sc := bufio.NewScanner(os.Stdin)
	bf := make([]byte, 1024*1024)
	sc.Buffer(bf, 10*1024*1024)
	sc.Split(bufio.ScanWords)

	in := func() int64 {
		sc.Scan()
		i, _ := strconv.ParseInt(sc.Text(), 10, 64)
		return i
	}

	n := in()
	a := make([]int64, n)

	for i := range a {
		a[i] = in()
	}

	m := make(map[int64]bool)

	cnt := 0

	m[a[0]] = true

	for i := int64(1); i < n; i++ {
		v := a[i] + a[i-1]

		//fmt.Println(a, a[i-1], a[i], v)

		if v == 0 || m[v] == true {
			cnt++
			m = make(map[int64]bool)
			m[a[i]] = true
			v = a[i]
		} else {
			m[v] = true
		}

		a[i] = v
	}

	fmt.Println(cnt)
}

package main

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

func main() {
	n := ReadInt64()
	a := ReadInt64s(int(n))
	fmt.Println(solve(a))
}

func solve(a []int64) int64 {
	s := make([]int64, len(a)+1)
	for i := 0; i < len(a); i++ {
		s[i+1] = s[i] + a[i]
	}
	var ans int64
	m := make(map[int64]int)
	last := -1
	for i := 0; i < len(s); i++ {
		if prev, exists := m[s[i]]; exists && prev > last {
			ans++
			last = i - 2
		}
		m[s[i]] = i
	}
	return ans
}

var reader = bufio.NewReader(os.Stdin)

func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(reader, a...); err != nil {
		panic(err)
	}
}
func ReadString() (s string) { Scan(&s); return }
func ReadInt() (i int)       { Scan(&i); return }
func ReadInts(n int) []int {
	v := make([]int, n)
	for i := 0; i < n; i++ {
		Scan(&v[i])
	}
	return v
}
func ReadInt64() (i int64) { Scan(&i); return }
func ReadInt64s(n int) []int64 {
	v := make([]int64, n)
	for i := 0; i < n; i++ {
		Scan(&v[i])
	}
	return v
}

package main

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

// https://codeforces.com/contest/1426/problem/D

var in *bufio.Reader
var out *bufio.Writer

func printf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(out, x, a...)
}

func scanf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fscanf(in, x, a...)
}

func scan(a ...interface{}) (n int, err error) {
	return fmt.Fscan(in, a...)
}

var err error

func next() (n string) {
	scan(&n)
	return n
}

func nextInt() (n int) {
	scan(&n)
	return n
}

func nextInt64() (n int64) {
	scan(&n)
	return n
}

func nextDouble() (n float64) {
	scan(&n)
	return n
}

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

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

// ==================== 以上是模版 ====================
func getIn() *bufio.Reader {
	/*

			1 2 -1 -2 1
			-1 | 1 | -1 | 1  | -1 | 1 1 | -1 -1

			4 -2 3 -9 2

		// 1. 获取到全部可能到值
			-3, 2
			1, 10 1,2
			2, 20
			3, 5, 3,5
			4,30  4,5
			6-10,

		//
			a b c d

			求和问题
			维护一个range
	*/
	x := `
4
1 -5 3 2
`
	return bufio.NewReaderSize(strings.NewReader(x), 8192)
}

const maxn = 200005

var A [maxn]int64
var S [maxn]int64
var M = make(map[int64][]int)
var P [][2]int

func solve() {

	n := nextInt()
	M[0] = []int{-1}
	for i := 0; i < n; i++ {
		A[i] = nextInt64()
		if i == 0 {
			S[i] = A[i]
		} else {
			S[i] = S[i-1] + A[i]
		}
		M[S[i]] = append(M[S[i]], i)
	}
	//fmt.Println("109")

	// get pairs
	//fmt.Println(M)
	for _, v := range M {
		l := len(v)
		if l > 1 {
			for i := 0; i < l-1; i++ {
				P = append(P, [2]int{v[i] + 1, v[i+1]})
			}
		}
	}
	//fmt.Println(len(P))
	//fmt.Println(P)

	// 合并pairs
	sort.Slice(P, func(i, j int) bool {
		return P[i][0] < P[j][0]
	})
	//fmt.Println(P)
	// 输出
	if len(P) <= 1 {
		printf("%d\n", len(P))
	} else {
		res := 1
		lastL, lastR := P[0][0], P[0][1]
		for i := 1; i < len(P); i++ {
			if Max(P[i][0], lastL) < Min(P[i][1], lastR) {
				lastL, lastR = Max(P[i][0], lastL), Min(P[i][1], lastR)
			} else {
				res += 1
				lastL, lastR = P[i][0], P[i][1]
			}
			//fmt.Println(lastL, lastR)
		}
		printf("%d\n", res)
	}
}

func main() {
	in = bufio.NewReaderSize(os.Stdin, 8192)
	//in = getIn()

	out = bufio.NewWriterSize(os.Stdout, 8192)
	defer out.Flush()
	//for t := nextInt(); t > 0; t-- {
	solve()
	//}
}

package main

// Problem Title: Non-zero Segments

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

// Both solutions 1 and 2 below got TLE of 2seconds in the
// 22nd test case without this fast io processing method
//
func processInput() (int, *[]int64) {
	var buf []byte
	buf, _ = ioutil.ReadAll(os.Stdin)
	l := len(buf)

	var i, n int
	for ; buf[i] >= '0' && buf[i] <= '9'; i++ {
		n = (n << 3) + (n << 1) + int(buf[i]&15)
	}

	ints := make([]int64, n)
	for j := 0; j < n; j++ {
		for ; buf[i] != '-' && !(buf[i] >= '0' && buf[i] <= '9'); i++ {
		}

		var neg bool
		if buf[i] == '-' {
			neg = true
			i++
		}

		for ; i < l && buf[i] >= '0' && buf[i] <= '9'; i++ {
			ints[j] = (ints[j] << 3) + (ints[j] << 1) + int64(buf[i]&15)
		}

		if neg {
			ints[j] = -ints[j]
		}
	}

	return n, &ints
}

// Solution1 uses mapping approach
// tutorial: https://codeforces.com/blog/entry/83120
//
func Solution1() {
	n, int64s := processInput()

	var ans int
	var sum int64
	pre := map[int64]int{0: 1}

	for i := 0; i < n; i++ {
		sum += (*int64s)[i]

		_, has := pre[sum]
		if has {
			ans++
			sum = (*int64s)[i]
			pre = map[int64]int{0: 1}
		}

		pre[sum]++
	}

	// fmt.Println(pre)

	fmt.Println(ans)
}

// below code credits
// https://codeforces.com/contest/1426/submission/94096753

type item struct {
	pos        int
	x          int64
	prefix     int64
	compressed int
}
type items []item

type itemsByPosAsc items

func (o itemsByPosAsc) Len() int           { return len(o) }
func (o itemsByPosAsc) Swap(i, j int)      { o[i], o[j] = o[j], o[i] }
func (o itemsByPosAsc) Less(i, j int) bool { return o[i].pos < o[j].pos }

type itemsByPrefixAsc items

func (o itemsByPrefixAsc) Len() int           { return len(o) }
func (o itemsByPrefixAsc) Swap(i, j int)      { o[i], o[j] = o[j], o[i] }
func (o itemsByPrefixAsc) Less(i, j int) bool { return o[i].prefix < o[j].prefix }

// fillCompressed fills the compressed property in the range [l, r] with x value
func (o items) fillCompressed(l, r int, x int) {
	for ; l <= r; l++ {
		o[l].compressed = x
	}
}

func (o items) showXs(s string) {
	fmt.Print(s, ":")
	for i, l := 0, len(o); i < l; i++ {
		fmt.Printf(" %2d", o[i].x)
	}
	fmt.Println()
}

func (o items) showPrefixes(s string) {
	fmt.Print(s, ":")
	for i, l := 0, len(o); i < l; i++ {
		fmt.Printf(" %2d", o[i].prefix)
	}
	fmt.Println()
}

// Solution2 uses arrays and compressed strategy of prefixes
// to solve the problem in O(NlogN) time without mappings
//
func Solution2() {
	n, int64s := processInput()

	arr := make([]item, n+1)

	for i := 1; i <= n; i++ {
		arr[i].pos = i
		arr[i].x = (*int64s)[i-1]
		arr[i].prefix = arr[i-1].prefix + arr[i].x
	}

	// items(arr).showXs("__x")

	// items(arr).showPrefixes("pre")
	sort.Sort(itemsByPrefixAsc(arr))
	// items(arr).showPrefixes("ord")

	// compress prefixes from [0, ..., sz)
	var sz int = 0
	var rangeStart int = 0

	for i := 1; i <= n; i++ {
		if arr[i].prefix != arr[i-1].prefix {
			items(arr).fillCompressed(rangeStart, i-1, sz)
			sz++
			rangeStart = i
		}
	}

	items(arr).fillCompressed(rangeStart, n, sz)
	sz++

	// sort pre by pos
	sort.Sort(itemsByPosAsc(arr))
	// items(arr).showPrefixes("__f")

	// make a seen_value arr of sz length
	seen := make([]int, sz)
	for i := 0; i < sz; i++ {
		seen[i] = -1
	}

	var ans int = 0
	var barrierAt = 1

	// in order for each compressed pre value: set as seen
	// then, if already seen: ans++

	for i := 1; i <= n; i++ {
		var _prefix int = arr[i].compressed

		if seen[_prefix] == barrierAt || arr[barrierAt-1].prefix == arr[i].prefix {
			ans++
			barrierAt = i
			// fmt.Println("Put a barrier before", i)
		}
		seen[_prefix] = barrierAt
	}

	fmt.Printf("%v\n", ans)
}

func main() {
	Solution1()
}

package main

// Problem Title: Non-zero Segments

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

func processInput() []int64 {
	var buf []byte
	buf, _ = ioutil.ReadAll(os.Stdin)

	ints := make([]int64, 2e5+5)
	var i int
	var neg, valid bool

	for _, v := range buf {
		if v >= '0' && v <= '9' {
			ints[i] = ints[i]*10 + int64(v-'0')
			valid = true
			continue
		}
		if v == '-' {
			neg = true
			valid = true
			continue
		}
		if valid {
			if neg {
				ints[i] = -ints[i]
			}
			i++
			neg = false
			valid = false
		}
	}

	return ints
}

// Both solutions 1 and 2 below got TLE of 2seconds in 22nd test case
//

// Solution1 uses mapping approach
// tutorial: https://codeforces.com/blog/entry/83120
//
func Solution1() {
	input := processInput()
	n := int(input[0])

	var ans int
	var sum int64
	pre := map[int64]int{0: 1}

	for i := 1; i <= n; i++ {
		sum += input[i]

		_, has := pre[sum]
		if has {
			ans++
			sum = input[i]
			pre = map[int64]int{0: 1}
		}

		pre[sum]++
	}

	// fmt.Println(pre)

	fmt.Println(ans)
}

// below code credits
// https://codeforces.com/contest/1426/submission/94096753

type item struct {
	pos        int
	x          int64
	prefix     int64
	compressed int
}
type items []item

type itemsByPosAsc items

func (o itemsByPosAsc) Len() int           { return len(o) }
func (o itemsByPosAsc) Swap(i, j int)      { o[i], o[j] = o[j], o[i] }
func (o itemsByPosAsc) Less(i, j int) bool { return o[i].pos < o[j].pos }

type itemsByPrefixAsc items

func (o itemsByPrefixAsc) Len() int           { return len(o) }
func (o itemsByPrefixAsc) Swap(i, j int)      { o[i], o[j] = o[j], o[i] }
func (o itemsByPrefixAsc) Less(i, j int) bool { return o[i].prefix < o[j].prefix }

// fillCompressed fills the compressed property in the range [l, r] with x value
func (o items) fillCompressed(l, r int, x int) {
	for ; l <= r; l++ {
		o[l].compressed = x
	}
}

func (o items) showXs(s string) {
	fmt.Print(s, ":")
	for i, l := 0, len(o); i < l; i++ {
		fmt.Printf(" %2d", o[i].x)
	}
	fmt.Println()
}

func (o items) showPrefixes(s string) {
	fmt.Print(s, ":")
	for i, l := 0, len(o); i < l; i++ {
		fmt.Printf(" %2d", o[i].prefix)
	}
	fmt.Println()
}

// Solution2 uses arrays and compressed strategy of prefixes
// to solve the problem in O(NlogN) time without mappings
//
func Solution2() {
	var n int
	fmt.Scanf("%v\n", &n)
	arr := make([]item, n+1)

	for i := 1; i <= n; i++ {
		arr[i].pos = i
		fmt.Scanf("%v", &arr[i].x)
		arr[i].prefix = arr[i-1].prefix + arr[i].x
	}

	// items(arr).showXs("__x")

	// items(arr).showPrefixes("pre")
	sort.Sort(itemsByPrefixAsc(arr))
	// items(arr).showPrefixes("ord")

	// compress prefixes from [0, ..., sz)
	var sz int = 0
	var rangeStart int = 0

	for i := 1; i <= n; i++ {
		if arr[i].prefix != arr[i-1].prefix {
			items(arr).fillCompressed(rangeStart, i-1, sz)
			sz++
			rangeStart = i
		}
	}

	items(arr).fillCompressed(rangeStart, n, sz)
	sz++

	// sort pre by pos
	sort.Sort(itemsByPosAsc(arr))
	// items(arr).showPrefixes("__f")

	// make a seen_value arr of sz length
	seen := make([]int, sz)
	for i := 0; i < sz; i++ {
		seen[i] = -1
	}

	var ans int = 0
	var barrierAt = 1

	// in order for each compressed pre value: set as seen
	// then, if already seen: ans++

	for i := 1; i <= n; i++ {
		var _prefix int = arr[i].compressed

		if seen[_prefix] == barrierAt || arr[barrierAt-1].prefix == arr[i].prefix {
			ans++
			barrierAt = i
			// fmt.Println("Put a barrier before", i)
		}
		seen[_prefix] = barrierAt
	}

	fmt.Printf("%v\n", ans)
}

func main() {
	Solution1()
}

package main

// Problem Title: Non-zero Segments

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

func processInput() []int64 {
	var buf []byte
	buf, _ = ioutil.ReadAll(os.Stdin)

	ints := make([]int64, 2e5+5)
	var i int
	var neg, valid bool

	for _, v := range buf {
		if v >= '0' && v <= '9' {
			ints[i] = ints[i]*10 + int64(v-'0')
			valid = true
			continue
		}
		if v == '-' {
			neg = true
			valid = true
			continue
		}
		if valid {
			if neg {
				ints[i] = -ints[i]
			}
			i++
			neg = false
			valid = false
		}
	}

	return ints
}

// Both solutions 1 and 2 below got TLE of 2seconds in 22nd test case
//

// Solution1 uses mapping approach
// tutorial: https://codeforces.com/blog/entry/83120
//
func Solution1() {
	input := processInput()
	n := int(input[0])

	var ans int
	var sum int64
	pre := map[int64]int{0: 1}

	for i := 1; i <= n; i++ {
		sum += input[i]

		_, has := pre[sum]
		if has {
			ans++
			sum = input[i]
			pre = map[int64]int{0: 1}
		}

		pre[sum]++
	}

	// fmt.Println(pre)

	fmt.Println(ans)
}

// below code credits
// https://codeforces.com/contest/1426/submission/94096753

type item struct {
	pos        int
	x          int64
	prefix     int64
	compressed int
}
type items []item

type itemsByPosAsc items

func (o itemsByPosAsc) Len() int           { return len(o) }
func (o itemsByPosAsc) Swap(i, j int)      { o[i], o[j] = o[j], o[i] }
func (o itemsByPosAsc) Less(i, j int) bool { return o[i].pos < o[j].pos }

type itemsByPrefixAsc items

func (o itemsByPrefixAsc) Len() int           { return len(o) }
func (o itemsByPrefixAsc) Swap(i, j int)      { o[i], o[j] = o[j], o[i] }
func (o itemsByPrefixAsc) Less(i, j int) bool { return o[i].prefix < o[j].prefix }

// fillCompressed fills the compressed property in the range [l, r] with x value
func (o items) fillCompressed(l, r int, x int) {
	for ; l <= r; l++ {
		o[l].compressed = x
	}
}

func (o items) showXs(s string) {
	fmt.Print(s, ":")
	for i, l := 0, len(o); i < l; i++ {
		fmt.Printf(" %2d", o[i].x)
	}
	fmt.Println()
}

func (o items) showPrefixes(s string) {
	fmt.Print(s, ":")
	for i, l := 0, len(o); i < l; i++ {
		fmt.Printf(" %2d", o[i].prefix)
	}
	fmt.Println()
}

// Solution2 uses arrays and compressed strategy of prefixes
// to solve the problem in O(NlogN) time without mappings
//
func Solution2() {
	input := processInput()
	n := int(input[0])

	arr := make([]item, n+1)

	for i := 1; i <= n; i++ {
		arr[i].pos = i
		arr[i].x = input[i]
		arr[i].prefix = arr[i-1].prefix + arr[i].x
	}

	// items(arr).showXs("__x")

	// items(arr).showPrefixes("pre")
	sort.Sort(itemsByPrefixAsc(arr))
	// items(arr).showPrefixes("ord")

	// compress prefixes from [0, ..., sz)
	var sz int = 0
	var rangeStart int = 0

	for i := 1; i <= n; i++ {
		if arr[i].prefix != arr[i-1].prefix {
			items(arr).fillCompressed(rangeStart, i-1, sz)
			sz++
			rangeStart = i
		}
	}

	items(arr).fillCompressed(rangeStart, n, sz)
	sz++

	// sort pre by pos
	sort.Sort(itemsByPosAsc(arr))
	// items(arr).showPrefixes("__f")

	// make a seen_value arr of sz length
	seen := make([]int, sz)
	for i := 0; i < sz; i++ {
		seen[i] = -1
	}

	var ans int = 0
	var barrierAt = 1

	// in order for each compressed pre value: set as seen
	// then, if already seen: ans++

	for i := 1; i <= n; i++ {
		var _prefix int = arr[i].compressed

		if seen[_prefix] == barrierAt || arr[barrierAt-1].prefix == arr[i].prefix {
			ans++
			barrierAt = i
			// fmt.Println("Put a barrier before", i)
		}
		seen[_prefix] = barrierAt
	}

	fmt.Printf("%v\n", ans)
}

func main() {
	Solution2()
}

package main

// Problem Title: Non-zero Segments

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

// Both solutions 1 and 2 below got TLE of 2seconds in the
// 22nd test case without this fast io processing method
//
func processInput() (int, []int64) {
	var buf []byte
	buf, _ = ioutil.ReadAll(os.Stdin)
	l := len(buf)

	var i, n int
	for ; buf[i] >= '0' && buf[i] <= '9'; i++ {
		n = (n << 3) + (n << 1) + int(buf[i]&15)
	}

	ints := make([]int64, n)
	for j := 0; j < n; j++ {
		for ; buf[i] != '-' && !(buf[i] >= '0' && buf[i] <= '9'); i++ {
		}

		var neg bool
		if buf[i] == '-' {
			neg = true
			i++
		}

		for ; i < l && buf[i] >= '0' && buf[i] <= '9'; i++ {
			ints[j] = (ints[j] << 3) + (ints[j] << 1) + int64(buf[i]&15)
		}

		if neg {
			ints[j] = -ints[j]
		}
	}

	return n, ints
}

// Solution1 uses mapping approach
// tutorial: https://codeforces.com/blog/entry/83120
//
func Solution1() {
	n, int64s := processInput()

	var ans int
	var sum int64
	pre := map[int64]int{0: 1}

	for i := 0; i < n; i++ {
		sum += int64s[i]

		_, has := pre[sum]
		if has {
			ans++
			sum = int64s[i]
			pre = map[int64]int{0: 1}
		}

		pre[sum]++
	}

	// fmt.Println(pre)

	fmt.Println(ans)
}

// below code credits
// https://codeforces.com/contest/1426/submission/94096753

type item struct {
	pos        int
	x          int64
	prefix     int64
	compressed int
}
type items []item

type itemsByPosAsc items

func (o itemsByPosAsc) Len() int           { return len(o) }
func (o itemsByPosAsc) Swap(i, j int)      { o[i], o[j] = o[j], o[i] }
func (o itemsByPosAsc) Less(i, j int) bool { return o[i].pos < o[j].pos }

type itemsByPrefixAsc items

func (o itemsByPrefixAsc) Len() int           { return len(o) }
func (o itemsByPrefixAsc) Swap(i, j int)      { o[i], o[j] = o[j], o[i] }
func (o itemsByPrefixAsc) Less(i, j int) bool { return o[i].prefix < o[j].prefix }

// fillCompressed fills the compressed property in the range [l, r] with x value
func (o items) fillCompressed(l, r int, x int) {
	for ; l <= r; l++ {
		o[l].compressed = x
	}
}

func (o items) showXs(s string) {
	fmt.Print(s, ":")
	for i, l := 0, len(o); i < l; i++ {
		fmt.Printf(" %2d", o[i].x)
	}
	fmt.Println()
}

func (o items) showPrefixes(s string) {
	fmt.Print(s, ":")
	for i, l := 0, len(o); i < l; i++ {
		fmt.Printf(" %2d", o[i].prefix)
	}
	fmt.Println()
}

// Solution2 uses arrays and compressed strategy of prefixes
// to solve the problem in O(NlogN) time without mappings
//
func Solution2() {
	n, int64s := processInput()

	arr := make([]item, n+1)

	for i := 1; i <= n; i++ {
		arr[i].pos = i
		arr[i].x = int64s[i-1]
		arr[i].prefix = arr[i-1].prefix + arr[i].x
	}

	// items(arr).showXs("__x")

	// items(arr).showPrefixes("pre")
	sort.Sort(itemsByPrefixAsc(arr))
	// items(arr).showPrefixes("ord")

	// compress prefixes from [0, ..., sz)
	var sz int = 0
	var rangeStart int = 0

	for i := 1; i <= n; i++ {
		if arr[i].prefix != arr[i-1].prefix {
			items(arr).fillCompressed(rangeStart, i-1, sz)
			sz++
			rangeStart = i
		}
	}

	items(arr).fillCompressed(rangeStart, n, sz)
	sz++

	// sort pre by pos
	sort.Sort(itemsByPosAsc(arr))
	// items(arr).showPrefixes("__f")

	// make a seen_value arr of sz length
	seen := make([]int, sz)
	for i := 0; i < sz; i++ {
		seen[i] = -1
	}

	var ans int = 0
	var barrierAt = 1

	// in order for each compressed pre value: set as seen
	// then, if already seen: ans++

	for i := 1; i <= n; i++ {
		var _prefix int = arr[i].compressed

		if seen[_prefix] == barrierAt || arr[barrierAt-1].prefix == arr[i].prefix {
			ans++
			barrierAt = i
			// fmt.Println("Put a barrier before", i)
		}
		seen[_prefix] = barrierAt
	}

	fmt.Printf("%v\n", ans)
}

func main() {
	Solution1()
}

package main

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

// github.com/EndlessCheng/codeforces-go
func main() {
	in := bufio.NewReader(os.Stdin)
	var n, ans, v int
	Fscan(in, &n)
	sum := make([]int64, n+1)
	mp := map[int64]bool{0: true}
	for i := 0; i < n; i++ {
		Fscan(in, &v)
		sum[i+1] = sum[i] + int64(v)
		if mp[sum[i+1]] {
			ans++
			mp = map[int64]bool{sum[i]: true}
		}
		mp[sum[i+1]] = true
	}
	Print(ans)
}

package main

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

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

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

/*program starts here*/
func main() {
	defer writer.Flush()

	var n int
	scanf("%d\n", &n)
	ar := make([]int, n)
	for i := range ar {
		scanf("%d", &ar[i])
	}

	mp := make(map[int]bool)
	res := 0
	mp[ar[0]] = true

	for i := 1; i < n; i++ {
		sum := ar[i] + ar[i-1]

		if sum == 0 || mp[sum] {
			//printf("%d: %d \n", i, sum)
			res++
			mp = make(map[int]bool)
			mp[ar[i]] = true
			sum = ar[i]
		} else {
			mp[sum] = true
		}
		ar[i] = sum
	}
	printf("%v\n", res)
}

package main

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

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

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

/*program starts here*/
func main() {
	defer writer.Flush()

	var n int
	scanf("%d", &n)
	ar := make([]int, n)
	for i := range ar {
		scanf("%d", &ar[i])
	}

	mp := make(map[int]bool)
	res := 0
	mp[ar[0]] = true

	for i := 1; i < n; i++ {
		sum := ar[i] + ar[i-1]

		if sum == 0 || mp[sum] {
			//printf("%d ", i)
			res++
			mp = make(map[int]bool)
			mp[ar[i]] = true
			sum = ar[i]
		} else {
			mp[sum] = true
		}
		ar[i] = sum
	}
	printf("%d\n", res)
}

package main

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

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

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

/*program starts here*/
func main() {
	defer writer.Flush()

	var n int
	scanf("%d\n", &n)
	ar := make([]int, n)
	for i := range ar {
		scanf("%d", &ar[i])
	}

	mp := make(map[int]bool)
	res := 0
	mp[ar[0]] = true

	for i := 1; i < n; i++ {
		sum := ar[i] + ar[i-1]

		if sum == 0 || mp[sum] {
			//printf("%d: %d \n", i, sum)
			res++
			mp = make(map[int]bool)
			mp[ar[i]] = true
			sum = ar[i]
		} else {
			mp[sum] = true
		}
		ar[i] = sum
	}
	printf("%d\n", res)
}

package main

// Problem Title: Non-zero Segments

import (
	"fmt"
	"sort"
)

// Solution1 uses mapping approach
// got TLE of 2seconds in 22nd test case
//
// tutorial: https://codeforces.com/blog/entry/83120
//
func Solution1() {
	var n, ans int
	fmt.Scanf("%v\n", &n)

	var x, sum int64
	pre := map[int64]int{0: 1}

	for i := 0; i < n; i++ {
		fmt.Scanf("%v", &x)

		sum += x

		_, has := pre[sum]
		if has {
			ans++
			sum = x
			pre = map[int64]int{0: 1}
		}

		pre[sum]++
	}

	// fmt.Println(pre)

	fmt.Println(ans)
}

// below code credits
// https://codeforces.com/contest/1426/submission/94096753

type item struct {
	pos        int
	x          int64
	prefix     int64
	compressed int
}
type items []item

type itemsByPosAsc items

func (o itemsByPosAsc) Len() int           { return len(o) }
func (o itemsByPosAsc) Swap(i, j int)      { o[i], o[j] = o[j], o[i] }
func (o itemsByPosAsc) Less(i, j int) bool { return o[i].pos < o[j].pos }

type itemsByPrefixAsc items

func (o itemsByPrefixAsc) Len() int           { return len(o) }
func (o itemsByPrefixAsc) Swap(i, j int)      { o[i], o[j] = o[j], o[i] }
func (o itemsByPrefixAsc) Less(i, j int) bool { return o[i].prefix < o[j].prefix }

// fillCompressed fills the compressed property in the range [l, r] with x value
func (o items) fillCompressed(l, r int, x int) {
	for ; l <= r; l++ {
		o[l].compressed = x
	}
}

func (o items) showXs(s string) {
	fmt.Print(s, ":")
	for i, l := 0, len(o); i < l; i++ {
		fmt.Printf(" %2d", o[i].x)
	}
	fmt.Println()
}

func (o items) showPrefixes(s string) {
	fmt.Print(s, ":")
	for i, l := 0, len(o); i < l; i++ {
		fmt.Printf(" %2d", o[i].prefix)
	}
	fmt.Println()
}

// Solution2 uses arrays and compressed strategy of prefixes
// to solve the problem in O(NlogN) time without mappings
//
func Solution2() {
	var n int
	fmt.Scanf("%v\n", &n)
	arr := make([]item, n+1)

	for i := 1; i <= n; i++ {
		arr[i].pos = i
		fmt.Scanf("%v", &arr[i].x)
		arr[i].prefix = arr[i-1].prefix + arr[i].x
	}

	// items(arr).showXs("__x")

	// items(arr).showPrefixes("pre")
	sort.Sort(itemsByPrefixAsc(arr))
	// items(arr).showPrefixes("ord")

	// compress prefixes from [0, ..., sz)
	var sz int = 0
	var rangeStart int = 0

	for i := 1; i <= n; i++ {
		if arr[i].prefix != arr[i-1].prefix {
			items(arr).fillCompressed(rangeStart, i-1, sz)
			sz++
			rangeStart = i
		}
	}

	items(arr).fillCompressed(rangeStart, n, sz)
	sz++

	// sort pre by pos
	sort.Sort(itemsByPosAsc(arr))
	// items(arr).showPrefixes("__f")

	// make a seen_value arr of sz length
	seen := make([]int, sz)
	for i := 0; i < sz; i++ {
		seen[i] = -1
	}

	var ans int = 0

	// in order for each compressed pre value: set as seen
	// then, if already seen: ans++

	for i := 1; i <= n; i++ {
		var idx int = arr[i].compressed

		if seen[idx] == ans || arr[ans].prefix == arr[i].prefix {
			ans++
			// fmt.Println("Put a barrier before", i)
		}
		seen[idx] = ans
	}

	fmt.Printf("%v\n", ans)
}

func main() {
	Solution2()
}

package main

// Problem Title: Non-zero Segments

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

func processInput() []int64 {
	var buf []byte
	buf, _ = ioutil.ReadAll(os.Stdin)

	ints := make([]int64, 2e5+5)
	var i int = 0
	var neg bool = false

	for _, v := range buf {
		if v >= '0' && v <= '9' {
			ints[i] = ints[i]*10 + int64(v-'0')
			continue
		}
		if v == '-' {
			neg = true
			continue
		}
		if neg {
			ints[i] = -ints[i]
		}
		i++
		neg = false
	}

	return ints
}

// Both solutions 1 and 2 below got TLE of 2seconds in 22nd test case
//

// Solution1 uses mapping approach
// tutorial: https://codeforces.com/blog/entry/83120
//
func Solution1() {
	input := processInput()
	n := int(input[0])

	var ans int
	var sum int64
	pre := map[int64]int{0: 1}

	for i := 1; i <= n; i++ {
		sum += input[i]

		_, has := pre[sum]
		if has {
			ans++
			sum = input[i]
			pre = map[int64]int{0: 1}
		}

		pre[sum]++
	}

	// fmt.Println(pre)

	fmt.Println(ans)
}

// below code credits
// https://codeforces.com/contest/1426/submission/94096753

type item struct {
	pos        int
	x          int64
	prefix     int64
	compressed int
}
type items []item

type itemsByPosAsc items

func (o itemsByPosAsc) Len() int           { return len(o) }
func (o itemsByPosAsc) Swap(i, j int)      { o[i], o[j] = o[j], o[i] }
func (o itemsByPosAsc) Less(i, j int) bool { return o[i].pos < o[j].pos }

type itemsByPrefixAsc items

func (o itemsByPrefixAsc) Len() int           { return len(o) }
func (o itemsByPrefixAsc) Swap(i, j int)      { o[i], o[j] = o[j], o[i] }
func (o itemsByPrefixAsc) Less(i, j int) bool { return o[i].prefix < o[j].prefix }

// fillCompressed fills the compressed property in the range [l, r] with x value
func (o items) fillCompressed(l, r int, x int) {
	for ; l <= r; l++ {
		o[l].compressed = x
	}
}

func (o items) showXs(s string) {
	fmt.Print(s, ":")
	for i, l := 0, len(o); i < l; i++ {
		fmt.Printf(" %2d", o[i].x)
	}
	fmt.Println()
}

func (o items) showPrefixes(s string) {
	fmt.Print(s, ":")
	for i, l := 0, len(o); i < l; i++ {
		fmt.Printf(" %2d", o[i].prefix)
	}
	fmt.Println()
}

// Solution2 uses arrays and compressed strategy of prefixes
// to solve the problem in O(NlogN) time without mappings
//
func Solution2() {
	var n int
	fmt.Scanf("%v\n", &n)
	arr := make([]item, n+1)

	for i := 1; i <= n; i++ {
		arr[i].pos = i
		fmt.Scanf("%v", &arr[i].x)
		arr[i].prefix = arr[i-1].prefix + arr[i].x
	}

	// items(arr).showXs("__x")

	// items(arr).showPrefixes("pre")
	sort.Sort(itemsByPrefixAsc(arr))
	// items(arr).showPrefixes("ord")

	// compress prefixes from [0, ..., sz)
	var sz int = 0
	var rangeStart int = 0

	for i := 1; i <= n; i++ {
		if arr[i].prefix != arr[i-1].prefix {
			items(arr).fillCompressed(rangeStart, i-1, sz)
			sz++
			rangeStart = i
		}
	}

	items(arr).fillCompressed(rangeStart, n, sz)
	sz++

	// sort pre by pos
	sort.Sort(itemsByPosAsc(arr))
	// items(arr).showPrefixes("__f")

	// make a seen_value arr of sz length
	seen := make([]int, sz)
	for i := 0; i < sz; i++ {
		seen[i] = -1
	}

	var ans int = 0
	var barrierAt = 1

	// in order for each compressed pre value: set as seen
	// then, if already seen: ans++

	for i := 1; i <= n; i++ {
		var _prefix int = arr[i].compressed

		if seen[_prefix] == barrierAt || arr[barrierAt-1].prefix == arr[i].prefix {
			ans++
			barrierAt = i
			// fmt.Println("Put a barrier before", i)
		}
		seen[_prefix] = barrierAt
	}

	fmt.Printf("%v\n", ans)
}

func main() {
	Solution1()
}

package main

// Problem Title: Non-zero Segments

import (
	"fmt"
	"sort"
)

// Solution1 uses mapping approach
// got TLE of 2seconds in 22nd test case
//
// tutorial: https://codeforces.com/blog/entry/83120
//
func Solution1() {
	var n, ans int
	fmt.Scanf("%v\n", &n)

	var x, sum int64
	pre := map[int64]int{0: 1}

	for i := 0; i < n; i++ {
		fmt.Scanf("%v", &x)

		sum += x

		_, has := pre[sum]
		if has {
			ans++
			sum = x
			pre = map[int64]int{0: 1}
		}

		pre[sum]++
	}

	// fmt.Println(pre)

	fmt.Println(ans)
}

// below code credits
// https://codeforces.com/contest/1426/submission/94096753

type item struct {
	pos        int
	x          int64
	prefix     int64
	compressed int
}
type items []item

type itemsByPosAsc items

func (o itemsByPosAsc) Len() int           { return len(o) }
func (o itemsByPosAsc) Swap(i, j int)      { o[i], o[j] = o[j], o[i] }
func (o itemsByPosAsc) Less(i, j int) bool { return o[i].pos < o[j].pos }

type itemsByPrefixAsc items

func (o itemsByPrefixAsc) Len() int           { return len(o) }
func (o itemsByPrefixAsc) Swap(i, j int)      { o[i], o[j] = o[j], o[i] }
func (o itemsByPrefixAsc) Less(i, j int) bool { return o[i].prefix < o[j].prefix }

// fillCompressed fills the compressed property in the range [l, r] with x value
func (o items) fillCompressed(l, r int, x int) {
	for ; l <= r; l++ {
		o[l].compressed = x
	}
}

func (o items) showXs(s string) {
	fmt.Print(s, ":")
	for i, l := 0, len(o); i < l; i++ {
		fmt.Printf(" %2d", o[i].x)
	}
	fmt.Println()
}

func (o items) showPrefixes(s string) {
	fmt.Print(s, ":")
	for i, l := 0, len(o); i < l; i++ {
		fmt.Printf(" %2d", o[i].prefix)
	}
	fmt.Println()
}

// Solution2 uses arrays and compressed strategy of prefixes
// to solve the problem in O(NlogN) time without mappings
//
func Solution2() {
	var n int
	fmt.Scanf("%v", &n)
	arr := make([]item, n+1)

	for i := 1; i <= n; i++ {
		arr[i].pos = i
		fmt.Scanf("%v", &arr[i].x)
		arr[i].prefix = arr[i-1].prefix + arr[i].x
	}

	// items(arr).showXs("__x")

	// items(arr).showPrefixes("pre")
	sort.Sort(itemsByPrefixAsc(arr))
	// items(arr).showPrefixes("ord")

	// compress prefixes from [0, ..., sz)
	var sz int = 0
	var rangeStart int = 0

	for i := 1; i <= n; i++ {
		if arr[i].prefix != arr[i-1].prefix {
			items(arr).fillCompressed(rangeStart, i-1, sz)
			sz++
			rangeStart = i
		}
	}

	items(arr).fillCompressed(rangeStart, n, sz)
	sz++

	// sort pre by pos
	sort.Sort(itemsByPosAsc(arr))
	// items(arr).showPrefixes("__f")

	// make a seen_value arr of sz length
	seen := make([]int, sz)
	for i := 0; i < sz; i++ {
		seen[i] = -1
	}

	var ans int = 0

	// in order for each compressed pre value: set as seen
	// then, if already seen: ans++

	for i := 1; i <= n; i++ {
		var idx int = arr[i].compressed

		if seen[idx] == ans || arr[ans].prefix == arr[i].prefix {
			ans++
			// fmt.Println("Put a barrier before", i)
		}
		seen[idx] = ans
	}

	fmt.Printf("%v\n", ans)
}

func main() {
	Solution2()
}


You are given two strings $$$s$$$ and $$$t$$$, both consisting only of lowercase Latin letters.The substring $$$s[l..r]$$$ is the string which is obtained by taking characters $$$s_l, s_{l + 1}, \dots, s_r$$$ without changing the order.Each of the occurrences of string $$$a$$$ in a string $$$b$$$ is a position $$$i$$$ ($$$1 \le i \le |b| - |a| + 1$$$) such that $$$b[i..i + |a| - 1] = a$$$ ($$$|a|$$$ is the length of string $$$a$$$).You are asked $$$q$$$ queries: for the $$$i$$$-th query you are required to calculate the number of occurrences of string $$$t$$$ in a substring $$$s[l_i..r_i]$$$.

The first line contains three integer numbers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 10^3$$$, $$$1 \le q \le 10^5$$$) — the length of string $$$s$$$, the length of string $$$t$$$ and the number of queries, respectively. The second line is a string $$$s$$$ ($$$|s| = n$$$), consisting only of lowercase Latin letters. The third line is a string $$$t$$$ ($$$|t| = m$$$), consisting only of lowercase Latin letters. Each of the next $$$q$$$ lines contains two integer numbers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — the arguments for the $$$i$$$-th query.

Print $$$q$$$ lines — the $$$i$$$-th line should contain the answer to the $$$i$$$-th query, that is the number of occurrences of string $$$t$$$ in a substring $$$s[l_i..r_i]$$$.

NoteIn the first example the queries are substrings: "cod", "deforces", "fo" and "for", respectively.

package main

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

func main() {

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

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

	var s, t string
	fmt.Fscanf(in, "%s\n%s\n", &s, &t)

	for i := 0; i < q; i++ {

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

		cnt := 0

		for j := 0; j < (r - l) + 1 - len(t) + 1; j++ {
			if s[l+j-1:l+j+len(t)-1] == t {
				cnt++
			}
		}

		fmt.Fprintln(out, cnt)

	}

}

package main

import "bufio"
import "fmt"
import "os"
import "strconv"
import "strings"

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	var q int
	scanner.Scan()
	line := scanner.Text()
	elems := strings.Split(line, " ")
	_, _ = strconv.Atoi(elems[0])
	_, _ = strconv.Atoi(elems[1])
	q, _ = strconv.Atoi(elems[2])
	//fmt.Scan(&n, &m, &q)
	var s, t string
	scanner.Scan()
	s = scanner.Text()
	//fmt.Scan(&s)
	scanner.Scan()
	t = scanner.Text()
	//fmt.Scan(&t)
	lt := len(t)
	ls := len(s)
	dp := make([]int, ls)
	for i := 0; i <= ls - lt; i++ {
		ok := true
		for j := 0; j < lt; j++ {
			if s[i+j] != t[j] {
				ok = false
				break
			}
		}
		if i > 0 {
			dp[i] = dp[i-1]
		}
		if ok {
			dp[i]++
		}
	}

	for i := 1; i <= q; i++ {
		var l, r int
		//fmt.Scan(&l, &r)
		//fmt.Println("here")
		scanner.Scan()
		line := scanner.Text()
		//fmt.Println(line)
		elems := strings.Split(line, " ")
		l, _ = strconv.Atoi(elems[0])
		r, _ = strconv.Atoi(elems[1])
		l--
		r--
		var ans int
		if (r-lt+1) < l {
			ans = 0
		} else {
			var lside int
			if l > 0 {
				lside = dp[l-1]
			} else {
				lside = 0
			}
			ans = dp[r-lt+1] - lside
		}
		fmt.Println(ans)
	}
}

package main

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

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

	var l1, l2, q,l,r int
	var s1, s2 string
	Fscan(in, &l1, &l2, &q, &s1, &s2)

	sum:=make([]int, l1+1)
	for i := 0; i +l2<=l1 ; i++ {
		if s1[i:i+l2] == s2 {
			sum[i+1] = sum[i] +1
		} else {
			sum[i+1] = sum[i]
		}
	}

	for q > 0{
		q--
		Fscan(in, &l,&r)
		r++
		if l+l2<=r {
			Fprintln(out, sum[r-l2]-sum[l-1])
		} else {
			Fprintln(out, 0)
		}
	}

}

package main

import "fmt"

func main() {
	var n, m, q int
	fmt.Scanf("%d%d%d", &n, &m, &q)
	var s, t string
	fmt.Scanf("%s", &s)
	fmt.Scanf("%s", &t)
	//fmt.Println(s, t)
	lt := len(t)
	ls := len(s)
	dp := make([]int, ls)
	for i := 0; i <= ls - lt; i++ {
		ok := true
		for j := 0; j < lt; j++ {
			if s[i+j] != t[j] {
				ok = false
				break
			}
		}
		if i > 0 {
			dp[i] = dp[i-1]
		}
		if ok {
			dp[i]++
		}
		//fmt.Println(dp[i])
	}

	for i := 1; i <= q; i++ {
		var l, r int
		fmt.Scanf("%d%d", &l, &r)
		//fmt.Println(l, r)
		l--
		r--
		var ans int
		if (r-lt+1) < l {
			ans = 0
		} else {
			var lside int
			if l > 0 {
				lside = dp[l-1]
			} else {
				lside = 0
			}
			ans = dp[r-lt+1] - lside
		}
		fmt.Println(ans)
	}
}


Tanya is learning how to add numbers, but so far she is not doing it correctly. She is adding two numbers $$$a$$$ and $$$b$$$ using the following algorithm:  If one of the numbers is shorter than the other, Tanya adds leading zeros so that the numbers are the same length.  The numbers are processed from right to left (that is, from the least significant digits to the most significant).  In the first step, she adds the last digit of $$$a$$$ to the last digit of $$$b$$$ and writes their sum in the answer.  At each next step, she performs the same operation on each pair of digits in the same place and writes the result to the left side of the answer.  For example, the numbers $$$a = 17236$$$ and $$$b = 3465$$$ Tanya adds up as follows:$$$$$$ \large{ \begin{array}{r} + \begin{array}{r} 17236\\ 03465\\ \end{array} \\ \hline \begin{array}{r} 1106911 \end{array} \end{array}} $$$$$$  calculates the sum of $$$6 + 5 = 11$$$ and writes $$$11$$$ in the answer.  calculates the sum of $$$3 + 6 = 9$$$ and writes the result to the left side of the answer to get $$$911$$$.  calculates the sum of $$$2 + 4 = 6$$$ and writes the result to the left side of the answer to get $$$6911$$$.  calculates the sum of $$$7 + 3 = 10$$$, and writes the result to the left side of the answer to get $$$106911$$$.  calculates the sum of $$$1 + 0 = 1$$$ and writes the result to the left side of the answer and get $$$1106911$$$. As a result, she gets $$$1106911$$$.You are given two positive integers $$$a$$$ and $$$s$$$. Find the number $$$b$$$ such that by adding $$$a$$$ and $$$b$$$ as described above, Tanya will get $$$s$$$. Or determine that no suitable $$$b$$$ exists.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of a single line containing two positive integers $$$a$$$ and $$$s$$$ ($$$1 \le a \lt s \le 10^{18}$$$) separated by a space.

For each test case print the answer on a separate line. If the solution exists, print a single positive integer $$$b$$$. The answer must be written without leading zeros. If multiple answers exist, print any of them. If no suitable number $$$b$$$ exists, output -1.

NoteThe first test case is explained in the main part of the statement.In the third test case, we cannot choose $$$b$$$ that satisfies the problem statement.

package main

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

func main() {
	reader := bReader(os.Stdin)
	writer := bWriter(os.Stdout)

	t := readInt(reader)

	for t > 0 {
		ss := readArrayString(reader)
		a, s := ss[0], ss[1]

		n, m := len(a)-1, len(s)-1

		ok := true
		b := ""
		for n >= 0 || m >= 0 {
			if m < 0 {
				ok = false
				break
			}

			x, y := 0, int(s[m]-'0')
			if n >= 0 {
				x = int(a[n] - '0')

				n--
			}

			if y < x {
				if m == 0 {
					ok = false
					break
				}

				y = int(s[m-1]-'0')*10 + y

				m -= 2
			} else {
				m--
			}

			if y-x > 9 || y-x < 0 {
				ok = false
				break
			}

			b = strconv.Itoa(y-x) + b
		}

		if !ok {
			fmt.Fprintln(writer, -1)
		} else {
			fmt.Fprintln(writer, strings.TrimLeft(b, "0"))
		}

		t--
	}

	writer.Flush()
}

func bReader(stdin *os.File) *bufio.Reader {
	return bufio.NewReaderSize(stdin, 16*1024*1024)
}

func bWriter(stdout *os.File) *bufio.Writer {
	return bufio.NewWriterSize(stdout, 16*1024*1024)
}

func readLine(reader *bufio.Reader) string {
	str, _, err := reader.ReadLine()
	if err == io.EOF {
		return ""
	}

	return strings.TrimRight(string(str), "\r\n")
}

func checkError(err error) {
	if err != nil {
		panic(err)
	}
}

func readInt(reader *bufio.Reader) int {
	return int(readInt64(reader))
}

func readInt64(reader *bufio.Reader) int64 {
	value, err := strconv.ParseInt(readLine(reader), 10, 64)
	checkError(err)

	return value
}

func readString(reader *bufio.Reader) string {
	return readLine(reader)
}

func readArrayString(reader *bufio.Reader) []string {
	return strings.Split(strings.TrimSpace(readLine(reader)), " ")
}

func readArrayInt(reader *bufio.Reader) []int {
	arTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
	n := len(arTemp)

	var ar []int

	for i := 0; i < n; i++ {
		arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 64)
		checkError(err)
		arItem := int(arItemTemp)
		ar = append(ar, arItem)
	}

	return ar
}

func readArrayInt64(reader *bufio.Reader) []int64 {
	arTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
	n := len(arTemp)

	var ar []int64

	for i := 0; i < n; i++ {
		arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 64)
		checkError(err)
		arItem := arItemTemp
		ar = append(ar, arItem)
	}

	return ar
}

func readTwoInt(reader *bufio.Reader) (int, int) {
	ar := readArrayInt(reader)
	return ar[0], ar[1]
}

func readTwoInt64(reader *bufio.Reader) (int64, int64) {
	ar := readArrayInt64(reader)
	return ar[0], ar[1]
}

func readThreeInt(reader *bufio.Reader) (int, int, int) {
	ar := readArrayInt(reader)
	return ar[0], ar[1], ar[2]
}

func readThreeInt64(reader *bufio.Reader) (int64, int64, int64) {
	ar := readArrayInt64(reader)
	return ar[0], ar[1], ar[2]
}

func gcd(x int64, y int64) int64 {
	for y > 0 {
		x, y = y, x%y
	}

	return x
}

func lcm(x int64, y int64) int64 {
	return x * y / gcd(x, y)
}

package main

import (
	"fmt"
	"strconv"
	"strings"
)

func main() {
	var t int
	fmt.Scan(&t)
	for test := 0; test < t; test++ {
		var a, s string
		var ans strings.Builder
		fmt.Scan(&a, &s)
		var ptr = len(s) - 1
		var g = false
		ans.Grow(len(s))
		for i := len(a) - 1; i >= 0 || ptr != -1; i-- {
			var found = false
			for j := 0; j < 10; j++ {
				var cur = 0
				if i >= 0 {
					cur = int(a[i] - '0')
				}
				var temp = strconv.Itoa(cur + j)
				if ptr-len(temp)+1 >= 0 && temp == s[ptr-len(temp)+1:ptr+1] {
					ans.WriteString(strconv.Itoa(j))
					found = true
					ptr -= len(temp)
					break
				}
			}
			if !found {
				g = true
				break
			}
		}
		if g || ptr != -1 {
			fmt.Println("-1")
		} else {
			var was = false
			var str = ans.String()
			for i := len(str) - 1; i > -1; i-- {
				if !was && i != 0 && str[i] == '0' {
					continue
				}
				fmt.Print(string(str[i]))
				was = true
			}
			fmt.Println()
		}
	}
}

package main

import (
	"fmt"
	"strconv"
	"strings"
)

func main() {
	var t int
	fmt.Scan(&t)
	for test := 0; test < t; test++ {
		var a, s string
		var ans strings.Builder
		fmt.Scan(&a, &s)
		var ptr = len(s) - 1
		var g = false
		for i := len(a) - 1; i >= 0 || ptr != -1; i-- {
			var found = false
			for j := 0; j < 10; j++ {
				var cur = 0
				if i >= 0 {
					cur = int(a[i] - '0')
				}
				var temp = strconv.Itoa(cur + j)
				if ptr-len(temp)+1 >= 0 && temp == s[ptr-len(temp)+1:ptr+1] {
					ans.WriteString(strconv.Itoa(j))
					found = true
					ptr -= len(temp)
					break
				}
			}
			if !found {
				g = true
				break
			}
		}
		if g || ptr != -1 {
			fmt.Println("-1")
		} else {
			var was = false
			var str = ans.String()
			for i := len(str) - 1; i > -1; i-- {
				if !was && i != 0 && str[i] == '0' {
					continue
				}
				fmt.Print(string(str[i]))
				was = true
			}
			fmt.Println()
		}
	}
}

package main

import (
	"fmt"
	"strconv"
	"strings"
)

func main() {
	var t int
	fmt.Scan(&t)
	for test := 0; test < t; test++ {
		var a, s string
		var ans strings.Builder
		fmt.Scan(&a, &s)
		var ptr = len(s) - 1
		var g = false
		for i := len(a) - 1; i >= 0 || ptr != -1; i-- {
			var found = false
			for j := 0; j < 10; j++ {
				var cur = 0
				if i >= 0 {
					cur = int(a[i] - '0')
				}
				var temp = strconv.Itoa(cur + j)
				if ptr-len(temp)+1 >= 0 && temp == s[ptr-len(temp)+1:ptr+1] {
					fmt.Fprint(&ans, strconv.Itoa(j))
					found = true
					ptr -= len(temp)
					break
				}
			}
			if !found {
				g = true
				break
			}
		}
		if g || ptr != -1 {
			fmt.Println("-1")
		} else {
			var was = false
			var str = ans.String()
			for i := len(str) - 1; i > -1; i-- {
				if !was && i != 0 && str[i] == '0' {
					continue
				}
				fmt.Print(string(str[i]))
				was = true
			}
			fmt.Println()
		}
	}
}

package main

import (
	"fmt"
	"strconv"
)

func main() {
	var t int
	fmt.Scan(&t)
	for test := 0; test < t; test++ {
		var a, s, ans string
		fmt.Scan(&a, &s)
		var ptr = len(s) - 1
		var g = false
		for i := len(a) - 1; i >= 0 || ptr != -1; i-- {
			var found = false
			for j := 0; j < 10; j++ {
				var cur = 0
				if i >= 0 {
					cur = int(a[i] - '0')
				}
				var temp = strconv.Itoa(cur + j)
				if ptr-len(temp)+1 >= 0 && temp == s[ptr-len(temp)+1:ptr+1] {
					ans += strconv.Itoa(j)
					found = true
					ptr -= len(temp)
					break
				}
			}
			if !found {
				g = true
				break
			}
		}
		if g || ptr != -1 {
			fmt.Println("-1")
		} else {
			var was = false
			for i := len(ans) - 1; i > -1; i-- {
				if !was && i != 0 && ans[i] == '0' {
					continue
				}
				fmt.Print(string(ans[i]))
				was = true
			}
			fmt.Println()
		}
	}
}

package main

import (
	"fmt"
)

func get_b(a, s int64) int64 {
	var b int64
	var pow int64 = 1

	for arem, srem := a, s; ; {
		if a == 0 && s == 0 {
			break
		} else if a == 0 {
			srem = s % 10
			s /= 10
			b += pow * srem
			pow *= 10
			continue
		} else if s == 0 {
			return -1
		}

		arem = a % 10
		a /= 10
		srem = s % 10
		s /= 10
		if srem >= arem {
			b += pow * (srem - arem)
		} else if srem < arem {
			if s == 0 || (s%10) != 1 {
				return -1
			} else {
				b += pow * (10 + srem - arem)
				s /= 10
			}
		}
		pow *= 10
	}
	return b
}

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

	for i := 0; i < t; i++ {
		var a, s int64
		fmt.Scanf("%d %d\n", &a, &s)
		fmt.Printf("%d\n", get_b(a, s))
	}
}

package main

import (
	"fmt"
)

func get_b(a, s string) int64 {
	var b int64
	var pow int64 = 1

	i, j := len(a)-1, len(s)-1
	for {
		if i < 0 && j < 0 {
			break
		} else if i < 0 {
			b += pow * int64(s[j]-'0')
			j--
			pow *= 10
			continue
		} else if j < 0 {
			return -1
		}

		if s[j] >= a[i] {
			b += pow * int64(s[j]-a[i])
			i--
			j--
		} else if s[j] < a[i] {
			if j == 0 || s[j-1] != '1' {
				return -1
			} else {
				b += pow * int64(10+s[j]-a[i])
				i--
				j -= 2
			}
		}
		pow *= 10
	}
	return b
}

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

	for i := 0; i < t; i++ {
		var a, s string
		fmt.Scanf("%s %s\n", &a, &s)
		fmt.Printf("%d\n", get_b(a, s))
	}
}

package main

import (
	"fmt"
)

func get_b(a, s string) int64 {
	var b int64
	var pow int64 = 1

	i, j := len(a)-1, len(s)-1
	for {
		if i < 0 && j < 0 {
			break
		} else if i < 0 {
			b += pow * int64(s[j]-'0')
			j--
			pow *= 10
			continue
		} else if j < 0 {
			return -1
		}

		if s[j] >= a[i] {
			b += pow * int64(s[j]-a[i])
			i--
			j--
		} else if s[j] < a[i] {
			if j == 0 || s[j-1] != '1' {
				return -1
			} else {
				b += pow * int64(10+s[j]-a[i])
				i--
				j -= 2
			}
		}
		pow *= 10
	}
	return b
}

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

	for i := 0; i < t; i++ {
		var a, s string
		fmt.Scanf("%s %s\n", &a, &s)
		fmt.Println(get_b(a, s))
	}
}

package main

import (
	"fmt"
	"strconv"
)

func main() {
	var (
		t    int
		a, s int64
	)
	fmt.Scanln(&t)
	for i := 0; i < t; i++ {
		fmt.Scanln(&a, &s)
		fmt.Println(wrongAddition(a, s))
	}
}

func wrongAddition(a, s int64) int64 {
	final := ""
	for s > 0 {
		if a > s {
			return -1
		} else if s%10-a%10 >= 0 {
			temp := strconv.FormatInt(s%10-a%10, 10)
			final = temp + final
			s = s / 10
			a = a / 10
		} else if s%100-a%10 > 0 && s%100 < 19 {
			temp := strconv.FormatInt(s%100-a%10, 10)
			final = temp + final
			s = s / 100
			a = a / 10
		} else if a > 0 {
			temp := strconv.FormatInt(s%10-a%10, 10)
			final = temp + final
			s = 0
			a = 0
		} else {
			return -1
		}
	}
	intFinal, _ := strconv.ParseInt(final, 10, 64)
	if intFinal > 0 {
		return intFinal
	} else {
		return -1
	}
}

package main

import(
    "fmt"
    "math"
)

func main(){
    var x,a,s int64
    fmt.Scan(&x)

    for d := int64(0); d < x ; d++{
      fmt.Scan(&a,&s)
      solution :=int64(0)
      copyS := s
      for n := int64(0);a > 0 || s > 0; {

          if a%10 > s%10{
            if l := s/10; l%10 != 1{
              solution = -1
              break
            }
            temp := s%10 + 10
            solution += (temp-a%10)*int64(math.Pow(float64(10),float64(n)))
            a /= 10
            s /= 100
            n += 1
          }else{
            solution += (s%10-a%10)*int64(math.Pow(float64(10),float64(n)))
            a /= 10
            s /= 10
            n += 1
          }
      }
      if  solution > copyS {solution = -1;}
      fmt.Println(solution)

    }
}

package main

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

/*
* lets try some fancy go :)

foreach digt in a find the digit of b so
that the sum matches the current digit in s or the next two
digits in s.
*/
func main() {
    re, w, e := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout), bufio.NewWriter(os.Stderr)
    defer w.Flush()
    defer e.Flush()

    var t int=0
    Fscan(re, &t)

    for i:=0; i<t; i++ {
        var a,s int64
        Fscan(re, &a, &s)

        if a==s {
            Fprintf(w, "0\n")
            continue
        }

        ok:=true
        ans:= []int64{}
        for ; a>0 || s>0; {
            d:=a%10
            a/=10
            ds:=s%10;
            s/=10
            if ds>=d {
                ans=append(ans, ds-d)
            } else {
                ds+=(s%10)*10
                s/=10
                if ds<d || ds>d+9 {
                    ok=false
                } else {
                    ans=append(ans,ds-d);
                }
            }
        }

        if !ok {
            Fprintf(w, "%d\n", -1)
        } else {
            /* remove leading zeros, sic. How is supposed syntax???  */
            for ; len(ans)>0 && ans[len(ans)-1]==0 ; {
                ans=ans[:len(ans)-1]
            }

            for i:=len(ans)-1; i>=0 ; i-- {
                Fprintf(w, "%d", ans[i])
            }
            Fprintf(w, "\n")
        }
    }
}

// 00
package main

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

func write(f *bufio.Writer, a ...interface{}) {
	f.Write([]byte(fmt.Sprint(a...)))
}

type Number interface {
	int64 | float64 | int
}

func min[K Number](a K, b K) K {
	if a < b {
		return a
	}
	return b
}
func max[K Number](a K, b K) K {
	if a > b {
		return a
	}
	return b
}
func main() {
	var T int
	reader := bufio.NewReader(os.Stdin)
	f := bufio.NewWriter(os.Stdout)
	defer f.Flush()
	fmt.Fscan(reader, &T)
	for t := 1; t <= T; t++ {
		var a, s string
		fmt.Fscan(reader, &a, &s)
		n := len(a)
		if len(s) < n {
			write(f, "-1\n")
			continue
		}
		ok := true
		ans := make([]rune, len(s))
		for i := 0; i < len(s); i++ {
			ans[i] = '0'
		}
		j := len(s) - 1
		p := len(s) - 1
		i := n - 1
		for ; ; i-- {

			ad := 0
			if i >= 0 {
				ad = int(a[i] - '0')
			}
			if j < 0 {
				break
			}
			sd := int(s[j] - '0')
			found := false
			for k := 0; k < 10; k++ {
				if ad+k == sd {
					ans[p] = rune(48 + k)
					found = true
					j--
					p--
					break
				}
			}
			if found {
				continue
			}
			if j-1 < 0 {
				ok = false
				break
			}
			sd, _ = strconv.Atoi(s[j-1 : j+1])
			for k := 0; k < 10; k++ {
				if ad+k == sd {
					ans[p] = rune(48 + k)
					found = true
					j -= 2
					p--
					break
				}
			}
			if !found {
				ok = false
				break
			}
		}
		//write(f, ans, string(ans), j, "\n")
		if ok {
			bi, _ := strconv.ParseInt(string(ans), 10, 64)
			if i >= 0 {
				write(f, "-1\n")
			} else {
				write(f, bi, "\n")
			}
		} else {
			write(f, "-1\n")
		}

	}
}

package main

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

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

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

		var ans int64
		pos := len(s) - 1
		for i := len(a) - 1; i >= 0 || pos >= 0; i-- {
			var d1, d2 int64
			if i >= 0 {
				d1 = int64(a[i] - '0')
			}

			if pos < 0 {
				ans = -1
				break
			}

			d2 = int64(s[pos] - '0')
			if d1 > d2 {
				if pos-1 < 0 || s[pos-1] != '1' {
					ans = -1
					break
				}
				ans += (10 + d2 - d1) * int64(math.Pow10(len(a)-i-1))
				pos--
			} else if d1 < d2 {
				ans += (d2 - d1) * int64(math.Pow10(len(a)-i-1))
			}
			pos--
		}
		fmt.Fprintln(out, ans)
	}
}

package main

import (
	"fmt"
)

func main() {

	var t int

	fmt.Scan(&t)

	for t > 0 {
		var a, s string
		fmt.Scan(&a, &s)
		// fmt.Printf("a=%s, s=%s \n", a, s)

		n, m := len(a)-1, len(s)-1
		i, j := n, m
		var ans string

		for i >= 0 && j >= 0 {
			if a[i] <= s[j] {
				ans = string(byte(int('0')+int(s[j])-int(a[i]))) + ans
				i--
				j--
			} else {
				del := 10 + int(s[j]) - int(a[i])
				ans = string(byte(int('0')+del)) + ans
				i--
				j--
				if j == -1 || s[j] != '1' {
					ans = "-1"
					break
				}
				j--
			}
		}

		if i != -1 || ans == "-1" {
			ans = "-1"
		} else {
			for j >= 0 {
				ans = string(s[j]) + ans
				j--
			}
		}

		flag := false

		// fmt.Printf("ans= %s\n", ans)

		for i := 0; i < len(ans); i++ {
			if ans[i] != '0' {
				flag = true
				fmt.Printf("%c", ans[i])
			} else {
				if flag == true {
					fmt.Printf("%c", ans[i])
				}
			}

		}

		fmt.Println()

		t--
	}

}

package main

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

func solve(in *bufio.Reader, out *bufio.Writer) {
	defer out.Flush()
	s1 := ""
	s2 := ""
	Fscan(in, &s1, &s2)
	s1L := len(s1) - 1
	s2L := len(s2) - 1
	ans := ""
	for s1L >= 0 {
		if s2L < 0 {
			ans = "-1"
			s2L = -1
			break
		}
		if s1[s1L] <= s2[s2L] {
			ans = strconv.FormatInt(int64(s2[s2L]-s1[s1L]), 10) + ans
			s1L--
			s2L--
		} else {
			if s2L <= 0 || s2[s2L-1] != '1' {
				ans = "-1"
				s2L = -1
				break
			}
			val := 10 + (s2[s2L] - '0') - (s1[s1L] - '0')
			ans = strconv.FormatInt(int64(val), 10) + ans
			s2L -= 2
			s1L--
		}
	}
	if s2L >= 0 {
		ans = s2[0:s2L+1] + ans
	}
	parseInt, _ := strconv.ParseInt(ans, 10, 64)
	Println(parseInt)
}

func main() {
	stdin := os.Stdin
	stdout := os.Stdout
	in := bufio.NewReader(stdin)
	out := bufio.NewWriter(stdout)
	n := 0
	Fscan(in, &n)
	for i := 0; i < n; i++ {
		solve(in, out)
	}
}

package main

import (
	"fmt"
	"strconv"
)

func main() {

	var t int
	fmt.Scanln(&t)

	for i := 0; i < t; i++ {

		var a int64
		var b int64
		fmt.Scanln(&a, &b)

		var a1 []int64
		var b1 []int64

		for j := 0; j < 1; j-- {

			a2 := a % 10
			b2 := b % 10

			a /= 10
			b /= 10

			if a2 > b2 {
				b2 = ((b % 10) * 10) + b2
				b /= 10
			}

			a1 = append(a1, a2)
			b1 = append(b1, b2)

			if a == 0 || b == 0 {
				break
			}
		}

		if a != 0 {
			fmt.Println(-1)
			continue
		}

		if b != 0 {
			for j := 0; j < 1; j-- {
				b2 := b % 10
				b /= 10

				a1 = append(a1, 0)
				b1 = append(b1, b2)

				if b == 0 {
					break
				}
			}
		}

		var a2 int64
		var b2 int64
		a2 = 0
		b2 = 0
		ans := ""
		for j := 0; j < len(a1); j++ {
			a2 = a1[j]
			b2 = b1[j]

			if a2 > b2 {
				break
			}
			var c2 int64
			c2 = b2 - a2
			if c2 >= 10 {
				break
			}
			ans = strconv.FormatInt(c2, 10) + ans
		}
		if a2 > b2 {
			fmt.Println(-1)
			continue
		}

		if (b2 - a2) >= 10 {
			fmt.Println(-1)
			continue
		}

		// fmt.Println(a1)
		// fmt.Println(b1)
		for j := 0; j < 1; j-- {
			if ans[0] != '0' {
				break
			}
			ans = ans[1:]
		}
		fmt.Println(ans)

	}
}

package main

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

var (
	rr = bufio.NewReader(os.Stdin)
	ww = bufio.NewWriter(os.Stdout)
)

var (
	T    int
	a, s string
)

func num(xs ...byte) int {
	res := 0
	for _, x := range xs {
		res = res*10 + int(x-'0')
	}
	return res
}

func sub(s, a string) int64 {
	b := ""
	si := len(s) - 1
	for ai := len(a) - 1; ai >= 0; ai-- {
		if si < 0 {
			return -1
		}
		bnum := num(s[si]) - num(a[ai])
		if bnum < 0 {
			if si == 0 {
				return -1
			}
			bnum = num(s[si-1], s[si]) - num(a[ai])
			if bnum < 0 || bnum >= 10 {
				return -1
			}
			si--
		}
		b = strconv.Itoa(bnum) + b
		si--
	}
	if si >= 0 {
		b = s[:si+1] + b
	}
	ans, _ := strconv.ParseInt(b, 10, 64)
	return ans
}

func Init() {
}

func main() {
	_, _ = fmt.Fscan(rr, &T)
	for iCase := 0; iCase < T; iCase++ {
		_, _ = fmt.Fscan(rr, &a, &s)

		_, _ = fmt.Fprintln(ww, sub(s, a))
	}
	_ = ww.Flush()
}

package main

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

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

func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }

//func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }

func Reverse(s string) string {
	sLen := len(s)
	str := make([]rune, 0)
	for i := sLen - 1; i >= 0; i-- {
		str = append(str, rune(s[i]))
	}
	return string(str)
}

func RemoveLeadingZeros(s string) string {
	sLen := len(s)
	str := make([]rune, 0)
	leading := true
	for i := 0; i < sLen; i++ {
		ch := rune(s[i])
		if ch == '0' {
			if !leading {
				str = append(str, ch)
			}
		} else {
			str = append(str, ch)
			leading = false
		}
	}
	return string(str)
}

func FSolve(a string, s string) string {
	var b []string
	aLen := len(a)
	sLen := len(s)
	sIndex := 0
	for i := 0; i < aLen; i++ {
		var num int
		ad := int(a[aLen-1-i] - '0')

		index := sLen - 1 - sIndex
		if index < 0 {
			return "-1"
		}
		d1 := int(s[index] - '0')
		num += d1
		sIndex++

		if num-ad < 0 {
			index = sLen - 1 - sIndex
			if index < 0 {
				return "-1"
			}
			d2 := int(s[index] - '0')
			sIndex++
			num += d2 * 10
		}

		x := num - ad
		if x < 0 || x >= 10 {
			return "-1"
		}

		b = append(b, strconv.Itoa(x))
	}

	if sIndex == sLen {
		str := strings.Join(b, "")
		str = Reverse(str)
		str = RemoveLeadingZeros(str)
		return str
	} else if sIndex < sLen {
		str := strings.Join(b, "")
		strN := Reverse(str)
		for i := sLen - 1 - sIndex; i >= 0; i-- {
			strN = string(s[i]) + strN
		}
		return strN
	} else {
		return "-1"
	}

}

func Solve(lines []string) {
	t, _ := strconv.Atoi(lines[0])
	for i := 1; i <= t; i++ {
		sp := strings.Split(lines[i], " ")
		a := sp[0]
		s := sp[1]
		printf("%v\n", FSolve(a, s))
	}
}

func main() {
	defer writer.Flush()

	var lines []string
	if len(os.Args) == 2 {
		b, err := os.ReadFile(os.Args[1])
		if err != nil {
			panic(err)
		}
		s := string(b)
		sp := strings.Split(s, "\r\n")
		lines = append(lines, sp...)
	} else {
		scanner := bufio.NewScanner(os.Stdin)
		for scanner.Scan() {
			line := scanner.Text()
			lines = append(lines, line)
		}
	}

	Solve(lines)
}

package main

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

/*
5
1 3
7 5
3215 5756
541 231082
241 84910
---
2
-1
2541
23541
8259
======
1
714 51118
---
5404
=====
1

sd 12
ad  4
bd  8

*/

//goland:noinspection GoUnhandledErrorResult
func solve() {
	var a, s string
	scanf("%s %s\n", &a, &s)

	if len(s) < len(a) {
		fmt.Fprintln(writer, -1)
		return
	}

	aOrigLen := len(a)

	a = reversed(a)
	bldA := strings.Builder{}
	bldA.WriteString(a)

	for i := 0; i < len(s)-len(a); i++ {
		bldA.WriteByte('0')
	}

	a = bldA.String()
	s = reversed(s)

	possible := true
	bld := strings.Builder{}

	i, j := 0, 0
	for ; i < len(s); i, j = i+1, j+1 {
		sd, _ := strconv.Atoi(string(s[i]))

		if j >= len(a) {
			possible = false
			break
		}

		ad, _ := strconv.Atoi(string(a[j]))

		if ad <= sd {
			bd := sd - ad
			fmt.Fprintf(&bld, "%d", bd)
		} else {
			if i+1 < len(s) {
				s1d, _ := strconv.Atoi(string(s[i+1]))
				if s1d == 1 {
					bd := 10 + sd - ad
					fmt.Fprintf(&bld, "%d", bd)
					i++
				} else {
					possible = false
					break
				}
			} else {
				possible = false
				break
			}
		}
	}

	if j < aOrigLen {
		possible = false
	}

	if possible {
		b := reversed(bld.String())

		for i, r := range b {
			if r != '0' {
				b = b[i:]
				break
			}
		}

		fmt.Fprintln(writer, b)
	} else {
		fmt.Fprintln(writer, -1)
	}
}

//goland:noinspection GoUnhandledErrorResult
func main() {
	defer writer.Flush()

	t := 1
	scanf("%d\n", &t)

	for ; t > 0; t-- {
		solve()
	}
}

const maxUint = ^uint(0)

//goland:noinspection GoUnusedConst
const minUint = 0
const maxInt = int(maxUint >> 1)

//goland:noinspection GoUnusedConst
const minInt = -maxInt - 1

var reader = bufio.NewReader(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

func scanf(f string, a ...interface{}) {
	if _, err := fmt.Fscanf(reader, f, a...); err != nil {
		panic(err)
	}
}

//goland:noinspection GoUnusedFunction
func reversed(s string) string {
	input := []rune(s)
	li := len(input)
	ret := make([]rune, li)
	for i, r := range input {
		ret[li-i-1] = r
	}
	return string(ret)
}

//goland:noinspection GoUnusedFunction
func divCeil(num, div int) int {
	quot := num / div
	if num%div != 0 {
		quot++
	}
	return quot
}

//goland:noinspection GoUnusedFunction
func min(nums ...int64) int64 {
	minimum := nums[0]
	for _, num := range nums {
		if num < minimum {
			minimum = num
		}
	}
	return minimum
}

//goland:noinspection GoUnusedFunction
func max(nums ...int) (max, idx int) {
	for i, num := range nums {
		if num > nums[idx] {
			idx = i
		}
	}

	return nums[idx], idx
}

//goland:noinspection GoUnusedFunction
func abs(num int) int {
	if num < 0 {
		return -num
	}
	return num
}

//goland:noinspection GoUnusedFunction
func isPrime(num int) bool {
	if num == 2 || num == 3 {
		return true
	}

	if num <= 1 || num%2 == 0 || num%3 == 0 {
		return false
	}

	for i := 5; i*i <= num; i += 6 {
		if num%i == 0 || num%(i+2) == 0 {
			return false
		}
	}

	return true
}

//goland:noinspection GoUnusedFunction
func gcd(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

//goland:noinspection GoUnusedFunction
func lcm(a, b int) int {
	return abs(a) / gcd(a, b) * abs(b)
}

// Examples:
//	digitAt(1234, -1) -> panic!
//	digitAt(1234, 0) -> 4
//	digitAt(1234, 1) -> 3
//	digitAt(1234, 2) -> 2
//	digitAt(1234, 3) -> 1
//	digitAt(1234, 4) -> panic!
//goland:noinspection GoUnusedFunction
func digitAt(num, pos int) int {
	if num == 0 {
		return 0
	}

	num = abs(num)

	lenNum := int(math.Log10(float64(num))) + 1
	if pos < 0 || pos >= lenNum {
		err := fmt.Sprintf("Out of bound access for digit. Position passed %d, number %d", pos, num)
		panic(err)
	}

	rem := num % int(math.Pow10(pos+1))
	return rem / int(math.Pow10(pos))
}

package main

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

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

func scan(a ...interface{})             { fmt.Fscan(reader, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }

func redirectInputToFile(r *bufio.Reader, fp string) {
	f, err := os.Open(fp)
	if err != nil {
		panic(err)
	}
	r.Reset(f)
}

func main() {
	defer writer.Flush()
	// redirectInputToFile(reader, "input.txt")

	T := 1
	scan(&T)
	for t := 0; t < T; t++ {
		solve()
	}
}

func solve() {
	var a, s string
	scan(&a, &s)

	res := []int{}

	var x, y int
	i, j := len(a)-1, len(s)-1
	for {
		x, y = 0, 0
		if i < 0 && j < 0 {
			break
		}
		if j < 0 {
			printf("-1\n")
			return
		}
		y = int(s[j] - '0')
		if i >= 0 {
			x = int(a[i] - '0')
		}

		if x <= y {
			res = append(res, y-x)
			i--
			j--
		} else {
			if j == 0 {
				printf("-1\n")
				return
			}
			yy := 10 * int(s[j-1]-'0')
			res = append(res, yy+y-x)
			i--
			j--
			j--
		}
	}
	for i := range res {
		if !(0 <= res[i] && res[i] <= 9) {
			printf("-1\n")
			return
		}
	}
	for len(res) > 0 && res[len(res)-1] == 0 {
		res = res[:len(res)-1]
	}
	var ans int64
	for i := range res {
		ans *= 10
		ans += int64(res[len(res)-1-i])
	}
	printf("%v\n", ans)
}

package main

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

var (
	reader = bufio.NewReader(os.Stdin)
	t      int
	a, s   int64
)

func solve(a, s int64) string {
	if s < a {
		return "-1"
	}
	var b string
	for s > 0 {
		if s < a {
			return "-1"
		}
		currentDigitA := a % 10
		currentDigitS := s % 10
		if currentDigitS >= currentDigitA {
			b = fmt.Sprint(currentDigitS-currentDigitA) + b
			a /= 10
			s /= 10
			continue
		}
		currentDigitS2 := s % 100
		if currentDigitS2 > 19 || currentDigitS2 < currentDigitA {
			return "-1"
		}
		b = fmt.Sprint(currentDigitS2-currentDigitA) + b
		a /= 10
		s /= 100
	}
	for b[0] == '0' {
		b = string(b[1:])
	}
	return b
}

func main() {
	fmt.Fscan(reader, &t)
	for ; t > 0; t-- {
		fmt.Fscan(reader, &a, &s)
		fmt.Println(solve(a, s))
	}
}

package main

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

func main() {
	reader := bReader(os.Stdin)
	writer := bWriter(os.Stdout)

	t := readInt(reader)

	for t > 0 {
		a1, s1 := readTwoInt(reader)
		a, s := strconv.Itoa(a1), strconv.Itoa(s1)

		n, m := len(a)-1, len(s)-1

		ok := true
		b := ""
		for n >= 0 || m >= 0 {
			if m < 0 {
				ok = false
				break
			}

			x, y := 0, int(s[m] - '0')
			if n >= 0 {
				x = int(a[n] - '0')
				n--
			}

			if y < x {
				if m == 0 {
					ok = false
					break
				}

				y = int(s[m-1] - '0') * 10 + y
				m -= 2
			} else {
				m--
			}

			if y-x > 9 || y - x < 0{
				ok = false
				break
			}

			b = strconv.Itoa(y-x) + b
		}

		if !ok {
			fmt.Fprintln(writer, -1)
		} else {
			fmt.Fprintln(writer, strings.TrimLeft(b, "0"))
		}

		t--
	}

	writer.Flush()
}

func bReader(stdin *os.File) *bufio.Reader {
	return bufio.NewReaderSize(stdin, 16*1024*1024)
}

func bWriter(stdout *os.File) *bufio.Writer {
	return bufio.NewWriterSize(stdout, 16*1024*1024)
}

func readLine(reader *bufio.Reader) string {
	str, _, err := reader.ReadLine()
	if err == io.EOF {
		return ""
	}

	return strings.TrimRight(string(str), "\r\n")
}

func checkError(err error) {
	if err != nil {
		panic(err)
	}
}

func readInt(reader *bufio.Reader) int {
	return int(readInt64(reader))
}

func readInt64(reader *bufio.Reader) int64 {
	value, err := strconv.ParseInt(readLine(reader), 10, 64)
	checkError(err)

	return value
}

func readString(reader *bufio.Reader) string {
	return readLine(reader)
}

func readArrayString(reader *bufio.Reader) []string {
	return strings.Split(strings.TrimSpace(readLine(reader)), " ")
}

func readArrayInt(reader *bufio.Reader) []int {
	arTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
	n := len(arTemp)

	var ar []int

	for i := 0; i < n; i++ {
		arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 64)
		checkError(err)
		arItem := int(arItemTemp)
		ar = append(ar, arItem)
	}

	return ar
}

func readArrayInt64(reader *bufio.Reader) []int64 {
	arTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
	n := len(arTemp)

	var ar []int64

	for i := 0; i < n; i++ {
		arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 64)
		checkError(err)
		arItem := arItemTemp
		ar = append(ar, arItem)
	}

	return ar
}

func readTwoInt(reader *bufio.Reader) (int, int) {
	ar := readArrayInt(reader)
	return ar[0], ar[1]
}

func readTwoInt64(reader *bufio.Reader) (int64, int64) {
	ar := readArrayInt64(reader)
	return ar[0], ar[1]
}

func readThreeInt(reader *bufio.Reader) (int, int, int) {
	ar := readArrayInt(reader)
	return ar[0], ar[1], ar[2]
}

func readThreeInt64(reader *bufio.Reader) (int64, int64, int64) {
	ar := readArrayInt64(reader)
	return ar[0], ar[1], ar[2]
}

func gcd(x int64, y int64) int64 {
	for y > 0 {
		x, y = y, x % y
	}

	return x
}

func lcm(x int64, y int64) int64 {
	return x*y/gcd(x,y)
}

package main

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

func main() {
	reader := bReader(os.Stdin)
	writer := bWriter(os.Stdout)

	t := readInt(reader)

	for t > 0 {
		a1, s1 := readTwoInt(reader)
		a, s := strconv.Itoa(a1), strconv.Itoa(s1)

		n, m := len(a)-1, len(s)-1

		ok := true
		b := ""
		for n >= 0 || m >= 0 {
			if m < 0 {
				ok = false
				break
			}

			x, y := 0, int(s[m] - '0')
			if n >= 0 {
				x = int(a[n] - '0')
				n--
			}

			if y < x && m > 0{
				y = int(s[m-1] - '0') * 10 + y
				m -= 2
			} else {
				m--
			}

			if y-x > 9 || y - x < 0{
				ok = false
				break
			}

			b = strconv.Itoa(y-x) + b
		}

		if !ok {
			fmt.Fprintln(writer, -1)
		} else {
			fmt.Fprintln(writer, strings.TrimLeft(b, "0"))
		}

		t--
	}

	writer.Flush()
}

func bReader(stdin *os.File) *bufio.Reader {
	return bufio.NewReaderSize(stdin, 16*1024*1024)
}

func bWriter(stdout *os.File) *bufio.Writer {
	return bufio.NewWriterSize(stdout, 16*1024*1024)
}

func readLine(reader *bufio.Reader) string {
	str, _, err := reader.ReadLine()
	if err == io.EOF {
		return ""
	}

	return strings.TrimRight(string(str), "\r\n")
}

func checkError(err error) {
	if err != nil {
		panic(err)
	}
}

func readInt(reader *bufio.Reader) int {
	return int(readInt64(reader))
}

func readInt64(reader *bufio.Reader) int64 {
	value, err := strconv.ParseInt(readLine(reader), 10, 64)
	checkError(err)

	return value
}

func readString(reader *bufio.Reader) string {
	return readLine(reader)
}

func readArrayString(reader *bufio.Reader) []string {
	return strings.Split(strings.TrimSpace(readLine(reader)), " ")
}

func readArrayInt(reader *bufio.Reader) []int {
	arTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
	n := len(arTemp)

	var ar []int

	for i := 0; i < n; i++ {
		arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 64)
		checkError(err)
		arItem := int(arItemTemp)
		ar = append(ar, arItem)
	}

	return ar
}

func readArrayInt64(reader *bufio.Reader) []int64 {
	arTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
	n := len(arTemp)

	var ar []int64

	for i := 0; i < n; i++ {
		arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 64)
		checkError(err)
		arItem := arItemTemp
		ar = append(ar, arItem)
	}

	return ar
}

func readTwoInt(reader *bufio.Reader) (int, int) {
	ar := readArrayInt(reader)
	return ar[0], ar[1]
}

func readTwoInt64(reader *bufio.Reader) (int64, int64) {
	ar := readArrayInt64(reader)
	return ar[0], ar[1]
}

func readThreeInt(reader *bufio.Reader) (int, int, int) {
	ar := readArrayInt(reader)
	return ar[0], ar[1], ar[2]
}

func readThreeInt64(reader *bufio.Reader) (int64, int64, int64) {
	ar := readArrayInt64(reader)
	return ar[0], ar[1], ar[2]
}

func gcd(x int64, y int64) int64 {
	for y > 0 {
		x, y = y, x % y
	}

	return x
}

func lcm(x int64, y int64) int64 {
	return x*y/gcd(x,y)
}

package main

import (
	"fmt"
	"strconv"
)

func main() {
	var t int
	fmt.Scan(&t)
	for test := 0; test < t; test++ {
		var a, s, ans string
		fmt.Scan(&a, &s)
		var ptr = len(s) - 1
		var g = false
		for i := len(a) - 1; i >= 0 || ptr != -1; i-- {
			var found = false
			for j := 0; j < 10; j++ {
				var cur = 0
				if i >= 0 {
					cur = int(a[i] - '0')
				}
				var temp = strconv.Itoa(cur + j)
				if ptr-len(temp)+1 >= 0 && temp == s[ptr-len(temp)+1:ptr+1] {
					ans += strconv.Itoa(j)
					found = true
					ptr -= len(temp)
					break
				}
			}
			if !found {
				g = true
				break
			}
		}
		if g || ptr != -1 {
			println("-1")
		} else {
			var was = false
			for i := len(ans) - 1; i > -1; i-- {
				if !was && i != 0 && ans[i] == '0' {
					continue
				}
				print(string(ans[i]))
				was = true
			}
			println()
		}
	}
}

package main

import (
	"fmt"
)

func get_b(a, s string) int64 {
	var b int64
	var pow int64 = 1

	i, j := len(a)-1, len(s)-1
	for {
		if i < 0 && j < 0 {
			break
		} else if i < 0 {
			b += pow * int64(s[j]-'0')
			j--
			pow *= 10
			continue
		} else if j < 0 {
			return -1
		}

		if s[j] >= a[i] {
			b += pow * int64(s[j]-a[i])
			i--
			j--
		} else if s[j] < a[i] {
			if j == 0 || s[j-1] != '1' {
				return -1
			} else {
				b += pow * int64(10+s[j]-a[i])
				i--
				j -= 2
			}
		}
		pow *= 10
	}
	return b
}

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

	for i := 0; i < t; i++ {
		var a, s string
		fmt.Scanf("%s %s\n", &a, &s)
		fmt.Printf("%s\n", get_b(a, s))
	}
}

package main

import (
	"fmt"
	"strconv"
)

func main() {
	var t, a, s int
	fmt.Scanln(&t)
	for i := 0; i < t; i++ {
		fmt.Scanln(&a, &s)
		fmt.Println(wrongAddition(a, s))
	}
}

func wrongAddition(a, s int) int {
	final := ""
	for s > 0 {
		if a > s {
			return -1
		} else if s%10-a%10 >= 0 {
			temp := strconv.Itoa(s%10 - a%10)
			final = temp + final
			s = s / 10
			a = a / 10
		} else if s%100-a%10 > 0 && s%100 < 19 {
			temp := strconv.Itoa(s%100 - a%10)
			final = temp + final
			s = s / 100
			a = a / 10
		} else if a > 0 {
			temp := strconv.Itoa(s%10 - a%10)
			final = temp + final
			s = 0
			a = 0
		} else {
			return -1
		}
	}
	intFinal, _ := strconv.Atoi(final)
	if intFinal > 0 {
		return intFinal
	} else {
		return -1
	}
}

package main

import (
	"fmt"
	"strconv"
)

func main() {
	var t, a, s int
	var res []int
	fmt.Scanln(&t)
	for i := 0; i < t; i++ {
		fmt.Scanln(&a, &s)
		res = append(res, wrongAddition(a, s))
	}
	for _, element := range res {
		fmt.Println(element)
	}
}

func wrongAddition(a, s int) int {
	final := ""
	for s > 0 {
		if a > s {
			return -1
		} else if s%10-a%10 >= 0 {
			temp := strconv.Itoa(s%10 - a%10)
			final = temp + final
			s = s / 10
			a = a / 10
		} else if s%100-a%10 > 0 && s%100 < 19 {
			temp := strconv.Itoa(s%100 - a%10)
			final = temp + final
			s = s / 100
			a = a / 10
		} else if a > 0 {
			temp := strconv.Itoa(s%10 - a%10)
			final = temp + final
			s = 0
			a = 0
		} else {
			return -1
		}
	}
	intFinal, _ := strconv.Atoi(final)
	return intFinal
}

package main

import (
	"fmt"
	"strconv"
)

func main() {
	var t, a, s int
	fmt.Scanln(&t)
	for i := 0; i < t; i++ {
		fmt.Scanln(&a, &s)
		fmt.Println(wrongAddition(a, s))
	}
}

func wrongAddition(a, s int) int {
	final := ""
	for s > 0 {
		if a > s {
			return -1
		} else if s%10-a%10 >= 0 {
			temp := strconv.Itoa(s%10 - a%10)
			final = temp + final
			s = s / 10
			a = a / 10
		} else if s%100-a%10 > 0 && s%100 < 19 {
			temp := strconv.Itoa(s%100 - a%10)
			final = temp + final
			s = s / 100
			a = a / 10
		} else if a > 0 {
			temp := strconv.Itoa(s%10 - a%10)
			final = temp + final
			s = 0
			a = 0
		} else {
			return -1
		}
	}
	intFinal, _ := strconv.Atoi(final)
	return intFinal
}

package main

import(
    "fmt"
    "math"
)

func main(){
    var x,a,s int
    fmt.Scan(&x)

    for d := 0; d < x ; d++{
      fmt.Scan(&a,&s)
      solution := 0
      copyS := s
      for n := 0;a > 0 || s > 0; {

          if a%10 > s%10{
            if l := s/10; l%10 != 1{
              solution = -1
              break
            }
            temp := s%10 + 10
            solution += (temp-a%10)*int(math.Pow(float64(10),float64(n)))
            a /= 10
            s /= 100
            n += 1
          }else{
            solution += (s%10-a%10)*int(math.Pow(float64(10),float64(n)))
            a /= 10
            s /= 10
            n += 1
          }
      }
      if  solution > copyS {solution = -1;}
      fmt.Println(solution)

    }
}

package main

import(
    "fmt"
    "math"
)

func main(){
    var x,a,s int
    fmt.Scan(&x)

    for d := 0; d < x ; d++{
      fmt.Scan(&a,&s)
      solution := 0
      copyS := s
      for n := 0;a > 0 || s > 0; {

          if a%10 > s%10{
            if s%100 != 1{
              solution = -1
              break
            }
            temp := s%10 + 10
            solution += (temp-a%10)*int(math.Pow(float64(10),float64(n)))
            a /= 10
            s /= 100
            n += 1
          }else{
            solution += (s%10-a%10)*int(math.Pow(float64(10),float64(n)))
            a /= 10
            s /= 10
            n += 1
          }
      }
      if  solution > copyS {solution = -1;}
      fmt.Println(solution)

    }
}

package main

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

/*
* lets try some fancy go :)

foreach digt in a find the digit of b so
that the sum matches the current digit in s or the next two
digits in s.
*/
func main() {
    re, w, e := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout), bufio.NewWriter(os.Stderr)
    defer w.Flush()
    defer e.Flush()

    var t int=0
    Fscan(re, &t)

    for i:=0; i<t; i++ {
        var a,s int
        Fscan(re, &a, &s)

        if a==s {
            Fprintf(w, "0\n")
            continue
        }

        ok:=true
        ans:= []int{}
        for ; a>0 || s>0; {
            d:=a%10
            a/=10
            ds:=s%10;
            s/=10
            if ds>=d {
                ans=append(ans, ds-d)
            } else {
                ds+=(s%10)*10
                s/=10
                if ds<d || ds>d+9 {
                    ok=false
                } else {
                    ans=append(ans,ds-d);
                }
            }
        }

        if !ok {
            Fprintf(w, "%d\n", -1)
        } else {
            /* remove leading zeros, sic. How is supposed syntax???  */
            for ; len(ans)>0 && ans[len(ans)-1]==0 ; {
                ans=ans[:len(ans)-1]
            }

            for i:=len(ans)-1; i>=0 ; i-- {
                Fprintf(w, "%d", ans[i])
            }
            Fprintf(w, "\n")
        }
    }
}

package main

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

/*
* lets try some fancy go :)

foreach digt in a find the digit of b so
that the sum matches the current digit in s or the next two
digits in s.
*/
func main() {
    re, w, e := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout), bufio.NewWriter(os.Stderr)
    defer w.Flush()
    defer e.Flush()

    var t int=0
    Fscan(re, &t)

    for i:=0; i<t; i++ {
        var a,s int
        Fscan(re, &a, &s)

        ok:=true
        ans:= []int{}
        for ; a>0 || s>0; {
            d:=a%10
            a/=10
            ds:=s%10;
            s/=10
            if ds>=d {
                ans=append(ans, ds-d)
            } else {
                ds+=(s%10)*10
                s/=10
                if ds<d || ds>d+9 {
                    ok=false
                } else {
                    ans=append(ans,ds-d);
                }
            }
        }

        if !ok {
            Fprintf(w, "%d\n", -1)
        } else {
            /* remove leading zeros, sic. How is supposed syntax???  */
            for ; len(ans)>0 && ans[len(ans)-1]==0 ; {
                ans=ans[:len(ans)-1]
            }

            for i:=len(ans)-1; i>=0 ; i-- {
                Fprintf(w, "%d", ans[i])
            }
            Fprintf(w, "\n")
        }
    }
}

package main

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

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

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

		var ans int
		pos := len(s) - 1
		for i := len(a) - 1; i >= 0 || pos >= 0; i-- {
			var d1, d2 int
			if i >= 0 {
				d1 = int(a[i] - '0')
			}

			if pos < 0 {
				ans = -1
				break
			}

			d2 = int(s[pos] - '0')
			if d1 > d2 {
				if pos-1 < 0 || s[pos-1] != '1' {
					ans = -1
					break
				}
				ans += (10 + d2 - d1) * int(math.Pow10(len(a)-i-1))
				pos--
			} else if d1 < d2 {
				ans += (d2 - d1) * int(math.Pow10(len(a)-i-1))
			}
			pos--
		}
		fmt.Fprintln(out, ans)
	}
}

package main

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

func solve(in *bufio.Reader, out *bufio.Writer) {
	defer out.Flush()
	s1 := ""
	s2 := ""
	Fscan(in, &s1, &s2)
	s1L := len(s1) - 1
	s2L := len(s2) - 1
	ans := ""
	for s1L >= 0 {
		if s2L < 0 {
			ans = "-1"
			break
		}
		if s1[s1L] <= s2[s2L] {
			ans = strconv.FormatInt(int64(s2[s2L]-s1[s1L]), 10) + ans
			s1L--
			s2L--
		} else {
			if s2L <= 0 || s2[s2L-1] != '1' {
				ans = "-1"
				break
			}
			val := 10 + (s2[s2L] - '0') - (s1[s1L] - '0')
			ans = strconv.FormatInt(int64(val), 10) + ans
			s2L -= 2
			s1L--
		}
	}
	if s2L >= 0 {
		ans = s2[0:s2L+1] + ans
	}
	parseInt, _ := strconv.ParseInt(ans, 10, 64)
	Println(parseInt)
}

func main() {
	stdin := os.Stdin
	stdout := os.Stdout
	in := bufio.NewReader(stdin)
	out := bufio.NewWriter(stdout)
	n := 0
	Fscan(in, &n)
	for i := 0; i < n; i++ {
		solve(in, out)
	}
}

package main

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

var (
	rr = bufio.NewReader(os.Stdin)
	ww = bufio.NewWriter(os.Stdout)
)

var (
	T    int
	a, s string
)

func num(xs ...byte) int {
	res := 0
	for _, x := range xs {
		res = res*10 + int(x-'0')
	}
	return res
}

func sub(s, a string) int64 {
	b := ""
	si := len(s) - 1
	for ai := len(a) - 1; ai >= 0; ai-- {
		if si < 0 {
			return -1
		}
		bnum := num(s[si]) - num(a[ai])
		if bnum < 0 {
			if si == 0 {
				return -1
			}
			bnum = num(s[si-1], s[si]) - num(a[ai])
			if bnum >= 10 {
				return -1
			}
			si--
		}
		b = strconv.Itoa(bnum) + b
		si--
	}
	if si >= 0 {
		b = s[:si+1] + b
	}
	ans, _ := strconv.ParseInt(b, 10, 64)
	return ans
}

func Init() {
}

func main() {
	_, _ = fmt.Fscan(rr, &T)
	for iCase := 0; iCase < T; iCase++ {
		_, _ = fmt.Fscan(rr, &a, &s)

		_, _ = fmt.Fprintln(ww, sub(s, a))
	}
	_ = ww.Flush()
}


You are given array a with n integers and m queries. The i-th query is given with three integers li, ri, xi.For the i-th query find any position pi (li ≤ pi ≤ ri) so that api ≠ xi.

The first line contains two integers n, m (1 ≤ n, m ≤ 2·105) — the number of elements in a and the number of queries. The second line contains n integers ai (1 ≤ ai ≤ 106) — the elements of the array a. Each of the next m lines contains three integers li, ri, xi (1 ≤ li ≤ ri ≤ n, 1 ≤ xi ≤ 106) — the parameters of the i-th query.

Print m lines. On the i-th line print integer pi — the position of any number not equal to xi in segment [li, ri] or the value  - 1 if there is no such number.

package main

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

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

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

	n, m := nextInt()+1, nextInt()
	a := make([]int, n)
	dp := make([]int, n)

	for i := 1; i < n; i++ {
		a[i] = nextInt()

		if a[i] == a[i-1] {
			dp[i] = dp[i-1]
		} else {
			dp[i] = i - 1
		}
	}

	for ; m > 0; m-- {
		l, r, x := nextInt(), nextInt(), nextInt()

		if a[r] != x {
			println(r)
		} else if dp[r] >= l {
			println(dp[r])
		} else {
			println(-1)
		}
	}
}

func next() string {
	if !scanner.Scan() {
		panic(scanner.Err())
	}
	return scanner.Text()
}

func nextInt64() int64 {
	n, _ := strconv.ParseInt(next(), 0, 64)
	return n
}

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

func nextFloat() float64 {
	n, _ := strconv.ParseFloat(next(), 64)
	return n
}

func println(a ...interface{})               { fmt.Fprintln(writer, a...) }
func print(a ...interface{})                 { fmt.Fprint(writer, a...) }
func printf(format string, a ...interface{}) { fmt.Fprintf(writer, format, a...) }

package main

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

var scanner *bufio.Scanner

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

type Span struct {
  Left, Right, Value int
}

var spans = []*Span{}

func findSpan(pos int) int {
  low, high := 0, len(spans) - 1
  for {
    mid := (low + high) / 2
    if spans[mid].Left > pos {
      high = mid - 1
    } else if spans[mid].Right < pos {
      low = mid + 1
    } else {
      return mid
    }
  }
}

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

  n, m := getI(), getI()
  xs := make([]int, n)
  for i := range xs {
    xs[i] = getI()
  }
  x, left := xs[0], 0
  for i := 0; i < len(xs); i++ {
    y := xs[i]
    if y != x {
      spans = append(spans, &Span{ left + 1, i, x })
      x, left = y, i
    }
  }
  spans = append(spans, &Span{ left + 1, len(xs), x })
  results := make([]int, m)

  for i := range results {
    l, r, x := getI(), getI(), getI()
    lSpan := spans[findSpan(l)]
    rSpan := spans[findSpan(r)]
    if lSpan == rSpan {
      if lSpan.Value != x {
        results[i] = l
      } else {
        results[i] = -1
      }
      continue
    }
    if lSpan.Value != x {
      results[i] = l
    } else if rSpan.Value != x {
      results[i] = r
    } else {
      results[i] = lSpan.Right + 1
    }
  }

  for _, pos := range results {
    writer.WriteString(fmt.Sprintf("%d\n", pos))
  }
}

package main

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

var scanner *bufio.Scanner

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

type Span struct {
  Left, Right, Value int
}

var spans = []*Span{}

func findSpan(pos int) int {
  low, high := 0, len(spans) - 1
  for {
    mid := (low + high) / 2
    if spans[mid].Left > pos {
      high = mid - 1
    } else if spans[mid].Right < pos {
      low = mid + 1
    } else {
      return mid
    }
  }
}

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

  n, m := getI(), getI()
  xs := make([]int, n)
  for i := range xs {
    xs[i] = getI()
  }
  x, left := xs[0], 0
  for i := 0; i < len(xs); i++ {
    y := xs[i]
    if y != x {
      spans = append(spans, &Span{ left + 1, i, x })
      x, left = y, i
    }
  }
  spans = append(spans, &Span{ left + 1, len(xs), x })
  results := make([]int, m)

  for i := range results {
    l, r, x := getI(), getI(), getI()
    lSpan := spans[findSpan(l)]
    rSpan := spans[findSpan(r)]
    if lSpan == rSpan {
      if lSpan.Value != x {
        results[i] = lSpan.Left
      } else {
        results[i] = -1
      }
      continue
    }
    if lSpan.Value != x {
      results[i] = lSpan.Left
    } else if rSpan.Value != x {
      results[i] = rSpan.Left
    } else {
      results[i] = lSpan.Right + 1
    }
  }

  for _, pos := range results {
    writer.WriteString(fmt.Sprintf("%d\n", pos))
  }
}


The only difference between easy and hard versions is the length of the string. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.Kirk has a binary string $$$s$$$ (a string which consists of zeroes and ones) of length $$$n$$$ and he is asking you to find a binary string $$$t$$$ of the same length which satisfies the following conditions: For any $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq n$$$) the length of the longest non-decreasing subsequence of the substring $$$s_{l}s_{l+1} \ldots s_{r}$$$ is equal to the length of the longest non-decreasing subsequence of the substring $$$t_{l}t_{l+1} \ldots t_{r}$$$; The number of zeroes in $$$t$$$ is the maximum possible.A non-decreasing subsequence of a string $$$p$$$ is a sequence of indices $$$i_1, i_2, \ldots, i_k$$$ such that $$$i_1 < i_2 < \ldots < i_k$$$ and $$$p_{i_1} \leq p_{i_2} \leq \ldots \leq p_{i_k}$$$. The length of the subsequence is $$$k$$$.If there are multiple substrings which satisfy the conditions, output any.

The first line contains a binary string of length not more than $$$10^5$$$.

Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.

NoteIn the first example:  For the substrings of the length $$$1$$$ the length of the longest non-decreasing subsequnce is $$$1$$$;  For $$$l = 1, r = 2$$$ the longest non-decreasing subsequnce of the substring $$$s_{1}s_{2}$$$ is $$$11$$$ and the longest non-decreasing subsequnce of the substring $$$t_{1}t_{2}$$$ is $$$01$$$;  For $$$l = 1, r = 3$$$ the longest non-decreasing subsequnce of the substring $$$s_{1}s_{3}$$$ is $$$11$$$ and the longest non-decreasing subsequnce of the substring $$$t_{1}t_{3}$$$ is $$$00$$$;  For $$$l = 2, r = 3$$$ the longest non-decreasing subsequnce of the substring $$$s_{2}s_{3}$$$ is $$$1$$$ and the longest non-decreasing subsequnce of the substring $$$t_{2}t_{3}$$$ is $$$1$$$; The second example is similar to the first one.

package main

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

const (
	mod = 998244353
)

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	s := ""
	fmt.Fscanf(in, "%s\n", &s)
	ans := []byte{}
	zero := 0
	for i := len(s) - 1; i >= 0; i-- {
		if s[i] == '0' {
			zero++
			ans = append(ans, '0')
		} else if zero == 0 {
			ans = append(ans, '0')
		} else {
			zero--
			ans = append(ans, '1')
		}
	}
	ans = reverse(ans)
	fmt.Fprintf(out, "%s\n", string(ans))
}

func reverse(a []byte) []byte {
	ans := []byte{}
	for i := len(a) - 1; i >= 0; i-- {
		ans = append(ans, a[i])
	}
	return ans
}

func first(a int) int64 {
	ans := int64(0)
	base := int64(10)
	for a > 0 {
		tail := int64(a % 10)
		a /= 10
		ans += base * tail
		base *= 100
		ans %= mod
		base %= mod
	}
	return ans
}

func second(a int) int64 {
	ans := int64(0)
	base := int64(1)
	for a > 0 {
		tail := int64(a % 10)
		a /= 10
		ans += base * tail
		base *= 100
		ans %= mod
		base %= mod
	}
	return ans
}