This is the hard version of this problem. In this version, $$$n \le 5000$$$ holds, and this version has no restriction between $$$x$$$ and $$$y$$$. You can make hacks only if both versions of the problem are solved.You are given two binary strings $$$a$$$ and $$$b$$$, both of length $$$n$$$. You can do the following operation any number of times (possibly zero).   Select two indices $$$l$$$ and $$$r$$$ ($$$l < r$$$).  Change $$$a_l$$$ to $$$(1 - a_l)$$$, and $$$a_r$$$ to $$$(1 - a_r)$$$.  If $$$l + 1 = r$$$, the cost of the operation is $$$x$$$. Otherwise, the cost is $$$y$$$. You have to find the minimum cost needed to make $$$a$$$ equal to $$$b$$$ or say there is no way to do so.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case consists of three lines. The first line of each test case contains three integers $$$n$$$, $$$x$$$, and $$$y$$$ ($$$5 \le n \le 5000$$$, $$$1 \le x, y \le 10^9$$$) — the length of the strings, and the costs per operation. The second line of each test case contains the string $$$a$$$ of length $$$n$$$. The string only consists of digits $$$0$$$ and $$$1$$$. The third line of each test case contains the string $$$b$$$ of length $$$n$$$. The string only consists of digits $$$0$$$ and $$$1$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$5000$$$.

For each test case, if there is no way to make $$$a$$$ equal to $$$b$$$, print $$$-1$$$. Otherwise, print the minimum cost needed to make $$$a$$$ equal to $$$b$$$.

NoteIn the first test case, selecting indices $$$2$$$ and $$$3$$$ costs $$$8$$$, which is the minimum.In the second test case, we can perform the following operations.   Select indices $$$1$$$ and $$$2$$$. It costs $$$2$$$, and $$$a$$$ is 110001 now.  Select indices $$$2$$$ and $$$3$$$. It costs $$$2$$$, and $$$a$$$ is 101001 now.  Select indices $$$3$$$ and $$$4$$$. It costs $$$2$$$, and $$$a$$$ is 100101 now.  Select indices $$$4$$$ and $$$5$$$. It costs $$$2$$$, and $$$a$$$ is 100011 now.  Select indices $$$5$$$ and $$$6$$$. It costs $$$2$$$, and $$$a$$$ is 100000 now. The total cost is $$$10$$$.In the third test case, we cannot make $$$a$$$ equal to $$$b$$$ using any number of operations.In the fourth test case, we can perform the following operations.   Select indices $$$3$$$ and $$$6$$$. It costs $$$3$$$, and $$$a$$$ is 0101011 now.  Select indices $$$4$$$ and $$$6$$$. It costs $$$3$$$, and $$$a$$$ is 0100001 now. The total cost is $$$6$$$.In the fifth test case, we can perform the following operations.   Select indices $$$1$$$ and $$$6$$$. It costs $$$4$$$, and $$$a$$$ is 110000 now.  Select indices $$$2$$$ and $$$3$$$. It costs $$$3$$$, and $$$a$$$ is 101000 now. The total cost is $$$7$$$.In the sixth test case, we don't have to perform any operation.

package main

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

func min(i, j float64) float64 {
	if i < j {
		return i
	}
	return j
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	txt, _ := reader.ReadString('\n')
	t, _ := strconv.Atoi(strings.TrimSpace(txt))
	for ; t > 0; t-- {
		txt, _ = reader.ReadString('\n')
		arr := strings.Split(strings.TrimSpace(txt), " ")
		n, _ := strconv.Atoi(arr[0])
		x, _ := strconv.ParseFloat(arr[1], 64)
		y, _ := strconv.ParseFloat(arr[2], 64)
		txt, _ = reader.ReadString('\n')
		a := strings.TrimSpace(txt)
		txt, _ = reader.ReadString('\n')
		b := strings.TrimSpace(txt)
		d := 0
		c := make([]bool, n, n)
		for i := 0; i < n; i++ {
			c[i] = a[i] != b[i]
			if c[i] {
				d++
			}
		}

		// если нужно поменять нечетное количество элементов, то решения нет
		if d%2 == 1 {
			fmt.Println(-1)
			continue
		}

		if d == 2 {
			var l, r int
			for l = 0; !c[l]; {
				l++
			}
			for r = n - 1; !c[r]; {
				r--
			}

			if l+1 == r {
				fmt.Println(int(min(2*y, x)))
			} else {
				fmt.Println(int(min(float64(r-l)*x, y)))
			}

			continue
		}

		if d == 0 || x >= y {
			fmt.Println(int(float64(d/2) * y))
			continue
		}
		z0 := make([][]float64, n, n)
		z1 := make([][]float64, n, n)
		for i := 0; i < n; i++ {
			z0[i] = make([]float64, n+1, n+1)
			z1[i] = make([]float64, n+1, n+1)
			for j := 0; j <= n; j++ {
				z0[i][j] = math.Inf(1)
				z1[i][j] = math.Inf(1)
			}
		}
		if c[0] {
			z1[0][1] = 0
		} else {
			z0[0][0] = 0
		}
		for i := 1; i < n; i++ {
			if c[i] {
				for j := i + 1; j >= 0; j-- {
					if j <= i {
						z0[i][j] = min(z0[i-1][j+1]+y, z1[i-1][j+1]+x)
					}
					if j > 0 {
						z0[i][j] = min(min(z0[i][j], z0[i-1][j-1]+x), z1[i-1][j-1]+y)
						z1[i][j] = min(z0[i-1][j-1], z1[i-1][j-1])
					}
				}
			} else {
				for j := i + 1; j >= 0; j-- {
					z0[i][j] = min(z0[i-1][j], z1[i-1][j])
					z1[i][j] = min(z0[i-1][j]+y, z1[i-1][j]+x)
					if j > 1 {
						z1[i][j] = min(min(z1[i][j], z0[i-1][j-2]+x), z1[i-1][j-2]+y)
					}
				}
			}
		}
		fmt.Printf("%d\n", int(z0[n-1][0]))
	}
}

package main

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

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

func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func print(a ...interface{})            { fmt.Println(a...) }
func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f+"\n", a...) }

func main() {
	defer writer.Flush()

	var testcases int64
	scanf("%d", &testcases)
  var i int64
	for i = 0; i < testcases; i++ {
		var n, x, y int64
		scanf("%d %d %d", &n, &x, &y)
    var a, b string
    scanf("%s", &a)
    scanf("%s", &b)

		print(solve(n, x, y, a, b))
	}
}

func max(nums ...int64) int64 {
  result := nums[0]
	for _, num := range nums {
		if num > result {
			result = num
		}
	}
	return result
}

func min(nums ...int64) int64 {
  result := nums[0]
  for _, num := range nums {
    if num < result {
      result = num
    }
  }
  return result
}

func solve(n, x, y int64, a, b string) int64 {
  diffs := make([]int64, 0, n)
  var i int64
  for i = 0; i < n; i++ {
    if a[i] != b[i] {
      diffs = append(diffs, i)
    }
  }

  m := int64(len(diffs))

  if m % 2 == 1 {
    return -1
  }

  if x >= y {
    if m == 2 && diffs[0] + 1 == diffs[1] {
      return min(x, y*2)
    }
    return y * m / 2
  }

  dp := make([][]int64, m)
  for i = 0; i < m; i++ {
    dp[i] = make([]int64, m)
    var j int64
    for j = 0; j < m; j++ {
      dp[i][j] = -1
    }
  }
  var dfs func(i, drop int64) int64
  dfs = func(i, drop int64) int64 {
    if i >= m {
      if drop == 0 {
        return 0
      }
      return math.MaxInt64
    }
    if dp[i][drop] != -1 {
      return dp[i][drop]
    }
    result := dfs(i+1, drop+1)
    if drop > 0 {
      this := dfs(i+1, drop-1)
      if this != math.MaxInt64 {
        result = min(result, this + y)
      }
    }
    if i < m-1 {
      this := dfs(i+2, drop)
      if this != math.MaxInt64 {
        result = min(result, this + min(y, x * (diffs[i+1] - diffs[i])))
      }
    }
    dp[i][drop] = result
    return result
  }
  res := dfs(0, 0)
  return res
}

package main

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

func min(i, j float64) float64 {
	if i < j {
		return i
	}
	return j
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	txt, _ := reader.ReadString('\n')
	t, _ := strconv.Atoi(strings.TrimSpace(txt))
	for ; t > 0; t-- {
		txt, _ = reader.ReadString('\n')
		arr := strings.Split(strings.TrimSpace(txt), " ")
		n, _ := strconv.Atoi(arr[0])
		x, _ := strconv.ParseFloat(arr[1], 64)
		y, _ := strconv.ParseFloat(arr[2], 64)
		txt, _ = reader.ReadString('\n')
		a := strings.TrimSpace(txt)
		txt, _ = reader.ReadString('\n')
		b := strings.TrimSpace(txt)
		d := 0
		c := make([]bool, n, n)
		for i := 0; i < n; i++ {
			c[i] = a[i] != b[i]
			if c[i] {
				d++
			}
		}

		// если нужно поменять нечетное количество элементов, то решения нет
		if d%2 == 1 {
			fmt.Println(-1)
			continue
		}

		if d == 2 {
			var l, r int
			for l = 0; !c[l]; {
				l++
			}
			for r = n - 1; !c[r]; {
				r--
			}

			if l+1 == r {
				fmt.Println(min(2*y, x))
			} else {
				fmt.Println(min(float64(r-l)*x, y))
			}

			continue
		}

		if d == 0 || x >= y {
			fmt.Println(float64(d/2) * y)
			continue
		}
		z0 := make([][]float64, n, n)
		z1 := make([][]float64, n, n)
		for i := 0; i < n; i++ {
			z0[i] = make([]float64, n+1, n+1)
			z1[i] = make([]float64, n+1, n+1)
			for j := 0; j <= n; j++ {
				z0[i][j] = math.Inf(1)
				z1[i][j] = math.Inf(1)
			}
		}
		if c[0] {
			z1[0][1] = 0
		} else {
			z0[0][0] = 0
		}
		for i := 1; i < n; i++ {
			if c[i] {
				for j := i + 1; j >= 0; j-- {
					if j <= i {
						z0[i][j] = min(z0[i-1][j+1]+y, z1[i-1][j+1]+x)
					}
					if j > 0 {
						z0[i][j] = min(min(z0[i][j], z0[i-1][j-1]+x), z1[i-1][j-1]+y)
						z1[i][j] = min(z0[i-1][j-1], z1[i-1][j-1])
					}
				}
			} else {
				for j := i + 1; j >= 0; j-- {
					z0[i][j] = min(z0[i-1][j], z1[i-1][j])
					z1[i][j] = min(z0[i-1][j]+y, z1[i-1][j]+x)
					if j > 1 {
						z1[i][j] = min(min(z1[i][j], z0[i-1][j-2]+x), z1[i-1][j-2]+y)
					}
				}
			}
		}
		fmt.Printf("%d\n", int(z0[n-1][0]))
	}
}

