Your math teacher gave you the following problem:There are $$$n$$$ segments on the $$$x$$$-axis, $$$[l_1; r_1], [l_2; r_2], \ldots, [l_n; r_n]$$$. The segment $$$[l; r]$$$ includes the bounds, i.e. it is a set of such $$$x$$$ that $$$l \le x \le r$$$. The length of the segment $$$[l; r]$$$ is equal to $$$r - l$$$.Two segments $$$[a; b]$$$ and $$$[c; d]$$$ have a common point (intersect) if there exists $$$x$$$ that $$$a \leq x \leq b$$$ and $$$c \leq x \leq d$$$. For example, $$$[2; 5]$$$ and $$$[3; 10]$$$ have a common point, but $$$[5; 6]$$$ and $$$[1; 4]$$$ don't have.You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given $$$n$$$ segments.In other words, you need to find a segment $$$[a; b]$$$, such that $$$[a; b]$$$ and every $$$[l_i; r_i]$$$ have a common point for each $$$i$$$, and $$$b-a$$$ is minimal.

The first line contains integer number $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of segments. The following $$$n$$$ lines contain segment descriptions: the $$$i$$$-th of them contains two integers $$$l_i,r_i$$$ ($$$1 \le l_i \le r_i \le 10^{9}$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.

For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.

NoteIn the first test case of the example, we can choose the segment $$$[5;7]$$$ as the answer. It is the shortest segment that has at least one common point with all given segments.

package main

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

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

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

func init() {
	var f *os.File
	if runtime.GOROOT() == "C:\\SOFT\\Go" {
		f, _ = os.Open("input.txt")
		//defer f.Close()
	} else {
		f = os.Stdin
	}
	ReadString = newReadString(f)
	stdout = bufio.NewWriter(os.Stdout)
}

func newReadString(ior io.Reader) func() string {
	r := bufio.NewScanner(ior)
	// r.Buffer(make([]byte, 1024), int(1e+11)) // for AtCoder
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	// Split sets the split function for the Scanner. The default split function is ScanLines.
	// Split panics if it is called after scanning has started.
	r.Split(bufio.ScanWords)

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

// ReadInt returns an integer.
func ReadInt() int {
	return int(readInt64())
}
func ReadInt2() (int, int) {
	return int(readInt64()), int(readInt64())
}
func ReadInt3() (int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64())
}
func ReadInt4() (int, int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64()), int(readInt64())
}

// ReadInt64 returns as integer as int64.
func ReadInt64() int64 {
	return readInt64()
}
func ReadInt64_2() (int64, int64) {
	return readInt64(), readInt64()
}
func ReadInt64_3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func ReadInt64_4() (int64, int64, int64, int64) {
	return readInt64(), readInt64(), readInt64(), readInt64()
}

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

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

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

// ReadFloat64 returns an float64.
func ReadFloat64() float64 {
	return float64(readFloat64())
}

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

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

// ReadRuneSlice returns a rune slice.
func ReadRuneSlice() []rune {
	return []rune(ReadString())
}

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

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

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

	return s
}

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

	if e == 0 {
		return 1
	}

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

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

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

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

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

	return a
}

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

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

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

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

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

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

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

	return string(res)
}

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

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

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

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

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

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

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

func solve() {
	n := ReadInt()
	lmax := ReadInt()
	lmin:= lmax
	rmin := ReadInt()
	rmax:= rmin
	for i:=1; i<n;i++{
		l := ReadInt()
		r := ReadInt()
		if l> lmax {
			lmax =l
		} else if l<lmin{
			lmin=l
		}
		if r< rmin {
			rmin =r
		} else if r>rmax{
			rmax=r
		}
	}
	if rmin>lmax {
		fmt.Println(0)
	}else {
		fmt.Println(AbsInt(rmin - lmax))
	}
}

func main() {
	t := ReadInt()
	//t :=1
	for ; t > 0; t-- {
		solve()
	}
}

package main

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

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

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

func init() {
	ReadString = newReadString(os.Stdin)
	stdout = bufio.NewWriter(os.Stdout)
}

func newReadString(ior io.Reader) func() string {
	r := bufio.NewScanner(ior)
	// r.Buffer(make([]byte, 1024), int(1e+11)) // for AtCoder
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	// Split sets the split function for the Scanner. The default split function is ScanLines.
	// Split panics if it is called after scanning has started.
	r.Split(bufio.ScanWords)

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

// ReadInt returns an integer.
func ReadInt() int {
	return int(readInt64())
}
func ReadInt2() (int, int) {
	return int(readInt64()), int(readInt64())
}
func ReadInt3() (int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64())
}
func ReadInt4() (int, int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64()), int(readInt64())
}

// ReadInt64 returns as integer as int64.
func ReadInt64() int64 {
	return readInt64()
}
func ReadInt64_2() (int64, int64) {
	return readInt64(), readInt64()
}
func ReadInt64_3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func ReadInt64_4() (int64, int64, int64, int64) {
	return readInt64(), readInt64(), readInt64(), readInt64()
}

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

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

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

// ReadFloat64 returns an float64.
func ReadFloat64() float64 {
	return float64(readFloat64())
}

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

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

// ReadRuneSlice returns a rune slice.
func ReadRuneSlice() []rune {
	return []rune(ReadString())
}

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

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

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

	return s
}

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

	if e == 0 {
		return 1
	}

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

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

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

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

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

	return a
}

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

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

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

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

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

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		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)
}

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

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

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

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

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

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

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

var t int
var n int
var L, R []int

func main() {
	t = ReadInt()

	for tc := 0; tc < t; tc++ {
		n = ReadInt()
		L, R = make([]int, n), make([]int, n)
		for i := 0; i < n; i++ {
			l, r := ReadInt2()
			L[i], R[i] = l, r
		}
		solve()
	}
}

func solve() {
	minR, maxL := 1000000000+5, 0
	for i := 0; i < n; i++ {
		ChMin(&minR, R[i])
		ChMax(&maxL, L[i])
	}
	fmt.Println(Max(maxL-minR, 0))
}

/*
- MODは最後にとりましたか？
- ループを抜けた後も処理が必要じゃありませんか？
- 和・積・あまりを求められたらint64が必要ではありませんか？
*/

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

package main

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

func solve(reader io.Reader, writer io.Writer) {
	in := bufio.NewReader(reader)
	out := bufio.NewWriter(writer)
	defer out.Flush()

	var t int
	for Fscan(in, &t); t > 0; t-- {
		var n int
		Fscan(in, &n)
		minR := int(1e9)
		maxL := 0
		for i := 0; i < n; i++ {
			var l, r int
			Fscan(in, &l, &r)
			minR = min(minR, r)
			maxL = max(maxL, l)
		}
		if n == 1 {
			Fprintln(out, 0)
			continue
		}
		if maxL > minR {
			Fprintln(out, maxL-minR)
		} else {
			Fprintln(out, 0)
		}
	}

}

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

func ifElseI(cond bool, a, b int) int {
	if cond {
		return a
	}
	return b
}
func ifElseS(cond bool, a, b string) string {
	if cond {
		return a
	}
	return b
}
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
}

package main

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

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

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

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

		max := -1
		min := -1
		var a, b int
		for j := 0; j < n; j++ {
			fmt.Fscan(in, &a, &b)

			if max == -1 || max < a {
				max = a
			}
			if min == -1 || min > b {
				min = b
			}
		}
		if min > max {
			fmt.Println(0)
		} else {
			fmt.Println(max - min)
		}
	}
}

package main

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

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

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

func init() {
	var f *os.File
	if runtime.GOROOT() == "C:\\SOFT\\Go" {
		f, _ = os.Open("input.txt")
		//defer f.Close()
	} else {
		f = os.Stdin
	}
	ReadString = newReadString(f)
	stdout = bufio.NewWriter(os.Stdout)
}

func newReadString(ior io.Reader) func() string {
	r := bufio.NewScanner(ior)
	// r.Buffer(make([]byte, 1024), int(1e+11)) // for AtCoder
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	// Split sets the split function for the Scanner. The default split function is ScanLines.
	// Split panics if it is called after scanning has started.
	r.Split(bufio.ScanWords)

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

// ReadInt returns an integer.
func ReadInt() int {
	return int(readInt64())
}
func ReadInt2() (int, int) {
	return int(readInt64()), int(readInt64())
}
func ReadInt3() (int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64())
}
func ReadInt4() (int, int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64()), int(readInt64())
}

// ReadInt64 returns as integer as int64.
func ReadInt64() int64 {
	return readInt64()
}
func ReadInt64_2() (int64, int64) {
	return readInt64(), readInt64()
}
func ReadInt64_3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func ReadInt64_4() (int64, int64, int64, int64) {
	return readInt64(), readInt64(), readInt64(), readInt64()
}

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

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

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

// ReadFloat64 returns an float64.
func ReadFloat64() float64 {
	return float64(readFloat64())
}

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

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

// ReadRuneSlice returns a rune slice.
func ReadRuneSlice() []rune {
	return []rune(ReadString())
}

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

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

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

	return s
}

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

	if e == 0 {
		return 1
	}

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

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

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

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

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

	return a
}

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

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

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

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

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

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

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

	return string(res)
}

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

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

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

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

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

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

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

func solve() {
	n := ReadInt()
	lm:= ReadInt()
	rm:= ReadInt()
	for i:=1; i<n;i++{
		l := ReadInt()
		r := ReadInt()
		if l>lm {lm=l}
		if r<rm {rm=r}
	}
	if n==1 {
		rm=lm
	}
	fmt.Println(AbsInt(rm-lm))
}

func main() {
	t := ReadInt()
	//t :=1
	for ; t > 0; t-- {
		solve()
	}
}


