Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1 × n in size, when viewed from above. This rectangle is divided into n equal square sections. The garden is very unusual as each of the square sections possesses its own fixed height and due to the newest irrigation system we can create artificial rain above each section.Creating artificial rain is an expensive operation. That's why we limit ourselves to creating the artificial rain only above one section. At that, the water from each watered section will flow into its neighbouring sections if their height does not exceed the height of the section. That is, for example, the garden can be represented by a 1 × 5 rectangle, where the section heights are equal to 4, 2, 3, 3, 2. Then if we create an artificial rain over any of the sections with the height of 3, the water will flow over all the sections, except the ones with the height of 4. See the illustration of this example at the picture:  As Petya is keen on programming, he decided to find such a section that if we create artificial rain above it, the number of watered sections will be maximal. Help him.

The first line contains a positive integer n (1 ≤ n ≤ 1000). The second line contains n positive integers which are the height of the sections. All the numbers are no less than 1 and not more than 1000.

Print a single number, the maximal number of watered sections if we create artificial rain above exactly one section.

package main
import (
	"fmt"
)
func max(a,b int) int{
	if a>b {
		return a
	} else {
		return b
	}
}

func main() {
	var n,ans int
	var a [1001]int
	ans=0
	fmt.Scan(&n)
	for i:=0; i<n; i++{
		fmt.Scan(&a[i])
	}
	for i:=0; i<n; i++{
		l,r:=0,0
		for ; (i-l)>0 && a[i-l-1]<=a[i-l];l++ {}
		for ; (i+r)<n-1 && a[i+r]>=a[i+r+1];r++ {}
		ans = max(ans,l+r+1)
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
)

func main() {
	var n int
	var arr [1001]int
	max := -1

	fmt.Scan(&n)

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

	for i := 0; i < n; i++ {
		counter := 1
		for j := i; (j-1) >= 0 && arr[j] >= arr[j-1]; j-- {
			counter++
		}

		for j := i; (j+1) < n && arr[j] >= arr[j+1]; j++ {
			counter++
		}

		if max < counter {
			max = counter
		}
	}

	fmt.Println(max)

}

package main

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

func max(nums ...int) int {
	res := math.MinInt32
	for _, num := range nums {
		if num > res {
			res = num
		}
	}
	return res
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanInt := func() int {
		scanner.Scan()
		num, err := strconv.Atoi(scanner.Text())
		if err != nil {
			log.Fatal(err)
		}
		return num
	}

	n := scanInt()
	f, width := make([]int, n), make([]int, n)
	for i := 0; i < n; i++ {
		f[i] = scanInt()
	}

	for i := 0; i < n; i++ {
		left, right := i, i
		for (left > 0) && (f[left-1] <= f[left]) {
			left--
		}
		for (right < (n - 1)) && (f[right+1] <= f[right]) {
			right++
		}
		width[i] = right - left + 1
	}
	fmt.Println(max(width...))
}


There are $$$n$$$ Christmas trees on an infinite number line. The $$$i$$$-th tree grows at the position $$$x_i$$$. All $$$x_i$$$ are guaranteed to be distinct.Each integer point can be either occupied by the Christmas tree, by the human or not occupied at all. Non-integer points cannot be occupied by anything.There are $$$m$$$ people who want to celebrate Christmas. Let $$$y_1, y_2, \dots, y_m$$$ be the positions of people (note that all values $$$x_1, x_2, \dots, x_n, y_1, y_2, \dots, y_m$$$ should be distinct and all $$$y_j$$$ should be integer). You want to find such an arrangement of people that the value $$$\sum\limits_{j=1}^{m}\min\limits_{i=1}^{n}|x_i - y_j|$$$ is the minimum possible (in other words, the sum of distances to the nearest Christmas tree for all people should be minimized).In other words, let $$$d_j$$$ be the distance from the $$$j$$$-th human to the nearest Christmas tree ($$$d_j = \min\limits_{i=1}^{n} |y_j - x_i|$$$). Then you need to choose such positions $$$y_1, y_2, \dots, y_m$$$ that $$$\sum\limits_{j=1}^{m} d_j$$$ is the minimum possible.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of Christmas trees and the number of people. The second line of the input contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$), where $$$x_i$$$ is the position of the $$$i$$$-th Christmas tree. It is guaranteed that all $$$x_i$$$ are distinct.

In the first line print one integer $$$res$$$ — the minimum possible value of $$$\sum\limits_{j=1}^{m}\min\limits_{i=1}^{n}|x_i - y_j|$$$ (in other words, the sum of distances to the nearest Christmas tree for all people). In the second line print $$$m$$$ integers $$$y_1, y_2, \dots, y_m$$$ ($$$-2 \cdot 10^9 \le y_j \le 2 \cdot 10^9$$$), where $$$y_j$$$ is the position of the $$$j$$$-th human. All $$$y_j$$$ should be distinct and all values $$$x_1, x_2, \dots, x_n, y_1, y_2, \dots, y_m$$$ should be distinct. If there are multiple answers, print any of them.

package main

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

const maxn = 200500

var n, m int
var x, y [maxn]int
var qu []int
var was map[int]int

func try_to_append(c int, dist int) {
    _, ok := was[c]
    if !ok {
        was[c] = dist
        qu = append(qu, c)
    }
}

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

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

    was = make(map[int]int)
    qu = make([]int, 0, n + m)
    for i := 1; i <= n; i++ {
        was[x[i]] = 0
        qu = append(qu, x[i])
    }

    for i := 0; len(qu) < n + m; i++ {
        cur := qu[i]
        try_to_append(cur - 1, was[cur] + 1)
        try_to_append(cur + 1, was[cur] + 1)
    }

    var sum int64 = 0
    for i := n; i < n + m; i++ {
        sum += int64(was[qu[i]])
    }

    fmt.Fprintf(writer, "%d\n", sum)
    for i := n; i < n + m; i++ {
        fmt.Fprintf(writer, "%d ", qu[i])
    }
}


Luckily, Serval got onto the right bus, and he came to the kindergarten on time. After coming to kindergarten, he found the toy bricks very funny.He has a special interest to create difficult problems for others to solve. This time, with many $$$1 \times 1 \times 1$$$ toy bricks, he builds up a 3-dimensional object. We can describe this object with a $$$n \times m$$$ matrix, such that in each cell $$$(i,j)$$$, there are $$$h_{i,j}$$$ bricks standing on the top of each other.However, Serval doesn't give you any $$$h_{i,j}$$$, and just give you the front view, left view, and the top view of this object, and he is now asking you to restore the object. Note that in the front view, there are $$$m$$$ columns, and in the $$$i$$$-th of them, the height is the maximum of $$$h_{1,i},h_{2,i},\dots,h_{n,i}$$$. It is similar for the left view, where there are $$$n$$$ columns. And in the top view, there is an $$$n \times m$$$ matrix $$$t_{i,j}$$$, where $$$t_{i,j}$$$ is $$$0$$$ or $$$1$$$. If $$$t_{i,j}$$$ equals $$$1$$$, that means $$$h_{i,j}>0$$$, otherwise, $$$h_{i,j}=0$$$.However, Serval is very lonely because others are bored about his unsolvable problems before, and refused to solve this one, although this time he promises there will be at least one object satisfying all the views. As his best friend, can you have a try?

The first line contains three positive space-separated integers $$$n, m, h$$$ ($$$1\leq n, m, h \leq 100$$$) — the length, width and height. The second line contains $$$m$$$ non-negative space-separated integers $$$a_1,a_2,\dots,a_m$$$, where $$$a_i$$$ is the height in the $$$i$$$-th column from left to right of the front view ($$$0\leq a_i \leq h$$$). The third line contains $$$n$$$ non-negative space-separated integers $$$b_1,b_2,\dots,b_n$$$ ($$$0\leq b_j \leq h$$$), where $$$b_j$$$ is the height in the $$$j$$$-th column from left to right of the left view. Each of the following $$$n$$$ lines contains $$$m$$$ numbers, each is $$$0$$$ or $$$1$$$, representing the top view, where $$$j$$$-th number of $$$i$$$-th row is $$$1$$$ if $$$h_{i, j}>0$$$, and $$$0$$$ otherwise. It is guaranteed that there is at least one structure satisfying the input.

Output $$$n$$$ lines, each of them contains $$$m$$$ integers, the $$$j$$$-th number in the $$$i$$$-th line should be equal to the height in the corresponding position of the top view. If there are several objects satisfying the views, output any one of them.

Note  The graph above illustrates the object in the first example.    The first graph illustrates the object in the example output for the second example, and the second graph shows the three-view drawing of it.

package main

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

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

	var n, m, h int
	fmt.Fscanf(buf, "%d %d %d\n", &n, &m, &h)
	matn := make([]int, n+1)
	matm := make([]int, m+1)

	for i := 1; i <= m; i++ {
		fmt.Fscanf(buf, "%d", &matm[i])
	}
	fmt.Fscanf(buf, "\n")
	for i := 1; i <= n; i++ {
		fmt.Fscanf(buf, "%d", &matn[i])
	}
	fmt.Fscanf(buf, "\n")
	var val int
	for i:=1;i <= n;i++{
		for j:=1;j <= m;j++{
			fmt.Fscanf(buf, "%d", &val)
			if val == 0{
				fmt.Printf("0 ")
			}else{
				if matn[i] < matm[j]{
					fmt.Printf("%d ",matn[i])
				}else{
					fmt.Printf("%d ",matm[j])
				}

			}
		}
		fmt.Printf("\n")
		fmt.Fscanf(buf, "\n")
	}

}
/**
2 0 0 0 2 0 0
0 0 0 0 0 0 1
2 3 0 0 0 0 0
 */

package main

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

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

    arTemp := strings.Split(readLine(reader), " ")
    n64, err := strconv.ParseInt(arTemp[0], 10, 32)
    checkError(err)
    m64, err := strconv.ParseInt(arTemp[1], 10, 32)
    checkError(err)
    //h64, err := strconv.ParseInt(arTemp[2], 10, 32)
    //checkError(err)
    n := int32(n64)
    m := int32(m64)
    //h := int32(h64)

    a := make([]int32, m)
    b := make([]int32, n)
    ans := make([][]int32, n)

    arTemp = strings.Split(readLine(reader), " ")
    for i := int32(0); i < m; i++ {
        arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 32)
        checkError(err)
        arItem := int32(arItemTemp)
        a[i] = arItem
    }
    arTemp = strings.Split(readLine(reader), " ")
    for i := int32(0); i < n; i++ {
        arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 32)
        checkError(err)
        arItem := int32(arItemTemp)
        b[i] = arItem
    }
    for i := int32(0); i < n; i++ {
        ans[i] = make([]int32, m)
        arTemp = strings.Split(readLine(reader), " ")
        for j := int32(0); j < m; j++ {
            arItemTemp, err := strconv.ParseInt(arTemp[j], 10, 32)
            checkError(err)
            arItem := int32(arItemTemp)
            ans[i][j] = arItem
        }
    }

    for i := int32(0); i < n; i++ {
        for j := int32(0); j < m; j++ {
            if ans[i][j] == 1 {
                if a[j] < b[i] {
                    fmt.Print(a[j])
                } else {
                    fmt.Print(b[i])
                }
            } else {
                fmt.Print(0)
            }
            if j < (m - 1) {
                fmt.Print(" ")
            }
        }
        fmt.Println("")
    }
}

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