package main

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

func min(i, j float64) float64 {
	if i < j {
		return i
	}
	return j
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	txt, _ := reader.ReadString('\n')
	t, _ := strconv.Atoi(strings.TrimSpace(txt))
	for ; t > 0; t-- {
		txt, _ = reader.ReadString('\n')
		arr := strings.Split(strings.TrimSpace(txt), " ")
		n, _ := strconv.Atoi(arr[0])
		x, _ := strconv.ParseFloat(arr[1], 64)
		y, _ := strconv.ParseFloat(arr[2], 64)
		txt, _ = reader.ReadString('\n')
		a := strings.TrimSpace(txt)
		txt, _ = reader.ReadString('\n')
		b := strings.TrimSpace(txt)
		d := 0
		c := make([]bool, n, n)
		for i := 0; i < n; i++ {
			c[i] = a[i] != b[i]
			if c[i] {
				d++
			}
		}

		// если нужно поменять нечетное количество элементов, то решения нет
		if d%2 == 1 {
			fmt.Println(-1)
			continue
		}

		if d == 2 {
			var l, r int
			for l = 0; !c[l]; {
				l++
			}
			for r = n - 1; !c[r]; {
				r--
			}

			if l+1 == r {
				fmt.Println(min(2*y, x))
			} else {
				fmt.Println(min(float64(r-l)*x, y))
			}

			continue
		}

		if d == 0 || x >= y {
			fmt.Println(float64(d/2) * y)
			continue
		}
		z0 := make([][]float64, n, n)
		z1 := make([][]float64, n, n)
		for i := 0; i < n; i++ {
			z0[i] = make([]float64, n+1, n+1)
			z1[i] = make([]float64, n+1, n+1)
			for j := 0; j <= n; j++ {
				z0[i][j] = math.Inf(1)
				z1[i][j] = math.Inf(1)
			}
		}
		if c[0] {
			z1[0][1] = 0
		} else {
			z0[0][0] = 0
		}
		for i := 1; i < n; i++ {
			if c[i] {
				for j := i + 1; j >= 0; j-- {
					if j <= i {
						z0[i][j] = min(z0[i-1][j+1]+y, z1[i-1][j+1]+x)
					}
					if j > 0 {
						z0[i][j] = min(min(z0[i][j], z0[i-1][j-1]+x), z1[i-1][j-1]+y)
						z1[i][j] = min(z0[i-1][j-1], z1[i-1][j-1])
					}
				}
			} else {
				for j := i + 1; j >= 0; j-- {
					z0[i][j] = min(z0[i-1][j], z1[i-1][j])
					z1[i][j] = min(z0[i-1][j]+y, z1[i-1][j]+x)
					if j > 1 {
						z1[i][j] = min(min(z1[i][j], z0[i-1][j-2]+x), z1[i-1][j-2]+y)
					}
				}
			}
		}
		fmt.Println(int(z0[n-1][0]))
	}
}

package main

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

func min(i, j float64) float64 {
	if i < j {
		return i
	}
	return j
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	txt, _ := reader.ReadString('\n')
	t, _ := strconv.Atoi(strings.TrimSpace(txt))
	for ; t > 0; t-- {
		txt, _ = reader.ReadString('\n')
		arr := strings.Split(strings.TrimSpace(txt), " ")
		n, _ := strconv.Atoi(arr[0])
		x, _ := strconv.ParseFloat(arr[1], 64)
		y, _ := strconv.ParseFloat(arr[2], 64)
		txt, _ = reader.ReadString('\n')
		a := strings.TrimSpace(txt)
		txt, _ = reader.ReadString('\n')
		b := strings.TrimSpace(txt)
		d := 0
		c := make([]bool, n, n)
		for i := 0; i < n; i++ {
			c[i] = a[i] != b[i]
			if c[i] {
				d++
			}
		}

		// если нужно поменять нечетное количество элементов, то решения нет
		if d%2 == 1 {
			fmt.Println(-1)
			continue
		}

		if d == 2 {
			var l, r int
			for l = 0; !c[l]; {
				l++
			}
			for r = n - 1; !c[r]; {
				r--
			}

			if l+1 == r {
				fmt.Println(min(2*y, x))
			} else {
				fmt.Println(min(float64(r-l)*x, y))
			}

			continue
		}

		if d == 0 || x >= y {
			fmt.Println(float64(d/2) * y)
			continue
		}
		z0 := make([][]float64, n, n)
		z1 := make([][]float64, n, n)
		for i := 0; i < n; i++ {
			z0[i] = make([]float64, n+1, n+1)
			z1[i] = make([]float64, n+1, n+1)
			for j := 0; j <= n; j++ {
				z0[i][j] = math.Inf(1)
				z1[i][j] = math.Inf(1)
			}
		}
		if c[0] {
			z1[0][1] = 0
		} else {
			z0[0][0] = 0
		}
		for i := 1; i < n; i++ {
			if c[i] {
				for j := i + 1; j >= 0; j-- {
					if j <= i {
						z0[i][j] = min(z0[i-1][j+1]+y, z1[i-1][j+1]+x)
					}
					if j > 0 {
						z0[i][j] = min(min(z0[i][j], z0[i-1][j-1]+x), z1[i-1][j-1]+y)
						z1[i][j] = min(z0[i-1][j-1], z1[i-1][j-1])
					}
				}
			} else {
				for j := i + 1; j >= 0; j-- {
					z0[i][j] = min(z0[i-1][j], z1[i-1][j])
					z1[i][j] = min(z0[i-1][j]+y, z1[i-1][j]+x)
					if j > 1 {
						z1[i][j] = min(min(z1[i][j], z0[i-1][j-2]+x), z1[i-1][j-2]+y)
					}
				}
			}
		}
		fmt.Println(z0[n-1][0])
	}
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	txt, _ := reader.ReadString('\n')
	t, _ := strconv.Atoi(strings.TrimSpace(txt))
	for ; t > 0; t-- {
		txt, _ = reader.ReadString('\n')
		arr := strings.Split(strings.TrimSpace(txt), " ")
		n, _ := strconv.Atoi(arr[0])
		x, _ := strconv.Atoi(arr[1])
		y, _ := strconv.Atoi(arr[2])
		txt, _ = reader.ReadString('\n')
		a := strings.TrimSpace(txt)
		txt, _ = reader.ReadString('\n')
		b := strings.TrimSpace(txt)
		indexes := make([]int, 0)
		for i := 0; i < n; i++ {
			if a[i] != b[i] {
				indexes = append(indexes, i)
			}
		}
		ln := len(indexes)
		if ln%2 > 0 {
			fmt.Println(-1)
			continue
		}
		if x >= y {
			if ln == 2 {
				if indexes[1]-indexes[0] == 1 {
					min := x
					if 2*y < min {
						min = 2 * y
					}
					fmt.Println(min)
				} else {
					fmt.Println(y)
				}
			} else {
				fmt.Println(ln / 2 * y)
			}
		} else {
			completed := make(map[int]bool)
			prevMinDistance := 0
			minDistance := n
			distances := make(map[int]int)
			for {
				for first, last := 0, 1; last < ln; first, last = last, last+1 {
					if completed[indexes[first]] {
						continue
					}
					for completed[indexes[last]] {
						last++
					}
					d := indexes[last] - indexes[first]
					if d > prevMinDistance && d < minDistance {
						minDistance = d
					}
				}
				if prevMinDistance == minDistance {
					break
				}
				for first, last := 0, 1; last < ln; first, last = last, last+1 {
					if completed[indexes[first]] {
						continue
					}
					for completed[indexes[last]] {
						last++
					}
					d := indexes[last] - indexes[first]
					if d == minDistance {
						completed[indexes[first]] = true
						completed[indexes[last]] = true
						first++
						last++
						distances[minDistance]++
					}
				}
				prevMinDistance = minDistance
				minDistance = n
			}

			min := 0
			for k, v := range distances {
				if k*x < y {
					min += k * x * v
				} else {
					min += v * y
				}
			}
			fmt.Println(min)
		}

	}
}

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	txt, _ := reader.ReadString('\n')
	t, _ := strconv.Atoi(strings.TrimSpace(txt))
	for ; t > 0; t-- {
		txt, _ = reader.ReadString('\n')
		arr := strings.Split(strings.TrimSpace(txt), " ")
		n, _ := strconv.Atoi(arr[0])
		x, _ := strconv.Atoi(arr[1])
		y, _ := strconv.Atoi(arr[2])
		txt, _ = reader.ReadString('\n')
		a := strings.TrimSpace(txt)
		txt, _ = reader.ReadString('\n')
		b := strings.TrimSpace(txt)
		indexes := make([]int, 0)
		for i := 0; i < n; i++ {
			if a[i] != b[i] {
				indexes = append(indexes, i)
			}
		}
		ln := len(indexes)
		if ln%2 > 0 {
			fmt.Println(-1)
			continue
		}
		if x >= y {
			if ln == 2 {
				if indexes[1]-indexes[0] == 1 {
					min := x
					if 2*y < min {
						min = 2 * y
					}
					fmt.Println(min)
				} else {
					fmt.Println(y)
				}
			} else {
				fmt.Println(ln / 2 * y)
			}
		} else {
			cntX := 0
			for i := 1; i < ln; i++ {
				if indexes[i]-indexes[i-1] == 1 {
					cntX++
					i++
				}
			}
			fmt.Println(cntX*x + (ln-cntX*2)/2*y)
		}

	}
}

package main

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

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

func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func print(a ...interface{})            { fmt.Println(a...) }
func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f+"\n", a...) }

func main() {
	defer writer.Flush()

	var testcases int64
	scanf("%d", &testcases)
  var i int64
	for i = 0; i < testcases; i++ {
		var n, x, y int64
		scanf("%d %d %d", &n, &x, &y)
    var a, b string
    scanf("%s", &a)
    scanf("%s", &b)

		print(solve(n, x, y, a, b))
	}
}

func max(nums ...int64) int64 {
  result := nums[0]
	for _, num := range nums {
		if num > result {
			result = num
		}
	}
	return result
}

func min(nums ...int64) int64 {
  result := nums[0]
  for _, num := range nums {
    if num < result {
      result = num
    }
  }
  return result
}