Yaroslav has an array, consisting of (2·n - 1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1.Yaroslav is now wondering: what maximum sum of array elements can be obtained if it is allowed to perform any number of described operations?Help Yaroslav.

The first line contains an integer n (2 ≤ n ≤ 100). The second line contains (2·n - 1) integers — the array elements. The array elements do not exceed 1000 in their absolute value.

In a single line print the answer to the problem — the maximum sum that Yaroslav can get.

NoteIn the first sample you do not need to change anything. The sum of elements equals 150.In the second sample you need to change the sign of the first two elements. Then we get the sum of the elements equal to 100.

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n int
	fmt.Scan(&n)
	numbers := make([]int, 2 * n - 1)
	for i := range numbers {
		fmt.Scan(&numbers[i])
	}
	sort.Ints(numbers)
	neg := 0
	for neg < len(numbers) && numbers[neg] < 0 {
		neg++
	}
	if neg % 2 == 1 && n % 2 == 1 {
		numbers[neg - 1] *= -1
		neg--
	}
	for i := 0; i < neg / 2 * 2; i++ {
		numbers[i] *= -1
	}
	sort.Ints(numbers)
	if numbers[0] + numbers[1] < -numbers[0] - numbers[1] {
		numbers[0] *= -1
		numbers[1] *= -1
	}
	sum := 0
	for _, v := range numbers {
		sum += v
	}
	fmt.Println(sum)
}

package main

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

var w *bufio.Writer

var sc *bufio.Scanner

const minus, zero byte = '-', '0'

func nextInt() int {
	var ans, fst int = 0, 0
	var neg bool = false
	sc.Scan()
	if sc.Bytes()[0] == minus {
		fst = 1
		neg = true
	}
	for _, j := range sc.Bytes()[fst:] {
		ans = ans*10 + int(j-zero)
	}
	if neg == true {
		ans = -ans
	}
	return ans
}

func main() {

	w = bufio.NewWriter(os.Stdout)
	sc = bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)

	n := nextInt()
	k := 2*n - 1
	a := make([]int, k, k)
	var cm, cp, cz, ans int = 0, 0, 0, 0
	for i := 0; i < k; i++ {
		a[i] = nextInt()
		if a[i] < 0 {
			cm += 1
			a[i] = -a[i]
		} else if a[i] > 0 {
			cp += 1
		} else {
			cz += 1
		}
	}
	sort.Ints(a)
	rem := cm % n
	if n%2 == 0 && rem%2 == 1 {
		rem = 1
	} else {
		rem = 0
	}
	if cz >= rem {
		rem = 0
	}
	for i := 0; i < rem; i++ {
		ans -= a[i]
	}
	for i := rem; i < k; i++ {
		ans += a[i]
	}

	w.WriteString(strconv.Itoa(ans))

	w.Flush()
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n int
	fmt.Scan(&n)
	numbers := make([]int, 2 * n - 1)
	for i := range numbers {
		fmt.Scan(&numbers[i])
	}
	sort.Ints(numbers)
	neg := 0
	for neg < len(numbers) && numbers[neg] < 0 {
		neg++
	}
	for i := 0; i < neg / 2 * 2; i++ {
		numbers[i] *= -1
	}
	sort.Ints(numbers)
	if numbers[0] + numbers[1] < -numbers[0] - numbers[1] {
		numbers[0] *= -1
		numbers[1] *= -1
	}
	sum := 0
	for _, v := range numbers {
		sum += v
	}
	fmt.Println(sum)
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n int
	fmt.Scan(&n)
	numbers := make([]int, 2 * n - 1)
	for i := range numbers {
		fmt.Scan(&numbers[i])
	}
	sort.Ints(numbers)
	neg := 0
	for neg < len(numbers) && numbers[neg] < 0 {
		neg++
	}
	if neg >= n && neg % 2 == 1 {
		for i := 0; i < n; i++ {
			numbers[i] *= -1
		}
		sort.Ints(numbers)
		neg = 0
		for neg < len(numbers) && numbers[neg] < 0 {
			neg++
		}
	}
	for i := 0; i < neg / 2 * 2; i++ {
		numbers[i] *= -1
	}
	sort.Ints(numbers)
	if numbers[0] + numbers[1] < -numbers[0] - numbers[1] {
		numbers[0] *= -1
		numbers[1] *= -1
	}
	sum := 0
	for _, v := range numbers {
		sum += v
	}
	fmt.Println(sum)
}

package main

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

var w *bufio.Writer

var sc *bufio.Scanner

const minus, zero byte = '-', '0'

func nextInt() int {
	var ans, fst int = 0, 0
	var neg bool = false
	sc.Scan()
	if sc.Bytes()[0] == minus {
		fst = 1
		neg = true
	}
	for _, j := range sc.Bytes()[fst:] {
		ans = ans*10 + int(j-zero)
	}
	if neg == true {
		ans = -ans
	}
	return ans
}

func main() {

	w = bufio.NewWriter(os.Stdout)
	sc = bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)

	n := nextInt()
	k := 2*n - 1
	a := make([]int, k, k)
	var cm, cp, cz, ans int = 0, 0, 0, 0
	for i := 0; i < k; i++ {
		a[i] = nextInt()
		if a[i] < 0 {
			cm += 1
			a[i] = -a[i]
		} else if a[i] > 0 {
			cp += 1
		} else {
			cz += 1
		}
	}
	sort.Ints(a)
	rem := cm%n - cp - cz
	if rem > n-rem {
		rem = n - rem
	}
	if rem < 0 {
		rem = 0
	}
	for i := 0; i < rem; i++ {
		ans -= a[i]
	}
	for i := rem; i < k; i++ {
		ans += a[i]
	}

	w.WriteString(strconv.Itoa(ans))

	w.Flush()
}


In Berland, $$$n$$$ different types of banknotes are used. Banknotes of the $$$i$$$-th type have denomination $$$10^{a_i}$$$ burles (burles are the currency used in Berland); the denomination of banknotes of the first type is exactly $$$1$$$.Let's denote $$$f(s)$$$ as the minimum number of banknotes required to represent exactly $$$s$$$ burles. For example, if the denominations of banknotes used in Berland are $$$1$$$, $$$10$$$ and $$$100$$$, then $$$f(59) = 14$$$: $$$9$$$ banknotes with denomination of $$$1$$$ burle and $$$5$$$ banknotes with denomination of $$$10$$$ burles can be used to represent exactly $$$9 \cdot 1 + 5 \cdot 10 = 59$$$ burles, and there's no way to do it with fewer banknotes.For a given integer $$$k$$$, find the minimum positive number of burles $$$s$$$ that cannot be represented with $$$k$$$ or fewer banknotes (that is, $$$f(s) > k$$$).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10; 1 \le k \le 10^9$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 = a_1 < a_2 < \dots < a_n \le 9$$$).

For each test case, print one integer — the minimum positive number of burles $$$s$$$ that cannot be represented with $$$k$$$ or fewer banknotes.

package main

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

const (
	MaxUint = ^uint(0)
	MinUint = 0
	MaxInt = int(MaxUint >> 1)
	MinInt = -MaxInt - 1
)

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

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

// end of template

func solve(in *bufio.Reader, out *bufio.Writer){
	defer out.Flush()
	var n int
	var k int64

	fmt.Fscan(in, &n, &k)
	number := make([]int64, n)
	pow := make([]int64, n)

	for i:=0 ; i<n ; i++ {
		fmt.Fscan(in, &number[i])
		pow[i] = int64(math.Pow(10,float64(number[i])))
	}

	now := k + 1
	idx := 0

	for idx < n {
		if idx != 0 {
			if now < pow[idx] {
				now += (pow[idx-1] - 1)
				break
			}
			now = (now - (pow[idx] - pow[idx-1])) / pow[idx-1] * pow[idx]
		}
		idx++
	}
	if idx == n {
		now += (pow[idx-1] - 1)
	}

	fmt.Fprintln(out, now)
	return
}

func main(){
	var tc int
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)

	fmt.Fscan(in, &tc)
	for t:=0 ; t<tc ; t++ {
		solve(in, out)
	}
}

package main

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

const (
	MaxUint = ^uint(0)
	MinUint = 0
	MaxInt = int(MaxUint >> 1)
	MinInt = -MaxInt - 1
)

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

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

// end of template

func solve(in *bufio.Reader){
	var n int
	var k int64

	fmt.Fscan(in, &n, &k)
	number := make([]int64, n)
	pow := make([]int64, n)

	for i:=0 ; i<n ; i++ {
		fmt.Fscan(in, &number[i])
		pow[i] = int64(math.Pow(10,float64(number[i])))
	}

	now := k + 1
	idx := 0

	for idx < n {
		if idx != 0 {
			if now < pow[idx] {
				now += (pow[idx-1] - 1)
				break
			}
			now = (now - (pow[idx] - pow[idx-1])) / pow[idx-1] * pow[idx]
		}
		idx++
	}
	if idx == n {
		now += (pow[idx-1] - 1)
	}

	fmt.Println(now)
	return
}

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

	fmt.Fscan(in, &tc)
	for t:=0 ; t<tc ; t++ {
		solve(in)
	}
}

package main

import (
	"fmt"
	"math"
)

const (
	MaxUint = ^uint(0)
	MinUint = 0
	MaxInt = int(MaxUint >> 1)
	MinInt = -MaxInt - 1
)

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

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

// end of template

func solve(){
	var n int
	var k int64

	fmt.Scan(&n, &k)
	number := make([]int64, n)
	pow := make([]int64, n)

	for i:=0 ; i<n ; i++ {
		fmt.Scan(&number[i])
		pow[i] = int64(math.Pow(10,float64(number[i])))
	}

	now := k + 1
	idx := 0

	for idx < n {
		if idx != 0 {
			if now < pow[idx] {
				now += (pow[idx-1] - 1)
				break
			}
			now = (now - (pow[idx] - pow[idx-1])) / pow[idx-1] * pow[idx]
		}
		idx++
	}
	if idx == n {
		now += (pow[idx-1] - 1)
	}

	fmt.Println(now)
	return
}

func main(){
	var tc int

	fmt.Scan(&tc)
	for t:=0 ; t<tc ; t++ {
		solve()
	}
}

package main

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

func solveC(my []int64, k int64) int64 {
	if my[0] != 0 {
		return 1
	}

	var result int64 = 0
	var i int
	for i = 1; i < len(my); i++ {
		bill := int64(math.Pow10(int(my[i-1])))
		needNum := int64(math.Pow10(int(my[i]-my[i-1]))) - 1
		if k >= needNum {
			result += bill * needNum
			k -= needNum
		} else {
			break
		}
	}

	bill := int64(math.Pow10(int(my[i-1])))
	needNum := k + 1 // 求凑不成的数，所以需要k+1
	result += bill * needNum

	return result
}

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

	var n int
	var t, k int64
	fmt.Fscan(input, &t)

	for t > 0 {
		t--
		fmt.Fscan(input, &n, &k)
		my := make([]int64, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(input, &my[i])
		}

		result := solveC(my, k)
		fmt.Println(result)
	}
}

