package main

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

const lg = 20

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

	n, q := io.NextInt(), io.NextInt()
	a := io.NextInts(1 << n)

	tree := build(n, 0, a)

	for ; q > 0; q-- {
		t := io.NextInt()
		switch t {
		case 1:
			x, k := io.NextInt()-1, io.NextInt()
			replace(tree, n, 0, x, k)
		case 2:
			k := io.NextInt()
			reverse(tree, k)
		case 3:
			k := io.NextInt()
			swap(tree, k+1)
		case 4:
			l, r := io.NextInt()-1, io.NextInt()
			io.Println(sum(tree, n, 0, l, r))
		}
	}
}

type Node struct {
	sum  int64
	rev  [lg]bool
	l, r *Node
}

func build(n int, i int, a []int) *Node {
	if n == 0 {
		return &Node{sum: int64(a[i])}
	}
	l, r := build(n-1, i, a), build(n-1, i+1<<(n-1), a)
	return &Node{sum: l.sum + r.sum, l: l, r: r}
}

func push(t *Node, n int) {
	if n == 0 {
		return
	}
	for i := 0; i <= n; i++ {
		if !t.rev[i] {
			continue
		}
		t.rev[i] = false
		if i == n {
			t.l, t.r = t.r, t.l
			t.l.rev[n-1] = !t.l.rev[n-1]
			t.r.rev[n-1] = !t.r.rev[n-1]
		} else {
			t.l.rev[i] = !t.l.rev[i]
			t.r.rev[i] = !t.r.rev[i]
		}
	}
}

func sum(t *Node, n, i, l, r int) int64 {
	push(t, n)
	j := i + (1 << n)
	if r <= i || j <= l {
		return 0
	}
	if l <= i && j <= r {
		return t.sum
	}
	return sum(t.l, n-1, i, l, r) + sum(t.r, n-1, i+1<<(n-1), l, r)
}

func replace(t *Node, n, i, x, k int) {
	push(t, n)
	j := i + (1 << n)
	if x < i || j <= x {
		return
	}
	if n == 0 {
		t.sum = int64(k)
		return
	}
	replace(t.l, n-1, i, x, k)
	replace(t.r, n-1, i+1<<(n-1), x, k)
	t.sum = t.l.sum + t.r.sum
}

func reverse(t *Node, n int) {
	t.rev[n] = !t.rev[n]
}

func swap(t *Node, n int) {
	t.rev[n], t.rev[n-1] = !t.rev[n], !t.rev[n-1]
}

type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

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

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

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

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

func main() {
	defer rw.Flush()
	n, q := rw.NextInt(), rw.NextInt()
	N := 1 << n
	a := make([]int64, N)
	a = append(a, rw.NextInt64s(N)...)
	for i := N - 1; i > 0; i-- {
		a[i] = a[i*2] + a[i*2+1]
	}
	swap := make([]int, n)
	for ; q > 0; q-- {
		t := rw.NextInt()
		switch t {
		case 1:
			x, k := rw.NextInt()-1, rw.NextInt64()
			u := 1
			for i := n - 1; i >= 0; i-- {
				u = 2*u ^ (x >> i & 1) ^ swap[i]
			}
			k -= a[u]
			u = 1
			a[u] += k
			for i := n - 1; i >= 0; i-- {
				u = 2*u ^ (x >> i & 1) ^ swap[i]
				a[u] += k
			}
		case 2:
			k := rw.NextInt()
			for k--; k >= 0; k-- {
				swap[k] ^= 1
			}
		case 3:
			k := rw.NextInt()
			swap[k] ^= 1
		case 4:
			l, r := rw.NextInt()-1, rw.NextInt()
			var calc func(int, int, int, int) int64
			calc = func(i, sl, sr, d int) int64 {
				if l <= sl && sr <= r {
					return a[i]
				}
				if l >= sr || sl >= r {
					return int64(0)
				}
				return calc(2*i^swap[d], sl, (sl+sr)/2, d-1) +
					calc(2*i^1^swap[d], (sl+sr)/2, sr, d-1)
			}
			rw.Println(calc(1, 0, N, n-1))
		}
	}
}

// @meooow template uwu
type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

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

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

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

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) NextInt64() int64 {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := int64(0)
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int64(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) NextInt64s(n int) []int64 {
	a := make([]int64, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt64()
	}
	return a
}

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

func (f *FastIO) Print(a ...interface{}) {
	fmt.Fprint(f, a...)
}
func (f *FastIO) PrintInts(a ...int) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInts(a ...int) {
	f.PrintInts(a...)
	f.Println()
}
func (f *FastIO) PrintInt64s(a ...int64) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInt64s(a ...int64) {
	f.PrintInt64s(a...)
	f.Println()
}

package main

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

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

func main() {
	defer rw.Flush()
	n, q := rw.NextInt(), rw.NextInt()
	N := 1 << n
	a := make([]int64, N)
	a = append(a, rw.NextInt64s(N)...)
	for i := N - 1; i > 0; i-- {
		a[i] = a[i*2] + a[i*2+1]
	}
	swap := make([]int, n)
	for ; q > 0; q-- {
		t := rw.NextInt()
		switch t {
		case 1:
			x, k := rw.NextInt()-1, rw.NextInt64()
			u := 1
			for i := 0; i < n; i++ {
				u = 2*u ^ (x >> (n - 1 - i) & 1) ^ swap[i]
			}
			k -= a[u]
			u = 1
			a[u] += k
			for i := 0; i < n; i++ {
				u = 2*u ^ (x >> (n - 1 - i) & 1) ^ swap[i]
				a[u] += k
			}
		case 2:
			k := rw.NextInt()
			for k--; k >= 0; k-- {
				swap[n-1-k] ^= 1
			}
		case 3:
			k := rw.NextInt()
			swap[n-1-k] ^= 1
		case 4:
			l, r := rw.NextInt()-1, rw.NextInt()
			var calc func(int, int, int, int) int64
			calc = func(i, sl, sr, d int) int64 {
				if l <= sl && sr <= r {
					return a[i]
				}
				if l >= sr || sl >= r {
					return int64(0)
				}
				return calc(2*i^swap[d], sl, (sl+sr)/2, d+1) +
					calc(2*i^1^swap[d], (sl+sr)/2, sr, d+1)
			}
			rw.Println(calc(1, 0, N, 0))
		}
	}
}

// @meooow template uwu
type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

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

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

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

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) NextInt64() int64 {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := int64(0)
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int64(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) NextInt64s(n int) []int64 {
	a := make([]int64, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt64()
	}
	return a
}

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

func (f *FastIO) Print(a ...interface{}) {
	fmt.Fprint(f, a...)
}
func (f *FastIO) PrintInts(a ...int) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInts(a ...int) {
	f.PrintInts(a...)
	f.Println()
}
func (f *FastIO) PrintInt64s(a ...int64) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInt64s(a ...int64) {
	f.PrintInt64s(a...)
	f.Println()
}

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
)

var reversed [19]bool
var swaped [19]bool
var tree [524288]uint64

func swap(l, r, x int) int {
	mid := (l + r) / 2
	if mid < x {
		return x - (r-l+1)/2
	} else {
		return x + (r-l+1)/2
	}
}

func replace(depth, x, k, l, r, index int) {
	if depth == 0 {
		tree[index] = uint64(k)
		return
	}
	mid := (l + r) / 2
	if reversed[depth] {
		x = l + r - x
	}
	if swaped[depth-1] {
		x = swap(l, r, x)
	}
	if x <= mid {
		replace(depth-1, x, k, l, mid, index*2+1)
	} else {
		replace(depth-1, x, k, mid+1, r, index*2+2)
	}
	tree[index] = tree[index*2+1] + tree[index*2+2]
}

func sum(depth, left, right, l, r, index int) uint64 {
	if left == l && right == r {
		return tree[index]
	}

	mid := (l + r) / 2
	if reversed[depth] {
		left, right = l+r-right, l+r-left
	}
	if swaped[depth-1] {
		if left <= mid && right > mid {
			return sum(depth-1, l, swap(l, r, right), l, mid, index*2+1) + sum(depth-1, swap(l, r, left), r, mid+1, r, index*2+2)
		} else if right <= mid {
			return sum(depth-1, swap(l, r, left), swap(l, r, right), mid+1, r, index*2+2)
		} else {
			return sum(depth-1, swap(l, r, left), swap(l, r, right), l, mid, index*2+1)
		}
	} else {
		if left <= mid && right > mid {
			return sum(depth-1, left, mid, l, mid, index*2+1) + sum(depth-1, mid+1, right, mid+1, r, index*2+2)
		} else if right <= mid {
			return sum(depth-1, left, right, l, mid, index*2+1)
		} else {
			return sum(depth-1, left, right, mid+1, r, index*2+2)
		}
	}
}

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewReader(bs)
	var n, q int
	fmt.Fscanf(reader, "%d %d\n", &n, &q)

	var a int
	count := (1 << n) - 1
	for i := 0; i < count; i++ {
		fmt.Fscanf(reader, "%d ", &a)
		replace(n, i, a, 0, count, 0)
	}
	fmt.Fscanf(reader, "%d\n", &a)
	replace(n, count, a, 0, count, 0)

	for i := 0; i < q; i++ {
		var op int
		fmt.Fscanf(reader, "%d ", &op)
		switch op {
		case 1:
			var x, k int
			fmt.Fscanf(reader, "%d %d\n", &x, &k)
			replace(n, x-1, k, 0, count, 0)
		case 2:
			var k int
			fmt.Fscanf(reader, "%d\n", &k)
			reversed[k] = !reversed[k]
		case 3:
			var k int
			fmt.Fscanf(reader, "%d\n", &k)
			swaped[k] = !swaped[k]
		case 4:
			var l, r int
			fmt.Fscanf(reader, "%d %d\n", &l, &r)
			fmt.Printf("%d\n", sum(n, l-1, r-1, 0, count, 0))
		}
	}
}

package main

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

