Emuskald is addicted to Codeforces, and keeps refreshing the main page not to miss any changes in the "recent actions" list. He likes to read thread conversations where each thread consists of multiple messages.Recent actions shows a list of n different threads ordered by the time of the latest message in the thread. When a new message is posted in a thread that thread jumps on the top of the list. No two messages of different threads are ever posted at the same time.Emuskald has just finished reading all his opened threads and refreshes the main page for some more messages to feed his addiction. He notices that no new threads have appeared in the list and at the i-th place in the list there is a thread that was at the ai-th place before the refresh. He doesn't want to waste any time reading old messages so he wants to open only threads with new messages.Help Emuskald find out the number of threads that surely have new messages. A thread x surely has a new message if there is no such sequence of thread updates (posting messages) that both conditions hold:   thread x is not updated (it has no new messages);  the list order 1, 2, ..., n changes to a1, a2, ..., an.

The first line of input contains an integer n, the number of threads (1 ≤ n ≤ 105). The next line contains a list of n space-separated integers a1, a2, ..., an where ai (1 ≤ ai ≤ n) is the old position of the i-th thread in the new list. It is guaranteed that all of the ai are distinct.

Output a single integer — the number of threads that surely contain a new message.

NoteIn the first test case, threads 2 and 5 are placed before the thread 1, so these threads must contain new messages. Threads 1, 3 and 4 may contain no new messages, if only threads 2 and 5 have new messages.In the second test case, there may be no new messages at all, since the thread order hasn't changed.In the third test case, only thread 1 can contain no new messages.

package main

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

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Split(bufio.ScanWords)
    var n,ans int
    fmt.Scan(&n)
    prev := 0
    for i := 0; i < n; i++ {
        scanner.Scan()
        cur, _ := strconv.Atoi(scanner.Text())
        if (i > 0) && (cur < prev) {
            ans = i
        }
        prev = cur
    }
    fmt.Println(ans)
}

package main

import "os"
import "bufio"
import "strconv"

func main() {
	var n, a, x, min int
	x = 0
	min = 0
	r := bufio.NewScanner(os.Stdin)
	r.Split(bufio.ScanWords)
	w := bufio.NewWriter(os.Stdout)
	r.Scan()
	n, _ = strconv.Atoi(r.Text())
	for i:=0; i<n; i++ {
		r.Scan()
		a, _ = strconv.Atoi(r.Text())
		if x > a {
			min = i
		}
		x = a
	}
	w.WriteString(strconv.Itoa(min)+"\n")
	w.Flush()
}

// 270B-mic_rizal
package main

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

func main() {
    var n, i int
    fmt.Scan(&n)
    z := bufio.NewReader(os.Stdin)
    a := make([]int, n)
    for i = 0; i < n; i++ {
        fmt.Fscan(z, &a[i])
    }
    for i = n - 2; i >= 0; i-- {
        if a[i] > a[i+1] {
            break
        }
    }
    fmt.Println(i + 1)
}

package main

import (
    "fmt"
    "bufio"
    "os"

)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Split(bufio.ScanWords)
    var n int
    fmt.Scan(&n)
    for i := 0; i < n; i++ {
        scanner.Scan()
        if scanner.Text() == "1" {
            fmt.Println(i)
			break
        }
    }
}

// 270B-mic_rizal
package main

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

func main() {
    var n, i int
    fmt.Scan(&n)
    z := bufio.NewReader(os.Stdin)
    a := make([]int, n)
    for i = 0; i < n; i++ {
        fmt.Scan(z, &a[i])
    }
    for i = n - 2; i >= 0; i-- {
        if a[i] > a[i+1] {
            break
        }
    }
    fmt.Println(i + 1)
}


Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.  The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that?

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of disks on the combination lock. The second line contains a string of n digits — the original state of the disks. The third line contains a string of n digits — Scrooge McDuck's combination that opens the lock.

Print a single integer — the minimum number of moves Scrooge McDuck needs to open the lock.

NoteIn the sample he needs 13 moves:  1 disk:   2 disk:   3 disk:   4 disk:   5 disk:

package main

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

var in *bufio.Scanner = bufio.NewScanner(os.Stdin)
var out *bufio.Writer = bufio.NewWriter(os.Stdout)

func main() {
	defer out.Flush()
	in.Split(bufio.ScanWords)

	n, a, b := nextInt(), next(), next()
	res := 0
	for i := 0; i < n; i++ {
		res += min(int(a[i] - b[i] + 10) % 10, int(b[i] - a[i] + 10) % 10)
	}
	fmt.Println(res)
}

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

func nextInt() int {
	in.Scan()
	res, _ := strconv.Atoi(in.Text())
	return res
}

func next() string {
	in.Scan()
	return in.Text()
}

package main

import "fmt"

func dist(a, b int) int {
	c, d := (a-b+10)%10, (b-a+10)%10
	if c < d {
		return c
	}
	return d
}

func main() {
	var n int
	var s1, s2 string
	fmt.Scanf("%d\n", &n)
	fmt.Scanf("%s\n", &s1)
	fmt.Scanf("%s\n", &s2)
	sum := 0
	for i := 0; i < n; i++ {
		sum += dist(int(s1[i]-'0'), int(s2[i]-'0'))
	}
	fmt.Println(sum)
}

package main
import (
	"fmt"
	"math"
)

func main() {
	var(
		n, count int
		current, target string
	)
	fmt.Scanln(&n)
	fmt.Scanln(&current)
	fmt.Scanln(&target)

	for i := 0; i < n; i ++ {
		sub := math.Abs(math.Abs(float64(current[i]))-math.Abs(float64(target[i])))
		if sub > 5 {
			count += int(10-sub)
		}else{
			count += int(sub)
		}
	}

	fmt.Println(count)
}

package main

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

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

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

	n, s, t := nextInt(), next(), next()
	action, dis := 0, 0

	for i := 0; i < n; i++ {
		if s[i] != t[i] {
			dis = abs(int(s[i]) - int(t[i]))
			// println(s[i], t[i], s[i]-t[i])
			// println(dis)

			if dis > 5 {
				dis = 10 - dis
			}
			// println(dis)
			action += dis
		}
	}

	println(action)
}

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

func scan(a ...interface{}) {
	fmt.Fscan(reader, a...)
}

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 (
	"fmt"
	"math"
)

func pluss(i, j int) int {
	res := 0
	var diff = int(math.Abs(float64(i - j)))
	if diff < 5 {
		res += diff
	} else {
		res += 10 - diff
	}
	return res
}

func main() {
	var n, s int
	fmt.Scan(&n)
	var a, b string
	fmt.Scan(&a, &b)
	for i, _ := range a {
		s += pluss(int(b[i]), int(a[i]))
	}
	fmt.Println(s)
}

package main

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

func abs(a, e int64) int64 {
	if a-e < 0 {
		return -1 * (a - e)
	}

	return a - e
}

func main() {

	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	n := scanner.Text()

	var length int64

	length, _ = strconv.ParseInt(n, 10, 64)
	scanner.Scan()
	actual := scanner.Text()
	scanner.Scan()
	expected := scanner.Text()

	var actDig, expDig int64

	var result, i int64

	for i = 0; i < length; i++ {
		actDig, expDig = int64((actual[i]-'0'))%10, int64((expected[i]-'0'))%10

		num1 := abs(actDig, expDig)

		if num1 < 5 {
			result += num1
		} else {
			if actDig > expDig {
				result += (expDig + 10) - actDig
			} else {
				result += (actDig + 10) - expDig
			}
		}
	}

	fmt.Println(result)
}

package main

import ("fmt"
		"math")
		//"strconv")

func calc(size int ,s1,s2 string) int{

	var ans float64
	for i:=0;i<size;i++{
		temp1 := s1[i]
		temp2 := s2[i]
		if temp2<temp1{
			temp3 := temp1
			temp1 = temp2
			temp2 = temp3
		}
		temp4 := math.Min(float64(temp2-temp1) , float64(temp1 + 1 + (9-temp2)))
		ans += temp4
	}
	return int(ans)
}

func main(){
	var a int
	fmt.Scanln(&a)
	var l string
	fmt.Scanln(&l)
	var o string
	fmt.Scanln(&o)
	fmt.Println(calc(a,l,o))
}

package main

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

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

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

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

  n := getI()
  s, t := getS(), getS()
  result := 0
  for i := 0; i < n; i++ {
    c, d := int(s[i]-'0'), int(t[i]-'0')
    if c > d {
      c, d = d, c
    }
    cost := d-c
    if cost > 5 {
      cost = 10-cost
    }
    result += cost
  }
  writer.WriteString(fmt.Sprintf("%d\n", result))
}

package main

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

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func getMove(from, to int) int {
	if from > to {
		from, to = to, from
	}

	return min(to-from, from+10-to)
}

func main() {
	var n int
	fmt.Scanf("%d \n", &n)
	var input, output string
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	input = scanner.Text()
	scanner.Scan()
	output = scanner.Text()
	result := 0
	for i := 0; i < n; i++ {
		result += getMove(int(input[i])-48, int(output[i])-48)
	}
	fmt.Print(result)
}

package main

import (
	"fmt"
	"math"
)

func main() {
	var frase1, frase2 string
	var n, dif, low int
	fmt.Scanf("%v\n%v\n%v", &n, &frase1, &frase2)

	for i := 0; i < n; i++ {
		dif = int(math.Abs(float64(frase1[i]) - float64(frase2[i])))
		if dif > 5 {
			dif = 10 - dif
		}
		low += dif
	}
	fmt.Println(low)
}

package main

import "fmt"
import "strconv"

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

func main() {
	var nstr, l1, l2 string
	fmt.Scanln(&nstr)
	fmt.Scanln(&l1)
	fmt.Scanln(&l2)

	total := 0
	n, _ := strconv.Atoi(nstr)
	for i := 0; i < n; i++ {
		d1 := int(l1[i] - '0')
		d2 := int(l2[i] - '0')
		total += min((d1 - d2 + 10) % 10, (d2 - d1 + 10) % 10)
	}
	fmt.Printf("%d\n", total)
}

package main

import (
	"fmt"
)

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

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

func mv(o int, d int) int {
	var r int = abs(d - o)
	r = min(r, abs(d - (o + 10)))
	r = min(r, abs(d + 10 - o))
	return r
}

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

	var r int = 0
	for i := 0; i < n; i++ {
		var o int = int(orig[i] - '0')
		var d int = int(dest[i] - '0')
		r += mv(o, d)
	}

	fmt.Println(r)
}

package main

import "fmt"

func main() {
	var n, diff int
	var pos, dst string
	fmt.Scan(&n, &pos, &dst)

	sum := 0
	for i := 0; i < len(pos); i++ {
		if pos[i] > dst[i] {
			diff = int(pos[i] - dst[i])
		} else {
			diff = int(dst[i] - pos[i])
		}

		if diff > 5 {
			diff = 10 - diff
		}
		sum += diff
	}

	fmt.Print(sum)
}

package main

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