package main

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

func solveC(my []int64, k int64) int64 {
	if my[0] != 0 {
		return 1
	}

	var result int64 = 0
	var i int
	for i = 1; i < len(my); i++ {
		bill := int64(math.Pow10(int(my[i-1])))
		needNum := int64(math.Pow10(int(my[i]-my[i-1]))) - 1
		if k >= needNum {
			result += bill * needNum
			k -= needNum
		} else {
			break
		}
	}

	i--
	k++
	if k > 0 {
		bill := int64(math.Pow10(int(my[i])))
		needNum := k
		result += bill * needNum
	}

	return result
}

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

	var n int
	var t, k int64
	fmt.Fscan(input, &t)

	for t > 0 {
		t--
		fmt.Fscan(input, &n, &k)
		my := make([]int64, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(input, &my[i])
		}

		result := solveC(my, k)
		fmt.Println(result)
	}
}

package main

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

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

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

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

		tot := k
		var d int
		for i := 1; i < n; i++ {
			if tot+int64(math.Pow10(aa[i-1])) < int64(math.Pow10(aa[i])) {
				break
			}

			b := int64(math.Pow10(aa[i]-aa[i-1]) - 1)
			tot = tot - k*int64(math.Pow10(aa[i-1])) + b*int64(math.Pow10(aa[i-1]))
			k -= b
			tot += k * int64(math.Pow10(aa[i]))
			d = aa[i]
		}
		fmt.Fprintln(out, tot+int64(math.Pow10(d)))

	}
}

package main

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

func pow10(pw int) int64 {
	res := int64(1)
	for i := 0; i < pw; i++ {
		res *= 10
	}
	return res
}

func solve(in *bufio.Reader) int64 {
	var n, k int
	fmt.Fscan(in, &n)
	fmt.Fscan(in, &k)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &a[i])
	}
	k++
	var ans int64
	for i := 0; i < n && k > 0; i++ {
		canUse := int64(k)
		if i < n-1 {
			canUse = pow10(a[i+1]-a[i]) - 1
		}
		if canUse > int64(k) {
			canUse = int64(k)
		}
		ans += pow10(a[i]) * canUse
		k -= int(canUse)
	}
	return ans
}

func main() {
	var T int
	in := bufio.NewReader(os.Stdin)
	fmt.Fscan(in, &T)
	for i := 0; i < T; i++ {
		fmt.Println(solve(in))
	}
}

package main

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

var n int
var k int64

var a []int

func main() {

	r := bufio.NewReader(os.Stdin)

	var t int
	fmt.Fscan(r, &t)

	for i := 0; i < t; i++ {
		fmt.Fscan(r, &n, &k)

		a = make([]int, n)

		for j := 0; j < n; j++ {
			fmt.Fscan(r, &a[j])
		}

		ans := solve()
		fmt.Println(ans)
	}
}

var b[]int64

func solve() int64 {

	b = make([]int64, n)

	for j := 0; j < n; j++ {
		b[j] = pow(a[j])
	}

	for i := 1; i <= 18; i++ {
		num := pow(i)
		num--

		temp := num

		var tot int64

		for j := n - 1; j >= 0; j-- {
			if b[j] > temp {
				continue
			}

			d := temp/b[j]

			tot +=d

			temp = num % b[j]

			if temp == 0 {
				break
			}
		}
		if tot > k {

			var p int64

			if i > a[n - 1] {
				 p = b[n - 1]
			}

			for j := n - 1; j >= 0; j-- {
				if a[j] < i {
					p = b[j]
					break
				}
			}

			diff := tot - k - 1

			return num - p * diff

		}
	}

	return -1
}

func pow(n int) int64 {
	var m int64 = 1
	for k := 0; k < n; k++ {
		m *= 10
	}
	return m
}

package main

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

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

	var T, n, k int64
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &k)
		k++
		a := make([]int, n)
		for i := range a {
			Fscan(in, &a[i])
		}
		ans := int64(0)
		for i, v := range a[:n-1] {
			w := int64(math.Pow10(a[i+1] - v))
			if w > k {
				ans += k * int64(math.Pow10(v))
				k = 0
				break
			}
			w--
			ans += w * int64(math.Pow10(v))
			k -= w
		}
		if k > 0 {
			ans += k * int64(math.Pow10(a[n-1]))
		}
		Fprintln(out, ans)
	}
}

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

package main

import (
	"bufio"
	"fmt"
	"os"
)
func min (x,y int64)int64{
	if x<y{
		return x
	}
	return y
}
func main() {
 	var t int
 	in := bufio.NewReader(os.Stdin)
 	out := os.Stdout
 	fmt.Fscan(in,&t)
 	for u:=1;u<=t;u++{
 		var n, k int
 		fmt.Fscan(in,&n,&k)
 		k++
 		l := []int{}
 		for i:=0;i<n;i++{
 			var a int
 			fmt.Fscan(in,&a)
			l = append(l,a)
		}
 		var ans int64
 		ans = 0
 		for i:=0;i<len(l);i++{
 			if i!=len(l)-1{
 				dif := l[i+1]-l[i]
 				b := 9
 				for j:=2;j<=dif;j++{
 					b = b*10 + 9
				}
				p := 1
				for j:=1;j<=l[i];j++{
					p = p*10
				}
 				ans += min(int64(k),int64(b))*int64(p)
 				if k<=b{
 					break
				}else{
					k-=b
				}
			}else{
				p:=1
				for j:=1;j<=l[i];j++{
					p=p*10
				}
				ans += int64(k)*int64(p)
			}
		}
		fmt.Fprintln(out,ans)
	}
}

package main

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

var T int
var N int
var K int64
var A [11]int64
var B = [10]int64{1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9}
var in = bufio.NewReader(os.Stdin)
var out = bufio.NewWriter(os.Stdout)

func main() {
	defer out.Flush()

	fmt.Fscan(in, &T)
	for ; T > 0; T-- {
		fmt.Fscan(in, &N, &K)
		for i := 0; i < N; i++ {
			fmt.Fscan(in, &A[i])
		}
		var ans, used int64
		for i := 0; i < N-1; i++ {
			v := min(K-used+1, (B[A[i+1]]-B[A[i]])/B[A[i]])
			used += v
			ans += v * B[A[i]]
		}
		ans += (K - used + 1) * B[A[N-1]]
		fmt.Fprintln(out, ans)
	}
}

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

package main

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

func main() {
	defer _w.Flush()
	t := ReadInt()
	for i := int64(0); i < t; i++ {
		solve()
	}
}
func solve() {
	n, k := ReadInt(), ReadInt()
	a := make([]int64, n)
	for i := int64(0); i < n; i++ {
		b := ReadInt()
		a[i] = int64(1)
		for j := int64(0); j < b; j++ {
			a[i] *= int64(10)
		}
	}

	kk := k + int64(1)

	sum := int64(0)
	used := int64(0)
	for i := int64(0); i < n; i++ {
		max := int64(1) << int64(60)
		if i < n-int64(1) {
			max = a[i+int64(1)]/a[i] - int64(1)
		}
		rest := kk - used
		if rest <= max {
			sum += rest * a[i]
			println(sum)
			return
		}
		used += max
		sum += max * a[i]
	}
}

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

func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(_r, a...); err != nil {
		panic(err)
	}
}
func ReadString() (s string) { Scan(&s); return }
func ReadInt() (i int64)     { Scan(&i); return }
func ReadInts(n int64) (a []int64) {
	for i := int64(0); i < n; i++ {
		a = append(a, ReadInt())
	}
	return
}
func ReadInt64() (i int64) { Scan(&i); return }
func ReadInt64s(n int64) (s []int64) {
	for i := int64(0); i < n; i++ {
		s = append(s, ReadInt64())
	}
	return
}
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 prints(s []int64)                  { v := fmt.Sprint(s); println(v[int64(1) : int64(len(v))-int64(1)]) }

package main

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

// var m []int
// err = json.Unmarshal([]byte(r.FormValue("example")), &m)

// for i := 0; i < len(m); i++ {
// 	fmt.Println(m[i])
// }

// sort.Slice(arr, func(i, j int) bool {
// 	return arr[i] > arr[j]
// })

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

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

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

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

func LCM(x, y int) int {
	if x >= y {
		initial := x
		for i := 1; i < y+2; i++ {
			if initial%y == 0 {
				break
			} else {
				initial = initial + x
			}

		}
		return initial
	} else {
		initial := y
		for i := 1; i < x+2; i++ {
			if initial%x == 0 {
				break
			} else {
				initial = initial + y
			}

		}
		return initial
	}
}

func GCD(x, y int64) int64 {
	if x*y == 0 {
		return MAX(x, y)
	} else {
		var l, q int64
		l = MAX(x, y)
		q = MIN(x, y)
		var m int64
		for l*q > 0 {
			a := l % q
			b := l - a
			cc := int64(b / q)
			remain := l - cc*q
			l = MAX(remain, q)
			q = MIN(remain, q)
			if l*q == 0 {
				m = l + q
				break
			}

		}
		return m
	}
}

func IsItPrime(x int) bool {
	if x < 10 {
		if x == 2 || x == 3 || x == 5 || x == 7 {
			return true
		} else {
			return false
		}
	} else {
		j := 0
		k := math.Sqrt(float64(x))
		for m := 3; m <= int(k); {
			if x%m == 0 {
				j = 1
				break
			}
			m = m + 2
		}
		if j == 1 {
			return false
		} else {
			return true
		}
	}
}

