package main

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

// github.com/EndlessCheng/codeforces-go
func CF1389D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	min := func(a, b int64) int64 {
		if a < b {
			return a
		}
		return b
	}
	max := func(a, b int64) int64 {
		if a > b {
			return a
		}
		return b
	}

	var T int
	var n, k, l1, r1, l2, r2 int64
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &k, &l1, &r1, &l2, &r2)
		if l1 > l2 {
			l1, r1, l2, r2 = l2, r2, l1, r1
		}
		r, R := min(r1, r2), max(r1, r2)
		D, d := R-l1, r-l2
		if d > 0 {
			k -= n * d
			if k <= 0 {
				Fprintln(out, 0)
				continue
			}
			D -= d
			d = 0
		} else {
			d = -d
		}
		ans := int64(0)
		if k <= D {
			ans = d + k
		} else {
			ans = d + D + (k-D)*2
			if k <= n*D {
				cnt := k/D*(d+D) + min(d+k%D, k%D*2)
				ans = min(ans, cnt)
			} else {
				cnt := n*(d+D) + (k-n*D)*2
				ans = min(ans, cnt)
			}
		}
		Fprintln(out, ans)
	}
}

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

package main

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

const (
	SCANNER_BUF_SIZE = 2 << 20

	INF = int64(math.MaxInt64)
	MOD = 1e9 + 7
)

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

func init() {
	writer = bufio.NewWriter(os.Stdout)
	scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, SCANNER_BUF_SIZE), SCANNER_BUF_SIZE)
}

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

func sint64() int64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := int64(0)
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int64(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func suint64() uint64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := uint64(0)
	for _, b := range bb {
		i *= 10
		i += uint64(b - '0')
	}
	return i
}

func sstring() string {
	scanner.Scan()
	return scanner.Text()
}

func gcd(a, b int64) int64 {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

func lcm(a, b int64) int64 {
	return a * b / gcd(a, b)
}

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

func min(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r < a {
			a = r
		}
	}
	return a
}

func max(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r > a {
			a = r
		}
	}
	return a
}

func main() {
	defer writer.Flush()
	t := sint64()
	for ; t > 0; t-- {
		n := sint64()
		k := sint64()
		al := sint64()
		ar := sint64()
		bl := sint64()
		br := sint64()
		printf("%d\n", sol(n, k, al, ar, bl, br))
	}
}

func sol(n, k, al, ar, bl, br int64) int64 {
	inter := min(ar, br) - max(al, bl) // can be negative
	if inter*n >= k {
		return 0
	}
	ret := int64(0)
	total := max(ar,br) - min(al,bl)
	gain := total - max(0, inter)
	stepsGain := max(al,bl) - min(al,bl) + max(ar,br) - min(ar,br)
	// printf("gain %d\n", gain)
	if total*n > k {
		// deduct existing intersections first
		if inter >= 0 {
			k -= inter * n
		}
		// printf("k rem %d\n", k)
		chunks := k / gain
		// printf("chunks %d\n", chunks)
		ret += chunks * stepsGain
		k -= chunks * gain
		// printf("remaining k %d\n", k)
		if chunks > 0 {
			rema := k
			if inter < 0 {
				rema -= inter
			}
			remb := k * 2
			// printf("rema remb %d %d\n", rema, remb)
			ret += min(rema, remb)
		} else {
			rema := k
			if inter < 0 {
				rema -= inter
			}
			ret += rema
			// printf("rema %d\n", rema)
		}
		return ret
	}
	ret += stepsGain*n
	k -= total*n
	ret += k*2
	return ret
}

package main

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

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

	T:= 0
	for Fscan(in, &T); T > 0; T-- {
		var n,k int64
		Fscan(in, &n,&k);
		var l1,r1,l2,r2 int64
		var cst[2]int64

		Fscan(in, &l1,&r1);
		Fscan(in, &l2,&r2);

		if l2<l1{
			l1,l2=l2,l1
			r1,r2=r2,r1
		}

		if r1<l2{
			cst[0]=l2-r1
			cst[1]=r2-l1
		} else if (r1<r2) {
			k-=n*(r1-l2)
			cst[1]=r2-l1-(r1-l2)
		} else {
			k-=n*(r2-l2)
			cst[1]=r1-l1-(r2-l2)
		}

		if(k<=0){
			Fprintln(out,0)
			continue
		}
		ans:=int64(2000000000000000000)
		// Fprintln(out,k,cst)
		for i:=int64(1);i<=n;i++{
			var cnt int64
			cnt+=cst[0]*i
			sg:=cst[1]*i
			if k<=sg{
				cnt+=k
			} else {
				cnt+=sg
				cnt+=2*(k-sg)
			}

			if ans>cnt{
				ans=cnt
			}
			// Fprintln(out,"i",i,cnt,sg)
		}

		Fprintln(out,ans)
	}
}

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

package main

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

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	for t := io.NextInt(); t > 0; t-- {
		n, k := io.NextInt(), int64(io.NextInt())
		l1, r1 := io.NextInt(), io.NextInt()
		l2, r2 := io.NextInt(), io.NextInt()

		x := int64(min(r1, r2) - max(l1, l2))
		y := int64(max(r1, r2) - min(l1, l2))

		getCost := func(n int) int64 {
			cur, lim := x*int64(n), y*int64(n)
			if k <= cur {
				return 0
			}
			if k <= lim {
				return k - cur
			}
			return lim - cur + (k-lim)*2
		}

		var ans int64 = math.MaxInt64
		for i := 1; i <= n; i++ {
			cost := getCost(i)
			if cost < ans {
				ans = cost
			}
		}

		io.Println(ans)
	}
}

func max(i, j int) int {
	if i > j {
		return i
	}
	return j
}

func min(i, j int) int {
	if i < j {
		return i
	}
	return j
}

type FastIO struct {
	*bufio.Reader
	*bufio.Writer
	c [1]byte
}

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

func (f *FastIO) readC() byte {
	f.Read(f.c[:])
	return f.c[0]
}

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

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

package main

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

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	for t := io.NextInt(); t > 0; t-- {
		n, k := io.NextInt(), int64(io.NextInt())
		l1, r1 := io.NextInt(), io.NextInt()
		l2, r2 := io.NextInt(), io.NextInt()

		x := int64(min(r1, r2) - max(l1, l2))
		y := int64(max(r1, r2) - min(l1, l2))

		getCost := func(n int) int64 {
			cur, lim := x*int64(n), y*int64(n)
			if k <= cur {
				return 0
			}
			if k <= lim {
				return k - cur
			}
			return lim - cur + (k-lim)*2
		}

		var ans int64 = math.MaxInt64
		for i := 1; i <= n; i++ {
			cost := getCost(i)
			if cost < ans {
				ans = cost
			}
		}

		io.Println(ans)
	}
}

func max(i, j int) int {
	if i > j {
		return i
	}
	return j
}

func min(i, j int) int {
	if i < j {
		return i
	}
	return j
}

type FastIO struct {
	*bufio.Reader
	*bufio.Writer
	c [1]byte
}

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

func (f *FastIO) readC() byte {
	f.Read(f.c[:])
	return f.c[0]
}

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

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

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

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

func (f *FastIO) Print(a ...interface{}) {
	fmt.Fprint(f.Writer, a...)
}

func (f *FastIO) PrintInts(a ...int) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(' ', x)
		}
	}
}

func (f *FastIO) PrintlnInts(a ...int) {
	f.PrintInts(a...)
	f.Println()
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1389D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	min := func(a, b int64) int64 {
		if a < b {
			return a
		}
		return b
	}
	max := func(a, b int64) int64 {
		if a > b {
			return a
		}
		return b
	}

	var T, n, k, l1, r1, l2, r2, ans int64
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &k, &l1, &r1, &l2, &r2)
		if l1 > l2 {
			l1, r1, l2, r2 = l2, r2, l1, r1
		}
		d, D := min(r1, r2)-l2, max(r1, r2)-l1
		if d > 0 {
			k -= n * d
			if k <= 0 {
				Fprintln(out, 0)
				continue
			}
			D -= d
			d = 0
		} else {
			d = -d
		}
		if k <= D {
			ans = d + k
		} else {
			ans = d + D + (k-D)*2
			if k <= n*D {
				ans = min(ans, k/D*(d+D)+min(d+k%D, k%D*2))
			} else {
				ans = min(ans, n*(d+D)+(k-n*D)*2)
			}
		}
		Fprintln(out, ans)
	}
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1389D(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	min := func(a, b int64) int64 {
		if a < b {
			return a
		}
		return b
	}
	max := func(a, b int64) int64 {
		if a > b {
			return a
		}
		return b
	}

	var T, n, k, l1, r1, l2, r2, ans int64
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &k, &l1, &r1, &l2, &r2)
		if l1 > l2 {
			l1, r1, l2, r2 = l2, r2, l1, r1
		}
		d, D := min(r1, r2)-l2, max(r1, r2)-l1
		if d > 0 {
			k -= n * d
			if k <= 0 {
				Fprintln(out, 0)
				continue
			}
			D -= d
			d = 0
		} else {
			d = -d
		}
		if k <= D {
			ans = d + k
		} else {
			ans = d + D + (k-D)*2
			if k <= n*D {
				cnt := k/D*(d+D) + min(d+k%D, k%D*2)
				ans = min(ans, cnt)
			} else {
				cnt := n*(d+D) + (k-n*D)*2
				ans = min(ans, cnt)
			}
		}
		Fprintln(out, ans)
	}
}

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

package main

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

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

func main() {
	defer rw.Flush()
	nTest := 1
	nTest = int(rw.nextInt())
	for i := 0; i < nTest; i++ {
		solveCase()
	}
}

func solveCase() {
	n := rw.nextInt()
	k := rw.nextInt()
	l1 := rw.nextInt()
	r1 := rw.nextInt()
	l2 := rw.nextInt()
	r2 := rw.nextInt()
	if l1 > l2 {
		l1, l2 = l2, l1
		r1, r2 = r2, r1
	}
	var cost, gain int64
	if r1 < l2 {
		cost = l2 - r1
		gain = r2 - l1
	} else {
		cost = 0
		ins := r1 - l2
		if r2 < r1 {
			ins = r2 - l2
		}
		gain = r1 - l1
		if r2 > r1 {
			gain = r2 - l1
		}
		gain -= ins
		k -= ins * n
	}
	steps := k
	if steps < 0 {
		steps = 0
	}
	if k > 0 {
		steps += cost
		k -= gain
	}
	for i := int64(1); i < n && k > 0; i++ {
		take := gain
		if k < take {
			take = k
		}
		if take < cost {
			steps += take
		} else {
			steps += cost
		}
		k -= take
	}
	if k > 0 {
		steps += k
	}
	rw.println(steps)
}

// @meooow template uwu
type fastIO struct {
	*bufio.Reader
	*bufio.Writer
	p [1]byte
}

func newFastIO(r io.Reader, w io.Writer) *fastIO {
	return &fastIO{Reader: bufio.NewReader(r), Writer: bufio.NewWriter(w)}
}

func (f *fastIO) nextInt() int64 {
	f.Read(f.p[:])
	for f.p[0] <= ' ' {
		f.Read(f.p[:])
	}
	neg := false
	if f.p[0] == '-' {
		neg = true
		f.Read(f.p[:])
	}
	n := int64(0)
	for '0' <= f.p[0] && f.p[0] <= '9' {
		n = n*10 + int64(f.p[0]) - '0'
		f.Read(f.p[:])
	}
	if neg {
		return -n
	}
	return n
}

// func (f *fastIO) nextInts(n int) []int {
// 	a := make([]int, n)
// 	for i := 0; i < n; i++ {
// 		a[i] = f.nextInt()
// 	}
// 	return a
// }

func (f *fastIO) next() string {
	f.Read(f.p[:])
	for f.p[0] <= ' ' {
		f.Read(f.p[:])
	}
	var s []byte
	for f.p[0] > ' ' {
		s = append(s, f.p[0])
		f.Read(f.p[:])
	}
	return string(s)
}

func (f *fastIO) println(a ...interface{}) {
	fmt.Fprintln(f.Writer, a...)
}

