It is the easy version of the problem. The only difference is that in this version $$$n = 1$$$.In the cinema seats can be represented as the table with $$$n$$$ rows and $$$m$$$ columns. The rows are numbered with integers from $$$1$$$ to $$$n$$$. The seats in each row are numbered with consecutive integers from left to right: in the $$$k$$$-th row from $$$m (k - 1) + 1$$$ to $$$m k$$$ for all rows $$$1 \le k \le n$$$. $$$1$$$$$$2$$$$$$\cdots$$$$$$m - 1$$$$$$m$$$$$$m + 1$$$$$$m + 2$$$$$$\cdots$$$$$$2 m - 1$$$$$$2 m$$$$$$2m + 1$$$$$$2m + 2$$$$$$\cdots$$$$$$3 m - 1$$$$$$3 m$$$$$$\vdots$$$$$$\vdots$$$$$$\ddots$$$$$$\vdots$$$$$$\vdots$$$$$$m (n - 1) + 1$$$$$$m (n - 1) + 2$$$$$$\cdots$$$$$$n m - 1$$$$$$n m$$$ The table with seats indices There are $$$nm$$$ people who want to go to the cinema to watch a new film. They are numbered with integers from $$$1$$$ to $$$nm$$$. You should give exactly one seat to each person.It is known, that in this cinema as lower seat index you have as better you can see everything happening on the screen. $$$i$$$-th person has the level of sight $$$a_i$$$. Let's define $$$s_i$$$ as the seat index, that will be given to $$$i$$$-th person. You want to give better places for people with lower sight levels, so for any two people $$$i$$$, $$$j$$$ such that $$$a_i < a_j$$$ it should be satisfied that $$$s_i < s_j$$$.After you will give seats to all people they will start coming to their seats. In the order from $$$1$$$ to $$$nm$$$, each person will enter the hall and sit in their seat. To get to their place, the person will go to their seat's row and start moving from the first seat in this row to theirs from left to right. While moving some places will be free, some will be occupied with people already seated. The inconvenience of the person is equal to the number of occupied seats he or she will go through.Let's consider an example: $$$m = 5$$$, the person has the seat $$$4$$$ in the first row, the seats $$$1$$$, $$$3$$$, $$$5$$$ in the first row are already occupied, the seats $$$2$$$ and $$$4$$$ are free. The inconvenience of this person will be $$$2$$$, because he will go through occupied seats $$$1$$$ and $$$3$$$.Find the minimal total inconvenience (the sum of inconveniences of all people), that is possible to have by giving places for all people (all conditions should be satisfied).

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$n = 1$$$, $$$1 \le m \le 300$$$) — the number of rows and places in each row respectively. The second line of each test case contains $$$n \cdot m$$$ integers $$$a_1, a_2, \ldots, a_{n \cdot m}$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the sight level of $$$i$$$-th person. It's guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print a single integer — the minimal total inconvenience that can be achieved.

NoteIn the first test case, there is a single way to arrange people, because all sight levels are distinct. The first person will sit on the first seat, the second person will sit on the second place, the third person will sit on the third place. So inconvenience of the first person will be $$$0$$$, inconvenience of the second person will be $$$1$$$ and inconvenience of the third person will be $$$2$$$. The total inconvenience is $$$0 + 1 + 2 = 3$$$.In the second test case, people should sit as follows: $$$s_1 = 2$$$, $$$s_2 = 1$$$, $$$s_3 = 5$$$, $$$s_4 = 4$$$, $$$s_5 = 3$$$. The total inconvenience will be $$$6$$$.

package main

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

type Scanner struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) *Scanner {
	scanner := bufio.NewScanner(reader)
	scanner.Split(bufio.ScanWords)
	return &Scanner{scanner}
}

func (s *Scanner) Word() string {
	s.Scan()
	return s.Text()
}

func (s *Scanner) Int() int {
	s.Scan()
	n, _ := strconv.Atoi(s.Text())
	return n
}

func (s *Scanner) Int64() int64 {
	s.Scan()
	n, _ := strconv.ParseInt(s.Text(), 10, 64)
	return n
}

func (s *Scanner) Words(count int) []string {
	words := make([]string, count)
	for i := range words {
		words[i] = s.Word()
	}
	return words
}

func (s *Scanner) Ints(count int) []int {
	ints := make([]int, count)
	for i := range ints {
		ints[i] = s.Int()
	}
	return ints
}

func (s *Scanner) Int64s(count int) []int64 {
	int64s := make([]int64, count)
	for i := range int64s {
		int64s[i] = s.Int64()
	}
	return int64s
}

func solve(a []int, rows, cols int) int64 {
	order := make([]int, len(a))
	for i := 0; i < len(a); i++ {
		order[i] = i
	}
	sort.Slice(order, func(i, j int) bool {
		if a[order[i]] == a[order[j]] {
			return order[i] > order[j]
		}
		return a[order[i]] < a[order[j]]
	})

	occupied := make([]bool, len(a))

	res := int64(0)
	for i := range a {
		var l int
		for ; order[l] != i; l++ {
			if occupied[l] {
				res++
			}
		}
		occupied[l] = true
	}
	return res
}

func main() {
	stdin := NewWordScanner(os.Stdin)
	tests := stdin.Int()

	for i := 0; i < tests; i++ {
		n, m := stdin.Int(), stdin.Int()
		a := stdin.Ints(n * m)
		fmt.Println(solve(a, n, m))
	}
}

package main

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

// 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 MKO(x, y int64) int64 {
	if x < y {
		return 0
	} else {
		return x - y + 1
	}
}

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

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, m int
		fmt.Fscan(input, &n, &m)

		ARRAY := make([]int, m)
		for i := 0; i < m; i++ {
			fmt.Fscan(input, &ARRAY[i])

		}
		var Ans int

		for i := 0; i < m; i++ {
			for j := 0; j < i; j++ {
				if ARRAY[i] > ARRAY[j] {
					Ans++
				}
			}
		}
		fmt.Println(Ans)

	}
}

package main

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

type IndexTree struct {
	n            int
	arr          []int
	f            func(i, j int) int
	defaultValue int
}

type Aggregation interface {
	DefaultValue() int
	Aggregate(left, right int) int
}

type MinIndex struct{}

func (m MinIndex) DefaultValue() int { return math.MaxInt32 }
func (m MinIndex) Aggregate(left, right int) int {
	if left < right {
		return left
	} else {
		return right
	}
}

type MaxIndex struct{}

func (m MaxIndex) DefaultValue() int { return math.MinInt32 }
func (m MaxIndex) Aggregate(left, right int) int {
	if left > right {
		return left
	} else {
		return right
	}
}

type SumIndex struct{}

func (m SumIndex) DefaultValue() int             { return 0 }
func (m SumIndex) Aggregate(left, right int) int { return left + right }

func NewIndexTree(n int, a Aggregation) *IndexTree {
	arr := make([]int, n*4)
	for i := 0; i < len(arr); i++ {
		arr[i] = a.DefaultValue()
	}

	return &IndexTree{n, arr, a.Aggregate, a.DefaultValue()}
}

func (i *IndexTree) Add(k, v int) {
	i.traverse(1, 0, i.n, func(node, b, e int) bool {
		if b <= k && e >= k {
			i.arr[node] = i.f(i.arr[node], v)
			return true
		}
		return false
	})
}

func (i *IndexTree) Get(qb, qe int) int {
	res := i.defaultValue
	i.traverse(1, 0, i.n, func(node, b, e int) bool {
		if b >= qb && e <= qe {
			res = i.f(res, i.arr[node])
			return false
		}
		return !(qe < b || qb > e)
	})
	return res
}

func (i *IndexTree) traverse(node int, b, e int, do func(node, b, e int) bool) {
	if !do(node, b, e) {
		return
	}
	m := (b + e) / 2
	if b != e {
		i.traverse(node*2, b, m, do)
		i.traverse(node*2+1, m+1, e, do)
	}
}

type pair struct {
	a, i int
}

func main() {
	r := bufio.NewReaderSize(os.Stdin, 1024*1024)

	var T int

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

	for t := 0; t < T; t++ {
		var n, m int
		fmt.Fscanf(r, "%d %d\n", &n, &m)
		arr := make([]pair, n*m)
		for i := 0; i < len(arr); i++ {
			arr[i].i = i
			fmt.Fscanf(r, "%d", &arr[i].a)
		}
		fmt.Fscanf(r, "\n")

		sort.Slice(arr, func(i, j int) bool {
			if arr[i].a != arr[j].a {
				return arr[i].a < arr[j].a
			}
			return arr[i].i > arr[j].i
		})

		idx := NewIndexTree(n*m, SumIndex{})

		res := 0
		for _, v := range arr {
			res += idx.Get(0, v.i)
			idx.Add(v.i, 1)
		}

		fmt.Println(res)
	}
}

package main

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

type Scanner struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) *Scanner {
	scanner := bufio.NewScanner(reader)
	scanner.Split(bufio.ScanWords)
	return &Scanner{scanner}
}

func (s *Scanner) Word() string {
	s.Scan()
	return s.Text()
}

func (s *Scanner) Int() int {
	s.Scan()
	n, _ := strconv.Atoi(s.Text())
	return n
}

func (s *Scanner) Int64() int64 {
	s.Scan()
	n, _ := strconv.ParseInt(s.Text(), 10, 64)
	return n
}

func (s *Scanner) Words(count int) []string {
	words := make([]string, count)
	for i := range words {
		words[i] = s.Word()
	}
	return words
}

func (s *Scanner) Ints(count int) []int {
	ints := make([]int, count)
	for i := range ints {
		ints[i] = s.Int()
	}
	return ints
}

func (s *Scanner) Int64s(count int) []int64 {
	int64s := make([]int64, count)
	for i := range int64s {
		int64s[i] = s.Int64()
	}
	return int64s
}

func solve(a []int, rows, cols int) int64 {
	order := make([]int, len(a))
	for i := 0; i < len(a); i++ {
		order[i] = i
	}
	sort.Slice(order, func(i, j int) bool {
		if a[order[i]] == a[order[j]] {
			return i > j
		}
		return a[order[i]] < a[order[j]]
	})

	occupied := make([]bool, len(a))

	res := int64(0)
	for i := range a{
		var l int
		for ;order[l] != i; l++ {
			if occupied[l] {
				res ++
			}
		}
		occupied[l] = true
	}
	return res
}

