You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.

The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.

Print minimal r so that each city will be covered by cellular network.

package main

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

var bufin *bufio.Reader
var bufout *bufio.Writer
var n, m int
var a, b []int

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

func nearest(x int) int {
	left := 0
	right := m - 1

	for right-left >= 3 {
		i1 := left + (right-left)/3
		i2 := right - (right-left)/3
		if f(x, b[i1]) < f(x, b[i2]) {
			right = i2
		} else {
			left = i1
		}
	}

	best := f(x, b[left])
	for i := left + 1; i <= right; i++ {
		d := f(x, b[i])
		if d < best {
			best = d
		}
	}

	return best
}

func unique(a []int, n *int) {
	p := 1
	for i := 1; i < *n; i++ {
		if a[i] > a[i-1] {
			a[p] = a[i]
			p++
		}
	}
	*n = p
}

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

	fmt.Fscan(bufin, &n, &m)

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

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

	unique(a, &n)
	unique(b, &m)

	r := 0
	for i := 0; i < n; i++ {
		d := nearest(a[i])
		if d > r {
			r = d
		}
	}

	fmt.Fprintln(bufout, r)
}

package main

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

var bufin *bufio.Reader
var bufout *bufio.Writer
var n, m int
var a, b []int

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

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

	fmt.Fscan(bufin, &n, &m)

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

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

	r := 0
	j := 0
	for i := 0; i < n; i++ {
		for j+1 < m && b[j+1] < a[i] {
			j++
		}

		d := abs(a[i] - b[j])
		if j+1 < m && d > b[j+1]-a[i] {
			d = b[j+1] - a[i]
		}

		if r < d {
			r = d
		}
	}

	fmt.Fprintln(bufout, r)
}

package main

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

var bufin *bufio.Reader
var bufout *bufio.Writer
var n, m, n1, m1 int
var a, b, a1, b1 []int

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

func nearest(x int) int {
	left := 0
	right := m - 1

	for right-left >= 3 {
		i1 := left + (right-left)/3
		i2 := right - (right-left)/3
		if f(x, b[i1]) < f(x, b[i2]) {
			right = i2
		} else {
			left = i1
		}
	}

	best := f(x, b[left])
	for i := left + 1; i <= right; i++ {
		d := f(x, b[i])
		if d < best {
			best = d
		}
	}

	return best
}

func doit() int {
	n1 = 0
	a1 = make([]int, n)
	for i := 0; i < n; i++ {
		if (i == 0) || (a[i] != a[i-1]) {
			a1[n1] = a[i]
			n1++
		}
	}

	m1 = 0
	b1 = make([]int, m)
	for i := 0; i < m; i++ {
		if (i == 0) || (b[i] != b[i-1]) {
			b1[m1] = b[i]
			m1++
		}
	}

	n = n1
	m = m1
	a = a1
	b = b1

	r := 0
	for i := 0; i < n; i++ {
		d := nearest(a[i])
		if d > r {
			r = d
		}
	}
	return r
}

func covered(x int, r int) bool {
	for i := 0; i < m; i++ {
		if f(x, b[i]) <= r {
			return true
		}
	}
	return false
}

func good(r int) bool {
	for i := 0; i < n; i++ {
		if !covered(a[i], r) {
			return false
		}
	}
	return true
}

func brute() int {
	r := 0
	for !good(r) {
		r++
	}
	return r
}

func gen() {
	n = rand.Int()%20 + 1
	m = rand.Int()%20 + 1
	fmt.Fprintln(bufout, n, m)

	a = make([]int, n)
	a[0] = rand.Int()%10 - 20
	fmt.Fprint(bufout, a[0], " ")
	for i := 1; i < n; i++ {
		a[i] = a[i-1] + rand.Int()%10
		fmt.Fprint(bufout, a[i], " ")
	}

	fmt.Fprintln(bufout)

	b = make([]int, m)
	b[0] = rand.Int()%10 - 20
	fmt.Fprint(bufout, b[0], " ")
	for i := 1; i < m; i++ {
		b[i] = b[i-1] + rand.Int()%10
		fmt.Fprint(bufout, b[i], " ")
	}

	fmt.Fprintln(bufout)
}