func (f *fastIO) print(a ...interface{}) {
	fmt.Fprint(f.Writer, a...)
}

func (f *fastIO) printInts(a ...int) {
	if len(a) > 0 {
		f.print(a[0])
		for _, x := range a[1:] {
			f.print(" ", x)
		}
	}
}

func (f *fastIO) printlnInts(a ...int) {
	f.printInts(a...)
	f.println()
}

package main

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

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

func main() {
	defer rw.Flush()
	nTest := 1
	nTest = int(rw.nextInt())
	for i := 0; i < nTest; i++ {
		solveCase()
	}
}

func solveCase() {
	n := rw.nextInt()
	k := rw.nextInt()
	l1 := rw.nextInt()
	r1 := rw.nextInt()
	l2 := rw.nextInt()
	r2 := rw.nextInt()
	if l1 > l2 {
		l1, l2 = l2, l1
		r1, r2 = r2, r1
	}
	var cost, gain int64
	if r1 < l2 {
		cost = l2 - r1
		gain = r2 - l1
	} else {
		cost = 0
		ins := r1 - l2
		if r2-l2 < ins {
			ins = r2 - l2
		}
		gain = r1 - l1
		if r2 > r1 {
			gain = r2 - l1
		}
		gain -= ins
		k -= ins * n
	}
	steps := k
	if steps < 0 {
		steps = 0
	}
	for i := int64(0); i < n && k > 0; i++ {
		take := gain
		if k < take {
			take = k
		}
		if take < cost {
			steps += take
		} else {
			steps += cost
		}
		k -= take
	}
	if k > 0 {
		steps += k
	}
	rw.println(steps)
}

// @meooow template uwu
type fastIO struct {
	*bufio.Reader
	*bufio.Writer
	p [1]byte
}

func newFastIO(r io.Reader, w io.Writer) *fastIO {
	return &fastIO{Reader: bufio.NewReader(r), Writer: bufio.NewWriter(w)}
}

func (f *fastIO) nextInt() int64 {
	f.Read(f.p[:])
	for f.p[0] <= ' ' {
		f.Read(f.p[:])
	}
	neg := false
	if f.p[0] == '-' {
		neg = true
		f.Read(f.p[:])
	}
	n := int64(0)
	for '0' <= f.p[0] && f.p[0] <= '9' {
		n = n*10 + int64(f.p[0]) - '0'
		f.Read(f.p[:])
	}
	if neg {
		return -n
	}
	return n
}

// func (f *fastIO) nextInts(n int) []int {
// 	a := make([]int, n)
// 	for i := 0; i < n; i++ {
// 		a[i] = f.nextInt()
// 	}
// 	return a
// }

func (f *fastIO) next() string {
	f.Read(f.p[:])
	for f.p[0] <= ' ' {
		f.Read(f.p[:])
	}
	var s []byte
	for f.p[0] > ' ' {
		s = append(s, f.p[0])
		f.Read(f.p[:])
	}
	return string(s)
}

func (f *fastIO) println(a ...interface{}) {
	fmt.Fprintln(f.Writer, a...)
}

func (f *fastIO) print(a ...interface{}) {
	fmt.Fprint(f.Writer, a...)
}

func (f *fastIO) printInts(a ...int) {
	if len(a) > 0 {
		f.print(a[0])
		for _, x := range a[1:] {
			f.print(" ", x)
		}
	}
}

func (f *fastIO) printlnInts(a ...int) {
	f.printInts(a...)
	f.println()
}

package main

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

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

func main() {
	defer rw.Flush()
	nTest := 1
	nTest = int(rw.nextInt())
	for i := 0; i < nTest; i++ {
		solveCase()
	}
}

func solveCase() {
	n := rw.nextInt()
	k := rw.nextInt()
	l1 := rw.nextInt()
	r1 := rw.nextInt()
	l2 := rw.nextInt()
	r2 := rw.nextInt()
	if l1 > l2 {
		l1, l2 = l2, l1
		r1, r2 = r2, r1
	}
	var cost, gain int64
	if r1 < l2 {
		cost = l2 - r1
		gain = r2 - l1
	} else {
		cost = 0
		ins := r1 - l2
		if r2-l2 < ins {
			ins = r2 - l2
		}
		gain = r1 - l1
		if r2 > r1 {
			gain = r2 - l1
		}
		gain -= ins
		k -= ins * n
	}
	steps := k
	if steps < 0 {
		steps = 0
	}
	for i := int64(0); i < n && k > 0; i++ {
		take := gain
		if k < take {
			take = k
		}
		if take < cost {
			steps += k
			break
		}
		steps += cost
		k -= take
	}
	rw.println(steps)
}

// @meooow template uwu
type fastIO struct {
	*bufio.Reader
	*bufio.Writer
	p [1]byte
}

func newFastIO(r io.Reader, w io.Writer) *fastIO {
	return &fastIO{Reader: bufio.NewReader(r), Writer: bufio.NewWriter(w)}
}

func (f *fastIO) nextInt() int64 {
	f.Read(f.p[:])
	for f.p[0] <= ' ' {
		f.Read(f.p[:])
	}
	neg := false
	if f.p[0] == '-' {
		neg = true
		f.Read(f.p[:])
	}
	n := int64(0)
	for '0' <= f.p[0] && f.p[0] <= '9' {
		n = n*10 + int64(f.p[0]) - '0'
		f.Read(f.p[:])
	}
	if neg {
		return -n
	}
	return n
}

// func (f *fastIO) nextInts(n int) []int {
// 	a := make([]int, n)
// 	for i := 0; i < n; i++ {
// 		a[i] = f.nextInt()
// 	}
// 	return a
// }

func (f *fastIO) next() string {
	f.Read(f.p[:])
	for f.p[0] <= ' ' {
		f.Read(f.p[:])
	}
	var s []byte
	for f.p[0] > ' ' {
		s = append(s, f.p[0])
		f.Read(f.p[:])
	}
	return string(s)
}

func (f *fastIO) println(a ...interface{}) {
	fmt.Fprintln(f.Writer, a...)
}

func (f *fastIO) print(a ...interface{}) {
	fmt.Fprint(f.Writer, a...)
}

func (f *fastIO) printInts(a ...int) {
	if len(a) > 0 {
		f.print(a[0])
		for _, x := range a[1:] {
			f.print(" ", x)
		}
	}
}

func (f *fastIO) printlnInts(a ...int) {
	f.printInts(a...)
	f.println()
}

package main

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

const (
	SCANNER_BUF_SIZE = 2 << 20

	INF = int64(math.MaxInt64)
	MOD = 1e9 + 7
)

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

func init() {
	writer = bufio.NewWriter(os.Stdout)
	scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, SCANNER_BUF_SIZE), SCANNER_BUF_SIZE)
}

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

func sint64() int64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := int64(0)
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int64(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func suint64() uint64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := uint64(0)
	for _, b := range bb {
		i *= 10
		i += uint64(b - '0')
	}
	return i
}

func sstring() string {
	scanner.Scan()
	return scanner.Text()
}

func gcd(a, b int64) int64 {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

func lcm(a, b int64) int64 {
	return a * b / gcd(a, b)
}

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

func min(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r < a {
			a = r
		}
	}
	return a
}

func max(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r > a {
			a = r
		}
	}
	return a
}

func main() {
	defer writer.Flush()
	t := sint64()
	for ; t > 0; t-- {
		n := sint64()
		k := sint64()
		al := sint64()
		ar := sint64()
		bl := sint64()
		br := sint64()
		printf("%d\n", sol(n, k, al, ar, bl, br))
	}
}

func sol(n, k, al, ar, bl, br int64) int64 {
	inter := min(ar, br) - max(al, bl) // can be negative
	if inter*n >= k {
		return 0
	}
	ret := int64(0)
	total := max(ar,br) - min(al,bl)
	gain := total - max(0, inter)
	stepsGain := max(al,bl) - min(al,bl) + max(ar,br) - min(ar,br)
	// printf("gain %d\n", gain)
	if total*n >= k {
		chunks := k / gain
		// printf("chunks %d\n", chunks)
		ret += chunks * stepsGain
		k -= chunks * gain
		// printf("remaining k %d\n", k)
		if chunks > 0 {
			rema := k - min(0, inter)
			remb := k * 2
			// printf("rema remb %d %d\n", rema, remb)
			ret += min(rema, remb)
		} else {
			rema := k - min(0, inter)
			ret += rema
			// printf("rema %d\n", rema)
		}
		return ret
	}
	ret += stepsGain*n
	k -= total*n
	ret += k*2
	return ret
}

package main

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

const (
	SCANNER_BUF_SIZE = 2 << 20

	INF = int64(math.MaxInt64)
	MOD = 1e9 + 7
)

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

func init() {
	writer = bufio.NewWriter(os.Stdout)
	scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, SCANNER_BUF_SIZE), SCANNER_BUF_SIZE)
}

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

func sint64() int64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := int64(0)
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int64(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func suint64() uint64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := uint64(0)
	for _, b := range bb {
		i *= 10
		i += uint64(b - '0')
	}
	return i
}

func sstring() string {
	scanner.Scan()
	return scanner.Text()
}

func gcd(a, b int64) int64 {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

func lcm(a, b int64) int64 {
	return a * b / gcd(a, b)
}

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

func min(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r < a {
			a = r
		}
	}
	return a
}

func max(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r > a {
			a = r
		}
	}
	return a
}

func main() {
	defer writer.Flush()
	t := sint64()
	for ; t > 0; t-- {
		n := sint64()
		k := sint64()
		al := sint64()
		ar := sint64()
		bl := sint64()
		br := sint64()
		printf("%d\n", sol(n, k, al, ar, bl, br))
	}
}

func sol(n, k, al, ar, bl, br int64) int64 {
	inter := min(ar, br) - max(al, bl) // can be negative
	if inter*n >= k {
		return 0
	}
	if inter > 0 {
		k -= inter * n
	}
	ret := int64(0)
	total := max(ar,br) - min(al,bl)
	gain := total - max(0, inter)
	stepsGain := max(al,bl) - min(al,bl) + max(ar,br) - min(ar,br)
	// printf("gain %d\n", gain)
	if total*n >= k {
		chunks := k / gain
		// printf("chunks %d\n", chunks)
		ret += chunks * stepsGain
		k -= chunks * gain
		// printf("remaining k %d\n", k)
		if chunks > 0 {
			rema := int64(0)
			if inter < 0 {
				rema -= inter
			}
			rema += k
			remb := k * 2
			// printf("rema remb %d %d\n", rema, remb)
			ret += min(rema, remb)
		} else {
			rema := int64(0)
			if inter < 0 {
				rema -= inter
			}
			rema += k
			ret += rema
			// printf("rema %d\n", rema)
		}
		return ret
	}
	ret += stepsGain*n
	k -= gain*n
	ret += k*2
	return ret
}


package main

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

var _x = uint(1)

func fastRand() uint {
	_x ^= _x << 13
	_x ^= _x >> 17
	_x ^= _x << 5
	return _x
}

type node struct {
	lr       [2]*node
	priority uint
	l, r     int
	work     bool
}

func (o *node) rotate(d int) *node {
	x := o.lr[d^1]
	o.lr[d^1] = x.lr[d]
	x.lr[d] = o
	return x
}

type treap struct {
	root       *node
	workDayCnt int
	comparator func(a, b int) int
}

func newTreap() *treap {
	return &treap{comparator: func(a, b int) int {
		if a < b {
			return 0
		}
		if a > b {
			return 1
		}
		return -1
	}}
}

func (t *treap) _put(o *node, l, r int, work bool) *node {
	if o == nil {
		return &node{priority: fastRand(), l: l, r: r, work: work}
	}
	if cmp := t.comparator(l, o.l); cmp >= 0 {
		o.lr[cmp] = t._put(o.lr[cmp], l, r, work)
		if o.lr[cmp].priority > o.priority {
			o = o.rotate(cmp ^ 1)
		}
	} else {
		o.work = work
	}
	return o
}

func (t *treap) put(l, r int, work bool) { t.root = t._put(t.root, l, r, work) }