func main() {
	stdin := NewWordScanner(os.Stdin)
	tests := stdin.Int()

	for i := 0; i < tests; i++ {
		n, m := stdin.Int(), stdin.Int()
		a := stdin.Ints(n * m)
		fmt.Println(solve(a, n, m))
	}
}


Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants.The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has $$$n$$$ hotels, where the $$$i$$$-th hotel is located in the city with coordinate $$$x_i$$$. Sonya is a smart girl, so she does not open two or more hotels in the same city.Sonya understands that her business needs to be expanded by opening new hotels, so she decides to build one more. She wants to make the minimum distance from this hotel to all others to be equal to $$$d$$$. The girl understands that there are many possible locations to construct such a hotel. Thus she wants to know the number of possible coordinates of the cities where she can build a new hotel. Because Sonya is lounging in a jacuzzi in one of her hotels, she is asking you to find the number of cities where she can build a new hotel so that the minimum distance from the original $$$n$$$ hotels to the new one is equal to $$$d$$$.

The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1\leq n\leq 100$$$, $$$1\leq d\leq 10^9$$$) — the number of Sonya's hotels and the needed minimum distance from a new hotel to all others. The second line contains $$$n$$$ different integers in strictly increasing order $$$x_1, x_2, \ldots, x_n$$$ ($$$-10^9\leq x_i\leq 10^9$$$) — coordinates of Sonya's hotels.

Print the number of cities where Sonya can build a new hotel so that the minimum distance from this hotel to all others is equal to $$$d$$$.

NoteIn the first example, there are $$$6$$$ possible cities where Sonya can build a hotel. These cities have coordinates $$$-6$$$, $$$5$$$, $$$6$$$, $$$12$$$, $$$13$$$, and $$$19$$$.In the second example, there are $$$5$$$ possible cities where Sonya can build a hotel. These cities have coordinates $$$2$$$, $$$6$$$, $$$13$$$, $$$16$$$, and $$$21$$$.

package main

import "fmt"

const (
    M int = 105
)

var (
    n int
    d int
    a [M]int
)

func gao() int {
    rt := 0
    mp := make(map[int]int)
    fmt.Scan(&n, &d)
    if n == 1 {
        return 2
    }
    for i := 0; i < n; i++ {
        fmt.Scan(&a[i])
    }
    for i := 1; i < n - 1; i++ {
        if a[i]-d >= a[i-1]+d && mp[a[i]-d] == 0{
            rt += 1
            mp[a[i]-d] = 1
        }
        if a[i]+d <= a[i+1]-d && mp[a[i]+d] == 0{
            rt += 1
            mp[a[i]+d] = 1
        }
    }
    if a[0]+d <= a[1]-d && mp[a[0]+d] == 0 {
        rt += 1
        mp[a[0]+d] = 1
    }
    if a[n-1]-d >= a[n-2]+d && mp[a[n-1]-d] == 0 {
        rt += 1
        mp[a[n-1]-d] = 1
    }
    return rt + 2
}

func main() {
    ans := gao()
    fmt.Println(ans)
}

// You can edit this code!
// Click here and start typing.
package main

import (
	"fmt"
)

var a [105]int

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

	for i := 1; i <= n; i++ {
		fmt.Scan(&a[i])
	}

	ans := 2
	for i := 1; i <= n-1; i++ {
		if a[i]+d < a[i+1]-d {
			ans += 2
		}
		if a[i]+d == a[i+1]-d {
			ans++
		}
	}
	fmt.Println(ans)
}

package main

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

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

// IO helper functions

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// IO functions

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

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

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

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

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

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

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

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

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

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

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

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

// Simple math functions

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

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

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

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

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

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

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

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

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

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

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

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

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

func main() {
	defer Flush()

	n := readi()
	d := readi()
	x := make([]int, n)
	for i := range x {
		x[i] = readi()
	}
	var ans = 2
	for i := 0; i+1 < n; i++ {
		if x[i+1]-x[i] == 2*d {
			ans++
		} else if 2*d < x[i+1]-x[i] {
			ans += 2
		}
	}
	println(ans)
}

package main

import ("fmt")

func main(){
	var n, d, ans int64
	scan(&n, &d)
	var a []int64 = make([]int64, n)
	for i := int64(0); i < n; i++{
		scan(&a[i])
	}
	for i := int64(1); i < n; i++{
		if a[i] - a[i - 1] == d * 2{ans++}
		if a[i] - a[i - 1] > d * 2{ans += 2}
	}
	sout(ans + 2)
}

func scan(in ... interface{}){
	for _,k := range in{
		fmt.Scan(k)
	}
}

func sout(obj ... interface{}){
	for _, k := range obj{
		fmt.Print(k, " ")
	}
	fmt.Println()
}

package main

import (
	"fmt"
)

func main() {
	var n, d int
	fmt.Scanf("%d %d\n", &n, &d)
	tab := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &tab[i])
	}
	var results []int
	results = append(results, tab[0]-d)
	for i := 0; i < n-1; i++ {
		if tab[i]+d <= tab[i+1]-d {
			results = append(results, tab[i]+d)
		}
		if tab[i]+d < tab[i+1]-d {
			results = append(results, tab[i+1]-d)
		}
	}
	results = append(results, tab[n-1]+d)
	fmt.Printf("%d\n", len(results))

}

package main

import "fmt"

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

package main

import "fmt"

const (
    M int = 105
)

var (
    n int
    d int
    a [M]int
)

func gao() int {
    rt := 0
    mp := make(map[int]int)
    fmt.Scan(&n, &d)
    if n == 1 {
        return 2
    }
    for i := 0; i < n; i++ {
        fmt.Scan(&a[i])
    }
    for i := 1; i < n - 1; i++ {
        if a[i]-d >= a[i-1]+d && mp[a[i]-d] == 0{
            rt += 1
            mp[a[i]-d] = 1
        }
        if a[i]+d <= a[i+1]-d && mp[a[i]+d] == 0{
            rt += 1
            mp[a[i]+d] = 1
        }
    }
    if a[0]+d <= a[1]-d && mp[a[0]+d] == 0 {
        rt += 1
    }
    if a[n-1]-d >= a[n-2]+d && mp[a[n-1]-d] == 0 {
        rt += 1
    }
    return rt + 2
}

func main() {
    ans := gao()
    fmt.Println(ans)
}

package main

import (
	"fmt"
)

func main() {
	var n, d int
	fmt.Scanf("%d %d", &n, &d)
	tab := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &tab[i])
	}
	var results []int
	results = append(results, tab[0]-d)
	for i := 0; i < n-1; i++ {
		if tab[i]+d <= tab[i+1]-d {
			results = append(results, tab[i]+d)
		}
		if tab[i]+d < tab[i+1]-d {
			results = append(results, tab[i+1]-d)
		}
	}
	results = append(results, tab[n-1]+d)
	fmt.Printf("%d\n", len(results))

}


Little girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from $$$1$$$ to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains $$$3$$$ steps, and the second contains $$$4$$$ steps, she will pronounce the numbers $$$1, 2, 3, 1, 2, 3, 4$$$.You are given all the numbers pronounced by Tanya. How many stairways did she climb? Also, output the number of steps in each stairway.The given sequence will be a valid sequence that Tanya could have pronounced when climbing one or more stairways.

The first line contains $$$n$$$ ($$$1 \le n \le 1000$$$) — the total number of numbers pronounced by Tanya. The second line contains integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 1000$$$) — all the numbers Tanya pronounced while climbing the stairs, in order from the first to the last pronounced number. Passing a stairway with $$$x$$$ steps, she will pronounce the numbers $$$1, 2, \dots, x$$$ in that order. The given sequence will be a valid sequence that Tanya could have pronounced when climbing one or more stairways.

In the first line, output $$$t$$$ — the number of stairways that Tanya climbed. In the second line, output $$$t$$$ numbers — the number of steps in each stairway she climbed. Write the numbers in the correct order of passage of the stairways.

package main

import "fmt"

func main() {
	var n int
	var ans [1000]int
	fmt.Scanf("%d\n", &n)
	count := 0
	for i := 0; i < n; i++ {
		var x int
		fmt.Scanf("%d", &x)
		if x > ans[count] {
			ans[count]++
		} else {
			count++
			ans[count]++
		}
	}
	fmt.Println(count + 1)
	for i := 0; i <= count	; i++ {
		fmt.Print(ans[i], " ")
	}
	fmt.Println()
}

package main

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

func main() {
	var n, a int
	in := bufio.NewReader(os.Stdin)
	fmt.Fscan(in, &n)
	la := 0
	count := 0
	ans := make([]int, 0)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &a)
		if a <= la {
			count++
			ans = append(ans, la)
		}
		la = a
	}
	count++
	ans = append(ans, a)
	fmt.Println(count)
	for _, v := range ans {
		fmt.Printf("%d ", v)
	}
	fmt.Println()
}

// A. Tanya and Stairways
/*
Little girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from 1 to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains 3 steps, and the second contains 4 steps, she will pronounce the numbers 1,2,3,1,2,3,4.

You are given all the numbers pronounced by Tanya. How many stairways did she climb? Also, output the number of steps in each stairway.

The given sequence will be a valid sequence that Tanya could have pronounced when climbing one or more stairways.

Input
The first line contains 𝑛 (1≤𝑛≤1000) — the total number of numbers pronounced by Tanya.

The second line contains integers 𝑎1,𝑎2,…,𝑎𝑛 (1≤𝑎𝑖≤1000) — all the numbers Tanya pronounced while climbing the stairs, in order from the first to the last pronounced number. Passing a stairway with 𝑥 steps, she will pronounce the numbers 1,2,…,𝑥 in that order.

The given sequence will be a valid sequence that Tanya could have pronounced when climbing one or more stairways.

Output
In the first line, output 𝑡— the number of stairways that Tanya climbed. In the second line, output 𝑡 numbers — the number of steps in each stairway she climbed. Write the numbers in the correct order of passage of the stairways.

Examples
Input
7
1 2 3 1 2 3 4

Output
2
3 4

Input
4
1 1 1 1

Output
4
1 1 1 1

Input
5
1 2 3 4 5

Output
1
5

Input
5
1 2 1 2 1

Output
3
2 2 1
*/
package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	input1, _ := reader.ReadString('\n')
	n, _ := strconv.Atoi(strings.TrimSpace(input1))

	input2, _ := reader.ReadString('\n')
	arr := strings.Split(strings.TrimSpace(input2), " ")

	tStarirways, steps := 0, 0
	tSteps := []int{}
	for i := 0; i < n; i++ {
		if arr[i] == "1" {
			tStarirways++

			if steps > 0 {
				tSteps = append(tSteps, steps)
				steps = 0
			}
		}
		steps++
	}

	if steps > 0 {
		tSteps = append(tSteps, steps)
	}
	fmt.Println(tStarirways)

	for _, v := range tSteps {
		fmt.Printf("%v ", v)
	}
}