func solve(n, x, y int64, a, b string) int64 {
  diffs := make([]int64, 0, n)
  var i int64
  for i = 0; i < n; i++ {
    if a[i] != b[i] {
      diffs = append(diffs, i)
    }
  }

  m := int64(len(diffs))

  if m % 2 == 1 {
    return -1
  }

  if x >= y {
    if m == 2 && diffs[0] + 1 == diffs[1] {
      return min(x, y*2)
    }
    return y * m / 2
  }

  dp := make([][]int64, m)
  for i = 0; i < m; i++ {
    dp[i] = make([]int64, m)
    var j int64
    for j = 0; j < m; j++ {
      dp[i][j] = -1
    }
  }
  var dfs func(i, drop int64) int64
  dfs = func(i, drop int64) int64 {
    if i >= m {
      if drop == 0 {
        return 0
      }
      return math.MaxInt32
    }
    if dp[i][drop] != -1 {
      return dp[i][drop]
    }
    result := dfs(i+1, drop+1)
    if drop > 0 {
      result = min(result, dfs(i+1, drop-1) + y)
    }
    if i < m-1 {
      result = min(result, dfs(i+2, drop) + min(y, x * (diffs[i+1] - diffs[i])))
    }
    dp[i][drop] = result
    return result
  }
  res := dfs(0, 0)
  return res
}

package main

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

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

func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func print(a ...interface{})            { fmt.Println(a...) }
func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f+"\n", a...) }

func main() {
	defer writer.Flush()

	var testcases int
	scanf("%d", &testcases)
	for i := 0; i < testcases; i++ {
		var n, x, y int
		scanf("%d %d %d", &n, &x, &y)
    var a, b string
    scanf("%s", &a)
    scanf("%s", &b)

		print(solve(n, x, y, a, b))
	}
}

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

func min(nums ...int) int {
  result := nums[0]
  for _, num := range nums {
    if num < result {
      result = num
    }
  }
  return result
}

func solve(n, x, y int, a, b string) int {
  diffs := make([]int, 0, n)
  for i := 0; i < n; i++ {
    if a[i] != b[i] {
      diffs = append(diffs, i)
    }
  }

  m := len(diffs)

  if m % 2 == 1 {
    return -1
  }

  if x >= y {
    if m == 2 && diffs[0] + 1 == diffs[1] {
      return min(x, y*2)
    }
    return y * m / 2
  }

  dp := make([][]int, m)
  for i := 0; i < m; i++ {
    dp[i] = make([]int, m)
    for j := 0; j < m; j++ {
      dp[i][j] = -1
    }
  }
  var dfs func(i, drop int) int
  dfs = func(i, drop int) int {
    if i >= m {
      if drop == 0 {
        return 0
      }
      return math.MaxInt32
    }
    if dp[i][drop] != -1 {
      return dp[i][drop]
    }
    result := dfs(i+1, drop+1)
    if drop > 0 {
      result = min(result, dfs(i+1, drop-1) + y)
    }
    if i < m-1 {
      result = min(result, dfs(i+2, drop) + min(y, x * (diffs[i+1] - diffs[i])))
    }
    dp[i][drop] = result
    return result
  }
  res := dfs(0, 0)
  return res
}


You are given $$$n$$$ arrays $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$; each array consists of exactly $$$m$$$ integers. We denote the $$$y$$$-th element of the $$$x$$$-th array as $$$a_{x, y}$$$.You have to choose two arrays $$$a_i$$$ and $$$a_j$$$ ($$$1 \le i, j \le n$$$, it is possible that $$$i = j$$$). After that, you will obtain a new array $$$b$$$ consisting of $$$m$$$ integers, such that for every $$$k \in [1, m]$$$ $$$b_k = \max(a_{i, k}, a_{j, k})$$$.Your goal is to choose $$$i$$$ and $$$j$$$ so that the value of $$$\min \limits_{k = 1}^{m} b_k$$$ is maximum possible.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$, $$$1 \le m \le 8$$$) — the number of arrays and the number of elements in each array, respectively. Then $$$n$$$ lines follow, the $$$x$$$-th line contains the array $$$a_x$$$ represented by $$$m$$$ integers $$$a_{x, 1}$$$, $$$a_{x, 2}$$$, ..., $$$a_{x, m}$$$ ($$$0 \le a_{x, y} \le 10^9$$$).

Print two integers $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$, it is possible that $$$i = j$$$) — the indices of the two arrays you have to choose so that the value of $$$\min \limits_{k = 1}^{m} b_k$$$ is maximum possible. If there are multiple answers, print any of them.

package main

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

const (
	mod = 998244353
)

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n, m := 0, 0
	fmt.Fscanf(in, "%d %d\n", &n, &m)
	a := make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, m)
		for j := 0; j < m; j++ {
			fmt.Fscanf(in, "%d", &a[i][j])
		}
		fmt.Fscanf(in, "\n")
	}
	//fmt.Println(a)
	l := 0
	r := int(1e9)
	for l < r {
		mid := (l + r + 1) / 2
		x, _ := find(a, mid)
		if x != -1 {
			l = mid
		} else {
			r = mid - 1
		}
	}
	x, y := find(a, l)
	fmt.Fprintf(out, "%d %d\n", x+1, y+1)
	return
}

func find(a [][]int, find int) (int, int) {
	//fmt.Println("try to find ", find, a)
	ansMap := make([]int, 256)
	for i := 0; i < 256; i++ {
		ansMap[i] = -1
	}
	n := len(a)
	m := len(a[0])
	for i := 0; i < n; i++ {
		weight := 1
		state := 0
		for j := 0; j < m; j++ {
			if a[i][j] >= find {
				state += weight
			}
			weight *= 2
		}
		if ansMap[state] == -1 {
			ansMap[state] = i
		}
	}
	wantedState := 1<<uint(m) - 1
	//fmt.Println("debug wantedState", wantedState, ansMap[:32])
	for i := 0; i <= wantedState; i++ {
		for j := 0; j <= wantedState; j++ {
			if i|j == wantedState && ansMap[i] != -1 && ansMap[j] != -1 {
				return ansMap[i], ansMap[j]
			}
		}
	}
	return -1, -1
}

package main

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

var (
	sc = bufio.NewScanner(os.Stdin)
	wr = bufio.NewWriter(os.Stdout)
)

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

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

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

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

func printInts(a ...int) {
	for i, e := range a {
		fmt.Fprint(wr, e)
		if i != len(a)-1 {
			fmt.Fprint(wr, " ")
		}
	}
	fmt.Fprintln(wr)
	wr.Flush()
}

const mod = 1000000007

var (
	n      int
	m      int
	a      [][]int
	single int
	ans1   int
	ans2   int
	MX     uint
)

func check(value int) (bool, int, int) {
	cnt := make([]int, MX)
	sum := make([]int, MX)
	for i := 0; i < n; i++ {
		mask := uint(0)
		for j := uint(0); j < uint(m); j++ {
			if a[i][j] >= value {
				mask |= (1 << j)
			}
		}
		cnt[mask] = i + 1
		sum[mask] = i + 1
	}
	for i := uint(0); i < uint(m); i++ {
		for j := uint(0); j < MX; j++ {
			if (j>>i&1) == 1 && sum[j] != 0 {
				sum[j^(1<<i)] = sum[j]
			}
		}
	}
	maskMax := uint(MX - 1)
	for mask := uint(1); mask < MX; mask++ {
		if cnt[mask] == 0 {
			continue
		}
		if sum[maskMax^mask] != 0 {
			return true, cnt[mask], sum[maskMax^mask]
		}
	}
	return false, 0, 0
}

func main() {
	sc.Split(bufio.ScanWords)
	n = scanInt()
	m = scanInt()
	a = make([][]int, n)
	MX = uint(1) << uint(m)
	for i := range a {
		a[i] = make([]int, m)
	}
	for i := 0; i < n; i++ {
		rowMin := 0
		for j := 0; j < m; j++ {
			a[i][j] = scanInt()
			if a[i][j] < rowMin {
				rowMin = a[i][j]
			}
			if rowMin >= single {
				single = rowMin
				ans1 = i + 1
				ans2 = i + 1
			}
		}
	}
	low, high, mid := single+1, 1000000000, 0
	for low <= high {
		mid = (low + high) >> 1
		judge, row1, row2 := check(mid)
		if judge {
			ans1, ans2 = row1, row2
			low = mid + 1
		} else {
			high = mid - 1
		}
	}
	fmt.Println(ans1, " ", ans2)
}

package main

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

// github.com/EndlessCheng/codeforces-go
func main() {
	in := bufio.NewScanner(os.Stdin)
	in.Split(bufio.ScanWords)
	read := func() (x int) {
		in.Scan()
		for _, b := range in.Bytes() {
			x = x*10 + int(b-'0')
		}
		return
	}

	n, m := read(), uint(read())
	mat := make([][]int, n)
	for i := range mat {
		mat[i] = make([]int, m)
		for j := range mat[i] {
			mat[i][j] = read()
		}
	}
	var ansI, ansJ int
	sort.Search(1e9+1, func(min int) bool {
		id := make([]int, 1<<m)
		for i, mi := range mat {
			v := 0
			for j, a := range mi {
				if a >= min {
					v |= 1 << uint(j)
				}
			}
			id[v] = i + 1
		}
		for i := range id {
			if id[i] > 0 {
				for j := i; j < 1<<m; j++ {
					if i|j == 1<<m-1 && id[j] > 0 {
						ansI, ansJ = id[i], id[j]
						return false
					}
				}
			}
		}
		return true
	})
	Print(ansI, ansJ)
}

package main

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

var (
	sc = bufio.NewScanner(os.Stdin)
	wr = bufio.NewWriter(os.Stdout)
)

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

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

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

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

func printInts(a ...int) {
	for i, e := range a {
		fmt.Fprint(wr, e)
		if i != len(a)-1 {
			fmt.Fprint(wr, " ")
		}
	}
	fmt.Fprintln(wr)
	wr.Flush()
}

const mod = 1000000007

var (
	n      int
	m      int
	a      [][]int
	single int
	ans1   int
	ans2   int
	MX     uint
)

func check(value int) (bool, int, int) {
	cnt := make([]int, MX)
	sum := make([]int, MX)
	for i := 0; i < n; i++ {
		mask := uint(0)
		for j := uint(0); j < uint(m); j++ {
			if a[i][j] >= value {
				mask |= (1 << j)
			}
		}
		cnt[mask] = i + 1
		sum[mask] = i + 1
	}
	for i := uint(0); i < uint(m); i++ {
		for j := uint(0); j < MX; j++ {
			if (j>>i&1) == 1 && sum[j] != 0 {
				sum[j^(1<<i)] = sum[j]
			}
		}
	}
	maskMax := uint(MX - 1)
	for mask := uint(1); mask < MX; mask++ {
		if cnt[mask] == 0 {
			continue
		}
		if sum[maskMax^mask] != 0 {
			return true, cnt[mask], sum[maskMax^mask]
		}
	}
	return false, 0, 0
}