func (t *treap) _delete(o *node, l int) *node {
	if o == nil {
		return nil
	}
	if cmp := t.comparator(l, o.l); cmp >= 0 {
		o.lr[cmp] = t._delete(o.lr[cmp], l)
	} else {
		if o.lr[1] == nil {
			return o.lr[0]
		}
		if o.lr[0] == nil {
			return o.lr[1]
		}
		cmp2 := 0
		if o.lr[0].priority > o.lr[1].priority {
			cmp2 = 1
		}
		o = o.rotate(cmp2)
		o.lr[cmp2] = t._delete(o.lr[cmp2], l)
	}
	return o
}

func (t *treap) delete(l int) { t.root = t._delete(t.root, l) }

func (t *treap) floor(l int) (floor *node) {
	for o := t.root; o != nil; {
		switch cmp := t.comparator(l, o.l); {
		case cmp == 0:
			o = o.lr[0]
		case cmp > 0:
			floor = o
			o = o.lr[1]
		default:
			return o
		}
	}
	return
}

func (t *treap) next(l int) (next *node) {
	for o := t.root; o != nil; {
		if cmp := t.comparator(l, o.l); cmp != 0 {
			o = o.lr[1]
		} else {
			next = o
			o = o.lr[0]
		}
	}
	return
}

func (t *treap) split(mid int) {
	if o := t.floor(mid); o.l < mid && mid <= o.r {
		or, oVal := o.r, o.work
		o.r = mid - 1
		t.put(mid, or, oVal)
	}
}

func (t *treap) prepare(l, r int) {
	t.split(l)
	t.split(r + 1)
}

func (t *treap) updateCnt(o *node, work bool) {
	if !o.work && work {
		t.workDayCnt += o.r - o.l + 1
	} else if o.work && !work {
		t.workDayCnt -= o.r - o.l + 1
	}
}

func (t *treap) merge(l, r int, work bool) {
	for o := t.next(l); o != nil && o.l <= r; o = t.next(o.l) {
		t.updateCnt(o, work)
		t.delete(o.l)
	}
	o := t.floor(l)
	t.updateCnt(o, work)
	o.r = r
	o.work = work
}

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

	var n, q, l, r, k int
	Fscan(in, &n, &q)
	t := newTreap()
	t.put(1, n, true)
	t.workDayCnt = n
	for ; q > 0; q-- {
		Fscan(in, &l, &r, &k)
		t.prepare(l, r)
		t.merge(l, r, k == 2)
		Fprintln(out, t.workDayCnt)
	}
}

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

package main

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

type Order struct {
    start, end int
    work int8
}

type SegmentTree struct {
    times []int
    time_map map[int]int
    data []int
    pending []int8
}

func (st *SegmentTree) Initialize(times []int) {
    st.times = times
    st.time_map = make(map[int]int, len(times))
    for i, t := range times {
        st.time_map[t] = i
    }
    n := 1
    for n < len(times) {
        n <<= 1
    }
    n = (n << 1) - 1
    st.data = make([]int, n)
    st.pending = make([]int8, n)
    for i, _ := range st.pending {
        st.pending[i] = -1
    }
}

func (st *SegmentTree) push(idx, l, r, L, R int) {
    if st.pending[idx] != -1 {
        if st.pending[idx] == 1 {
            st.data[idx] = st.times[r + 1] - st.times[l]
        } else {
            st.data[idx] = 0
        }
        if l != r {
            st.pending[L] = st.pending[idx]
            st.pending[R] = st.pending[idx]
        }
        st.pending[idx] = -1
    }
}

func (st *SegmentTree) update(i, j int, work int8, idx, l, r int) {
    if l >= i && r <= j {
        st.pending[idx] = work
    }
    L := (idx << 1) + 1
    R := L + 1
    st.push(idx, l, r, L, R)
    if (l >= i && r <= j) || r < i || l > j {
        return
    }
    mid := (l + r) >> 1
    st.update(i, j, work, L, l, mid)
    st.update(i, j, work, R, mid + 1, r)
    st.data[idx] = st.data[L] + st.data[R]
}

func (st *SegmentTree) Update(i, j int, work int8) {
    st.update(st.time_map[i], st.time_map[j + 1] - 1, work, 0, 0, len(st.times) - 2)
}

func (st *SegmentTree) Query() int {
    st.push(0, 0, len(st.times) - 2, 1, 2)
    return st.data[0]
}

func unique(v []int) []int {
    u := make([]int, 0, len(v))
    u = append(u, v[0])
    for i := 1; i < len(v); i++ {
        if v[i] != u[len(u) - 1] {
            u = append(u, v[i])
        }
    }
    return u
}

func toInt(buf []byte) (n int, buf_left []byte) {
    for i, v := range buf {
        if v == ' ' {
            buf_left = buf[i + 1:]
            break
        }
        n = n * 10 + int(v - '0')
    }
    return
}

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Scan()
    n, _ := toInt(scanner.Bytes())
    scanner.Scan()
    q, _ := toInt(scanner.Bytes())

    orders := make([]Order, q)
    times := make([]int, 0, 2 * q + 2)
    times = append(times, 1, n + 1)
    var k int
    for i, _ := range orders {
        order := &orders[i]
        scanner.Scan()
        buf := scanner.Bytes()
        order.start, buf = toInt(buf)
        order.end, buf = toInt(buf)
        k, buf = toInt(buf)
        order.work = int8(k - 1)
        times = append(times, order.start, order.end + 1)
    }
    sort.Ints(times)
    times = unique(times)

    st := new(SegmentTree)
    st.Initialize(times)

    output := bufio.NewWriter(os.Stdout)

    st.Update(0, n, 1)
    for _, order := range orders {
        st.Update(order.start, order.end, order.work)
        fmt.Fprintln(output, st.Query())
    }

    output.Flush()
}

package main

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

var _x = uint(1)

func fastRand() uint {
	_x ^= _x << 13
	_x ^= _x >> 17
	_x ^= _x << 5
	return _x
}

type node struct {
	lr       [2]*node
	priority uint
	l, r     int
	work     bool
}

func (o *node) rotate(d int) *node {
	x := o.lr[d^1]
	o.lr[d^1] = x.lr[d]
	x.lr[d] = o
	return x
}

type treap struct {
	root       *node
	workDayCnt int
	comparator func(a, b int) int
}

func newTreap() *treap {
	return &treap{comparator: func(a, b int) int {
		if a < b {
			return 0
		}
		if a > b {
			return 1
		}
		return -1
	}}
}

func (t *treap) _put(o *node, l, r int, work bool) *node {
	if o == nil {
		return &node{priority: fastRand(), l: l, r: r, work: work}
	}
	if cmp := t.comparator(l, o.l); cmp >= 0 {
		o.lr[cmp] = t._put(o.lr[cmp], l, r, work)
		if o.lr[cmp].priority > o.priority {
			o = o.rotate(cmp ^ 1)
		}
	} else {
		o.work = work
	}
	return o
}

func (t *treap) put(l, r int, work bool) { t.root = t._put(t.root, l, r, work) }

func (t *treap) _delete(o *node, l int) *node {
	if o == nil {
		return nil
	}
	if cmp := t.comparator(l, o.l); cmp >= 0 {
		o.lr[cmp] = t._delete(o.lr[cmp], l)
	} else {
		if o.lr[1] == nil {
			return o.lr[0]
		}
		if o.lr[0] == nil {
			return o.lr[1]
		}
		cmp2 := 0
		if o.lr[0].priority > o.lr[1].priority {
			cmp2 = 1
		}
		o = o.rotate(cmp2)
		o.lr[cmp2] = t._delete(o.lr[cmp2], l)
	}
	return o
}

func (t *treap) delete(l int) { t.root = t._delete(t.root, l) }

func (t *treap) floor(l int) (floor *node) {
	for o := t.root; o != nil; {
		switch cmp := t.comparator(l, o.l); {
		case cmp == 0:
			o = o.lr[0]
		case cmp > 0:
			floor = o
			o = o.lr[1]
		default:
			return o
		}
	}
	return
}

func (t *treap) next(l int) (next *node) {
	for o := t.root; o != nil; {
		if cmp := t.comparator(l, o.l); cmp != 0 {
			o = o.lr[1]
		} else {
			next = o
			o = o.lr[0]
		}
	}
	return
}

func (t *treap) split(mid int) {
	if o := t.floor(mid); o.l < mid && mid <= o.r {
		or, oVal := o.r, o.work
		o.r = mid - 1
		t.put(mid, or, oVal)
	}
}

func (t *treap) prepare(l, r int) {
	t.split(l)
	t.split(r + 1)
}

func (t *treap) updateCnt(o *node, work bool) {
	if !o.work && work {
		t.workDayCnt += o.r - o.l + 1
	} else if o.work && !work {
		t.workDayCnt -= o.r - o.l + 1
	}
}

func (t *treap) merge(l, r int, work bool) {
	for o := t.next(l); o != nil && o.l <= r; o = t.next(o.l) {
		t.updateCnt(o, work)
		t.delete(o.l)
	}
	o := t.floor(l)
	t.updateCnt(o, work)
	o.r = r
	o.work = work
}

// github.com/EndlessCheng/codeforces-go
func Sol915E(reader io.Reader, writer io.Writer) {
	in := bufio.NewScanner(reader)
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(writer)
	defer out.Flush()
	read := func() (x int) {
		in.Scan()
		for _, b := range in.Bytes() {
			x = x*10 + int(b-'0')
		}
		return
	}

	n := read()
	t := newTreap()
	t.put(1, n, true)
	t.workDayCnt = n
	for q := read(); q > 0; q-- {
		l, r, k := read(), read(), read()
		t.prepare(l, r)
		t.merge(l, r, k == 2)
		Fprintln(out, t.workDayCnt)
	}
}

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

package main

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

type Order struct {
    start, end int
    work bool
}

type SegmentTree struct {
    times []int
    time_map map[int]int
    data []int
    pending []int8
}

func (st *SegmentTree) Initialize(times []int) {
    st.times = times
    st.time_map = make(map[int]int, len(times))
    for i, t := range times {
        st.time_map[t] = i
    }
    n := 1
    for n < len(times) {
        n <<= 1
    }
    n = (n << 1) - 1
    st.data = make([]int, n)
    st.pending = make([]int8, n)
    for i, _ := range st.pending {
        st.pending[i] = -1
    }
}

func (st *SegmentTree) push(idx, l, r, L, R int) {
    if st.pending[idx] != -1 {
        if st.pending[idx] == 1 {
            st.data[idx] = st.times[r + 1] - st.times[l]
        } else {
            st.data[idx] = 0
        }
        if l != r {
            st.pending[L] = st.pending[idx]
            st.pending[R] = st.pending[idx]
        }
        st.pending[idx] = -1
    }
}

func (st *SegmentTree) update(i, j int, work bool, idx, l, r int) {
    L := (idx << 1) + 1
    R := L + 1
    if l >= i && r <= j {
        if work {
            st.pending[idx] = 1
        } else {
            st.pending[idx] = 0
        }
    }
    st.push(idx, l, r, L, R)
    if (l >= i && r <= j) || r < i || l > j {
        return
    }
    mid := (l + r) >> 1
    st.update(i, j, work, L, l, mid)
    st.update(i, j, work, R, mid + 1, r)
    st.data[idx] = st.data[L] + st.data[R]
}

func (st *SegmentTree) Update(i, j int, work bool) {
    st.update(st.time_map[i], st.time_map[j + 1] - 1, work, 0, 0, len(st.times) - 2)
}

func (st *SegmentTree) query(i, j, idx, l, r int) int {
    L := (idx << 1) + 1
    R := L + 1
    st.push(idx, l, r, L, R)
    if l >= i && r <= j {
        return st.data[idx]
    }
    if r < i || l > j {
        return 0
    }
    mid := (l + r) >> 1
    return st.query(i, j, L, l, mid) + st.query(i, j, R, mid + 1, r)
}

func (st *SegmentTree) Query(i, j int) int {
    return st.query(st.time_map[i], st.time_map[j + 1] - 1, 0, 0, len(st.times) - 2)
}