func main() {
	var n, s int
	var s1, s2 string
	in := bufio.NewReader(os.Stdin)
	fmt.Fscanf(in, "%d\n", &n)
	fmt.Fscanf(in, "%s\n", &s1)
	fmt.Fscanf(in, "%s\n", &s2)

	for i := int(0); i < n; i++ {
		current, _ := strconv.Atoi(string(s1[i]))
		key, _ := strconv.Atoi(string(s2[i]))
		result := math.Abs(float64(key) - float64(current))
		s += check(int(result), current, key)
	}
	fmt.Println(s)
}
func check(a int, b int, c int) int {
	var d int
	if b > c {
		d = int(math.Abs(float64(b-10))) + c
	} else {
		d = int(math.Abs(float64(c-10))) + b
	}
	if a > d {
		return d
	} else {
		return a
	}
}

package main

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

// -----------------------------------------------------------------------------

// IO helper functions

// Returns next token from input.  It must be initialized by SetInput()
// before the first call.
var nextToken func() ([]byte, error)
var nextLine func() ([]byte, error)

// Holds a buffer for output.  It must be initialized by SetOutput().
// All IO fucntions (read*() and [e]print*()) should write to OutputWriter
// instead of this.
var OutputBuffer *bufio.Writer

// Holds an io.Writer.  It must be initialized by SetOutput()
var OutputWriter io.Writer

// Set IO functions for interactive input/output.
func SetInteractive(w io.Writer, r io.Reader) {
	SetUnbefferedInput(r)
	OutputBuffer = nil
	OutputWriter = w
}

// Setup OutputBuffer and OutputWriter.
func SetOutput(w io.Writer) {
	OutputBuffer = bufio.NewWriter(w)
	OutputWriter = OutputBuffer
}

// Flushes OutputBuffer
func Flush() {
	if OutputBuffer != nil {
		OutputBuffer.Flush()
	}
}

// Returns true if c is a white space
func IsSpace(c byte) bool {
	switch c {
	case '\t', '\n', '\v', '\f', '\r', ' ':
		return true
	}
	return false
}

func IsNewLine(c byte) bool {
	switch c {
	case '\n', '\r':
		return true
	}
	return false
}

// Setup nextToken with input buffer.
func SetInput(r io.Reader) {
	buf := new(bytes.Buffer)
	var b []byte

	var i int
	rest := func() ([]byte, error) {
		for i < len(b) && IsSpace(b[i]) {
			i++
		}
		if i == len(b) {
			return nil, io.ErrUnexpectedEOF
		}
		j := i
		for i < len(b) && !IsSpace(b[i]) {
			i++
		}
		return b[j:i], nil
	}
	initial := func() ([]byte, error) {
		io.Copy(buf, r)
		b = buf.Bytes()
		nextToken = rest
		return rest()
	}
	nextToken = initial

	restLn := func() ([]byte, error) {
		for i < len(b) && IsNewLine(b[i]) {
			i++
		}
		if i == len(b) {
			return nil, io.ErrUnexpectedEOF
		}
		j := i
		for i < len(b) && !IsNewLine(b[i]) {
			i++
		}
		return b[j:i], nil
	}

	initialLn := func() ([]byte, error) {
		io.Copy(buf, r)
		b = buf.Bytes()
		nextLine = restLn
		return restLn()
	}
	nextLine = initialLn
}

// Setup nextToken without input buffer.
func SetUnbefferedInput(r io.Reader) {
	buf := bufio.NewReader(r)
	var b []byte

	var i int
	nextToken = func() ([]byte, error) {
		var err error
		if i == len(b) {
			b, err = buf.ReadBytes('\n')
			if err != nil {
				return nil, err
			}
			i = 0
			j := len(b) - 1
			for 0 <= j && IsSpace(b[j]) {
				j--
			}
			b = b[0 : j+1]
		}
		for i < len(b) && IsSpace(b[i]) {
			i++
		}
		j := i
		for i < len(b) && !IsSpace(b[i]) {
			i++
		}
		if i == j {
			return nil, io.ErrUnexpectedEOF
		}
		return b[j:i], nil
	}
}

// -----------------------------------------------------------------------------

// IO functions

// Reads next token and return it as []byte
func readb() []byte {
	b, err := nextToken()
	if err != nil {
		panic(err)
	}
	return b
}

// Reads next token and return it as string
func reads() string {
	return string(readb())
}

// Read next line as []byte
func readbln() []byte {
	b, err := nextLine()
	if err != nil {
		panic(err)
	}
	return b
}

// Read next line as string
func readsln() string {
	return string(readbln())
}