const lg = 20

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

	n, q := io.NextInt(), io.NextInt()
	n2 := 1 << n
	a := io.NextInts(n2)

	tree := Build(n, 0, a)

	for ; q > 0; q-- {
		t := io.NextInt()
		switch t {
		case 1:
			x, k := io.NextInt()-1, io.NextInt()
			Replace(tree, n, 0, x, k)
		case 2:
			k := io.NextInt()
			Reverse(tree, k)
		case 3:
			k := io.NextInt()
			Swap(tree, k+1)
		case 4:
			l, r := io.NextInt()-1, io.NextInt()
			io.Println(Sum(tree, n, 0, l, r))
		}
	}
}

type Node struct {
	sum       int64
	rev, swap [lg]bool
	l, r      *Node
}

func Build(n int, i int, a []int) *Node {
	if n == 0 {
		return &Node{sum: int64(a[i])}
	}
	l := Build(n-1, i, a)
	r := Build(n-1, i+1<<(n-1), a)
	return &Node{sum: l.sum + r.sum, l: l, r: r}
}

func Push(t *Node, n int) {
	if n == 0 {
		return
	}
	for i := 0; i < n; i++ {
		if t.rev[i] {
			t.l.rev[i] = !t.l.rev[i]
			t.r.rev[i] = !t.r.rev[i]
		}
		if t.swap[i] {
			t.l.swap[i] = !t.l.swap[i]
			t.r.swap[i] = !t.r.swap[i]
		}
	}
	if t.rev[n] {
		t.l, t.r = t.r, t.l
		t.l.rev[n-1] = !t.l.rev[n-1]
		t.r.rev[n-1] = !t.r.rev[n-1]
	}
	if t.swap[n] {
		t.l, t.r = t.r, t.l
	}
	for i := range t.rev {
		t.rev[i] = false
		t.swap[i] = false
	}
}

func Sum(t *Node, n, i, l, r int) int64 {
	Push(t, n)
	j := i + (1 << n)
	if r <= i || j <= l {
		return 0
	}
	if l <= i && j <= r {
		return t.sum
	}
	return Sum(t.l, n-1, i, l, r) + Sum(t.r, n-1, i+1<<(n-1), l, r)
}

func Replace(t *Node, n, i, x, k int) {
	Push(t, n)
	j := i + (1 << n)
	if x < i || j <= x {
		return
	}
	if n == 0 {
		t.sum = int64(k)
		return
	}
	Replace(t.l, n-1, i, x, k)
	Replace(t.r, n-1, i+1<<(n-1), x, k)
	t.sum = t.l.sum + t.r.sum
}

func Reverse(t *Node, n int) {
	t.rev[n] = !t.rev[n]
}

func Swap(t *Node, n int) {
	t.swap[n] = !t.swap[n]
}

type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

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

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

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

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

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

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

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

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

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

package main

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

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

func main() {
	defer rw.Flush()
	n, q := rw.NextInt(), rw.NextInt()
	N := 1 << n
	a := make([]int64, N)
	a = append(a, rw.NextInt64s(N)...)
	for i := N - 1; i > 0; i-- {
		a[i] = a[i*2] + a[i*2+1]
	}
	swap := make([]int, n)
	for ; q > 0; q-- {
		t := rw.NextInt()
		switch t {
		case 1:
			x, k := rw.NextInt()-1+N, rw.NextInt64()
			k -= a[x^swap[0]]
			a[1] += k
			for i, s := range swap {
				a[x>>i^s] += k
			}
		case 2:
			k := rw.NextInt()
			for k--; k > 0; k-- {
				swap[k] ^= 1
			}
		case 3:
			k := rw.NextInt()
			swap[k] ^= 1
		case 4:
			l, r := rw.NextInt()-1, rw.NextInt()
			var calc func(int, int, int, int) int64
			calc = func(i, sl, sr, d int) int64 {
				if l <= sl && sr <= r {
					return a[i]
				}
				if l >= sr || sl >= r {
					return int64(0)
				}
				return calc((2*i)^swap[d], sl, (sl+sr)/2, d-1) +
					calc((2*i+1)^swap[d], (sl+sr)/2, sr, d-1)
			}
			rw.Println(calc(1, 0, N, n-1))
		}
	}
}

// @meooow template uwu
type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

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

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

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

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) NextInt64() int64 {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := int64(0)
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int64(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) NextInt64s(n int) []int64 {
	a := make([]int64, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt64()
	}
	return a
}

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

func (f *FastIO) Print(a ...interface{}) {
	fmt.Fprint(f, a...)
}
func (f *FastIO) PrintInts(a ...int) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInts(a ...int) {
	f.PrintInts(a...)
	f.Println()
}
func (f *FastIO) PrintInt64s(a ...int64) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInt64s(a ...int64) {
	f.PrintInt64s(a...)
	f.Println()
}

package main

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

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

func main() {
	defer rw.Flush()
	n, q := rw.NextInt(), rw.NextInt()
	N := 1 << n
	a := make([]int64, N)
	a = append(a, rw.NextInt64s(N)...)
	for i := N - 1; i > 0; i-- {
		a[i] = a[i*2] + a[i*2+1]
	}
	swap := make([]int, n)
	for ; q > 0; q-- {
		t := rw.NextInt()
		switch t {
		case 1:
			x, k := rw.NextInt()-1+N, rw.NextInt64()
			k -= a[x^swap[0]]
			a[1] += k
			for i, s := range swap {
				a[(x>>i)^s] += k
			}
		case 2:
			k := rw.NextInt()
			for k--; k > 0; k-- {
				swap[k] ^= 1
			}
		case 3:
			k := rw.NextInt()
			swap[k] ^= 1
		case 4:
			l, r := rw.NextInt()-1, rw.NextInt()
			var calc func(int, int, int, int) int64
			calc = func(i, sl, sr, d int) int64 {
				if l <= sl && sr <= r {
					return a[i]
				}
				if l >= sr || sl >= r {
					return int64(0)
				}
				return calc((2*i)^swap[d], sl, (sl+sr)/2, d-1) +
					calc((2*i+1)^swap[d], (sl+sr)/2, sr, d-1)
			}
			rw.Println(calc(1, 0, N, n-1))
		}
	}
}

// @meooow template uwu
type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

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

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

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

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) NextInt64() int64 {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := int64(0)
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int64(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) NextInt64s(n int) []int64 {
	a := make([]int64, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt64()
	}
	return a
}

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

func (f *FastIO) Print(a ...interface{}) {
	fmt.Fprint(f, a...)
}
func (f *FastIO) PrintInts(a ...int) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInts(a ...int) {
	f.PrintInts(a...)
	f.Println()
}
func (f *FastIO) PrintInt64s(a ...int64) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInt64s(a ...int64) {
	f.PrintInt64s(a...)
	f.Println()
}

package main

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

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

func main() {
	defer rw.Flush()
	n, q := rw.NextInt(), rw.NextInt()
	N := 1 << n
	a := make([]int64, N)
	a = append(a, rw.NextInt64s(N)...)
	for i := N - 1; i > 0; i-- {
		a[i] = a[i*2] + a[i*2+1]
	}
	swap := make([]int, n)
	for ; q > 0; q-- {
		t := rw.NextInt()
		switch t {
		case 1:
			x, k := rw.NextInt()-1, rw.NextInt64()
			for i, u := 0, 1; i < n; i++ {
				u = 2*u ^ (x >> (n - 1 - i) & 1) ^ swap[i]
				if i == n-1 {
					k -= a[u]
				}
			}
			a[1] += k
			for i, u := 0, 1; i < n; i++ {
				u = 2*u ^ (x >> (n - 1 - i) & 1) ^ swap[i]
				a[u] += k
			}
		case 2:
			k := rw.NextInt()
			for k--; k > 0; k-- {
				swap[n-1-k] ^= 1
			}
		case 3:
			k := rw.NextInt()
			swap[n-1-k] ^= 1
		case 4:
			l, r := rw.NextInt()-1, rw.NextInt()
			var calc func(int, int, int, int) int64
			calc = func(i, sl, sr, d int) int64 {
				if l <= sl && sr <= r {
					return a[i]
				}
				if l >= sr || sl >= r {
					return int64(0)
				}
				return calc(2*i^swap[d], sl, (sl+sr)/2, d+1) +
					calc(2*i^1^swap[d], (sl+sr)/2, sr, d+1)
			}
			rw.Println(calc(1, 0, N, 0))
		}
	}
}

// @meooow template uwu
type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

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

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

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

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) NextInt64() int64 {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := int64(0)
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int64(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) NextInt64s(n int) []int64 {
	a := make([]int64, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt64()
	}
	return a
}

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

func (f *FastIO) Print(a ...interface{}) {
	fmt.Fprint(f, a...)
}
func (f *FastIO) PrintInts(a ...int) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInts(a ...int) {
	f.PrintInts(a...)
	f.Println()
}
func (f *FastIO) PrintInt64s(a ...int64) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInt64s(a ...int64) {
	f.PrintInt64s(a...)
	f.Println()
}

package main

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

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

func main() {
	defer rw.Flush()
	n, q := rw.NextInt(), rw.NextInt()
	N := 1 << n
	a := make([]int64, N)
	a = append(a, rw.NextInt64s(N)...)
	for i := N - 1; i > 0; i-- {
		a[i] = a[i*2] + a[i*2+1]
	}
	swap := make([]int, n)
	for ; q > 0; q-- {
		t := rw.NextInt()
		switch t {
		case 1:
			x, k := rw.NextInt()-1+N, rw.NextInt64()
			k -= a[x^swap[0]]
			a[1] += k
			for i, u := 0, 1; i < n; i++ {
				u = 2*u ^ (x >> (n - 1 - i) & 1) ^ swap[i]
				a[u] += k
			}
		case 2:
			k := rw.NextInt()
			for k--; k > 0; k-- {
				swap[n-1-k] ^= 1
			}
		case 3:
			k := rw.NextInt()
			swap[n-1-k] ^= 1
		case 4:
			l, r := rw.NextInt()-1, rw.NextInt()
			var calc func(int, int, int, int) int64
			calc = func(i, sl, sr, d int) int64 {
				if l <= sl && sr <= r {
					return a[i]
				}
				if l >= sr || sl >= r {
					return int64(0)
				}
				return calc(2*i^swap[d], sl, (sl+sr)/2, d+1) +
					calc(2*i^1^swap[d], (sl+sr)/2, sr, d+1)
			}
			rw.Println(calc(1, 0, N, 0))
		}
	}
}

// @meooow template uwu
type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

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

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

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

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) NextInt64() int64 {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := int64(0)
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int64(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) NextInt64s(n int) []int64 {
	a := make([]int64, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt64()
	}
	return a
}

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

func (f *FastIO) Print(a ...interface{}) {
	fmt.Fprint(f, a...)
}
func (f *FastIO) PrintInts(a ...int) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInts(a ...int) {
	f.PrintInts(a...)
	f.Println()
}
func (f *FastIO) PrintInt64s(a ...int64) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInt64s(a ...int64) {
	f.PrintInt64s(a...)
	f.Println()
}

package main

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

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

func main() {
	defer rw.Flush()
	n, q := rw.NextInt(), rw.NextInt()
	N := 1 << n
	a := make([]int64, N)
	a = append(a, rw.NextInt64s(N)...)
	for i := N - 1; i > 0; i-- {
		a[i] = a[i*2] + a[i*2+1]
	}
	swap := make([]int, n)
	for ; q > 0; q-- {
		t := rw.NextInt()
		switch t {
		case 1:
			x, k := rw.NextInt()-1, rw.NextInt64()
			u := 1
			for i := 0; i < n; i++ {
				u = 2*u ^ (x >> i & 1) ^ swap[n-1-i]
			}
			k -= a[u]
			u = 1
			a[u] += k
			for i := 0; i < n; i++ {
				u = 2*u ^ (x >> i & 1) ^ swap[n-1-i]
				a[u] += k
			}
		case 2:
			k := rw.NextInt()
			for k--; k >= 0; k-- {
				swap[k] ^= 1
			}
		case 3:
			k := rw.NextInt()
			swap[k] ^= 1
		case 4:
			l, r := rw.NextInt()-1, rw.NextInt()
			var calc func(int, int, int, int) int64
			calc = func(i, sl, sr, d int) int64 {
				if l <= sl && sr <= r {
					return a[i]
				}
				if l >= sr || sl >= r {
					return int64(0)
				}
				return calc(2*i^swap[d], sl, (sl+sr)/2, d-1) +
					calc(2*i^1^swap[d], (sl+sr)/2, sr, d-1)
			}
			rw.Println(calc(1, 0, N, n-1))
		}
	}
}

// @meooow template uwu
type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

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

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

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

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) NextInt64() int64 {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := int64(0)
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int64(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) NextInt64s(n int) []int64 {
	a := make([]int64, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt64()
	}
	return a
}

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

func (f *FastIO) Print(a ...interface{}) {
	fmt.Fprint(f, a...)
}
func (f *FastIO) PrintInts(a ...int) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInts(a ...int) {
	f.PrintInts(a...)
	f.Println()
}
func (f *FastIO) PrintInt64s(a ...int64) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInt64s(a ...int64) {
	f.PrintInt64s(a...)
	f.Println()
}

package main

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

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

func main() {
	defer rw.Flush()
	n, q := rw.NextInt(), rw.NextInt()
	N := 1 << n
	a := make([]int64, N)
	a = append(a, rw.NextInt64s(N)...)
	for i := N - 1; i > 0; i-- {
		a[i] = a[i*2] + a[i*2+1]
	}
	swap := make([]int, n)
	for ; q > 0; q-- {
		t := rw.NextInt()
		switch t {
		case 1:
			x, k := rw.NextInt()-1, rw.NextInt64()
			for i, u := 0, 1; i < n; i++ {
				u = 2*u ^ (x >> (n - 1 - i) & 1) ^ swap[i]
				if i == n-1 {
					k -= a[u]
				}
			}
			a[1] += k
			for i, u := 0, 1; i < n; i++ {
				u = 2*u ^ (x >> (n - 1 - i) & 1) ^ swap[i]
				a[u] += k
			}
		case 2:
			k := rw.NextInt()
			for k--; k >= 0; k-- {
				swap[n-1-k] ^= 1
			}
		case 3:
			k := rw.NextInt()
			swap[n-1-k] ^= 1
		case 4:
			l, r := rw.NextInt()-1, rw.NextInt()
			var calc func(int, int, int, int) int64
			calc = func(i, sl, sr, d int) int64 {
				if l <= sl && sr <= r {
					return a[i]
				}
				if l >= sr || sl >= r {
					return int64(0)
				}
				return calc(2*i^swap[d], sl, (sl+sr)/2, d+1) +
					calc(2*i^1^swap[d], (sl+sr)/2, sr, d+1)
			}
			rw.Println(calc(1, 0, N, 0))
		}
	}
}

// @meooow template uwu
type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

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

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

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

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) NextInt64() int64 {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := int64(0)
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int64(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) NextInt64s(n int) []int64 {
	a := make([]int64, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt64()
	}
	return a
}

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

func (f *FastIO) Print(a ...interface{}) {
	fmt.Fprint(f, a...)
}
func (f *FastIO) PrintInts(a ...int) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInts(a ...int) {
	f.PrintInts(a...)
	f.Println()
}
func (f *FastIO) PrintInt64s(a ...int64) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInt64s(a ...int64) {
	f.PrintInt64s(a...)
	f.Println()
}


package main

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

type contest struct {
	in  io.Reader
	out io.Writer
}

func (con *contest) Scan(a ...interface{}) (int, error) {
	return fmt.Fscan(con.in, a...)
}
func (con *contest) Scanln(a ...interface{}) (int, error) {
	return fmt.Fscanln(con.in, a...)
}
func (con *contest) Scanf(f string, a ...interface{}) (int, error) {
	return fmt.Fscanf(con.in, f, a...)
}
func (con *contest) Print(a ...interface{}) (int, error) {
	return fmt.Fprint(con.out, a...)
}
func (con *contest) Println(a ...interface{}) (int, error) {
	return fmt.Fprintln(con.out, a...)
}
func (con *contest) Printf(f string, a ...interface{}) (int, error) {
	return fmt.Fprintf(con.out, f, a...)
}
func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	con := &contest{in: in, out: out}
	con.main()
}