func main() {
    var n, q int
    input := bufio.NewReader(os.Stdin)
    output := bufio.NewWriter(os.Stdout)
    fmt.Fscan(input, &n, &q)
    orders := make([]Order, q)
    times_set := make(map[int]bool, 2 * q)
    times_set[1] = true
    times_set[n + 1] = true
    for i, _ := range orders {
        order := &orders[i]
        var k int
        fmt.Fscan(input, &order.start, &order.end, &k)
        order.work = k == 2
        times_set[order.start] = true
        times_set[order.end + 1] = true
    }
    times := make([]int, 0, len(times_set))
    for key, _ := range times_set {
        times = append(times, key)
    }
    sort.Ints(times)

    st := new(SegmentTree)
    st.Initialize(times)

    if q < 300000 {

        st.Update(0, n, true)
        for _, order := range orders {
            st.Update(order.start, order.end, order.work)
            fmt.Fprintln(output, st.Query(1, n))
        }
        output.Flush()
    }
}

package main

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

type Order struct {
    start, end int
    work bool
}

type SegmentTree struct {
    times []int
    time_map map[int]int
    data []int
    pending []int8
}

func (st *SegmentTree) Initialize(times []int) {
    st.times = times
    st.time_map = make(map[int]int, len(times))
    for i, t := range times {
        st.time_map[t] = i
    }
    n := 1
    for n < len(times) {
        n <<= 1
    }
    n = (n << 1) - 1
    st.data = make([]int, n)
    st.pending = make([]int8, n)
    for i, _ := range st.pending {
        st.pending[i] = -1
    }
}

func (st *SegmentTree) push(idx, l, r, L, R int) {
    if st.pending[idx] != -1 {
        if st.pending[idx] == 1 {
            st.data[idx] = st.times[r + 1] - st.times[l]
        } else {
            st.data[idx] = 0
        }
        if l != r {
            st.pending[L] = st.pending[idx]
            st.pending[R] = st.pending[idx]
        }
        st.pending[idx] = -1
    }
}

func (st *SegmentTree) update(i, j int, work bool, idx, l, r int) {
    L := (idx << 1) + 1
    R := L + 1
    if l >= i && r <= j {
        if work {
            st.pending[idx] = 1
        } else {
            st.pending[idx] = 0
        }
    }
    st.push(idx, l, r, L, R)
    if (l >= i && r <= j) || r < i || l > j {
        return
    }
    mid := (l + r) >> 1
    st.update(i, j, work, L, l, mid)
    st.update(i, j, work, R, mid + 1, r)
    st.data[idx] = st.data[L] + st.data[R]
}

func (st *SegmentTree) Update(i, j int, work bool) {
    st.update(st.time_map[i], st.time_map[j + 1] - 1, work, 0, 0, len(st.times) - 2)
}

func (st *SegmentTree) query(i, j, idx, l, r int) int {
    L := (idx << 1) + 1
    R := L + 1
    st.push(idx, l, r, L, R)
    if l >= i && r <= j {
        return st.data[idx]
    }
    if r < i || l > j {
        return 0
    }
    mid := (l + r) >> 1
    return st.query(i, j, L, l, mid) + st.query(i, j, R, mid + 1, r)
}

func (st *SegmentTree) Query(i, j int) int {
    return st.query(st.time_map[i], st.time_map[j + 1] - 1, 0, 0, len(st.times) - 2)
}

func unique(v []int) []int {
    u := make([]int, 0, len(v))
    u = append(u, v[0])
    for i := 1; i < len(v); i++ {
        if v[i] != u[len(u) - 1] {
            u = append(u, v[i])
        }
    }
    return u
}

func main() {
    var n, q int
    input := bufio.NewReader(os.Stdin)
    output := bufio.NewWriter(os.Stdout)
    fmt.Fscan(input, &n, &q)
    orders := make([]Order, q)
    times := make([]int, 0, 2 * q + 2)
    times = append(times, 1, n + 1)
    for i, _ := range orders {
        order := &orders[i]
        var k int
        fmt.Fscan(input, &order.start, &order.end, &k)
        order.work = k == 2
        times = append(times, order.start, order.end + 1)
    }
    sort.Ints(times)
    times = unique(times)

    st := new(SegmentTree)
    st.Initialize(times)

    if q < 300000 {

        st.Update(0, n, true)
        for _, order := range orders {
            st.Update(order.start, order.end, order.work)
            fmt.Fprintln(output, st.Query(1, n))
        }
        output.Flush()
    }
}


package main

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

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

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

	n := nextInt()
	a := make([]int, n)
	move := 0

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

	i := 0

	for ; i < n && a[i] == 0; i++ {}

	if i < n {
		move++
		i++
	}

	for ; i < n; i++ {
		// println(i, a[i], move)
		if a[i] == 1 {
			move++
		} else {
			for ; i < n && a[i] == 0; i++ {}
			if i < n {
				move += 2
			}
		}
	}

	println(move)
}

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

func nextInt() int {
	n, err := strconv.Atoi(next())
	if err != nil {
		panic(err)
	}
	return n
}

func nextFloat() float64 {
	n, err := strconv.ParseFloat(next(), 64)
	if err != nil {
		panic(err)
	}
	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 (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func main() {
	var n int
	if _, err := fmt.Scanf("%d\n", &n); err != nil {
		return
	}

	list := make([]int, n)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := 0; scanner.Scan(); i++ {
		a, err := strconv.Atoi(scanner.Text())
		if err != nil {
			return
		}
		list[i] = a
	}

	click := 0

	list_view := true
	pointer := 0
	for pointer < n {
		if list_view {
			for pointer < n {
				if list[pointer] == 1 {
					click++
					list[pointer] = 0
					list_view = false
					break
				} else {
					pointer++
				}
			}
			if list_view && click > 0 {
				click--
			}
		} else {
			for pointer < n-1 {
				if list[pointer+1] == 1 {
					click++
					pointer++
					list[pointer] = 0
				} else {
					if pointer >= n-2 {
						pointer++
						break
					} else if list[pointer+2] == 1 {
						click += 2
						pointer += 2
						list[pointer] = 0
					} else {
						click++
						pointer += 2
						list_view = true
						break
					}
				}
			}
			if pointer >= n-1 {
				if list_view && click > 0 {
					click--
				}
				break
			}
		}
	}

	fmt.Println(click)
}

package main

import (
	"fmt"
)

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

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

	ans := 0
	pre := -1
	for i := 0; i < n; i++ {
		if letters[i] == 1 {
			if pre == -1 {
				ans++
			} else {
				if i-pre == 1 {
					ans++
				} else {
					ans += 2
				}
			}
			pre = i
		}
	}

	fmt.Println(ans)
}

package main

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

func main() {
	var n int
	if _, err := fmt.Scanf("%d\n", &n); err != nil {
		return
	}

	list := make([]int, n)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := 0; scanner.Scan(); i++ {
		a, err := strconv.Atoi(scanner.Text())
		if err != nil {
			return
		}
		list[i] = a
	}

	click := 0

	list_view := true
	pointer := 0
	for pointer < n {
		if list_view {
			for pointer < n {
				if list[pointer] == 1 {
					click++
					list[pointer] = 0
					list_view = false
					break
				} else {
					pointer++
				}
			}
		} else {
			for pointer < n-1 {
				if list[pointer+1] == 1 {
					click++
					pointer++
					list[pointer] = 0
				} else {
					if pointer >= n-2 {
						pointer++
						break
					} else if list[pointer+2] == 1 {
						click += 2
						pointer += 2
						list[pointer] = 0
					} else {
						click++
						pointer += 2
						list_view = true
						break
					}
				}
			}
			if pointer >= n-1 {
				break
			}
		}
	}

	fmt.Println(click)
}

package main

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

func main() {
	var n int
	if _, err := fmt.Scanf("%d\n", &n); err != nil {
		return
	}

	list := make([]int, n)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := 0; scanner.Scan(); i++ {
		a, err := strconv.Atoi(scanner.Text())
		if err != nil {
			return
		}
		list[i] = a
	}

	click := 0

	list_view := true
	pointer := 0
	for pointer < n {
		if list_view {
			for pointer < n {
				if list[pointer] == 1 {
					click++
					list[pointer] = 0
					list_view = false
					break
				} else {
					pointer++
				}
			}
			if list_view && click > 0 {
				click--
			}
		} else {
			for pointer < n-1 {
				if list[pointer+1] == 1 {
					click++
					pointer++
					list[pointer] = 0
				} else {
					if pointer >= n-2 {
						pointer++
						break
					} else if list[pointer+2] == 1 {
						click += 2
						pointer += 2
						list[pointer] = 0
					} else {
						click++
						pointer += 2
						list_view = true
						break
					}
				}
			}
			if pointer >= n-1 {
				break
			}
		}
	}

	fmt.Println(click)
}


package main

import (
	"errors"
	"fmt"
)

type Stack struct{
	Tail *StackNode
}

type StackNode struct {
	Value uint32
	Next *StackNode
}

func (s *Stack) Push(value uint32) {

	if s.Tail == nil {
		s.Tail = &StackNode {Value: value, Next: nil}
	}   else {
		s.Tail = &StackNode {Value: value, Next:  s.Tail}
	}
}

func (s *Stack) Pop() (value uint32, err error){

	if s.Tail == nil {
		return 1, errors.New("StackUnderflow")
	}   else {

		v := s.Tail.Value

		s.Tail = s.Tail.Next

		return v, nil
	}
}

func Round (a uint32, b uint32) uint32{

if (a + b) % 2 == 0 {
return (a + b) / 2
} else {

return ((a + b) / 2) + 1
}

}

func main () {
	var lim uint32
	var t int

	s := Stack{}
	fmt.Scan(&t)

	for k := 1; k <= t; k++ {
		fmt.Scan(&lim)

		for i := 1; uint32 (i) <= lim; i++{
			s.Push(uint32(i))
		}
		fmt.Println(2)

		for i := 1; uint32(i) <= lim - 1; i++{

			a, _ := s.Pop()
			b, _ := s.Pop()
			c, err := s.Pop()

			if err != nil {
				fmt.Println(a, b)
				break
			}

			if i == 1 {

				s.Push(b)
				fmt.Println(a,c)
				s.Push(Round(a, c))

			}	else {
				s.Push(c)
				fmt.Println(a,b)
				s.Push(Round(a, b))
			}

		}

	}

}

package main

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

type IntHeap []int

func (h IntHeap) Len() int {
	return len(h)
}

func (h IntHeap) Less(i, j int) bool {
	return h[i] > h[j]
}

func (h IntHeap) Swap(i, j int) {
	h[i], h[j] = h[j], h[i]
}
func (h *IntHeap) Push(x interface{}) {
	*h = append(*h, x.(int))
}
func (h *IntHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

var T, n int

func solve(n int) {

	h := &IntHeap{}
	heap.Init(h)
	for i := 1; i <= n; i++ {
		heap.Push(h, i)
	}

	_, _ = fmt.Fprintln(_w, 2)
	//_ = _w.Flush()

	for h.Len() > 0 {
		var x = (*h)[0]
		heap.Pop(h)
		var y = (*h)[0]
		heap.Pop(h)
		_, _ = fmt.Fprintln(_w, x, y)
		//_ = _w.Flush()
		var z = (x + y + 1) / 2
		if h.Len() == 0 {
			break
		}
		h.Push(z)
	}

}

var _r = bufio.NewReader(os.Stdin)
var _w = bufio.NewWriter(os.Stdout)

func main() {
	defer _w.Flush()
	_, _ = fmt.Fscan(_r, &T)
	for kase := 1; kase <= T; kase++ {
		_, _ = fmt.Fscan(_r, &n)
		solve(n)
	}
}

package main

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

type IntHeap []int

func (h IntHeap) Len() int {
	return len(h)
}

func (h IntHeap) Less(i, j int) bool {
	return h[i] > h[j]
}

func (h IntHeap) Swap(i, j int) {
	h[i], h[j] = h[j], h[i]
}
func (h *IntHeap) Push(x interface{}) {
	*h = append(*h, x.(int))
}
func (h *IntHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

var T, n int

func solve(n int) {

	h := &IntHeap{}
	heap.Init(h)
	for i := 1; i <= n; i++ {
		heap.Push(h, i)
	}

	_, _ = fmt.Fprintln(_w, 2)
	_ = _w.Flush()

	for h.Len() > 0 {
		var x = (*h)[0]
		heap.Pop(h)
		var y = (*h)[0]
		heap.Pop(h)
		_, _ = fmt.Fprintln(_w, x, y)
		_ = _w.Flush()
		var z = (x + y + 1) / 2
		if h.Len() == 0 {
			break
		}
		h.Push(z)
	}

}

var _r = bufio.NewReader(os.Stdin)
var _w = bufio.NewWriter(os.Stdout)

func main() {
	_, _ = fmt.Fscan(_r, &T)
	for kase := 1; kase <= T; kase++ {
		_, _ = fmt.Fscan(_r, &n)
		solve(n)
	}
}

package main

import (
	"fmt"
	"bufio"
	"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...) }

func solve() {
	var n int
	scanf("%d\n", &n)
	if n == 2 {
		printf("%s\n", "2\n1 2")
		return
	}
	printf("%d\n", 2)
	printf("%d %d\n", n, n - 2)
	printf("%d %d\n", n - 1, n - 1)
	curr := n - 1
	for i := n - 3; i > 0; i-- {
		printf("%d %d\n", i, curr)
		curr = (i + curr + 1) / 2
	}
}

func main() {
	defer writer.Flush()
	var t int
	scanf("%d\n", &t)
	for ; t > 0; t-- {
		solve()
	}
}

package main

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

func main() {
	defer _w.Flush()
	t := ReadInt()
	for i := 0; i < t; i++ {
		n := ReadInt()
		solve(n)
	}
}

func solve(n int) {
	Println(2)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = i + 1
	}

	if len(a) >= 3 {
		Println(a[len(a)-3], a[len(a)-1])
		v := (a[len(a)-3] + a[len(a)-1]) / 2
		a[len(a)-3], a[len(a)-2] = a[len(a)-2], v
		a = a[:len(a)-1]
	}

	for len(a) >= 3 {
		Println(a[len(a)-2], a[len(a)-1])
		v := (a[len(a)-2] + a[len(a)-1] + 1) / 2
		a[len(a)-2] = v
		a = a[:len(a)-1]
	}

	Println(a[0], a[1])
}

var _r, _w = bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)

func Print(a ...interface{})            { fmt.Fprint(_w, a...) }
func Printf(f string, a ...interface{}) { fmt.Fprintf(_w, f, a...) }
func Println(a ...interface{})          { fmt.Fprintln(_w, a...) }
func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(_r, a...); err != nil {
		panic(err)
	}
}
func ReadString() (s string) { Scan(&s); return }
func ReadInt() (i int)       { Scan(&i); return }
func ReadInts(n int) (a []int) {
	for i := 0; i < n; i++ {
		a = append(a, ReadInt())
	}
	return
}
func ReadInt64() (i int64) { Scan(&i); return }
func ReadInt64s(n int) (a []int64) {
	for i := 0; i < n; i++ {
		a = append(a, ReadInt64())
	}
	return
}

/*
URL:
https://codeforces.com/contest/1430/problem/C
*/

package main

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

var (
	t int

	n int
)

func main() {
	defer stdout.Flush()

	t = readi()
	for tc := 0; tc < t; tc++ {
		n = readi()

		solve()
	}
}

func solve() {
	printf("%d\n", 2)

	nokori := n
	for i := n - 1; i >= 1; i-- {
		a, b := i, nokori
		printf("%d %d\n", a, b)

		nokori = Kiriage(a+b, 2)
	}
}

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

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

/********** common constants **********/

const (
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPH_N  = 26
	INF_I64 = math.MaxInt64
	INF_B60 = 1 << 60
	INF_I32 = math.MaxInt32
	INF_B30 = 1 << 30
	NIL     = -1
	EPS     = 1e-10
)

/********** bufio setting **********/

func init() {
	// bufio.ScanWords <---> bufio.ScanLines
	reads = newReadString(os.Stdin, bufio.ScanWords)
	stdout = bufio.NewWriter(os.Stdout)
}

// mod can calculate a right residual whether value is positive or negative.
func mod(val, m int) int {
	res := val % m
	if res < 0 {
		res += m
	}
	return res
}

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

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

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

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

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

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

	return s
}

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

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

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