package main

import "fmt"

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

	a := make([]int, n)
	t := []int{}
	for i := range a {
		fmt.Scan(&a[i])

		if i == 0 || a[i-1] >= a[i] {
			t = append(t, a[i])
		} else {
			t[len(t)-1] = a[i]
		}
	}

	fmt.Println(len(t))
	for i, v := range t {
		if i != 0 {
			fmt.Print(" ")
		}
		fmt.Print(v)
	}
	fmt.Println()
}

package main

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

func main() {
	var n int
	fmt.Scanln(&n)
	el := make([]int, n)
	for i := range el {
		fmt.Scan(&el[i])
	}
	stairs := 0
	stairMax := make([]string, 0)
	for i := range el {
		if len(el) == 1 {
			stairs++
		} else {
			if el[i] == 1 {
				stairs++
				if i > 0 {
					stairMax = append(stairMax, strconv.Itoa(el[i-1]))
				} else if i == len(el)-1 {
					stairMax = append(stairMax, strconv.Itoa(el[i-1]))
				}
			}
		}
	}
	stairMax = append(stairMax, strconv.Itoa(el[len(el)-1]))
	fmt.Println(stairs)
	fmt.Println(str.Join(stairMax, " "))
}

package main

import "fmt"

func main()  {
	var n, cnt int;
	fmt.Scan(&n)
	var res []int
	for i, x := 0, 0; i < n; i++ {
		fmt.Scan(&x)
		if x == 1 {
			if cnt > 0 {
				res = append(res, cnt)
			}
			cnt = 0
		}
		cnt++
	}
	if cnt > 0 {
		res = append(res, cnt)
	}
	fmt.Println(len(res))
	for _, val := range res {
		fmt.Print(val, " ")
	}
	fmt.Println()
}

package main

import "fmt"

func main() {
	var buf []int
	var n, k, colvo int
	fmt.Scan(&k)
	for i:=0; i<k; i++ {
		fmt.Scan(&n)
		buf = append(buf, n)
	}
	buf = append(buf, 1)
	for i:=0; i<k; i++ {
		if buf[i] == 1 {
			colvo++
		}
	}
	fmt.Println(colvo)
	for i:=0; i<k+1; i++ {
		if buf[i] == 1 &&  i != 0 {
			fmt.Print(buf[i-1], " ")
		}
	}
}

package main

import (
	"fmt"
	"strings"
)

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

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

	var steps []int
	last := -1
	for _, v := range list {
		if v == 1 && last != -1 {
			steps = append(steps, last)
		}

		last = v
	}

	steps = append(steps, last)
	output := fmt.Sprint(steps)
	output = strings.Replace(output, "[", "", -1)
	output = strings.Replace(output, "]", "", -1)

	fmt.Println(len(steps))
	fmt.Println(output)
}

package main
import "fmt"
func main() {
	var n, x int
	l := 0
	r := []int{}
	fmt.Scan(&n)
	for i:=0; i < n; i++ {
		fmt.Scan(&x)
		if x <= l {
			r = append(r, l)
		}
		l = x
	}
	r = append(r, l)
	fmt.Println(len(r))
	for _,x := range r {
		fmt.Printf("%d ", x)
	}
}

package main

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

//Item eh um elemento da fila de prioridades
type Item struct {
	value    int
	priority int
	index    int
}

//PriorityQueue implmenta a heap interface
type PriorityQueue []*Item

//Len retorna o tamanho da  pq
func (pq PriorityQueue) Len() int { return len(pq) }

//Less verifica se um tem maior priotidade que o outro
func (pq PriorityQueue) Less(i, j int) bool { return pq[i].priority < pq[j].priority }

//Swap troca os elementos de lugar
func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

//Push insere um elemento na pq
func (pq *PriorityQueue) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Item)
	item.index = n
	*pq = append(*pq, item)
}

//Pop remove um elemento da pq
func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	item.index = -1 //for safety
	*pq = old[0 : n-1]
	return item
}

//update modifica o valor e a prioridade de um item na fila
func (pq *PriorityQueue) update(item *Item, value int, priority int) {
	item.value = value
	item.priority = priority
	heap.Fix(pq, item.index)
}

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

type pair struct {
	first  interface{}
	second interface{}
}

type intPair struct {
	first  int64
	second int64
}

type vertex struct {
	list []intPair
}

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

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

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

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

/*************************************************************************/
func main() {
	var (
		n        int
		num      int
		stairway []int
		cnt      int
		degraus  []int
	)

	fmt.Scan(&n)
	for i := 0; i < n; i++ {
		fmt.Scan(&num)
		stairway = append(stairway, num)
	}

	for i := 1; i < n; i++ {
		if stairway[i] <= stairway[i-1] {
			cnt++
			degraus = append(degraus, stairway[i-1])
		}
	}

	cnt++
	degraus = append(degraus, stairway[n-1])

	fmt.Println(cnt)

	for i := 0; i < len(degraus); i++ {
		if i > 0 {
			fmt.Print(" ")
		}
		fmt.Print(degraus[i])
	}
	fmt.Println()
}

package main

import "fmt"

func main() {
	var n int
	var count int = 0
	fmt.Scan(&n)
	var a []int = make([]int, n+1)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}
	for i := 0; i < n; i++ {
		if a[i] == 1 {
			count++
		}
	}
	fmt.Println(count)
	a[n] = 1
	for i := 0; i < n; i++ {
		if a[i+1] == 1 {
			fmt.Printf("%v ", a[i])
		}
	}
}

package main

import ("fmt")

func main(){
	var n, cur int
	scan(&n, &cur)
	ct := 0
	q := nQueue()
	for i := 1; i < n; i++{
		var t int
		scan(&t)
		ct++
		if cur + 1 != t{
			q.add(ct)
			ct = 0
		}
		cur = t
	}
	q.add(ct + 1)
	sout(q.size())
	r := q.toArray()
	for _,k := range r{
		sout(k)
	}
}

func scan(in ... interface{}){
	for _,k := range in{
		fmt.Scan(k)
	}
}
func sout(obj ... interface{}){
	for _, k := range obj{
		fmt.Print(k, " ")
	}
	fmt.Println()
}

type Queue struct{
	sz int
	val *int
	current, next, last *Queue
}

func nQueue()*Queue{
	q := Queue{}
	q.last = &q
	q.current = &q
	return &q
}

func (self *Queue)add(v int){
	if self.val != nil{
		nxt := Queue{}
		nxt.val = &v
		self.last.next = &nxt
		self.last = &nxt
	}else{
		self.val = &v
	}
	self.sz++
}

func (self *Queue)poll()int{
	v := *self.current.val
	self.current = self.current.next
	self.sz--
	return v
}

func (self *Queue)size()int{return self.sz}

func (self *Queue)peek()int{return *self.current.val}

func (self *Queue)toArray()[]int{
	ret := make([]int, self.sz)
	cur := self.current
	i := 0
	for cur != nil{
		ret[i] = *cur.val
		cur = cur.next
		i++
	}
	return ret
}

package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scan(&n)
	var l []int
	p :=0
	m :=0
	for i:=0;i<n;i++{
		var s int
		fmt.Scan(&s)
		if m<s {
			p++
		} else {
			l = append(l,p)
			p=1
		}
		m = s
	}
	l = append(l,p)
	fmt.Println(len(l))
	sl := fmt.Sprint(l)
	fmt.Println(sl[1:len(sl)-1])
}

package main

import "fmt"

func main() {
	var n int
	var ans [1000]int
	fmt.Scanf("%d", &n)
	count := 0
	for i := 0; i < n; i++ {
		var x int
		fmt.Scanf("%d", &x)
		if x != (ans[count] + 1) {
			count++
			ans[count] = ans[count] + 1
		} else {
			ans[count] = ans[count] + 1
		}
	}
	fmt.Println(count + 1)
	for i := 0; i <= count	; i++ {
		fmt.Print(ans[i], " ")
	}
	fmt.Println()
}

package main

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

func main() {
	var n int
	fmt.Scanln(&n)
	el := make([]int, n)
	for i := range el {
		fmt.Scan(&el[i])
	}
	stairs := 0
	stairMax := make([]string, 0)
	for i := range el {
		if i > 0 {
			if el[i] == 1 {
				stairs++

				stairMax = append(stairMax, strconv.Itoa(el[i-1]))
			} else if i == len(el)-1 {
				stairs++

				stairMax = append(stairMax, strconv.Itoa(el[i]))
			}
		}
	}
	fmt.Println(stairs)
	fmt.Println(str.Join(stairMax, " "))
}


You are a mayor of Berlyatov. There are $$$n$$$ districts and $$$m$$$ two-way roads between them. The $$$i$$$-th road connects districts $$$x_i$$$ and $$$y_i$$$. The cost of travelling along this road is $$$w_i$$$. There is some path between each pair of districts, so the city is connected.There are $$$k$$$ delivery routes in Berlyatov. The $$$i$$$-th route is going from the district $$$a_i$$$ to the district $$$b_i$$$. There is one courier on each route and the courier will always choose the cheapest (minimum by total cost) path from the district $$$a_i$$$ to the district $$$b_i$$$ to deliver products.The route can go from the district to itself, some couriers routes can coincide (and you have to count them independently).You can make at most one road to have cost zero (i.e. you choose at most one road and change its cost with $$$0$$$).Let $$$d(x, y)$$$ be the cheapest cost of travel between districts $$$x$$$ and $$$y$$$.Your task is to find the minimum total courier routes cost you can achieve, if you optimally select the some road and change its cost with $$$0$$$. In other words, you have to find the minimum possible value of $$$\sum\limits_{i = 1}^{k} d(a_i, b_i)$$$ after applying the operation described above optimally.

The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 1000$$$; $$$n - 1 \le m \le min(1000, \frac{n(n-1)}{2})$$$; $$$1 \le k \le 1000$$$) — the number of districts, the number of roads and the number of courier routes. The next $$$m$$$ lines describe roads. The $$$i$$$-th road is given as three integers $$$x_i$$$, $$$y_i$$$ and $$$w_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \ne y_i$$$; $$$1 \le w_i \le 1000$$$), where $$$x_i$$$ and $$$y_i$$$ are districts the $$$i$$$-th road connects and $$$w_i$$$ is its cost. It is guaranteed that there is some path between each pair of districts, so the city is connected. It is also guaranteed that there is at most one road between each pair of districts. The next $$$k$$$ lines describe courier routes. The $$$i$$$-th route is given as two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) — the districts of the $$$i$$$-th route. The route can go from the district to itself, some couriers routes can coincide (and you have to count them independently).