func PrimeFactorization(n int) (pfs map[int]int) {
	pfs = make(map[int]int)

	// Get the number of 2s that divide n
	for n%2 == 0 {
		if _, ok := pfs[2]; ok {
			pfs[2] += 1
		} else {
			pfs[2] = 1
		}
		n = n / 2
	}

	// n must be odd at this point. so we can skip one element
	// (note i = i + 2)
	for i := 3; i*i <= n; i = i + 2 {
		// while i divides n, append i and divide n
		for n%i == 0 {
			if _, ok := pfs[i]; ok {
				pfs[i] += 1
			} else {
				pfs[i] = 1
			}
			n = n / i
		}
	}

	// This condition is to handle the case when n is a prime number
	// greater than 2
	if n > 2 {
		pfs[n] = 1
	}

	return
}

func NumberOfDivisors(n int) int {
	pfs := PrimeFactorization(n)

	num := 1
	for _, exponents := range pfs {
		num *= (exponents + 1)
	}

	return num
}

func KthPrime(x int) (y int) {
	if x == 1 {
		y = 2
	}
	if x == 2 {
		y = 3
	}
	if x > 2 {
		var sum int = 2
		begin := 5
		for sum < x+1 {
			if IsItPrime(begin) == true {
				sum++
			}
			if sum == x {
				y = begin
				break
			} else {
				if begin%6 == 1 {
					begin = begin + 4
				} else {
					begin = begin + 2
				}
			}
		}
	}
	return
}

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

func BITAND(x, y int64) int64 {
	var ans int64
	begin := x
	sec := y
	var count int64 = 1
	for 1 == 1 {
		if (begin%2)*(sec%2) == 1 {
			ans = ans + count
			count = count * 2
			begin = int64(begin / 2)
			sec = int64(sec / 2)
			if begin*sec == 0 {
				break
			}

		} else {
			count = count * 2
			begin = int64(begin / 2)
			sec = int64(sec / 2)
			if begin*sec == 0 {
				break
			}
		}
	}
	return ans
}

func Sum(n, m int) int {
	var ans int

	if n == 1 {
		return 0
	} else {
		for i := 2; i < n; i++ {
			ans = (ans + Sum(i, m)) % m
		}
		for j := 2; j < n+1; j++ {
			ans = (ans + Sum(n/j, m)) % m
		}
		return ans
	}
}

func ChangeStringToDate(x string) (t time.Time, err error) {
	t, err = time.Parse("2006-01-02", x)
	return
}

func DiffrenceBetweenTwoDates(first, second time.Time) int64 {
	date := first
	date2 := second
	k := date.Unix() - date2.Unix()
	return k
}

func Union(a, b []int) []int {
	m := make(map[int]bool)

	for _, item := range a {
		m[item] = true
	}

	for _, item := range b {
		if _, ok := m[item]; !ok {
			a = append(a, item)
		}
	}
	return a
}

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

var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &t)

	for o := 0; o < t; o++ {
		var n int
		var k int64
		fmt.Fscan(input, &n, &k)
		B := make([]int64, 0)
		B = append(B, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000)
		C := make([]int64, 0)
		ARR := make([]int, 10)
		for i := 1; i <= n; i++ {
			var m int
			fmt.Fscan(input, &m)
			ARR[m]++
			if ARR[m] == 1 {
				C = append(C, B[m])
			}

		}

		if len(C) == 1 {
			fmt.Println(k + 1)
		} else {
			var ans int64
			Need := k + 1
			q := len(C)
			for i := 0; i < q-1; i++ {
				CurrentMax := MIN((C[i+1]/C[i])-1, Need)
				ans = ans + CurrentMax*C[i]
				Need = Need - CurrentMax
				if Need <= 0 {
					break
				}
			}

			if Need > 0 {
				ans = ans + Need*C[q-1]
			}

			fmt.Println(ans)
		}

	}

}

package main

import (
	"fmt"
	"math"
)

const (
	MaxUint = ^uint(0)
	MinUint = 0
	MaxInt = int(MaxUint >> 1)
	MinInt = -MaxInt - 1
)

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
}

// end of template

func solve(){
	var n, k int

	fmt.Scan(&n,&k)
	number := make([]int,n)
	pow := make([]int ,n)

	for i:=0 ; i<n ; i++ {
		fmt.Scan(&number[i])
		pow[i] = int(math.Pow(10,float64(number[i])))
	}

	now := k + 1
	idx := 0

	for idx < n {
		if idx != 0 {
			if now < pow[idx] {
				now += (pow[idx-1] - 1)
				break
			}
			now = (now - (pow[idx] - pow[idx-1])) / pow[idx-1] * pow[idx]
		}
		idx++
	}
	if idx == n {
		now += (pow[idx-1] - 1)
	}

	fmt.Println(now)
	return
}

func main(){
	var tc int

	fmt.Scan(&tc)
	for t:=0 ; t<tc ; t++ {
		solve()
	}
}

package main

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

func solveC(my []int64, k int64) int64 {
	if my[0] != 0 {
		return 1
	}

	var result int64 = 0
	var i int
	for i = 1; i < len(my); i++ {
		bill := int64(math.Pow10(int(my[i-1])))
		needNum := int64(math.Pow10(int(my[i]-my[i-1]))) - 1
		if k >= needNum {
			result += bill * needNum
			k -= needNum
		} else {
			break
		}
	}

	i--
	if k > 0 {
		bill := int64(math.Pow10(int(my[i])))
		needNum := k + 1
		result += bill * needNum
	}

	return result
}

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

	var n int
	var t, k int64
	fmt.Fscan(input, &t)

	for t > 0 {
		t--
		fmt.Fscan(input, &n, &k)
		my := make([]int64, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(input, &my[i])
		}

		result := solveC(my, k)
		fmt.Println(result)
	}
}

package main

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

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

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

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

		tot := k
		var d int
		for i := 1; i < n; i++ {
			if tot < int64(math.Pow10(aa[i])) {
				break
			}

			b := int64(math.Pow10(aa[i]-aa[i-1]) - 1)
			tot = tot - k*int64(math.Pow10(aa[i-1])) + b*int64(math.Pow10(aa[i-1]))
			k -= b
			tot += k * int64(math.Pow10(aa[i]))
			d = aa[i]
		}
		fmt.Fprintln(out, tot+int64(math.Pow10(d)))

	}
}

package main

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

func pow10(pw int) int {
	res := 1
	for i := 0; i < pw; i++ {
		res *= 10
	}
	return res
}

func solve(in *bufio.Reader) int {
	var n, k int
	fmt.Fscan(in, &n)
	fmt.Fscan(in, &k)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &a[i])
	}
	k++
	var ans int
	for i := 0; i < n && k > 0; i++ {
		canUse := k
		if i < n-1 {
			canUse = pow10(a[i+1]-a[i]) - 1
		}
		if canUse > k {
			canUse = k
		}
		ans += pow10(a[i]) * canUse
		k -= canUse
	}
	return ans
}

func main() {
	var T int
	in := bufio.NewReader(os.Stdin)
	fmt.Fscan(in, &T)
	for i := 0; i < T; i++ {
		fmt.Println(solve(in))
	}
}

package main

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

var n int
var k int64

var a []int

func main() {

	r := bufio.NewReader(os.Stdin)

	var t int
	fmt.Fscan(r, &t)

	for i := 0; i < t; i++ {
		fmt.Fscan(r, &n, &k)

		a = make([]int, n)

		for j := 0; j < n; j++ {
			fmt.Fscan(r, &a[j])
		}

		ans := solve()
		fmt.Println(ans)
	}
}

var b[]int64

func solve() int64 {

	b = make([]int64, n)

	for j := 0; j < n; j++ {
		b[j] = pow(a[j])
	}

	for i := 1; i <= 18; i++ {
		num := pow(i)
		num--

		temp := num

		var tot int64

		for j := n - 1; j >= 0; j-- {
			if b[j] > num {
				continue
			}

			d := num/b[j]

			tot +=d

			temp = num % b[j]

			if temp == 0 {
				break
			}
		}
		if tot > k {

			var p int64

			if i > a[n - 1] {
				 p = b[n - 1]
			}

			for j := n - 1; j >= 0; j-- {
				if a[j] < i {
					p = b[j]
					break
				}
			}

			diff := k - tot

			return num - p * diff

		}
	}

	return -1
}

func pow(n int) int64 {
	var m int64 = 1
	for k := 0; k < n; k++ {
		m *= 10
	}
	return m
}


Berland Government decided to improve relations with neighboring countries. First of all, it was decided to build new roads so that from each city of Berland and neighboring countries it became possible to reach all the others. There are n cities in Berland and neighboring countries in total and exactly n - 1 two-way roads. Because of the recent financial crisis, the Berland Government is strongly pressed for money, so to build a new road it has to close some of the existing ones. Every day it is possible to close one existing road and immediately build a new one. Your task is to determine how many days would be needed to rebuild roads so that from each city it became possible to reach all the others, and to draw a plan of closure of old roads and building of new ones.

The first line contains integer n (2 ≤ n ≤ 1000) — amount of cities in Berland and neighboring countries. Next n - 1 lines contain the description of roads. Each road is described by two space-separated integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — pair of cities, which the road connects. It can't be more than one road between a pair of cities. No road connects the city with itself.

Output the answer, number t — what is the least amount of days needed to rebuild roads so that from each city it became possible to reach all the others. Then output t lines — the plan of closure of old roads and building of new ones. Each line should describe one day in the format i j u v — it means that road between cities i and j became closed and a new road between cities u and v is built. Cities are numbered from 1. If the answer is not unique, output any.

//http://codeforces.com/problemset/problem/25/D
//D. Roads not only in Berland

package main

import (
	"fmt"
)

type Edg struct {
	a, b         int32
	nexta, nextb *Edg
	used         bool
}

func (o *Edg) Read() {
	fmt.Scan(&o.a)
	fmt.Scan(&o.b)
}

var (
	edg   []Edg
	beg   []*Edg
	comp  []int32
	ncomp int32
)

func Trav(akt int32) {
	var (
		adj      int32
		it, next *Edg
	)
	comp[akt] = ncomp
	it = beg[akt]
	for it != nil {
		//println(akt, it.a, it.b)
		if it.a == akt {
			adj = it.b
			next = it.nexta
		} else {
			adj = it.a
			next = it.nextb
		}

		if comp[adj] == 0 {
			it.used = true
			Trav(adj)
		}
		it = next
	}
}