//str := reads()
//i := readi()
//X := readis(n)
//S := readrs()
//a := readf()
//A := readfs(n)

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

/*********** Input ***********/

var (
	// reads returns a WORD string.
	reads  func() string
	stdout *bufio.Writer
)

func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	r.Split(sf)

	return func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
}

// readi returns an integer.
func readi() int {
	return int(_readInt64())
}
func readi2() (int, int) {
	return int(_readInt64()), int(_readInt64())
}
func readi3() (int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64())
}
func readi4() (int, int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64()), int(_readInt64())
}

// readll returns as integer as int64.
func readll() int64 {
	return _readInt64()
}
func readll2() (int64, int64) {
	return _readInt64(), _readInt64()
}
func readll3() (int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64()
}
func readll4() (int64, int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64(), _readInt64()
}

func _readInt64() int64 {
	i, err := strconv.ParseInt(reads(), 0, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// readis returns an integer slice that has n integers.
func readis(n int) []int {
	b := make([]int, n)
	for i := 0; i < n; i++ {
		b[i] = readi()
	}
	return b
}

// readlls returns as int64 slice that has n integers.
func readlls(n int) []int64 {
	b := make([]int64, n)
	for i := 0; i < n; i++ {
		b[i] = readll()
	}
	return b
}

// readf returns an float64.
func readf() float64 {
	return float64(_readFloat64())
}

func _readFloat64() float64 {
	f, err := strconv.ParseFloat(reads(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// ReadFloatSlice returns an float64 slice that has n float64.
func readfs(n int) []float64 {
	b := make([]float64, n)
	for i := 0; i < n; i++ {
		b[i] = readf()
	}
	return b
}

// readrs returns a rune slice.
func readrs() []rune {
	return []rune(reads())
}

/*********** Output ***********/

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

// Printf is function for output strings to buffered os.Stdout.
// You may have to call stdout.Flush() finally.
func printf(format string, a ...interface{}) {
	fmt.Fprintf(stdout, format, a...)
}

/*********** Debugging ***********/

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

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

package main

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

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

	solve := func(Case int) {
		var n int
		Fscan(in, &n)
		a := make([]int, n)
		for i := range a {
			a[i] = i+1
		}
		Fprintln(out, 2)
		for i := n - 1; i>0; i-- {
			Fprintln(out, a[i], a[i-1])
			a[i-1] = (a[i]+a[i-1]+1)/2
		}
		//println(a[0])

		return
	}

	var t int
	Fscan(in, &t)
	for Case := 1; Case <= t; Case++ {
		solve(Case)
	}
}

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

package main

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

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

	var T, n int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		a := make([]int, n)
		for i := range a {
			a[i] = i + 1
		}
		Fprintln(out, 2)
		for i := n - 1; i > 0; i-- {
			Fprintln(out, a[i], a[i-1])
			a[i-1] = (a[i] + a[i-1] + 1) / 2
		}
	}
}

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

package main

import (
	"fmt"
)

type pair struct {
	f, s int
}

func main() {
	var test_case_count int

	for fmt.Scan(&test_case_count); test_case_count > 0; test_case_count-- {
		var n int
		fmt.Scan(&n)
		var a []int
		for k := 1; k <= n; k++ {
			a = append(a, k)
		}
		var ans []pair
		for len(a) > 1 {
			x := a[len(a) - 1]
			y := a[len(a) - 2]
			a[len(a) - 2] = (x + y + 1) / 2
			a = a[:len(a) - 1]
			ans = append(ans, pair{x, y})
		}

		fmt.Printf("%d\n", a[0])
		for k := 0; k < len(ans); k++ {
			fmt.Printf("%d %d\n", ans[k].f, ans[k].s)
		}
	}
}

package main

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

var reader = bufio.NewReader(os.Stdin)

type Pair struct {
	a, b int
}

func main() {
	var t int
	fmt.Fscan(reader, &t)

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

		sol := n
		pairs := []Pair{}
		for j := n - 1; j >= 1; j-- {
			pairs = append(pairs, Pair{sol, j})
			sol = (sol + j + 1) / 2
		}

		fmt.Println(sol)
		for _, p := range pairs {
			fmt.Println(p.a, p.b)
		}
	}
}

package main

import "fmt"

func calc(k uint64) {
	fmt.Printf("2\n")
	if k == 2 {
		fmt.Printf("%v %v\n", k, k-1)
		return
	}
	fmt.Printf("%v %v\n", k, k-2)
	fmt.Printf("%v %v\n", k-1, k-1)
	for j := int64(k - 1); j >= 3; j-- {
		fmt.Printf("%v %v\n", j, j-2)
	}
}

func main() {
	var n int64
	fmt.Scanf("%d\n", &n)
	r := make([]uint64, n)
	for j := int64(0); j < n; j++ {
		var n1 uint64
		fmt.Scanf("%d\n", &n1)
		r[j] = n1
	}

	for j := int64(0); j < n; j++ {
		calc(r[j])
	}
}

package main

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

var tempResultCache [][]int

func main() {
	var scanner = bufio.NewScanner(os.Stdin)
	var testCases int = convertInputToInt(stdInput(scanner, 1))[0]

	for i := 1; i <= testCases; i++ {
		tempResultCache = nil
		var numberSlice []int = createNumberSlice(
			convertInputToInt(stdInput(scanner, 1))[0])

		runTestCase(numberSlice)
	}
}

func stdInput(scanner *bufio.Scanner, varCount int) []string {
	var inputParameters []string

	scanner.Scan()
	input := strings.Split(scanner.Text(), " ")
	for i := 0; i < varCount; i++ {
		inputParameters = append(inputParameters, input[i])
	}
	return inputParameters
}

func convertInputToInt(variables []string) []int {
	var convertedInput []int
	for _, value := range variables {
		convertedVar, _ := strconv.Atoi(value)
		convertedInput = append(convertedInput, convertedVar)
	}
	return convertedInput
}

func createNumberSlice(number int) []int {
	numberSlice := make([]int, number)
	for i := 1; i <= number; i++ {
		numberSlice[i-1] = i
	}
	return numberSlice
}

func runTestCase(numberSlice []int) {
	n := len(numberSlice) - 1
	for i := 0; i < n; i++ {
		numberSlice = minimizeNumber(numberSlice)
	}
	showResult(numberSlice[0])
}

func minimizeNumber(numberSlice []int) []int {
	if len(numberSlice) <= 1 {
		return numberSlice
	}
	tempIndex := minimizeNumberAlgorithm(numberSlice)
	numberSlice = adjustNumberSlice(numberSlice, tempIndex)
	return numberSlice
}

func removeIndex(slice []int, index int) []int {
	return append(slice[:index], slice[index+1:]...)
}

func adjustNumberSlice(numberSlice []int, index int) []int {
	newNumber := (float64(numberSlice[index]) + float64(numberSlice[len(numberSlice)-1])) / 2.
	newNumber = math.Ceil(newNumber)
	// fmt.Println(numberSlice[index], numberSlice[len(numberSlice)-1])
	tempResultCache = append(
		tempResultCache,
		[]int{numberSlice[index], numberSlice[len(numberSlice)-1]})
	numberSlice = removeIndex(numberSlice, index)
	numberSlice = removeIndex(numberSlice, len(numberSlice)-1)
	numberSlice = append(numberSlice, int(newNumber))

	return numberSlice
}

func minimizeNumberAlgorithm(numberSlice []int) int {
	checkEqualNumber := minimizeNumberAlgorithmCheckEqualNumber(numberSlice)
	if checkEqualNumber != -1 {
		return checkEqualNumber
	}
	checkBestMatch := minimizeNumberAlgorithmCheckBestMatch(numberSlice)
	if checkBestMatch != -1 {
		return checkBestMatch
	}
	return 0
}

func minimizeNumberAlgorithmCheckEqualNumber(numberSlice []int) int {
	lastIndex := len(numberSlice) - 1
	if numberSlice[lastIndex] == numberSlice[lastIndex-1] {
		return lastIndex - 1
	}
	return -1
}

func minimizeNumberAlgorithmCheckBestMatch(numberSlice []int) int {
	lastIndex := len(numberSlice) - 1
	for i := lastIndex - 1; i >= 0; i-- {
		if (numberSlice[lastIndex]+numberSlice[i])%2 == 0 {
			return i
		}
	}
	return -1
}

func showResult(finalNumber int) {
	fmt.Println(finalNumber)
	for _, tuple := range tempResultCache {
		fmt.Println(tuple[0], tuple[1])
	}
}

package main

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

func div(a, b int) int {
	return int((float64(a) / float64(b)) + 0.5)
}

func NumbersOnWhiteBoard(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var T, N int

	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &N)
		var stack []int
		for i := 1; i <= N; i++ {
			stack = append(stack, i)
		}

		var result [][]int
		for len(stack) >= 2 {
			result = append(result, []int{stack[len(stack)-2], stack[len(stack)-1]})
			mid := div(stack[len(stack)-2]+stack[len(stack)-1], 2)
			stack = stack[:len(stack)-2]
			stack = append(stack, mid)
		}

		Fprintln(out, stack[0])
		for _, data := range result {
			Fprintln(out, data[0], data[1])
		}
	}
}

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