Print one integer — the minimum total courier routes cost you can achieve (i.e. the minimum value $$$\sum\limits_{i=1}^{k} d(a_i, b_i)$$$, where $$$d(x, y)$$$ is the cheapest cost of travel between districts $$$x$$$ and $$$y$$$) if you can make some (at most one) road cost zero.

NoteThe picture corresponding to the first example:There, you can choose either the road $$$(2, 4)$$$ or the road $$$(4, 6)$$$. Both options lead to the total cost $$$22$$$.The picture corresponding to the second example:There, you can choose the road $$$(3, 4)$$$. This leads to the total cost $$$13$$$.

package main

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

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

type edge struct {
	first  int
	second int
}

var n, m, k int
var dis [1007][1007]int
var G [1007][]edge
var path []edge

/******** Here is Heap *********/
type PairHeap []edge

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

func (h PairHeap) Less(i, j int) bool {
	if h[i].first == h[j].first {
		return h[i].second < h[j].second
	}
	return h[i].first < h[j].first
}

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

/******** End of Heap *********/

func dijkstra(st int) {
	for i := 0; i <= n; i++ {
		dis[st][i] = 1e9 + 7
	}
	dis[st][st] = 0
	vis := make([]bool, n+2)
	h := &PairHeap{}
	heap.Init(h)
	heap.Push(h, edge{0, st})
	for h.Len() > 0 {
		cur := (*h)[0]
		heap.Pop(h)
		if vis[cur.second] {
			continue
		}
		vis[cur.second] = true
		for _, e := range G[cur.second] {
			if dis[st][e.first] > dis[st][cur.second]+e.second {
				dis[st][e.first] = dis[st][cur.second] + e.second
				heap.Push(h, edge{dis[st][e.first], e.first})
			}
		}
	}
}

func min(x int, y int) int {
	if x < y {
		return x
	} else {
		return y
	}
}
func main() {
	_, _ = fmt.Fscan(_r, &n, &m, &k)
	for i := 1; i <= m; i++ {
		var x, y, w int
		_, _ = fmt.Fscan(_r, &x, &y, &w)
		G[x] = append(G[x], edge{y, w})
		G[y] = append(G[y], edge{x, w})
	}
	for i := 1; i <= k; i++ {
		var x, y int
		_, _ = fmt.Fscan(_r, &x, &y)
		path = append(path, edge{x, y})
	}
	for i := 1; i <= n; i++ {
		dijkstra(i)
	}
	ans := int(2e9 + 7)

	for v := 1; v <= n; v++ {
		for _, e := range G[v] {
			//enumerate edges
			res := 0
			for _, tmp := range path {
				res += min(dis[tmp.first][tmp.second], min(dis[tmp.first][v]+dis[e.first][tmp.second], dis[tmp.first][e.first]+dis[tmp.second][v]))
			}
			ans = min(ans, res)
		}
	}

	fmt.Println(ans)

}

package main

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

// github.com/EndlessCheng/codeforces-go
type vdPair struct {
	v   int
	dis int
}
type vdHeap []vdPair

func (h vdHeap) Len() int              { return len(h) }
func (h vdHeap) Less(i, j int) bool    { return h[i].dis < h[j].dis }
func (h vdHeap) Swap(i, j int)         { h[i], h[j] = h[j], h[i] }
func (h *vdHeap) Push(v interface{})   { *h = append(*h, v.(vdPair)) }
func (h *vdHeap) Pop() (v interface{}) { a := *h; *h, v = a[:len(a)-1], a[len(a)-1]; return }
func (h *vdHeap) push(v vdPair)        { heap.Push(h, v) }
func (h *vdHeap) pop() vdPair          { return heap.Pop(h).(vdPair) }

func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type edge struct{ v, w, wt int }

	var n, m, k int
	Fscan(in, &n, &m, &k)
	type nb struct {
		to int
		wt int
	}
	g := make([][]nb, n)
	es := make([]edge, m)
	for i := 0; i < m; i++ {
		var v, w, wt int
		Fscan(in, &v, &w, &wt)
		v--
		w--
		es[i] = edge{v, w, wt}
		g[v] = append(g[v], nb{w, wt})
		g[w] = append(g[w], nb{v, wt})
	}

	dij := func(st int) []int {
		const inf int = 1e9 + 1
		dist := make([]int, n)
		for i := range dist {
			dist[i] = inf
		}
		dist[st] = 0
		q := vdHeap{{st, 0}}
		for len(q) > 0 {
			p := q.pop()
			v := p.v
			if dist[v] < p.dis {
				continue
			}
			for _, e := range g[v] {
				w := e.to
				if newD := dist[v] + e.wt; newD < dist[w] {
					dist[w] = newD
					q.push(vdPair{w, newD})
				}
			}
		}
		return dist
	}
	dis := make([][]int, n)
	for i := 0; i < n; i++ {
		dis[i] = dij(i)
	}

	ans := 0
	rs := make([]edge, k)
	for i := range rs {
		var v, w int
		Fscan(in, &v, &w)
		v--
		w--
		ans += dis[v][w]
		rs[i] = edge{v, w, dis[v][w]}
	}

	maxDelta := 0
	for _, e := range es {
		v, w := e.v, e.w
		delta := 0
		for _, r := range rs {
			d := min(dis[r.v][v]+dis[r.w][w], dis[r.v][w]+dis[r.w][v])
			if d < r.wt {
				delta += r.wt - d
			}
		}
		maxDelta = max(maxDelta, delta)
	}
	Fprint(out, ans-maxDelta)
}

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

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
}


They say that Berland has exactly two problems, fools and roads. Besides, Berland has n cities, populated by the fools and connected by the roads. All Berland roads are bidirectional. As there are many fools in Berland, between each pair of cities there is a path (or else the fools would get upset). Also, between each pair of cities there is no more than one simple path (or else the fools would get lost). But that is not the end of Berland's special features. In this country fools sometimes visit each other and thus spoil the roads. The fools aren't very smart, so they always use only the simple paths.A simple path is the path which goes through every Berland city not more than once.The Berland government knows the paths which the fools use. Help the government count for each road, how many distinct fools can go on it.Note how the fools' paths are given in the input.

The first line contains a single integer n (2 ≤ n ≤ 105) — the number of cities.  Each of the next n - 1 lines contains two space-separated integers ui, vi (1 ≤ ui, vi ≤ n, ui ≠ vi), that means that there is a road connecting cities ui and vi.  The next line contains integer k (0 ≤ k ≤ 105) — the number of pairs of fools who visit each other.  Next k lines contain two space-separated numbers. The i-th line (i > 0) contains numbers ai, bi (1 ≤ ai, bi ≤ n). That means that the fool number 2i - 1 lives in city ai and visits the fool number 2i, who lives in city bi. The given pairs describe simple paths, because between every pair of cities there is only one simple path.

Print n - 1 integer. The integers should be separated by spaces. The i-th number should equal the number of fools who can go on the i-th road. The roads are numbered starting from one in the order, in which they occur in the input.

NoteIn the first sample the fool number one goes on the first and third road and the fool number 3 goes on the second, first and fourth ones.In the second sample, the fools number 1, 3 and 5 go on the first road, the fool number 5 will go on the second road, on the third road goes the fool number 3, and on the fourth one goes fool number 1.

package main

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

var w *bufio.Writer = bufio.NewWriter(os.Stdout)
var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)

var n, k, tyme uint
var log uint
var uu, vv, tin, tout []uint
var count []int
var used []bool
var g, q, p [][]uint

func DFS(v uint, par uint) {
    tyme++
    tin[v] = tyme
    p[v][0] = par
    for i := uint(1); i <= log; i++ {
        p[v][i] = p[p[v][i-1]][i-1]
    }
    for i := 0; i < len(g[v]); i++ {
        if g[v][i] != par {
            DFS(g[v][i], v)
        }
    }
    tyme++
    tout[v] = tyme
}

func IsP(v1 uint, v2 uint) bool {
    return tin[v1] <= tin[v2] && tout[v1] >= tout[v2]
}

func LCA(v1 uint, v2 uint) uint {
    if IsP(v1, v2) {
        return v1
    }
    if IsP(v2, v1) {
        return v2
    }
    for i := int(log); i >= 0; i-- {
        if !IsP(p[v1][i], v2) {
            v1 = p[v1][i]
        }
    }
    return p[v1][0]
}

func GetAns(v uint) int {
    if used[v] {
        return count[v]
    } else {
        for i := 0; i < len(g[v]); i++ {
            if !IsP(g[v][i], v) {
                count[v] += GetAns(g[v][i])
            }
        }
        used[v] = true
        return count[v]
    }
}

func Max(a uint, b uint) uint {
    if a < b {
        return b
    }
    return a
}

func main() {
    scanner.Split(bufio.ScanWords)

    scanner.Scan()
    tmp, _ := strconv.ParseUint(scanner.Text(), 10, 32)
    n = uint(tmp)
    for log = 1; (1 << log) <= n; log++ {
    }
    uu, vv, tin, tout, count = make([]uint, n),
        make([]uint, n),
        make([]uint, n),
        make([]uint, n),
        make([]int, n)
    g, q, p = make([][]uint, n), make([][]uint, n), make([][]uint, n)
    for i := uint(0); i < n; i++ {
        p[i] = make([]uint, log+1)
    }

    used = make([]bool, n)
    var u, v uint
    for i := uint(0); i < n-1; i++ {
        scanner.Scan()
        tmp, _ = strconv.ParseUint(scanner.Text(), 10, 32)
        u = uint(tmp)
        scanner.Scan()
        tmp, _ = strconv.ParseUint(scanner.Text(), 10, 32)
        v = uint(tmp)
        u--
        v--
        uu[i] = u
        vv[i] = v
        g[u] = append(g[u], v)
        g[v] = append(g[v], u)
    }
    DFS(0, 0)
    scanner.Scan()
    tmp, _ = strconv.ParseUint(scanner.Text(), 10, 32)
    k = uint(tmp)
    for i := uint(0); i < k; i++ {
        scanner.Scan()
        tmp, _ = strconv.ParseUint(scanner.Text(), 10, 32)
        u = uint(tmp)
        scanner.Scan()
        tmp, _ = strconv.ParseUint(scanner.Text(), 10, 32)
        v = uint(tmp)
        u--
        v--
        count[u]++
        count[v]++
        count[LCA(u, v)] -= 2
    }
    for i := 0; i < int(n); i++ {
        used[i] = false
    }
    for i := 0; i < int(n-1); i++ {
        if IsP(uu[i], vv[i]) {
            w.WriteString(strconv.Itoa(GetAns(vv[i])))
        } else {
            w.WriteString(strconv.Itoa(GetAns(uu[i])))
        }
        w.WriteByte(' ')
    }
    w.WriteByte('\n')
    w.Flush()
}