func main() {
	sc.Split(bufio.ScanWords)
	n = scanInt()
	m = scanInt()
	a = make([][]int, n)
	MX = uint(1) << uint(m)
	for i := range a {
		a[i] = make([]int, m)
	}
	for i := 0; i < n; i++ {
		rowMin := 0
		for j := 0; j < m; j++ {
			a[i][j] = scanInt()
			if a[i][j] < rowMin {
				rowMin = a[i][j]
			}
			if rowMin > single {
				single = rowMin
				ans1 = i + 1
				ans2 = i + 1
			}
		}
	}
	low, high, mid := single+1, 1000000000, 0
	for low <= high {
		mid = (low + high) >> 1
		judge, row1, row2 := check(mid)
		if judge {
			ans1, ans2 = row1, row2
			low = mid + 1
		} else {
			high = mid - 1
		}
	}
	println(ans1, " ", ans2)
}

package main

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

var (
	sc = bufio.NewScanner(os.Stdin)
	wr = bufio.NewWriter(os.Stdout)
)

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

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

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

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

func printInts(a ...int) {
	for i, e := range a {
		fmt.Fprint(wr, e)
		if i != len(a)-1 {
			fmt.Fprint(wr, " ")
		}
	}
	fmt.Fprintln(wr)
	wr.Flush()
}

const mod = 1000000007

var (
	n      int
	m      int
	a      [][]int
	single int
	ans1   int
	ans2   int
	MX     uint
)

func check(value int) (bool, int, int) {
	cnt := make([]int, MX)
	sum := make([]int, MX)
	for i := 0; i < n; i++ {
		mask := uint(0)
		for j := uint(0); j < uint(m); j++ {
			if a[i][j] >= value {
				mask |= (1 << j)
			}
		}
		cnt[mask] = i + 1
		sum[mask] = i + 1
	}
	for i := uint(0); i < uint(m); i++ {
		for j := uint(0); j < MX; j++ {
			if (j>>i&1) == 1 && sum[j] != 0 {
				sum[j^(1<<i)] = sum[j]
			}
		}
	}
	maskMax := uint(MX - 1)
	for mask := uint(1); mask < MX; mask++ {
		if cnt[mask] == 0 {
			continue
		}
		if sum[maskMax^mask] != 0 {
			return true, cnt[mask], sum[maskMax^mask]
		}
	}
	return false, 0, 0
}

func main() {
	sc.Split(bufio.ScanWords)
	n = scanInt()
	m = scanInt()
	a = make([][]int, n)
	MX = uint(1) << uint(m)
	for i := range a {
		a[i] = make([]int, m)
	}
	for i := 0; i < n; i++ {
		rowMin := 0
		for j := 0; j < m; j++ {
			a[i][j] = scanInt()
			if a[i][j] < rowMin {
				rowMin = a[i][j]
			}
			if rowMin > single {
				single = rowMin
				ans1 = i + 1
				ans2 = i + 1
			}
		}
	}
	low, high, mid := single+1, 1000000000, 0
	for low <= high {
		mid = (low + high) >> 1
		judge, row1, row2 := check(mid)
		if judge {
			ans1, ans2 = row1, row2
			low = mid + 1
		} else {
			high = mid - 1
		}
	}
	fmt.Println(ans1, " ", ans2)
}


You got a box with a combination lock. The lock has a display showing n digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the display one position to the right (the last digit becomes the first one). For example, if the display is currently showing number 579, then if we push the first button, the display will show 680, and if after that we push the second button, the display will show 068.You know that the lock will open if the display is showing the smallest possible number that can be obtained by pushing the buttons in some order. The leading zeros are ignored while comparing numbers. Now your task is to find the desired number.

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of digits on the display. The second line contains n digits — the initial state of the display.

Print a single line containing n digits — the desired state of the display containing the smallest possible number.

package main

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

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

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

	n := nextInt()
	s := next()
	min := []rune(s)

	for k := n; k > 0; k-- {
		s = s[1:] + s[:1]
		si := []rune(s)
		dif := si[0] - '0'

		// println(s, string(si), string(min))
		for i := 0; i < n; i++ {
			si[i] -= dif

			if si[i] < '0' {
				si[i] = '9' + 1 - '0' + si[i]
			}
		}

		for i := 0; i < n; i++ {
			if si[i] == min[i] {
				continue
			}

			if si[i] < min[i] {
				// println(string(si[i]), i ,string(min), string(min[i]))
				min = si
			}

			break
		}

		// println(s, string(si), string(min))
		// println()
	}

	println(string(min))
}

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

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

func nextFloat() float64 {
	n, err := strconv.ParseFloat(next(), 64)
	if err != nil {
		panic(err)
	}
	return n
}

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

package main

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

var scanner = bufio.NewScanner(os.Stdin)
var ans []byte

func compare(s *[]byte, move int) {
    n := len(*s)
    isOk := false
    for i, c := range ans {
        ch := (*s)[(i+move)%n]
        if ch < c {
            isOk = true
            break
        } else if ch > c {
            break
        }
    }
    if isOk {
        for i := 0; i < n; i++ {
            ans[i] = (*s)[(i+move)%n]
        }
    }
}

func main() {
    scanner.Split(bufio.ScanWords)
    n := nextInt()
    str := next()
    num := make([]byte, n, n)
    ans = make([]byte, n, n)
    for i := 0; i < n; i++ {
        num[i] = byte(str[i] - '0')
        ans[i] = byte(str[i] - '0')
    }

    first := byte(0)
    for i := 0; i < 11; i++ {
        for j := 0; j < n; j++ {
            num[j] = (num[j] + first) % 10
        }
        for j := 0; j < n; j++ {
            compare(&num, j)
        }
        first = byte(1)
    }
    for _, s := range ans {
        fmt.Printf("%c", '0'+s)
    }
    fmt.Println()
}

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

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

package main

import (
	"bytes"
	"fmt"
)

var (
	n      int
	input  string
	result string
)

func in() {
	fmt.Scanln(&n)
	fmt.Scanln(&input)
}

func out() {
	fmt.Println(result)
}

func run() {
	var digits []byte = make([]byte, n)
	for i := 0; i < n; i++ {
		digits[i] = input[i] - byte('0')
	}

	var min []byte = nil
	for i := 0; i < n; i++ {
		curr := transform(digits, i)
		if isSmaller(curr, min) {
			min = curr
		}
	}

	result = toString(min)
}

func transform(digits []byte, pos int) []byte {
	var v byte = digits[pos]
	var trans []byte = make([]byte, n)
	for i := 0; i < n; i++ {
		trans[i] = (digits[(i+pos)%n] - v + 10) % 10
	}
	return trans
}

func isSmaller(curr, min []byte) bool {
	if min == nil {
		return true
	}

	for i := 0; i < len(curr); i++ {
		if curr[i] < min[i] {
			return true
		} else if curr[i] > min[i] {
			return false
		}
	}
	return false
}

func toString(value []byte) string {
	var buffer bytes.Buffer
	for _, v := range value {
		buffer.WriteByte(byte('0') + v)
	}
	return buffer.String()
}

func main() {
	in()
	run()
	out()
}

package main

import (
	"fmt"
)

func main() {
	var n int
	var init, res string

	fmt.Scan(&n)
	fmt.Scan(&init)

	for i := 0; i < n; i++ {
		res += "9"
	}

	for i := 0; i < n; i++ {
		var candidate string

		s := init[i:] + init[:i]
		diff := ('9' + 1 - s[0]) % 10

		for j := 0; j < n; j++ {
			candidate += string('0' + (s[j]+diff-'0')%10)
		}

		if candidate < res {
			res = candidate
		}
	}

	fmt.Println(res)
}

package main

import (
	"fmt"
)

type digits []int

func compareTo(a, b digits) int {
	n := len(a)
	for i := 0; i < n; i++ {
		switch {
		case a[i] < b[i]:
			return -1
		case a[i] > b[i]:
			return 1
		}
	}
	return 0
}

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

	var a [10]digits
	for i := 0; i < 10; i++ {
		a[i] = make(digits, n)
	}
	for i, r := range s {
		a[0][i] = int(r - '0')
	}
	for i := 1; i < 10; i++ {
		for j := 0; j < n; j++ {
			a[i][j] = (a[0][j] + i) % 10
		}
	}
	z := a[0]
	for i := 0; i < 10; i++ {
		x := a[i]
		for j := 0; j < n; j++ {
			if compareTo(x, z) < 0 {
				z = x
			}
			h := x[0]
			x = append(x[1:], h)
		}
	}
	for i := 0; i < n; i++ {
		fmt.Printf("%c", z[i]+'0')
	}
	fmt.Println()
}

package main

import (
	"bytes"
	"fmt"
)

var (
	n      int
	input  string
	result string
)

func in() {
	fmt.Scanln(&n)
	fmt.Scanln(&input)
}

func out() {
	fmt.Println(result)
}

func run() {
	var digits []byte = make([]byte, n)
	for i := 0; i < n; i++ {
		digits[i] = input[i] - byte('0')
	}

	var min []byte = nil
	for i := 0; i < n; i++ {
		curr := transform(digits, i)
		if isSmaller(curr, min) {
			min = curr
		}
	}

	result = toString(min)
}

func transform(digits []byte, pos int) []byte {
	var v byte = digits[pos]
	var trans []byte = make([]byte, n)
	for i := 0; i < n; i++ {
		trans[i] = digits[(i+pos)%n] - v
	}
	return trans
}

func isSmaller(curr, min []byte) bool {
	if min == nil {
		return true
	}

	for i := 0; i < len(curr); i++ {
		if curr[i] < min[i] {
			return true
		} else if curr[i] > min[i] {
			return false
		}
	}
	return false
}

func toString(value []byte) string {
	var buffer bytes.Buffer
	for _, v := range value {
		buffer.WriteByte(byte('0') + v)
	}
	return buffer.String()
}

func main() {
	in()
	run()
	out()
}


You find yourself on an unusual crossroad with a weird traffic light. That traffic light has three possible colors: red (r), yellow (y), green (g). It is known that the traffic light repeats its colors every $$$n$$$ seconds and at the $$$i$$$-th second the color $$$s_i$$$ is on.That way, the order of the colors is described by a string. For example, if $$$s=$$$"rggry", then the traffic light works as the following: red-green-green-red-yellow-red-green-green-red-yellow- ... and so on.More formally, you are given a string $$$s_1, s_2, \ldots, s_n$$$ of length $$$n$$$. At the first second the color $$$s_1$$$ is on, at the second — $$$s_2$$$, ..., at the $$$n$$$-th second the color $$$s_n$$$ is on, at the $$$n + 1$$$-st second the color $$$s_1$$$ is on and so on.You need to cross the road and that can only be done when the green color is on. You know which color is on the traffic light at the moment, but you don't know the current moment of time. You need to find the minimum amount of time in which you are guaranteed to cross the road.You can assume that you cross the road immediately. For example, with $$$s=$$$"rggry" and the current color r there are two options: either the green color will be on after $$$1$$$ second, or after $$$3$$$. That way, the answer is equal to $$$3$$$ — that is the number of seconds that we are guaranteed to cross the road, if the current color is r.