func main() {
	var (
		i, j, nvtx int32
		ucomp      []bool
	)

	fmt.Scan(&nvtx)
	edg = make([]Edg, nvtx+1, nvtx+1)
	beg = make([]*Edg, nvtx+1, nvtx+1)
	comp = make([]int32, nvtx+1, nvtx+1)

	for i = 0; i < nvtx-1; i = i + 1 {
		ei := &edg[i]
		ei.Read()
		ei.nexta, ei.nextb = beg[ei.a], beg[ei.b]
		beg[ei.a], beg[ei.b] = ei, ei
	}

	for i = 1; i <= nvtx; i++ {
		if 0 == comp[i] {
			ncomp++
			Trav(i)
		}
	}

	//for i = 0; i < nvtx-1; i = i + 1 {
	//	println(edg[i].a, edg[i].b, edg[i].used)
	//}

	//for i = 1; i <= nvtx; i = i + 1 {
	//	println(comp[i])
	//}

	fmt.Println(ncomp - 1)
	// mindent az "egyes" komponenssel kotok ossze

	if ncomp > 1 {
		ucomp = make([]bool, nvtx+1, nvtx+1)

		//comp[i]=1 mindig
		ucomp[1] = true
		for i, j = 2, 0; i <= nvtx; i++ {
			if ucomp[comp[i]] == false {
				ucomp[comp[i]] = true
				for ; edg[j].used == true; j++ {
				}
				//				fmt.Println(1, i, edg[j].a, edg[j].b)
				fmt.Println(edg[j].a, edg[j].b, 1, i)
				j++
			}
		}
	}
}

package main

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

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

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

	dsu := make([]int, n+1)
	for i := 1; i <= n; i++ {
		dsu[i] = i
	}

	var from, to []int
	for i := 0; i < n-1; i++ {
		var u, v int
		fmt.Fscanf(r, "%d %d\n", &u, &v)
		if find(dsu, u) == find(dsu, v) {
			from = append(from, u)
			to = append(to, v)
		} else {
			union(dsu, u, v)
		}
	}

	w := bufio.NewWriter(os.Stdout)
	defer w.Flush()

	fmt.Fprintf(w, "%d\n", len(from))

	for i := 1; i <= n; i++ {
		if find(dsu, 1) != find(dsu, i) {
			fmt.Fprintf(w, "%d %d %d %d\n", from[0], to[0], 1, i)
			union(dsu, 1, i)
			from, to = from[1:], to[1:]
		}
	}
}

func union(dsu []int, u, v int) {
	u = find(dsu, u)
	v = find(dsu, v)

	if u == v {
		return
	}

	dsu[v] = u
}

func find(dsu []int, u int) int {
	if dsu[u] != u {
		dsu[u] = find(dsu, dsu[u])
	}
	return dsu[u]
}

package main

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

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

	var n, v, w int
	Fscan(in, &n)
	g := make([][]int, n)
	for i := 1; i < n; i++ {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}

	type pair struct{ v, w int }
	todo := []pair{}
	vis := make([]bool, n)
	var f func(v, fa int)
	f = func(v, fa int) {
		vis[v] = true
		for _, w := range g[v] {
			if !vis[w] {
				f(w, v)
			} else if w != fa && v < w {
				todo = append(todo, pair{v, w})
			}
		}
	}
	vs := []int{}
	for i, b := range vis {
		if !b {
			vs = append(vs, i)
			f(i, -1)
		}
	}
	Fprintln(out, len(todo))
	for i, p := range todo {
		Fprintln(out, p.v+1, p.w+1, vs[i]+1, vs[i+1]+1)
	}
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	var n, v, w int
	Fscan(in, &n)
	g := make([][]int, n+1)
	for i := 1; i < n; i++ {
		Fscan(in, &v, &w)
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}

	type edge struct{ v, w int }
	deletes := []edge{}
	vis := make([]bool, n+1)
	var f func(v, fa int)
	f = func(v, fa int) {
		vis[v] = true
		for _, w := range g[v] {
			if !vis[w] {
				f(w, v)
			} else if w != fa && v < w {
				deletes = append(deletes, edge{v, w})
			}
		}
	}
	vs := []int{}
	for i := 1; i <= n; i++ {
		if !vis[i] {
			vs = append(vs, i)
			f(i, 0)
		}
	}

	Fprintln(out, len(deletes))
	for i, p := range deletes {
		Fprintln(out, p.v, p.w, vs[i], vs[i+1])
	}
}

package main

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

func Init() {
}

func Solve(io *FastIO) {
	N := io.NextInt()

	djs := NewDisjointSet(N + 1)
	bad := make([]*Road, 0)

	for i := 1; i < N; i++ {
	  A := io.NextInt()
	  B := io.NextInt()

	  if !djs.union(A, B) {
	    bad = append(bad, &Road{
	      U: A,
	      V: B,
	    })
	  }
	}

	canonicals := make([]int, 0)

	for i := 1; i <= N; i++ {
	  if i == djs.find(i) {
	    canonicals = append(canonicals, i)
	  }
	}

	io.Println(len(bad))
	for i := 1; i < len(canonicals); i++ {
	  r := bad[i - 1]
	  io.Println(r.U, r.V, canonicals[0], canonicals[i])
	}
}

type Road struct {
  U int
  V int
}

type DisjointSet struct {
	parent []int
	rank []int
}

func NewDisjointSet(n int) *DisjointSet {
	dj := DisjointSet{
		parent: make([]int, n),
		rank: make([]int, n),
	}
	for i := 0; i < n; i++ {
		dj.parent[i] = i
	}
	return &dj
}

func (dj *DisjointSet) find(x int) int {
	if dj.parent[x] != x {
		dj.parent[x] = dj.find(dj.parent[x])
	}
	return dj.parent[x]
}

func (dj *DisjointSet) union(x, y int) bool {
	xr := dj.find(x)
	yr := dj.find(y)

	if xr == yr {
		return false
	}

	if dj.rank[xr] < dj.rank[yr] {
		dj.parent[xr] = yr
	} else if dj.rank[xr] > dj.rank[yr] {
		dj.parent[yr] = xr
	} else {
		dj.parent[xr] = yr
		dj.rank[yr]++
	}
	return true
}

type FastIO struct {
	reader *bufio.Reader
	writer *bufio.Writer
}

func (io *FastIO) NextChar() byte {
	c, _ := io.reader.ReadByte()
	return c
}

func (io *FastIO) NextInt() int {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := 1
	if c == '-' {
		sgn = -1
		c = io.NextChar()
	}
	res := 0
	for !IsSpaceChar(c) {
		res = (res * 10) + int(c - '0')
		c = io.NextChar()
	}
	return sgn * res
}

func (io *FastIO) NextLong() int64 {
	c := io.NextChar()
	for IsSpaceChar(c) {
		c = io.NextChar()
	}
	sgn := int64(1)
	if c == '-' {
		sgn = -1
		c = io.NextChar()
	}
	res := int64(0)
	for !IsSpaceChar(c) {
		res = (res * 10) + int64(c - '0')
		c = io.NextChar()
	}
	return sgn * res
}

func (io *FastIO) NextIntArray(size int) []int {
	return io.NextIntArrayOffset(size, 0)
}

func (io *FastIO) NextIntArrayOffset(size, offset int) []int {
	arr := make([]int, size + offset)
	for i := 0; i < size; i++ {
		arr[i + offset] = io.NextInt()
	}
	return arr
}

func (io *FastIO) NextLongArray(size int) []int64 {
	return io.NextLongArrayOffset(size, 0)
}

func (io *FastIO) NextLongArrayOffset(size, offset int) []int64 {
	arr := make([]int64, size + offset)
	for i := 0; i < size; i++ {
		arr[i + offset] = io.NextLong()
	}
	return arr
}

func (io *FastIO) NextString() string {
	c := io.NextChar()
	for (IsSpaceChar(c)) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsSpaceChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}

func (io *FastIO) NextLine() string {
	c := io.NextChar()
	for (IsSpaceChar(c)) {
		c = io.NextChar()
	}
	var sb bytes.Buffer
	for !IsLineBreakChar(c) {
		sb.WriteByte(c)
		c = io.NextChar()
	}
	return sb.String()
}

func (io *FastIO) Println(args ...interface{}) {
	io.writer.WriteString(fmt.Sprintln(args...))
}

func (io *FastIO) Printf(format string, args ...interface{}) {
	io.writer.WriteString(fmt.Sprintf(format, args...))
}

func (io *FastIO) FlushOutput() {
	io.writer.Flush()
}

func IsSpaceChar(c byte) bool {
	switch c {
	case 0, '\t', '\n', '\r', ' ':
		return true
	default:
		return false
	}
}

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

func main() {
	io := FastIO{reader: bufio.NewReader(os.Stdin), writer: bufio.NewWriter(os.Stdout)}
	Init()
	Solve(&io)
	io.FlushOutput()
}

package main

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

func dsuGet(p []int, v int) int {
	if v == p[v] {
		return v
	}
	p[v] = dsuGet(p, p[v])
	return p[v]
}

func dsuUnite(p []int, a, b int) {
	a = dsuGet(p, a)
	b = dsuGet(p, b)
	if rand.Int() & 1 == 1 {
		a, b = b, a
	}
	if a != b {
		p[a] = b
	}
}

type R struct {
	i, j int
}

func main() {

	//unionday
	//stdin, err := os.Open("file.in")
	//if err != nil {
	//	panic(err)
	//}
	//defer stdin.Close()
	stdin := os.Stdin
	reader := bufio.NewReaderSize(stdin, 512*1024)

	/*stdout, err := os.Create("file.out")
	if err != nil {
		panic(err)
	}*/
	//defer stdout.Close()
	stdout := os.Stdout
	writer := bufio.NewWriterSize(stdout, 512*1024)

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

	res := make([]R, 0)
	p := make([]int, n)
	for i := 0; i < n; i++ {
		p[i] = i
	}

	for i := 0; i < n - 1; i++ {
		var l, r int
		fmt.Fscanf(reader, "%d %d\n", &l, &r)
		l--
		r--
		if dsuGet(p, l) == dsuGet(p, r) {
			res = append(res, R{i: l, j: r})
		} else {
			dsuUnite(p, l, r)
		}
	}

	fmt.Fprintf(writer, "%d\n", len(res))

	if len(res) > 0 {
		c := 0
		for i := 1; i < n; i++ {
			if dsuGet(p, 0) != dsuGet(p, i) {
				dsuUnite(p, 0, i)
				fmt.Fprintf(writer, "%d %d %d %d\n", res[c].i + 1, res[c].j + 1, 1, i + 1)
				c++
			}
		}
	}

	writer.Flush()
}