var mirrorTab = []int{0, 1, 5, -1, -1, 2, -1, -1, 8, -1}

func good(h int, m int, H int, M int) bool {
	D1 := mirrorTab[h/10]
	D2 := mirrorTab[h%10]
	D3 := mirrorTab[m/10]
	D4 := mirrorTab[m%10]
	if D1 < 0 || D2 < 0 || D3 < 0 || D4 < 0 {
		return false
	}
	h = D4*10 + D3
	m = D2*10 + D1
	return h < H && m < M
}

func (con *contest) main() error {
	var testcases int
	con.Scan(&testcases)
	for testcase := 0; testcase < testcases; testcase++ {
		var H, M int
		var S string
		con.Scan(&H, &M, &S)
		h := int(S[0]-'0')*10 + int(S[1]-'0')
		m := int(S[3]-'0')*10 + int(S[4]-'0')
		for !good(h, m, H, M) {
			m++
			if m >= M {
				m = 0
				h++
				if h >= H {
					h = 0
				}
			}
		}
		con.Printf("%02d:%02d\n", h, m)
	}
	return nil
}

package main

import (
	"fmt"
)
var mxh,mxm int
func check(h int,m int) bool{
	ref:=[10]int{0,1,5,-1,-1,2,-1,-1,8,-1}
	for i:=m;i>0;i/=10{
		num:=i%10
		if ref[num]==-1 {
			return false
		}
	}
	for i:=h;i>0;i/=10{
		num:=i%10
		if ref[num]==-1{
			return false
		}
	}
	mh,mm:=(ref[m%10])*10+ref[m/10],(ref[h%10])*10+ref[h/10]
	if mm>=mxm||mh>=mxh{
		return false
	}
	return true
}
func work() {
	fmt.Scanf("%d %d\n",&mxh,&mxm)
	var h,m int
	fmt.Scanf("%d:%d\n",&h,&m)
	tot:=mxh*mxm
	for i:=h*mxm+m;i<=h*mxm+m+tot;i++{
		x,y:=(i/mxm)%mxh,i%mxm
		if check(x,y){
			fmt.Printf("%02d:%02d\n",x,y)
			return
		}
	}
}
func main() {
	var T int
	fmt.Scanln(&T)
	for cas:=1;cas<=T;cas++{
		work()
	}
	return
}

/*
URL:
https://codeforces.com/contest/1493/problem/B
*/

package main

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

var (
	println = fmt.Println

	t int

	H, M int
	S    []rune

	memo map[int]int
)

func main() {
	defer stdout.Flush()

	memo = make(map[int]int)
	memo[0] = 0
	memo[1] = 1
	memo[2] = 5
	memo[5] = 2
	memo[8] = 8

	t = readi()
	for tc := 0; tc < t; tc++ {
		H, M = readi2()
		S = readrs()

		solve()
	}
}

func solve() {
	strs := strings.Split(string(S), ":")
	hh, _ := strconv.Atoi(strs[0])
	mm, _ := strconv.Atoi(strs[1])

	// 全部試す
	for i := 0; i < H*M; i++ {
		// 反転文字列を作る
		ans, ok := isValidTime(hh, mm)
		if ok {
			printf("%s\n", ans)
			return
		}

		mm++
		mq := mm / M
		mm %= M
		hh += mq
		hh %= H
	}
}

func isValidTime(hh, mm int) (string, bool) {
	hstr := []rune(strconv.Itoa(hh))
	mstr := []rune(strconv.Itoa(mm))
	if len(hstr) == 1 {
		hstr = []rune{'0', hstr[0]}
	}
	if len(mstr) == 1 {
		mstr = []rune{'0', mstr[0]}
	}

	mir := []rune{mstr[1], mstr[0], ':', hstr[1], hstr[0]}

	valid := true
	for _, r := range mir {
		if r == ':' {
			continue
		}
		val := int(r - '0')
		if _, ok := memo[val]; !ok {
			valid = false
			break
		}
	}
	if !valid {
		return "", false
	}

	// mirを反転する
	for i := 0; i < len(mir); i++ {
		if mir[i] == ':' {
			continue
		}
		number := int(mir[i] - '0')
		mirNum := memo[number]
		mir[i] = '0' + rune(mirNum)
	}

	strs := strings.Split(string(mir), ":")
	hour, _ := strconv.Atoi(strs[0])
	minute, _ := strconv.Atoi(strs[1])
	if hour < H && minute < M {
		ans := []rune{hstr[0], hstr[1], ':', mstr[0], mstr[1]}
		return string(ans), true
	}
	return "", false
}

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

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

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

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

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

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

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

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

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

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

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

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

	return s
}

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

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

	if e == 0 {
		return 1
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return string(res)
}

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

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

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

	return string(res)
}

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

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

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

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

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

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

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

	return res
}