// Reads next token and return it as int64
func readll() int64 {
	i, err := strconv.ParseInt(reads(), 10, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// Reads next token and return it as int
func readi() int {
	return int(readll())
}

// Reads next token and return it as float64
func readf() float64 {
	f, err := strconv.ParseFloat(reads(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// Write args to OutputWriter with the format f
func printf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(OutputWriter, f, args...)
}

// Write args to OutputWriter without format
func println(args ...interface{}) (int, error) {
	return fmt.Fprintln(OutputWriter, args...)
}

// Write args to stderr with the format f
func eprintf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(os.Stderr, f, args...)
}

// Write args to stderr without format
func eprintln(args ...interface{}) (int, error) {
	return fmt.Fprintln(os.Stderr, args...)
}

// -----------------------------------------------------------------------------

// Simple math functions

const (
	// big prime
	INF  = 1000000007
	INF2 = 1000000009
	INF3 = 998244353
)

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

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

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

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

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

func absll(a int64) int64 {
	if a < 0 {
		return -a
	}
	return a
}

// egcd(a, b) returns d, x, y:
//   d is gcd(a,b)
//   x, y are  integers that satisfy ax + by = d
func egcd(a, b int) (int, int, int) {
	if b == 0 {
		return a, 1, 0
	}
	d, x, y := egcd(b, a%b)
	return d, y, x - a/b*y
}

func egcdll(a, b int64) (int64, int64, int64) {
	if b == 0 {
		return a, 1, 0
	}
	d, x, y := egcdll(b, a%b)
	return d, y, x - a/b*y
}

func gcd(a, b int) int {
	d, _, _ := egcd(a, b)
	return d
}

func gcdll(a, b int64) int64 {
	d, _, _ := egcdll(a, b)
	return d
}

// set up IO functions
func init() {
	// for non-interactive
	SetInput(os.Stdin)
	SetOutput(os.Stdout)

	// Enable below when interactive.  Its ok to leave above intact.
	// SetInteractive(os.Stdout, os.Stdin)
}

func main() {
	defer Flush()

	n := readi()
	a := readb()
	b := readb()
	var ans int
	for i := 0; i < n; i++ {
		x := int(a[i] - '0')
		y := int(b[i] - '0')
		ans += check(x, y)
	}
	println(ans)
}

func check(a, b int) int {
	if b < a {
		a, b = b, a
	}
	return min(b-a, a+10-b)
}

package main

import (
        "fmt"
)

func main() {
        var n, m int
        var s1, s2 string
        fmt.Scan(&n, &s1, &s2)
        for i, _ := range s1 {
                a := int(s1[i] - '0')
                b := int(s2[i] - '0')
                j := a
                k := 0
                for ; a != b && j != b; k++ {
                        if a == 10 {
                                a = 0
                                if b == 0 {
                                        break
                                }
                        }
                        if j == -1 {
                                j = 9
                                if b == 9 {
                                        break
                                }
                        }
                        a++
                        j--
                }
                m += k
        }
        fmt.Println(m)
}

package main

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

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

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

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

func main() {
	var T int
	var A, B string

	scanf("%d \n", &T)
	scanf("%s \n", &A)
	scanf("%s \n", &B)

	aArray := strings.Split(A, "")
	bArray := strings.Split(B, "")
	result := 0
	for i, _ := range aArray {
		a, _ := strconv.Atoi(aArray[i])
		b, _ := strconv.Atoi(bArray[i])
		diff := getDiff(a, b)
		if diff <=5 {
			result += diff
			continue
		}

		if a < b {
			a = a + 10
			result += getDiff(a, b)
		}else {
			b = b + 10
			result += getDiff(a, b)
		}

	}

	fmt.Println(result)
}

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

	return a - b
}

package main

import "fmt"
import "bufio"
import "os"

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 main() {
	scanner := bufio.NewScanner(os.Stdin)
	var n int
	scanner.Scan()

	fmt.Sscanf(scanner.Text(), "%d", &n)

	M := make([][]int, 2)
	for x := 0; x < 2; x++ {
		M[x] = make([]int, n)
	}
	for i := 0; i < 2; i++ {
		scanner.Scan()
		line := scanner.Text()
		for u, c := range line {
			M[i][u] = int(c - '0')
		}
	}

	var ret int

	for i := 0; i < n; i++ {
		a := max(M[0][i], M[1][i])
		b := min(M[0][i], M[1][i])

		ret += min(a - b, min(10 - a + b, 10 - b + a))
	}

	fmt.Println(ret)
}

package main

import (
	"fmt"
	"math"
)

func solve(first, second int) int {
	ans := 0
	var difference = int(math.Abs(float64(first - second)))
	if difference < 5 {
		ans += difference
	} else {
		ans += 10 - difference
	}
	return ans
}

func main() {
	var n, s int
	fmt.Scan(&n)
	var a, b string
	fmt.Scan(&a, &b)
	for i, _ := range a {
		s += solve(int(b[i]), int(a[i]))
	}
	fmt.Println(s)
}

// CombinationLock project main.go
package main

import (
	"fmt"
)

func main() {
	num_digit := 0
	original := ""
	comb := ""

	fmt.Scan(&num_digit)
	fmt.Scan(&original)
	fmt.Scan(&comb)

	sum_move := 0
	for idx, _ := range original {

		original_digit := int(original[idx] - '0')
		comb_digit := int(comb[idx] - '0')

		if original_digit < comb_digit {
			tmp := original_digit
			original_digit = comb_digit
			comb_digit = tmp
		}

		if original_digit-comb_digit > 5 {
			comb_digit += 10
			original_digit *= -1
		} else {
			comb_digit *= -1
		}

		sum_remain := comb_digit + original_digit

		if sum_remain < 0 {
			sum_remain *= -1
		}
		sum_move += (sum_remain)

	}

	fmt.Printf("%d\n", sum_move)

}

// CombinationLock project main.go
package main

import (
	"fmt"
)

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

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

func main() {
	num_digit := 0
	original := ""
	comb := ""

	fmt.Scan(&num_digit)
	fmt.Scan(&original)
	fmt.Scan(&comb)

	sum_move := 0
	for idx, _ := range original {

		original_digit := int(original[idx] - '0')
		comb_digit := int(comb[idx] - '0')

		if original_digit < comb_digit {
			tmp := original_digit
			original_digit = comb_digit
			comb_digit = tmp
		}

		sum_digit := Min(original_digit - comb_digit, 10+comb_digit-original_digit)

		sum_move += (sum_digit)

	}

	fmt.Printf("%d\n", sum_move)

}

// CombinationLock project main.go
package main

import (
	"fmt"
)

func main() {
	num_digit := 0
	state_original := 0
	state_comb := 0

	original := ""
	comb := ""

	fmt.Scan(&num_digit)
	fmt.Scan(&original)
	fmt.Scan(&comb)

	sum_move := 0
	for idx, _ := range original {

		state_original = int(original[idx] - '0')
		state_comb = int(comb[idx] - '0')

		original_remain := state_original % 10
		state_original = state_original / 10

		comb_remain := state_comb % 10
		state_comb = state_comb / 10

		if original_remain < comb_remain {
			tmp := original_remain
			original_remain = comb_remain
			comb_remain = tmp
		}

		if original_remain-comb_remain > 5 {
			comb_remain += 10
			original_remain *= -1
		} else {
			comb_remain *= -1
		}

		sum_remain := comb_remain + original_remain

		if sum_remain < 0 {
			sum_remain *= -1
		}
		sum_move += (sum_remain)

	}

	fmt.Printf("%d\n", sum_move)

}

package main

import (
	"fmt"
	"math"
)

func main() {
	var n, res int
	fmt.Scan(&n)
	var beg, end string
	fmt.Scan(&beg, &end)

	for i, _ := range beg {
		var diff = int(math.Abs(float64(int(end[i]) - int(beg[i]))))
		if diff < 5 {
			res += diff
		} else {
			res += 10 - diff
		}
	}
	fmt.Println(res)
}

package main

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

func abs(a, e int64) int64 {
	if a-e < 0 {
		return -1 * (a - e)
	}

	return a - e
}

func main() {

	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	n := scanner.Text()

	_, _ = strconv.Atoi(n)
	scanner.Scan()
	actual := scanner.Text()
	scanner.Scan()
	expected := scanner.Text()

	var actualNum, expectedNum int64

	actualNum, _ = strconv.ParseInt(actual, 10, 64)
	expectedNum, _ = strconv.ParseInt(expected, 10, 64)

	var result int64

	for actualNum > 0 && expectedNum > 0 {
		var actDig, expDig int64 = actualNum % 10, expectedNum % 10
		num1 := abs(actDig, expDig)

		if num1 < 5 {
			result += num1
		} else {
			if actDig > expDig {
				result += (expDig + 10) - actDig
			} else {
				result += (actDig + 10) - expDig
			}
		}

		actualNum /= 10
		expectedNum /= 10
	}

	fmt.Println(result)
}

package main

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

func abs(a, e int) int {
	if a-e < 0 {
		return -1 * (a - e)
	}

	return a - e
}

func main() {

	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	n := scanner.Text()

	_, _ = strconv.Atoi(n)
	scanner.Scan()
	actual := scanner.Text()
	scanner.Scan()
	expected := scanner.Text()

	actualNum, _ := strconv.Atoi(actual)
	expectedNum, _ := strconv.Atoi(expected)

	result := 0

	for actualNum > 0 && expectedNum > 0 {
		actDig, expDig := actualNum%10, expectedNum%10
		num1 := abs(actDig, expDig)

		if num1 < 5 {
			result += num1
		} else {
			if actDig > expDig {
				result += (expDig + 10) - actDig
			} else {
				result += (actDig + 10) - expDig
			}
		}

		actualNum /= 10
		expectedNum /= 10
	}

	fmt.Println(result)
}

package main

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

func main() {
	var n, s int
	var s1, s2 string
	in := bufio.NewReader(os.Stdin)
	fmt.Fscanf(in, "%d\n", &n)
	fmt.Fscanf(in, "%s\n", &s1)
	fmt.Fscanf(in, "%s\n", &s2)

	for i := int(0); i < n; i++ {
		current, _ := strconv.Atoi(string(s1[i]))
		key, _ := strconv.Atoi(string(s2[i]))
		result := math.Abs(float64(key) - float64(current))
		s += check(int(result), int(math.Abs(float64(key+current-10))))
	}
	fmt.Println(s)
}
func check(a int, b int) int {
	if a > b {
		return b
	} else {
		return a
	}
}

package main

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

func main() {
	var n int16
	var s uint16
	var s1, s2 string
	in := bufio.NewReader(os.Stdin)
	fmt.Fscanf(in, "%d\n", &n)
	fmt.Fscanf(in, "%s\n", &s1)
	fmt.Fscanf(in, "%s\n", &s2)

	for i := int16(0); i < n; i++ {
		current, _ := strconv.Atoi(string(s1[i]))
		key, _ := strconv.Atoi(string(s2[i]))
		result := math.Abs(float64(key) - float64(current))
		s += check(uint16(result), uint16(key)-10+uint16(current))
	}
	fmt.Println(s)
}
func check(a uint16, b uint16) uint16 {
	if a > b {
		return b
	} else {
		return a
	}
}

package main

import (
        "fmt"
)

func main() {
        var n, m int
        var s1, s2 string
        fmt.Scan(&n, &s1, &s2)
        for i, _ := range s1 {
                a := int(s1[i] - '0')
                b := int(s2[i] - '0')
                j := a
                k := 0
                for ; a != b && j != b; k++ {
                        if a == 10 {
                                a = 0
                        }
                        if j == -1 {
                                j = 9
                        }
                        a++
                        j--
                }
                m += k
        }
        fmt.Println(m)
}

// CombinationLock project main.go
package main

import (
	"fmt"
)

func main() {
	num_digit := 0
	state_original := 0
	state_comb := 0

	fmt.Scan(&num_digit)
	fmt.Scan(&state_original)
	fmt.Scan(&state_comb)

	sum_move := 0
	for state_original != 0 {
		original_remain := state_original % 10
		state_original = state_original / 10

		comb_remain := state_comb % 10
		state_comb = state_comb / 10

		if original_remain < comb_remain {
			tmp := original_remain
			original_remain = comb_remain
			comb_remain = tmp
		}

		if original_remain-comb_remain > 5 {
			comb_remain += 10
			original_remain *= -1
		} else {
			comb_remain *= -1
		}

		sum_remain := comb_remain + original_remain

		if sum_remain < 0 {
			sum_remain *= -1
		}
		sum_move += (sum_remain)

	}

	fmt.Printf("%d\n", sum_move)

}


You are given a simple connected undirected graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$.A vertex cover of a graph is a set of vertices such that each edge has at least one of its endpoints in the set.Let's call a lenient vertex cover such a vertex cover that at most one edge in it has both endpoints in the set.Find a lenient vertex cover of a graph or report that there is none. If there are multiple answers, then print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^6$$$; $$$n - 1 \le m \le \min(10^6, \frac{n \cdot (n - 1)}{2})$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the descriptions of the edges. For each testcase, the graph is connected and doesn't have multiple edges. The sum of $$$n$$$ over all testcases doesn't exceed $$$10^6$$$. The sum of $$$m$$$ over all testcases doesn't exceed $$$10^6$$$.

For each testcase, the first line should contain YES if a lenient vertex cover exists, and NO otherwise. If it exists, the second line should contain a binary string $$$s$$$ of length $$$n$$$, where $$$s_i = 1$$$ means that vertex $$$i$$$ is in the vertex cover, and $$$s_i = 0$$$ means that vertex $$$i$$$ isn't. If there are multiple answers, then print any of them.

NoteHere are the graphs from the first example. The vertices in the lenient vertex covers are marked red.

package main

import (
	"bufio"
	"flag"
	"fmt"
	"io"
	"log"
	"math/big"
	"os"
	"runtime/pprof"
)

type Graph struct {
	g [][]int

	used   []int
	parity []int
}

func NewGraph(n int) *Graph {
	return &Graph{
		g:      make([][]int, n),
		used:   make([]int, n),
		parity: make([]int, n),
	}
}

func (g *Graph) clear() {
	for i := range g.used {
		g.used[i] = 0
	}
}

func (g *Graph) addEdge(u, v int) {
	g.g[u] = append(g.g[u], v)
	g.g[v] = append(g.g[v], u)
}

func (g *Graph) dfs(v int, p int, totalBad int, F *int, T *int) (int, int) {
	g.used[v] = 1
	if p != -1 {
		g.parity[v] = g.parity[p] ^ 1
	}

	bad, good := 0, 0

	for _, to := range g.g[v] {
		if to == p {
			continue
		}

		if g.used[to] == 2 {
			if g.parity[to] == g.parity[v] {
				bad -= 1
			} else {
				good -= 1
			}
		} else if g.used[to] == 1 {
			if g.parity[to] == g.parity[v] {
				bad += 1
			} else {
				good += 1
			}
		} else {
			nbad, ngood := g.dfs(to, v, totalBad, F, T)

			if nbad == totalBad && ngood == 0 {
				*F = v
				*T = to
			}

			bad += nbad
			good += ngood
		}

	}

	g.used[v] = 2

	return bad, good
}

func (g *Graph) dfs2(v int, p int, c int, F *int, T *int) (int, int) {
	g.used[v] = 1
	g.parity[v] = c

	bad, good := 0, 0

	for _, to := range g.g[v] {
		if to == p {
			continue
		}

		if g.used[to] == 2 {
			continue
		} else if g.used[to] == 1 {
			if g.parity[to] == g.parity[v] {
				*F = v
				*T = to

				bad += 1
			} else {
				good += 1
			}
		} else {
			nbad, ngood := g.dfs2(to, v, c^1, F, T)

			bad += nbad
			good += ngood
		}

	}

	g.used[v] = 2

	return bad, good
}

func solve() {
	n := NextInt()
	m := NextInt()

	g := NewGraph(n)

	for i := 0; i < m; i++ {
		u := NextInt() - 1
		v := NextInt() - 1

		g.addEdge(u, v)
	}

	F, T := -1, -1

	bad, _ := g.dfs2(0, -1, 0, &F, &T)
	g.clear()

	if bad == 0 {
		println("YES")
		for i := range g.parity {
			printf("%d", g.parity[i]^1)
		}
		printf("\n")
	} else if bad == 1 {
		g.used[T] = 2
		g.dfs2(F, T, 0, nil, nil)
		g.dfs2(T, F, 0, nil, nil)

		println("YES")
		for i := range g.parity {
			printf("%d", g.parity[i]^1)
		}
		printf("\n")
	} else {
		F, T = -1, -1
		g.dfs(0, -1, bad, &F, &T)

		if F == -1 {
			println("NO")
			return
		}
		g.clear()

		g.used[T] = 2
		g.dfs2(F, T, 0, nil, nil)
		g.dfs2(T, F, 0, nil, nil)

		println("YES")
		for i := range g.parity {
			printf("%d", g.parity[i]^1)
		}
		printf("\n")
	}

}

func main() {
	defer writer.Flush()

	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	T := NextInt()

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

var reader *bufio.Reader
var writer *bufio.Writer

var inputFile = flag.String("input", "", "")
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")

func init() {
	flag.Parse()

	var i io.Reader
	if *inputFile != "" {
		i, _ = os.Open(*inputFile)
	} else {
		i = os.Stdin
	}
	reader = bufio.NewReaderSize(i, 1<<20)
	writer = bufio.NewWriterSize(os.Stdout, 1<<20)
}

func println(a ...interface{}) {
	_, _ = fmt.Fprintln(writer, a...)
}

func printf(format string, a ...interface{}) {
	_, _ = fmt.Fprintf(writer, format, a...)
}

func scanf(format string, a ...interface{}) {
	_, _ = fmt.Fscanf(reader, format, a...)
}

func scan(a interface{}) {
	_, _ = fmt.Fscan(reader, a)
}

func NextInt64() int64 {
	var res int64
	scan(&res)
	return res
}

func NextInt() int {
	var res int
	scan(&res)
	return res
}

func NextIntArray(n int) []int {
	res := make([]int, n)
	for i := range res {
		scan(&res[i])
	}
	return res
}

func NextInt64Array(n int) []int64 {
	res := make([]int64, n)
	for i := range res {
		scan(&res[i])
	}
	return res
}

func NextString() string {
	var res string
	scan(&res)
	return res
}

func NextBigInt() *big.Int {
	n := new(big.Int)
	n, _ = n.SetString(NextString(), 10)
	return n
}

func AbsInt64(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

func MinInt64(x, y int64) int64 {
	if x < y {
		return x
	}
	return y
}

func MaxInt64(x, y int64) int64 {
	if x > y {
		return x
	}
	return y
}

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

package main

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

func acc(op func(int, int) int, c ...int) int {
	res := c[0]
	for _, i := range c {
		res = op(res, i)
	}
	return res
}

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

func min(c ...int) int {
	return acc(func(a int, b int) int {
		if a > b {
			return b
		}
		return a
	}, c...)
}

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

func btoI(a bool) int {
	if a {
		return 1
	}
	return 0
}

type State struct {
	fa, dep int
}

type Record struct {
	node int
	State
}

type VDSU struct {
	state []State
	rcd   []Record
}

func (dsu *VDSU) initialize(n int) {
	dsu.state = make([]State, n+1)
	for i, _ := range dsu.state {
		dsu.state[i] = State{i, 0}
	}
}

func (dsu *VDSU) getTime() int { return len(dsu.rcd) }
func (dsu *VDSU) reserve(time int) {
	rcdlen := len(dsu.rcd)
	for rcdlen > time {
		rcdlen--
		dsu.state[dsu.rcd[rcdlen].node] = dsu.rcd[rcdlen].State
		dsu.rcd = dsu.rcd[:rcdlen]
	}
}
func (dsu *VDSU) getfa(v int) int {
	if dsu.state[v].fa == v {
		return v
	}
	return dsu.getfa(dsu.state[v].fa)
}
func (dsu *VDSU) merge(u, v int) bool {
	u, v = dsu.getfa(u), dsu.getfa(v)
	if u == v {
		return false
	}
	if dsu.state[u].dep > dsu.state[v].dep {
		u, v = v, u
	}
	dsu.rcd = append(dsu.rcd, Record{v, dsu.state[v]})
	dsu.rcd = append(dsu.rcd, Record{u, dsu.state[u]})
	dsu.state[u].fa = v
	dsu.state[v].dep = max(dsu.state[v].dep, dsu.state[u].dep+1)
	return true
}
func (dsu *VDSU) same(u, v int) bool {
	return dsu.getfa(u) == dsu.getfa(v)
}

type Edge struct {
	u, v int
}

var dsu VDSU

func tryMerge(l, r int, edges []Edge) bool {
	for i := l; i <= r; i++ {
		u, v := edges[i].u, edges[i].v
		dsu.merge(u<<1, v<<1|1)
		dsu.merge(u<<1|1, v<<1)
		if dsu.same(u<<1, u<<1|1) {
			return false
		}
	}
	return true
}

func dfs(left, right int, edges []Edge) bool {
	if left == right {
		u, v := edges[left].u, edges[left].v

		if dsu.same(u<<1, v<<1|1) || dsu.same(u<<1, v<<1) {
			dsu.merge(u<<1, 1)
		} else {
			dsu.merge(u<<1, 1)
			dsu.merge(v<<1, 1)
		}
		return true
	}
	mid := (left + right) >> 1
	t := dsu.getTime()
	flag := tryMerge(mid+1, right, edges)
	if flag && dfs(left, mid, edges) {
		return true
	}
	dsu.reserve(t)
	t = dsu.getTime()
	if tryMerge(left, mid, edges) && dfs(mid+1, right, edges) {
		return true
	}

	dsu.reserve(t)
	return false
}

func solve(inout io.ReadWriter) {
	scan := func(inp ...interface{}) {
		fmt.Fscan(inout, inp...)
	}
	printf := func(format string, outp ...interface{}) {
		fmt.Fprintf(inout, format, outp...)
	}
	var n, m int
	scan(&n, &m)

	dsu.initialize(n<<1 | 1)
	edges := make([]Edge, m)

	for i := 0; i < m; i++ {
		scan(&edges[i].u, &edges[i].v)
	}

	if dfs(0, m-1, edges) {
		printf("YES\n")
		ans := make([]rune, n+1)
		for i := 1; i <= n; i++ {
			if dsu.same(i<<1, 1) {
				ans[i-1] = '1'
			} else if dsu.same(i<<1|1, 1) {
				ans[i-1] = '0'
			} else {
				dsu.merge(i<<1, 1)
				ans[i-1] = '1'
			}
		}
		ans[n] = '\n'
		printf(string(ans))

	} else {
		printf("NO\n")
	}

}

func main() {

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

	var T int = 1
	fmt.Fscan(inout, &T)
	for ; T > 0; T-- {
		solve(inout)
	}
}

package main

import (
	"bufio"
	"flag"
	"fmt"
	"io"
	"math/big"
	"os"
)

type DSU struct {
	ptrs []*int
	vals []int

	p      []int
	sz     []int
	parity []int

	isBipartite int
}

func NewDSU(n int) *DSU {
	res := DSU{
		ptrs:        nil,
		vals:        nil,
		p:           make([]int, n),
		sz:          make([]int, n),
		parity:      make([]int, n),
		isBipartite: 1,
	}

	for i := 0; i < n; i++ {
		res.p[i] = i
		res.sz[i] = i
	}

	return &res
}

func (d *DSU) get(v int) (int, int) {
	if d.p[v] != v {
		par, res := d.get(d.p[v])
		return d.parity[v] ^ par, res
	}

	return 0, v
}

func (d *DSU) set(ptr *int, val int) {
	d.ptrs = append(d.ptrs, ptr)
	d.vals = append(d.vals, *ptr)

	*ptr = val
}

func (d *DSU) revert(version int) {
	for len(d.ptrs) > version {
		nlen := len(d.ptrs) - 1
		*d.ptrs[nlen] = d.vals[nlen]
		d.ptrs, d.vals = d.ptrs[:nlen], d.vals[:nlen]
	}
}

func (d *DSU) unite(a, b int) {
	pa, a := d.get(a)
	pb, b := d.get(b)
	if a == b {
		if pa == pb {
			d.set(&d.isBipartite, 0)
		}
		return
	}

	if d.sz[a] > d.sz[b] {
		a, b = b, a
	}

	d.set(&d.p[a], b)
	d.set(&d.parity[a], pa^pb^1)
	d.set(&d.sz[b], d.sz[a]+d.sz[b])
}

type Query struct {
	tp int
	l  int
	r  int
	u  int
	v  int
}

func doProcess(dsu *DSU, queries []Query, left, right int, answer []int) {
	if right-left == 1 {
		version := len(dsu.ptrs)

		for _, q := range queries {
			if q.tp == 1 {
				if q.l <= left && q.r >= right {
					dsu.unite(q.u, q.v)
				}
			}
		}

		for _, q := range queries {
			if q.tp == 0 && q.l == left && dsu.isBipartite == 1 {
				if answer[0] == -1 {
					//println("OK", q.l)
					//for i := range dsu.p {
					//	parity, parent := dsu.get(i)
					//	println(i, parity, parent)
					//}
					for i := range dsu.p {
						p, _ := dsu.get(i)
						if p == 0 {
							answer[i] = 1
						} else {
							answer[i] = 0
						}
					}
				}
			}
		}

		dsu.revert(version)
		return
	}

	version := len(dsu.ptrs)
	var nqueries []Query

	for _, q := range queries {
		if q.tp == 1 && q.l <= left && q.r >= right {
			dsu.unite(q.u, q.v)
			continue
		}

		if q.tp == 0 && q.l >= left && q.r <= right {
			nqueries = append(nqueries, q)
		}

		if q.tp == 1 && q.l < right && q.r > left {
			nqueries = append(nqueries, q)
		}
	}

	mid := (left + right) / 2
	doProcess(dsu, nqueries, left, mid, answer)
	doProcess(dsu, nqueries, mid, right, answer)

	dsu.revert(version)
}

type Edge struct {
	u int
	v int
}

func solve() {
	n := NextInt()
	m := NextInt()

	dsu := NewDSU(n)

	edges := make([]Edge, m)
	for i := 0; i < m; i++ {
		edges[i].u = NextInt() - 1
		edges[i].v = NextInt() - 1
	}

	queries := make([]Query, 0, 2*m)
	for i := 0; i < m; i++ {
		queries = append(queries, Query{
			tp: 1,
			l:  0,
			r:  i,
			u:  edges[i].u,
			v:  edges[i].v,
		})

		queries = append(queries, Query{
			tp: 0,
			l:  i,
			r:  i + 1,
		})

		queries = append(queries, Query{
			tp: 1,
			l:  i + 1,
			r:  m,
			u:  edges[i].u,
			v:  edges[i].v,
		})
	}

	answer := make([]int, n)
	answer[0] = -1

	doProcess(dsu, queries, 0, m, answer)
	if answer[0] != -1 {
		println("YES")
		for i := range answer {
			printf("%d", answer[i])
		}
		println()
	} else {
		println("NO")
	}
}

func main() {
	defer writer.Flush()

	T := NextInt()

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

var reader *bufio.Reader
var writer *bufio.Writer

var inputFile = flag.String("input", "", "")

func init() {
	flag.Parse()
	var i io.Reader
	if *inputFile != "" {
		i, _ = os.Open(*inputFile)
	} else {
		i = os.Stdin
	}
	reader = bufio.NewReaderSize(i, 1<<20)
	writer = bufio.NewWriterSize(os.Stdout, 1<<20)
}

func println(a ...interface{}) {
	_, _ = fmt.Fprintln(writer, a...)
}

func printf(format string, a ...interface{}) {
	_, _ = fmt.Fprintf(writer, format, a...)
}

func scanf(format string, a ...interface{}) {
	_, _ = fmt.Fscanf(reader, format, a...)
}

func scan(a interface{}) {
	_, _ = fmt.Fscan(reader, a)
}

func NextInt64() int64 {
	var res int64
	scan(&res)
	return res
}

func NextInt() int {
	var res int
	scan(&res)
	return res
}

func NextIntArray(n int) []int {
	res := make([]int, n)
	for i := range res {
		scan(&res[i])
	}
	return res
}

func NextInt64Array(n int) []int64 {
	res := make([]int64, n)
	for i := range res {
		scan(&res[i])
	}
	return res
}

func NextString() string {
	var res string
	scan(&res)
	return res
}

func NextBigInt() *big.Int {
	n := new(big.Int)
	n, _ = n.SetString(NextString(), 10)
	return n
}

func AbsInt64(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

func MinInt64(x, y int64) int64 {
	if x < y {
		return x
	}
	return y
}

func MaxInt64(x, y int64) int64 {
	if x > y {
		return x
	}
	return y
}

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

package main

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

func acc(op func(int, int) int, c ...int) int {
	res := c[0]
	for _, i := range c {
		res = op(res, i)
	}
	return res
}

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

func min(c ...int) int {
	return acc(func(a int, b int) int {
		if a > b {
			return b
		}
		return a
	}, c...)
}

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

func btoI(a bool) int {
	if a {
		return 1
	}
	return 0
}

type State struct {
	fa, dep int
}

type Record struct {
	node int
	State
}

type VDSU struct {
	state []State
	rcd   []Record
}

func (dsu *VDSU) initialize(n int) {
	dsu.state = make([]State, n+1)
	for i, _ := range dsu.state {
		dsu.state[i] = State{i, 0}
	}
}

func (dsu *VDSU) getTime() int { return len(dsu.rcd) }
func (dsu *VDSU) reserve(time int) {
	rcdlen := len(dsu.rcd)
	for rcdlen > time {
		rcdlen--
		dsu.state[dsu.rcd[rcdlen].node] = dsu.rcd[rcdlen].State
		dsu.rcd = dsu.rcd[:rcdlen]
	}
}
func (dsu *VDSU) getfa(v int) int {
	if dsu.state[v].fa == v {
		return v
	}
	return dsu.getfa(dsu.state[v].fa)
}
func (dsu *VDSU) merge(u, v int) bool {
	u, v = dsu.getfa(u), dsu.getfa(v)
	if u == v {
		return false
	}
	if dsu.state[u].dep > dsu.state[v].dep {
		u, v = v, u
	}
	dsu.rcd = append(dsu.rcd, Record{v, dsu.state[v]})
	dsu.rcd = append(dsu.rcd, Record{u, dsu.state[u]})
	dsu.state[u].fa = v
	dsu.state[v].dep = max(dsu.state[v].dep, dsu.state[u].dep+1)
	return true
}
func (dsu *VDSU) same(u, v int) bool {
	return dsu.getfa(u) == dsu.getfa(v)
}

type Edge struct {
	u, v int
}

var dsu VDSU

func tryMerge(l, r int, edges []Edge) bool {
	for i := l; i <= r; i++ {
		u, v := edges[i].u, edges[i].v
		dsu.merge(u<<1, v<<1|1)
		dsu.merge(u<<1|1, v<<1)
		if dsu.same(u<<1, u<<1|1) {
			return false
		}
	}
	return true
}

func dfs(left, right int, edges []Edge) bool {
	if left == right {
		u, v := edges[left].u, edges[left].v

		if dsu.same(u<<1, v<<1|1) || dsu.same(u<<1, v<<1) {
			dsu.merge(u<<1, 1)
		} else {
			dsu.merge(u<<1, 1)
			dsu.merge(v<<1, 1)
		}
		return true
	}
	mid := (left + right) >> 1
	t := dsu.getTime()
	flag := tryMerge(mid+1, right, edges)
	if flag && dfs(left, mid, edges) {
		return true
	}
	dsu.reserve(t)
	t = dsu.getTime()
	if tryMerge(left, mid, edges) && dfs(mid+1, right, edges) {
		return true
	}

	dsu.reserve(t)
	return false
}

func solve(inout io.ReadWriter) {
	scan := func(inp ...interface{}) {
		fmt.Fscan(inout, inp...)
	}
	printf := func(format string, outp ...interface{}) {
		fmt.Fprintf(inout, format, outp...)
	}
	var n, m int
	scan(&n, &m)

	dsu.initialize(n<<1 | 1)
	edges := make([]Edge, m)

	for i := 0; i < m; i++ {
		scan(&edges[i].u, &edges[i].v)
	}

	if dfs(0, m-1, edges) {
		printf("YES\n")
		ans := make([]rune, n+2)
		for i := 1; i <= n; i++ {
			if dsu.same(i<<1, 1) {
				ans[i-1] = '1'
			} else if dsu.same(i<<1|1, 1) {
				ans[i-1] = '0'
			} else {
				dsu.merge(i<<1, 1)
				ans[i-1] = '1'
			}
		}
		ans[n] = '\n'
		ans[n+1] = 0
		printf(string(ans))

	} else {
		printf("NO\n")
	}

}

func main() {

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

	var T int = 1
	fmt.Fscan(inout, &T)
	for ; T > 0; T-- {
		solve(inout)
	}
}

package main

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

func acc(op func(int, int) int, c ...int) int {
	res := c[0]
	for _, i := range c {
		res = op(res, i)
	}
	return res
}

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

func min(c ...int) int {
	return acc(func(a int, b int) int {
		if a > b {
			return b
		}
		return a
	}, c...)
}

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

func btoI(a bool) int {
	if a {
		return 1
	}
	return 0
}

type State struct {
	fa, dep int
}

type Record struct {
	node int
	State
}

type VDSU struct {
	state []State
	rcd   []Record
}

func (dsu *VDSU) initialize(n int) {
	dsu.state = make([]State, n+1)
	for i, _ := range dsu.state {
		dsu.state[i] = State{i, 0}
	}
}

func (dsu *VDSU) getTime() int { return len(dsu.rcd) }
func (dsu *VDSU) reserve(time int) {
	rcdlen := len(dsu.rcd)
	for rcdlen > time {
		rcdlen--
		dsu.state[dsu.rcd[rcdlen].node] = dsu.rcd[rcdlen].State
		dsu.rcd = dsu.rcd[:rcdlen]
	}
}
func (dsu *VDSU) getfa(v int) int {
	if dsu.state[v].fa == v {
		return v
	}
	return dsu.getfa(dsu.state[v].fa)
}
func (dsu *VDSU) merge(u, v int) bool {
	u, v = dsu.getfa(u), dsu.getfa(v)
	if u == v {
		return false
	}
	if dsu.state[u].dep > dsu.state[v].dep {
		u, v = v, u
	}
	dsu.rcd = append(dsu.rcd, Record{v, dsu.state[v]})
	dsu.rcd = append(dsu.rcd, Record{u, dsu.state[u]})
	dsu.state[u].fa = v
	dsu.state[v].dep = max(dsu.state[v].dep, dsu.state[u].dep+1)
	return true
}
func (dsu *VDSU) same(u, v int) bool {
	return dsu.getfa(u) == dsu.getfa(v)
}

type Edge struct {
	u, v int
}

var dsu VDSU

func tryMerge(l, r int, edges []Edge) bool {
	for i := l; i <= r; i++ {
		u, v := edges[i].u, edges[i].v
		dsu.merge(u<<1, v<<1|1)
		dsu.merge(u<<1|1, v<<1)
		if dsu.same(u<<1, u<<1|1) {
			return false
		}
	}
	return true
}

func dfs(left, right int, edges []Edge) bool {
	if left == right {
		u, v := edges[left].u, edges[left].v

		if dsu.same(u<<1, v<<1|1) || dsu.same(u<<1, v<<1) {
			dsu.merge(u<<1, 1)
		} else {
			dsu.merge(u<<1, 1)
			dsu.merge(v<<1, 1)
		}
		return true
	}
	mid := (left + right) >> 1
	t := dsu.getTime()
	flag := tryMerge(mid+1, right, edges)
	if flag && dfs(left, mid, edges) {
		return true
	}
	dsu.reserve(t)
	t = dsu.getTime()
	if tryMerge(left, mid, edges) && dfs(mid+1, right, edges) {
		return true
	}

	dsu.reserve(t)
	return false
}

func solve(inout io.ReadWriter) {
	scan := func(inp ...interface{}) {
		fmt.Fscan(inout, inp...)
	}
	printf := func(format string, outp ...interface{}) {
		fmt.Fprintf(inout, format, outp...)
	}
	var n, m int
	scan(&n, &m)

	dsu.initialize(n<<1 | 1)
	edges := make([]Edge, m)

	for i := 0; i < m; i++ {
		scan(&edges[i].u, &edges[i].v)
	}

	if dfs(0, m-1, edges) {
		printf("YES\n")
		ans := make([]rune, n+2)
		for i := 1; i <= n; i++ {
			if dsu.same(i<<1, 1) {
				ans[i-1] = '1'
			} else if dsu.same(i<<1|1, 1) {
				ans[i-1] = '0'
			} else {
				dsu.merge(i<<1, 1)
				ans[i-1] = '1'
			}
		}
		ans[n] = '\n'
		ans[n+1] = 0
		printf(string(ans))

	} else {
		printf("NO")
	}

}

func main() {

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

	var T int = 1
	fmt.Fscan(inout, &T)
	for ; T > 0; T-- {
		solve(inout)
	}
}

package main

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

func acc(op func(int, int) int, c ...int) int {
	res := c[0]
	for _, i := range c {
		res = op(res, i)
	}
	return res
}

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

func min(c ...int) int {
	return acc(func(a int, b int) int {
		if a > b {
			return b
		}
		return a
	}, c...)
}

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

func btoI(a bool) int {
	if a {
		return 1
	}
	return 0
}

type State struct {
	fa, dep int
}

type Record struct {
	node int
	State
}

type VDSU struct {
	state []State
	rcd   []Record
}

func (dsu *VDSU) initialize(n int) {
	dsu.state = make([]State, n+1)
	for i, _ := range dsu.state {
		dsu.state[i] = State{i, 0}
	}
}

func (dsu *VDSU) getTime() int { return len(dsu.rcd) }
func (dsu *VDSU) reserve(time int) {
	rcdlen := len(dsu.rcd)
	for rcdlen > time {
		rcdlen--
		dsu.state[dsu.rcd[rcdlen].node] = dsu.rcd[rcdlen].State
		dsu.rcd = dsu.rcd[:rcdlen]
	}
}
func (dsu *VDSU) getfa(v int) int {
	if dsu.state[v].fa == v {
		return v
	}
	return dsu.getfa(dsu.state[v].fa)
}
func (dsu *VDSU) merge(u, v int) bool {
	u, v = dsu.getfa(u), dsu.getfa(v)
	if u == v {
		return false
	}
	if dsu.state[u].dep > dsu.state[v].dep {
		u, v = v, u
	}
	dsu.rcd = append(dsu.rcd, Record{v, dsu.state[v]})
	dsu.rcd = append(dsu.rcd, Record{u, dsu.state[u]})
	dsu.state[u].fa = v
	dsu.state[v].dep = max(dsu.state[v].dep, dsu.state[u].dep+1)
	return true
}
func (dsu *VDSU) same(u, v int) bool {
	return dsu.getfa(u) == dsu.getfa(v)
}

type Edge struct {
	u, v int
}

var dsu VDSU

func tryMerge(l, r int, edges []Edge) bool {
	for i := l; i <= r; i++ {
		u, v := edges[i].u, edges[i].v
		dsu.merge(u<<1, v<<1|1)
		dsu.merge(u<<1|1, v<<1)
		if dsu.same(u<<1, u<<1|1) {
			return false
		}
	}
	return true
}

func dfs(left, right int, edges []Edge) bool {
	if left == right {
		u, v := edges[left].u, edges[left].v

		if dsu.same(u<<1, v<<1|1) || dsu.same(u<<1, v<<1) {
			dsu.merge(u<<1, 1)
		} else {
			dsu.merge(u<<1, 1)
			dsu.merge(v<<1, 1)
		}
		return true
	}
	mid := (left + right) >> 1
	t := dsu.getTime()
	flag := tryMerge(mid+1, right, edges)
	if flag && dfs(left, mid, edges) {
		return true
	}
	dsu.reserve(t)
	t = dsu.getTime()
	if tryMerge(left, mid, edges) && dfs(mid+1, right, edges) {
		return true
	}

	dsu.reserve(t)
	return false
}

func solve(inout io.ReadWriter) {
	scan := func(inp ...interface{}) {
		fmt.Fscan(inout, inp...)
	}
	printf := func(format string, outp ...interface{}) {
		fmt.Fprintf(inout, format, outp...)
	}
	var n, m int
	scan(&n, &m)

	dsu.initialize(n<<1 | 1)
	edges := make([]Edge, m)

	for i := 0; i < m; i++ {
		scan(&edges[i].u, &edges[i].v)
	}

	if dfs(0, m-1, edges) {
		printf("YES\n")
		ans := make([]rune, n+2)
		for i := 1; i <= n; i++ {
			if dsu.same(i<<1, 1) {
				ans[i-1] = '1'
			} else if dsu.same(i<<1|1, 1) {
				ans[i-1] = '0'
			} else {
				dsu.merge(i<<1, 1)
				ans[i-1] = '2'
			}
		}
		ans[n] = '\n'
		ans[n+1] = 0
		printf(string(ans))

	} else {
		printf("NO")
	}

}

func main() {

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

	var T int = 1
	fmt.Fscan(inout, &T)
	for ; T > 0; T-- {
		solve(inout)
	}
}


It has been noted that if some ants are put in the junctions of the graphene integer lattice then they will act in the following fashion: every minute at each junction (x, y) containing at least four ants a group of four ants will be formed, and these four ants will scatter to the neighbouring junctions (x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1) — one ant in each direction. No other ant movements will happen. Ants never interfere with each other.Scientists have put a colony of n ants into the junction (0, 0) and now they wish to know how many ants will there be at some given junctions, when the movement of the ants stops.

First input line contains integers n (0 ≤ n ≤ 30000) and t (1 ≤ t ≤ 50000), where n is the number of ants in the colony and t is the number of queries. Each of the next t lines contains coordinates of a query junction: integers xi, yi ( - 109 ≤ xi, yi ≤ 109). Queries may coincide. It is guaranteed that there will be a certain moment of time when no possible movements can happen (in other words, the process will eventually end).

Print t integers, one per line — the number of ants at the corresponding junctions when the movement of the ants stops.

NoteIn the first sample the colony consists of the one ant, so nothing happens at all.In the second sample the colony consists of 6 ants. At the first minute 4 ants scatter from (0, 0) to the neighbouring junctions. After that the process stops.

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

type point struct {
	x, y int
}

func (p point) move(dx, dy int) point {
	return point{p.x + dx, p.y + dy}
}

const max = 100
const max2 = max*2 + 2

var dx = [4]int{-1, 0, 1, 0}
var dy = [4]int{0, -1, 0, 1}

var m [max2][max2]int
var f [max2][max2]bool
var origin = point{x: max + 1, y: max + 1}

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

func set(p point, v int) {
	m[p.x][p.y] = v
}

func get(p point) int {
	return m[p.x][p.y]
}

var queue = make([]point, 0)

func add(p point) {
	queue = append(queue, p)
	f[p.x][p.y] = true
}

func pop() point {
	res := queue[0]
	f[res.x][res.y] = false
	queue = queue[1:]
	return res
}

func bfs() {

	for len(queue) > 0 {
		p := pop()
		temp := get(p) / 4
		set(p, get(p)%4)
		for i := range dx {
			nP := p.move(dx[i], dy[i])
			set(nP, get(nP)+temp)
			if get(nP) >= 4 && !f[nP.x][nP.y] {
				add(nP)
			}
		}
	}
}

func main() {

	defer writer.Flush()
	var n, t int
	scanf("%d%d\n", &n, &t)
	set(origin, n)
	add(origin)
	bfs()
	var x, y int
	for i := 0; i < t; i++ {
		scanf("%d%d\n", &x, &y)
		if abs(x) >= max || abs(y) >= max {
			printf("%d\n", 0)
			continue
		}
		np := origin.move(x, y)
		printf("%d\n", get(np))
	}
}

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

type point struct {
	x, y int
}

func (p point) move(dx, dy int) point {
	return point{p.x + dx, p.y + dy}
}

const max = 100
const max2 = max*2 + 1

var dx = [4]int{-1, 0, 1, 0}
var dy = [4]int{0, -1, 0, 1}

var m [max2][max2]int
var f [max2][max2]bool
var origin = point{x: max + 1, y: max + 1}

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

func set(p point, v int) {
	m[p.x][p.y] = v
}

func get(p point) int {
	return m[p.x][p.y]
}

var queue = make([]point, 0)

func add(p point) {
	queue = append(queue, p)
	f[p.x][p.y] = true
}

func pop() point {
	res := queue[0]
	f[res.x][res.y] = false
	queue = queue[1:]
	return res
}

func bfs() {

	for len(queue) > 0 {
		p := pop()
		temp := get(p) / 4
		set(p, get(p)%4)
		for i := range dx {
			nP := p.move(dx[i], dy[i])
			set(nP, get(nP)+temp)
			if get(nP) >= 4 && !f[nP.x][nP.y] {
				add(nP)
			}
		}
	}
}

func main() {

	defer writer.Flush()
	var n, t int
	scanf("%d%d\n", &n, &t)
	set(origin, n)
	add(origin)
	bfs()
	var x, y int
	for i := 0; i < t; i++ {
		scanf("%d%d\n", &x, &y)
		if abs(x) > max || abs(y) > max {
			fmt.Println(0)
			continue
		}
		np := origin.move(x, y)
		println(get(np))
	}
}


Polycarp lives on the coordinate axis $$$Ox$$$ and travels from the point $$$x=a$$$ to $$$x=b$$$. It moves uniformly rectilinearly at a speed of one unit of distance per minute.On the axis $$$Ox$$$ at the point $$$x=c$$$ the base station of the mobile operator is placed. It is known that the radius of its coverage is $$$r$$$. Thus, if Polycarp is at a distance less than or equal to $$$r$$$ from the point $$$x=c$$$, then he is in the network coverage area, otherwise — no. The base station can be located both on the route of Polycarp and outside it.Print the time in minutes during which Polycarp will not be in the coverage area of the network, with a rectilinear uniform movement from $$$x=a$$$ to $$$x=b$$$. His speed — one unit of distance per minute.

The first line contains a positive integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. In the following lines are written $$$t$$$ test cases. The description of each test case is one line, which contains four integers $$$a$$$, $$$b$$$, $$$c$$$ and $$$r$$$ ($$$-10^8 \le a,b,c \le 10^8$$$, $$$0 \le r \le 10^8$$$) — the coordinates of the starting and ending points of the path, the base station, and its coverage radius, respectively. Any of the numbers $$$a$$$, $$$b$$$ and $$$c$$$ can be equal (either any pair or all three numbers). The base station can be located both on the route of Polycarp and outside it.

Print $$$t$$$ numbers — answers to given test cases in the order they are written in the test. Each answer is an integer — the number of minutes during which Polycarp will be unavailable during his movement.

NoteThe following picture illustrates the first test case.     Polycarp goes from $$$1$$$ to $$$10$$$. The yellow area shows the coverage area of the station with a radius of coverage of $$$1$$$, which is located at the point of $$$7$$$. The green area shows a part of the path when Polycarp is out of coverage area.

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := int64(1)
	fmt.Fscanf(in, "%d\n", &t)
	for test := int64(0); test < t ; test++ {
		a, b, c, r := 0, 0, 0, 0
		fmt.Fscanf(in, "%d %d %d %d\n", &a, &b, &c, &r)
		if a > b {
			a, b = b, a
		}
		lo := c - r
		hi := c + r
		ans := 0
		if lo >= b || hi <= a {
			ans = b - a
		} else {
			if lo > a {
				ans = lo - a
			}
			if hi < b {
				ans += b - hi
			}
		}
		fmt.Fprintf(out, "%d\n", ans)
	}
}

package main
import (
    "fmt"
)

func main() {
    var t int
    fmt.Scan(&t)
    for i := 0; i < t; i++ {
        var a, b, c, r int
        fmt.Scan(&a, &b, &c, &r)
        d := c + r
        c = c - r
        if a > b {
            a, b = b, a
        }
        if a == b {
            fmt.Println(0)
            continue
        }
        if d <= a || b <= c {
            fmt.Println(b-a)
            continue
        }
        ans := 0
        if a <= c && c <= b {
            ans += c - a
        }
        if a <= d && d <= b {
            ans += b - d
        }
        fmt.Println(ans)
    }
}

package main

import "fmt"

func calculateTime(a, b, c, r int) int {
	if a > b {
		a, b = b, a
	}

	path := b - a

	cLeft := c - r
	cRight := c + r
	if cRight < a {
		return path
	}
	if cLeft <= a && a <= cRight {
		if path-cRight+a > 0 {
			return path - cRight + a
		}

	}
	if cLeft > a {
		if cRight < b {
			return path - 2*r
		}
		if cLeft <= b && b <= cRight {
			if path-b+cLeft > 0 {
				return path - b + cLeft
			}
		}
		if cLeft > b {
			return path
		}
	}
	return 0
}

func main() {
	var n int
	fmt.Scan(&n)
	for i := 0; i < n; i++ {
		var a, b, c, r int
		fmt.Scan(&a, &b, &c, &r)
		time := calculateTime(a, b, c, r)
		fmt.Println(time)
	}
}

package main

import (
	"fmt"
)

func main() {
	var t int
	fmt.Scanf("%d\n", &t)
	for i := 0; i < t; i++ {
		var a, b, c, r int
		fmt.Scanf("%d %d %d %d\n", &a, &b, &c, &r)

		cl := c - r
		cr := c + r

		if a > b {
			a, b = b, a
		}

		if cr <= a {
			fmt.Println(b - a)
		} else if cl >= b {
			fmt.Println(b - a)
		} else if cl <= a && cr >= b {
			fmt.Println(0)
		} else if cl < a && cr > a {
			fmt.Println(b - cr)
		} else if cl < b && cr > b {
			fmt.Println(cl - a)
		} else {
			fmt.Println((cl - a) + (b - cr))
		}
	}
}

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
}

// Strtoi is a wrapper of strconv.Atoi().
// If strconv.Atoi() returns an error, Strtoi calls panic.
func Strtoi(s string) int {
	if i, err := strconv.Atoi(s); err != nil {
		panic(errors.New("[argument error]: Strtoi only accepts integer string"))
	} else {
		return i
	}
}

// PrintIntsLine returns integers string delimited by a space.
func PrintIntsLine(A ...int) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// PrintIntsLine returns integers string delimited by a space.
func PrintInts64Line(A ...int64) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.FormatInt(A[i], 10) // 64bit int version
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

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

/********** FAU standard libraries **********/

//fmt.Sprintf("%b\n", 255) 	// binary expression

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

//str := ReadString()
//i := ReadInt()
//X := ReadIntSlice(n)
//S := ReadRuneSlice()
//a := ReadFloat64()
//A := ReadFloat64Slice(n)

//str := ZeroPaddingRuneSlice(num, 32)
//str := PrintIntsLine(X...)

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

const MOD = 1000000000 + 7
const ALPHABET_NUM = 26
const INF_INT64 = math.MaxInt64
const INF_BIT60 = 1 << 60
const INF_INT32 = math.MaxInt32
const INF_BIT30 = 1 << 30

var t int
var a, b, c, r int

func main() {
	t = ReadInt()

	for tc := 0; tc < t; tc++ {
		a, b, c, r = ReadInt4()

		solve()
	}
}

func solve() {
	if a > b {
		a, b = b, a
	}

	left, right := c-r, c+r

	if b <= left || a >= right {
		fmt.Println(b - a)
	} else if a <= left && right <= b {
		fmt.Println(b - a - (right - left))
	} else if (a <= right && right <= b) && !(a <= left && left <= b) {
		fmt.Println(Max(0, b-right))
	} else {
		fmt.Println(Max(0, left-a))
	}
}

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

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

/*
ASCII code

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

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

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := int64(1)
	fmt.Fscanf(in, "%d\n", &t)
	for tt := int64(0); tt < t; tt++ {
		a, b, c, r := 0, 0, 0, 0
		fmt.Fscanf(in, "%d %d %d %d\n", &a, &b, &c, &r)
		if a > b {
			a, b = b, a
		}
		small := c - r
		large := c + r
		ans := 0
		if small >= b || large <= a {
			ans = b - a
		} else {
			if small > a {
				ans = small - a
			}
			if b > large {
				ans += b - large
			}
		}
		fmt.Fprintf(out, "%d\n", ans)
	}
	return
}

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

package main

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

// -----------------------------------------------------------------------------

// IO helper functions

// Returns next token from input.  It must be initialized by SetInput()
// before the first call.
var nextToken func() ([]byte, error)
var nextLine func() ([]byte, error)

// Holds a buffer for output.  It must be initialized by SetOutput().
// All IO fucntions (read*() and [e]print*()) should write to OutputWriter
// instead of this.
var OutputBuffer *bufio.Writer

// Holds an io.Writer.  It must be initialized by SetOutput()
var OutputWriter io.Writer

// Set IO functions for interactive input/output.
func SetInteractive(w io.Writer, r io.Reader) {
	SetUnbefferedInput(r)
	OutputBuffer = nil
	OutputWriter = w
}

// Setup OutputBuffer and OutputWriter.
func SetOutput(w io.Writer) {
	OutputBuffer = bufio.NewWriter(w)
	OutputWriter = OutputBuffer
}

// Flushes OutputBuffer
func Flush() {
	if OutputBuffer != nil {
		OutputBuffer.Flush()
	}
}

// Returns true if c is a white space
func IsSpace(c byte) bool {
	switch c {
	case '\t', '\n', '\v', '\f', '\r', ' ':
		return true
	}
	return false
}

func IsNewLine(c byte) bool {
	switch c {
	case '\n', '\r':
		return true
	}
	return false
}

// Setup nextToken with input buffer.
func SetInput(r io.Reader) {
	buf := new(bytes.Buffer)
	var b []byte

	var i int
	rest := func() ([]byte, error) {
		for i < len(b) && IsSpace(b[i]) {
			i++
		}
		if i == len(b) {
			return nil, io.ErrUnexpectedEOF
		}
		j := i
		for i < len(b) && !IsSpace(b[i]) {
			i++
		}
		return b[j:i], nil
	}
	initial := func() ([]byte, error) {
		io.Copy(buf, r)
		b = buf.Bytes()
		nextToken = rest
		return rest()
	}
	nextToken = initial

	restLn := func() ([]byte, error) {
		for i < len(b) && IsNewLine(b[i]) {
			i++
		}
		if i == len(b) {
			return nil, io.ErrUnexpectedEOF
		}
		j := i
		for i < len(b) && !IsNewLine(b[i]) {
			i++
		}
		return b[j:i], nil
	}

	initialLn := func() ([]byte, error) {
		io.Copy(buf, r)
		b = buf.Bytes()
		nextLine = restLn
		return restLn()
	}
	nextLine = initialLn
}

// Setup nextToken without input buffer.
func SetUnbefferedInput(r io.Reader) {
	buf := bufio.NewReader(r)
	var b []byte

	var i int
	nextToken = func() ([]byte, error) {
		var err error
		if i == len(b) {
			b, err = buf.ReadBytes('\n')
			if err != nil {
				return nil, err
			}
			i = 0
			j := len(b) - 1
			for 0 <= j && IsSpace(b[j]) {
				j--
			}
			b = b[0 : j+1]
		}
		for i < len(b) && IsSpace(b[i]) {
			i++
		}
		j := i
		for i < len(b) && !IsSpace(b[i]) {
			i++
		}
		if i == j {
			return nil, io.ErrUnexpectedEOF
		}
		return b[j:i], nil
	}
}

// -----------------------------------------------------------------------------

// IO functions

// Reads next token and return it as []byte
func readb() []byte {
	b, err := nextToken()
	if err != nil {
		panic(err)
	}
	return b
}

// Reads next token and return it as string
func reads() string {
	return string(readb())
}

// Read next line as []byte
func readbln() []byte {
	b, err := nextLine()
	if err != nil {
		panic(err)
	}
	return b
}

// Read next line as string
func readsln() string {
	return string(readbln())
}

// Reads next token and return it as int64
func readll() int64 {
	i, err := strconv.ParseInt(reads(), 10, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// Reads next token and return it as int
func readi() int {
	return int(readll())
}

// Reads next token and return it as float64
func readf() float64 {
	f, err := strconv.ParseFloat(reads(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// Write args to OutputWriter with the format f
func printf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(OutputWriter, f, args...)
}

// Write args to OutputWriter without format
func println(args ...interface{}) (int, error) {
	return fmt.Fprintln(OutputWriter, args...)
}

// Write args to stderr with the format f
func eprintf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(os.Stderr, f, args...)
}

// Write args to stderr without format
func eprintln(args ...interface{}) (int, error) {
	return fmt.Fprintln(os.Stderr, args...)
}

// -----------------------------------------------------------------------------

// Simple math functions

const (
	// big prime
	INF  = 1000000007
	INF2 = 1000000009
	INF3 = 998244353
)

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

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

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

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

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

func absll(a int64) int64 {
	if a < 0 {
		return -a
	}
	return a
}

// egcd(a, b) returns d, x, y:
//   d is gcd(a,b)
//   x, y are  integers that satisfy ax + by = d
func egcd(a, b int) (int, int, int) {
	if b == 0 {
		return a, 1, 0
	}
	d, x, y := egcd(b, a%b)
	return d, y, x - a/b*y
}

func egcdll(a, b int64) (int64, int64, int64) {
	if b == 0 {
		return a, 1, 0
	}
	d, x, y := egcdll(b, a%b)
	return d, y, x - a/b*y
}

func gcd(a, b int) int {
	d, _, _ := egcd(a, b)
	return d
}

func gcdll(a, b int64) int64 {
	d, _, _ := egcdll(a, b)
	return d
}

// set up IO functions
func init() {
	// for non-interactive
	SetInput(os.Stdin)
	SetOutput(os.Stdout)

	// Enable below when interactive.  Its ok to leave above intact.
	// SetInteractive(os.Stdout, os.Stdin)
}

func main() {
	defer Flush()

	t := readi()
	for i := 0; i < t; i++ {
		a := readi()
		b := readi()
		c := readi()
		r := readi()
		println(solve(a, b, c, r))
	}
}

func solve(a, b, c, r int) int {
	if b < a {
		a, b = b, a
	}
	cl := c - r
	cr := c + r
	if cr <= a || b <= cl {
		return b - a
	}
	if a <= cl && cr <= b {
		return b - a - (cr - cl)
	}
	if cl < a && b < cr {
		return 0
	}
	if cl < a {
		return b - cr
	}
	if b < cr {
		return cl - a
	}
	return 0
}

package main

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

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

	testCount := 0
	fmt.Fscanf(in, "%d\n", &testCount)

	for i := 0; i < testCount; i++ {
		a, b, c, r := 0, 0, 0, 0
		fmt.Fscanf(in, "%d %d %d %d\n", &a, &b, &c, &r)
		if a > b {
			a, b = b, a
		}

		p := c - r
		q := c + r

		pr := maxInt(0, minInt(b, q)-maxInt(a, p))
		fmt.Println((b - a - pr))
	}
}

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

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

package main

import (
	"fmt"
)

func main() {

	testCount := 0
	fmt.Scanf("%d\n", &testCount)

	for i := 0; i < testCount; i++ {
		a, b, c, r := 0, 0, 0, 0
		fmt.Scanf("%d %d %d %d\n", &a, &b, &c, &r)
		if a > b {
			a, b = b, a
		}

		p := c - r
		q := c + r

		pr := maxInt(0, minInt(b, q)-maxInt(a, p))
		fmt.Println((b - a - pr))
	}
}

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

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

package main

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

func main(){
    in := bufio.NewReader(os.Stdin)
    out := bufio.NewWriter(os.Stdout)
    defer out.Flush()
    var n int
    fmt.Fscan(in, &n)

    for i := 0; i < n; i++ {
        var a, b, c, r int
        fmt.Fscan(in, &a, &b, &c, &r)
        if a > b {
            a, b = b, a
        }
        x, y := c - r, c + r
        ans := 0
        if y <= a || x >= b {
            ans = b - a
        } else {
            if x < a {
                x = a
            }
            if y > b {
                y = b
            }
            ans = (b - a) - (y - x)
        }
        fmt.Fprintln(out, ans)
    }
}

package main

import "fmt"

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

    for i := 0; i < n; i++ {
        var a, b, c, r int
        fmt.Scan(&a, &b, &c, &r)
        if a > b {
            a, b = b, a
        }
        x, y := c - r, c + r
        ans := 0
        if y <= a || x >= b {
            ans = b - a
        } else {
            if x < a {
                x = a
            }
            if y > b {
                y = b
            }
            ans = (b - a) - (y - x)
        }
        fmt.Println(ans)
    }
}

package main

import "fmt"

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

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

type Segment struct {
	l int
	r int
}

func intersect(s1, s2 Segment) Segment {
	l := max(s1.l, s2.l)
	r := min(s1.r, s2.r)
	return Segment{l, r}
}

func solve() {
	var a, b, c, r int
	fmt.Scanf("%d %d %d %d\n", &a, &b, &c, &r)
	if a > b {
		a, b = b, a
	}
	s1 := Segment{a, b}
	s2 := Segment{c-r, c+r}
	s := intersect(s1, s2)
	len := s.r - s.l
	if len < 0 {
		len = 0
	}
	ans := b - a - len
	fmt.Println(ans)
}

func main() {
	var t int
	fmt.Scanf("%d\n", &t)
	for i := 0; i < t; i++ {
		solve()
	}
}

package main

import "fmt"

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

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

type Segment struct {
	l int
	r int
}

func intersect(s1, s2 Segment) Segment {
	l := max(s1.l, s2.l)
	r := min(s1.r, s2.r)
	return Segment{l, r}
}

func solve() {
	var a, b, c, r int
	fmt.Scanf("%d %d %d %d\n", &a, &b, &c, &r)
	if a > b {
		a, b = b, a
	}
	s1 := Segment{a, b}
	s2 := Segment{c-r, c+r}
	s := intersect(s1, s2)
	len := max(s.r - s.l, 0)
	ans := b - a - len
	fmt.Println(ans)
}

func main() {
	var t int
	fmt.Scanf("%d\n", &t)
	for i := 0; i < t; i++ {
		solve()
	}
}

package main

import (
	"fmt"
)

func main() {
	testCount := 0
	fmt.Scanf("%d\n", &testCount)

	for i := 0; i < testCount; i++ {
		a, b, c, r := 0, 0, 0, 0
		fmt.Scanf("%d %d %d %d\n", &a, &b, &c, &r)
		p := maxInt(a, c-r)
		q := minInt(b, c+r)

		timeUnavailable := (b - a) - (q - p)
		fmt.Println(timeUnavailable)
	}
}

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

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

package main

import (
	"fmt"
)

func main() {
	testCount := 0
	fmt.Scanf("%d\n", &testCount)

	for i := 0; i < testCount; i++ {
		a, b, c, r := 0, 0, 0, 0
		fmt.Scanf("%d %d %d %d\n", &a, &b, &c, &r)
		if a > b {
			tmp := a
			a = b
			b = tmp
		}

		p := c - r
		q := c + r

		if p <= a && q <= a {
			fmt.Println((b - a))
		} else if p < a && q > a && q < b {
			fmt.Println((b - q))
		} else if p < a && q > b {
			fmt.Println(0)
		} else if p > a && p < b && q > a && q < b {
			fmt.Println((b - a) - (q - p))
		} else if p > a && p < b && q > b {
			fmt.Println((b - a) - (b - p))
		} else if p >= b && q >= b {
			fmt.Println((b - a))
		} else {
			fmt.Println(0)
		}
	}
}

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

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


You are playing a very popular computer game. The next level consists of $$$n$$$ consecutive locations, numbered from $$$1$$$ to $$$n$$$, each of them containing either land or water. It is known that the first and last locations contain land, and for completing the level you have to move from the first location to the last. Also, if you become inside a location with water, you will die, so you can only move between locations with land.You can jump between adjacent locations for free, as well as no more than once jump from any location with land $$$i$$$ to any location with land $$$i + x$$$, spending $$$x$$$ coins ($$$x \geq 0$$$).Your task is to spend the minimum possible number of coins to move from the first location to the last one.Note that this is always possible since both the first and last locations are the land locations.

There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. This is followed by the test cases description. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the number of locations. The second line of the test case contains a sequence of integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 1$$$), where $$$a_i = 1$$$ means that the $$$i$$$-th location is the location with land, and $$$a_i = 0$$$ means that the $$$i$$$-th location is the location with water. It is guaranteed that $$$a_1 = 1$$$ and $$$a_n = 1$$$.

For each test case print a single integer — the answer to the problem.

NoteIn the first test case, it is enough to make one free jump from the first location to the second one, which is also the last one, so the answer is $$$0$$$.In the second test case, the only way to move from the first location to the last one is to jump between them, which will cost $$$4$$$ coins.In the third test case, you can jump from the first location to the third for $$$2$$$ coins, and then jump to the fourth location for free, so the answer is $$$2$$$. It can be shown that this is the optimal way.

package main

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

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

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

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

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

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

/**
Run solve the problem CF1649A
Date: 11/10/22
User: pepradere
URL: https://codeforces.com/problemset/problem/1649/A
Problem: CF1649A
**/
func (in *CF1649A) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		arr := make([]int, n)
		for i := 0; i < n; i++ {
			arr[i] = in.NextInt()
		}
		ans := 0

		last := n - 1
		for ; last >= 0; last-- {
			if arr[last] == 1 {
				continue
			} else {
				break
			}
		}
		last++
		ini := 0

		for ; ini <= last; ini++ {
			if arr[ini] == 1 {
				continue
			} else {
				break
			}
		}
		ini--

		start := ini
		zero := false
		for i := ini; i <= last; i++ {
			if arr[i] == 0 {
				zero = true
			}
			if zero && arr[i] == 1 {
				ans += i - start
				start = i
			}
		}

		fmt.Println(ans)

	}

}

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

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

package main

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

var land [105]int

func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewScanner(_r)
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	read := func() (x int) {
		in.Scan()
		for _, b := range in.Bytes() {
			x = x*10 + int(b&15)
		}
		return
	}
	T := read()
	for T > 0 {
		T--
		n := read()
		l, r := 1, n
		for i := 1; i <= n; i++ {
			land[i] = read()
		}
		for l < n && land[l+1] == 1 {
			l++
		}
		for r-1 > l && land[r-1] == 1 {
			r--
		}
		Fprintln(out, r-l)
	}
}

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

package main

import "fmt"

func main() {
	var t int
	fmt.Scan(&t)
	for t > 0 {
		var n int
		fmt.Scan(&n)
		var arr = make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Scan(&arr[i])
		}
		first := 0
		last := 0
		for i := 0; i < n; i++ {
			if arr[i] == 0 {
				first = i
				break
			}
		}
		for i := 0; i < n; i++ {
			if arr[i] == 0 {
				last = i
			}
		}
		if first == 0 {
			fmt.Println(0)
		} else {
			fmt.Println((last + 1) - (first - 1))
		}
		t -= 1
	}
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1649A(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	var T, n int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		land := make([]bool, n)
		for i := range land {
			Fscan(in, &land[i])
		}
		i, j := 1, n-2
		for ; i < n && land[i]; i++ {
		}
		for ; j > i && land[j]; j-- {
		}
		Fprintln(out, j-i+2)
	}
}

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