The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^4$$$) — the number of test cases. Then the description of the test cases follows. The first line of each test case contains an integer $$$n$$$ and a symbol $$$c$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$, $$$c$$$ is one of allowed traffic light colors r, y or g)— the length of the string $$$s$$$ and the current color of the traffic light.  The second line of each test case contains a string $$$s$$$ of the length $$$n$$$, consisting of the letters r, y and g. It is guaranteed that the symbol g is in the string $$$s$$$ and the symbol $$$c$$$ is in the string $$$s$$$.  It is guaranteed, that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

For each test case output the minimal number of second in which you are guaranteed to cross the road.

6

5 r

rggry

1 g

g

3 r

rrg

5 y

yrrgy

7 r

rgrgyrg

9 y

rrrgyyygy

NoteThe first test case is explained in the statement.In the second test case the green color is on so you can cross the road immediately. In the third test case, if the red color was on at the second second, then we would wait for the green color for one second, and if the red light was on at the first second, then we would wait for the green light for two seconds.In the fourth test case the longest we would wait for the green color is if we wait for it starting from the fifth second.

package main

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

const (
	N = 2e5 + 10
)

var (
	ans, t, n int
	idx       []int
	c, s      string
)

func main() {
	defer flush()
	scan(&t)
	idx = make([]int, N)
	for ; t != 0; t-- {
		scan(&n, &c, &s)
		le := len(s)
		last := -1
		first := 0
		for i := le - 1; i >= 0; i-- {
			if s[i] == 'g' {
				last = i
				first = i
			}
			idx[i] = last
		}
		ans = 0
		for i := 0; i < le; i++ {
			if s[i] == c[0] {
				if idx[i] == -1 {
					ans = max(ans, le-i+first)
				} else {
					ans = max(ans, idx[i]-i)
				}
			}
		}
		println(ans)
	}
}

func max(i, j int) int {
	if i > j {
		return i
	}
	return j
}

var (
	IOReader *bufio.Reader
	IOWriter *bufio.Writer
)

func init() {
	IOReader = bufio.NewReader(os.Stdin)
	IOWriter = bufio.NewWriter(os.Stdout)
}

func scan(a ...any) {
	fmt.Fscan(IOReader, a...)
}

func println(a ...any) {
	fmt.Fprintln(IOWriter, a...)
}

func flush() {
	IOWriter.Flush()
}

package main

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

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

func main() {
	var t int
	fmt.Fscan(in, &t)
	for i := 0; i < t; i++ {
		var n int
		var c string
		fmt.Fscan(in, &n, &c)
		var colors string
		fmt.Fscan(in, &colors)
		colors = colors + colors
		last := 0
		max := 0
		for j := len(colors) - 1; j >= 0; j-- {
			if colors[j] == 'g' {
				last = j
			}
			if colors[j] == c[0] {
				if last-j > max {
					max = last - j
				}
			}
		}
		fmt.Println(max)
	}
}

func countPow2(x int) int {
	temp := x
	count := 0
	for temp%2 == 0 {
		temp = temp / 2
		count++
	}
	return count
}

func GCD(a, b int) int {
	for a != b {
		if a > b {
			a -= b
		} else {
			b -= a
		}
	}

	return a
}

func max[T Ordered](x, y T) T {
	if x > y {
		return x
	}
	return y
}

type Ordered interface {
	int | float64 | ~string
}

package main

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

var reader = bufio.NewReader(os.Stdin)

var n, m int

func solve(typ, x int) {
	if x%2 == 0 {
		// will not change the odd even
		if typ == 0 { // even
			sum += even * x
		} else {
			sum += odd * x
		}
	} else { // will change the odd even, x is odd number
		if typ == 0 { // operating even number
			sum += even * x
			odd += even
			even = 0
		} else { // operating odd number
			sum += odd * x
			even += odd
			odd = 0
		}
	}
	fmt.Println(sum)
}

var odd, even, sum int

func main() {
	var t int

	fmt.Fscan(reader, &t)

	for t > 0 {
		t--
		var n int
		var c string
		fmt.Fscan(reader, &n)
		fmt.Fscan(reader, &c)
		var s string
		fmt.Fscan(reader, &s)
		//0123456789
		//rggryrggry
		// 1    3
		//
		s = s + s
		res := 0
		for i := 0; i < n; i++ {
			if s[i] == c[0] {
				var j int
				for j = i; j < i+n; j++ {
					if s[j] == 'g' {
						res = max(res, j-i)
						break
					}
				}
				i = j
			}
		}
		fmt.Println(res)
	}
}

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

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

package main

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

func solution_1(input io.Reader, output io.Writer) {
	in := bufio.NewReader(input)
	var n int
	_, err := fmt.Fscanf(in, "%d\n", &n)
	if err != nil {
		panic(err)
	}

	for i := 0; i < n; i++ {
		var narr int
		_, err := fmt.Fscanf(in, "%d\n", &narr)
		if err != nil {
			panic(err)
		}

		arr := make([]int, 0, narr)
		for j := 0; j < narr; j++ {
			var v int
			_, err := fmt.Fscanf(in, "%d", &v)
			if err != nil {
				panic(err)
			}
			arr = append(arr, v)
		}
		fmt.Fscanf(in, "\n")
		var s string
		_, err = fmt.Fscanf(in, "%s\n", &s)
		fmt.Fprintln(output, numberReplacement(arr, s))
	}
}

func solution_2(input io.Reader, output io.Writer) {
	in := bufio.NewReader(input)
	var n int
	_, err := fmt.Fscanf(in, "%d\n", &n)
	if err != nil {
		panic(err)
	}

	for i := 0; i < n; i++ {
		var narr, q int
		_, err := fmt.Fscanf(in, "%d %d\n", &narr, &q)
		if err != nil {
			panic(err)
		}

		arr := make([]int, 0, narr)
		for j := 0; j < narr; j++ {
			var v int
			_, err := fmt.Fscanf(in, "%d", &v)
			if err != nil {
				panic(err)
			}
			arr = append(arr, v)
		}
		fmt.Fscanf(in, "\n")

		nOdd := 0
		nEven := 0
		sum := 0

		for _, n := range arr {
			sum += n
			if n%2 == 0 {
				nEven++
			} else {
				nOdd++
			}
		}
		for j := 0; j < q; j++ {
			var a, b int
			fmt.Fscanf(in, "%d %d\n", &a, &b)
			if a == 0 {
				sum += nEven * b
				if b%2 != 0 {
					nOdd += nEven
					nEven = 0
				}
			}

			if a == 1 {
				sum += nOdd * b
				if b%2 != 0 {
					nEven += nOdd
					nOdd = 0
				}
			}
			fmt.Fprintln(output, sum)
		}

	}
}

func numberReplacement(arr []int, s string) string {
	if len(arr) != len(s) {
		return "NO"
	}

	someMap := make(map[int]byte)
	for i, n := range arr {
		if v, ok := someMap[n]; !ok {
			someMap[n] = s[i]
		} else {
			if v != s[i] {
				return "NO"
			}
		}
	}

	return "YES"
}

func solution_3(input io.Reader, output io.Writer) {
	in := bufio.NewReader(input)
	var n int
	_, err := fmt.Fscanf(in, "%d\n", &n)
	if err != nil {
		panic(err)
	}

	for i := 0; i < n; i++ {
		var narr int
		var colour string
		_, err := fmt.Fscanf(in, "%d %s\n", &narr, &colour)
		if err != nil {
			panic(err)
		}

		var s string
		_, err = fmt.Fscanf(in, "%s\n", &s)
		if err != nil {
			panic(err)
		}
		fmt.Fprintln(output, waitTime(s, colour))
	}
}

func waitTime(s string, c string) int {
	if c == "g" {
		return 0
	}
	maxRes := 0
	firstGreenIndex := -1
	i := len(s) - 1
	curDist := 1

	for {
		if s[i] == 'g' {
			firstGreenIndex = i
			break
		}
		i--
	}

	i--
	if i < 0 {
		i = len(s) - 1
	}
	distances := make([]int, len(s))

	for i != firstGreenIndex {
		if s[i] == 'g' {
			curDist = 0
		}
		distances[i] = curDist
		curDist++
		i--
		if i < 0 {
			i = len(s) - 1
		}
	}

	for i := 0; i < len(s); i++ {
		if s[i] == c[0] {
			curDist := distances[i]
			if curDist > maxRes {
				maxRes = curDist
			}
		}
	}

	return maxRes
}

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

package main

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

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

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

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

		ch := c[0]
		if ch == 'g' {
			fmt.Fprintln(out, 0)
			continue
		}

		last := -1
		var mx int
		var crossed bool
		for i := 0; i < n; i++ {
			if s[i] == ch {
				if last < 0 || crossed {
					last = i
					crossed = false
				}
			} else if s[i] == 'g' && last >= 0 && !crossed {
				mx = max(mx, i-last)
				crossed = true
			}
		}
		if last > 0 && !crossed {
			var d int
			for i := range s {
				if s[i] == 'g' {
					d = i
					break
				}
			}
			mx = max(mx, n-last+d)
		}
		fmt.Fprintln(out, mx)
	}
}

package main

import "fmt"

func main() {
	var test, l int
	var s, si string

	fmt.Scanln(&test)
	for test > 0 {
		fmt.Scanln(&l, &si)
		fmt.Scanln(&s)
		fmt.Println(trafficLight(si, s))
		test--
	}
}

func trafficLight(si, s string) int {
	mp := map[byte][]int{}
	for i := range s {
		mp[s[i]] = append(mp[s[i]], i)
	}
	k := mp[si[0]]
	g := mp['g']
	g = append(g, g[0]+len(s))
	max := 0
	gi := 0
	for i := range k {
		if k[i] > g[gi] {
			for k[i] > g[gi] {
				gi++
			}
		}
		if max < g[gi]-k[i] {
			max = g[gi] - k[i]
		}
	}
	return max
}

package main

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

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

	var T int
	for fmt.Fscan(r, &T); T > 0; T-- {

		var n, res, cd, pd int
		var c rune
		var s []byte
		fmt.Fscanf(r, "\n%d %c\n%s", &n, &c, &s)

		for i, v := range s {
			if v == 'g' {
				pd = i
				break
			}
		}

		for j := n-1; j >= 0; j-- {
			if s[j] == 'g' {
				cd = 0
			} else {
				cd = pd + 1
			}

			if s[j] == byte(c) && cd > res {
				res = cd
			}
			pd = cd
		}

		fmt.Fprintln(w, res)
	}
}

package main

import "fmt"