package main

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

func main() {

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

	corrent := []int{
		0,  // 0
		1,  // 1
		5,  // 2
		-1, // 3
		-1, // 4
		2,  // 5
		-1, // 6
		-1, // 7
		8,  // 8
		-1, // 9
	}

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

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

		var maxHour, maxMinute int
		fmt.Fscanln(in, &maxHour, &maxMinute)

		var s string
		fmt.Fscanln(in, &s)

		clockStr := strings.Split(strings.Trim(s, " "), ":")
		hour, _ := strconv.Atoi(clockStr[0])
		minute, _ := strconv.Atoi(clockStr[1])

		for {

			if corrent[hour/10] != -1 &&
				corrent[hour%10] != -1 &&
				corrent[minute/10] != -1 &&
				corrent[minute%10] != -1 {
				tmpHour, _ := strconv.Atoi(fmt.Sprintf("%d%d", corrent[minute%10], corrent[minute/10]))
				tmpMinute, _ := strconv.Atoi(fmt.Sprintf("%d%d", corrent[hour%10], corrent[hour/10]))
				if tmpHour < maxHour && tmpMinute < maxMinute {
					break
				}
			}

			minute++

			if minute >= maxMinute {
				hour++
				minute = 0
			}

			if hour >= maxHour {
				hour = 0
			}

		}

		fmt.Fprintf(out, "%d%d:%d%d\n", hour/10, hour%10, minute/10, minute%10)

	}

}

package main
import."fmt"

// github.com/EndlessCheng/codeforces-go
func main() {
	d := [][2]int{{},{1,1},{2,5},{5,2},{8,8}}
	var T, H, M, h, m, ansH, ansM int
	for Scanln(&T); T > 0; T-- {
		Scanln(&H, &M)
		Scanf("%d:%d\n", &h, &m)
		t0, mi := h*M+m, int(1e9)
		for _, h0 := range d {
			for _, h1 := range d {
				h = h0[0]*10 + h1[0]
				if h >= H || h1[1]*10+h0[1] >= M {
					continue
				}
				for _, m0 := range d {
					for _, m1 := range d {
						m = m0[0]*10 + m1[0]
						if m >= M || m1[1]*10+m0[1] >= H {
							continue
						}
						t := h*M + m
						if t < t0 {
							t += H * M
						}
						if t-t0 < mi {
							mi, ansH, ansM = t-t0, h, m
						}
					}
				}
			}
		}
		Printf("%02d:%02d\n", ansH, ansM)
	}
}

package main

import . "fmt"

// github.com/EndlessCheng/codeforces-go
func main() {
	ds := [][2]int{{}, {1, 1}, {2, 5}, {5, 2}, {8, 8}}
	var T, H, M, h, m, ansH, ansM int
	for Scanln(&T); T > 0; T-- {
		Scanln(&H, &M)
		Scanf("%d:%d\n", &h, &m)
		t0, minD := h*M+m, int(1e9)
		for _, h0 := range ds {
			for _, h1 := range ds {
				h = h0[0]*10 + h1[0]
				if h >= H || h1[1]*10+h0[1] >= M {
					continue
				}
				for _, m0 := range ds {
					for _, m1 := range ds {
						m = m0[0]*10 + m1[0]
						if m >= M || m1[1]*10+m0[1] >= H {
							continue
						}
						t := h*M + m
						if t < t0 {
							t += H * M
						}
						if t-t0 < minD {
							minD, ansH, ansM = t-t0, h, m
						}
					}
				}
			}
		}
		Printf("%02d:%02d\n", ansH, ansM)
	}
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1493B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	ds := [][2]int{{}, {1, 1}, {2, 5}, {5, 2}, {8, 8}}

	var T, H, M, h, m, ansH, ansM int
	for Fscanln(in, &T); T > 0; T-- {
		Fscanln(in, &H, &M)
		Fscanf(in, "%d:%d\n", &h, &m)
		t0, minD := h*M+m, int(1e9)
		for _, h0 := range ds {
			for _, h1 := range ds {
				h := h0[0]*10 + h1[0]
				if h >= H || h1[1]*10+h0[1] >= M {
					continue
				}
				for _, m0 := range ds {
					for _, m1 := range ds {
						m := m0[0]*10 + m1[0]
						if m >= M || m1[1]*10+m0[1] >= H {
							continue
						}
						t := h*M + m
						if t < t0 {
							t += H * M
						}
						if t-t0 < minD {
							minD, ansH, ansM = t-t0, h, m
						}
					}
				}
			}
		}
		Fprintf(out, "%02d:%02d\n", ansH, ansM)
	}
}

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

package main

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

var maxHrs int
var maxMinutes int

func main() {
	var tcs int
	in := bufio.NewReader(os.Stdin)
	_, _ = fmt.Fscan(in, &tcs)

	for tc := 0; tc < tcs; tc++ {
		_, _ = fmt.Fscan(in, &maxHrs, &maxMinutes)

		var s string
		_, _ = fmt.Fscan(in, &s)

		t := parse(s)
		for ; !t.ifMirror(); t.increment() {
		}

		fmt.Printf("%02d:%02d\n", t.hour, t.min)
	}
}

type time struct {
	hour int
	min  int
}

func parse(s string) time {
	arr := strings.Split(s, ":")

	t := time{}
	t.hour, _ = strconv.Atoi(arr[0])
	t.min, _ = strconv.Atoi(arr[1])

	return t
}

func (t *time) increment() {
	t.min++
	if t.min == maxMinutes {
		t.hour++
	}

	t.min %= maxMinutes
	t.hour %= maxHrs
}

func (t *time) ifMirror() bool {
	arr := []int{t.hour / 10, t.hour % 10, t.min / 10, t.min % 10}

	for i := 0; i < 4; i++ {
		var ok bool

		arr[i], ok = intMirror(arr[i])
		if !ok {
			return false
		}
	}

	newHour := arr[3]*10 + arr[2]
	newMin := arr[1]*10 + arr[0]

	if newHour < maxHrs && newMin < maxMinutes {
		return true
	}

	return false
}

func intMirror(i int) (int, bool) {
	same := []int{0, 1, 8}
	for _, v := range same {
		if i == v {
			return i, true
		}
	}

	if i == 2 {
		return 5, true
	}
	if i == 5 {
		return 2, true
	}

	return -1, false
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1493B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	ds := []int{0, 1, 2, 5, 8}

	var T, H, M, h, m, ansH, ansM int
	for Fscanln(in, &T); T > 0; T-- {
		Fscanln(in, &H, &M)
		Fscanf(in, "%d:%d\n", &h, &m)
		t0, minD := h*M+m, int(1e9)
		for _, h0 := range ds {
			for _, h1 := range ds {
				h := h0*10 + h1
				if h >= H || h1*10+h0 >= M {
					continue
				}
				for _, m0 := range ds {
					for _, m1 := range ds {
						m := m0*10 + m1
						if m >= M || m1*10+m0 >= H {
							continue
						}
						t := h*M + m
						if t < t0 {
							t += H * M
						}
						if t-t0 < minD {
							minD, ansH, ansM = t-t0, h, m
						}
					}
				}
			}
		}
		Fprintf(out, "%02d:%02d\n", ansH, ansM)
	}
}

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

package main

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

var maxHrs int
var maxMinutes int

func main() {
	var tcs int
	in := bufio.NewReader(os.Stdin)
	_, _ = fmt.Fscan(in, &tcs)

	for tc := 0; tc < tcs; tc++ {
		_, _ = fmt.Fscan(in, &maxHrs, &maxMinutes)

		var s string
		_, _ = fmt.Fscan(in, &s)

		t := parse(s)
		t.increment()
		for ; !t.ifMirror(); t.increment() {
		}

		fmt.Printf("%02d:%02d\n", t.hour, t.min)
	}
}

type time struct {
	hour int
	min  int
}

func parse(s string) time {
	arr := strings.Split(s, ":")

	t := time{}
	t.hour, _ = strconv.Atoi(arr[0])
	t.min, _ = strconv.Atoi(arr[1])

	return t
}

func (t *time) increment() {
	t.min++
	if t.min == maxMinutes {
		t.hour++
	}

	t.min %= maxMinutes
	t.hour %= maxHrs
}

func (t *time) ifMirror() bool {
	arr := []int{t.hour / 10, t.hour % 10, t.min / 10, t.min % 10}

	for i := 0; i < 4; i++ {
		var ok bool

		arr[i], ok = intMirror(arr[i])
		if !ok {
			return false
		}
	}

	newHour := arr[3]*10 + arr[2]
	newMin := arr[1]*10 + arr[0]

	if newHour < maxHrs && newMin < maxMinutes {
		return true
	}

	return false
}

func intMirror(i int) (int, bool) {
	same := []int{0, 1, 8}
	for _, v := range same {
		if i == v {
			return i, true
		}
	}

	if i == 2 {
		return 5, true
	}
	if i == 5 {
		return 2, true
	}

	return -1, false
}

package main

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

var maxHrs int
var maxMinutes int

func main() {
	var tcs int
	in := bufio.NewReader(os.Stdin)
	_, _ = fmt.Fscan(in, &tcs)

	for tc := 0; tc < tcs; tc++ {
		_, _ = fmt.Fscan(in, &maxHrs, &maxMinutes)

		var s string
		_, _ = fmt.Fscan(in, &s)

		t := parse(s)

		for ; !t.ifMirror(); t.increment() {
		}

		fmt.Printf("%02d:%02d\n", t.hour, t.min)
	}
}

type time struct {
	hour int
	min  int
}