package main

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

type edge struct {
	id, to int
}

type rmq struct {
	r      [][]int
	values []int
}

func makeRMQ(indices, values []int) rmq {
	r := [][]int{indices}
	for i := 1; 1<<i <= len(indices); i++ {
		l := 1 << i
		r = append(r, make([]int, len(indices)-l+1))
		for j := range r[i] {
			a := r[i-1][j]
			b := r[i-1][j+l/2]
			if values[a] < values[b] {
				r[i][j] = a
			} else {
				r[i][j] = b
			}
		}
	}
	return rmq{r, values}
}

func (rmq rmq) min(fr, to int) int {
	if fr > to {
		fr, to = to, fr
	}
	i := bits.Len(uint(to-fr+1)) - 1
	a := rmq.r[i][fr]
	b := rmq.r[i][to-(1<<i)+1]
	if rmq.values[a] < rmq.values[b] {
		return a
	}
	return b
}

func main() {
	in := bufio.NewReaderSize(os.Stdin, 2<<16)
	var n int
	fmt.Fscan(in, &n)
	edges := make([][]edge, n+1)
	for i := 0; i < n-1; i++ {
		var u, v int
		fmt.Fscan(in, &u, &v)
		edges[u] = append(edges[u], edge{i, v})
		edges[v] = append(edges[v], edge{i, u})
	}

	var traversal []int
	traversalIndex := make([]int, n+1)
	depth := make([]int, n+1)
	var buildTraversal func(v, p int)
	buildTraversal = func(v, p int) {
		depth[v] = depth[p] + 1
		traversalIndex[v] = len(traversal)
		traversal = append(traversal, v)
		for _, e := range edges[v] {
			if e.to == p {
				continue
			}
			buildTraversal(e.to, v)
			traversal = append(traversal, v)
		}
	}
	buildTraversal(1, 1)

	rmq := makeRMQ(traversal, depth)

	numLCAs := make([]int, n+1)
	numStart := make([]int, n+1)

	var k int
	fmt.Fscan(in, &k)
	for i := 0; i < k; i++ {
		var a, b int
		fmt.Fscan(in, &a, &b)
		numStart[a]++
		numStart[b]++
		numLCAs[rmq.min(traversalIndex[a], traversalIndex[b])]++
	}

	ans := make([]int, n-1)
	var fools func(v, p int) int
	fools = func(v, p int) int {
		f := numStart[v] - 2*numLCAs[v]
		for _, e := range edges[v] {
			if e.to == p {
				continue
			}
			cur := fools(e.to, v)
			ans[e.id] = cur
			f += cur
		}
		return f
	}
	fools(1, 1)

	out := bufio.NewWriterSize(os.Stdout, 2<<16)
	defer out.Flush()
	for _, ans := range ans {
		fmt.Fprintln(out, ans)
	}
}

package main

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

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

	n := r()
	type edge struct{ to, id int }
	g := make([][]edge, n)
	for i := 0; i < n-1; i++ {
		v, w := r()-1, r()-1
		g[v] = append(g[v], edge{w, i})
		g[w] = append(g[w], edge{v, i})
	}
	pa := make([]int, n)
	for i := range pa {
		pa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if pa[x] != x {
			pa[x] = find(pa[x])
		}
		return pa[x]
	}

	d := make([]int, n)
	qs := make([][]int, n)
	vis := make([]int8, n)
	var _f func(int)
	_f = func(v int) {
		vis[v] = 1
		for _, e := range g[v] {
			if w := e.to; vis[w] == 0 {
				_f(w)
				pa[w] = v
			}
		}
		for _, w := range qs[v] {
			if vis[w] == 2 {
				d[v]++
				d[w]++
				d[find(w)] -= 2
			}
		}
		vis[v] = 2
	}
	for q := r(); q > 0; q-- {
		if v, w := r()-1, r()-1; v != w {
			qs[v] = append(qs[v], w)
			qs[w] = append(qs[w], v)
		}
	}
	_f(0)

	ans := make([]interface{}, n-1)
	var f func(v, fa int) int
	f = func(v, fa int) int {
		sum := d[v]
		for _, e := range g[v] {
			if w := e.to; w != fa {
				s := f(w, v)
				ans[e.id] = s
				sum += s
			}
		}
		return sum
	}
	f(0, -1)
	Fprint(out, ans...)
}

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

package main

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

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

	var n, v, w, q int
	Fscan(in, &n)
	type edge struct{ to, id int }
	g := make([][]edge, n)
	for i := 0; i < n-1; i++ {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], edge{w, i})
		g[w] = append(g[w], edge{v, i})
	}
	pa := make([]int, n)
	for i := range pa {
		pa[i] = i
	}
	var find func(int) int
	find = func(x int) int {
		if pa[x] != x {
			pa[x] = find(pa[x])
		}
		return pa[x]
	}

	d := make([]int, n)
	Fscan(in, &q)
	qs := make([][]int, n)
	vis := make([]int8, n)
	var _f func(int)
	_f = func(v int) {
		vis[v] = 1
		for _, e := range g[v] {
			if w := e.to; vis[w] == 0 {
				_f(w)
				pa[w] = v
			}
		}
		for _, w := range qs[v] {
			if vis[w] == 2 {
				d[v]++
				d[w]++
				d[find(w)] -= 2
			}
		}
		vis[v] = 2
	}
	for ; q > 0; q-- {
		Fscan(in, &v, &w)
		if v != w {
			v--
			w--
			qs[v] = append(qs[v], w)
			qs[w] = append(qs[w], v)
		}
	}
	_f(0)

	ans := make([]interface{}, n-1)
	var f func(v, fa int) int
	f = func(v, fa int) int {
		sum := d[v]
		for _, e := range g[v] {
			if w := e.to; w != fa {
				s := f(w, v)
				ans[e.id] = s
				sum += s
			}
		}
		return sum
	}
	f(0, -1)
	Fprint(out, ans...)
}

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


Olya has an array of integers $$$a_1, a_2, \ldots, a_n$$$. She wants to split it into tandem repeats. Since it's rarely possible, before that she wants to perform the following operation several (possibly, zero) number of times: insert a pair of equal numbers into an arbitrary position. Help her!More formally:  A tandem repeat is a sequence $$$x$$$ of even length $$$2k$$$ such that for each $$$1 \le i \le k$$$ the condition $$$x_i = x_{i + k}$$$ is satisfied.  An array $$$a$$$ could be split into tandem repeats if you can split it into several parts, each being a subsegment of the array, such that each part is a tandem repeat.  In one operation you can choose an arbitrary letter $$$c$$$ and insert $$$[c, c]$$$ to any position in the array (at the beginning, between any two integers, or at the end).  You are to perform several operations and split the array into tandem repeats or determine that it is impossible. Please note that you do not have to minimize the number of operations.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 30\,000$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 500$$$).  The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)  — the initial array.  It is guaranteed that the sum of $$$n^2$$$ over all test cases does not exceed $$$250\,000$$$.

For each test case print answer in the following format. If you cannot turn the array into a concatenation of tandem repeats, print a single integer $$$-1$$$. Otherwise print the number of operations $$$q$$$ ($$$0 \le q \le 2 \cdot n^2$$$) that you want to do. Then print the descriptions of operations. In each of the following $$$q$$$ lines print two integers $$$p$$$ and $$$c$$$ ($$$1 \le c \le 10^9$$$), which mean that you insert the integer $$$c$$$ twice after $$$p$$$ elements of the array. If the length of the array is $$$m$$$ before the operation, then the condition $$$0 \le p \le m$$$ should be satisfied. Then you should print any way to split the resulting array into tandem repeats. First, print a single integer $$$d$$$, and then print a sequence $$$t_1, t_2, \ldots, t_d$$$ of even integers of size $$$d$$$ ($$$d, t_i \ge 1$$$). These numbers are the lengths of the subsegments from left to right. Note that the size of the resulting array $$$a$$$ is $$$m = n + 2 \cdot q$$$. The following statements must hold:    $$$m = \sum\limits_{i = 1}^{d}{t_i}$$$.    For all integer $$$i$$$ such that $$$1 \le i \le d$$$, the sequence $$$a_l, a_{l+1}, \ldots, a_r$$$ is a tandem repeat, where $$$l = \sum\limits_{j = 1}^{i - 1}{t_j} + 1$$$, $$$r = l + t_i - 1$$$.  It can be shown that if the array can be turned into a concatenation of tandem repeats, then there exists a solution satisfying all constraints. If there are multiple answers, you can print any.

NoteIn the first test case, you cannot apply operations to the array to make it possible to split it into tandem repeats.In the second test case the array is already a tandem repeat $$$[5, 5] = \underbrace{([5] + [5])}_{t_1 = 2}$$$, thus we can do no operations at all.In the third test case, initially, we have the following array: $$$$$$[1, 3, 1, 2, 2, 3].$$$$$$ After the first insertion with $$$p = 1, c = 3$$$: $$$$$$[1, \textbf{3, 3}, 3, 1, 2, 2, 3].$$$$$$ After the second insertion with $$$p = 5, c = 3$$$: $$$$$$[1, 3, 3, 3, 1, \textbf{3, 3}, 2, 2, 3].$$$$$$ After the third insertion with $$$p = 5, c = 3$$$: $$$$$$[1, 3, 3, 3, 1, \textbf{3, 3}, 3, 3, 2, 2, 3].$$$$$$ After the fourth insertion with $$$p = 10, c = 3$$$: $$$$$$[1, 3, 3, 3, 1, 3, 3, 3, 3, 2, \textbf{3, 3}, 2, 3].$$$$$$ The resulting array can be represented as a concatenation of tandem repeats: $$$$$$\underbrace{([1, 3, 3, 3] + [1, 3, 3, 3])}_{t_1 = 8} + \underbrace{([3, 2, 3] + [3, 2, 3])}_{t_2 = 6}.$$$$$$In the fourth test case, initially, we have the following array: $$$$$$[3, 2, 1, 1, 2, 3].$$$$$$ After the first insertion with $$$p = 0, c = 3$$$: $$$$$$[\textbf{3, 3}, 3, 2, 1, 1, 2, 3].$$$$$$ After the second insertion with $$$p = 8, c = 3$$$: $$$$$$[3, 3, 3, 2, 1, 1, 2, 3, \textbf{3, 3}].$$$$$$ After the third insertion with $$$p = 5, c = 3$$$ $$$$$$[3, 3, 3, 2, 1, \textbf{3, 3}, 1, 2, 3, 3, 3].$$$$$$ After the fourth insertion with $$$p = 6, c = 2$$$: $$$$$$[3, 3, 3, 2, 1, 3, \textbf{2, 2}, 3, 1, 2, 3, 3, 3].$$$$$$ After the fifth insertion with $$$p = 7, c = 1$$$: $$$$$$[3, 3, 3, 2, 1, 3, 2, \textbf{1, 1}, 2, 3, 1, 2, 3, 3, 3].$$$$$$ The resulting array can be represented as a concatenation of tandem repeats: $$$$$$\underbrace{([3] + [3])}_{t_1 = 2} + \underbrace{([3, 2, 1] + [3, 2, 1])}_{t_2 = 6} + \underbrace{([1, 2, 3] + [1, 2, 3])}_{t_3 = 6} + \underbrace{([3] + [3])}_{t_4 = 2}.$$$$$$