func test() {
	rand.Seed(time.Now().UTC().UnixNano())

	for i := 0; i < 10000; i++ {
		fmt.Fprintln(bufout, "\n>>> Test", i+1)
		gen()
		r := doit()
		e := brute()
		g := r == e
		fmt.Fprintln(bufout, r, e, g)
		if !g {
			break
		}
	}
}

func solve() {
	fmt.Fscan(bufin, &n, &m)

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

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

	r := doit()
	fmt.Fprintln(bufout, r)
}

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

	// test()
	solve()
}

package main

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

var bufin *bufio.Reader
var bufout *bufio.Writer
var n, m int
var a, b []int

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

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

	fmt.Fscan(bufin, &n, &m)

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

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

	r := 0
	j := 0
	for i := 0; i < n; i++ {
		for j+1 < m && abs(a[i]-b[j]) >= abs(a[i]-b[j+1]) {
			j++
		}
		d := abs(a[i] - b[j])
		if r < d {
			r = d
		}
	}

	fmt.Fprintln(bufout, r)
}

package main

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

func ternary(a int, m int, b []int) int {
	f := func(j int) int {
		if a < b[j] {
			return b[j] - a
		}
		return a - b[j]
	}

	left := 0
	right := m - 1

	for right-left >= 3 {
		j1 := left + (right-left)/3
		j2 := right - (right-left)/3
		if f(j1) < f(j2) {
			right = j2
		} else {
			left = j1
		}
	}

	minimum := f(left)
	for j := left + 1; j <= right; j++ {
		d := f(j)
		if d < minimum {
			minimum = d
		}
	}

	return minimum
}

func solution(n int, m int, a []int, b []int) int {
	p := 1
	for i := 1; i < m; i++ {
		if b[i] > b[i-1] {
			b[p] = b[i]
			p++
		}
	}
	m = p

	result := 0
	for i := 0; i < n; i++ {
		d := ternary(a[i], m, b)
		if d > result {
			result = d
		}
	}

	return result
}

func main() {
	var bufin *bufio.Reader
	var bufout *bufio.Writer
	var n, m int
	var a, b []int

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

	fmt.Fscan(bufin, &n, &m)

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

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

	fmt.Fprintln(bufout, solution(n, m, a, b))
}

package main

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

var scanner *bufio.Scanner

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}

func getUniques(num int) []int {
  previous := getI()
  unique := []int{ previous }
  for i := 1; i < num; i++ {
    current := getI()
    if current != previous {
      unique = append(unique, current)
      previous = current
    }
  }
  return unique
}

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

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer := bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  n, m := getI(), getI()
  cities := getUniques(n)
  towers := getUniques(m)
  n = len(cities)
  m = len(towers)

  result := 0
  if cities[0] < towers[0] {
    result = towers[0] - cities[0]
  }
  if towers[m - 1] < cities[n - 1] {
    result = max(result, cities[n - 1] - towers[m - 1])
  }
  if len(towers) == 1 {
    writer.WriteString(fmt.Sprintf("%d\n", result))
    return
  }

  right := 1
  for _, city := range cities {
    for towers[right] < city {
      right++
      if right == m {
        break
      }
    }
    if right == m {
      break
    }
    distance := min(city - towers[right - 1], towers[right] - city)
    result = max(result, distance)
  }

  writer.WriteString(fmt.Sprintf("%d\n", result))
}

package main

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

var n, m int
var a, b []int
var r int

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