func parse(s string) time {
	arr := strings.Split(s, ":")

	t := time{}
	t.hour, _ = strconv.Atoi(arr[0])
	t.min, _ = strconv.Atoi(arr[1])

	return t
}

func (t *time) increment() {
	t.min++
	if t.min == maxMinutes {
		t.hour++
	}

	t.min %= maxMinutes
	t.hour %= maxHrs
}

func (t *time) ifMirror() bool {
	arr := []int{t.hour / 10, t.hour % 10, t.min / 10, t.min % 10}

	for i := 0; i < 4; i++ {
		var ok bool

		arr[i], ok = intMirror(arr[i])
		if !ok {
			return false
		}
	}

	newHour := arr[0]*10 + arr[1]
	newMin := arr[2]*10 + arr[3]

	if newHour < maxHrs && newMin < maxMinutes {
		return true
	}

	return false
}

func intMirror(i int) (int, bool) {
	same := []int{0, 1, 8}
	for _, v := range same {
		if i == v {
			return i, true
		}
	}

	if i == 2 {
		return 5, true
	}
	if i == 5 {
		return 2, true
	}

	return -1, false
}

package main

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

var maxHrs int
var maxMinutes int

func main() {
	var tcs int
	in := bufio.NewReader(os.Stdin)
	_, _ = fmt.Fscan(in, &tcs)

	for tc := 0; tc < tcs; tc++ {
		_, _ = fmt.Fscan(in, &maxHrs, &maxMinutes)

		var s string
		_, _ = fmt.Fscan(in, &s)

		t := parse(s)

		for ; !t.ifMirror(); t.increment() {
		}

		fmt.Printf("%02d:%012d\n", t.hour, t.min)
	}
}

type time struct {
	hour int
	min  int
}

func parse(s string) time {
	arr := strings.Split(s, ":")

	t := time{}
	t.hour, _ = strconv.Atoi(arr[0])
	t.min, _ = strconv.Atoi(arr[1])

	return t
}

func (t *time) increment() {
	t.min++
	if t.min == maxMinutes {
		t.hour++
	}

	t.min %= maxMinutes
	t.hour %= maxHrs
}

func (t *time) ifMirror() bool {
	arr := []int{t.hour / 10, t.hour % 10, t.min / 10, t.min % 10}

	for i := 0; i < 4; i++ {
		var ok bool

		arr[i], ok = intMirror(arr[i])
		if !ok {
			return false
		}
	}

	newHour := arr[0]*10 + arr[1]
	newMin := arr[2]*10 + arr[3]

	if newHour < maxHrs && newMin < maxMinutes {
		return true
	}

	return false
}

func intMirror(i int) (int, bool) {
	same := []int{0, 1, 8}
	for _, v := range same {
		if i == v {
			return i, true
		}
	}

	if i == 2 {
		return 5, true
	}
	if i == 5 {
		return 2, true
	}

	return -1, false
}

package main

import (
	"fmt"
)
var mxh,mxm int
func check(h int,m int) bool{
	ref:=[10]int{0,1,5,-1,-1,2,-1,-1,8,-1}
	for i:=m;i>0;i/=10{
		num:=i%10
		if ref[num]==-1 {
			return false
		}
	}
	for i:=h;i>0;i/=10{
		num:=i%10
		if ref[num]==-1{
			return false
		}
	}
	mh,mm:=(m%10)*10+m/10,(h%10)*10+h/10
	if mm>=mxm||mh>=mxh{
		return false
	}
	return true
}
func work() {
	fmt.Scanf("%d %d\n",&mxh,&mxm)
	var h,m int
	fmt.Scanf("%d:%d\n",&h,&m)
	for i:=h;i<=mxh+h;i++{
		for j:=m;j<=mxm+m;j++{
			x,y:=i%mxh,j%mxm
			if check(x,y){
				fmt.Printf("%02d:%02d\n",x,y)
				return
			}
		}
	}
}
func main() {
	var T int
	fmt.Scanln(&T)
	for cas:=1;cas<=T;cas++{
		work()
	}
	return
}

/*
URL:
https://codeforces.com/contest/1493/problem/B
*/

package main

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

var (
	println = fmt.Println

	t int

	H, M int
	S    []rune

	memo map[int]int
)

func main() {
	defer stdout.Flush()

	memo = make(map[int]int)
	memo[0] = 0
	memo[1] = 1
	memo[2] = 5
	memo[5] = 2
	memo[8] = 8

	t = readi()
	for tc := 0; tc < t; tc++ {
		H, M = readi2()
		S = readrs()

		solve()
	}
}

func solve() {
	strs := strings.Split(string(S), ":")
	hh, _ := strconv.Atoi(strs[0])
	mm, _ := strconv.Atoi(strs[1])

	// 全部試す
	for i := 0; i < H*M; i++ {
		// 反転文字列を作る
		ans, ok := isValidTime(hh, mm)
		if ok {
			printf("%s\n", ans)
			return
		}

		mm++
		mq := mm / M
		mm %= M
		hh += mq
		hh %= H
	}
}

func isValidTime(hh, mm int) (string, bool) {
	hstr := []rune(strconv.Itoa(hh))
	mstr := []rune(strconv.Itoa(mm))
	if len(hstr) == 1 {
		hstr = []rune{'0', hstr[0]}
	}
	if len(mstr) == 1 {
		mstr = []rune{'0', mstr[0]}
	}

	mir := []rune{mstr[1], mstr[0], ':', hstr[1], hstr[0]}

	valid := true
	for _, r := range mir {
		if r == ':' {
			continue
		}
		val := int(r - '0')
		if _, ok := memo[val]; !ok {
			valid = false
			break
		}
	}
	if !valid {
		return "", false
	}

	strs := strings.Split(string(mir), ":")
	hour, _ := strconv.Atoi(strs[0])
	minute, _ := strconv.Atoi(strs[1])
	if hour < H && minute < M {
		ans := []rune{hstr[0], hstr[1], ':', mstr[0], mstr[1]}
		return string(ans), true
	}
	return "", false
}

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

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

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

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

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

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

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

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

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

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

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

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

	return s
}

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

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

	if e == 0 {
		return 1
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return string(res)
}

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

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

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

	return string(res)
}

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

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

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

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

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

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

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

	return res
}


package main

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

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 Max(a, b int64) int64 {
	if a >= b {
		return a
	}
	return b
}

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

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

const MAXN = 100010

var (
	n, a, r, m int
	arr        [MAXN]int
	ar         []int
	sum        [MAXN]int64
)

func find_lm(ar []int, h int) (lt, mt int64) {
	lt_i := sort.Search(len(ar), func(i int) bool { return ar[i] >= h }) - 1
	mt_i := sort.Search(len(ar), func(i int) bool { return ar[i] > h })

	lt, mt = 0, 0
	if lt_i >= 0 {
		lt = sum[lt_i]
	}
	lt = int64(lt_i + 1) * int64(h) - lt;

	mt = sum[n - 1]
	if mt_i > 0 {
		mt -= sum[mt_i - 1]
	}
	mt = mt - int64(n - mt_i) * int64(h);

	return
}

func Tern(mx int, f func(i int) int64) (i int, val int64) {
	lo, hi := 0, mx
	for lo < hi {
		mid := lo + (hi - lo) / 2
		if f(mid) > f(mid + 1) {
			lo = mid + 1
		} else {
			hi = mid
		}
	}
	return lo, f(lo)
}

func main() {
	scanf("%d %d %d %d\n", &n, &a, &r, &m)

	for i := 0; i < n; i++ {
		if i < n - 1 {
			scanf("%d", &arr[i])
		} else {
			scanf("%d\n", &arr[i])
		}
	}

	ar = arr[:n]
	sort.Ints(ar)
	for i := 0; i < n; i++ {
		sum[i] = int64(ar[i])
		if i > 0 {
			sum[i] += sum[i - 1]
		}
	}

	max_height := arr[n - 1]

	_, cost1 := Tern(max_height, func(h int) int64 {
		lt, mt := find_lm(ar, h)
		return lt*int64(a) + mt*int64(r)
	})

	_, cost2 := Tern(max_height, func(h int) int64 {
		lt, mt := find_lm(ar, h)
		to_move := Min(lt, mt)
		return to_move*int64(m) + (lt-to_move)*int64(a) + (mt-to_move)*int64(r)
	})

	fmt.Println(Min(cost1, cost2))
}

package main

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

func main () {

	r := bufio.NewReader(os.Stdin)

	var N, A, M, R int

	fmt.Fscan(r, &N, &A, &R, &M)

	h := make([]int64, N)

	for i := 0; i < N; i++ {
		fmt.Fscan(r, &h[i])
	}

	fmt.Println(solveE(h, int64(A), int64(R), int64(M)))
}

func solveE(h []int64, A, R , M int64) int64 {
	sort.Slice(h, func(i, j int) bool {
		return h[i] < h[j]
	})

	dp := make([]int64, len(h))
	dp[0] = h[0]
	for i := 1; i < len(h); i++ {
		dp[i] = dp[i - 1] + h[i]
	}
	lastIndex := len(dp) - 1

	var minCost int64 = 1e18

	for i := 0; i < len(h) - 1; i++ {
		if h[i] == h[i + 1] {
			continue
		}
		leftCount := int64(i + 1)
		rightCount := int64(len(h) - i - 1)

		if A + R < M {

			var height int64

			if leftCount * A > rightCount * R {
				height = h[i]

			} else {
				height = h[i+1] - 1
			}

			top := height * leftCount
			sm := top - dp[i]
			sp := dp[lastIndex] - dp[i] - rightCount * height

			cost := sm * A + sp * R

			if cost < minCost {
				minCost = cost
			}

		} else {
			bottomSM := leftCount * h[i] - dp[i]
			bottomSP := dp[lastIndex] - dp[i] - rightCount * h[i]
			smTop :=  leftCount * (h[i + 1] - 1) - dp[i]
			spTop := dp[lastIndex] - dp[i] - rightCount * (h[i + 1] - 1)

			var bottomCost int64
			var tCost int64 = 1e18
			var t2Cost int64 = 1e18
			var topCost int64
			var localMin int64

			if bottomSP > bottomSM {
				bottomCost = R * (bottomSP - bottomSM) + M * bottomSM

				diff := bottomSP - bottomSM
				t := diff/(leftCount + rightCount)
				threshold := t
				if diff % (leftCount + rightCount) != 0 {
					threshold++
				}

				if threshold < h[i + 1] - h[i] {
					sm1 := leftCount * (h[i] + t) - dp[i]
					sp1 := dp[lastIndex] - dp[i] - rightCount * (h[i] + t)
					tCost = sm1 * M + (sp1 - sm1) * R

					sm2 := leftCount * (h[i] + t + 1) - dp[i]
					sp2 := dp[lastIndex] - dp[i] - rightCount * (h[i] + t + 1)
					t2Cost = (sm2 - sp2) * A + sp2 * M
					topCost = (smTop - spTop) * A + spTop * M
				} else {
					topCost = (spTop - smTop) * R + smTop * M
				}

				localMin = min(bottomCost, min(tCost, min(t2Cost, topCost)))

				minCost = min(minCost, localMin)

			} else {
				bottomCost = A * (bottomSM - bottomSP) + M * bottomSP
				topCost = (smTop - spTop) * A + spTop * M

				localMin = min(bottomCost, topCost)
				minCost = min(minCost, localMin)
			}
		}
	}

	var lastCost int64 = ((int64(h[lastIndex]) * int64(len(h))) - dp[lastIndex]) * A

	minCost = min(minCost, lastCost)

	return minCost
}

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