func main() {
	var (
		t, n, max, cur int
		c, pattern     string
	)
	fmt.Scan(&t)
	for j := 0; j < t; j++ {
		fmt.Scan(&n, &c)
		fmt.Scan(&pattern)
		if c == "g" {
			fmt.Println(0)
			continue
		}
		max = 0
		for i := 0; i < 2*n; i++ {
			for ; pattern[i%n] != c[0]; i++ {
			}
			cur = 0
			for ; i < 2*n; i++ {
				if pattern[i%n] == "g"[0] {
					if cur > max {
						max = cur
					}
					break
				}
				cur += 1
			}
		}
		fmt.Println(max)
	}
}

package main

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

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

func max(i, j int) int {
    if i >= j {
        return i
    } else {
        return j
    }
}

func solve() {
    var n int
    var c, s string
    Fscan(in, &n, &c, &s)

    s = s + s
    ans := 0
    for i, j := 0, 0; i < 2 * n; i++ {
        if string(s[i]) != c {
            continue
        }

        for ; j < 2 * n && (j < i || string(s[j]) != "g"); j++ {

        }

        if j < 2 * n && j - i > ans {
            ans = j - i
        }
    }

    Fprintln(out, ans)
}

func main() {
    var T int
    Fscan(in, &T)
    for ; T > 0; T-- {
        solve()
    }
    out.Flush()
}

package main

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

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

func solve() {
	_ = _readInt()
	start := rune(_readStr()[0])
	s := []rune(_readStr())
	if start == 'g' {
		_print(0)
		return
	}

	var fg int
	for s[fg] != 'g' {
		fg++
	}
	s = append(s, s[:fg+1]...)

	var res int
	for i := 0; i < len(s); i++ {
		if s[i] == start {
			var cnt int
			for s[i] != 'g' {
				cnt++
				i++
			}
			res = _max(res, cnt)
		}
	}
	_print(res)
}

func main() {
	defer out.Flush()
	var t int
	for fmt.Fscanln(in, &t); t > 0; t-- {
		solve()
	}
}

// ====
func _readInt() int {
	var x int
	fmt.Fscan(in, &x)
	return x
}
func _readStr() string {
	var x string
	fmt.Fscan(in, &x)
	return x
}
func _readArr() (int, []int) {
	var n int
	fmt.Fscan(in, &n)
	var v = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &v[i])
	}
	return n, v
}
func _print(x ...any) {
	fmt.Fprintln(out, x...)
}
func _max(x, y int) int {
	if x > y {
		return x
	}
	return y
}
func _min(x, y int) int {
	if x < y {
		return x
	}
	return y
}
func _abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}
func _sortStr(x string) string {
	r := []rune(x)
	sort.Slice(r, func(i, j int) bool {
		return r[i] < r[j]
	})
	return string(r)
}
func _reverseInts(x []int) {
	n := len(x)
	for i := 0; i < n/2; i++ {
		x[i], x[n-1-i] = x[n-1-i], x[i]
	}
}
func _reverseStr(s string) string {
	x := []rune(s)
	n := len(x)
	for i := 0; i < n/2; i++ {
		x[i], x[n-1-i] = x[n-1-i], x[i]
	}
	return string(x)
}

package main

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

var sc = bufio.NewScanner(os.Stdin)

const mod int = 998244353
const N int = 5e5 + 5

func main() {
	sc.Buffer(make([]byte, 500000*1+1), 500000)
	sc.Split(bufio.ScanWords)

	T := nextInt()
	for T > 0 {
		T--
		n, c := nextInt(), nextString()[0]
		s := nextString()
		idx := 0
		for i := 0; i < n; i++ {
			if s[i] == 'g' {
				idx = i
				break
			}
		}
		flag := false
		ans := 0
		for i, j := n-1, -1; i >= 0; i-- {
			if !flag && s[i] == 'g' {
				flag = true
			}
			if s[i] == 'g' {
				j = i
			}
			if s[i] != c {
				continue
			}
			if !flag {
				ans = max(ans, n-i+idx)
			} else {
				ans = max(ans, j-i)
			}
		}
		fmt.Println(ans)
	}
}

func max(args ...int) int {
	res := args[0]
	for _, v := range args {
		if v > res {
			res = v
		}
	}
	return res
}

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

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

package main

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

const cf = true

func solve() {
	var n int
	var c string
	fmt.Fscan(in, &n, &c)
	var str string
	fmt.Fscan(in, &str)
	worst := make(map[byte]int)
	curG := 0
	for str[curG] != byte('g') {
		curG++
	}
	curG += n
	for i := n - 1; i >= 0; i-- {
		if str[i] == byte('g') {
			curG = i
			continue
		}
		val, ok := worst[str[i]]
		if !ok {
			worst[str[i]] = curG - i
		} else {
			worst[str[i]] = max(val, curG-i)
		}
	}
	fmt.Fprintln(out, worst[c[0]])
}

func main() {
	defer out.Flush()
	t := 1
	fmt.Fscan(in, &t)
	for ; t > 0; t-- {
		solve()
	}
}

func GCD(a, b int) int {
	for a != b {
		if a > b {
			a -= b
		} else {
			b -= a
		}
	}

	return a
}

type SqrtInt interface {
	SignedSqrt | UnsignedSqrt
}

type SignedSqrt interface {
	~int | ~int32 | ~int64
}

type UnsignedSqrt interface {
	~uint | ~uint32 | ~uint64 | ~uintptr
}

func sqrt[T SqrtInt](x T) T {
	l, r := T(0), T(2000000123)
	for l < r {
		mid := (l + r) / 2
		if mid*mid > x {
			r = mid
		} else {
			l = mid + 1
		}
	}
	return l - 1
}

func ConvertInt(val string, base, toBase int) (string, error) {
	i, err := strconv.ParseInt(val, base, 64)
	if err != nil {
		return "", err
	}
	return strconv.FormatInt(i, toBase), nil
}

type set[T Ordered] struct {
	itms map[T]struct{}
}

func (s *set[T]) init() {
	if s.itms == nil {
		s.itms = make(map[T]struct{})
	}
}

func (s *set[T]) add(item T) *set[T] {
	s.init()
	s.itms[item] = exists
	return s
}

func (s *set[T]) remove(item T) *set[T] {
	s.init()
	delete(s.itms, item)
	return s
}

func (s *set[T]) has(item T) bool {
	s.init()
	_, c := s.itms[item]
	return c
}

func (s *set[T]) sortedItems() []T {
	s.init()
	items := make([]T, 0, s.size())
	for item := range s.itms {
		items = append(items, item)
	}
	sort.Slice(items, func(i, j int) bool {
		return items[i] < items[j]
	})
	return items
}

func (s *set[T]) items() []T {
	s.init()
	items := make([]T, 0, s.size())
	for item := range s.itms {
		items = append(items, item)
	}
	return items
}

func (s *set[T]) size() int {
	s.init()
	return len(s.itms)
}

var exists = struct{}{}

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

func reverseStr(s string) string {
	r := []byte(s)
	for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
		r[i], r[j] = r[j], r[i]
	}
	return string(r)
}

type Float interface {
	~float32 | ~float64
}

type Integer interface {
	Signed | Unsigned
}

type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

type Unsigned interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

type Ordered interface {
	Integer | Float | ~string
}

func abs[T Signed](x T) T {
	if x < 0 {
		return -x
	}
	return x
}

func min[T Ordered](x, y T) T {
	if x < y {
		return x
	}
	return y
}

func max[T Ordered](x, y T) T {
	if x > y {
		return x
	}
	return y
}

var (
	in  = getReader()
	out = getWriter()
)

func getReader() *bufio.Reader {
	if cf {
		return bufio.NewReader(os.Stdin)
	} else {
		in, _ := os.Open("input.txt")
		return bufio.NewReader(in)
	}
}

func getWriter() *bufio.Writer {
	if cf {
		return bufio.NewWriter(os.Stdout)
	} else {
		out, _ := os.Create("output.txt")
		return bufio.NewWriter(out)
	}
}

package main

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

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

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

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

		ch := c[0]
		if ch == 'g' {
			fmt.Fprintln(out, 0)
			continue
		}

		last := -1
		var mx int
		var crossed bool
		for i := 0; i < n; i++ {
			if s[i] == ch {
				if last < 0 || crossed {
					last = i
					crossed = false
				}
			} else if s[i] == 'g' && last >= 0 {
				mx = max(mx, i-last)
				crossed = true
			}
		}
		if last > 0 && !crossed {
			var d int
			for i := range s {
				if s[i] == 'g' {
					d = i
					break
				}
			}
			mx = max(mx, n-last+d)
		}
		fmt.Fprintln(out, mx)
	}
}


This problem is interactive.We decided to play a game with you and guess the number $$$x$$$ ($$$1 \le x < n$$$), where you know the number $$$n$$$.You can make queries like this: + c: this command assigns $$$x = x + c$$$ ($$$1 \le c < n$$$) and then returns you the value $$$\lfloor\frac{x}{n}\rfloor$$$ ($$$x$$$ divide by $$$n$$$ and round down).You win if you guess the current number with no more than $$$10$$$ queries.

NoteIn the first sample initially $$$x = 2$$$. After the first query $$$x = 3$$$, $$$\lfloor\frac{x}{n}\rfloor = 1$$$.In the second sample also initially $$$x = 2$$$. After the first query $$$x = 3$$$, $$$\lfloor\frac{x}{n}\rfloor = 0$$$. After the second query $$$x = 4$$$, $$$\lfloor\frac{x}{n}\rfloor = 0$$$. After the third query $$$x=5$$$, $$$\lfloor\frac{x}{n}\rfloor = 1$$$.

package main

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

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

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

func redirectInputToFile(r *bufio.Reader, fp string) {
	f, err := os.Open(fp)
	if err != nil {
		panic(err)
	}
	r.Reset(f)
}

func main() {
	// defer writer.Flush()
	// redirectInputToFile(reader, "input.txt")

	T := 1
	// scan(&T)
	for t := 0; t < T; t++ {
		solve()
	}
}

func solve() {
	var n int
	scan(&n)
	var (
		sum  = 0
		k    = 0
		l, r = 0, n
	)
	for r-l > 1 {
		m := l + (r-l)/2
		req := n - m
		if sum%n > 0 {
			if n-m-sum%n < 0 {
				req += n - sum%n
			} else {
				req -= sum % n
			}
		}
		resp := ask(req)
		if resp == k {
			r = m
		} else {
			l = m
		}
		sum += req
		k = resp
	}
	printf("! %v\n", sum+l)
	writer.Flush()
}

func ask(c int) (r int) {
	printf("+ %v\n", c)
	writer.Flush()
	scan(&r)
	return
}

package main

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

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

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

func redirectInputToFile(r *bufio.Reader, fp string) {
	f, err := os.Open(fp)
	if err != nil {
		panic(err)
	}
	r.Reset(f)
}