func nearest(x int) int {
	left := 0
	right := m - 1

	for right-left >= 3 {
		i1 := left + (right-left)/3
		i2 := right - (right-left)/3

		y1 := b[i1]
		y2 := b[i2]
		if f(x, y1) < f(x, y2) {
			right = i2
		} else {
			left = i1
		}
	}

	best := f(x, b[left])
	for i := left + 1; i <= right; i++ {
		d := f(x, b[i])
		if d < best {
			best = d
		}
	}

	return best
}

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

	fmt.Fscan(bufin, &n, &m)

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

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

	r = 0
	for i := 0; i < n; i++ {
		d := nearest(a[i])
		if d > r {
			r = d
		}
	}

	fmt.Fprint(bufout, r)
}

package main

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

var bufin *bufio.Reader
var bufout *bufio.Writer
var n, m int
var a, b []int

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

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

	fmt.Fscan(bufin, &n, &m)

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

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

	r := 0
	j := 0
	for i := 0; i < n; i++ {
		for j+1 < m && abs(a[i]-b[j]) > abs(a[i]-b[j+1]) {
			j++
		}
		d := abs(a[i] - b[j])
		if r < d {
			r = d
		}
	}

	fmt.Fprintln(bufout, r)
}

package main

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

var bufin *bufio.Reader
var bufout *bufio.Writer
var n, m, n1, m1 int
var a, b, a1, b1 []int

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

func nearest(x int) int {
	left := 0
	right := m - 1

	for right-left >= 3 {
		i1 := left + (right-left)/3
		i2 := right - (right-left)/3
		if f(x, b[i1]) < f(x, b[i2]) {
			right = i2
		} else {
			left = i1
		}
	}

	best := f(x, b[left])
	for i := left + 1; i <= right; i++ {
		d := f(x, b[i])
		if d < best {
			best = d
		}
	}

	return best
}

func doit() int {
	n1 = 0
	a1 = make([]int, n)
	for i := 0; i < n; i++ {
		if (i == 0) || (a[i] != a[i-1]) {
			a1[n1] = a[i]
			n1++
		}
	}

	m1 = 0
	b1 = make([]int, m)
	for i := 0; i < m; i++ {
		if (i == 0) || (b[i] != b[i-1]) {
			b[m1] = b[i]
			m1++
		}
	}

	n = n1
	m = m1
	a = a1
	b = b1

	r := 0
	for i := 0; i < n; i++ {
		d := nearest(a[i])
		if d > r {
			r = d
		}
	}
	return r
}

func covered(x int, r int) bool {
	for i := 0; i < m; i++ {
		if f(x, b[i]) <= r {
			return true
		}
	}
	return false
}

func good(r int) bool {
	for i := 0; i < n; i++ {
		if !covered(a[i], r) {
			return false
		}
	}
	return true
}

func brute() int {
	r := 0
	for !good(r) {
		r++
	}
	return r
}

func gen() {
	n = rand.Int()%20 + 1
	m = rand.Int()%20 + 1
	fmt.Fprintln(bufout, n, m)

	a = make([]int, n)
	a[0] = rand.Int()%10 - 20
	fmt.Fprint(bufout, a[0], " ")
	for i := 1; i < n; i++ {
		a[i] = a[i-1] + rand.Int()%10
		fmt.Fprint(bufout, a[i], " ")
	}

	fmt.Fprintln(bufout)

	b = make([]int, m)
	b[0] = rand.Int()%10 - 20
	fmt.Fprint(bufout, b[0], " ")
	for i := 1; i < m; i++ {
		b[i] = b[i-1] + rand.Int()%10
		fmt.Fprint(bufout, b[i], " ")
	}

	fmt.Fprintln(bufout)
}

func test() {
	rand.Seed(time.Now().UTC().UnixNano())

	for i := 0; i < 10000; i++ {
		fmt.Fprintln(bufout, "\n>>> Test", i+1)
		gen()
		r := doit()
		e := brute()
		g := r == e
		fmt.Fprintln(bufout, r, e, g)
		if !g {
			break
		}
	}
}

func solve() {
	fmt.Fscan(bufin, &n, &m)

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

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

	r := doit()
	fmt.Fprintln(bufout, r)
}

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

	// test()
	solve()
}