package main

import (
	"errors"
	"fmt"
)

type Stack struct{
	Tail *StackNode
}

type StackNode struct {
	Value uint32
	Next *StackNode
}

func (s *Stack) Push(value uint32) {

	if s.Tail == nil {
		s.Tail = &StackNode {Value: value, Next: nil}
	}   else {
		s.Tail = &StackNode {Value: value, Next:  s.Tail}
	}
}

func (s *Stack) Pop() (value uint32, err error){

	if s.Tail == nil {
		return 0, errors.New("StackUnderflow")
	}   else {

		v := s.Tail.Value

		s.Tail = s.Tail.Next

		return v, nil
	}
}

func Round (a uint32, b uint32) uint32{

if (a + b) % 2 == 0 {
return (a + b) / 2
} else {

return ((a + b) / 2) + 1
}

}

func main () {
	var lim uint32
	var t int

	s := Stack{}
	fmt.Scan(&t)

	for k := 1; k <= t; k++ {
		fmt.Scan(&lim)

		for i := 1; uint32 (i) <= lim; i++{
			s.Push(uint32(i))
		}
		fmt.Println(2)

		for ;; {
			a, _ := s.Pop()
			b, err := s.Pop()

			if err != nil {
				break
			}

			if a % 2 == 0 && b % 2 != 0 {

				c, _ := s.Pop()

				fmt.Println(a, c)
				c = Round(a, c)
				s.Push(b)
				s.Push(c)

			}   else {

				fmt.Println(a, b)
				s.Push(Round(a, b))
			}
		}

	}

}

package main

import (
	"errors"
	"fmt"
)

type Stack struct{
	Tail *StackNode
}

type StackNode struct {
	Value uint32
	Next *StackNode
}

func (s *Stack) Push(value uint32) {

	if s.Tail == nil {
		s.Tail = &StackNode {Value: value, Next: nil}
	}   else {
		s.Tail = &StackNode {Value: value, Next:  s.Tail}
	}
}

func (s *Stack) Pop() (value uint32, err error){

	if s.Tail == nil {
		return 1, errors.New("StackUnderflow")
	}   else {

		v := s.Tail.Value

		s.Tail = s.Tail.Next

		return v, nil
	}
}

func Round (a uint32, b uint32) uint32{

if (a + b) % 2 == 0 {
return (a + b) / 2
} else {

return ((a + b) / 2) + 1
}

}

func main () {
	var lim uint32
	var t int

	s := Stack{}
	fmt.Scan(&t)

	for k := 1; k <= t; k++ {
		fmt.Scan(&lim)

		for i := 1; uint32 (i) <= lim; i++{
			s.Push(uint32(i))
		}
		fmt.Println(2)

		for ;; {
			a, _ := s.Pop()
			b, _ := s.Pop()
			c, err := s.Pop()

			if err != nil {
				fmt.Println(a, b)
				break
			}

			if a % 2 == 0 && b % 2 != 0 {

				fmt.Println(c, a)
				c = Round(a, c)
				s.Push(b)
				s.Push(c)

			}   else {

				fmt.Println(b, a)
				s.Push(Round(a, b))
			}
		}

	}

}

package main

import (
	"errors"
	"fmt"
)

type Stack struct{
	Tail *StackNode
}

type StackNode struct {
	Value uint32
	Next *StackNode
}

func (s *Stack) Push(value uint32) {

	if s.Tail == nil {
		s.Tail = &StackNode {Value: value, Next: nil}
	}   else {
		s.Tail = &StackNode {Value: value, Next:  s.Tail}
	}
}

func (s *Stack) Pop() (value uint32, err error){

	if s.Tail == nil {
		return 0, errors.New("StackUnderflow")
	}   else {

		v := s.Tail.Value

		s.Tail = s.Tail.Next

		return v, nil
	}
}

func Round (a uint32, b uint32) uint32{

if (a + b) % 2 == 0 {
return (a + b) / 2
} else {

return ((a + b) / 2) + 1
}

}

func main () {
	var lim uint32
	var t int

	s := Stack{}
	fmt.Scan(&t)

	for k := 1; k <= t; k++ {
		fmt.Scan(&lim)

		for i := 1; uint32 (i) <= lim; i++{
			s.Push(uint32(i))
		}
		fmt.Println(2)

		for ;; {
			a, _ := s.Pop()
			b, err := s.Pop()

			if err != nil {
				break
			}

			if a % 2 == 0 && b % 2 != 0 {

				c, _ := s.Pop()

				fmt.Println(c, a)
				c = Round(a, c)
				s.Push(b)
				s.Push(c)

			}   else {

				fmt.Println(b, a)
				s.Push(Round(a, b))
			}
		}

	}

}

package main