func doBs(h []int64, target int64) int {
	lo, hi := 0, len(h) - 1

	for ;; {
		if hi - lo < 3 {
			for j := lo ; j <= hi; j++ {
				if h[j] <= target {
					continue
				}
				return j
			}
			return -1
		}

		m := (lo  + hi) /2

		if h[m] > target {
			hi = m
		} else {
			lo = m
		}
	}
}

package main

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

var sc = WordScanner()
var memory [1000000]int
var memory2 [1000000]int64

func main() {
	n := sc.Int()
	a := int64(sc.Int())
	r := int64(sc.Int())
	m := int64(sc.Int())
	if m > a + r {
		m = a + r
	}
	hsp := memory[:n]
	for i := range hsp {
		hsp[i] = sc.Int()
	}
	sort.Ints(hsp)
	hs := memory2[:n]
	for i := range hs {
		hs[i] = int64(hsp[i])
	}
	for i := range hs[1:] {
		hs[i + 1] += hs[i]
	}
	var ans int64 = r * (hs[n - 1] - hs[0] * int64(n))
	var f bool
	for i := range hs {
		if i > 0 && hsp[i] == hsp[i - 1] {
			continue
		}
		h := int64(hsp[i])
		x := int64(i + 1) * h - hs[i]
		y := hs[n - 1] - hs[i] - int64(n - i - 1) * h
		w := x * m + (y - x) * r
		if y < x {
			if !f {
				d := (x - y) / int64(n)
				w = (y + d * int64(n - i)) * m + (x - y - d * int64(n)) * a
				if ans > w {
					ans = w
				}
				if d * int64(n) < x - y {
					w = (x - (d + 1) * int64(i)) * m + (y - x + (d + 1) * int64(n)) * r
					if ans > w {
						ans = w
					}
				}
				f = true
			}
			w = y * m + (x - y) * a
		}
		if ans > w {
			ans = w
		}
	}
	fmt.Println(ans)
}

type Scanner struct {
	*bufio.Scanner
}

func WordScanner() Scanner {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	return Scanner{sc}
}

func (sc Scanner) Text() string {
	sc.Scan()
	return sc.Scanner.Text()
}

func (sc Scanner) Int() int {
	i, _ := strconv.Atoi(sc.Text())
	return i
}

package main

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

func main () {

	r := bufio.NewReader(os.Stdin)

	var N, A, M, R int

	fmt.Fscan(r, &N, &A, &R, &M)

	h := make([]int64, N)

	for i := 0; i < N; i++ {
		fmt.Fscan(r, &h[i])
	}

	fmt.Println(solveE(h, int64(A), int64(R), int64(M)))
}

func solveE(h []int64, A, R , M int64) int64 {
	sort.Slice(h, func(i, j int) bool {
		return h[i] < h[j]
	})

	dp := make([]int64, len(h))
	dp[0] = h[0]
	for i := 1; i < len(h); i++ {
		dp[i] = dp[i - 1] + h[i]
	}
	lastIndex := len(dp) - 1

	var minCost int64 = 1e18

	for i := 0; i < len(h) - 1; i++ {
		if h[i] == h[i + 1] {
			continue
		}
		leftCount := int64(i + 1)
		rightCount := int64(len(h) - i - 1)

		if A + R < M {

			var height int64

			if leftCount * A > rightCount * R {
				height = h[i]

			} else {
				height = h[i+1] - 1
			}

			top := height * leftCount
			sm := top - dp[i]
			sp := dp[lastIndex] - dp[i] - rightCount * height

			cost := sm * A + sp * R

			if cost < minCost {
				minCost = cost
			}

		} else {
			bottomSM := leftCount * h[i] - dp[i]
			bottomSP := dp[lastIndex] - dp[i] - rightCount * h[i]
			smTop :=  leftCount * (h[i + 1] - 1) - dp[i]
			spTop := dp[lastIndex] - dp[i] - rightCount * (h[i + 1] - 1)

			var bottomCost int64
			var tCost int64 = 1e18
			var t2Cost int64 = 1e18
			var topCost int64
			var localMin int64

			if bottomSP > bottomSM {
				bottomCost = R * (bottomSP - bottomSM) + M * bottomSM

				diff := bottomSP - bottomSM
				t := diff/(leftCount + rightCount)
				if diff % (leftCount + rightCount) != 0 {
					t++
				}

				if t < h[i + 1] - h[i] {
					tCost = (leftCount * (h[i] + t) - dp[i]) * M
					sm2 := leftCount * (h[i] + t + 1) - dp[i]
					sp2 := dp[lastIndex] - dp[i] - rightCount * (h[i] + t + 1)
					t2Cost = (sm2 - sp2) * A + sp2 * M
					topCost = (smTop - spTop) * A + spTop * M
				} else {
					topCost = (spTop - smTop) * R + smTop * M
				}

				localMin = min(bottomCost, min(tCost, min(t2Cost, topCost)))

				minCost = min(minCost, localMin)

			} else {
				bottomCost = A * (bottomSM - bottomSP) + M * bottomSP
				topCost = (smTop - spTop) * A + spTop * M

				localMin = min(bottomCost, topCost)
				minCost = min(minCost, localMin)
			}
		}
	}

	lastCost := int64(h[lastIndex]) * int64(len(h)) - dp[lastIndex] * A

	minCost = min(minCost, lastCost)

	return minCost
}

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

func doBs(h []int64, target int64) int {
	lo, hi := 0, len(h) - 1

	for ;; {
		if hi - lo < 3 {
			for j := lo ; j <= hi; j++ {
				if h[j] <= target {
					continue
				}
				return j
			}
			return -1
		}

		m := (lo  + hi) /2

		if h[m] > target {
			hi = m
		} else {
			lo = m
		}
	}
}

package main

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

func main () {

	r := bufio.NewReader(os.Stdin)

	var N, A, M, R int

	fmt.Fscan(r, &N, &A, &R, &M)

	h := make([]int64, N)

	for i := 0; i < N; i++ {
		fmt.Fscan(r, &h[i])
	}

	fmt.Println(solveE(h, int64(A), int64(R), int64(M)))
}

func solveE(h []int64, A, R , M int64) int64 {
	sort.Slice(h, func(i, j int) bool {
		return h[i] < h[j]
	})

	dp := make([]int64, len(h))
	dp[0] = h[0]
	for i := 1; i < len(h); i++ {
		dp[i] = dp[i - 1] + h[i]
	}

	var minCost int64 = 1e18
	var startCost = (dp[len(dp) - 1] - int64(len(dp)) * h[0]) * R

	for i := 1; i < len(h); i++ {
		if h[i] == h[i - 1] {
			continue
		}
		if A + R < M {
			leftCount := i
			rightCount := len(h) - i

			if int64(leftCount) * A > int64(rightCount) * R {
				if minCost > startCost {
					minCost = startCost
				}

			} else {
				k := h[i] - 1

				sumNeg := k * int64(i) - dp[i - 1]
				sumPos := dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

				c := sumNeg * A + sumPos * R

				if minCost > c {
					minCost = c
				}
			}

			left := h[i] * (int64(i) + 1) - dp[i]
			right := dp[len(dp) - 1] - dp[i] - h[i] * (int64(len(h)) - int64(i) - 1)

			startCost = left * A + right * R

		} else {
			var left = int64(i)
			var right = int64(len(h) - i)
			sMinus := left * h[i - 1] - dp[i - 1]
			sPlus := dp[len(dp) - 1] - dp[i - 1] - right * h[i - 1]

			if sMinus >= sPlus {
				if int64(len(h)) * A > right * M {
					if minCost > startCost {
						minCost = startCost
					}

				} else {
					k := h[i] - 1

					sumNeg := k * int64(i) - dp[i - 1]
					sumPos := dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

					c := (sumNeg - sumPos) * A + sumPos * M

					if minCost > c {
						minCost = c
					}
				}

				leftSum := h[i] * (int64(i) + 1) - dp[i]
				rightSum := dp[len(dp) - 1] - dp[i] - h[i] * (int64(len(h)) - int64(i) - 1)

				startCost = (leftSum - rightSum) * A + rightSum * M

			} else {
				if left * M > (left + right) * R {
					diff := sPlus - sMinus
					heightDiff := h[i] - h[i - 1]

					if heightDiff > diff/int64(len(h)) {
						if right * M > (left + right) * A {
							k := h[i] - 1

							sumNeg := k * int64(i) - dp[i - 1]
							sumPos := dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

							c := (sumNeg - sumPos) * A + sumPos * M

							var min int64
							if c > startCost {
								min = startCost
							} else {
								min =  c
							}

							if minCost > min {
								minCost = min
							}

						} else {
							if minCost > startCost {
								minCost = startCost
							}
						}

					} else {
						if minCost > startCost {
							minCost = startCost
						}
					}
				} else {
					diff := sPlus - sMinus
					heightDiff := h[i] - h[i - 1]

					if heightDiff > diff/int64(len(h)) {

						//todo

						if right * M > (left + right) * A {
							k := h[i] - 1

							sumNeg := k * int64(i) - dp[i - 1]
							sumPos := dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

							c1 := (sumNeg - sumPos) * A + sumPos * M

							k = diff/int64(len(h))

							k += h[i - 1]

							sumNeg = k * int64(i) - dp[i - 1]
							sumPos = dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

							c2 := (sumPos - sumNeg) * R + sumNeg * M

							var min int64

							if c1 > c2 {
								min = c2
							} else {
								min = c1
							}

							if minCost > min {
								minCost = min
							}
						} else {

							k := diff/int64(len(h))

							k += h[i - 1]

							sumNeg := k * int64(i) - dp[i - 1]
							sumPos := dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

							c2 := (sumPos - sumNeg) * R + sumNeg * M

							if minCost > c2 {
								minCost = c2
							}
						}

					} else {
						k := h[i] - 1

						sumNeg := k * int64(i) - dp[i - 1]
						sumPos := dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

						c := (sumPos - sumNeg) * R + sumNeg * M

						if minCost > c {
							minCost = c
						}
					}
				}

				leftSum := h[i] * (int64(i) + 1) - dp[i]
				rightSum := dp[len(dp) - 1] - dp[i] - h[i] * (int64(len(h)) - int64(i) - 1)

				if leftSum > rightSum {
					startCost = (leftSum - rightSum) * A + rightSum * M
				} else {
					startCost = (rightSum - leftSum) * R + leftSum * M
				}

				if minCost > startCost {
					minCost = startCost
				}

			}
		}

	}

	return minCost
}