package main

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

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

	var T, n int
o:
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		cnt := map[int]int{}
		a := make([]int, n)
		for i := range a {
			Fscan(in, &a[i])
			cnt[a[i]]++
		}
		for _, c := range cnt {
			if c&1 > 0 {
				Fprintln(out, -1)
				continue o
			}
		}

		op := [][2]int{}
		sz := []int{}
		for len(a) > 0 {
			pos := map[int]int{}
			for i, v := range a {
				p := pos[v]
				if p == 0 {
					pos[v] = i + 1
					continue
				}
				p--

				for j := p - 1; j >= 0; j-- {
					op = append(op, [2]int{i + (len(op)+len(sz))*2 - (p - 1 - j), a[j]})
				}
				for j := p + 1; j < i; j++ {
					op = append(op, [2]int{i + 1 + (len(op)+len(sz))*2 - (j - 1 - p), a[j]})
				}
				for j := p - 1; j >= 0; j-- {
					op = append(op, [2]int{i + 1 + (len(op)+len(sz))*2 - (i - 2 - j), a[j]})
				}
				sz = append(sz, (i+p)*2)

				for i, j := p+1, i-1; i < j; i++ {
					a[i], a[j] = a[j], a[i]
					j--
				}
				copy(a[p:], a[p+1:i])
				copy(a[i-1:], a[i+1:])
				a = a[:len(a)-2]
				break
			}
		}

		Fprintln(out, len(op))
		for _, p := range op {
			Fprintln(out, p[0], p[1])
		}
		Fprintln(out, len(sz))
		for _, v := range sz {
			Fprint(out, v, " ")
		}
		Fprintln(out)
	}
}

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

package main

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

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

	var T, n int
o:
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		cnt := map[int]int{}
		a := make([]int, n)
		for i := range a {
			Fscan(in, &a[i])
			cnt[a[i]]++
		}
		for _, c := range cnt {
			if c&1 > 0 {
				Fprintln(out, -1)
				continue o
			}
		}

		op := [][2]int{}
		sz := []int{}
		for len(a) > 0 {
			pos := map[int]int{}
			for i, v := range a {
				p := pos[v]
				if p == 0 {
					pos[v] = i + 1
					continue
				}
				p--

				for j := p - 1; j >= 0; j-- {
					op = append(op, [2]int{i + (len(op)+len(sz))*2 - (p - 1 - j), a[j]})
				}
				for j := p + 1; j < i; j++ {
					op = append(op, [2]int{i + 1 + (len(op)+len(sz))*2 - (j - 1 - p), a[j]})
				}
				for j := p - 1; j >= 0; j-- {
					op = append(op, [2]int{i + 1 + (len(op)+len(sz))*2 - (i - p - 1 + p - 1 - j), a[j]})
				}
				sz = append(sz, (i+p)*2)
				b := append([]int{}, a[p+1:i]...)
				for i, n := 0, len(b); i < n/2; i++ {
					b[i], b[n-1-i] = b[n-1-i], b[i]
				}

				a = append(append(append([]int{}, a[:p]...), b...), a[i+1:]...)
				break
			}
		}

		Fprintln(out, len(op))
		for _, p := range op {
			Fprintln(out, p[0], p[1])
		}
		Fprintln(out, len(sz))
		for _, v := range sz {
			Fprint(out, v, " ")
		}
		Fprintln(out)
	}
}

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

package main

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

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

	var T, n int
o:
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		cnt := map[int]int{}
		a := make([]int, n)
		for i := range a {
			Fscan(in, &a[i])
			cnt[a[i]]++
		}
		for _, c := range cnt {
			if c&1 > 0 {
				Fprintln(out, -1)
				continue o
			}
		}
		op := [][2]int{}
		sz := []int{}
		for len(a) > 2 {
			pos := map[int]int{}
			for i, v := range a {
				p := pos[v]
				if p == 0 {
					pos[v] = i + 1
					continue
				}
				p--

				for j := p - 1; j >= 0; j-- {
					op = append(op, [2]int{i + (len(op)+len(sz))*2 - (p - 1 - j), a[j]})
				}
				for j, k := i-1, 0; j >= 0; j-- {
					if j != p {
						op = append(op, [2]int{i + 1 + (len(op)+len(sz))*2 - k, a[j]})
						k++
					}
				}
				sz = append(sz, (i+p)*2)

				a = append(append(append([]int{}, a[:p]...), a[p+1:i]...), a[i+1:]...)
				break
			}
		}
		sz = append(sz, 2)

		Fprintln(out, len(op))
		for _, p := range op {
			Fprintln(out, p[0], p[1])
		}
		Fprintln(out, len(sz))
		for _, v := range sz {
			Fprint(out, v, " ")
		}
		Fprintln(out)
	}
}

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


There are $$$n$$$ block towers in a row, where tower $$$i$$$ has a height of $$$a_i$$$. You're part of a building crew, and you want to make the buildings look as nice as possible. In a single day, you can perform the following operation:  Choose two indices $$$i$$$ and $$$j$$$ ($$$1 \leq i, j \leq n$$$; $$$i \neq j$$$), and move a block from tower $$$i$$$ to tower $$$j$$$. This essentially decreases $$$a_i$$$ by $$$1$$$ and increases $$$a_j$$$ by $$$1$$$. You think the ugliness of the buildings is the height difference between the tallest and shortest buildings. Formally, the ugliness is defined as $$$\max(a)-\min(a)$$$. What's the minimum possible ugliness you can achieve, after any number of days?

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the number of buildings. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^7$$$) — the heights of the buildings.

For each test case, output a single integer — the minimum possible ugliness of the buildings.

NoteIn the first test case, the ugliness is already $$$0$$$.In the second test case, you should do one operation, with $$$i = 1$$$ and $$$j = 3$$$. The new heights will now be $$$[2, 2, 2, 2]$$$, with an ugliness of $$$0$$$.In the third test case, you may do three operations:   with $$$i = 3$$$ and $$$j = 1$$$. The new array will now be $$$[2, 2, 2, 1, 5]$$$,  with $$$i = 5$$$ and $$$j = 4$$$. The new array will now be $$$[2, 2, 2, 2, 4]$$$,  with $$$i = 5$$$ and $$$j = 3$$$. The new array will now be $$$[2, 2, 3, 2, 3]$$$.  The resulting ugliness is $$$1$$$. It can be proven that this is the minimum possible ugliness for this test.

package main
// github.com/jamesgrimard/codeforces
import(
    "fmt"
    "bufio"
    "os"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var n,sum int
		fmt.Fscan(in,&n)
		list:= make([]int,n)
		for j:=0;j<n;j++ {
			fmt.Fscan(in,&list[j])
			sum+=list[j]
		}
		if sum%n == 0 {
			fmt.Fprintln(out,0)
		} else {
			fmt.Fprintln(out,1)
		}
	}
}

package main

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

func solve() {
	f := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	N, n, p := 0, 0, 0
	fmt.Fscan(f, &N)
	for i := 0; i < N; i++ {
		fmt.Fscan(f, &n)
		sum := 0
		for j := 0; j < n; j++ {
			fmt.Fscan(f, &p)
			sum += p
		}
		if sum%n == 0 {
			fmt.Fprintln(w, 0)
		} else {
			fmt.Fprintln(w, 1)
		}
	}
	w.Flush()
}

func main() {
	solve()
}

package main

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

func CF1615A(rawIn io.Reader, rawOut io.Writer) {
	in := bufio.NewReader(rawIn)
	out := bufio.NewWriter(rawOut)
	defer out.Flush()

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

		var sum int64
		sum = 0
		for i := int64(0); i < t; i++ {
			var th int64
			fmt.Fscan(in, &th)
			sum += th
		}

		if sum%t == 0 {
			fmt.Fprint(out, "0\n")
		} else {
			fmt.Fprint(out, "1\n")
		}
	}
}

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

package main

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

func main() {

	f := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)

	t := 0
	fmt.Fscan(f, &t)

	for t > 0 {

		n := 0
		fmt.Fscan(f, &n)
		size := n

		sum := 0

		for n > 0 {
			temp := 0
			fmt.Fscan(f, &temp)
			sum += temp
			n--
		}

		if sum%size == 0 {
			fmt.Fprintln(w, 0)
		} else {
			fmt.Fprintln(w, 1)
		}

		w.Flush()

		t--
	}

	// a := []int{1, 2, 3, 1, 5}
	// fmt.Println(solve(a))
}

// func solve(a []int) int {

// 	sum := 0
// 	size := len(a)

// 	for i := range a {
// 		sum += a[i]
// 	}

// 	if sum%size == 0 {
// 		return 0
// 	} else {
// 		return 1
// 	}

// }

package main

import (
	"bufio"
	"fmt"
	"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
		fmt.Fscan(in, &n)

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

			sum += v
		}

		if sum%n == 0 {
			fmt.Fprintln(out, 0)
		} else {
			fmt.Fprintln(out, 1)
		}
	}
}

package main

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

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

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

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

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

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

/**
TO SEND
Run solve the problem CF1615A
Date: 8/01/22
User: pepradere
URL: https://codeforces.com/problemset/problem/1615/A
Problem: CF1615A
**/
func (in *CF1615A) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		sum := 0
		for i := 0; i < n; i++ {
			num := in.NextInt()
			sum += num
		}

		ans := 0
		if sum%n != 0 {
			ans = 1
		}
		fmt.Println(ans)
	}
}

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

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