package main

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

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

	var n, m, h int
	fmt.Fscanln(in, &n, &m, &h)

	marr := make([]int, m)
	narr := make([]int, n)

	for i := range marr {
		fmt.Fscan(in, &marr[i])
	}
	in.ReadLine()
	for i := range narr {
		fmt.Fscan(in, &narr[i])
	}
	in.ReadLine()

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

			if cur == 0 {
				fmt.Print(0, " ")
				continue
			}

			if narr[i] < marr[j] {
				fmt.Print(narr[i], " ")
			} else {
				fmt.Print(marr[j], " ")
			}
		}
		fmt.Println()
		in.ReadLine()
	}
}

package main

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

func main() {
	sc := NewScanner()
	n, m, _ := sc.NextInt(), sc.NextInt(), sc.NextInt()
	a := sc.NextIntArray()
	b := sc.NextIntArray()

	ans := make([][]int, n)

	H := make([][]int, n)
	for i := 0; i < n; i++ {
		ans[i] = make([]int, m)
		H[i] = sc.NextIntArray()
	}

	for j := 0; j < m; j++ {
		for k := 0; k < n; k++ {
			if H[k][j] == 1 {
				//fmt.Println(k, j)
				ans[k][j] = min(a[j], b[k])
			}
		}
	}
	for i := 0; i < n; i++ {
		PrintI(ans[i]...)
	}
}

func mapToString(arr []int) []string {
	ret := make([]string, len(arr))
	for i := 0; i < len(arr); i++ {
		ret[i] = strconv.Itoa(arr[i])
	}
	return ret
}

func PrintI(args ...int) {
	fmt.Println(strings.Join(mapToString(args), " "))
}

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

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

func maxA(arg ...int) int {
	var s = arg[0]
	for _, v := range arg {
		s = max(s, v)
	}
	return s
}

type Scanner struct {
	r   *bufio.Reader
	buf []byte
	p   int
}

func NewScanner() *Scanner {
	rdr := bufio.NewReaderSize(os.Stdin, 1000)
	return &Scanner{r: rdr}
}
func (s *Scanner) Next() string {
	s.pre()
	start := s.p
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			break
		}
	}
	result := string(s.buf[start:s.p])
	s.p++
	return result
}
func (s *Scanner) NextLine() string {
	s.pre()
	start := s.p
	s.p = len(s.buf)
	return string(s.buf[start:])
}
func (s *Scanner) NextInt() int {
	v, _ := strconv.Atoi(s.Next())
	return v
}
func (s *Scanner) NextInt64() int64 {
	v, _ := strconv.ParseInt(s.Next(), 10, 64)
	return v
}

func (s *Scanner) NextFloat() float64 {
	v, _ := strconv.ParseFloat(s.Next(), 64)
	return v
}

func (s *Scanner) NextIntArray() []int {
	s.pre()
	start := s.p
	result := []int{}
	for ; s.p < len(s.buf)+1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 0)
			result = append(result, int(v))
			start = s.p + 1
		}
	}

	return result
}
func (s *Scanner) NextInt64Array() []int64 {
	s.pre()
	start := s.p
	result := []int64{}
	for ; s.p < len(s.buf)+1; s.p++ {
		if s.p == len(s.buf) || s.buf[s.p] == ' ' {
			v, _ := strconv.ParseInt(string(s.buf[start:s.p]), 10, 64)
			result = append(result, v)
			start = s.p + 1
		}
	}
	return result
}

func (s *Scanner) NextMap() map[int]bool {
	s.pre()
	start := s.p
	mp := map[int]bool{}
	for ; s.p < len(s.buf); s.p++ {
		if s.buf[s.p] == ' ' {
			v, _ := strconv.Atoi(string(s.buf[start:s.p]))
			mp[v] = true
			start = s.p + 1
		}
	}
	v, _ := strconv.Atoi(string(s.buf[start:s.p]))
	mp[v] = true

	return mp
}

func (s *Scanner) pre() {
	if s.p >= len(s.buf) {
		s.readLine()
		s.p = 0
	}
}
func (s *Scanner) readLine() {
	s.buf = make([]byte, 0)
	for {
		l, p, e := s.r.ReadLine()
		if e != nil {
			panic(e)
		}
		s.buf = append(s.buf, l...)
		if !p {
			break
		}
	}
}

package main

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

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

	var n, m, h int
	fmt.Fscanln(in, &n, &m, &h)

	marr := make([]int, m)
	narr := make([]int, n)

	for i := range marr {
		fmt.Fscan(in, &marr[i])
	}
	in.ReadLine()
	for i := range narr {
		fmt.Fscan(in, &narr[i])
	}
	in.ReadLine()

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

			if cur == 0 {
				fmt.Print(0, " ")
				continue
			}

			if narr[i] > marr[i] {
				fmt.Print(narr[i], " ")
			} else {
				fmt.Print(marr[i], " ")
			}
		}
		fmt.Println()
		in.ReadLine()
	}
}


Vasily has a deck of cards consisting of n cards. There is an integer on each of the cards, this integer is between 1 and 100 000, inclusive. It is possible that some cards have the same integers on them.Vasily decided to sort the cards. To do this, he repeatedly takes the top card from the deck, and if the number on it equals the minimum number written on the cards in the deck, then he places the card away. Otherwise, he puts it under the deck and takes the next card from the top, and so on. The process ends as soon as there are no cards in the deck. You can assume that Vasily always knows the minimum number written on some card in the remaining deck, but doesn't know where this card (or these cards) is.You are to determine the total number of times Vasily takes the top card from the deck.

The first line contains single integer n (1 ≤ n ≤ 100 000) — the number of cards in the deck. The second line contains a sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000), where ai is the number written on the i-th from top card in the deck.

Print the total number of times Vasily takes the top card from the deck.

NoteIn the first example Vasily at first looks at the card with number 6 on it, puts it under the deck, then on the card with number 3, puts it under the deck, and then on the card with number 1. He places away the card with 1, because the number written on it is the minimum among the remaining cards. After that the cards from top to bottom are [2, 6, 3]. Then Vasily looks at the top card with number 2 and puts it away. After that the cards from top to bottom are [6, 3]. Then Vasily looks at card 6, puts it under the deck, then at card 3 and puts it away. Then there is only one card with number 6 on it, and Vasily looks at it and puts it away. Thus, in total Vasily looks at 7 cards.

package main

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

const INF int = 10000000

var a [100005]int
var minv, pos, sum [300005]int

func up(o int) {
	sum[o] = sum[o<<1] + sum[o<<1|1]
	if minv[o<<1] <= minv[o<<1|1] {
		minv[o] = minv[o<<1]
		pos[o] = pos[o<<1]
	} else {
		minv[o] = minv[o<<1|1]
		pos[o] = pos[o<<1|1]
	}
}

func build(o, l, r int) {
	if l >= r {
		minv[o] = a[l]
		pos[o] = l
		sum[o] = 1
		return
	}
	m := (l + r) >> 1
	build(o<<1, l, m)
	build(o<<1|1, m+1, r)
	up(o)
}

func query(L, R, o, l, r int) (x, y, z int) {
	if L <= l && r <= R {
		return minv[o], pos[o], sum[o]
	}
	m := (l + r) >> 1
	x, y = INF, INF
	z = 0
	if L <= m {
		x1, y1, z1 := query(L, R, o<<1, l, m)
		if x > x1 {
			x = x1
			y = y1
		} else if x == x1 {
			if y > y1 {
				y = y1
			}
		}
		z += z1
	}
	if m < R {
		x1, y1, z1 := query(L, R, o<<1|1, m+1, r)
		if x > x1 {
			x = x1
			y = y1
		} else if x == x1 {
			if y > y1 {
				y = y1
			}
		}
		z += z1
	}
	return
}

func update(x, o, l, r int) {
	if l >= r {
		minv[o] = INF
		pos[o] = INF
		sum[o] = 0
		return
	}
	m := (l + r) >> 1
	if x <= m {
		update(x, o<<1, l, m)
	} else {
		update(x, o<<1|1, m+1, r)
	}
	up(o)
}

func main() {
	stdin := bufio.NewReader(os.Stdin)
	var n int
	var now = 1
	var ans int64 = 0
	fmt.Fscan(stdin, &n)
	for i := 1; i <= n; i++ {
		fmt.Fscan(stdin, &a[i])
	}
	build(1, 1, n)
	for sum[1] > 0 {
		_, nxt, cnt := query(now, n, 1, 1, n)
		if nxt != INF && a[nxt] == minv[1] {
			_, _, cnt = query(now, nxt, 1, 1, n)
			ans += int64(cnt)
			update(nxt, 1, 1, n)
		} else {
			ans += int64(cnt)
			_, nxt, cnt = query(1, now, 1, 1, n)
			_, _, cnt = query(1, nxt, 1, 1, n)
			ans += int64(cnt)
			update(nxt, 1, 1, n)
		}
		now = nxt
	}
	fmt.Println(ans)
}

package main

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

const INF int = 10000000

var a [100005]int
var minv, pos, sum [300005]int

func up(o int) {
	sum[o] = sum[o<<1] + sum[o<<1|1]
	if minv[o<<1] <= minv[o<<1|1] {
		minv[o] = minv[o<<1]
		pos[o] = pos[o<<1]
	} else {
		minv[o] = minv[o<<1|1]
		pos[o] = pos[o<<1|1]
	}
}

func build(o, l, r int) {
	if l >= r {
		minv[o] = a[l]
		pos[o] = l
		sum[o] = 1
		return
	}
	m := (l + r) >> 1
	build(o<<1, l, m)
	build(o<<1|1, m+1, r)
	up(o)
}

func query(L, R, o, l, r int) (x, y, z int) {
	if L <= l && r <= R {
		return minv[o], pos[o], sum[o]
	}
	m := (l + r) >> 1
	x, y = INF, INF
	z = 0
	if L <= m {
		x1, y1, z1 := query(L, R, o<<1, l, m)
		if x > x1 {
		    x = x1
		    y = y1
		} else if x == x1 {
		    if y > y1 {
		        y = y1
		    }
		}
		z += z1
	}
	if m < R {
		x1, y1, z1 := query(L, R, o<<1|1, m+1, r)
		if x > x1 {
		    x = x1
		    y = y1
		} else if x == x1 {
		    if y > y1 {
		        y = y1
		    }
		}
		z += z1
	}
	return
}

func update(x, o, l, r int) {
	if l >= r {
		minv[o] = INF
		pos[o] =  INF
		sum[o] = 0
		return
	}
	m := (l + r) >> 1
	if x <= m {
		update(x, o<<1, l, m)
	} else {
		update(x, o<<1|1, m+1, r)
	}
	up(o)
}

func main() {
	stdin := bufio.NewReader(os.Stdin)
	stdout := bufio.NewWriter(os.Stdout)
	var n int
	var now = 1
	var ans int64 = 0
	fmt.Fscan(stdin, &n)
	for i := 1; i <= n; i++ {
		fmt.Fscan(stdin, &a[i])
	}
	build(1, 1, n)
	for sum[1] > 0 {
		_, nxt, cnt := query(now, n, 1, 1, n)
		if nxt != INF && a[nxt] == minv[1] {
			_, _, cnt = query(now, nxt, 1, 1, n)
			ans += int64(cnt)
			update(nxt, 1, 1, n)
		} else {
			ans += int64(cnt)
			_, nxt, cnt = query(1, now, 1, 1, n)
			_, _, cnt = query(1, nxt, 1, 1, n)
			ans += int64(cnt)
			update(nxt, 1, 1, n)
		}
		now = nxt
	}
	fmt.Fprintln(stdout, ans)
	stdout.Flush()
}