package main

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

func dsuGet(p []int, v int) int {
	if v == p[v] {
		return v
	}
	p[v] = dsuGet(p, p[v])
	return p[v]
}

func dsuUnite(p []int, a, b int) {
	a = dsuGet(p, a)
	b = dsuGet(p, b)
	if rand.Int() & 1 == 1 {
		a, b = b, a
	}
	if a != b {
		p[a] = b
	}
}

func main() {

	//stdin, err := os.Open("file.in")
	//if err != nil {
	//	panic(err)
	//}
	//defer stdin.Close()
	stdin := os.Stdin
	reader := bufio.NewReaderSize(stdin, 1024*1024)

	//stdout, err := os.Create("file.out")
	//if err != nil {
	//	panic(err)
	//}
	//defer stdout.Close()
	stdout := os.Stdout
	writer := bufio.NewWriterSize(stdout, 1024*1024)

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

	p := make([]int, n)

	xx := make([]int, 0)
	yy := make([]int, 0)
	for i := 0; i < n; i++ {
		p[i] = i
	}
	for i := 1; i < n ; i++ {
		var a, b int
		fmt.Fscanf(reader, "%d %d\n", &a, &b)
		a--
		b--
		if dsuGet(p, a) != dsuGet(p, b) {
			dsuUnite(p, a, b)
		} else {
			xx = append(xx, a)
			yy = append(yy, b)
		}
	}

	fmt.Fprintf(writer, "%d\n", len(xx))

	if len(xx) != 0 {
		for i := 1; i < n; i++ {
			if dsuGet(p, 0) != dsuGet(p, i) {
				dsuUnite(p, 0, i)
				fmt.Fprintf(writer, "%d %d %d %d\n", xx[0] + 1, yy[0] + 1, 1, i + 1)
				xx = xx[1:]
				yy = yy[1:]
			}
		}
	}

	writer.Flush()
}

//http://codeforces.com/problemset/problem/25/D
//D. Roads not only in Berland

package main

import (
	"fmt"
)

type Edg struct {
	a, b         int32
	nexta, nextb *Edg
	used         bool
}

func (o *Edg) Read() {
	fmt.Scan(&o.a)
	fmt.Scan(&o.b)
}

var (
	edg   []Edg
	beg   []*Edg
	comp  []int32
	ncomp int32
)

func Trav(akt int32) {
	var (
		adj      int32
		it, next *Edg
	)
	comp[akt] = ncomp
	it = beg[akt]
	for it != nil {
		//println(akt, it.a, it.b)
		if it.a == akt {
			adj = it.b
			next = it.nexta
		} else {
			adj = it.a
			next = it.nextb
		}

		if comp[adj] == 0 {
			it.used = true
			Trav(adj)
		}
		it = next
	}
}

func main() {
	var (
		i, j, nvtx int32
		ucomp      []bool
	)

	fmt.Scan(&nvtx)
	edg = make([]Edg, nvtx+1, nvtx+1)
	beg = make([]*Edg, nvtx+1, nvtx+1)
	comp = make([]int32, nvtx+1, nvtx+1)

	for i = 0; i < nvtx-1; i = i + 1 {
		ei := &edg[i]
		ei.Read()
		ei.nexta, ei.nextb = beg[ei.a], beg[ei.b]
		beg[ei.a], beg[ei.b] = ei, ei
	}

	for i = 1; i <= nvtx; i++ {
		if 0 == comp[i] {
			ncomp++
			Trav(i)
		}
	}

	//for i = 0; i < nvtx-1; i = i + 1 {
	//	println(edg[i].a, edg[i].b, edg[i].used)
	//}

	//for i = 1; i <= nvtx; i = i + 1 {
	//	println(comp[i])
	//}

	fmt.Println(ncomp - 1)
	// mindent az "egyes" komponenssel kotok ossze

	if ncomp > 1 {
		ucomp = make([]bool, nvtx+1, nvtx+1)

		//comp[i]=1 mindig
		ucomp[1] = true
		for i, j = 2, 0; i <= nvtx; i++ {
			if ucomp[comp[i]] == false {
				ucomp[comp[i]] = true
				for ; edg[j].used == true; j++ {
				}
				//				fmt.Println(1, i, edg[j].a, edg[j].b)
				fmt.Println(edg[j].a, edg[j].b, 1, i)

			}
		}
	}
}

//http://codeforces.com/problemset/problem/25/D
//D. Roads not only in Berland

package main

import (
	"fmt"
)

type Edg struct {
	a, b         int32
	nexta, nextb *Edg
	used         bool
}

func (o *Edg) Read() {
	fmt.Scan(&o.a)
	fmt.Scan(&o.b)
}

var (
	edg   []Edg
	beg   []*Edg
	comp  []int32
	ncomp int32
)

func Trav(akt int32) {
	comp[akt] = ncomp
	it := beg[akt]
	for it != nil {
		//		println(akt, it.a, it.b)
		adj := it.a
		next := it.nexta
		if adj == akt {
			adj = it.b
			next = it.nextb
		}
		if comp[adj] == 0 {
			it.used = true
			Trav(adj)
		}
		it = next
	}
}

func main() {
	var (
		i, j, nvtx int32
		ucomp      []bool
	)

	fmt.Scan(&nvtx)
	edg = make([]Edg, nvtx+1, nvtx+1)
	beg = make([]*Edg, nvtx+1, nvtx+1)
	comp = make([]int32, nvtx+1, nvtx+1)

	for i = 0; i < nvtx-1; i = i + 1 {
		ei := &edg[i]
		ei.Read()
		ei.nexta, ei.nextb = beg[ei.a], beg[ei.b]
		beg[ei.a], beg[ei.b] = ei, ei
	}

	for i = 1; i <= nvtx; i++ {
		if 0 == comp[i] {
			ncomp++
			Trav(i)
		}
	}

	//for i = 0; i < nvtx-1; i = i + 1 {
	//	println(edg[i].a, edg[i].b, edg[i].used)
	//}

	//for i = 1; i <= nvtx; i = i + 1 {
	//	println(comp[i])
	//}

	fmt.Println(ncomp - 1)
	// mindent az "egyes" komponenssel kotok ossze

	if ncomp > 1 {
		ucomp = make([]bool, nvtx+1, nvtx+1)

		//comp[i]=1 mindig
		ucomp[1] = true
		for i, j = 2, 0; i <= nvtx; i++ {
			if ucomp[comp[i]] == false {
				ucomp[comp[i]] = true
				for ; edg[j].used == true; j++ {
				}
				//				fmt.Println(1, i, edg[j].a, edg[j].b)
				fmt.Println(edg[j].a, edg[j].b, 1, i)

			}
		}
	}
}

//http://codeforces.com/problemset/problem/25/D
//D. Roads not only in Berland

package main

import (
	"fmt"
)

type Edg struct {
	a, b         int32
	nexta, nextb *Edg
	used         bool
}

func (o *Edg) Read() {
	fmt.Scan(&o.a)
	fmt.Scan(&o.b)
}

var (
	edg   []Edg
	beg   []*Edg
	comp  []int32
	ncomp int32
)

func Trav(akt int32) {
	comp[akt] = ncomp
	it := beg[akt]
	for it != nil {
		//		println(akt, it.a, it.b)
		adj := it.a
		next := it.nexta
		if adj == akt {
			adj = it.b
			next = it.nextb
		}
		if comp[adj] == 0 {
			it.used = true
			Trav(adj)
		}
		it = next
	}
}

func main() {
	var (
		i, j, nvtx int32
		ucomp      []bool
	)

	fmt.Scan(&nvtx)
	edg = make([]Edg, nvtx+1, nvtx+1)
	beg = make([]*Edg, nvtx+1, nvtx+1)
	comp = make([]int32, nvtx+1, nvtx+1)

	for i = 0; i < nvtx-1; i = i + 1 {
		ei := &edg[i]
		ei.Read()
		ei.nexta, ei.nextb = beg[ei.a], beg[ei.b]
		beg[ei.a], beg[ei.b] = ei, ei
	}

	for i = 1; i <= nvtx; i++ {
		if 0 == comp[i] {
			ncomp++
			Trav(i)
		}
	}

	//for i = 0; i < nvtx-1; i = i + 1 {
	//	println(edg[i].a, edg[i].b, edg[i].used)
	//}

	//for i = 1; i <= nvtx; i = i + 1 {
	//	println(comp[i])
	//}

	fmt.Println(ncomp - 1)
	// mindent az "egyes" komponenssel kotok ossze

	if ncomp > 1 {
		ucomp = make([]bool, nvtx+1, nvtx+1)

		//comp[i]=1 mindig
		ucomp[1] = true
		for i, j = 2, 0; i <= nvtx; i++ {
			if ucomp[comp[i]] == false {
				ucomp[comp[i]] = true
				for ; edg[j].used == true; j++ {
				}
				fmt.Println(1, i, edg[j].a, edg[j].b)
			}
		}
	}
}

package main

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

func dsuGet(p []int, v int) int {
	if v == p[v] {
		return v
	}
	p[v] = dsuGet(p, p[v])
	return p[v]
}

func dsuUnite(p []int, a, b int) {
	a = dsuGet(p, a)
	b = dsuGet(p, b)
	if rand.Int() & 1 == 1 {
		a, b = b, a
	}
	p[a] = b
}