package main

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

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

func solve(t int) {
	n := readInt()
	sum := 0
	for i := 0; i < n; i++ {
		sum += readInt()
	}
	if sum%n == 0 {
		println(0)
	} else {
		println(1)
	}
}

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

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

// READ
func readInt() int {
	var res int
	fmt.Fscan(in, &res)
	return res
}

func readInt64() int64 {
	var res int64
	fmt.Fscan(in, &res)
	return res
}

func readString() string {
	var res string
	fmt.Fscan(in, &res)
	return res
}

// PRINT
func print(args ...interface{}) {
	fmt.Fprint(out, args...)
}

func println(args ...interface{}) {
	fmt.Fprintln(out, args...)
	out.Flush()
}

package main

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

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

func main() {

	var t int64
	fmt.Fscan(rr, &t)

	for i := int64(0); i < t; i++ {

		var n int64
		fmt.Fscan(rr, &n)

		var sum int64
		for j := int64(0); j < n; j++ {
			var tmp int64
			fmt.Fscan(rr, &tmp)

			sum += tmp

		}

		var bruh int64
		bruh = sum / n
		bruh = bruh * n

		ans := 0

		if bruh != sum {
			ans = 1
		}

		fmt.Fprintln(ww, ans)
		ww.Flush()

	}
	ww.Flush()
}

package main

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

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

	t := readInt(reader)

	for t > 0 {
		n := readInt(reader)
		sum := 0

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

		if sum % n == 0 {
			fmt.Fprintln(writer, 0)
		} else {
			fmt.Fprintln(writer, 1)
		}

		t--
	}

	writer.Flush()
}

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

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

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

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

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

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

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

	return value
}

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

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

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

	var ar []int

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

	return ar
}

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

	var ar []int64

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

	return ar
}

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

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

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

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

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

	return x
}

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

package main

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

const MOD int64 = 1000000007

var n int

var a[]int

// ByAge implements sort.Interface based on the Age field.
type ByV []*pair

func (a ByV) Len() int           { return len(a) }
func (a ByV) Less(i, j int) bool { return a[i].v < a[j].v }
func (a ByV) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

func main() {

	read := bufio.NewReader(os.Stdin)

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

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

		fmt.Fscan(read, &n)

		a = make([]int, n)

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

		fmt.Println(solve())
	}
}

type pair struct {
	v int
	idx []int
}

func solve() int64 {

	var sum int64

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

	if sum % int64(n) == 0 {
		return 0
	}

	return 1
}

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

package main

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

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

func main() {
	var ntc int
	fmt.Fscan(in, &ntc)
	for t := 0; t < ntc; t++ {
		var n = 0
		fmt.Fscan(in, &n)
		var ai = 0
		var sum = 0
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &ai)
			sum += ai
		}
		if sum%n == 0 {
			fmt.Fprintf(out, "0\n")
		} else {
			fmt.Fprintf(out, "1\n")
		}
	}
	out.Flush()
}

package main
// github.com/jamesgrimard/codeforces
import(
    "fmt"
    "bufio"
    "os"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var n int
		fmt.Fscan(in,&n)
		list:= make([]int,n)
		for j:=0;j<n;j++ {fmt.Fscan(in,&list[j])}
		for j:=1;j<n;j++{
			if list[j] < list[j-1] {
				list[j],list[j-1]=list[j-1],list[j]
				j-=2
				if j<0 {
					j=0
				}
			}
		}
		for j:=0;j<=n/2;j++{
			list[j],list[n-1-j] = (list[j]+(list[n-1-j]-list[j])/2),(list[n-j-1]-(list[n-1-j]-list[j])/2)
		}
		for j:=1;j<n;j++{
			if list[j] < list [j-1] {
				list[j],list[j-1] = list[j-1],list[j]
				j-=2
				if j < 0 {
					j=0
				}
			}
		}
		fmt.Fprintln(out,list[n-1]-list[0])
	}
}

package main
// github.com/jamesgrimard/codeforces
import(
    "fmt"
    "bufio"
    "os"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var n int
		fmt.Fscan(in,&n)
		list:= make([]int,n)
		for j:=0;j<n;j++ {fmt.Fscan(in,&list[j])}
		for j:=1;j<n;j++{
			if list[j] < list[j-1] {
				list[j],list[j-1]=list[j-1],list[j]
				j-=2
				if j<0 {
					j=0
				}
			}
		}
		for j:=0;j<=n/2;j++{
			list[j],list[n-1-j] = (list[j]+(list[n-1-j]-list[j])/2),(list[n-j-1]-(list[n-1-j]-list[j])/2)
		}
		fmt.Fprintln(out,list[n-1]-list[1])
	}
}

package main
// github.com/jamesgrimard/codeforces
import(
    "fmt"
    "bufio"
    "os"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var n,xor,sum int
		fmt.Fscan(in,&n)
		list:= make([]int,n)
		for j:=0;j<n;j++{
			fmt.Fscan(in,&list[j])
			sum+=list[j]
			xor^=list[j]
		}
		if sum%n != 0 {
			fmt.Fprintln(out,xor-(sum/n+1))
			continue
		}
		fmt.Fprintln(out,xor-sum/n)
	}
}

package main

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

func solve() {
	f := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	N, n, p := 0, 0, 0
	fmt.Fscan(f, &N)
	for i := 0; i < N; i++ {
		fmt.Fscan(f, &n)
		min, max, sum, o := math.MaxInt, math.MinInt, 0, map[int]int{}
		for j := 0; j < n; j++ {
			fmt.Fscan(f, &p)
			sum += p
			if p > max {
				max = p
			}
			if p < min {
				min = p
			}
			o[p]++
		}
		avg := sum / n
		fmt.Fprintln(w, ((o[max] * (max - avg)) - (o[min] * (avg - min))))
	}
	w.Flush()
}

func main() {
	solve()
}

package main

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

func CF1615A(in io.Reader, out io.Writer) {
	var cases int
	fmt.Fscan(in, &cases)
	for c := 0; c < cases; c++ {
		var t int64
		fmt.Fscan(in, &t)

		var sum int64
		sum = 0
		for i := int64(0); i < t; i++ {
			var th int64
			fmt.Fscan(in, &th)
			sum += th
		}

		if sum%t == 0 {
			fmt.Fprint(out, "0\n")
		} else {
			fmt.Fprint(out, "1\n")
		}
	}
}

func main() { CF1615A(bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)) }


You are given $$$n$$$ segments on a number line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide.The intersection of a sequence of segments is such a maximal set of points (not necesserily having integer coordinates) that each point lies within every segment from the sequence. If the resulting set isn't empty, then it always forms some continuous segment. The length of the intersection is the length of the resulting segment or $$$0$$$ in case the intersection is an empty set.For example, the intersection of segments $$$[1;5]$$$ and $$$[3;10]$$$ is $$$[3;5]$$$ (length $$$2$$$), the intersection of segments $$$[1;5]$$$ and $$$[5;7]$$$ is $$$[5;5]$$$ (length $$$0$$$) and the intersection of segments $$$[1;5]$$$ and $$$[6;6]$$$ is an empty set (length $$$0$$$).Your task is to remove exactly one segment from the given sequence in such a way that the intersection of the remaining $$$(n - 1)$$$ segments has the maximal possible length.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the number of segments in the sequence. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \le l_i \le r_i \le 10^9$$$) — the description of the $$$i$$$-th segment.

Print a single integer — the maximal possible length of the intersection of $$$(n - 1)$$$ remaining segments after you remove exactly one segment from the sequence.

NoteIn the first example you should remove the segment $$$[3;3]$$$, the intersection will become $$$[2;3]$$$ (length $$$1$$$). Removing any other segment will result in the intersection $$$[3;3]$$$ (length $$$0$$$).In the second example you should remove the segment $$$[1;3]$$$ or segment $$$[2;6]$$$, the intersection will become $$$[2;4]$$$ (length $$$2$$$) or $$$[1;3]$$$ (length $$$2$$$), respectively. Removing any other segment will result in the intersection $$$[2;3]$$$ (length $$$1$$$).In the third example the intersection will become an empty set no matter the segment you remove.In the fourth example you will get the intersection $$$[3;10]$$$ (length $$$7$$$) if you remove the segment $$$[1;5]$$$ or the intersection $$$[1;5]$$$ (length $$$4$$$) if you remove the segment $$$[3;10]$$$.

package main

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

const (
	MaxN = 300005
	MaxEnd = 1000000001
)

type segment struct {
	start, end int64
}

var n int
var s []segment

func (s *segment) length() int64 {
	dist := s.end - s.start
	if dist < 0 {
		return 0
	}
	return dist
}

func (s *segment) intersect(other *segment) {
	if s.start < other.start {
		s.start = other.start
	}
	if s.end > other.end {
		s.end = other.end
	}
}

func findBest(s []segment) int64 {
	skippedOne := segment{0, MaxEnd}
	intersection := s[0]
	for i := 1; i < n; i++ {
		skippedOne.intersect(&s[i])
		if intersection.length() > skippedOne.length() {
			skippedOne = intersection
		}
		intersection.intersect(&s[i])
	}
	return skippedOne.length()
}

func reverse(s []segment) []segment {
	n := len(s)
	for i := 0; i < n / 2; i++ {
		s[i], s[n - i - 1] = s[n - i - 1], s[i]
	}
	return s
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d\n", &n)
	s = make([]segment, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d %d\n", &s[i].start, &s[i].end)
	}

	sort.Slice(s, func(i, j int) bool {
		if s[i].end > s[j].end {
			return true
		}
		if s[i].end < s[j].end {
			return false
		}
		return s[i].start > s[j].start
	})
	l1 := findBest(s)
	s = reverse(s)
	l2 := findBest(s)

	if l1 < l2 {
		fmt.Println(l2)
	} else {
		fmt.Println(l1)
	}

}

package main

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

const (
	MaxN = 300005
	MaxEnd = 1000000001
)

type segment struct {
	start, end int
}

var n int
var s [MaxN]segment
var intersection, skippedOne, best segment

func (s *segment) length() int {
	if s.end - s.start < 0 {
		return 0
	}
	return s.end - s.start
}