You are given an array $$$a$$$ of length $$$2^n$$$. You should process $$$q$$$ queries on it. Each query has one of the following $$$4$$$ types:   $$$Replace(x, k)$$$ — change $$$a_x$$$ to $$$k$$$;  $$$Reverse(k)$$$ — reverse each subarray $$$[(i-1) \cdot 2^k+1, i \cdot 2^k]$$$ for all $$$i$$$ ($$$i \ge 1$$$);  $$$Swap(k)$$$ — swap subarrays $$$[(2i-2) \cdot 2^k+1, (2i-1) \cdot 2^k]$$$ and $$$[(2i-1) \cdot 2^k+1, 2i \cdot 2^k]$$$ for all $$$i$$$ ($$$i \ge 1$$$);  $$$Sum(l, r)$$$ — print the sum of the elements of subarray $$$[l, r]$$$. Write a program that can quickly process given queries.

The first line contains two integers $$$n$$$, $$$q$$$ ($$$0 \le n \le 18$$$; $$$1 \le q \le 10^5$$$) — the length of array $$$a$$$ and the number of queries. The second line contains $$$2^n$$$ integers $$$a_1, a_2, \ldots, a_{2^n}$$$ ($$$0 \le a_i \le 10^9$$$). Next $$$q$$$ lines contains queries — one per line. Each query has one of $$$4$$$ types:    "$$$1$$$ $$$x$$$ $$$k$$$" ($$$1 \le x \le 2^n$$$; $$$0 \le k \le 10^9$$$) — $$$Replace(x, k)$$$;  "$$$2$$$ $$$k$$$" ($$$0 \le k \le n$$$) — $$$Reverse(k)$$$;  "$$$3$$$ $$$k$$$" ($$$0 \le k < n$$$) — $$$Swap(k)$$$;  "$$$4$$$ $$$l$$$ $$$r$$$" ($$$1 \le l \le r \le 2^n$$$) — $$$Sum(l, r)$$$.  It is guaranteed that there is at least one $$$Sum$$$ query.

Print the answer for each $$$Sum$$$ query.

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

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


The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts $$$h$$$ hours and each hour lasts $$$m$$$ minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from $$$0$$$ to $$$h-1$$$ and minutes are numbered from $$$0$$$ to $$$m-1$$$.  That's how the digits are displayed on the clock. Please note that digit $$$1$$$ is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day).The image of the clocks in the mirror is reflected against a vertical axis.  The reflection is not a valid time.The reflection is a valid time with $$$h=24$$$, $$$m = 60$$$. However, for example, if $$$h=10$$$, $$$m=60$$$, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment $$$s$$$ and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid.It can be shown that with any $$$h$$$, $$$m$$$, $$$s$$$ such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest.You are asked to solve the problem for several test cases.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. The next $$$2 \cdot T$$$ lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers $$$h$$$, $$$m$$$ ($$$1 \le h, m \le 100$$$). The second line contains the start time $$$s$$$ in the described format HH:MM.

For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct.

NoteIn the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct.

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


Consider a sequence of distinct integers $$$a_1, \ldots, a_n$$$, each representing one node of a graph. There is an edge between two nodes if the two values are not coprime, i. e. they have a common divisor greater than $$$1$$$.There are $$$q$$$ queries, in each query, you want to get from one given node $$$a_s$$$ to another $$$a_t$$$. In order to achieve that, you can choose an existing value $$$a_i$$$ and create new value $$$a_{n+1} = a_i \cdot (1 + a_i)$$$, with edges to all values that are not coprime with $$$a_{n+1}$$$. Also, $$$n$$$ gets increased by $$$1$$$. You can repeat that operation multiple times, possibly making the sequence much longer and getting huge or repeated values. What's the minimum possible number of newly created nodes so that $$$a_t$$$ is reachable from $$$a_s$$$?Queries are independent. In each query, you start with the initial sequence $$$a$$$ given in the input.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$2 \leq n \leq 150\,000$$$, $$$1 \leq q \leq 300\,000$$$) — the size of the sequence and the number of queries. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \ldots, a_n$$$ ($$$2 \leq a_i \leq 10^6$$$, $$$a_i \neq a_j$$$ if $$$i \ne j$$$). The $$$j$$$-th of the following $$$q$$$ lines contains two distinct integers $$$s_j$$$ and $$$t_j$$$ ($$$1 \leq s_j, t_j \leq n$$$, $$$s_j \neq t_j$$$) — indices of nodes for $$$j$$$-th query.