func main() {

	//stdin, err := os.Open("file.in")
	//if err != nil {
	//	panic(err)
	//}
	//defer stdin.Close()
	stdin := os.Stdin
	reader := bufio.NewReaderSize(stdin, 1024*1024)

	//stdout, err := os.Create("file.out")
	//if err != nil {
	//	panic(err)
	//}
	//defer stdout.Close()
	stdout := os.Stdout
	writer := bufio.NewWriterSize(stdout, 1024*1024)

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

	p := make([]int, n)

	xx := make([]int, 0)
	yy := make([]int, 0)
	for i := 1; i < n ; i++ {
		p[i] = i
		var a, b int
		fmt.Fscanf(reader, "%d %d\n", &a, &b)
		a--
		b--
		if dsuGet(p, a) != dsuGet(p, b) {
			dsuUnite(p, a, b)
		} else {
			xx = append(xx, a)
			yy = append(yy, b)
		}
	}

	fmt.Fprintf(writer, "%d\n", len(xx))

	if len(xx) != 0 {
		for i := 1; i < n; i++ {
			if dsuGet(p, 0) != dsuGet(p, i) {
				dsuUnite(p, 0, i)
				fmt.Fprintf(writer, "%d %d %d %d\n", xx[0] + 1, yy[0] + 1, 1, i + 1)
				xx = xx[1:]
				yy = yy[1:]
			}
		}
	}

	writer.Flush()
}


Katya studies in a fifth grade. Recently her class studied right triangles and the Pythagorean theorem. It appeared, that there are triples of positive integers such that you can construct a right triangle with segments of lengths corresponding to triple. Such triples are called Pythagorean triples.For example, triples (3, 4, 5), (5, 12, 13) and (6, 8, 10) are Pythagorean triples.Here Katya wondered if she can specify the length of some side of right triangle and find any Pythagorean triple corresponding to such length? Note that the side which length is specified can be a cathetus as well as hypotenuse.Katya had no problems with completing this task. Will you do the same?

The only line of the input contains single integer n (1 ≤ n ≤ 109) — the length of some side of a right triangle.

Print two integers m and k (1 ≤ m, k ≤ 1018), such that n, m and k form a Pythagorean triple, in the only line. In case if there is no any Pythagorean triple containing integer n, print  - 1 in the only line. If there are many answers, print any of them.

package main

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

func triangle(x int64, y int64, z int64) bool {
	return (x > 0) && (y > 0) && (z > 0) && (x+y > z) && (x+z > y) && (y+z > x)
}

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

func run(a int64) (int64, int64) {
	for m := int64(1); m*m < a; m++ {
		n := int64(math.Sqrt(float64(a - m*m)))
		if (n*n+m*m == a) && (m != n) {
			x := abs(m*m - n*n)
			y := 2 * m * n
			if triangle(x, y, a) {
				return x, y
			}
		}
	}

	for d := int64(1); d*d <= a; d++ {
		if a%d == 0 {
			e := a / d
			if (e != d) && ((e+d)%2 == 0) {
				m := (e + d) / 2
				n := abs(e-d) / 2
				x := m*m + n*n
				y := 2 * m * n
				if triangle(x, y, a) {
					return x, y
				}
			}
		}
	}

	if a%2 == 0 {
		b := a / 2
		for m := int64(1); m*m <= b; m++ {
			if b%m == 0 {
				n := b / m
				if m != n {
					x := abs(m*m - n*n)
					y := m*m + n*n
					return x, y
				}
			}
		}
	}

	return -1, -1
}

func main() {
	in := bufio.NewScanner(os.Stdin)
	out := bufio.NewWriter(os.Stdout)

	in.Split(bufio.ScanWords)
	defer out.Flush()

	in.Scan()
	n, _ := strconv.ParseInt(in.Text(), 10, 64)

	x, y := run(n)
	if x == -1 {
		out.WriteString("-1\n")
	} else {
		out.WriteString(strconv.FormatInt(x, 10))
		out.WriteByte(' ')
		out.WriteString(strconv.FormatInt(y, 10))
		out.WriteByte('\n')
	}
}

/*
URL:
https://codeforces.com/problemset/problem/707/C
*/

package main

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