package main

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

const INF int = 10000000

var a [100005]int
var minv, pos, sum [300005]int

func up(o int) {
	sum[o] = sum[o<<1] + sum[o<<1|1]
	if minv[o<<1] <= minv[o<<1|1] {
		minv[o] = minv[o<<1]
		pos[o] = pos[o<<1]
	} else {
		minv[o] = minv[o<<1|1]
		pos[o] = pos[o<<1|1]
	}
}

func build(o, l, r int) {
	if l >= r {
		minv[o] = a[l]
		pos[o] = l
		sum[o] = 1
		return
	}
	m := (l + r) >> 1
	build(o<<1, l, m)
	build(o<<1|1, m+1, r)
	up(o)
}

func query(L, R, o, l, r int) (x, y, z int) {
	if L <= l && r <= R {
		return minv[o], pos[o], sum[o]
	}
	m := (l + r) >> 1
	x, y = INF, INF
	z = 0
	if L <= m {
		x1, y1, z1 := query(L, R, o<<1, l, m)
		if x > x1 {
		    x = x1
		    y = y1
		} else if x == x1 {
		    if y > y1 {
		        y = y1
		    }
		}
		z += z1
	}
	if m < R {
		x1, y1, z1 := query(L, R, o<<1|1, m+1, r)
		if x > x1 {
		    x = x1
		    y = y1
		} else if x == x1 {
		    if y > y1 {
		        y = y1
		    }
		}
		z += z1
	}
	return
}

func update(x, o, l, r int) {
	if l >= r {
		minv[o] = INF
		pos[o] =  INF
		sum[o] = 0
		return
	}
	m := (l + r) >> 1
	if x <= m {
		update(x, o<<1, l, m)
	} else {
		update(x, o<<1|1, m+1, r)
	}
	up(o)
}

func main() {
	stdin := bufio.NewReader(os.Stdin)
	var n int
	var now = 1
	var ans int64 = 0
	fmt.Fscan(stdin, &n)
	for i := 1; i <= n; i++ {
		fmt.Fscan(stdin, &a[i])
	}
	build(1, 1, n)
	for sum[1] > 0 {
		_, nxt, cnt := query(now, n, 1, 1, n)
		if nxt != INF && a[nxt] == minv[1] {
			_, _, cnt = query(now, nxt, 1, 1, n)
			ans += int64(cnt)
			update(nxt, 1, 1, n)
		} else {
			ans += int64(cnt)
			_, nxt, cnt = query(1, now, 1, 1, n)
			_, _, cnt = query(1, nxt, 1, 1, n)
			ans += int64(cnt)
			update(nxt, 1, 1, n)
		}
		now = nxt
	}
	fmt.Println(ans)
}

package main

import (
	"fmt"
)

const INF int = 10000000

var a [100005]int
var minv, pos, sum [300005]int

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

func up(o int) {
	sum[o] = sum[o<<1] + sum[o<<1|1]
	if minv[o<<1] <= minv[o<<1|1] {
		minv[o] = minv[o<<1]
		pos[o] = pos[o<<1]
	} else {
		minv[o] = minv[o<<1|1]
		pos[o] = pos[o<<1|1]
	}
}

func build(o, l, r int) {
	if l >= r {
		minv[o] = a[l]
		pos[o] = l
		sum[o] = 1
		return
	}
	m := (l + r) >> 1
	build(o<<1, l, m)
	build(o<<1|1, m+1, r)
	up(o)
}

func query(L, R, o, l, r int) (x, y int) {
	if L <= l && r <= R {
		return pos[o], sum[o]
	}
	m := (l + r) >> 1
	x = INF
	y = 0
	if L <= m {
		x1, y1 := query(L, R, o<<1, l, m)
		x = min(x, x1)
		y += y1
	}
	if m < R {
		x1, y1 := query(L, R, o<<1|1, m+1, r)
		x = min(x, x1)
		y += y1
	}
	return
}

func update(x, v, o, l, r int) {
	if l >= r {
		minv[o] = INF
		pos[o] =  INF
		sum[o] = 0
		return
	}
	m := (l + r) >> 1
	if x <= m {
		update(x, v, o<<1, l, m)
	} else {
		update(x, v, o<<1|1, m+1, r)
	}
	up(o)
}

func main() {
	var n int
	var now = 1
	var ans int64 = 0
	fmt.Scan(&n)
	for i := 1; i <= n; i++ {
		fmt.Scan(&a[i])
	}
	build(1, 1, n)
	for sum[1] > 0 {
		nxt, cnt := query(now, n, 1, 1, n)
		if nxt != INF && a[nxt] == minv[1] {
			_, cnt = query(now, nxt, 1, 1, n)
			ans += int64(cnt)
			update(nxt, INF, 1, 1, n)
		} else {
			ans += int64(cnt)
			nxt, cnt = query(1, now, 1, 1, n)
			_, cnt = query(1, nxt, 1, 1, n)
			ans += int64(cnt)
			update(nxt, INF, 1, 1, n)
		}
		//fmt.Println(ans, nxt, sum[1])
		now = nxt
	}
	fmt.Println(ans)
}

package main

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

const INF int = 10000000

var a [100005]int
var minv, pos, sum [300005]int

func up(o int) {
	sum[o] = sum[o<<1] + sum[o<<1|1]
	if minv[o<<1] <= minv[o<<1|1] {
		minv[o] = minv[o<<1]
		pos[o] = pos[o<<1]
	} else {
		minv[o] = minv[o<<1|1]
		pos[o] = pos[o<<1|1]
	}
}

func build(o, l, r int) {
	if l >= r {
		minv[o] = a[l]
		pos[o] = l
		sum[o] = 1
		return
	}
	m := (l + r) >> 1
	build(o<<1, l, m)
	build(o<<1|1, m+1, r)
	up(o)
}

func query(L, R, o, l, r int) (x, y, z int) {
	if L <= l && r <= R {
		return minv[o], pos[o], sum[o]
	}
	m := (l + r) >> 1
	x, y = INF, INF
	z = 0
	if L <= m {
		x1, y1, z1 := query(L, R, o<<1, l, m)
		if x > x1 {
		    x = x1
		    y = y1
		} else if x == x1 {
		    if y > y1 {
		        y = y1
		    }
		}
		z += z1
	}
	if m < R {
		x1, y1, z1 := query(L, R, o<<1|1, m+1, r)
		if x > x1 {
		    x = x1
		    y = y1
		} else if x == x1 {
		    if y > y1 {
		        y = y1
		    }
		}
		z += z1
	}
	return
}

func update(x, o, l, r int) {
	if l >= r {
		minv[o] = INF
		pos[o] =  INF
		sum[o] = 0
		return
	}
	m := (l + r) >> 1
	if x <= m {
		update(x, o<<1, l, m)
	} else {
		update(x, o<<1|1, m+1, r)
	}
	up(o)
}

func main() {
	stdin := bufio.NewReader(os.Stdin)
	stdout := bufio.NewWriter(os.Stdout)
	var n int
	var now = 1
	var ans int64 = 0
	fmt.Fscan(stdin, &n)
	for i := 1; i <= n; i++ {
		fmt.Fscan(stdin, &a[i])
	}
	build(1, 1, n)
	for sum[1] > 0 {
		_, nxt, cnt := query(now, n, 1, 1, n)
		if nxt != INF && a[nxt] == minv[1] {
			_, _, cnt = query(now, nxt, 1, 1, n)
			ans += int64(cnt)
			update(nxt, 1, 1, n)
		} else {
			ans += int64(cnt)
			_, nxt, cnt = query(1, now, 1, 1, n)
			_, _, cnt = query(1, nxt, 1, 1, n)
			ans += int64(cnt)
			update(nxt, 1, 1, n)
		}
		now = nxt
	}
	fmt.Fprintln(stdout, ans)
}


Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy: Each piece should contain at least l numbers. The difference between the maximal and the minimal number on the piece should be at most s.Please help Alexandra to find the minimal number of pieces meeting the condition above.

The first line contains three space-separated integers n, s, l (1 ≤ n ≤ 105, 0 ≤ s ≤ 109, 1 ≤ l ≤ 105). The second line contains n integers ai separated by spaces ( - 109 ≤ ai ≤ 109).

Output the minimal number of strip pieces. If there are no ways to split the strip, output -1.

NoteFor the first sample, we can split the strip into 3 pieces: [1, 3, 1], [2, 4], [1, 2].For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists.

package main

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

type minMaxQ struct {
	q, minDeq, maxDeq []int
}

func (q *minMaxQ) push(v int) {
	q.q = append(q.q, v)

	for {
		l := len(q.minDeq)
		if l == 0 || q.minDeq[l-1] <= v {
			break
		}
		q.minDeq = q.minDeq[:l-1]
	}
	q.minDeq = append(q.minDeq, v)

	for {
		l := len(q.maxDeq)
		if l == 0 || q.maxDeq[l-1] >= v {
			break
		}
		q.maxDeq = q.maxDeq[:l-1]
	}
	q.maxDeq = append(q.maxDeq, v)
}

func (q *minMaxQ) pop() {
	v := q.q[0]
	q.q = q.q[1:]
	if q.minDeq[0] == v {
		q.minDeq = q.minDeq[1:]
	}
	if q.maxDeq[0] == v {
		q.maxDeq = q.maxDeq[1:]
	}
}

func (q *minMaxQ) min() int {
	return q.minDeq[0]
}

func (q *minMaxQ) max() int {
	return q.maxDeq[0]
}

func (q *minMaxQ) length() int {
	return len(q.q)
}

func main() {
	in := bufio.NewReaderSize(os.Stdin, 2<<16)
	var n, s, l int
	fmt.Fscan(in, &n, &s, &l)
	a := make([]int, n)
	for i := range a {
		fmt.Fscan(in, &a[i])
	}

	maxLen := make([]int, n)
	q := new(minMaxQ)
	for i, a := range a {
		q.push(a)
		for q.max()-q.min() > s {
			q.pop()
		}
		maxLen[i] = q.length()
	}

	inf := 2 * n
	dp := make([]int, n+1)
	for i := 1; i <= n; i++ {
		dp[i] = inf
	}

	q = new(minMaxQ)
	for i := l; i <= n; i++ {
		q.push(dp[i-l])
		for q.length() > 0 && l+q.length()-1 > maxLen[i-1] {
			q.pop()
		}
		if q.length() == 0 {
			continue
		}
		dp[i] = 1 + q.min()
	}

	if dp[n] >= inf {
		fmt.Println(-1)
		return
	}
	fmt.Println(dp[n])
}


The Queen of England has n trees growing in a row in her garden. At that, the i-th (1 ≤ i ≤ n) tree from the left has height ai meters. Today the Queen decided to update the scenery of her garden. She wants the trees' heights to meet the condition: for all i (1 ≤ i < n), ai + 1 - ai = k, where k is the number the Queen chose.Unfortunately, the royal gardener is not a machine and he cannot fulfill the desire of the Queen instantly! In one minute, the gardener can either decrease the height of a tree to any positive integer height or increase the height of a tree to any positive integer height. How should the royal gardener act to fulfill a whim of Her Majesty in the minimum number of minutes?