//nolint
package main

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

//{
var reader = bufio.NewReader(os.Stdin)
var 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 print(a ...interface{})            { fmt.Fprint(writer, a...) }
func println(a ...interface{})          { fmt.Fprintln(writer, a...) }
func scan(a ...interface{})             { fmt.Fscan(reader, a...) }

func main() {
	defer writer.Flush()

	Main()
}

func Main() {
	var t int
	scan(&t)
	for ; t > 0; t-- {
		Solve()
	}
}

//}

func Solve() {
	var n int
	scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		scan(&a[i])
	}
	l, r := 0, 0
	for l = 0; l+1 < n && a[l+1] == 1; l++ {
	}
	for r = n - 1; r-1 >= 0 && a[r-1] == 1; r-- {
	}
	if l >= r {
		println(0)
	} else {
		println(r - l)
	}
}

package main

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

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

  var t int
  for fmt.Fscan(reader, &t); t > 0; t-- {
		var n int
		fmt.Fscan(reader, &n)
		a := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(reader, &a[i])
		}
		l := 0
		r := n-1
		for ; l < n-1 && a[l+1] == 1; l++ {}
		for ; r > 0 && a[r-1] == 1; r-- {}
		ans := r-l
		if ans < 0 {
			ans = 0
		}
		fmt.Fprintf(writer, "%d\n", ans)
  }
}