Print $$$q$$$ lines. The $$$j$$$-th line should contain one integer: the minimum number of new nodes you create in order to move from $$$a_{s_j}$$$ to $$$a_{t_j}$$$.

NoteIn the first example, you can first create new value $$$2 \cdot 3 = 6$$$ or $$$10 \cdot 11 = 110$$$ or $$$3 \cdot 4 = 12$$$. None of that is needed in the first query because you can already get from $$$a_1 = 2$$$ to $$$a_2 = 10$$$.In the second query, it's optimal to first create $$$6$$$ or $$$12$$$. For example, creating $$$6$$$ makes it possible to get from $$$a_1 = 2$$$ to $$$a_3 = 3$$$ with a path $$$(2, 6, 3)$$$.  In the last query of the second example, we want to get from $$$a_3 = 7$$$ to $$$a_5 = 25$$$. One way to achieve that is to first create $$$6 \cdot 7 = 42$$$ and then create $$$25 \cdot 26 = 650$$$. The final graph has seven nodes and it contains a path from $$$a_3 = 7$$$ to $$$a_5 = 25$$$.

package main

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

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

func Read() int {
	in.Scan()
	r := 0
	for _, v := range in.Bytes() {
		r = r*10 + int(v-'0')
	}
	return r
}

func init() {
	const MaxInt = int(^uint(0) >> 1)
	in.Buffer(make([]byte, 1<<12), MaxInt)
	in.Split(bufio.ScanWords)
}

const N = 1000100

type pair struct {
	x, y int
}

var (
	p    [N][]int
	a, c [N]int
	mp   map[pair]bool
)

func get(x int) int {
	if x == c[x] {
		return x
	}
	c[x] = get(c[x])
	return c[x]
}

func un(x, y int) {
	x = get(x)
	y = get(y)
	c[x] = c[y]
}

func check(a []int, b []int) bool {
	for _, i := range a {
		for _, j := range b {
			if get(i) == get(j) {
				return true
			}
		}
	}
	return false
}

func check2(a []int, b []int) bool {
	for _, i := range a {
		for _, j := range b {
			if mp[pair{get(i), get(j)}] || mp[pair{get(j), get(i)}] {
				return true
			}
		}
	}
	return false
}

func main() {
	defer out.Flush()
	for i := 2; i < N; i++ {
		if len(p[i]) == 0 {
			for j := i; j < N; j += i {
				p[j] = append(p[j], i)
			}
		}
	}
	n := Read()
	q := Read()
	for i := 0; i < N; i++ {
		c[i] = i
	}
	mp = make(map[pair]bool)
	for i := 0; i < n; i++ {
		a[i] = Read()
		for j := 1; j < len(p[a[i]]); j++ {
			un(p[a[i]][j-1], p[a[i]][j])
		}
	}
	for i := 0; i < n; i++ {
		for _, j := range p[a[i]] {
			for _, k := range p[a[i]+1] {
				mp[pair{get(j), get(k)}] = true
			}
		}
		for _, j := range p[a[i]+1] {
			for _, k := range p[a[i]+1] {
				mp[pair{get(j), get(k)}] = true
			}
		}
	}
	for i := 0; i < q; i++ {
		x := Read() - 1
		y := Read() - 1
		if check(p[a[x]][:], p[a[y]][:]) {
			Fprintln(out, 0)
		} else if check2(p[a[x]][:], p[a[y]][:]) {
			Fprintln(out, 1)
		} else {
			Fprintln(out, 2)
		}
	}
}

package main

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

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