func (s *segment) intersect(other *segment) {
	if s.start <= other.start {
		s.start = other.start
		if s.end >= other.end {
			s.end = other.end
		}
	} else {
		if s.end >= other.end {
			s.end = other.end
		}
	}
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d\n", &n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d %d\n", &s[i].start, &s[i].end)
	}

	skippedOne = segment{0, MaxEnd}
	intersection = s[0]

	for i := 1; i < n; i++ {
		skippedOne.intersect(&s[i])
		if intersection.length() > skippedOne.length() {
			skippedOne = intersection
		}
		intersection.intersect(&s[i])
	}

	fmt.Println(skippedOne.length())
}

package main

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

const (
	MaxN = 300005
	MaxEnd = 1000000001
)

type segment struct {
	start, end int64
}

var n int
var s []segment
var intersection, skippedOne, best segment

func (s *segment) length() int64 {
	dist := s.end - s.start
	if dist < 0 {
		return 0
	}
	return dist
}

func (s *segment) intersect(other *segment) {
	if s.start < other.start {
		s.start = other.start
	}
	if s.end > other.end {
		s.end = other.end
	}
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d\n", &n)
	s = make([]segment, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d %d\n", &s[i].start, &s[i].end)
	}

	sort.Slice(s, func(i, j int) bool {
		if s[i].start < s[j].start {
			return true
		}
		if s[i].start > s[j].start {
			return false
		}
		return s[i].end > s[j].end
	})

	skippedOne = segment{0, MaxEnd}
	intersection = s[0]
	for i := 1; i < n; i++ {
		skippedOne.intersect(&s[i])
		if intersection.length() > skippedOne.length() {
			skippedOne = intersection
		}
		intersection.intersect(&s[i])
	}

	fmt.Println(skippedOne.length())
}

package main

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

const (
	MaxN = 300005
	MaxEnd = 1000000001
)

type segment struct {
	start, end int64
}

var n int
var s [MaxN]segment
var intersection, skippedOne, best segment

func (s *segment) length() int64 {
	if s.end - s.start < 0 {
		return 0
	}
	return s.end - s.start
}

func (s *segment) intersect(other *segment) {
	if s.start < other.start {
		s.start = other.start
		if s.end > other.end {
			s.end = other.end
		}
	} else {
		if s.end > other.end {
			s.end = other.end
		}
	}
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d\n", &n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d %d\n", &s[i].start, &s[i].end)
	}

	skippedOne = segment{0, MaxEnd}
	intersection = s[0]

	for i := 1; i < n; i++ {
		skippedOne.intersect(&s[i])
		if intersection.length() > skippedOne.length() {
			skippedOne = intersection
		}
		intersection.intersect(&s[i])
	}

	fmt.Println(skippedOne.length())
}

package main

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

const (
	MaxN = 300005
	MaxEnd = 1000000001
)

type segment struct {
	start, end int64
}

var n int
var s []segment
var intersection, skippedOne, best segment

func (s *segment) length() int64 {
	dist := s.end - s.start
	if dist < 0 {
		return 0
	}
	return dist
}

func (s *segment) intersect(other *segment) {
	if s.start < other.start {
		s.start = other.start
	}
	if s.end > other.end {
		s.end = other.end
	}
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d\n", &n)
	s = make([]segment, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d %d\n", &s[i].start, &s[i].end)
	}

	sort.Slice(s, func(i, j int) bool {
		if s[i].end > s[j].end {
			return true
		}
		if s[i].end < s[j].end {
			return false
		}
		return s[i].start < s[j].start
	})

	skippedOne = segment{0, MaxEnd}
	intersection = s[0]
	for i := 1; i < n; i++ {
		skippedOne.intersect(&s[i])
		if intersection.length() > skippedOne.length() {
			skippedOne = intersection
		}
		intersection.intersect(&s[i])
	}
	fmt.Println(skippedOne.length())
}

package main

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

const (
	MaxN = 300005
	MaxEnd = 1000000001
)

type segment struct {
	start, end int
}

var n int
var s [MaxN]segment
var intersection, skippedOne, best segment

func (s *segment) length() int {
	if s.end - s.start < 0 {
		return 0
	}
	return s.end - s.start
}

func (s *segment) intersect(other *segment) {
	if s.start < other.start {
		s.start = other.start
		if s.end > other.end {
			s.end = other.end
		}
	} else {
		if s.end > other.end {
			s.end = other.end
		}
	}
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d\n", &n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d %d\n", &s[i].start, &s[i].end)
	}

	skippedOne = segment{0, MaxEnd}
	intersection = s[0]

	for i := 1; i < n; i++ {
		skippedOne.intersect(&s[i])
		if intersection.length() > skippedOne.length() {
			skippedOne = intersection
		}
		intersection.intersect(&s[i])
	}
	if intersection.length() > skippedOne.length() {
		skippedOne = intersection
	}

	fmt.Println(skippedOne.length())
}

package main

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

const (
	MaxN = 300005
	MaxEnd = 1000000001
)

type segment struct {
	start, end int64
}

var n int
var s []segment

func (s *segment) length() int64 {
	dist := s.end - s.start
	if dist < 0 {
		return 0
	}
	return dist
}

func (s *segment) intersect(other *segment) {
	if s.start < other.start {
		s.start = other.start
	}
	if s.end > other.end {
		s.end = other.end
	}
}

func findBest(s []segment) int64 {
	skippedOne := segment{0, MaxEnd}
	intersection := s[0]
	for i := 1; i < n; i++ {
		skippedOne.intersect(&s[i])
		if intersection.length() > skippedOne.length() {
			skippedOne = intersection
		}
		intersection.intersect(&s[i])
	}
	return skippedOne.length()
}

func reverse(s []segment) []segment {
	n := len(s)
	for i := 0; i < n / 2; i++ {
		s[i], s[n - i - 1] = s[n - i - 1], s[i]
	}
	return s
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d\n", &n)
	s = make([]segment, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d %d\n", &s[i].start, &s[i].end)
	}

	l1 := findBest(s)
	s = reverse(s)
	l2 := findBest(s)

	if l1 < l2 {
		fmt.Println(l2)
	} else {
		fmt.Println(l1)
	}

}

package main

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

const (
	MaxN = 300005
	MaxEnd = 1000000001
)

type segment struct {
	start, end int64
}

var n int
var s []segment
var intersection, skippedOne, best segment

func (s *segment) length() int64 {
	dist := s.end - s.start
	if dist < 0 {
		return 0
	}
	return dist
}

func (s *segment) intersect(other *segment) {
	if s.start < other.start {
		s.start = other.start
	}
	if s.end > other.end {
		s.end = other.end
	}
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d\n", &n)
	s = make([]segment, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d %d\n", &s[i].start, &s[i].end)
	}

	sort.Slice(s, func(i, j int) bool {
		if s[i].start < s[j].start {
			return true
		}
		if s[i].start > s[j].start {
			return false
		}
		return s[i].end > s[j].end
	})

	skippedOne = segment{0, MaxEnd}
	intersection = s[0]
	for i := 1; i < n; i++ {
		skippedOne.intersect(&s[i])
		if intersection.length() >= skippedOne.length() {
			skippedOne = intersection
		}
		intersection.intersect(&s[i])
	}

	fmt.Println(skippedOne.length())
}

package main

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

const (
	MaxN = 300005
	MaxEnd = 1000000001
)

type segment struct {
	start, end int64
}

var n int
var s []segment
var intersection, skippedOne, best segment

func (s *segment) length() int64 {
	dist := s.end - s.start
	if dist < 0 {
		return 0
	}
	return dist
}

func (s *segment) intersect(other *segment) {
	if s.start < other.start {
		s.start = other.start
	}
	if s.end > other.end {
		s.end = other.end
	}
}

func main() {
	buf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(buf, "%d\n", &n)
	s = make([]segment, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(buf, "%d %d\n", &s[i].start, &s[i].end)
	}

	sort.Slice(s, func(i, j int) bool {
		if s[i].start < s[j].start {
			return true
		}
		if s[i].start > s[j].start {
			return false
		}
		return s[i].end < s[j].end
	})

	skippedOne = segment{0, MaxEnd}
	intersection = s[0]
	for i := 1; i < n; i++ {
		skippedOne.intersect(&s[i])
		if intersection.length() > skippedOne.length() {
			skippedOne = intersection
		}
		intersection.intersect(&s[i])
	}
	fmt.Println(skippedOne.length())
}


Vasya has got two number: a and b. However, Vasya finds number a too short. So he decided to repeat the operation of lengthening number a n times.One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is divisible by Vasya's number b. If it is impossible to obtain the number which is divisible by b, then the lengthening operation cannot be performed.Your task is to help Vasya and print the number he can get after applying the lengthening operation to number a n times.

The first line contains three integers: a, b, n (1 ≤ a, b, n ≤ 105).

In a single line print the integer without leading zeros, which Vasya can get when he applies the lengthening operations to number a n times. If no such number exists, then print number -1. If there are multiple possible answers, print any of them.

package main
import (
	"fmt"
)
func main() {
	var a,b,n,j int
	fmt.Scan(&a,&b,&n)
	flag:=false
	for i:=0;i<10;i++ {
		if (a*10+i)%b==0 {
			fmt.Printf("%d%d",a,i)
		for j=0;j<n-1;j++ {
			fmt.Printf("0")
		}
		flag=true
		break
		}
	}
	if flag==false {
		fmt.Println("-1")
	}
}

package main

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

func main() {
    writer := bufio.NewWriter(os.Stdout)
    var a,b,n int
    fmt.Scan(&a,&b,&n)
    ok := false
    for i := 0; i < 10; i++ {
        if ((a*10)+i)%b == 0 {
            ok, a = true, (a*10)+i
            n--
            break
        }
    }
    if ok {
        fmt.Print(a)
        for ; n > 0; n-- { writer.WriteRune('0') }
        writer.WriteRune('\n')
        writer.Flush()
    } else {
        fmt.Println(-1)
    }
}

// 260A-mic
package main

import (
    "fmt"
)

func main() {
    var a, b, n int
    fmt.Scan(&a, &b, &n)
    a *= 10
    x := a % b
    if x != 0 {
        x = b - x
    }
    if x/10 == 0 {
        a += x
    } else {
        a = -1
    }
    fmt.Print(a)

    if a != -1 {
        for i := 1; i < n; i++ {
            fmt.Print("0")
        }
        fmt.Println()
    }
}

package main
import (
	"fmt"
)
func main() {
	var a,b,n,j int
	fmt.Scan(&a,&b,&n)
	flag:=false
	for i:=0;i<10;i++ {
		if (a*10+i)%b==0 {
			fmt.Printf("%d%d",a,i)
		for j=0;j<n-1;j++ {
			fmt.Printf("0")
			flag=true
		}
		break
		}
	}
	if flag==false {
		fmt.Println("-1")
	}
}