package main

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

/*
2
4
1 1 0 1
6
1 0 1 0 0 1
---
2
5
*/

//goland:noinspection GoUnhandledErrorResult
func solve() {
	var n int
	scanf("%d\n", &n)

	a := make([]int, n)

	for i := range a {
		scanf("%d", &a[i])
	}
	scanf("\n")

	leftIdx := -1

	for i, num := range a {
		if num == 0 {
			leftIdx = i
			break
		}
	}

	rgtIdx := -1

	for i := n - 1; i >= 0; i-- {
		if a[i] == 0 {
			rgtIdx = i
			break
		}
	}

	if leftIdx > 0 {
		fmt.Fprintln(writer, rgtIdx-leftIdx+2)
	} else {
		fmt.Fprintln(writer, 0)
	}
}

//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 ...int) int {
	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"
	"strconv"
	"strings"
)

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

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

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

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

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

/**
Run solve the problem CF1649A
Date: 11/10/22
User: pepradere
URL: https://codeforces.com/problemset/problem/1649/A
Problem: CF1649A
**/
func (in *CF1649A) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		arr := make([]int, n)
		for i := 0; i < n; i++ {
			arr[i] = in.NextInt()
		}
		ans := 0

		last := n - 1
		for ; last >= 0; last-- {
			if arr[last] == 1 {
				continue
			} else {
				break
			}
		}
		last++

		start := 0
		zero := false
		for i := 1; i <= last; i++ {
			if arr[i] == 0 {
				zero = true
			}
			if zero && arr[i] == 1 {
				ans += i - start
				start = i
			}
		}

		fmt.Println(ans)

	}

}

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

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