func main() {
	// defer writer.Flush()
	// redirectInputToFile(reader, "input.txt")

	T := 1
	// scan(&T)
	for t := 0; t < T; t++ {
		solve()
	}
}

func solve() {
	var n int
	scan(&n)
	var (
		sum  = 0
		k    = 0
		l, r = 0, n
	)
	for r-l > 1 {
		m := l + (r-l)/2
		req := n - m
		if sum%n > 0 {
			if n-m-sum%n < 0 {
				req += n - sum%n
			} else {
				req -= sum % n
			}
		}
		if req >= n {
			panic("123")
		}
		// printf("--> %v %v [%v] n-m=%v sum%%n=%v k=%v\n", l, r, m, n-m, sum%n, k)
		// writer.Flush()
		resp := ask(req)
		writer.Flush()
		if resp == k {
			r = m
		} else {
			l = m
		}
		sum += req
		k = resp
	}
	printf("! %v\n", sum+l)
	writer.Flush()
}

func ask(c int) (r int) {
	printf("+ %v\n", c)
	writer.Flush()
	scan(&r)
	return
}

package main

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

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

	ask := func(c int) int {
		fmt.Printf("+ %d\n", c)
		return readNum(reader)
	}

	n := readNum(reader)

	res := solve(n, ask)

	fmt.Printf("! %d\n", res)
}

func readString(reader *bufio.Reader) string {
	s, _ := reader.ReadString('\n')
	for i := 0; i < len(s); i++ {
		if s[i] == '\n' {
			return s[:i]
		}
	}
	return s
}

func normalize(s string) string {

	for i := len(s); i > 0; i-- {
		if s[i-1] >= 'a' && s[i-1] <= 'z' {
			return s[:i]
		}
	}
	return ""
}

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

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

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

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

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

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

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

	return i
}

func solve(n int, ask func(c int) int) int {

	l, r := 1, n
	var div int

	for r-l > 1 {
		mid := (l + r) / 2
		d := ask(n - mid)

		if d > div {
			l = mid
		} else {
			r = mid
		}
		l = (l + n - mid) % n
		r = (r + n - mid) % n
		if r == 0 {
			r = n
		}
		div = d
	}

	return div*n + l
}

// generated by 1e9y at 10-01-2022
// template version: 2022-01

package main

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

// 1624.F
func solve() {
	// here goes solution
}

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

	n := ReadInt(in)
	left, right := 1, n
	prev, total := 0, 0
	var mid, curr int
	for left <= right {
		mid = left + (right-left)/2
		c := (prev+1)*n - (mid + total)
		total += c
		Fprintf(out, "+ %v\n", c)
		out.Flush()
		curr = ReadInt(in)
		if curr <= prev {
			right = mid - 1
		} else {
			left = mid + 1
		}
		prev = curr
		// here goes input reading
		// input := ReadIntSlice(in)
	}
	Fprintf(out, "! %v\n", right+total)
	out.Flush()
}

// helpers for convenient input reading

func ReadInt(in *bufio.Reader) int {
	line, _ := in.ReadString('\n')
	line = strings.Trim(line, "\n\r")
	n, _ := strconv.Atoi(line)
	return n
}

func ReadLine(in *bufio.Reader) string {
	line, _ := in.ReadString('\n')
	line = strings.Trim(line, "\n\r")
	return line
}

func ReadLineParts(in *bufio.Reader) []string {
	line, _ := in.ReadString('\n')
	line = strings.Trim(line, "\n\r")
	parts := strings.Split(line, " ")
	return parts
}

func ReadIntSlice(in *bufio.Reader) []int {
	parts := ReadLineParts(in)
	slice := make([]int, len(parts))
	for i, n := range parts {
		slice[i] = MustAtoi(n)
	}
	return slice
}

func ReadInt64Slice(in *bufio.Reader) []int64 {
	parts := ReadLineParts(in)
	slice := make([]int64, len(parts))
	for i, n := range parts {
		slice[i] = MustParseInt(n, 10, 64)
	}
	return slice
}

func ReadUint64Slice(in *bufio.Reader) []uint64 {
	parts := ReadLineParts(in)
	slice := make([]uint64, len(parts))
	for i, n := range parts {
		slice[i] = MustParseUint(n, 10, 64)
	}
	return slice
}

func MustAtoi(s string) int {
	v, _ := strconv.Atoi(s)
	return v
}

func MustParseInt(s string, base, bitSize int) int64 {
	v, _ := strconv.ParseInt(s, base, bitSize)
	return v
}

func MustParseUint(s string, base, bitSize int) uint64 {
	v, _ := strconv.ParseUint(s, base, bitSize)
	return v
}

func SkipLine(in *bufio.Reader) {
	_, _ = in.ReadString('\n')
}

package main

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

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

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

func redirectInputToFile(r *bufio.Reader, fp string) {
	f, err := os.Open(fp)
	if err != nil {
		panic(err)
	}
	r.Reset(f)
}

func main() {
	// defer writer.Flush()
	// redirectInputToFile(reader, "input.txt")

	T := 1
	// scan(&T)
	for t := 0; t < T; t++ {
		solve()
	}
}

func solve() {
	var n int
	scan(&n)
	var (
		sum  = 0
		k    = 0
		l, r = 1, n
	)
	for r-l > 1 {
		m := l + (r-l)/2
		req := n - m
		if sum%n > 0 {
			if n-m-sum%n < 0 {
				req += n - sum%n
				k++
			} else {
				req -= sum % n
			}
		}
		if req >= n {
			panic("123")
		}
		resp := ask(req)
		if resp == k {
			r = m
		} else {
			l = m
		}
		sum += req
		k = resp
	}
	printf("! %v\n", sum+l)
	writer.Flush()
}

func ask(c int) (r int) {
	printf("+ %v\n", c)
	writer.Flush()
	scan(&r)
	return
}

package main

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

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

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

func redirectInputToFile(r *bufio.Reader, fp string) {
	f, err := os.Open(fp)
	if err != nil {
		panic(err)
	}
	r.Reset(f)
}

func main() {
	// defer writer.Flush()
	// redirectInputToFile(reader, "input.txt")

	T := 1
	// scan(&T)
	for t := 0; t < T; t++ {
		solve()
	}
}

func solve() {
	var n int
	scan(&n)
	var (
		sum  = 0
		k    = 0
		l, r = 1, n
	)
	for r-l > 1 {
		m := l + (r-l)/2
		req := n - m
		if sum%n > 0 {
			if n-m-sum%n < 0 {
				req += n - sum%n
				k++
			} else {
				req -= sum % n
			}
		}
		if req >= n {
			panic("123")
		}
		resp := ask(req)
		if resp == k {
			r = m
		} else {
			l = m
		}
		sum += req
	}
	printf("! %v\n", l)
	writer.Flush()
}

func ask(c int) (r int) {
	printf("+ %v\n", c)
	writer.Flush()
	scan(&r)
	return
}

package main

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

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

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

func redirectInputToFile(r *bufio.Reader, fp string) {
	f, err := os.Open(fp)
	if err != nil {
		panic(err)
	}
	r.Reset(f)
}

func main() {
	// defer writer.Flush()
	// redirectInputToFile(reader, "input.txt")

	T := 1
	// scan(&T)
	for t := 0; t < T; t++ {
		solve()
	}
}

func solve() {
	var n int
	scan(&n)
	var (
		sum  = 0
		k    = 0
		l, r = 1, n
	)
	for r-l > 1 {
		// printf("Request: %v %v %v\n", l, r, l+(r-l)/2)
		// writer.Flush()

		m := l + (r-l)/2
		req := n - m
		if sum%n > 0 {
			req += n - sum%n
			if sum/n < (sum+n-sum%n)/n {
				k++
			}
		}

		// printf("%v %v\n\n", req, k)
		// writer.Flush()

		resp := ask(req)
		if resp == k {
			r = m
		} else {
			l = m
		}
		sum += req
	}
	printf("! %v\n", l)
	writer.Flush()
}

func ask(c int) (r int) {
	printf("+ %v\n", c)
	writer.Flush()
	scan(&r)
	return
}

package main

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

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

	ask := func(c int) int {
		fmt.Printf("+ %d\n", c)
		return readNum(reader)
	}

	n := readNum(reader)

	res := solve(n, ask)

	fmt.Printf("! %d\n", res)
}

func readString(reader *bufio.Reader) string {
	s, _ := reader.ReadString('\n')
	for i := 0; i < len(s); i++ {
		if s[i] == '\n' {
			return s[:i]
		}
	}
	return s
}

func normalize(s string) string {

	for i := len(s); i > 0; i-- {
		if s[i-1] >= 'a' && s[i-1] <= 'z' {
			return s[:i]
		}
	}
	return ""
}

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

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

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

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

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

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

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

	return i
}

func solve(n int, ask func(c int) int) int {

	l, r := 1, n

	i := 1
	var sum int
	for l < r {
		mid := (l + r) / 2

		tmp := i*n + mid - sum
		// x + n + mid
		ans := ask(tmp)

		// this time ask tmp
		// and we want x + tmp + tmp2 = x + i * n - mid
		// tmp2 = i * n - mid - tmp

		sum += tmp

		if ans == i {
			// x + mid < n
			// x <  n - mid
			// what now? in next round, we need to increase mid, to make it approch x
			l = mid + 1
		} else {
			// ans = expect + 1
			// x >= n - mid
			r = mid
		}
		i++
	}

	return sum + n - r
}

// generated by 1e9y at 10-01-2022
// template version: 2022-01

package main

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

// 1624.F
func solve() {
	// here goes solution
}

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

	n := ReadInt(in)
	left, right := 1, n
	prev, total := 0, 0
	var mid, curr int
	for left <= right {
		mid = left + (right-left)/2
		c := (prev+1)*n - (mid + total)
		Fprintf(out, "+ %v\n", c)
		out.Flush()
		curr = ReadInt(in)
		if curr <= prev {
			right = mid - 1
		} else {
			left = mid + 1
		}
		prev = curr
		// here goes input reading
		// input := ReadIntSlice(in)
	}
	Fprintf(out, "! %v\n", right+total)
	out.Flush()
}

// helpers for convenient input reading

func ReadInt(in *bufio.Reader) int {
	line, _ := in.ReadString('\n')
	line = strings.Trim(line, "\n\r")
	n, _ := strconv.Atoi(line)
	return n
}

func ReadLine(in *bufio.Reader) string {
	line, _ := in.ReadString('\n')
	line = strings.Trim(line, "\n\r")
	return line
}

func ReadLineParts(in *bufio.Reader) []string {
	line, _ := in.ReadString('\n')
	line = strings.Trim(line, "\n\r")
	parts := strings.Split(line, " ")
	return parts
}

func ReadIntSlice(in *bufio.Reader) []int {
	parts := ReadLineParts(in)
	slice := make([]int, len(parts))
	for i, n := range parts {
		slice[i] = MustAtoi(n)
	}
	return slice
}