func Read() int {
	in.Scan()
	r := 0
	for _, v := range in.Bytes() {
		r = r*10 + int(v-'0')
	}
	return r
}

func init() {
	const MaxInt = int(^uint(0) >> 1)
	in.Buffer(make([]byte, 1<<12), MaxInt)
	in.Split(bufio.ScanWords)
}

const N = 1000100

type pair struct {
	x, y int
}

var (
	p    [N][]int
	a, c [N]int
	mp   map[pair]bool
)

func get(x int) int {
	if x == c[x] {
		return x
	}
	c[x] = get(c[x])
	return c[x]
}

func un(x, y int) {
	x = get(x)
	y = get(y)
	c[x] = c[y]
}

func check(a []int, b []int) bool {
	for _, i := range a {
		for _, j := range b {
			if get(i) == get(j) {
				return true
			}
		}
	}
	return false
}

func check2(a []int, b []int) bool {
	for _, i := range a {
		for _, j := range b {
			if mp[pair{get(i), get(j)}] || mp[pair{get(j), get(i)}] {
				return true
			}
		}
	}
	return false
}

func main() {
	defer out.Flush()
	for i := 2; i < N; i++ {
		if len(p[i]) == 0 {
			for j := i; j < N; j += i {
				p[j] = append(p[j], i)
			}
		}
	}
	n := Read()
	q := Read()
	for i := 0; i < N; i++ {
		c[i] = i
	}
	mp = make(map[pair]bool)
	for i := 0; i < n; i++ {
		a[i] = Read()
		for j := 1; j < len(p[a[i]]); j++ {
			un(p[a[i]][j-1], p[a[i]][j])
		}
	}
	for i := 0; i < n; i++ {
		for _, j := range p[a[i]] {
			for _, k := range p[a[i]+1] {
				mp[pair{get(j), get(k)}] = true
			}
		}
	}
	for i := 0; i < q; i++ {
		x := Read() - 1
		y := Read() - 1
		if check(p[a[x]][:], p[a[y]][:]) {
			Fprintln(out, 0)
		} else if check2(p[a[x]][:], p[a[y]][:]) {
			Fprintln(out, 1)
		} else {
			Fprintln(out, 2)
		}
	}
}

package main

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

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

func Read() int {
	in.Scan()
	r := 0
	for _, v := range in.Bytes() {
		r = r*10 + int(v-'0')
	}
	return r
}

func init() {
	const MaxInt = int(^uint(0) >> 1)
	in.Buffer(make([]byte, 1<<12), MaxInt)
	in.Split(bufio.ScanWords)
}

const N = 1000100

type pair struct {
	x, y int
}

var (
	p    [N][]int
	a, c [N]int
	mp   map[pair]bool
)

func get(x int) int {
	if x == c[x] {
		return x
	}
	c[x] = get(c[x])
	return c[x]
}

func un(x, y int) {
	x = get(x)
	y = get(y)
	c[x] = c[y]
}

func check(a []int, b []int) bool {
	for _, i := range a {
		for _, j := range b {
			if get(i) == get(j) {
				return true
			}
		}
	}
	return false
}

func check2(a []int, b []int) bool {
	for _, i := range a {
		for _, j := range b {
			if mp[pair{i, j}] {
				return true
			}
		}
	}
	return false
}

func main() {
	defer out.Flush()
	for i := 2; i < N; i++ {
		if len(p[i]) == 0 {
			for j := i; j < N; j += i {
				p[j] = append(p[j], i)
			}
		}
	}
	n := Read()
	q := Read()
	for i := 0; i < N; i++ {
		c[i] = i
	}
	mp = make(map[pair]bool)
	for i := 0; i < n; i++ {
		a[i] = Read()
		for j := 1; j < len(p[a[i]]); j++ {
			un(p[a[i]][j-1], p[a[i]][j])
		}
		for _, j := range p[a[i]] {
			for _, k := range p[a[i]+1] {
				mp[pair{j,k}] = true
			}
		}
		for _, j := range p[a[i]+1] {
			for k := range p[a[i]+1] {
				mp[pair{j,k}] = true
			}
		}
	}
	for i := 0; i < q; i++ {
		x := Read() - 1
		y := Read() - 1
		if check(p[a[x]][:], p[a[y]][:]) {
			Fprintln(out, 0)
		} else if check2(p[a[x]][:], p[a[y]][:]) {
			Fprintln(out, 1)
		} else {
			Fprintln(out, 2)
		}
	}
}