package main

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

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

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

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

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

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

/**
Run solve the problem CF1649A
Date: 11/10/22
User: pepradere
URL: https://codeforces.com/problemset/problem/1649/A
Problem: CF1649A
**/
func (in *CF1649A) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		space := 0
		ans := 0
		val := in.NextInt()
		for i := 1; i < n; i++ {
			val = in.NextInt()
			if val == 1 {
				if space > 0 {
					ans += space + 1
				}

				space = 0
			} else {
				space++
			}
		}
		fmt.Println(ans)

	}

}

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

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

package main

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

//var land [105]int

func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewScanner(_r)
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	read := func() (x int) {
		in.Scan()
		for _, b := range in.Bytes() {
			x = x*10 + int(b&15)
		}
		return
	}
	T := read()
	for T > 0 {
		T--
		sum := 0
		cnt := 0
		n := read()
		for i := 1; i <= n; i++ {
			if tmp := read(); tmp == 0 {
				cnt++
			} else if cnt != 0 {
				sum += cnt + 1
				cnt = 0
			}
		}
		Fprintln(out, sum)
	}
}

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

package main

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

//var land [105]int

func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewScanner(_r)
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	read := func() (x int) {
		in.Scan()
		for _, b := range in.Bytes() {
			x = x*10 + int(b&15)
		}
		return
	}
	T := read()
	for T > 0 {
		T--
		sum := 0
		cnt := 0
		n := read()
		for i := 1; i <= n; i++ {
			if tmp := read(); tmp == 1 {
				cnt++
			} else {
				sum += cnt + 1
				cnt = 0
			}
		}
		Fprintln(out, sum)
	}
}

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

package main

import "fmt"

func main() {
	var t int
	fmt.Scan(&t)
	for t > 0 {
		var n int
		fmt.Scan(&n)
		ans := 0
		for i := 0; i < n; i++ {
			var x int
			fmt.Scan(&x)
			c := 0
			if x == 0 {
				for x == 0 && i < n {
					fmt.Scan(&x)
					i++
					c++
				}
				c++
			}
			ans += c
		}
		fmt.Println(ans)
		t -= 1
	}
}