func doBs(h []int64, target int64) int {
	lo, hi := 0, len(h) - 1

	for ;; {
		if hi - lo < 3 {
			for j := lo ; j <= hi; j++ {
				if h[j] <= target {
					continue
				}
				return j
			}
			return -1
		}

		m := (lo  + hi) /2

		if h[m] > target {
			hi = m
		} else {
			lo = m
		}
	}
}

package main

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

func main () {

	r := bufio.NewReader(os.Stdin)

	var N, A, M, R int

	fmt.Fscan(r, &N, &A, &R, &M)

	h := make([]int64, N)

	for i := 0; i < N; i++ {
		fmt.Fscan(r, &h[i])
	}

	fmt.Println(solveE(h, int64(A), int64(R), int64(M)))
}

func solveE(h []int64, A, R , M int64) int64 {
	sort.Slice(h, func(i, j int) bool {
		return h[i] < h[j]
	})

	dp := make([]int64, len(h))
	dp[0] = h[0]
	for i := 1; i < len(h); i++ {
		dp[i] = dp[i - 1] + h[i]
	}
	lastIndex := len(dp) - 1

	var minCost int64 = 1e18

	for i := 0; i < len(h) - 1; i++ {
		if h[i] == h[i + 1] {
			continue
		}
		leftCount := int64(i + 1)
		rightCount := int64(len(h) - i - 1)

		if A + R < M {

			var height int64

			if leftCount * A > rightCount * R {
				height = h[i]

			} else {
				height = h[i+1] - 1
			}

			top := height * leftCount
			sm := top - dp[i]
			sp := dp[lastIndex] - dp[i] - rightCount * height

			cost := sm * A + sp * R

			if cost < minCost {
				minCost = cost
			}

		} else {
			bottomSM := leftCount * h[i] - dp[i]
			bottomSP := dp[lastIndex] - dp[i] - rightCount * h[i]
			smTop :=  leftCount * (h[i + 1] - 1) - dp[i]
			spTop := dp[lastIndex] - dp[i] - rightCount * (h[i + 1] - 1)

			var bottomCost int64
			var tCost int64 = 1e18
			var t2Cost int64 = 1e18
			var topCost int64
			var localMin int64

			if bottomSP > bottomSM {
				bottomCost = R * (bottomSP - bottomSM) + M * bottomSM

				diff := bottomSP - bottomSM
				t := diff/(leftCount + rightCount)
				if diff % (leftCount + rightCount) != 0 {
					t++
				}

				if t < h[i + 1] - h[i] {
					tCost = (leftCount * (h[i] + t) - dp[i]) * M
					sm2 := leftCount * (h[i] + t + 1) - dp[i]
					sp2 := dp[lastIndex] - dp[i] - rightCount * (h[i] + t + 1)
					t2Cost = (sm2 - sp2) * A + sp2 * M
					topCost = (smTop - spTop) * A + spTop * M
				} else {
					topCost = (spTop - smTop) * R + smTop * M
				}

				localMin = min(bottomCost, min(tCost, min(t2Cost, topCost)))

				minCost = min(minCost, localMin)

			} else {
				bottomCost = A * (bottomSM - bottomSP) + M * bottomSP
				topCost = (smTop - spTop) * A + spTop * M

				localMin = min(bottomCost, topCost)
				minCost = min(minCost, localMin)
			}
		}
	}

	var lastCost int64 = ((int64(h[lastIndex]) * int64(len(h))) - dp[lastIndex]) * A

	minCost = min(minCost, lastCost)

	return minCost
}

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

func doBs(h []int64, target int64) int {
	lo, hi := 0, len(h) - 1

	for ;; {
		if hi - lo < 3 {
			for j := lo ; j <= hi; j++ {
				if h[j] <= target {
					continue
				}
				return j
			}
			return -1
		}

		m := (lo  + hi) /2

		if h[m] > target {
			hi = m
		} else {
			lo = m
		}
	}
}

package main

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

func main () {

	r := bufio.NewReader(os.Stdin)

	var N, A, M, R int

	fmt.Fscan(r, &N, &A, &R, &M)

	h := make([]int64, N)

	for i := 0; i < N; i++ {
		fmt.Fscan(r, &h[i])
	}

	fmt.Println(solveE(h, int64(A), int64(R), int64(M)))
}

func solveE(h []int64, A, R , M int64) int64 {
	sort.Slice(h, func(i, j int) bool {
		return h[i] < h[j]
	})

	dp := make([]int64, len(h))
	dp[0] = h[0]
	for i := 1; i < len(h); i++ {
		dp[i] = dp[i - 1] + h[i]
	}

	var minCost int64 = 1e18
	var startCost = (dp[len(dp) - 1] - int64(len(dp)) * h[0]) * R

	for i := 1; i < len(h); i++ {
		if h[i] == h[i - 1] {
			continue
		}
		if A + R < M {
			leftCount := i
			rightCount := len(h) - i

			if int64(leftCount) * A > int64(rightCount) * R {
				if minCost > startCost {
					minCost = startCost
				}

			} else {
				k := h[i] - 1

				sumNeg := k * int64(i) - dp[i - 1]
				sumPos := dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

				c := sumNeg * A + sumPos * R

				if minCost > c {
					minCost = c
				}
			}

			left := h[i] * (int64(i) + 1) - dp[i]
			right := dp[len(dp) - 1] - dp[i] - h[i] * (int64(len(h)) - int64(i) - 1)

			startCost = left * A + right * R

		} else {
			var left = int64(i)
			var right = int64(len(h) - i)
			sMinus := left * h[i - 1] - dp[i - 1]
			sPlus := dp[len(dp) - 1] - dp[i - 1] - right * h[i - 1]

			if sMinus >= sPlus {
				if int64(len(h)) * A > right * M {
					if minCost > startCost {
						minCost = startCost
					}

				} else {
					k := h[i] - 1

					sumNeg := k * int64(i) - dp[i - 1]
					sumPos := dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

					c := (sumNeg - sumPos) * A + sumPos * M

					if minCost > c {
						minCost = c
					}
				}

				leftSum := h[i] * (int64(i) + 1) - dp[i]
				rightSum := dp[len(dp) - 1] - dp[i] - h[i] * (int64(len(h)) - int64(i) - 1)

				startCost = (leftSum - rightSum) * A + rightSum * M

			} else {
				if left * M > (left + right) * R {
					diff := sPlus - sMinus
					heightDiff := h[i] - h[i - 1]

					if heightDiff > diff/int64(len(h)) {
						if right * M > (left + right) * A {
							k := h[i] - 1

							sumNeg := k * int64(i) - dp[i - 1]
							sumPos := dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

							c := (sumNeg - sumPos) * A + sumPos * M

							var min int64
							if c > startCost {
								min = startCost
							} else {
								min =  c
							}

							if minCost > min {
								minCost = min
							}

						} else {
							if minCost > startCost {
								minCost = startCost
							}
						}

					} else {
						if minCost > startCost {
							minCost = startCost
						}
					}
				} else {
					diff := sPlus - sMinus
					heightDiff := h[i] - h[i - 1]

					if heightDiff > diff/int64(len(h)) {

						//todo

						if right * M > (left + right) * A {
							k := h[i] - 1

							sumNeg := k * int64(i) - dp[i - 1]
							sumPos := dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

							c1 := (sumNeg - sumPos) * A + sumPos * M

							k = diff/int64(len(h))

							sumNeg = k * int64(i) - dp[i - 1]
							sumPos = dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

							c2 := (sumPos - sumNeg) * R + sumNeg * M

							var min int64

							if c1 > c2 {
								min = c2
							} else {
								min = c1
							}

							if minCost > min {
								minCost = min
							}
						} else {

							k := diff/int64(len(h))

							k += h[i - 1]

							sumNeg := k * int64(i) - dp[i - 1]
							sumPos := dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

							c2 := (sumPos - sumNeg) * R + sumNeg * M

							if minCost > c2 {
								minCost = c2
							}
						}

					} else {
						k := h[i] - 1

						sumNeg := k * int64(i) - dp[i - 1]
						sumPos := dp[len(dp) - 1] - dp[i - 1] - k * int64(len(h) - i)

						c := (sumPos - sumNeg) * R + sumNeg * M

						if minCost > c {
							minCost = c
						}
					}
				}

				leftSum := h[i] * (int64(i) + 1) - dp[i]
				rightSum := dp[len(dp) - 1] - dp[i] - h[i] * (int64(len(h)) - int64(i) - 1)

				if leftSum > rightSum {
					startCost = (leftSum - rightSum) * A + rightSum * M
				} else {
					startCost = (rightSum - leftSum) * R + leftSum * M
				}

				if minCost > startCost {
					minCost = startCost
				}

			}
		}

	}

	return minCost
}