The first line contains two space-separated integers: n, k (1 ≤ n, k ≤ 1000). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 1000) — the heights of the trees in the row.

In the first line print a single integer p — the minimum number of minutes the gardener needs. In the next p lines print the description of his actions.  If the gardener needs to increase the height of the j-th (1 ≤ j ≤ n) tree from the left by x (x ≥ 1) meters, then print in the corresponding line "+ j x". If the gardener needs to decrease the height of the j-th (1 ≤ j ≤ n) tree from the left by x (x ≥ 1) meters, print on the corresponding line "- j x". If there are multiple ways to make a row of trees beautiful in the minimum number of actions, you are allowed to print any of them.

package main

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

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

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

	n, k := nextInt(), nextInt()

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

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

	max := 0
	min := 0
	notCut := 0
	minHeight := 0

	for i:=1; i<len(a); i++ {
		minHeight = a[i] - k*(i-1)
		if minHeight < 1 || min == minHeight {
			continue
		}

		notCut = 0
		for j:=1; j<len(a); j++ {
			if a[j] - k*(j-1) == minHeight {
				notCut++
			}
		}

		if notCut > max {
			max = notCut
			min = minHeight
		}
	}

	println(n - max)

	for i:=1 ; i<len(a); i++ {
		n = a[i] - k*(i-1)

		if n < min {
			println("+", i, min-n)
		}

		if n > min {
			println("-", i, n-min)
		}
	}
}

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

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

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

func print(a ...interface{}) {
	fmt.Fprint(writer, a...)
}

package main

import (
    "fmt"
)

func main() {
    var n, k int
    fmt.Scanf("%d %d\n", &n, &k)
    var h = make([]int, n)
    for i := 0; i < n; i++ {
        fmt.Scanf("%d", &h[i])
    }
    var idx = -1
    var ans = n
    for i := 0; i < n; i++ {
        //fmt.Printf("%d %d\n", i, h[i])
        var now = h[i] - k*i
        //fmt.Printf("%d\n", now)
        if now <= 0 {
            continue
        }
        //fmt.Printf("%d\n", now)
        var cur_ans = 0
        for j := 0; j < n; j++ {
            if now+j*k != h[j] {
                cur_ans++
            }
        }
        if ans > cur_ans {
            ans = cur_ans
            idx = i
        }
    }
    fmt.Printf("%d\n", ans)
    for i := 0; i < n; i++ {
        var target = h[idx] - (idx-i)*k
        if target > h[i] {
            fmt.Printf("+ %d %d\n", i+1, target-h[i])
        } else if target < h[i] {
            fmt.Printf("- %d %d\n", i+1, h[i]-target)
        }
    }
}


Danny, the local Math Maniac, is fascinated by circles, Omkar's most recent creation. Help him solve this circle problem!You are given $$$n$$$ nonnegative integers $$$a_1, a_2, \dots, a_n$$$ arranged in a circle, where $$$n$$$ must be odd (ie. $$$n-1$$$ is divisible by $$$2$$$). Formally, for all $$$i$$$ such that $$$2 \leq i \leq n$$$, the elements $$$a_{i - 1}$$$ and $$$a_i$$$ are considered to be adjacent, and $$$a_n$$$ and $$$a_1$$$ are also considered to be adjacent. In one operation, you pick a number on the circle, replace it with the sum of the two elements adjacent to it, and then delete the two adjacent elements from the circle. This is repeated until only one number remains in the circle, which we call the circular value.Help Danny find the maximum possible circular value after some sequences of operations.

The first line contains one odd integer $$$n$$$ ($$$1 \leq n < 2 \cdot 10^5$$$, $$$n$$$ is odd)  — the initial size of the circle. The second line contains $$$n$$$ integers $$$a_{1},a_{2},\dots,a_{n}$$$ ($$$0 \leq a_{i} \leq 10^9$$$)  — the initial numbers in the circle.

Output the maximum possible circular value after applying some sequence of operations to the given circle.

NoteFor the first test case, here's how a circular value of $$$17$$$ is obtained:Pick the number at index $$$3$$$. The sum of adjacent elements equals $$$17$$$. Delete $$$7$$$ and $$$10$$$ from the circle and replace $$$2$$$ with $$$17$$$.Note that the answer may not fit in a $$$32$$$-bit integer.

package main

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

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

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

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

type priorityQueue [][2]int

func (pq priorityQueue) Len() int {
	return len(pq)
}

func (pq priorityQueue) Less(i, j int) bool {
	return pq[i][1] > pq[j][1]
}

func (pq priorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
}

func (pq *priorityQueue) Push(x interface{}) {
	*pq = append(*pq, x.([2]int))
}

func (pq *priorityQueue) Pop() (res interface{}) {
	res = (*pq)[len(*pq)-1]
	*pq = (*pq)[:len(*pq)-1]
	return res
}

var err error

func nextInt() (n int) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func nextLong() (n int64) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

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

func main() {
	out = bufio.NewWriterSize(os.Stdout, 8192)
	defer out.Flush()
	if false {
		file, err := os.Open("in")
		if err != nil {
			log.Fatal(err)
		}
		in = bufio.NewReaderSize(file, 8192)
	} else {
		in = bufio.NewReaderSize(os.Stdin, 8192)
	}

	n := nextInt()
	arr, pre, end := make([]int64, n), make([]int64, n+2), make([]int64, n+2)
	for i := 0; i < n; i++ {
		arr[i] = nextLong()
		pre[i+2] = pre[i] + arr[i]
	}
	for i := n - 1; i >= 0; i-- {
		end[i] = end[i+2] + arr[i]
	}

	var res int64 = 0
	for i := 0; i < n; i++ {
		res = Max(res, pre[i+1]+end[i])
	}
	printf("%d\n", res)
}

package main

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

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

	n := readNum(reader)
	A := readNNums(reader, n)

	fmt.Println(solve(n, A))
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func solve(n int, A []int) int64 {
	m := (n + 1) / 2
	var cur int64
	for j := 0; j < m; j++ {
		cur += int64(A[(j*2)%n])
	}
	var ans = cur

	for j := 0; j < n; j++ {
		cur -= int64(A[(j*2)%n])
		cur += int64(A[((j+m)*2)%n])
		ans = max(ans, cur)
	}

	return ans
}

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

package main

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

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

	n := io.NextInt()
	a := io.NextInts(n)
	p, s := make([]int64, n+2), make([]int64, n+2)
	for i, x := range a {
		p[i+2] = int64(x) + p[i]
	}
	for i := n - 1; i >= 0; i-- {
		s[i] = int64(a[i]) + s[i+2]
	}
	var ans int64
	for i := range a {
		if p[i+2]+s[i+1] > ans {
			ans = p[i+2] + s[i+1]
		}
	}
	io.Println(ans)
}

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

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

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

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

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

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1372D(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	var n int
	var sum, cur, ans int64
	Fscan(in, &n)
	a := make([]int64, n)
	for i := range a {
		Fscan(in, &a[i])
		sum += a[i]
	}
	for i := 0; i < n; i += 2 {
		cur += a[i]
	}
	for _, v := range a {
		if cur > ans {
			ans = cur
		}
		cur = sum - cur + v
	}
	Fprint(out, ans)
}

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


Alice has a birthday today, so she invited home her best friend Bob. Now Bob needs to find a way to commute to the Alice's home.In the city in which Alice and Bob live, the first metro line is being built. This metro line contains $$$n$$$ stations numbered from $$$1$$$ to $$$n$$$. Bob lives near the station with number $$$1$$$, while Alice lives near the station with number $$$s$$$. The metro line has two tracks. Trains on the first track go from the station $$$1$$$ to the station $$$n$$$ and trains on the second track go in reverse direction. Just after the train arrives to the end of its track, it goes to the depot immediately, so it is impossible to travel on it after that.Some stations are not yet open at all and some are only partially open — for each station and for each track it is known whether the station is closed for that track or not. If a station is closed for some track, all trains going in this track's direction pass the station without stopping on it.When the Bob got the information on opened and closed stations, he found that traveling by metro may be unexpectedly complicated. Help Bob determine whether he can travel to the Alice's home by metro or he should search for some other transport.

The first line contains two integers $$$n$$$ and $$$s$$$ ($$$2 \le s \le n \le 1000$$$) — the number of stations in the metro and the number of the station where Alice's home is located. Bob lives at station $$$1$$$. Next lines describe information about closed and open stations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$). If $$$a_i = 1$$$, then the $$$i$$$-th station is open on the first track (that is, in the direction of increasing station numbers). Otherwise the station is closed on the first track. The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$b_i = 0$$$ or $$$b_i = 1$$$). If $$$b_i = 1$$$, then the $$$i$$$-th station is open on the second track (that is, in the direction of decreasing station numbers). Otherwise the station is closed on the second track.

Print "YES" (quotes for clarity) if Bob will be able to commute to the Alice's home by metro and "NO" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower).

NoteIn the first example, all stations are opened, so Bob can simply travel to the station with number $$$3$$$.In the second example, Bob should travel to the station $$$5$$$ first, switch to the second track and travel to the station $$$4$$$ then.In the third example, Bob simply can't enter the train going in the direction of Alice's home.

package main

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

var reader *bufio.Reader = bufio.NewReader(os.Stdin)

func read_int_array(array_length int) []int {
    input_array := make([]int, array_length)
    for i := 0; i < array_length; i++ {
        fmt.Fscan(reader, &input_array[i])
    }
    return input_array
}

func main() {
    var n, s int
    fmt.Fscan(reader, &n)
    fmt.Fscanln(reader, &s)
    first_track := read_int_array(n)
    second_track := read_int_array(n)
    norm_s := s-1
    if first_track[0] == 0 {
        fmt.Print("NO")
        return
    }
    if first_track[norm_s] == 1 {
        fmt.Print("YES")
        return
    } else {
        if second_track[norm_s] == 1 {
            for i:=norm_s+1;i<n;i++ {
                if first_track[i]==1 && second_track[i]==1 {
                    fmt.Print("YES")
                    return
                }
            }
            fmt.Print("NO")
            return
        } else {
            fmt.Print("NO")
            return
        }
    }
}

package main

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

func solve() {
	n := readInt()
	s := readInt()
	g := make([][]int, 2 * n)
	for i := 0; i < 2 * n; i++ {
		g[i] = make([]int, 0)
	}
	a:=readIntArray(n)
	b:=readIntArray(n)

	prev := -1
	for i := 0; i < n; i++ {
		if a[i] == 1 {
			if prev != -1 {
				g[prev] = append(g[prev], i)
			}
			prev = i
		}
	}
	prev = -1
	for i := n - 1; i >= 0; i-- {
		if b[i] == 1 {
			if prev != -1 {
				g[prev + n] = append(g[prev + n], i + n)
			}
			prev = i
		}
	}
	for i := 0; i < n; i++ {
		if a[i] == 1 && b[i] == 1 {
			g[i] = append(g[i], i + n)
		}
	}
	vis := make([]bool, 2*n)
	dfs(g, 0, vis)
	if vis[0] && (vis[s-1] || vis[s-1+n]) {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}

func dfs(g [][]int, u int, vis []bool) {
	vis[u] = true
	for _, next := range g[u] {
		if !vis[next] {
			dfs(g, next, vis)
		}
	}
}

var scanner *bufio.Scanner

func main() {
	scanner = bufio.NewScanner(os.Stdin)
	const MaxTokenLength = 1024 * 1024
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)
	solve()
}

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

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