import (
	"fmt"
	"bufio"
	"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...) }

func solve() {
	var n int
	scanf("%d\n", &n)
	ans := (n + 1) / 2
	printf("%d\n", ans)
	var l int
	l = 1
	if n % 2 == 0 {
		l = 2
	}
	cnt := 0
	for i := n; i > l; i-- {
		printf("%d %d\n", l, i)
		l++
		cnt++
	}
	if n % 2 == 1 {
		for ; cnt < n - 1; cnt++ {
			printf("%d %d\n", l, l)
		}
		return
	} else {
		for ; cnt < n - 2; cnt++ {
			printf("%d %d\n", l, l)
		}
		printf("%d %d", 1, l)
	}
}

func main() {
	defer writer.Flush()
	var t int
	scanf("%d\n", &t)
	for ; t > 0; t-- {
		solve()
	}
}

package main

import (
	"fmt"
	"bufio"
	"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...) }

func solve() {
	var n int
	scanf("%d\n", &n)
	ans := (n + 1) / 2
	if n == 2 {
		ans = 2
	}
	printf("%d\n", ans)
	var l int
	l = 1
	if n % 2 == 0 {
		l = 2
	}
	cnt := 0
	for i := n; i > l; i-- {
		printf("%d %d\n", l, i)
		l++
		cnt++
	}
	if n % 2 == 1 {
		for ; cnt < n - 1; cnt++ {
			printf("%d %d\n", l, l)
		}
		return
	} else {
		for ; cnt < n - 2; cnt++ {
			printf("%d %d\n", l, l)
		}
		printf("%d %d", 1, l)
	}
}

func main() {
	defer writer.Flush()
	var t int
	scanf("%d\n", &t)
	for ; t > 0; t-- {
		solve()
	}
}

package main

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

var reader = bufio.NewReader(os.Stdin)

func main() {
	var t int
	fmt.Fscan(reader, &t)

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

		sol := n
		for j := n - 1; j >= 1; j-- {
			fmt.Println(sol, j)
			sol = (sol + j + 1) / 2
		}

		fmt.Println(sol)
	}
}

package main

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

func main() {
	var scanner = bufio.NewScanner(os.Stdin)
	var testCases int = convertInputToInt(stdInput(scanner, 1))[0]
	var numberSlice []int = createNumberSlice(
		convertInputToInt(stdInput(scanner, 1))[0])

	runTestCases(testCases, numberSlice)

	// fmt.Println()
}

func stdInput(scanner *bufio.Scanner, varCount int) []string {
	var inputParameters []string

	scanner.Scan()
	input := strings.Split(scanner.Text(), " ")
	for i := 0; i < varCount; i++ {
		inputParameters = append(inputParameters, input[i])
	}
	return inputParameters
}

func convertInputToInt(variables []string) []int {
	var convertedInput []int
	for _, value := range variables {
		convertedVar, _ := strconv.Atoi(value)
		convertedInput = append(convertedInput, convertedVar)
	}
	return convertedInput
}

func createNumberSlice(number int) []int {
	numberSlice := make([]int, number)
	for i := 1; i <= number; i++ {
		numberSlice[i-1] = i
	}
	return numberSlice
}

func runTestCases(testCases int, numberSlice []int) {
	n := len(numberSlice) - 1
	for i := 0; i < n; i++ {
		numberSlice = minimizeNumber(numberSlice)
	}
}

func minimizeNumber(numberSlice []int) []int {
	if len(numberSlice) <= 1 {
		return numberSlice
	}
	tempIndex := minimizeNumberAlgorithm(numberSlice)
	numberSlice = adjustNumberSlice(numberSlice, tempIndex)
	return numberSlice
}

func removeIndex(slice []int, index int) []int {
	return append(slice[:index], slice[index+1:]...)
}

func adjustNumberSlice(numberSlice []int, index int) []int {
	newNumber := float64((numberSlice[index] + numberSlice[len(numberSlice)-1]) / 2)
	newNumber = math.Ceil(newNumber)
	fmt.Println(numberSlice[index], numberSlice[len(numberSlice)-1])
	numberSlice = removeIndex(numberSlice, index)
	numberSlice = removeIndex(numberSlice, len(numberSlice)-1)
	numberSlice = append(numberSlice, int(newNumber))
	return numberSlice
}

func minimizeNumberAlgorithm(numberSlice []int) int {
	checkEqualNumber := minimizeNumberAlgorithmCheckEqualNumber(numberSlice)
	if checkEqualNumber != -1 {
		return checkEqualNumber
	}
	checkBestMatch := minimizeNumberAlgorithmCheckBestMatch(numberSlice)
	if checkBestMatch != -1 {
		return checkBestMatch
	}

	return 0
}

func minimizeNumberAlgorithmCheckEqualNumber(numberSlice []int) int {
	lastIndex := len(numberSlice) - 1
	if numberSlice[lastIndex] == numberSlice[lastIndex-1] {
		return lastIndex - 1
	}
	return -1
}

func minimizeNumberAlgorithmCheckBestMatch(numberSlice []int) int {
	lastIndex := len(numberSlice) - 1
	for i := lastIndex - 1; i >= 0; i-- {
		if (numberSlice[lastIndex]+numberSlice[i])%2 == 0 {
			return i
		}
	}
	return -1
}

package main

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

var tempResultCache [][]int

func main() {
	var scanner = bufio.NewScanner(os.Stdin)
	var testCases int = convertInputToInt(stdInput(scanner, 1))[0]
	var numberSlice []int = createNumberSlice(
		convertInputToInt(stdInput(scanner, 1))[0])

	runTestCases(testCases, numberSlice)

	// fmt.Println()
}

func stdInput(scanner *bufio.Scanner, varCount int) []string {
	var inputParameters []string

	scanner.Scan()
	input := strings.Split(scanner.Text(), " ")
	for i := 0; i < varCount; i++ {
		inputParameters = append(inputParameters, input[i])
	}
	return inputParameters
}

func convertInputToInt(variables []string) []int {
	var convertedInput []int
	for _, value := range variables {
		convertedVar, _ := strconv.Atoi(value)
		convertedInput = append(convertedInput, convertedVar)
	}
	return convertedInput
}

func createNumberSlice(number int) []int {
	numberSlice := make([]int, number)
	for i := 1; i <= number; i++ {
		numberSlice[i-1] = i
	}
	return numberSlice
}

func runTestCases(testCases int, numberSlice []int) {
	n := len(numberSlice) - 1
	for i := 0; i < n; i++ {
		numberSlice = minimizeNumber(numberSlice)
	}
	showResult(numberSlice[0])
}

func minimizeNumber(numberSlice []int) []int {
	if len(numberSlice) <= 1 {
		return numberSlice
	}
	tempIndex := minimizeNumberAlgorithm(numberSlice)
	numberSlice = adjustNumberSlice(numberSlice, tempIndex)
	return numberSlice
}

func removeIndex(slice []int, index int) []int {
	return append(slice[:index], slice[index+1:]...)
}

func adjustNumberSlice(numberSlice []int, index int) []int {
	newNumber := float64((numberSlice[index] + numberSlice[len(numberSlice)-1]) / 2)
	newNumber = math.Ceil(newNumber)
	// fmt.Println(numberSlice[index], numberSlice[len(numberSlice)-1])
	tempResultCache = append(
		tempResultCache,
		[]int{numberSlice[index], numberSlice[len(numberSlice)-1]})
	numberSlice = removeIndex(numberSlice, index)
	numberSlice = removeIndex(numberSlice, len(numberSlice)-1)
	numberSlice = append(numberSlice, int(newNumber))
	return numberSlice
}

func minimizeNumberAlgorithm(numberSlice []int) int {
	checkEqualNumber := minimizeNumberAlgorithmCheckEqualNumber(numberSlice)
	if checkEqualNumber != -1 {
		return checkEqualNumber
	}
	checkBestMatch := minimizeNumberAlgorithmCheckBestMatch(numberSlice)
	if checkBestMatch != -1 {
		return checkBestMatch
	}

	return 0
}

func minimizeNumberAlgorithmCheckEqualNumber(numberSlice []int) int {
	lastIndex := len(numberSlice) - 1
	if numberSlice[lastIndex] == numberSlice[lastIndex-1] {
		return lastIndex - 1
	}
	return -1
}

func minimizeNumberAlgorithmCheckBestMatch(numberSlice []int) int {
	lastIndex := len(numberSlice) - 1
	for i := lastIndex - 1; i >= 0; i-- {
		if (numberSlice[lastIndex]+numberSlice[i])%2 == 0 {
			return i
		}
	}
	return -1
}

func showResult(finalNumber int) {
	fmt.Println(finalNumber)
	for _, tuple := range tempResultCache {
		fmt.Println(tuple[0], tuple[1])
	}
}

package main

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

var tempResultCache [][]int

func main() {
	var scanner = bufio.NewScanner(os.Stdin)
	var testCases int = convertInputToInt(stdInput(scanner, 1))[0]

	for i := 1; i <= testCases; i++ {
		tempResultCache = nil
		var numberSlice []int = createNumberSlice(
			convertInputToInt(stdInput(scanner, 1))[0])

		runTestCase(numberSlice)
	}
}

func stdInput(scanner *bufio.Scanner, varCount int) []string {
	var inputParameters []string

	scanner.Scan()
	input := strings.Split(scanner.Text(), " ")
	for i := 0; i < varCount; i++ {
		inputParameters = append(inputParameters, input[i])
	}
	return inputParameters
}

func convertInputToInt(variables []string) []int {
	var convertedInput []int
	for _, value := range variables {
		convertedVar, _ := strconv.Atoi(value)
		convertedInput = append(convertedInput, convertedVar)
	}
	return convertedInput
}

func createNumberSlice(number int) []int {
	numberSlice := make([]int, number)
	for i := 1; i <= number; i++ {
		numberSlice[i-1] = i
	}
	return numberSlice
}

func runTestCase(numberSlice []int) {
	n := len(numberSlice) - 1
	for i := 0; i < n; i++ {
		numberSlice = minimizeNumber(numberSlice)
	}
	showResult(numberSlice[0])
}

func minimizeNumber(numberSlice []int) []int {
	if len(numberSlice) <= 1 {
		return numberSlice
	}
	tempIndex := minimizeNumberAlgorithm(numberSlice)
	numberSlice = adjustNumberSlice(numberSlice, tempIndex)
	return numberSlice
}

func removeIndex(slice []int, index int) []int {
	return append(slice[:index], slice[index+1:]...)
}

func adjustNumberSlice(numberSlice []int, index int) []int {
	newNumber := float64((numberSlice[index] + numberSlice[len(numberSlice)-1]) / 2)
	newNumber = math.Ceil(newNumber)
	// fmt.Println(numberSlice[index], numberSlice[len(numberSlice)-1])
	tempResultCache = append(
		tempResultCache,
		[]int{numberSlice[index], numberSlice[len(numberSlice)-1]})
	numberSlice = removeIndex(numberSlice, index)
	numberSlice = removeIndex(numberSlice, len(numberSlice)-1)
	numberSlice = append(numberSlice, int(newNumber))
	return numberSlice
}

func minimizeNumberAlgorithm(numberSlice []int) int {
	checkEqualNumber := minimizeNumberAlgorithmCheckEqualNumber(numberSlice)
	if checkEqualNumber != -1 {
		return checkEqualNumber
	}
	checkBestMatch := minimizeNumberAlgorithmCheckBestMatch(numberSlice)
	if checkBestMatch != -1 {
		return checkBestMatch
	}

	return 0
}

func minimizeNumberAlgorithmCheckEqualNumber(numberSlice []int) int {
	lastIndex := len(numberSlice) - 1
	if numberSlice[lastIndex] == numberSlice[lastIndex-1] {
		return lastIndex - 1
	}
	return -1
}

func minimizeNumberAlgorithmCheckBestMatch(numberSlice []int) int {
	lastIndex := len(numberSlice) - 1
	for i := lastIndex - 1; i >= 0; i-- {
		if (numberSlice[lastIndex]+numberSlice[i])%2 == 0 {
			return i
		}
	}
	return -1
}

func showResult(finalNumber int) {
	fmt.Println(finalNumber)
	for _, tuple := range tempResultCache {
		fmt.Println(tuple[0], tuple[1])
	}
}


package main

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

// Pair holds left and right spread of an integer
type Pair struct {
	x, y int
}

// MAX is the array size
const MAX = 500005

var a [MAX]int
var last [MAX]int
var back [MAX]int
var p []Pair

// start of merge sort tree
var tree [20][MAX]int
var mx [20][MAX]int
var rgt [20][MAX]int

// mergeInit is the merge sort tree
func mergeInit(level, b, e int) {
	if b == e {
		tree[level][b] = b
		rgt[level][b] = p[b].y
		mx[level][b] = a[b]
		return
	}
	mid := (b + e) / 2
	mergeInit(level+1, b, mid)
	mergeInit(level+1, mid+1, e)
	i, j, idx := b, mid+1, b
	for i <= mid && j <= e {
		if p[tree[level+1][i]].x <= p[tree[level+1][j]].x {
			tree[level][idx] = tree[level+1][i]
			idx++
			i++
		} else {
			tree[level][idx] = tree[level+1][j]
			idx++
			j++
		}
	}
	for ; i <= mid; idx, i = idx+1, i+1 {
		tree[level][idx] = tree[level+1][i]
	}
	for ; j <= e; idx, j = idx+1, j+1 {
		tree[level][idx] = tree[level+1][j]
	}
	tempMax := 0
	tempMaxVal := 0
	for i = b; i <= e; i++ {
		if tempMax < p[tree[level][i]].y {
			tempMax = p[tree[level][i]].y
			tempMaxVal = a[tree[level][i]]
		}
		rgt[level][i] = tempMax
		mx[level][i] = tempMaxVal
	}
}

func query(level, b, e int, st, en *int) int {
	if b > *en || e < *st {
		return 0
	} else if b >= *st && e <= *en {
		return binarySearch(&level, &b, &e, st, en)
	}
	ret := query(level+1, b, (b+e)/2, st, en)
	if ret > 0 {
		return ret
	}
	return query(level+1, (b+e)/2+1, e, st, en)
}

func binarySearch(level, b, e, st, en *int) int {
	for low, high, mid := *b, *e, 0; low <= high; {
		mid = (low + high) >> 1
		if p[tree[*level][mid]].x <= *st && rgt[*level][mid] >= *en {
			return mx[*level][mid]
		} else if p[tree[*level][mid]].x <= *st {
			low = mid + 1
		} else {
			high = mid - 1
		}
	}
	return 0
}

// end of merge sort tree

func main() {
	var (
		n int
		q int
		l int
		r int
	)
	p = make([]Pair, MAX, MAX)
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)

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

	for i := 1; i <= n; i++ {
		fmt.Fscanf(reader, "%d", &a[i])
	}
	fmt.Fscanf(reader, "\n")
	//fmt.Println(a)

	for i := 1; i < MAX; i++ {
		last[i] = n + 1
	}

	for i := n; i >= 1; i-- {
		back[i] = last[a[i]]
		last[a[i]] = i
	}

	for i := 1; i < MAX; i++ {
		last[i] = 0
	}

	for i := 1; i <= n; i++ {
		p[i].x = last[a[i]] + 1
		p[i].y = back[i] - 1
		last[a[i]] = i
	}

	mergeInit(0, 1, n)

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

	for i := 0; i < q; i++ {
		fmt.Fscanf(reader, "%d %d\n", &l, &r)
		fmt.Fprintf(writer, "%d\n", query(0, 1, n, &l, &r))
	}
	writer.Flush()
}