func doBs(h []int64, target int64) int {
	lo, hi := 0, len(h) - 1

	for ;; {
		if hi - lo < 3 {
			for j := lo ; j <= hi; j++ {
				if h[j] <= target {
					continue
				}
				return j
			}
			return -1
		}

		m := (lo  + hi) /2

		if h[m] > target {
			hi = m
		} else {
			lo = m
		}
	}
}

package main

import (
	"fmt"
	"sort"
)

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

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

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

const MAXN = 100010

var (
	n, a, r, m int
	arr        [MAXN]int
	ar         []int
	sum        [MAXN]int64
)

func find_lm(ar []int, h int) (lt, mt int64) {
	lt_i := sort.Search(len(ar), func(i int) bool { return ar[i] >= h }) - 1
	mt_i := sort.Search(len(ar), func(i int) bool { return ar[i] > h })

	lt, mt = 0, 0
	if lt_i >= 0 {
		lt = sum[lt_i]
	}
	lt = int64(lt_i + 1) * int64(h) - lt;

	mt = sum[n - 1]
	if mt_i > 0 {
		mt -= sum[mt_i - 1]
	}
	mt = mt - int64(n - mt_i) * int64(h);

	return
}

func Tern(mx int, f func(i int) int64) (i int, val int64) {
	lo, hi := 0, mx
	for lo < hi {
		mid := lo + (hi - lo) / 2
		if f(mid) > f(mid + 1) {
			lo = mid + 1
		} else {
			hi = mid
		}
	}
	return lo, f(lo)
}

func main() {
	fmt.Scanf("%d %d %d %d", &n, &a, &r, &m)

	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &arr[i])
	}

	ar = arr[:n]
	sort.Ints(ar)
	for i := 0; i < n; i++ {
		sum[i] = int64(ar[i])
		if i > 0 {
			sum[i] += sum[i - 1]
		}
	}

	max_height := arr[n - 1]

	_, cost1 := Tern(max_height, func(h int) int64 {
		lt, mt := find_lm(ar, h)
		return lt*int64(a) + mt*int64(r)
	})

	_, cost2 := Tern(max_height, func(h int) int64 {
		lt, mt := find_lm(ar, h)
		to_move := Min(lt, mt)
		ret := to_move*int64(m) + (lt-to_move)*int64(a) + (mt-to_move)*int64(r)
		//fmt.Println(h, lt, mt, ret)
		return ret
	})

	fmt.Println(Min(cost1, cost2))
}


package main

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

func btoi(b bool) int {
	if b {
		return 1
	} else {
		return 0
	}
}
func main() {
	var n, m int
	in := bufio.NewReader(os.Stdin)
	fmt.Fscan(in, &n, &m)
	pos := make([]bool, n*m)
	for i := 0; i < n; i++ {
		for k := 0; k < m; k++ {
			index := i*m + k
			fmt.Fscan(in, &pos[index])
		}
	}

	flagrow := make([]bool, n)
	flagcolumn := make([]bool, m)
	ans := 0
	for index := 0; index < n*m; index++ {
		i := index / m
		k := index % m
		if pos[index] {
			flagrow[i] = true
			flagcolumn[k] = true
		} else {
			ans += btoi(flagrow[i])
			ans += btoi(flagcolumn[k])
		}
	}

	flagrow = make([]bool, n)
	flagcolumn = make([]bool, m)
	for index := n*m - 1; index >= 0; index-- {
		i := index / m
		k := index % m
		if pos[index] {
			flagrow[i] = true
			flagcolumn[k] = true
		} else {
			ans += btoi(flagrow[i])
			ans += btoi(flagcolumn[k])
		}
	}

	fmt.Println(ans)
}

package main

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

func main() {
	reader := bufio.NewReaderSize(os.Stdin, 1<<13)
	n, m := ReadInt(reader), ReadInt(reader)
	grid := make([][]int, n)
	rowSum := make([][]int, n)
	for i := 0; i < n; i++ {
		grid[i] = make([]int, m)
		rowSum[i] = make([]int, m)
		for j := 0; j < m; j++ {
			grid[i][j] = ReadInt(reader)
			rowSum[i][j] = grid[i][j]
			if j > 0 {
				rowSum[i][j] += rowSum[i][j-1]
			}
		}
	}
	colSum := make([][]int, m)
	for i := 0; i < m; i++ {
		colSum[i] = make([]int, n)
		for j := 0; j < n; j++ {
			colSum[i][j] = grid[j][i]
			if j > 0 {
				colSum[i][j] += colSum[i][j-1]
			}
		}
	}
	fmt.Println(countPositions(grid, rowSum, colSum))
}

func countPositions(grid, rowSum, colSum [][]int) int {
	count := 0
	for i, row := range grid {
		for j, col := range row {
			if col == 0 {
				count += contains(rowSum[i], 0, j)
				count += contains(rowSum[i], j, len(rowSum[i])-1)
				count += contains(colSum[j], 0, i)
				count += contains(colSum[j], i, len(colSum[j])-1)
			}
		}
	}
	return count
}

func contains(prefixSum []int, start, end int) int {
	total := prefixSum[end]
	if start > 0 {
		total -= prefixSum[start-1]
	}
	if total > 0 {
		return 1
	}
	return 0
}

func ReadInt(reader *bufio.Reader) int {
	b, err := reader.ReadByte()
	for !isValid(b, err) {
		b, err = reader.ReadByte()
	}
	res := 0
	for isValid(b, err) {
		res = res*10 + int(b-'0')
		b, err = reader.ReadByte()
	}
	return res
}

func isValid(b byte, err error) bool {
	return err == nil && '0' <= b && b <= '9'
}

package main

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

func solve() {
    dirs := [][]int{
        []int{0, -1},
        []int{0, 1},
        []int{-1, 0},
        []int{1, 0},
    }
    n, m := readInt(), readInt()
    a := make([][]int, n)
    for i := 0; i < n; i++ {
        a[i] = readIntArray(m)
    }

    mem := make([][][]int, len(dirs))
    for dir := range dirs {
        mem[dir] = make([][]int, n)
        for i := 0; i < n; i++ {
            mem[dir][i] = make([]int, m)
        }
    }

    var dp func(i, j, dir int) bool
    dp = func(i, j, dir int) bool {
        if i < 0 || i >= n || j < 0 || j >= m {
            return false
        }
        m := mem[dir][i][j]
        if m == 0 {
            d, v := dirs[dir], -1
            if a[i][j] == 1 || dp(i+d[0], j+d[1], dir) {
                v = 1
            }
            mem[dir][i][j] = v
        }
        return mem[dir][i][j] == 1
    }

    res := 0
    for dir := range dirs {
        for i := 0; i < n; i++ {
            for j := 0; j < m; j++ {
                if a[i][j] == 0 && dp(i, j, dir) {

                    res++
                }
            }
        }
    }

    fmt.Println(res)
}

var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)

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

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

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

func min(x, y int) int {
	return x + y - max(x, y)
}

// 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 readArray(n int) []int {
	res := make([]int, n)
	for i := 0; i < n; i++ {
		res[i] = readInt()
	}
	return res
}

/* Sort tempalte
func (a ) Len() int           { return len(a) }
func (a ) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ) Less(i, j int) bool { return  }
*/

package main

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

var bufin *bufio.Reader
var bufout *bufio.Writer

func main() {
	bufin = bufio.NewReader(os.Stdin)
	bufout = bufio.NewWriter(os.Stdout)
	defer bufout.Flush()

	var n, m int
	fmt.Fscanf(bufin, "%d %d\n", &n, &m)
	a := make([][]int, n+2)
	left := make([][]int, n+2)
	right := make([][]int, n+2)
	up := make([][]int, n+2)
	down := make([][]int, n+2)
	for i := 0; i <= n+1; i++ {
		a[i] = make([]int, m+2)
		left[i] = make([]int, m+2)
		right[i] = make([]int, m+2)
		up[i] = make([]int, m+2)
		down[i] = make([]int, m+2)
	}
	for i := 1; i <= n; i++ {
		for j := 1; j <= m; j++ {
			fmt.Fscanf(bufin, "%d\n", &a[i][j])
		}
	}

	for i := 1; i <= n; i++ {
		for j := 1; j <= m; j++ {
			if (left[i][j-1] == 1) || (a[i][j-1] == 1) {
				left[i][j] = 1
			}
		}
		for j := m; j >= 1; j-- {
			if (right[i][j+1] == 1) || (a[i][j+1] == 1) {
				right[i][j] = 1
			}
		}
	}

	for j := 1; j <= m; j++ {
		for i := 1; i <= n; i++ {
			if (up[i-1][j] == 1) || (a[i-1][j] == 1) {
				up[i][j] = 1
			}
		}
		for i := n; i >= 1; i-- {
			if (down[i+1][j] == 1) || (a[i+1][j] == 1) {
				down[i][j] = 1
			}
		}
	}

	res := 0
	for i := 1; i <= n; i++ {
		for j := 1; j <= m; j++ {
			if a[i][j] == 0 {
				res += left[i][j]
				res += right[i][j]
				res += up[i][j]
				res += down[i][j]
			}
		}
	}

	fmt.Fprintf(bufout, "%d\n", res)
}

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	var word string
	fmt.Scan(&word)
	fmt.Println(replace(word))
}

func replace(word string) string {
	ans := ""
	for i := 0; i < len(word); i++ {
		if word[i] == 'o' {
			last := findLast(word, i)
			if last > i {
				ans += "***"
				i = last
			} else {
				ans += string(word[i])
			}
		} else {
			ans += string(word[i])
		}
	}
	return string(ans)
}

func findLast(word string, pos int) int {
	for i := pos; i < len(word); i++ {
		expected := byte('o')
		if (i-pos)&1 == 1 {
			expected = 'g'
		}
		if word[i] != expected {
			if word[i-1] == 'o' {
				return i - 1
			} else {
				return i - 2
			}
		}
	}
	return len(word) - 1
}