// IO

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

func readInt() int {
	val, _ := strconv.Atoi(readString())
	return val
}

func readInt64() int64 {
	v, _ := strconv.ParseInt(readString(), 10, 64)
	return v
}

func readIntArray(sz int) []int {
	a := make([]int, sz)
	for i := 0; i < sz; i++ {
		a[i] = readInt()
	}
	return a
}

func readInt64Array(n int) []int64 {
	res := make([]int64, n)
	for i := 0; i < n; i++ {
		res[i] = readInt64()
	}
	return res
}

package main

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

var n, s int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)

	fmt.Fscan(input, &n, &s)

	a := make([]int, n+5)
	b := make([]int, n+5)

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

	for i := 1; i <= n; i++ {
		fmt.Fscan(input, &b[i])
	}

	if a[s] == 0 && b[s] == 0 || a[1] == 0 {
		fmt.Println("NO")
		return
	}

	if a[s] == 1 {
		fmt.Println("YES")
		return
	} else {
		ok := 0
		for i := s + 1; i <= n; i++ {
			if a[i] == 1 && b[i] == 1 {
				ok = 1
				break
			}
		}

		if ok == 1 {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

package main

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

var n, s int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)

	fmt.Fscan(input, &n, &s)

	a := make([]bool, n+5)
	b := make([]bool, n+5)

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

	for i := 1; i <= n; i++ {
		fmt.Fscan(input, &b[i])
	}

	if a[s] == false && b[s] == false || a[1] == false {
		fmt.Println("NO")
		return
	}

	if a[s] == true {
		fmt.Println("YES")
		return
	} else {
		ok := false
		for i := s + 1; i <= n; i++ {
			if a[i] == true && b[i] == true {
				ok = true
				break
			}
		}

		if ok == true {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

// A<->B X円
// B<->C Y円

package main

import (
	"fmt"
)

func main() {
	var (
		N, S int
	)
    ans := "NO"
	fmt.Scan(&N, &S)

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

    var max_N int
    for max_N = N; 0 < max_N; max_N-- {
        if A[max_N-1] == 1 {
            break
        }
    }

    if A[0] == 0 && S != 1 {
	 	ans = "NO"
    } else {
        if A[S-1] == 1 {
            ans = "YES"
        } else {
            var max_can_turn int
            for i:=0; i < N; i++ {
                if A[i] == 1 && B[i] == 1 {
                    max_can_turn = i
                }
            }
            for i:=max_can_turn; 0 <= i; i-- {
                if B[i] == 1 {
                    if i == S-1 {
                        ans = "YES"
                        break
                    }
                }
            }
        }
    }

    // else if max_N <= S {
    //     ans = "NO"
	// } else if A[S-1] == 0 && B[S-1] == 0 {
	// 	ans = "NO"
	// } else {
	// 	ans = "YES"
	// }
	fmt.Println(ans)
}

package main

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

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

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

func main() {
	defer writer.Flush()
	n, s := 0, 0

	scanf("%d %d\n", &n, &s)

	s--
	a := make([]int, n)
	b := make([]int, n)
	f := make([]bool, n)
	for i := 0; i < n; i++ {
		scanf("%d", &a[i])
		f[i] = false
	}
	scanf("\n")
	for i := 0; i < n; i++ {
		scanf("%d", &b[i])
		if b[i] == 1 && a[i] == 1 {
			f[i] = true
		}
	}

	if a[0] == 0 {
		printf("NO")
		return
	}

	if a[s] == 1 {
		printf("YES")
		return
	}

	for i := s + 1; i < n; i++ {
		if f[i] && b[s] == 1 {
			printf("YES")
			return
		}
	}

	printf("NO")

}

package main

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

var scanner = bufio.NewScanner(os.Stdin)

func init() {
	scanner.Split(bufio.ScanWords)
}

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

func scanInt64() int64 {
	scanner.Scan()
	v, _ := strconv.ParseInt(scanner.Text(), 10, 64)
	return v
}

func scanInt() int {
	scanner.Scan()
	v, _ := strconv.Atoi(scanner.Text())
	return v
}

func scanInts(n int) []int {
	l := make([]int, n)
	for i := 0; i < n; i++ {
		scanner.Scan()
		l[i], _ = strconv.Atoi(scanner.Text())
	}

	return l
}

func scanInts64(n int64) []int64 {
	l := make([]int64, n)
	for i := int64(0); i < n; i++ {
		scanner.Scan()
		l[i], _ = strconv.ParseInt(scanner.Text(), 10, 64)
	}

	return l
}

func scanBool() bool {
	scanner.Scan()
	v, _ := strconv.ParseInt(scanner.Text(), 10, 64)
	return v == 1
}

func scanBools(n int64) []bool {
	l := make([]bool, n)
	for i := int64(0); i < n; i++ {
		scanner.Scan()
		v, _ := strconv.ParseInt(scanner.Text(), 10, 64)
		l[i] = v == 1
	}

	return l
}

func main() {
	n, s := scanInt(), scanInt()
	OF, OB := scanBools(int64(n)), scanBools(int64(n))

	if !OF[0] {
		fmt.Println("NO")
		return
	}

	if OF[s-1] {
		fmt.Println("YES")
		return
	}

	if !OF[s-1] && !OB[s-1] {
		fmt.Println("NO")
		return
	}

	for i := s - 1; i < n; i++ {
		if OF[i] && OB[i] {
			fmt.Println("YES")
			return
		}
	}

	fmt.Println("NO")
}

func abs(a int64) int64 {
	if a >= 0 {
		return a
	}

	return -a
}

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

	return b
}

// A<->B X円
// B<->C Y円

package main

import (
	"fmt"
)

func main() {
	var (
		N, S int
		ans  string
	)
	fmt.Scan(&N, &S)

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

    var max_N int
    for max_N = N-1; 0 <= max_N; max_N-- {
        if A[max_N] == 1 {
            break
        }
    }

	if A[0] == 0 && S != 1 {
		ans = "NO"
    } else if max_N < S {
        ans = "NO"
	} else if A[S-1] == 0 && B[S-1] == 0 {
		ans = "NO"
	} else {
		ans = "YES"
	}
	fmt.Println(ans)
}

// A<->B X円
// B<->C Y円

package main

import (
	"fmt"
)

func main() {
	var (
		N, S int
	)
    ans := "NO"
	fmt.Scan(&N, &S)

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

    var max_N int
    for max_N = N; 0 < max_N; max_N-- {
        if A[max_N-1] == 1 {
            break
        }
    }

    if A[0] == 0 && S != 1 {
	 	ans = "NO"
    } else {

        var turn int
        for i:=0; i < N; i++ {
            if A[i] == 1 {
                if i == S-1 {
                    ans = "YES"
                    break
                } else {
                    turn = i
                }
            }
        }
        for i:=turn; 0 <= i; i-- {
            if B[i] == 1 {
                if i == S-1 {
                    ans = "YES"
                    break
                }
            }
        }
    }

    // else if max_N <= S {
    //     ans = "NO"
	// } else if A[S-1] == 0 && B[S-1] == 0 {
	// 	ans = "NO"
	// } else {
	// 	ans = "YES"
	// }
	fmt.Println(ans)
}

// A<->B X円
// B<->C Y円

package main

import (
	"fmt"
)

func main() {
	var (
		N, S int
		ans  string
	)
	fmt.Scan(&N, &S)

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

    var max_N int
    for max_N = N; 0 < max_N; max_N-- {
        if A[max_N-1] == 1 {
            break
        }
    }

	if A[0] == 0 && S != 1 {
		ans = "NO"
    } else if max_N <= S {
        ans = "NO"
	} else if A[S-1] == 0 && B[S-1] == 0 {
		ans = "NO"
	} else {
		ans = "YES"
	}
	fmt.Println(ans)
}

// A<->B X円
// B<->C Y円

package main

import (
	"fmt"
)

func main() {
	var (
		N, S int
		ans  string
	)
	fmt.Scan(&N, &S)

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

	if A[0] == 0 && S != 1 {
		ans = "NO"
	} else if A[S-1] == 0 && B[S-1] == 0 {
		ans = "NO"
	} else {
		ans = "YES"
	}
	fmt.Println(ans)
}

package main

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

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

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

func main() {
	defer writer.Flush()
	n, s := 0, 0

	scanf("%d %d\n", &n, &s)
	s--
	a := make([]int, n)
	b := make([]int, n)
	f := make([]bool, n)
	for i := 0; i < n; i++ {
		scanf("%d", &a[i])
	}

	for i := n - 1; i >= 0; i-- {
		scanf("%d", &b[i])
		if b[i] == 1 && a[i] == 1 {
			f[i] = true
		}
	}

	if a[0] == 0 {
		printf("NO")
		return
	}

	if a[s] == 1 {
		printf("YES")
		return
	}

	for i := s + 1; i < n; i++ {
		if f[i] && b[s] == 1 {
			printf("YES")
			return
		}
	}

	printf("NO")

}

package main

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

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

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

func main() {
	defer writer.Flush()
	n, s := 0, 0

	scanf("%d %d\n", &n, &s)
	s--
	a := make([]int, n)
	b := make([]int, n)
	f := make([]bool, n)
	for i := 0; i < n; i++ {
		scanf("%d", &a[i])
	}

	for i := 0; i < n; i++ {
		scanf("%d", &b[i])
		if b[i] == 1 && a[i] == 1 {
			f[i] = true
		}
	}

	if a[0] == 0 {
		printf("NO")
		return
	}

	if a[s] == 1 {
		printf("YES")
		return
	}

	for i := s + 1; i < n; i++ {
		if f[i] && b[s] == 1 {
			printf("YES")
			return
		}
	}

	printf("NO")

}


Once upon a time in the Kingdom of Far Far Away lived Sam the Farmer. Sam had a cow named Dawn and he was deeply attached to her. Sam would spend the whole summer stocking hay to feed Dawn in winter. Sam scythed hay and put it into haystack. As Sam was a bright farmer, he tried to make the process of storing hay simpler and more convenient to use. He collected the hay into cubical hay blocks of the same size. Then he stored the blocks in his barn. After a summer spent in hard toil Sam stored A·B·C hay blocks and stored them in a barn as a rectangular parallelepiped A layers high. Each layer had B rows and each row had C blocks.At the end of the autumn Sam came into the barn to admire one more time the hay he'd been stacking during this hard summer. Unfortunately, Sam was horrified to see that the hay blocks had been carelessly scattered around the barn. The place was a complete mess. As it turned out, thieves had sneaked into the barn. They completely dissembled and took away a layer of blocks from the parallelepiped's front, back, top and sides. As a result, the barn only had a parallelepiped containing (A - 1) × (B - 2) × (C - 2) hay blocks. To hide the evidence of the crime, the thieves had dissembled the parallelepiped into single 1 × 1 × 1 blocks and scattered them around the barn. After the theft Sam counted n hay blocks in the barn but he forgot numbers A, B и C.Given number n, find the minimally possible and maximally possible number of stolen hay blocks.

The only line contains integer n from the problem's statement (1 ≤ n ≤ 109).

Print space-separated minimum and maximum number of hay blocks that could have been stolen by the thieves. Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.

NoteLet's consider the first sample test. If initially Sam has a parallelepiped consisting of 32 = 2 × 4 × 4 hay blocks in his barn, then after the theft the barn has 4 = (2 - 1) × (4 - 2) × (4 - 2) hay blocks left. Thus, the thieves could have stolen 32 - 4 = 28 hay blocks. If Sam initially had a parallelepiped consisting of 45 = 5 × 3 × 3 hay blocks in his barn, then after the theft the barn has 4 = (5 - 1) × (3 - 2) × (3 - 2) hay blocks left. Thus, the thieves could have stolen 45 - 4 = 41 hay blocks. No other variants of the blocks' initial arrangement (that leave Sam with exactly 4 blocks after the theft) can permit the thieves to steal less than 28 or more than 41 blocks.

// http://codeforces.com/contest/142/problem/A
package main

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

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
}

func lost(a, b, c int64) int64 {
	return (a + 1)*(b + 2)*(c + 2) - a*b*c
}

func main () {
	var n int64

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)

	fmt.Fscanln(input, &n)

	mx := int64(0)
	mn := int64(math.MaxInt64)

	for a := int64(1); a * a * a <= n; a++ {
		if n % a == 0 {
			for b := a; b * b <= n / a; b++ {
				if n / a % b == 0 {
					c := n / a / b

					l := lost(a, b, c)
					mx = max(mx, l)
					mn = min(mn, l)

					l = lost(b, a, c)
					mx = max(mx, l)
					mn = min(mn, l)

					l = lost(c, a, b)
					mx = max(mx, l)
					mn = min(mn, l)

				}
			}
		}
	}

	fmt.Println(mn, mx)
}