func ReadInt64Slice(in *bufio.Reader) []int64 {
	parts := ReadLineParts(in)
	slice := make([]int64, len(parts))
	for i, n := range parts {
		slice[i] = MustParseInt(n, 10, 64)
	}
	return slice
}

func ReadUint64Slice(in *bufio.Reader) []uint64 {
	parts := ReadLineParts(in)
	slice := make([]uint64, len(parts))
	for i, n := range parts {
		slice[i] = MustParseUint(n, 10, 64)
	}
	return slice
}

func MustAtoi(s string) int {
	v, _ := strconv.Atoi(s)
	return v
}

func MustParseInt(s string, base, bitSize int) int64 {
	v, _ := strconv.ParseInt(s, base, bitSize)
	return v
}

func MustParseUint(s string, base, bitSize int) uint64 {
	v, _ := strconv.ParseUint(s, base, bitSize)
	return v
}

func SkipLine(in *bufio.Reader) {
	_, _ = in.ReadString('\n')
}


Now you get Baby Ehab's first words: "Given an integer $$$n$$$, find the longest subsequence of $$$[1,2, \ldots, n-1]$$$ whose product is $$$1$$$ modulo $$$n$$$." Please solve the problem.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly all) elements. The product of an empty subsequence is equal to $$$1$$$.

The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$).

The first line should contain a single integer, the length of the longest subsequence. The second line should contain the elements of the subsequence, in increasing order. If there are multiple solutions, you can print any.

NoteIn the first example, the product of the elements is $$$6$$$ which is congruent to $$$1$$$ modulo $$$5$$$. The only longer subsequence is $$$[1,2,3,4]$$$. Its product is $$$24$$$ which is congruent to $$$4$$$ modulo $$$5$$$. Hence, the answer is $$$[1,2,3]$$$.

package main

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

// github.com/EndlessCheng/codeforces-go
func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	primeDivisors := func(x int) (primes []int) {
		for i := 2; i*i <= x; i++ {
			if x%i == 0 {
				for x /= i; x%i == 0; x /= i {
				}
				primes = append(primes, i)
			}
		}
		if x > 1 {
			primes = append(primes, x)
		}
		return
	}

	var n int
	Fscan(in, &n)
	if n == 2 {
		Fprintln(out, 1)
		Fprintln(out, 1)
		return
	}
	ans := []int{}

	ps := primeDivisors(n)
	if ps[0] == n {
		for i := 1; i < n-1; i++ {
			ans = append(ans, i)
		}
		Fprintln(out, len(ans))
		for _, v := range ans {
			Fprint(out, v, " ")
		}
		return
	}

	del := make([]bool, n)
	for _, p := range ps {
		for i := p; i < n; i += p {
			del[i] = true
		}
	}

	mul := int64(1)
	for i := 1; i < n-1; i++ {
		if !del[i] {
			ans = append(ans, i)
			mul = mul * int64(i) % int64(n)
		}
	}
	if mul != 1 {
		mul = mul*int64(n-1)%int64(n)
		ans = append(ans, n-1)
	}
	if mul != 1 {
		panic(n)
	}
	//Println(n,mul, len(ans))
	Fprintln(out, len(ans))
	for _, v := range ans {
		Fprint(out, v, " ")
	}
}

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

package main

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

func gcd(x, y int)int{
	for y>0{
		temp :=y
		y = x%y
		x = temp
	}
	return x
}
func max(x, y int)int{
	if x>y{
		return x
	}
	return y
}
func main() {
	var n int
	in := bufio.NewReader(os.Stdin)
	out := os.Stdout
	fmt.Fscan(in,&n)
	ans := []int{}
	for i:=1;i<=n-1;i++{
		if gcd(n,i)==1{
			ans = append(ans,i)
		}
	}
	var cool int64
	cool = 1
	ma := 0
	for i:=0;i<len(ans);i++{
		cool = (cool%int64(n) * int64(ans[i]%n))%int64(n)
		if cool==1{
			ma = i
		}
	}
	cool = 1
	fmt.Fprintln(out,ma+1)
	for i:=0;i<=ma;i++{
		cool = (cool%int64(n) * int64(ans[i])%int64(n))%int64(n)
		fmt.Fprintf(out,"%d " ,ans[i])
	}
}

package main

import "fmt"

func gcd(a, b int) int {
	if b > a {
		return gcd(b, a)
	}
	if b == 0 {
		return a
	}
	return gcd(b, a%b)
}

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

	candi := []int64{}
	candiProd := int64(1)
	for i := 1; i < n; i++ {
		if gcd(i, n) != 1 {
			continue
		}
		candi = append(candi, int64(i))
		candiProd *= int64(i)
		candiProd %= int64(n)
	}
	if candiProd != 1 {
		for i, v := range candi {
			if v != candiProd {
				continue
			}
			candi = append(candi[:i], candi[i+1:]...)
			break
		}
	}
	fmt.Println(len(candi))
	for _, v := range candi {
		fmt.Print(v, " ")
	}
	fmt.Println()
}

package main

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

func gcd(a, b int64) int64 {
	if b == 0 {
		return a
	}
	return gcd(b, a%b)

}
func exgcd(a, b int64) (gcd, x, y int64) {
	if b == 0 {
		return a, 1, 0
	}
	gcd, y, x = exgcd(b, a%b)
	y -= a / b * x
	return
}
func inv(a, b int64) int64 {
	_, x, _ := exgcd(a, b)
	x = (x%b + b) % b
	return x
}

func run(or io.Reader, ow io.Writer) {
	in := bufio.NewReader(or)
	out := bufio.NewWriter(ow)
	defer out.Flush()

	solve := func() {
		var n int64
		fmt.Fscan(in, &n)
		var prod int64 = 1

		for i := int64(1); i < n; i++ {
			if gcd(n, i) == 1 {
				prod = prod * i % n
			}
		}

		var j int64 = inv(prod, n)
		var ans []int64
		for i := int64(1); i < n; i++ {
			if gcd(n, i) == 1 {
				if i*j%n != 1 || prod == 1 {
					ans = append(ans, i)
				}
			}
		}
		fmt.Fprintln(out, len(ans))
		for i := 0; i < len(ans); i++ {
			fmt.Fprint(out, ans[i], " ")
		}
		fmt.Fprintln(out)
	}

	var T int = 1
	// fmt.Fscan(in, &T)
	for o := 0; o < T; o++ {
		solve()
	}

}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	primeDivisors := func(x int) (primes []int) {
		for i := 2; i*i <= x; i++ {
			if x%i == 0 {
				for x /= i; x%i == 0; x /= i {
				}
				primes = append(primes, i)
			}
		}
		if x > 1 {
			primes = append(primes, x)
		}
		return
	}

	var n int
	Fscan(in, &n)
	ps := primeDivisors(n)

	del := make([]bool, n)
	for _, p := range ps {
		for i := p; i < n; i += p {
			del[i] = true
		}
	}

	mul := 1
	ans := []int{}
	for i := 1; i < n-1; i++ {
		if !del[i] {
			ans = append(ans, i)
			mul = mul * i % n
		}
	}
	if mul != 1 {
		ans = append(ans, n-1)
		mul = mul*(n-1)%n
	}
	Fprintln(out, len(ans))
	for _, v := range ans {
		Fprint(out, v, " ")
	}
}

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

package main

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

func gcd(x, y int)int{
	for y>0{
		temp :=y
		y = x%y
		x = temp
	}
	return x
}
func max(x, y int)int{
	if x>y{
		return x
	}
	return y
}
func main() {
	var n int
	in := bufio.NewReader(os.Stdin)
	out := os.Stdout
	fmt.Fscan(in,&n)
	ans := []int{}
	for i:=1;i<=n-1;i++{
		if gcd(n,i)==1{
			ans = append(ans,i)
		}
	}
	cool := 1
	ma := 0
	for i:=0;i<len(ans);i++{
		cool = (cool%n * ans[i]%n)%n
		if cool==1{
			ma = i
		}
	}
	cool = 1
	fmt.Fprintln(out,ma+1)
	for i:=0;i<=ma;i++{
		cool = (cool%n * ans[i]%n)%n
		fmt.Fprintf(out,"%d " ,ans[i])
	}
}

package main

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

func gcd(x, y int)int{
	for y>0{
		temp :=y
		y = x%y
		x = temp
	}
	return x
}
func main() {
	var n int
	in := bufio.NewReader(os.Stdin)
	out := os.Stdout
	fmt.Fscan(in,&n)
	ans := []int{}
	for i:=1;i<=n-1;i++{
		if gcd(n,i)==1{
			ans = append(ans,i)
		}
	}
	if n%2==1{
		ans = ans[:len(ans)-1]
	}
	fmt.Fprintln(out,len(ans))
	for i:=0;i<len(ans);i++{
		fmt.Fprintf(out,"%d ",ans[i])
	}
}

package main

import "fmt"

func gcd(a, b int) int {
	if b > a {
		return gcd(b, a)
	}
	if b == 0 {
		return a
	}
	return gcd(b, a%b)
}

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

	candi := []int64{}
	candiProd := int64(1)
	for i := 1; i < n; i++ {
		if gcd(i, n) != 1 {
			continue
		}
		candi = append(candi, int64(i))
		candiProd *= int64(i)
		candiProd %= int64(n)
	}
	if candiProd != 1 {
		for i, v := range candi {
			if v != candiProd {
				continue
			}
			candi = append(candi[:i], candi[i+1:]...)
			break
		}
	}
	for _, v := range candi {
		fmt.Print(v, " ")
	}
	fmt.Println()
}

package main

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

func gcd(a, b int64) int64 {
	if b == 0 {
		return a
	}
	return gcd(b, a%b)

}
func exgcd(a, b int64) (gcd, x, y int64) {
	if b == 0 {
		return a, 1, 0
	}
	gcd, y, x = exgcd(b, a%b)
	y -= a / b * x
	return
}
func inv(a, b int64) int64 {
	_, x, _ := exgcd(a, b)
	x = (x%b + b) % b
	return x
}

func run(or io.Reader, ow io.Writer) {
	in := bufio.NewReader(or)
	out := bufio.NewWriter(ow)
	defer out.Flush()

	solve := func() {
		var n int64
		fmt.Fscan(in, &n)
		var prod int64 = 1

		for i := int64(1); i < n; i++ {
			if gcd(n, i) == 1 {
				prod = prod * i % n
			}
		}

		var j int64 = inv(prod, n)

		for i := int64(1); i < n; i++ {
			if gcd(n, i) == 1 {
				if i*j%n != 1 || prod == 1 {
					fmt.Fprint(out, i, " ")
				}
			}
		}
		fmt.Fprintln(out)
	}

	var T int = 1
	// fmt.Fscan(in, &T)
	for o := 0; o < T; o++ {
		solve()
	}

}

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