/*

6
2 2 1 3 4 5
4
2 2
1 2
1 6
1 3

*/

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1000F(_r io.Reader, _w io.Writer) {
	out := bufio.NewWriter(_w)
	defer out.Flush()
	buf := make([]byte, 4096)
	_i := len(buf)
	rc := func() byte {
		if _i == len(buf) {
			_r.Read(buf)
			_i = 0
		}
		b := buf[_i]
		_i++
		return b
	}
	ri := func() (x int) {
		b := rc()
		for ; '0' > b; b = rc() {
		}
		for ; '0' <= b; b = rc() {
			x = x*10 + int(b&15)
		}
		return
	}
	type query struct{ bid, l, r, idx int }

	n := ri()
	a := make([]int, n)
	for i := range a {
		a[i] = ri()
	}
	q := ri()
	qs := make([]query, q)
	blockSize := int(math.Round(math.Sqrt(float64(n))))
	for i := range qs {
		l := ri()
		qs[i] = query{l / blockSize, l, ri() + 1, i}
	}
	sort.Slice(qs, func(i, j int) bool {
		qi, qj := qs[i], qs[j]
		if qi.bid != qj.bid {
			return qi.bid < qj.bid
		}
		if qi.bid&1 == 0 {
			return qi.r < qj.r
		}
		return qi.r > qj.r
	})

	cnt := [5e5 + 1]int{}
	del := [5e5 + 1]int{}
	s := []int{0}
	update := func(i, d int) {
		v := a[i-1]
		if cnt[v] == 1 {
			del[v]++
		}
		cnt[v] += d
		if cnt[v] == 1 {
			if del[v] > 0 {
				del[v]--
			} else {
				s = append(s, v)
			}
		}
	}
	ans := make([]int, q)
	l, r := 1, 1
	for _, q := range qs {
		for ; r < q.r; r++ {
			update(r, 1)
		}
		for ; l < q.l; l++ {
			update(l, -1)
		}
		for l > q.l {
			l--
			update(l, 1)
		}
		for r > q.r {
			r--
			update(r, -1)
		}
		for del[s[len(s)-1]] > 0 {
			del[s[len(s)-1]]--
			s = s[:len(s)-1]
		}
		ans[q.idx] = s[len(s)-1]
	}
	for _, v := range ans {
		Fprintln(out, v)
	}
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1000F(_r io.Reader, _w io.Writer) {
	out := bufio.NewWriter(_w)
	defer out.Flush()
	buf := make([]byte, 4096)
	_i := len(buf)
	rc := func() byte {
		if _i == len(buf) {
			_r.Read(buf)
			_i = 0
		}
		b := buf[_i]
		_i++
		return b
	}
	ri := func() (x int) {
		b := rc()
		for ; '0' > b; b = rc() {
		}
		for ; '0' <= b; b = rc() {
			x = x*10 + int(b&15)
		}
		return
	}
	type query struct{ bid, l, r, idx int }

	n := ri()
	a := make([]int, n)
	for i := range a {
		a[i] = ri()
	}
	q := ri()
	qs := make([]query, q)
	blockSize := int(math.Round(math.Sqrt(float64(n))))
	for i := range qs {
		l := ri()
		qs[i] = query{l / blockSize, l, ri() + 1, i}
	}
	sort.Slice(qs, func(i, j int) bool {
		qi, qj := qs[i], qs[j]
		if qi.bid != qj.bid {
			return qi.bid < qj.bid
		}
		if qi.bid&1 == 0 {
			return qi.r < qj.r
		}
		return qi.r > qj.r
	})

	cnt := [5e5 + 1]int{}
	del := [5e5 + 1]int{}
	s := []int{0}
	update := func(i, d int) {
		v := a[i-1]
		if cnt[v] == 1 {
			del[v]++
		}
		cnt[v] += d
		if cnt[v] == 1 {
			if del[v] > 0 {
				del[v]--
			} else {
				s = append(s, v)
			}
		}
	}
	ans := make([]int, q)
	l, r := 1, 1
	for _, q := range qs {
		for ; r < q.r; r++ {
			update(r, 1)
		}
		for ; l < q.l; l++ {
			update(l, -1)
		}
		for l > q.l {
			l--
			update(l, 1)
		}
		for r > q.r {
			r--
			update(r, -1)
		}
		for del[s[len(s)-1]] > 0 {
			del[s[len(s)-1]]--
			s = s[:len(s)-1]
		}
		ans[q.idx] = s[len(s)-1]
	}
	for _, v := range ans {
		Fprintln(out, v)
	}
}

func main() {
	debug.SetGCPercent(-1)
	CF1000F(os.Stdin, os.Stdout)
}

package main

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

// Pair holds left and right spread of an integer
type Pair struct {
	x, y int
}

// MAX is the array size
const MAX = 500005

var a [MAX]int
var last [MAX]int
var back [MAX]int
var p [MAX]Pair

// start of merge sort tree
var tree [20][MAX]int
var mx [20][MAX]int
var rgt [20][MAX]int

// mergeInit is the merge sort tree
func mergeInit(level, b, e int) {
	if b == e {
		tree[level][b] = b
		rgt[level][b] = p[b].y
		mx[level][b] = a[b]
		return
	}
	mid := (b + e) / 2
	mergeInit(level+1, b, mid)
	mergeInit(level+1, mid+1, e)
	i, j, idx := b, mid+1, b
	for i <= mid && j <= e {
		if p[tree[level+1][i]].x <= p[tree[level+1][j]].x {
			tree[level][idx] = tree[level+1][i]
			idx++
			i++
		} else {
			tree[level][idx] = tree[level+1][j]
			idx++
			j++
		}
	}
	for ; i <= mid; idx, i = idx+1, i+1 {
		tree[level][idx] = tree[level+1][i]
	}
	for ; j <= e; idx, j = idx+1, j+1 {
		tree[level][idx] = tree[level+1][j]
	}
	tempMax := 0
	tempMaxVal := 0
	for i = b; i <= e; i++ {
		if tempMax < p[tree[level][i]].y {
			tempMax = p[tree[level][i]].y
			tempMaxVal = a[tree[level][i]]
		}
		rgt[level][i] = tempMax
		mx[level][i] = tempMaxVal
	}
}

func query(level, b, e int, st, en *int) int {
	if b > *en || e < *st {
		return 0
	} else if b >= *st && e <= *en {
		return binarySearch(&level, &b, &e, st, en)
	}
	ret := query(level+1, b, (b+e)/2, st, en)
	if ret > 0 {
		return ret
	}
	return query(level+1, (b+e)/2+1, e, st, en)
}

func binarySearch(level, b, e, st, en *int) int {
	for low, high, mid := *b, *e, 0; low <= high; {
		mid = (low + high) >> 1
		if p[tree[*level][mid]].x <= *st && rgt[*level][mid] >= *en {
			return mx[*level][mid]
		} else if p[tree[*level][mid]].x <= *st {
			low = mid + 1
		} else {
			high = mid - 1
		}
	}
	return 0
}

// end of merge sort tree

func main() {
	var (
		n int
		q int
		l int
		r int
	)
	//p = make([]Pair, MAX, MAX)
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)

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

	for i := 1; i <= n; i++ {
		fmt.Fscanf(reader, "%d", &a[i])
	}
	fmt.Fscanf(reader, "\n")
	//fmt.Println(a)

	for i := 1; i < MAX; i++ {
		last[i] = n + 1
	}

	for i := n; i >= 1; i-- {
		back[i] = last[a[i]]
		last[a[i]] = i
	}

	for i := 1; i < MAX; i++ {
		last[i] = 0
	}

	for i := 1; i <= n; i++ {
		p[i].x = last[a[i]] + 1
		p[i].y = back[i] - 1
		last[a[i]] = i
	}

	mergeInit(0, 1, n)

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

	for i := 0; i < q; i++ {
		fmt.Fscanf(reader, "%d %d\n", &l, &r)
		fmt.Fprintf(writer, "%d\n", query(0, 1, n, &l, &r))
	}
	writer.Flush()
}

/*

6
2 2 1 3 4 5
4
2 2
1 2
1 6
1 3

*/

package main

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

// Pair holds left and right spread of an integer
type Pair struct {
	x, y int
}

// MAX is the array size
const MAX = 500005

var a [MAX]int
var last [MAX]int
var back [MAX]int
var p []Pair

// start of merge sort tree
var tree [20][MAX]int
var mx [20][MAX]int
var rgt [20][MAX]int

// mergeInit is the merge sort tree
func mergeInit(level, b, e int) {
	if b == e {
		tree[level][b] = b
		rgt[level][b] = p[b].y
		mx[level][b] = a[b]
		return
	}
	mid := (b + e) / 2
	mergeInit(level+1, b, mid)
	mergeInit(level+1, mid+1, e)
	i, j, idx := b, mid+1, b
	for i <= mid && j <= e {
		if p[tree[level+1][i]].x <= p[tree[level+1][j]].x {
			tree[level][idx] = tree[level+1][i]
			idx++
			i++
		} else {
			tree[level][idx] = tree[level+1][j]
			idx++
			j++
		}
	}
	for ; i <= mid; idx, i = idx+1, i+1 {
		tree[level][idx] = tree[level+1][i]
	}
	for ; j <= e; idx, j = idx+1, j+1 {
		tree[level][idx] = tree[level+1][j]
	}
	tempMax := 0
	tempMaxVal := 0
	for i = b; i <= e; i++ {
		if tempMax < p[tree[level][i]].y {
			tempMax = p[tree[level][i]].y
			tempMaxVal = a[tree[level][i]]
		}
		rgt[level][i] = tempMax
		mx[level][i] = tempMaxVal
	}
}

func query(level, b, e int, st, en *int) int {
	if b > *en || e < *st {
		return 0
	} else if b >= *st && e <= *en {
		return binarySearch(&level, &b, &e, st, en)
	}
	ret := query(level+1, b, (b+e)/2, st, en)
	if ret > 0 {
		return ret
	}
	return query(level+1, (b+e)/2+1, e, st, en)
}

func binarySearch(level, b, e, st, en *int) int {
	for low, high, mid := *b, *e, 0; low <= high; {
		mid = (low + high) >> 1
		if p[tree[*level][mid]].x <= *st && rgt[*level][mid] >= *en {
			return mx[*level][mid]
		} else if p[tree[*level][mid]].x <= *st {
			low = mid + 1
		} else {
			high = mid - 1
		}
	}
	return 0
}

// end of merge sort tree

func main() {
	var (
		n int
		q int
		l int
		r int
	)
	p = make([]Pair, MAX, MAX)
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)

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

	for i := 1; i <= n; i++ {
		fmt.Fscanf(reader, "%d", &a[i])
	}
	fmt.Fscanf(reader, "\n")
	//fmt.Println(a)

	for i := 1; i < MAX; i++ {
		last[i] = n + 1
	}

	for i := n; i >= 1; i-- {
		back[i] = last[a[i]]
		last[a[i]] = i
	}

	for i := 1; i < MAX; i++ {
		last[i] = 0
	}

	for i := 1; i <= n; i++ {
		p[i].x = last[a[i]] + 1
		p[i].y = back[i] - 1
		last[a[i]] = i
	}

	mergeInit(0, 1, n)

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

	for i := 0; i < q; i++ {
		fmt.Fscanf(reader, "%d %d\n", &l, &r)
		fmt.Fprintln(writer, query(0, 1, n, &l, &r))
	}
	writer.Flush()
}

/*

6
2 2 1 3 4 5
4
2 2
1 2
1 6
1 3

*/

package main

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

// Pair holds left and right spread of an integer
type Pair struct {
	x, y int
}

// MAX is the array size
const MAX = 500005

var a [MAX]int
var last [MAX]int
var back [MAX]int
var p []Pair

// start of merge sort tree
var tree [20][MAX]int
var mx [20][MAX]int
var rgt [20][MAX]int

// mergeInit is the merge sort tree
func mergeInit(level, b, e int) {
	if b == e {
		tree[level][b] = b
		rgt[level][b] = p[b].y
		mx[level][b] = a[b]
		return
	}
	mid := (b + e) / 2
	mergeInit(level+1, b, mid)
	mergeInit(level+1, mid+1, e)
	i, j, idx := b, mid+1, b
	for i <= mid && j <= e {
		if p[tree[level+1][i]].x <= p[tree[level+1][j]].x {
			tree[level][idx] = tree[level+1][i]
			idx++
			i++
		} else {
			tree[level][idx] = tree[level+1][j]
			idx++
			j++
		}
	}
	for ; i <= mid; idx, i = idx+1, i+1 {
		tree[level][idx] = tree[level+1][i]
	}
	for ; j <= e; idx, j = idx+1, j+1 {
		tree[level][idx] = tree[level+1][j]
	}
	tempMax := 0
	tempMaxVal := 0
	for i = b; i <= e; i++ {
		if tempMax < p[tree[level][i]].y {
			tempMax = p[tree[level][i]].y
			tempMaxVal = a[tree[level][i]]
		}
		rgt[level][i] = tempMax
		mx[level][i] = tempMaxVal
	}
}

var st int
var en int

func query(level, b, e int) int {
	if b > en || e < st {
		return 0
	} else if b >= st && e <= en {
		return binarySearch(&level, &b, &e)
	}
	ret := query(level+1, b, (b+e)/2)
	if ret > 0 {
		return ret
	}
	return query(level+1, (b+e)/2+1, e)
}

func binarySearch(level, b, e *int) int {
	for low, high, mid := *b, *e, 0; low <= high; {
		mid = (low + high) >> 1
		if p[tree[*level][mid]].x <= st && rgt[*level][mid] >= en {
			return mx[*level][mid]
		} else if p[tree[*level][mid]].x <= st {
			low = mid + 1
		} else {
			high = mid - 1
		}
	}
	return 0
}

// end of merge sort tree

func main() {
	var (
		n int
		q int
		l int
		r int
	)
	p = make([]Pair, MAX, MAX)
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)

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

	for i := 1; i <= n; i++ {
		fmt.Fscanf(reader, "%d", &a[i])
	}
	fmt.Fscanf(reader, "\n")
	//fmt.Println(a)

	for i := 1; i < MAX; i++ {
		last[i] = n + 1
	}

	for i := n; i >= 1; i-- {
		back[i] = last[a[i]]
		last[a[i]] = i
	}

	for i := 1; i < MAX; i++ {
		last[i] = 0
	}

	for i := 1; i <= n; i++ {
		p[i].x = last[a[i]] + 1
		p[i].y = back[i] - 1
		last[a[i]] = i
	}

	mergeInit(0, 1, n)

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

	for i := 0; i < q; i++ {
		fmt.Fscanf(reader, "%d %d\n", &l, &r)
		st = l
		en = r
		fmt.Fprintf(writer, "%d\n", query(0, 1, n))
	}
	writer.Flush()
}

/*

6
2 2 1 3 4 5
4
2 2
1 2
1 6
1 3

*/