package main

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

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

func Read() int {
	in.Scan()
	r := 0
	for _, v := range in.Bytes() {
		r = r*10 + int(v-'0')
	}
	return r
}

func init() {
	const MaxInt = int(^uint(0) >> 1)
	in.Buffer(make([]byte, 1<<12), MaxInt)
	in.Split(bufio.ScanWords)
}

const N = 1000100

var (
	p    [N][]int
	a, c [N]int
)

func get(x int) int {
	if x == c[x] {
		return x
	}
	c[x] = get(c[x])
	return c[x]
}

func un(x, y int) {
	x = get(x)
	y = get(y)
	c[x] = c[y]
}

func check(a []int, b []int) bool {
	for _, i := range a {
		for _, j := range b {
			if get(i) == get(j) {
				return true
			}
		}
	}
	return false
}

func main() {
	defer out.Flush()
	for i := 2; i < N; i++ {
		if len(p[i]) == 0 {
			for j := i; j < N; j += i {
				p[j] = append(p[j], i)
			}
		}
	}
	n := Read()
	q := Read()
	for i := 0; i < N; i++ {
		c[i] = i
	}
	for i := 0; i < n; i++ {
		a[i] = Read()
		for j := 1; j < len(p[a[i]]); j++ {
			un(p[a[i]][j-1], p[a[i]][j])
		}
	}
	for i := 0; i < q; i++ {
		x := Read()
		y := Read()
		x--
		y--
		if check(p[a[x]][:], p[a[y]][:]) {
			Fprintln(out, 0)
		} else if check(p[a[x]+1][:], p[a[y]][:]) || check(p[a[x]][:], p[a[y]+1][:]) {
			Fprintln(out, 1)
		} else {
			Fprintln(out, 2)
		}
	}
}

package main

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

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

func Read() int {
	in.Scan()
	r := 0
	for _, v := range in.Bytes() {
		r = r*10 + int(v-'0')
	}
	return r
}

func init() {
	const MaxInt = int(^uint(0) >> 1)
	in.Buffer(make([]byte, 1<<12), MaxInt)
	in.Split(bufio.ScanWords)
}

const N = 1000100

var (
	p    [N][]int
	a, c [N]int
)

func get(x int) int {
	if x == c[x] {
		return x
	}
	c[x] = get(c[x])
	return c[x]
}

func un(x, y int) {
	x = get(x)
	y = get(y)
	c[x] = c[y]
}

func check(a []int, b []int) bool {
	for _, i := range a {
		for _, j := range b {
			if c[i] == c[j] {
				return true
			}
		}
	}
	return false
}

func main() {
	defer out.Flush()
	for i := 2; i < N; i++ {
		if len(p[i]) == 0 {
			for j := i; j < N; j += i {
				p[j] = append(p[j], i)
			}
		}
	}
	n := Read()
	q := Read()
	for i := 0; i < N; i++ {
		c[i] = i
	}
	for i := 0; i < n; i++ {
		a[i] = Read()
		for j := 1; j < len(p[a[i]]); j++ {
			un(p[a[i]][j-1], p[a[i]][j])
		}
	}
	for i := 0; i < q; i++ {
		x := Read()
		y := Read()
		x--
		y--
		if check(p[a[x]][:], p[a[y]][:]) {
			Fprintln(out, 0)
		} else if check(p[a[x]+1][:], p[a[y]][:]) || check(p[a[x]][:], p[a[y]+1][:]) {
			Fprintln(out, 1)
		} else {
			Fprintln(out, 2)
		}
	}
}