/********** 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 (
	// General purpose
	MOD          = 1000000000 + 7
	ALPHABET_NUM = 26
	INF_INT64    = math.MaxInt64
	INF_BIT60    = 1 << 60
	INF_INT32    = math.MaxInt32
	INF_BIT30    = 1 << 30
	NIL          = -1

	// for dijkstra, prim, and so on
	WHITE = 0
	GRAY  = 1
	BLACK = 2
)

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

var (
	n int64
)

func main() {
	n = ReadInt64()

	if n == 1 || n == 2 {
		fmt.Println(-1)
		return
	}

	if n%2 == 0 {
		k := n*n/4 + 1
		m := k - 2
		fmt.Println(m, k)
	} else {
		k := (n*n + 1) / 2
		m := n*n - k
		fmt.Println(m, k)
	}
}

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

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

var (
	// ReadString returns a WORD string.
	ReadString 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()
	}
}

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

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

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


Your friend is developing a computer game. He has already decided how the game world should look like — it should consist of $$$n$$$ locations connected by $$$m$$$ two-way passages. The passages are designed in such a way that it should be possible to get from any location to any other location.Of course, some passages should be guarded by the monsters (if you just can go everywhere without any difficulties, then it's not fun, right?). Some crucial passages will be guarded by really fearsome monsters, requiring the hero to prepare for battle and designing his own tactics of defeating them (commonly these kinds of monsters are called bosses). And your friend wants you to help him place these bosses.The game will start in location $$$s$$$ and end in location $$$t$$$, but these locations are not chosen yet. After choosing these locations, your friend will place a boss in each passage such that it is impossible to get from $$$s$$$ to $$$t$$$ without using this passage. Your friend wants to place as much bosses as possible (because more challenges means more fun, right?), so he asks you to help him determine the maximum possible number of bosses, considering that any location can be chosen as $$$s$$$ or as $$$t$$$.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 3 \cdot 10^5$$$, $$$n - 1 \le m \le 3 \cdot 10^5$$$) — the number of locations and passages, respectively. Then $$$m$$$ lines follow, each containing two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$, $$$x \ne y$$$) describing the endpoints of one of the passages. It is guaranteed that there is no pair of locations directly connected by two or more passages, and that any location is reachable from any other location.

Print one integer — the maximum number of bosses your friend can place, considering all possible choices for $$$s$$$ and $$$t$$$.

package main

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

// github.com/EndlessCheng/codeforces-go
func main() {
	in := bufio.NewReader(os.Stdin)
	min := func(a, b int) int {
		if a < b {
			return a
		}
		return b
	}
	type neighbor struct{ to, eid int }

	var n, m, v, w, u, ans int
	Fscan(in, &n, &m)
	g := make([][]neighbor, n)
	for i := 0; i < m; i++ {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], neighbor{w, i})
		g[w] = append(g[w], neighbor{v, i})
	}

	is := make([]bool, m)
	dfn := make([]int, n)
	t := 0
	var f func(v, fa int) int
	f = func(v, fa int) int {
		t++
		dfn[v] = t
		lowV := t
		for _, e := range g[v] {
			w := e.to
			if dfn[w] == 0 {
				lowW := f(w, v)
				if lowW > dfn[v] {
					is[e.eid] = true
				}
				lowV = min(lowV, lowW)
			} else if w != fa && dfn[w] < dfn[v] {
				lowV = min(lowV, dfn[w])
			}
		}
		return lowV
	}
	for i, t := range dfn {
		if t == 0 {
			f(i, -1)
		}
	}

	vis := make([]bool, n)
	var h func(v, d int)
	h = func(v, d int) {
		vis[v] = true
		if d > ans {
			ans = d
			u = v
		}
		for _, e := range g[v] {
			if w := e.to; !vis[w] {
				if is[e.eid] {
					h(w, d+1)
				} else {
					h(w, d)
				}
			}
		}
	}
	ans = -1
	h(0, 0)
	vis = make([]bool, n)
	ans = -1
	h(u, 0)
	Print(ans)
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1000E(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	min := func(a, b int) int {
		if a < b {
			return a
		}
		return b
	}
	type neighbor struct{ to, eid int }
	type edge struct{ v, w int }

	var n, m, v, w, u, ans int
	Fscan(in, &n, &m)
	g := make([][]neighbor, n)
	edges := make([]edge, m)
	for i := 0; i < m; i++ {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], neighbor{w, i})
		g[w] = append(g[w], neighbor{v, i})
		edges[i] = edge{v, w}
	}

	isBridge := make([]bool, m)
	dfn := make([]int, n)
	dfsClock := 0
	var f func(v, fa int) int
	f = func(v, fa int) int {
		dfsClock++
		dfn[v] = dfsClock
		lowV := dfsClock
		for _, e := range g[v] {
			w := e.to
			if dfn[w] == 0 {
				lowW := f(w, v)
				if lowW > dfn[v] {
					isBridge[e.eid] = true
				}
				lowV = min(lowV, lowW)
			} else if w != fa && dfn[w] < dfn[v] {
				lowV = min(lowV, dfn[w])
			}
		}
		return lowV
	}
	for i, t := range dfn {
		if t == 0 {
			f(i, -1)
		}
	}
	ids := make([]int, n)
	idCnt := 0
	var f2 func(int)
	f2 = func(v int) {
		ids[v] = idCnt
		for _, e := range g[v] {
			if w := e.to; ids[w] == 0 && !isBridge[e.eid] {
				f2(w)
			}
		}
	}
	for i, id := range ids {
		if id == 0 {
			idCnt++
			f2(i)
		}
	}

	t := make([][]int, idCnt+1)
	for _, e := range edges {
		if v, w := ids[e.v], ids[e.w]; v != w {
			t[v] = append(t[v], w)
			t[w] = append(t[w], v)
		}
	}
	var f3 func(v, fa, d int)
	f3 = func(v, fa, d int) {
		if d > ans {
			ans = d
			u = v
		}
		for _, w := range t[v] {
			if w != fa {
				f3(w, v, d+1)
			}
		}
	}
	ans = -1
	f3(1, 0, 0)
	ans = -1
	f3(u, 0, 0)
	Fprint(out, ans)
}

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

package main

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

var n int
var nodes [][]int
var low, num, parent, crit []int

func readInput() {
	inp := bufio.NewReader(os.Stdin)

	// read n
	var m int
	fmt.Fscanf(inp, "%d %d\n", &n, &m)

	nodes, low, num, parent, crit = make([][]int, n+1), make([]int, n+1), make([]int, n+1), make([]int, n+1), make([]int, n+1)
	for i := range nodes {
		nodes[i] = make([]int, 0, 64)
	}

	var u, v int
	for m > 0 {
		m--
		fmt.Fscanf(inp, "%d %d\n", &u, &v)
		nodes[u] = append(nodes[u], v)
		nodes[v] = append(nodes[v], u)
	}
}

var time int

func visit(u int) {
	time++
	num[u], low[u] = time, n+2

	for _, v := range nodes[u] {
		if v != parent[u] { // no reverse back
			if num[v] == 0 {
				parent[v] = u
				visit(v)

				if low[v] < low[u] {
					low[u] = low[v]
				}

				if low[v] >= num[v] { // critical edge u --> v
					crit[v] = u
				}
			} else if num[v] < low[u] {
				low[u] = num[v]
			}
		}
	}
}

func longest(u int) (int, int) {
	var tmp1, tmp2, max, max1, max2 int

	for _, v := range nodes[u] {
		tmp1, tmp2 = longest(v)

		if crit[v] == u {
			tmp2++
		}

		if max < tmp1 {
			max = tmp1
		}

		if tmp2 > max2 {
			if max2 = tmp2; max2 > max1 {
				max1, max2 = max2, max1
			}
		}
	}

	if max < max2+max1 {
		max = max2 + max1
	}

	return max, max1
}

func solve() {
	parent[1] = -1
	visit(1)

	for i := 1; i <= n; i++ {
		nodes[i] = make([]int, 64)
	}

	var p int
	for u := 2; u <= n; u++ {
		p = parent[u]
		nodes[p] = append(nodes[p], u)
	}

	max1, max2 := longest(1)
	if max1 < max2 {
		fmt.Print(max2)
	} else {
		fmt.Print(max1)
	}
}

func main() {
	readInput()
	solve()
}


Major Ram is being chased by his arch enemy Raghav. Ram must reach the top of the building to escape via helicopter. The building, however, is on fire. Ram must choose the optimal path to reach the top of the building to lose the minimum amount of health.The building consists of $$$n$$$ floors, each with $$$m$$$ rooms each. Let $$$(i, j)$$$ represent the $$$j$$$-th room on the $$$i$$$-th floor. Additionally, there are $$$k$$$ ladders installed. The $$$i$$$-th ladder allows Ram to travel from $$$(a_i, b_i)$$$ to $$$(c_i, d_i)$$$, but not in the other direction. Ram also gains $$$h_i$$$ health points if he uses the ladder $$$i$$$. It is guaranteed $$$a_i < c_i$$$ for all ladders.If Ram is on the $$$i$$$-th floor, he can move either left or right. Travelling across floors, however, is treacherous. If Ram travels from $$$(i, j)$$$ to $$$(i, k)$$$, he loses $$$|j-k| \cdot x_i$$$ health points.Ram enters the building at $$$(1, 1)$$$ while his helicopter is waiting at $$$(n, m)$$$. What is the minimum amount of health Ram loses if he takes the most optimal path? Note this answer may be negative (in which case he gains health). Output "NO ESCAPE" if no matter what path Ram takes, he cannot escape the clutches of Raghav.

The first line of input contains $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^4$$$) — the number of test cases. The first line of each test case consists of $$$3$$$ integers $$$n, m, k$$$ ($$$2 \leq n, m \leq 10^5$$$; $$$1 \leq k \leq 10^5$$$) — the number of floors, the number of rooms on each floor and the number of ladders respectively. The second line of a test case consists of $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \leq x_i \leq 10^6$$$). The next $$$k$$$ lines describe the ladders. Ladder $$$i$$$ is denoted by $$$a_i, b_i, c_i, d_i, h_i$$$ ($$$1 \leq a_i < c_i \leq n$$$; $$$1 \leq b_i, d_i \leq m$$$; $$$1 \leq h_i \leq 10^6$$$)  — the rooms it connects and the health points gained from using it. It is guaranteed $$$a_i < c_i$$$ for all ladders and there is at most one ladder between any 2 rooms in the building. The sum of $$$n$$$, the sum of $$$m$$$, and the sum of $$$k$$$ over all test cases do not exceed $$$10^5$$$.

Output the minimum health Ram loses on the optimal path from $$$(1, 1)$$$ to $$$(n, m)$$$. If Ram cannot escape the clutches of Raghav regardless of the path he takes, output "NO ESCAPE" (all uppercase, without quotes).

NoteThe figure for the first test case is in the statement. There are only $$$2$$$ possible paths to $$$(n, m)$$$:   Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 2)$$$, takes the ladder to $$$(5, 1)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-2| - h_3 + x_5 \cdot |1-3| \\ &= 5 \cdot 2 - 4 + 8 \cdot 1 - 6 + 4 \cdot 2 \\ &= 16. \end{align*} $$$$$$  Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 1)$$$, takes the ladder to $$$(5, 2)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-1| - h_2 + a_5 \cdot |2-3| \\ &= 5 \cdot 2 - 4 + 8 \cdot 2 - 5 + 4 \cdot 1 \\ &= 21. \end{align*} $$$$$$  Therefore, the minimum health lost would be $$$16$$$.In the second test case, there is no path to $$$(n, m)$$$.In the third case case, Ram travels to $$$(1, 3)$$$ and takes the only ladder to $$$(5, 3)$$$. He loses $$$5 \cdot 2$$$ health points and gains $$$h_1 = 100$$$ health points. Therefore the total loss is $$$10-100=-90$$$ (negative implies he gains health after the path).

package main

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

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

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

type Ladder struct {
	fri             int
	frj             int
	toi             int
	toj             int
	health          int
	bestEntryHealth int64
}

type EntryPoint struct {
	j      int
	health int64
}

func NewEntryPoint(j int, health int64) *EntryPoint {
	return &EntryPoint{j: j, health: health}
}

var h, w int
var floorDamage []int             // Each step in floor i causes floorDamage[i] health loss
var laddersAt [][]*Ladder         // Ladders starting at each floor
var entryPointsAt [][]*EntryPoint // Entry points at each floor

func solveFloor(i int) {
	// fmt.Printf("solving floor %d\n", i)
	var ladders = laddersAt[i]
	var entryPoints = entryPointsAt[i]
	var dmg = int64(floorDamage[i])

	// this floor is doomed :(
	if len(entryPoints) == 0 || len(ladders) == 0 {
		return
	}

	sort.Slice(ladders, func(i, j int) bool {
		return ladders[i].frj < ladders[j].frj
	})
	sort.Slice(entryPoints, func(i, j int) bool {
		return entryPoints[i].j < entryPoints[j].j
	})

	for _, ladder := range ladders {
		ladder.bestEntryHealth = math.MinInt64
	}

	var entryIndex = 0
	var bestEntryIndex = 0
	for _, ladder := range ladders {
		for entryIndex+1 < len(entryPoints) && entryPoints[entryIndex+1].j <= ladder.frj {
			entryIndex++
			var e0 = entryPoints[bestEntryIndex]
			var e1 = entryPoints[entryIndex]
			var health0 = int64(e0.health) - int64(ladder.frj-e0.j)*dmg
			var health1 = int64(e1.health) - int64(ladder.frj-e1.j)*dmg
			if health1 > health0 {
				bestEntryIndex = entryIndex
			}
		}
		var e = entryPoints[bestEntryIndex]
		if e.j <= ladder.frj {
			var health = int64(e.health) - int64(ladder.frj-e.j)*dmg
			ladder.bestEntryHealth = max(ladder.bestEntryHealth, health)
		}
	}

	entryIndex = len(entryPoints) - 1
	bestEntryIndex = entryIndex
	for ladderIndex := len(ladders) - 1; ladderIndex >= 0; ladderIndex-- {
		var ladder = ladders[ladderIndex]
		for entryIndex-1 >= 0 && entryPoints[entryIndex-1].j >= ladder.frj {
			entryIndex--
			var e0 = entryPoints[bestEntryIndex]
			var e1 = entryPoints[entryIndex]
			var health0 = int64(e0.health) - int64(e0.j-ladder.frj)*dmg
			var health1 = int64(e1.health) - int64(e1.j-ladder.frj)*dmg
			if health1 > health0 {
				bestEntryIndex = entryIndex
			}
		}
		var e = entryPoints[bestEntryIndex]
		if e.j >= ladder.frj {
			var health = int64(e.health) - int64(e.j-ladder.frj)*dmg
			ladder.bestEntryHealth = max(ladder.bestEntryHealth, health)
		}
	}

	for _, ladder := range ladders {
		// fmt.Printf("ladder = %v\n", ladder)
		entryPointsAt[ladder.toi] = append(entryPointsAt[ladder.toi], NewEntryPoint(
			ladder.toj,
			ladder.bestEntryHealth+int64(ladder.health),
		))
	}
}

func solveCase() {
	var nLadders int
	fmt.Fscan(in, &h, &w, &nLadders)
	floorDamage = make([]int, h)
	laddersAt = make([][]*Ladder, h)
	entryPointsAt = make([][]*EntryPoint, h+1)
	for i := 0; i < h; i++ {
		fmt.Fscan(in, &floorDamage[i])
	}
	for i := 0; i < nLadders; i++ {
		var ladder Ladder = Ladder{}
		fmt.Fscan(in, &ladder.fri, &ladder.frj, &ladder.toi, &ladder.toj, &ladder.health)
		ladder.fri--
		ladder.frj--
		ladder.toi--
		ladder.toj--
		laddersAt[ladder.fri] = append(laddersAt[ladder.fri], &ladder)
	}

	// this final ladder represents getting to the helicopter, tucutucutucutucu
	laddersAt[h-1] = append(laddersAt[h-1], &Ladder{
		fri:    h - 1,
		frj:    w - 1,
		toi:    h,
		toj:    0,
		health: 0,
	})
	entryPointsAt[0] = append(entryPointsAt[0], NewEntryPoint(0, 0))
	for i := 0; i < h; i++ {
		solveFloor(i)
	}
	if len(entryPointsAt[h]) == 0 {
		fmt.Fprintf(out, "NO ESCAPE\n")
	} else {
		fmt.Fprintf(out, "%d\n", -entryPointsAt[h][0].health)
	}
}

func main() {
	var ntc int
	fmt.Fscan(in, &ntc)
	for t := 0; t < ntc; t++ {
		solveCase()
	}
	out.Flush()
}