// http://codeforces.com/contest/142/problem/A
package main

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

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
}

func lost(a, b, c int64) int64 {
	return (a + 1)*(b + 2)*(c + 2) - a*b*c
}

func main () {
	var n int64

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)

	fmt.Fscanln(input, &n)

	mx := int64(0)
	mn := int64(math.MaxInt64)

	for a := int64(1); a * a * a <= n; a++ {
		if n % a == 0 {
			for b := a; b * b <= n / a; b++ {
				if (n / a) % b == 0 {
					c := n / a / b

					l := lost(a, b, c)
					mx = max(mx, l)
					mn = min(mn, l)

					l = lost(b, a, c)
					mx = max(mx, l)
					mn = min(mn, l)

					l = lost(c, a, b)
					mx = max(mx, l)
					mn = min(mn, l)

				}
			}
		}
	}

	fmt.Println(mn, mx)
}

// http://codeforces.com/contest/142/problem/A
package main

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

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
}

func lost(a, b, c int64) int64 {
	return (a + 1)*(b + 2)*(c + 2) - a*b*c
}

func main () {
	var n int64

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)

	fmt.Fscanln(input, &n)

	mx := int64(0)
	mn := int64(math.MaxInt64)

	for a := int64(1); a * a * a < n; a++ {
		if n % a == 0 {
			for b := a; b * b <= n / a; b++ {
				if (n / a) % b == 0 {
					c := n / a / b

					l := lost(a, b, c)
					mx = max(mx, l)
					mn = min(mn, l)

					l = lost(b, a, c)
					mx = max(mx, l)
					mn = min(mn, l)

					l = lost(c, a, b)
					mx = max(mx, l)
					mn = min(mn, l)

				}
			}
		}
	}

	fmt.Println(mn, mx)
}


Polycarp likes to play with numbers. He takes some integer number $$$x$$$, writes it down on the board, and then performs with it $$$n - 1$$$ operations of the two kinds:   divide the number $$$x$$$ by $$$3$$$ ($$$x$$$ must be divisible by $$$3$$$);  multiply the number $$$x$$$ by $$$2$$$. After each operation, Polycarp writes down the result on the board and replaces $$$x$$$ by the result. So there will be $$$n$$$ numbers on the board after all.You are given a sequence of length $$$n$$$ — the numbers that Polycarp wrote down. This sequence is given in arbitrary order, i.e. the order of the sequence can mismatch the order of the numbers written on the board.Your problem is to rearrange (reorder) elements of this sequence in such a way that it can match possible Polycarp's game in the order of the numbers written on the board. I.e. each next number will be exactly two times of the previous number or exactly one third of previous number.It is guaranteed that the answer exists.

The first line of the input contatins an integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the number of the elements in the sequence. The second line of the input contains $$$n$$$ integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 3 \cdot 10^{18}$$$) — rearranged (reordered) sequence that Polycarp can wrote down on the board.

Print $$$n$$$ integer numbers — rearranged (reordered) input sequence that can be the sequence that Polycarp could write down on the board. It is guaranteed that the answer exists.

NoteIn the first example the given sequence can be rearranged in the following way: $$$[9, 3, 6, 12, 4, 8]$$$. It can match possible Polycarp's game which started with $$$x = 9$$$.

package main

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

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

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

type delimeters struct {
	twos   int
	threes int
}

type sortDelimeters []delimeters

func (arr sortDelimeters) Len() int {
	return len(arr)
}

func (arr sortDelimeters) Swap(i, j int) {
	arr[i], arr[j] = arr[j], arr[i]
}

func (arr sortDelimeters) Less(i, j int) bool {
	return arr[i].twos <= arr[j].twos && arr[i].threes >= arr[j].threes
}

func getDelimeters(n uint64) delimeters {
	r := delimeters{0, 0}
	for {
		if n%2 == 0 {
			r.twos++
			n /= 2
		} else if n%3 == 0 {
			r.threes++
			n /= 3
		} else {
			break
		}
	}
	return r
}

func insert(num uint64, i int, array *[]uint64) {
	*array = append(*array, 0)
	buffer := (*array)[i]
	(*array)[i] = num
	// printf("buffer: %v, a[i]: %v\n", buffer, (*array)[i])
	for f := i + 1; f < len((*array)); f++ {
		printf("f == %v\n", f)
		buffer, (*array)[f] = (*array)[f], buffer
	}
	// printf("array: %v\n", *array)
}

func main() {
	//STDOUT MUST BE FLUSHED MANUALLY
	defer writer.Flush()

	var n int
	scanf("%d\n", &n)
	arr := make([]uint64, n)
	sortedArr := make([]delimeters, n)
	answerArr := make([]uint64, n)
	delCounter := make(map[delimeters]uint64)

	for i := range arr {
		scanf("%d", &arr[i])
		del := getDelimeters(arr[i])
		delCounter[del] = arr[i]
		sortedArr[i] = del
	}

	// printf("sortedArr: %v\n", sortedArr)

	sort.Sort(sortDelimeters(sortedArr))

	// printf("sortedArr: %v\n", sortedArr)

	for i, val := range sortedArr {
		answerArr[i] = delCounter[val]
	}

	for _, val := range answerArr {
		printf("%v ", val)
	}

	printf("\n")

	// printf("%v\n", answerArr)
	// printf("%v\n", delCounter)

	// var a, b int
	// scanf("%d %d", &a, &b)
	// printf("%d\n", a+b)
}

package main

import (
	. "fmt"
	"sort"
)

// github.com/EndlessCheng/codeforces-go
func main() {
	g,n,v := [64][]int64{},0,int64(0)
	for Scan(&n); n > 0; n-- {
		Scan(&v)
		c := 0
		for w := v; w&1 == 0; w >>= 1 {
			c++
		}
		g[c] = append(g[c], v)
	}
	for _, a := range g {
		sort.Slice(a, func(i, j int) bool { return a[i] > a[j] })
		for _, v := range a {
			Print(v, " ")
		}
	}
}

package main

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

func Init() {
}

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

	F := make(map[int64]int)
	for _, v := range A {
		F[v]++
	}

	arr := make([]int64, N)
	for _, v := range A {
		if attempt(F, arr, v, 0) {
			break
		}
	}
	for _, v := range arr {
		io.Printf("%d ", v)
	}
	io.Println()
}

func attempt(F map[int64]int, sofar []int64, what int64, idx int) bool {
	if idx >= len(sofar) {
		return true
	}

	if F[what] <= 0 {
		return false
	}

	sofar[idx] = what
	F[what]--

	if attempt(F, sofar, what << 1, idx + 1) {
		return true
	}

	if what % 3 == 0 && attempt(F, sofar, what / 3, idx + 1) {
		return true
	}

	F[what]++
	return false
}

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"
	"bytes"
	"fmt"
	"os"
)

func Init() {
}

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

	F := make(map[int64]int)
	for _, v := range A {
		F[v]++
	}

	arr := make([]int64, N)
	good := false
	for _, v := range A {
		if attempt(F, arr, v, 0) {
			good = true
			break
		}
	}
	if !good {
		fmt.Println("WTF THIS FAILED?")
	}
	for i := 1; i < N; i++ {
		if arr[i] != arr[i - 1] * 2 && arr[i - 1] != arr[i] * 3 {
			fmt.Printf("WTF: %d, [%d %d]\n", i, arr[i - 1], arr[i])
		}
	}
	for _, v := range arr {
		io.Printf("%d ", v)
	}
	io.Println()
}

func attempt(F map[int64]int, sofar []int64, what int64, idx int) bool {
	if idx >= len(sofar) {
		return true
	}

	if F[what] <= 0 {
		return false
	}

	sofar[idx] = what
	F[what]--

	if attempt(F, sofar, what << 1, idx + 1) {
		return true
	}

	if what % 3 == 0 && attempt(F, sofar, what / 3, idx + 1) {
		return true
	}

	F[what]++
	return false
}

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"
	"bytes"
	"fmt"
	"os"
)

func Init() {
}

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

	F := make(map[int64]int)
	for _, v := range A {
		F[v]++
	}

	arr := make([]int64, N)
	for _, v := range A {
		if attempt(F, arr, v, 0) {
			break
		}
	}
	for i := 1; i < N; i++ {
		if arr[i] != arr[i - 1] * 2 && arr[i - 1] != arr[i] * 3 {
			fmt.Printf("WTF: %d, [%d %d]\n", i, arr[i - 1], arr[i])
		}
	}
	for _, v := range arr {
		io.Printf("%d ", v)
	}
	io.Println()
}

func attempt(F map[int64]int, sofar []int64, what int64, idx int) bool {
	if idx >= len(sofar) {
		return true
	}

	sofar[idx] = what

	mul2 := what << 1
	if F[mul2] > 0 {
		F[mul2]--
		if attempt(F, sofar, mul2, idx + 1) {
			return true
		}
		F[mul2]++
	}

	div3 := what / 3
	if what % 3 == 0 && F[div3] > 0 {
		F[div3]--
		if attempt(F, sofar, div3, idx + 1) {
			return true
		}
		F[div3]++
	}

	return false
}

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"
	"bytes"
	"fmt"
	"os"
)

func Init() {
}

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

	F := make(map[int64]int)
	for _, v := range A {
		F[v]++
	}

	arr := make([]int64, N)
	for _, v := range A {
		if attempt(F, arr, v, 0) {
			break
		}
	}
	for _, v := range arr {
		io.Printf("%d ", v)
	}
	io.Println()
}

func attempt(F map[int64]int, sofar []int64, what int64, idx int) bool {
	if idx >= len(sofar) {
		return true
	}

	sofar[idx] = what

	mul2 := what << 1
	if F[mul2] > 0 {
		F[mul2]--
		if attempt(F, sofar, mul2, idx + 1) {
			return true
		}
		F[mul2]++
	}

	div3 := what / 3
	if what % 3 == 0 && F[div3] > 0 {
		F[div3]--
		if attempt(F, sofar, div3, idx + 1) {
			return true
		}
		F[div3]++
	}

	return false
}

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


The Little Elephant loves playing with arrays. He has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai. Additionally the Little Elephant has m queries to the array, each query is characterised by a pair of integers lj and rj (1 ≤ lj ≤ rj ≤ n). For each query lj, rj the Little Elephant has to count, how many numbers x exist, such that number x occurs exactly x times among numbers alj, alj + 1, ..., arj.Help the Little Elephant to count the answers to all queries.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 105) — the size of array a and the number of queries to it. The next line contains n space-separated positive integers a1, a2, ..., an (1 ≤ ai ≤ 109). Next m lines contain descriptions of queries, one per line. The j-th of these lines contains the description of the j-th query as two space-separated integers lj and rj (1 ≤ lj ≤ rj ≤ n).

In m lines print m integers — the answers to the queries. The j-th line should contain the answer to the j-th query.

package main

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

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

	var n, q int
	Fscan(in, &n, &q)
	a := make([]int, n+1)
	for i := 1; i <= n; i++ {
		Fscan(in, &a[i])
	}
	qs := make([][4]int, q)
	blockSize := int(math.Round(math.Sqrt(float64(q))))
	for i := range qs {
		var ql, qr int
		Fscan(in, &ql, &qr)
		qs[i] = [4]int{ql / blockSize, qr + 1, ql, i}
	}
	sort.Slice(qs, func(i, j int) bool {
		for k := range qs[i] {
			if qs[i][k] != qs[j][k] {
				return qs[i][k] < qs[j][k]
			}
		}
		return true
	})

	cnt := make([]int, n+1)
	nowCnt := 0
	update := func(val, delta int) {
		if val > n {
			return
		}
		if cnt[val] == val {
			nowCnt--
		}
		cnt[val] += delta
		if cnt[val] == val {
			nowCnt++
		}
	}
	ans := make([]int, q)
	l, r := 1, 1
	for _, tuple := range qs {
		ql, qr, i := tuple[2], tuple[1], tuple[3]
		for ; l < ql; l++ {
			update(a[l], -1)
		}
		for ; r < qr; r++ {
			update(a[r], 1)
		}
		for l > ql {
			l--
			update(a[l], 1)
		}
		for r > qr {
			r--
			update(a[r], -1)
		}
		ans[i] = nowCnt
	}
	for _, v := range ans {
		Fprintln(out, v)
	}
}

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

package main

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

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

	var n, q int
	Fscan(in, &n, &q)
	a := make([]int, n+1)
	for i := 1; i <= n; i++ {
		Fscan(in, &a[i])
	}
	qs := make([][4]int, q)
	blockSize := int(math.Round(math.Sqrt(float64(q))))
	for i := range qs {
		var ql, qr int
		Fscan(in, &ql, &qr)
		qs[i] = [4]int{ql / blockSize, qr, ql, i}
	}
	sort.Slice(qs, func(i, j int) bool {
		for k := range qs[i] {
			if qs[i][k] != qs[j][k] {
				return qs[i][k] < qs[j][k]
			}
		}
		return true
	})

	cnt := make([]int, n+1)
	nowCnt := 0
	update := func(val, delta int) {
		if val > n {
			return
		}
		if cnt[val] == val {
			nowCnt--
		}
		cnt[val] += delta
		if cnt[val] == val {
			nowCnt++
		}
	}
	ans := make([]int, q)
	l, r := 1, 1
	for _, tuple := range qs {
		ql, qr, i := tuple[2], tuple[1], tuple[3]
		for ; l < ql; l++ {
			update(a[l], -1)
		}
		for ; r <= qr; r++ {
			update(a[r], 1)
		}
		for l > ql {
			l--
			update(a[l], 1)
		}
		for r > qr+1 {
			r--
			update(a[r], -1)
		}
		ans[i] = nowCnt
	}
	for _, v := range ans {
		Fprintln(out, v)
	}
}

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

package main

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

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

	var n, q int
	Fscan(in, &n, &q)
	a := make([]int, n+1)
	for i := 1; i <= n; i++ {
		Fscan(in, &a[i])
	}
	qs := make([][4]int, q)
	blockSize := int(math.Round(math.Sqrt(float64(n))))
	for i := range qs {
		var ql, qr int
		Fscan(in, &ql, &qr)
		qs[i] = [4]int{ql / blockSize, qr + 1, ql, i}
	}
	sort.Slice(qs, func(i, j int) bool {
		for k := range qs[i] {
			if qs[i][k] != qs[j][k] {
				return qs[i][k] < qs[j][k]
			}
		}
		return true
	})

	cnt := make([]int, n+1)
	nowCnt := 0
	update := func(val, delta int) {
		if val > n {
			return
		}
		if cnt[val] == val {
			nowCnt--
		}
		cnt[val] += delta
		if cnt[val] == val {
			nowCnt++
		}
	}
	ans := make([]int, q)
	l, r := 1, 1
	for _, tuple := range qs {
		ql, qr, i := tuple[2], tuple[1], tuple[3]
		for ; l < ql; l++ {
			update(a[l], -1)
		}
		for ; r < qr; r++ {
			update(a[r], 1)
		}
		for l > ql {
			l--
			update(a[l], 1)
		}
		for r > qr {
			r--
			update(a[r], -1)
		}
		ans[i] = nowCnt
	}
	for _, v := range ans {
		Fprintln(out, v)
	}
}

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


You have $$$n$$$ sticks of the given lengths.Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose such sticks.Let $$$S$$$ be the area of the rectangle and $$$P$$$ be the perimeter of the rectangle. The chosen rectangle should have the value $$$\frac{P^2}{S}$$$ minimal possible. The value is taken without any rounding.If there are multiple answers, print any of them.Each testcase contains several lists of sticks, for each of them you are required to solve the problem separately.

The first line contains a single integer $$$T$$$ ($$$T \ge 1$$$) — the number of lists of sticks in the testcase. Then $$$2T$$$ lines follow — lines $$$(2i - 1)$$$ and $$$2i$$$ of them describe the $$$i$$$-th list. The first line of the pair contains a single integer $$$n$$$ ($$$4 \le n \le 10^6$$$) — the number of sticks in the $$$i$$$-th list. The second line of the pair contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_j \le 10^4$$$) — lengths of the sticks in the $$$i$$$-th list. It is guaranteed that for each list there exists a way to choose four sticks so that they form a rectangle. The total number of sticks in all $$$T$$$ lists doesn't exceed $$$10^6$$$ in each testcase.

Print $$$T$$$ lines. The $$$i$$$-th line should contain the answer to the $$$i$$$-th list of the input. That is the lengths of the four sticks you choose from the $$$i$$$-th list, so that they form a rectangle and the value $$$\frac{P^2}{S}$$$ of this rectangle is minimal possible. You can print these four lengths in arbitrary order. If there are multiple answers, print any of them.

NoteThere is only one way to choose four sticks in the first list, they form a rectangle with sides $$$2$$$ and $$$7$$$, its area is $$$2 \cdot 7 = 14$$$, perimeter is $$$2(2 + 7) = 18$$$. $$$\frac{18^2}{14} \approx 23.143$$$.The second list contains subsets of four sticks that can form rectangles with sides $$$(1, 2)$$$, $$$(2, 8)$$$ and $$$(1, 8)$$$. Their values are $$$\frac{6^2}{2} = 18$$$, $$$\frac{20^2}{16} = 25$$$ and $$$\frac{18^2}{8} = 40.5$$$, respectively. The minimal one of them is the rectangle $$$(1, 2)$$$.You can choose any four of the $$$5$$$ given sticks from the third list, they will form a square with side $$$5$$$, which is still a rectangle with sides $$$(5, 5)$$$.

package main

import."fmt"
import"bufio"
import"os"
import."sort"

func main(){
	var t int
	Scan(&t)
	in:=bufio.NewReader(os.Stdin)
	out:=bufio.NewWriter(os.Stdout)
	defer out.Flush()
	for i:=0;i<t;i++{
		var n int
		Fscan(in,&n)
		if n==4{
			var num1,num2,num3,num5 int
			Fscan(in,&num1,&num2,&num3,&num5)
			Fprintln(out,num1,num2,num3,num5)
			continue
		}
		m:=map[int]int{}
		for j:=0;j<n;j++{
			var num int
			Fscan(in,&num)
			_,ok:=m[num]
			if ok{
				m[num]++
			}else{
				m[num]=1
			}
		}
		a:=[]int{}
		isFound:=false
		for k,v:=range m{
			if v>=4{
				Fprintln(out,k,k,k,k)
				isFound=true
				break
			}
			if v>=2{
				a=append(a,k)
			}
		}
		if isFound{
			continue
		}
		Ints(a)
		len:=len(a)-1
		pos:=-1
		min:=100000.0
		for j:=0;j<len;j++{
			p:=(a[j]+a[j+1])<<1
			s:=a[j]*a[j+1]
			res:=float64(p*p)/float64(s)
			if min>res{
				min=res
				pos=j
			}
		}
		Fprintln(out,a[pos],a[pos],a[pos+1],a[pos+1])
	}
}

package main

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

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)

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

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

		x, y, prev, distP2, distS := int64(0), int64(0), int64(0), int64(math.MaxInt32), int64(1)

		for i := 0; i < n - 1; i++ {
			if arr[i] == arr[i + 1] {
				if prev != 0 {
					p := 2 * arr[i] + 2 * prev
					s := arr[i] * prev
					if distP2 * s > p * p * distS {
						distP2 = p * p
						distS = s
						x, y = prev, arr[i]
					}
				}
				prev = arr[i]
				i++
			}
		}

		fmt.Fprintln(out, x, x, y, y)

	}

}

package main

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

var scanner * bufio.Scanner

func next_int()(result int64){
  if !scanner.Scan() {
    panic("Unable to read next integer. Input has no data remain")
  }
  res, err := strconv.ParseInt(scanner.Text(), 10, 32)
  if err != nil {
    panic(err)
  }
  return res
}

func next_str()(result string){
  if !scanner.Scan() {
    panic("Unable to read next token. Input has no data remain")
  }
  return scanner.Text()
}

func main() {

  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)

  T := int(next_int())
  for test := 1 ; test <= T; test++ {
    n := int(next_int())
    sticks := make([] int, n, n)
    for j := 0; j < n; j++ {
      sticks[j] = int(next_int())
    }

    sort.Slice(sticks, func(i, j int) bool { return sticks[i] < sticks[j] })
    var min_ratio float64 = 1e+30
    var side_a, side_b int = 0, 0
    for j := 0; j + 1 < n; {
      if sticks[j] == sticks[j + 1] {
        var k int = j + 2
        for k < n && sticks[k] == sticks[j] {
            k++;
        }
        if (k - j >= 4) {
          min_ratio = 16
          side_a = sticks[j]
          side_b = sticks[j]
          break
        }

        for (k+1) < n && sticks[k] != sticks[k+1] {
          k++;
        }

        if ((k+1 < n) && (sticks[k] == sticks[k+1])) {
          p := float64(sticks[j]*2 + sticks[k]*2)
          ratio := (p * p) / float64(sticks[j]*sticks[k])
          if ratio < min_ratio {
            min_ratio = ratio
            side_a = sticks[j]
            side_b = sticks[k]
          }
        }
        j = k
      } else {
        j++;
      }
    }
    fmt.Printf("%v %v %v %v\n", side_a, side_a, side_b, side_b)
  }
}

package main

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

var scanner * bufio.Scanner

func next_int()(result int64){
  if !scanner.Scan() {
    panic("Unable to read next integer. Input has no data remain")
  }
  res, err := strconv.ParseInt(scanner.Text(), 10, 32)
  if err != nil {
    panic(err)
  }
  return res
}

func next_str()(result string){
  if !scanner.Scan() {
    panic("Unable to read next token. Input has no data remain")
  }
  return scanner.Text()
}

func main() {

  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)

  T := int(next_int())
  for test := 1 ; test <= T; test++ {
    n := int(next_int())
    sticks := make([] int, n, n)
    for j := 0; j < n; j++ {
      sticks[j] = int(next_int())
    }

    if (n >= 40000) {
      cnt := make([]int, 10001, 10001)
      for j := 0; j < n; j++ {
        len := sticks[j];
        cnt[len]++;
        if (cnt[len] == 4) {
          fmt.Printf("%v %v %v %v\n", len, len, len, len);
          break;
        }
      }
      continue
    }

    sort.Slice(sticks, func(i, j int) bool { return sticks[i] < sticks[j] })
    var min_ratio float64 = 1e+30
    var side_a, side_b int = 0, 0
    for j := 0; j + 1 < n; {
      if sticks[j] == sticks[j + 1] {
        var k int = j + 2
        for k < n && sticks[k] == sticks[j] {
            k++;
        }
        if (k - j >= 4) {
          min_ratio = 16
          side_a = sticks[j]
          side_b = sticks[j]
          break
        }

        for (k+1) < n && sticks[k] != sticks[k+1] {
          k++;
        }

        if ((k+1 < n) && (sticks[k] == sticks[k+1])) {
          p := float64(sticks[j]*2 + sticks[k]*2)
          ratio := (p * p) / float64(sticks[j]*sticks[k])
          if ratio < min_ratio {
            min_ratio = ratio
            side_a = sticks[j]
            side_b = sticks[k]
          }
        }
        j = k
      } else {
        j++;
      }
    }
    fmt.Printf("%v %v %v %v\n", side_a, side_a, side_b, side_b)
  }
}

package main

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

var scanner * bufio.Scanner

func next_int()(result int64){
  if !scanner.Scan() {
    panic("Unable to read next integer. Input has no data remain")
  }
  res, err := strconv.ParseInt(scanner.Text(), 10, 32)
  if err != nil {
    panic(err)
  }
  return res
}

func next_str()(result string){
  if !scanner.Scan() {
    panic("Unable to read next token. Input has no data remain")
  }
  return scanner.Text()
}

func main() {

  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)

  sticks := make([] int, 1000000, 1000000)
  T := int(next_int())
  for test := 1 ; test <= T; test++ {
    sticks = sticks[0:0]
    n := int(next_int())
    for j := 0; j < n; j++ {
      sticks = append(sticks, int(next_int()))
    }

    /*if (n >= 40000) {
      cnt := make([]int, 10001, 10001)
      for j := 0; j < n; j++ {
        len := sticks[j];
        cnt[len]++;
        if (cnt[len] == 4) {
          fmt.Printf("%v %v %v %v\n", len, len, len, len);
          break;
        }
      }
      continue
    }*/

    sort.Slice(sticks, func(i, j int) bool { return sticks[i] < sticks[j] })
    var min_ratio float64 = 1e+30
    var side_a, side_b int = 0, 0
    for j := 0; j + 1 < n; {
      if sticks[j] == sticks[j + 1] {
        var k int = j + 2
        for k < n && sticks[k] == sticks[j] {
            k++;
        }
        if (k - j >= 4) {
          min_ratio = 16
          side_a = sticks[j]
          side_b = sticks[j]
          break
        }

        for (k+1) < n && sticks[k] != sticks[k+1] {
          k++;
        }

        if ((k+1 < n) && (sticks[k] == sticks[k+1])) {
          p := float64(sticks[j]*2 + sticks[k]*2)
          ratio := (p * p) / float64(sticks[j]*sticks[k])
          if ratio < min_ratio {
            min_ratio = ratio
            side_a = sticks[j]
            side_b = sticks[k]
          }
        }
        j = k
      } else {
        j++;
      }
    }
    fmt.Printf("%v %v %v %v\n", side_a, side_a, side_b, side_b)
  }
}

package main

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

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)

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

		sort.Ints(arr)

		x, y, prev, dist := 0, 0, 0, int(1e4 + 1)

		for i := 0; i < n - 1; i++ {
			if i < n - 3 && arr[i] == arr[i + 1] && arr[i + 1] == arr[i + 2] && arr[i + 2] == arr[i + 3] {
				x, y = arr[i], arr[i]
				dist = 0
				continue
			}
			if arr[i] == arr[i + 1] {
				if prev != 0 {
					if dist >= arr[i] - prev {
						dist = arr[i] - prev
						x, y = arr[i], prev
					}
				}
				prev = arr[i]
			}
		}

		fmt.Fprintln(out, x, x, y, y)

	}

}

package main

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

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)

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

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

		x, y, prev, dist := int64(0), int64(0), int64(0), math.MaxFloat64

		for i := 0; i < n - 1; i++ {
			if arr[i] == arr[i + 1] {
				if prev != 0 {
					p := 2 * arr[i] + 2 * prev
					s := arr[i] * prev
					distTmp := float64(p * p) / float64(s)
					if !(math.Abs(dist - distTmp) <= 1e-6) && dist > distTmp {
						dist = distTmp
						x, y = prev, arr[i]
					}
				}
				prev = arr[i]
				i++
			}
		}

		fmt.Fprintln(out, x, x, y, y)

	}

}

package main

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

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)

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

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

		x, y, prev, dist := int64(0), int64(0), int64(0), math.MaxFloat64

		for i := 0; i < n - 1; i++ {
			if arr[i] == arr[i + 1] {
				if prev != 0 {
					p := 2 * arr[i] + 2 * prev
					s := arr[i] * prev
					distTmp := float64(p * p) / float64(s)
					if !(math.Abs(dist - distTmp) <= 1e-5) && dist > distTmp {
						dist = distTmp
						x, y = prev, arr[i]
					}
				}
				prev = arr[i]
				i++
			}
		}

		fmt.Fprintln(out, x, x, y, y)

	}

}

package main

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

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)

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

		sort.Ints(arr)

		x, y, prev, dist := 0, 0, 0, int(1e4 + 1)

		for i := 0; i < n - 1; i++ {
			if i < n - 3 && arr[i] == arr[i + 1] && arr[i + 1] == arr[i + 2] && arr[i + 2] == arr[i + 3] {
				x, y = arr[i], arr[i]
				dist = 0
				i += 3
				continue
			}
			if arr[i] == arr[i + 1] {
				if prev != 0 {
					if dist >= arr[i] - prev {
						dist = arr[i] - prev
						x, y = arr[i], prev
					}
				}
				prev = arr[i]
				i++
			}
		}

		fmt.Fprintln(out, x, x, y, y)

	}

}

package main

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

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)

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

		sort.Ints(arr)

		x, y, prev, dist := 0, 0, 0, int(1e4 + 1)

		for i := 0; i < n - 1; i++ {
			if i < n - 3 && arr[i] == arr[i + 1] && arr[i] == arr[i + 2] && arr[i] == arr[i + 3] {
				x, y = arr[i], arr[i]
				dist = 0
				break
			}
			if arr[i] == arr[i + 1] {
				if prev != 0 {
					if dist >= arr[i] - prev {
						dist = arr[i] - prev
						x, y = arr[i], prev
					}
				}
				prev = arr[i]
				i++
			}
		}

		fmt.Fprintln(out, x, x, y, y)

	}

}

package main

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

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)

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

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

		x, y, prev, dist := int64(0), int64(0), int64(0), math.MaxFloat64

		for i := 0; i < n - 1; i++ {
			if arr[i] == arr[i + 1] {
				if prev != 0 {
					p := 2 * arr[i] + 2 * prev
					s := arr[i] * prev
					distTmp := float64(p * p) / float64(s)
					if !(math.Abs(dist - distTmp) <= 1e-6) && dist > distTmp {
						dist = distTmp
						x, y = prev, arr[i]
					}
				}
				prev = arr[i]
				i++
			}
		}

		fmt.Fprintln(out, x, x, y, y)

	}

}

package main

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

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)

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

		sort.Ints(arr)

		x, y, prev, dist := 0, 0, 0, math.MaxFloat64

		for i := 0; i < n - 1; i++ {
			if arr[i] == arr[i + 1] {
				if prev != 0 {
					p := 2 * int64(arr[i]) + 2 * int64(prev)
					s := int64(arr[i]) * int64(prev)
					distTmp := float64(p * p) / float64(s)
					if !(math.Abs(dist - distTmp) <= 1e-6) && dist > distTmp {
						dist = distTmp
						x, y = prev, arr[i]
					}
				}
				prev = arr[i]
				i++
			}
		}

		fmt.Fprintln(out, x, x, y, y)

	}

}

package main

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

var scanner * bufio.Scanner

func next_int()(result int64){
  if !scanner.Scan() {
    panic("Unable to read next integer. Input has no data remain")
  }
  res, err := strconv.ParseInt(scanner.Text(), 10, 32)
  if err != nil {
    panic(err)
  }
  return res
}

func next_str()(result string){
  if !scanner.Scan() {
    panic("Unable to read next token. Input has no data remain")
  }
  return scanner.Text()
}

func main() {

  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)

  T := int(next_int())
  for test := 1 ; test <= T; test++ {
    n := int(next_int())
    sticks := make([] int, n, n)
    for j := 0; j < n; j++ {
      sticks[j] = int(next_int())
    }

    if (n >= 40000) {
      cnt := make([]int, 10001, 10001)
      for j := 0; j < n; j++ {
        len := sticks[j];
        cnt[len]++;
        if (cnt[len] == 4) {
          fmt.Printf("%v %v %v %v\n", len, len, len, len);
          break;
        }
      }
      continue
    }

    sort.Slice(sticks, func(i, j int) bool { return sticks[i] < sticks[j] })
    var min_ratio float64 = 1e+30
    var side_a, side_b int = 0, 0
    for j := 0; j + 1 < n; {
      if sticks[j] == sticks[j + 1] {
        var k int = j + 2
        for k < n && sticks[k] == sticks[j] {
          k++;
        }
        if (k - j >= 4) {
          min_ratio = 16
          side_a = sticks[j]
          side_b = sticks[j]
          break
        }
        if ((k+1 < n) && (sticks[k] == sticks[k+1])) {
          p := float64(sticks[j]*2 + sticks[k]*2)
          ratio := (p * p) / float64(sticks[j]*sticks[k])
          if ratio < min_ratio {
            min_ratio = ratio
            side_a = sticks[j]
            side_b = sticks[k]
          }
        }
        j = k
      } else {
        j++;
      }
    }
    fmt.Printf("%v %v %v %v\n", side_a, side_a, side_b, side_b)
  }
}