There are two types of burgers in your restaurant — hamburgers and chicken burgers! To assemble a hamburger you need two buns and a beef patty. To assemble a chicken burger you need two buns and a chicken cutlet. You have $$$b$$$ buns, $$$p$$$ beef patties and $$$f$$$ chicken cutlets in your restaurant. You can sell one hamburger for $$$h$$$ dollars and one chicken burger for $$$c$$$ dollars. Calculate the maximum profit you can achieve.You have to answer $$$t$$$ independent queries.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) – the number of queries. The first line of each query contains three integers $$$b$$$, $$$p$$$ and $$$f$$$ ($$$1 \le b, ~p, ~f \le 100$$$) — the number of buns, beef patties and chicken cutlets in your restaurant. The second line of each query contains two integers $$$h$$$ and $$$c$$$ ($$$1 \le h, ~c \le 100$$$) — the hamburger and chicken burger prices in your restaurant.

For each query print one integer — the maximum profit you can achieve.

NoteIn first query you have to sell two hamburgers and three chicken burgers. Your income is $$$2 \cdot 5 + 3 \cdot 10 = 40$$$.In second query you have to ell one hamburgers and two chicken burgers. Your income is $$$1 \cdot 10 + 2 \cdot 12 = 34$$$.In third query you can not create any type of burgers because because you have only one bun. So your income is zero.

t = readline.to_i

t.times do
  b,p,f = readline.split.map(&:to_i)
  h,c = readline.split.map(&:to_i)
  if h >= c
    p1 = [b/2,p].min
    p2 = [(b - 2*p1)/2,f].min
  else
    p2 = [b/2,f].min
    p1 = [(b - 2*p2)/2,p].min
  end
  puts h*p1 + c*p2
end

q = gets.to_i
q.times do
  n,a,b = gets.split.map(&:to_i)
  h,c = gets.split.map(&:to_i)
  ans = 0
  if h > c
    t = [n/2,a].min
    ans += t*h
    n -= t*2
    ans += c*[n/2,b].min
  else
    t = [n/2,b].min
    ans += t*c
    n -= t*2
    ans += h*[n/2,a].min
  end
  p ans
end

t=gets.to_i
while t > 0
  total = 0
  b, p, f = gets.split.map(&:to_i)
  h, c= gets.split.map(&:to_i)
  t-=1
  if h > c
      total += ([(b/2).to_i, p].min) * h
      b -= ([(b/2).to_i, p].min)*2
      total += ([(b/2).to_i, f].min) * c
  else
      total += ([(b/2).to_i, f].min) * c
      b -= ([(b/2).to_i, f].min)*2
      total += ([(b/2).to_i, p].min) * h
  end
  puts(total)
end

gets.to_i.times do
  b, p, f = gets.split.map(&:to_i)
  h, c = gets.split.map(&:to_i)
  ans = 0
  if h >= c
    p_num = [b/2, p].min
    b -= p_num * 2
    ans += p_num * h
    ans += [b/2, f].min * c
  else
    f_num = [b/2, f].min
    b -= f_num * 2
    ans += f_num * c
    ans += [b/2, p].min * h
  end
  puts ans
end

# http://codeforces.com/contest/1207/problem/A

def maximum_profit
  q = gets.chomp.to_i
  results = Array.new
  until q.zero? do
    ingredients = gets.chomp
    ingredients = get_each(ingredients)
    prices = gets.chomp
    prices = get_each(prices)
    results << get_maximum(ingredients, prices)
    q -= 1
  end
  results
end
$burger_num = 0

def get_maximum(ingredients, prices)
  $burger_num = ingredients[0]/2
  ham_num = ingredients[1]
  chicken_num = ingredients[2]
  pay = 0
  if prices[0] >= prices[1]
    pay += payment(prices[0], ham_num)
    pay += payment(prices[1], chicken_num)
  else
    pay += payment(prices[1], chicken_num)
    pay += payment(prices[0], ham_num)
  end
  pay
end

def payment(price, ingredient)
  pay = 0
  if $burger_num >= ingredient
    pay = price * ingredient
    $burger_num -= ingredient
  else
    pay = price * $burger_num
    $burger_num = 0
  end
  pay
end

def get_each(str)
  arr = Array.new
  num = 0
  str.each_char do |e|
    if e == ' '
      arr << num
      num = 0
    else
      num = num * 10 + e.to_i
    end
  end
  arr << num unless num.zero?
  arr
end

puts maximum_profit

t = gets.to_i
bpf = []
hc = []
t.times do|_x|
   bpf << gets.split.map(&:to_i)
   hc << gets.split.map(&:to_i)
end

max = []
0.upto(t-1) do |i|
  price = 0
  buns = bpf[i][0]
  beef = bpf[i][1]
  chi = bpf[i][2]
  price1 = hc[i][0]
  price2 = hc[i][1]

  if price1 >= price2
    # ハンバーガーを優先して作る
    if beef*2 > buns
      # beefが多いならbunsが足りるまで使う
      price =  buns / 2 * price1
    else
      buns -= beef * 2
      price = beef*price1 + (chi*2>buns ? buns/2 : chi)*price2
    end
  else
    # チキンバーガーを優先して作る
    if chi*2 > buns
      # chiが多いならbunsが足りるまで使う
      price =  buns / 2 * price2
    else
      buns -= chi * 2
      price = chi*price2 + (beef*2>buns ? buns/2 : beef)*price1
    end
  end
  max << price
end
puts max.join("\n")

t = gets.to_i
t.times do
  b, p, f = gets.split.map &:to_i
  h, c = gets.split.map &:to_i
  if h > c
    hs = [b/2, p].min
    cs = [(b - hs*2)/2, f].min
  else
    cs = [b/2, f].min
    hs = [(b - cs*2)/2, p].min
  end
  puts hs*h + cs*c
end

1.upto(gets.to_i) do
  b, p, f = gets.split(' ').map(&:to_i)
  h, c = gets.split(' ').map(&:to_i)

  puts (0..b/2).map { |x| [x, p].min*h + [(b/2 - x), f].min*c }.max
end


"The Chamber of Secrets has been opened again" — this news has spread all around Hogwarts and some of the students have been petrified due to seeing the basilisk. Dumbledore got fired and now Harry is trying to enter the Chamber of Secrets. These aren't good news for Lord Voldemort. The problem is, he doesn't want anybody to be able to enter the chamber. The Dark Lord is going to be busy sucking life out of Ginny.The Chamber of Secrets is an n × m rectangular grid in which some of the cells are columns. A light ray (and a basilisk's gaze) passes through the columns without changing its direction. But with some spell we can make a column magic to reflect the light ray (or the gaze) in all four directions when it receives the ray. This is shown in the figure below.   The left light ray passes through a regular column, and the right ray — through the magic column.  The basilisk is located at the right side of the lower right cell of the grid and is looking to the left (in the direction of the lower left cell). According to the legend, anyone who meets a basilisk's gaze directly dies immediately. But if someone meets a basilisk's gaze through a column, this person will get petrified. We know that the door to the Chamber is located on the left side of the upper left corner of the grid and anyone who wants to enter will look in the direction of its movement (in the direction of the upper right cell) from that position.   This figure illustrates the first sample test.  Given the dimensions of the chamber and the location of regular columns, Lord Voldemort has asked you to find the minimum number of columns that we need to make magic so that anyone who wants to enter the chamber would be petrified or just declare that it's impossible to secure the chamber.

The first line of the input contains two integer numbers n and m (2 ≤ n, m ≤ 1000). Each of the next n lines contains m characters. Each character is either "." or "#" and represents one cell of the Chamber grid. It's "." if the corresponding cell is empty and "#" if it's a regular column.

Print the minimum number of columns to make magic or -1 if it's impossible to do.

NoteThe figure above shows the first sample test. In the first sample we should make both columns magic. The dragon figure represents the basilisk and the binoculars represent the person who will enter the Chamber of secrets. The black star shows the place where the person will be petrified. Yellow lines represent basilisk gaze moving through columns.

n,m = gets.split.map &:to_i
a = [nil]*(n+m)
0.upto(n+m) {|i| a[i] = []}

0.upto(n-1) do |i|
  s = gets.chomp
  len = s.size
  0.upto(len) do |j|
    if s[j] == '#'
      a[i] << n+j
      a[n+j] << i
    end
  end
end

d = [100500] * 2100
q = []
d[0] = 0
q << 0
while !q.empty? do
  x = q.shift
  a[x].each do |y|
    if d[y] == 100500
      d[y] = d[x] + 1
      q << y
    end
  end
end

if d[n-1] == 100500
  puts -1
  exit
end
puts d[n-1]


The only difference between the easy and hard versions is that the given string $$$s$$$ in the easy version is initially a palindrome, this condition is not always true for the hard version.A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.Alice and Bob are playing a game on a string $$$s$$$ (which is initially a palindrome in this version) of length $$$n$$$ consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.In each turn, the player can perform one of the following operations:   Choose any $$$i$$$ ($$$1 \le i \le n$$$), where $$$s[i] =$$$ '0' and change $$$s[i]$$$ to '1'. Pay 1 dollar.  Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa. Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^3$$$). The second line of each test case contains the string $$$s$$$ of length $$$n$$$, consisting of the characters '0' and '1'. It is guaranteed that the string $$$s$$$ is a palindrome and contains at least one '0'.  Note that there is no limit on the sum of $$$n$$$ over test cases.

For each test case print a single word in a new line:    "ALICE", if Alice will win the game,  "BOB", if Bob will win the game,  "DRAW", if the game ends in a draw.

NoteIn the first test case of the example,   in the $$$1$$$-st move Alice has to perform the $$$1$$$-st operation, since the string is currently a palindrome.  in the $$$2$$$-nd move Bob reverses the string.  in the $$$3$$$-rd move Alice again has to perform the $$$1$$$-st operation. All characters of the string are '1', game over.  Alice spends $$$2$$$ dollars while Bob spends $$$0$$$ dollars. Hence, Bob always wins.

gets.to_i.times {
  gets
  s = gets.strip
  n = s.count '0'
  if s.size.odd? && s[s.size / 2] == '0'
    puts(n > 1 ? 'ALICE' : 'BOB')
  else
    #puts(n % 4 == 0 ? 'DRAW' : 'BOB')
    puts 'BOB'
  end
}

gets.to_i.times do
    gets
    s = gets.chomp
    cnt = s.count '0'
    if cnt == 1
        puts "BOB"
    elsif cnt % 2 == 1
        puts "ALICE"
    else
        puts "BOB"
    end
end

gets.to_i.times{|c|
	n = gets.to_i
	s = gets.chomp
	if s.count(?0)==1 then
		puts 'BOB'
		next
	elsif s.count(?0)==0 then
		puts 'DRAW'
		next
	end
	puts (n%2==1&&s[n/2]=='0') ? 'ALICE' : 'BOB'
}

gets.to_i.times {
  gets
  n = gets.strip.count '0'
  puts(n % 4 == 0 ? 'DRAW' : 'BOB')
}


Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with $$$n$$$ elements. The $$$i$$$-th element is $$$a_i$$$ ($$$i$$$ = $$$1, 2, \ldots, n$$$). He gradually takes the first two leftmost elements from the deque (let's call them $$$A$$$ and $$$B$$$, respectively), and then does the following: if $$$A > B$$$, he writes $$$A$$$ to the beginning and writes $$$B$$$ to the end of the deque, otherwise, he writes to the beginning $$$B$$$, and $$$A$$$ writes to the end of the deque. We call this sequence of actions an operation.For example, if deque was $$$[2, 3, 4, 5, 1]$$$, on the operation he will write $$$B=3$$$ to the beginning and $$$A=2$$$ to the end, so he will get $$$[3, 4, 5, 1, 2]$$$.The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him $$$q$$$ queries. Each query consists of the singular number $$$m_j$$$ $$$(j = 1, 2, \ldots, q)$$$. It is required for each query to answer which two elements he will pull out on the $$$m_j$$$-th operation.Note that the queries are independent and for each query the numbers $$$A$$$ and $$$B$$$ should be printed in the order in which they will be pulled out of the deque.Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq q \leq 3 \cdot 10^5$$$) — the number of elements in the deque and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$, where $$$a_i$$$ $$$(0 \leq a_i \leq 10^9)$$$ — the deque element in $$$i$$$-th position. The next $$$q$$$ lines contain one number each, meaning $$$m_j$$$ ($$$1 \leq m_j \leq 10^{18}$$$).

For each teacher's query, output two numbers $$$A$$$ and $$$B$$$ — the numbers that Valeriy pulls out of the deque for the $$$m_j$$$-th operation.

inp = gets
n, q = inp.split(' ').map(&:to_i)

inp = gets
a = inp.split(' ').map(&:to_i)

i_max = 0
deque = []
n_deque = 0

for i in 0..n-1
    if a[i] > a[i_max]
        i_max = i
    end
end

for i in i_max+1..n-1
    deque[n_deque] = a[i]
    n_deque += 1
end

st = []
ed = []
n_query = 0
i1 = 0
i2 = 1

while i1 != i_max
    st[n_query] = a[i1]
    ed[n_query] = a[i2]
    if a[i1] > a[i2]
        deque[n_deque] = a[i2]
        i2 += 1
    else
        deque[n_deque] = a[i1]
        i1 = i2
        i2 += 1
    end
    n_deque += 1
    n_query += 1
end

for i in 0..q-1
    inp = gets
    q_i = inp.to_i
    if q_i <= n_query
        puts "#{st[q_i-1]} #{ed[q_i-1]}"
    else
        puts "#{a[i_max]} #{deque[(q_i - i_max + n_deque) % n_deque - 1]}"
    end
end

n, m = gets.split(' ').map(&:to_i)
l = gets.split(' ').map(&:to_i)
a, r = l[0], []
(1...n).each do |i|
  b = l[i]
  l[i] = "#{a} #{b}"
  a, b = b, a if a < b
  r.push b
end
n -= 1
m.times do
  q = gets.to_i
  puts n < q ? "#{a} #{r[(q - 1) % n]}" : l[q]
end

n, m = gets.split(' ').map(&:to_i)
l = gets.split(' ')
sa, r = l[0], []
a = sa.to_i
(1...n).each do |i|
  sb = l[i]
  b = sb.to_i
  l[i] = "#{a} #{b}"
  a, sa, sb = b, sb, sa, a if a < b
  r.push sb
end
n -= 1
m.times do
  q = gets.to_i
  puts n < q ? "#{sa} #{r[(q - 1) % n]}" : l[q]
end

n, m = gets.split(' ').map(&:to_i)
l = gets.split(' ')
sa, r = l[0], []
a = sa.to_i
(1...n).each do |i|
  sb = l[i]
  b = sb.to_i
  l[i] = "#{a} #{b}"
  a, sa, sb = b, sb, sa, a if a < b
  r.push sb
end
n -= 1
m.times do
  q = gets.to_i
  puts n < q ? "#{a} #{r[(q - 1) % n]}" : l[q]
end

inp = gets
n, q = inp.split(' ').map(&:to_i)

inp = gets
a = inp.split(' ').map(&:to_i)

i_max = 0
deque = []
n_deque = 0

for i in 0..n-1
    if a[i] > a[i_max]
        i_max = i
    end
end

for i in i_max+1..n-1
    deque[n_deque] = a[i]
    n_deque += 1
end

st = []
ed = []
n_query = 0
i1 = 0
i2 = 1

while i1 != i_max
    st[n_query] = a[i1]
    ed[n_query] = a[i2]
    if a[i1] > a[i2]
        deque[n_deque] = a[i2]
        i2 += 1
    else
        deque[n_deque] = a[i1]
        i1 = i2
        i2 += 1
    end
    n_deque += 1
    n_query += 1
end

for i in 0..q-1
    inp = gets
    q_i = inp.to_i
    if q_i <= n_query
        puts "#{st[q_i-1]} #{ed[q_i-1]}"
    else
        puts i_max
        puts q_i
        puts n_deque
        puts "#{a[i_max]} #{deque[(q_i - i_max + n_deque) % n_deque - 1]}"
    end
end

n, m = gets.split(' ').map(&:to_i)
l = gets.split(' ').map(&:to_i)
a, buf, res = l.shift, [], []
l.each do |b|
  buf.push "#{a} #{b}"
  a, b = b, a if a < b
  res.push b
end
n -= 1
m.times do
  q = gets.to_i
  puts q < n ? buf[q - 1] : "#{a} #{res[(q - 1) % n]}"
end


You are given array $$$a_1, a_2, \dots, a_n$$$. Find the subsegment $$$a_l, a_{l+1}, \dots, a_r$$$ ($$$1 \le l \le r \le n$$$) with maximum arithmetic mean $$$\frac{1}{r - l + 1}\sum\limits_{i=l}^{r}{a_i}$$$ (in floating-point numbers, i.e. without any rounding).If there are many such subsegments find the longest one.

The first line contains single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — the array $$$a$$$.

Print the single integer — the length of the longest subsegment with maximum possible arithmetic mean.

NoteThe subsegment $$$[3, 4]$$$ is the longest among all subsegments with maximum arithmetic mean.

n = gets
a = gets.to_s.chomp.split(" ").map{|x| x.to_i}
max = a.max
i = 0
res = 0
a.each do |x|
  if(x == max)
    i += 1
    res = [i, res].max
  else
    i = 0
    #print "#{x} #{max} #{i}"
    #puts
  end
end
puts res

gets
a = gets.to_s.chomp.split(" ").map{|x| x.to_i}
max = 0
i = 0
res = 0
a.each do |x|
  if(max <= x)
    i += 1
    max = x
    if(res < i)
      res = i
    end
  else
    i = 0
  end
  #print "#{x} #{max} #{i}"
  #puts
end
puts res

gets
a = gets.to_s.chomp.split(" ").map{|x| x.to_i}
max = 0
i = 1
res = 0
a.each do |x|
  if(max <= x)
    i += 1
    max = x
    if(res < i)
      res = i
    end
  else
    i = 0
  end
  #print "#{x} #{max} #{i}"
  #puts
end
puts res


Tokitsukaze has a sequence $$$a$$$ of length $$$n$$$. For each operation, she selects two numbers $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$; $$$1 \leq i,j \leq n$$$).   If $$$a_i = a_j$$$, change one of them to $$$0$$$.  Otherwise change both of them to $$$\min(a_i, a_j)$$$. Tokitsukaze wants to know the minimum number of operations to change all numbers in the sequence to $$$0$$$. It can be proved that the answer always exists.

The first line contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the length of the sequence $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 100$$$) — the sequence $$$a$$$.

For each test case, print a single integer — the minimum number of operations to change all numbers in the sequence to $$$0$$$.

NoteIn the first test case, one of the possible ways to change all numbers in the sequence to $$$0$$$:In the $$$1$$$-st operation, $$$a_1 < a_2$$$, after the operation, $$$a_2 = a_1 = 1$$$. Now the sequence $$$a$$$ is $$$[1,1,3]$$$.In the $$$2$$$-nd operation, $$$a_1 = a_2 = 1$$$, after the operation, $$$a_1 = 0$$$. Now the sequence $$$a$$$ is $$$[0,1,3]$$$.In the $$$3$$$-rd operation, $$$a_1 < a_2$$$, after the operation, $$$a_2 = 0$$$. Now the sequence $$$a$$$ is $$$[0,0,3]$$$.In the $$$4$$$-th operation, $$$a_2 < a_3$$$, after the operation, $$$a_3 = 0$$$. Now the sequence $$$a$$$ is $$$[0,0,0]$$$.So the minimum number of operations is $$$4$$$.

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  zc = 0
  ac = {}
  flag = false
  0.upto(a.size-1) do |i|
    flag = true if ac[a[i]]
    zc += 1 if a[i] == 0
    ac[a[i]] = true
  end
  if zc > 0 then
    puts n - zc
  else
    puts flag ? (n) : (n+1)
  end
end


Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns — from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≤ p ≤ max(x1, x2), min(y1, y2) ≤ q ≤ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.

The first line contains exactly two integers n, m (3 ≤ n, m ≤ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.

Print a single number — the minimum number of operations Simon needs to carry out his idea.

NoteIn the first sample, the sequence of operations can be like this:    For the first time you need to choose cell (2, 2) and corner (1, 1).  For the second time you need to choose cell (2, 2) and corner (3, 3).  For the third time you need to choose cell (2, 2) and corner (3, 1).  For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this:    For the first time you need to choose cell (3, 1) and corner (4, 3).  For the second time you need to choose cell (2, 3) and corner (1, 1).

def main
    n, m = STDIN.readline.chomp.split.map{|x| x.to_i}
  lis = []
  n.times do |i|
    lis << STDIN.readline.chomp.split.map{|x|x.to_i}
  end

  if (not lis.first.select{|x| x == 1}.empty?) or (not lis.last.select{|x| x == 1}.empty?) then
    puts 2
    return
  else
    lis.each do |x|
      if x.first == 1 or x.last == 1 then
        puts 2
        return
      end
    end
  end
  puts 4
end

if __FILE__ == $0
  main
end

n, m = gets.split.map(&:to_i)
n.times do |i|
  a = gets.split(' ')
  if i == 0 || i == n-1
    if a.any? { |e| e == '1' }
      puts 2
      exit
    end
  elsif a.first == '1' || a.last == '1'
    puts 2
    exit
  end
end
puts 4

n,m=gets.chomp.split.map(&:to_i)
a=gets.chomp.split.include? '1'
for i in 0..n-3 do
	x=gets.chomp.split
	if x[-1]=='1' || x[0]=='1'
		b=true
	end
end
c=gets.chomp.split.include? '1'
puts (a||c||b)? "2" : "4"

def run
  m, n = $stdin.gets.split.map(&:to_i)
  a = $stdin.readlines.map {|line| line.split.map(&:to_i) }
  min = 4
  a.each_with_index do |x, i|
    x.each_with_index do |y, j|
      if y == 1
        cnt = 0
        cnt += 1 if i == 0 or i == m - 1
        cnt += 1 if j == 0 or j == n - 1

        if cnt == 1
          min = [2, min].min
        elsif cnt == 2
          min = [1, min].min
        end
      end
    end
  end

  puts min
end

run if $0 == __FILE__

n, m = gets.chomp.split(/ /).map(&:to_i)
ans = 4
n.times do |i|
    line = gets.chomp.split(/ /).map(&:to_i)
    m.times do |j|
        if line[j] == 1
            ans = 2 if i == 0 || i == n - 1
            ans = 2 if j == 0 || j == m - 1
        end
    end
end
puts ans

m,n = gets.split(" ").map(&:to_i)
arr = []
m.times do
	arr << gets.split(" ").map(&:to_i)
end
ans = nil
ans = 2 if arr[0].include?(1) || arr[m-1].include?(1)
unless ans
	j = 0
	(0..m-1).each do |i|
		if arr[i][j] == 1
			ans = 2
			break
		end
	end
end

unless ans
	j = n - 1
	(0..m-1).each do |i|
		if arr[i][j] == 1
			ans = 2
			break
		end
	end
end

ans = 4 unless ans
puts ans

n, m = gets.split.collect{|i| i.to_i}
a = Array.new(n)
(0...n).each do |i|
    a[i] = gets.split
end
if a[0].count("1") > 0 or a[n-1].count("1") > 0 or\
   a.transpose[0].count("1") > 0 or a.transpose[m-1].count("1") > 0
    puts 2
else
    puts 4
end

def parse(s)
    s = s.split
    for i in 0...s.length do s[i] = s[i].to_i end
    s
end

n,m = parse gets
a = []
(0...n).each { |i|
    a << []
    (parse gets).each { |val|
        a[-1] << val
    }
}

(a[0]+a[-1]).each do |i| if i == 1 then puts 2; exit 0 end end
(0...n).each do |i| if a[i][-1] == 1 or a[i][0] == 1 then puts 2; exit 0 end end
puts 4

n,m=gets.split.map(&:to_i)
d=false
n.times do |i|
  r=gets.split.map(&:to_i)
  if (i==0||i==n-1)&&r.include?(1)||r[0]==1|| r[m-1]==1
    d=true
    break
  end
end
p d ? 2:4

line = gets.chomp.split(" ").map {|e| e.to_i}

side = false

table = []
line[0].times do
  row = gets.chomp.split(" ").map {|e| e.to_i}
  if ((table.length == 0 || table.length == (line[0] - 1)) && row.include?(1))
    side = true
  end

  if row[0] == 1 || row[line[1] - 1] == 1
    side = true
  end

  table.push(row)
end

if side
  puts 2
else
  puts 4
end

n, m = gets.split.map(&:to_i)
n.times do
  a = gets.split(' ')
  if a.first == '1' || a.last == '1'
    puts 2
    exit
  end
end
puts 4

n,m=gets.chomp.split.map(&:to_i)
a=gets.chomp.split.include? '1'
for i in 0..n-3 do
	x=gets.chomp.split
	if x[-1]=='1'
		b=true
	end
end
c=gets.chomp.split.include? '1'
puts (a||c||b)? "2" : "4"

n, m = gets.chomp.split(/ /).map(&:to_i)
good_cells = []
n.times do |i|
    line = gets.chomp.split(/ /).map(&:to_i)
    line.each do |j|
        good_cells << [i, j] if line[j] == 1
    end
end
ans = 4
good_cells.each do |cell|
    x = cell[0]
    y = cell[1]
    if x == 0 || y == 0 || x == n - 1 || y == m - 1
        ans = 2
        break
    end
end
puts ans

n, m = gets.chomp.split(/ /).map(&:to_i)
table = []
good_cells = []
n.times do |i|
    line = gets.chomp.split(/ /).map(&:to_i)
    line.each do |j|
        good_cells << [i, j] if line[j] == 1
    end
    table << line
end
ans = 4
good_cells.each do |cell|
    x = cell[0]
    y = cell[1]
    ans = 2 if x == 0 || y == 0 || x == n - 1 || y == m - 1
end
puts ans

n, m = gets.chomp.split(/ /).map(&:to_i)
table = []
good_cells = []
n.times do |i|
    line = gets.chomp.split(/ /).map(&:to_i)
    line.each do |j|
        good_cells << [i, j] if line[j] == 1
    end
    table << line
end
ans = 4
good_cells.each do |cell|
    x = cell[0]
    y = cell[1]
    ans = 2 if x == 0 || x == n - 1
    ans = 2 if y == 0 || y == m - 1
end
puts ans


Integer factorisation is hard. The RSA Factoring Challenge offered $$$$100\,000$$$ for factoring RSA-$$$1024$$$, a $$$1024$$$-bit long product of two prime numbers. To this date, nobody was able to claim the prize. We want you to factorise a $$$1024$$$-bit number.Since your programming language of choice might not offer facilities for handling large integers, we will provide you with a very simple calculator. To use this calculator, you can print queries on the standard output and retrieve the results from the standard input. The operations are as follows:   + x y where $$$x$$$ and $$$y$$$ are integers between $$$0$$$ and $$$n-1$$$. Returns $$$(x+y) \bmod n$$$.  - x y where $$$x$$$ and $$$y$$$ are integers between $$$0$$$ and $$$n-1$$$. Returns $$$(x-y) \bmod n$$$.  * x y where $$$x$$$ and $$$y$$$ are integers between $$$0$$$ and $$$n-1$$$. Returns $$$(x \cdot y) \bmod n$$$.  / x y where $$$x$$$ and $$$y$$$ are integers between $$$0$$$ and $$$n-1$$$ and $$$y$$$ is coprime with $$$n$$$. Returns $$$(x \cdot y^{-1}) \bmod n$$$ where $$$y^{-1}$$$ is multiplicative inverse of $$$y$$$ modulo $$$n$$$. If $$$y$$$ is not coprime with $$$n$$$, then $$$-1$$$ is returned instead.  sqrt x where $$$x$$$ is integer between $$$0$$$ and $$$n-1$$$ coprime with $$$n$$$. Returns $$$y$$$ such that $$$y^2 \bmod n = x$$$. If there are multiple such integers, only one of them is returned. If there are none, $$$-1$$$ is returned instead.  ^ x y where $$$x$$$ and $$$y$$$ are integers between $$$0$$$ and $$$n-1$$$. Returns $$${x^y \bmod n}$$$. Find the factorisation of $$$n$$$ that is a product of between $$$2$$$ and $$$10$$$ distinct prime numbers, all of form $$$4x + 3$$$ for some integer $$$x$$$.Because of technical issues, we restrict number of requests to $$$100$$$.

The only line contains a single integer $$$n$$$ ($$$21 \leq n \leq 2^{1024}$$$). It is guaranteed that $$$n$$$ is a product of between $$$2$$$ and $$$10$$$ distinct prime numbers, all of form $$$4x + 3$$$ for some integer $$$x$$$.

You can print as many queries as you wish, adhering to the time limit (see the Interaction section for more details).  When you think you know the answer, output a single line of form ! k p_1 p_2 ... p_k, where $$$k$$$ is the number of prime factors of $$$n$$$, and $$$p_i$$$ are the distinct prime factors. You may print the factors in any order. Hacks input For hacks, use the following format:.  The first should contain $$$k$$$ ($$$2 \leq k \leq 10$$$) — the number of prime factors of $$$n$$$.  The second should contain $$$k$$$ space separated integers $$$p_1, p_2, \dots, p_k$$$ ($$$21 \leq n \leq 2^{1024}$$$) — the prime factors of $$$n$$$. All prime factors have to be of form $$$4x + 3$$$ for some integer $$$x$$$. They all have to be distinct.

NoteWe start by reading the first line containing the integer $$$n = 21$$$. Then, we ask for:   $$$(12 + 16) \bmod 21 = 28 \bmod 21 = 7$$$.  $$$(6 - 10) \bmod 21 = -4 \bmod 21 = 17$$$.  $$$(8 \cdot 15) \bmod 21 = 120 \bmod 21 = 15$$$.  $$$(5 \cdot 4^{-1}) \bmod 21 = (5 \cdot 16) \bmod 21 = 80 \bmod 21 = 17$$$.  Square root of $$$16$$$. The answer is $$$11$$$, as $$$(11 \cdot 11) \bmod 21 = 121 \bmod 21 = 16$$$. Note that the answer may as well be $$$10$$$.  Square root of $$$5$$$. There is no $$$x$$$ such that $$$x^2 \bmod 21 = 5$$$, so the output is $$$-1$$$.  $$$(6^{12}) \bmod 21 = 2176782336 \bmod 21 = 15$$$. We conclude that our calculator is working, stop fooling around and realise that $$$21 = 3 \cdot 7$$$.

def modpow(a,b,m)
  r = 1
  while b > 0
    r = r * a % m if b % 2 == 1
    a = a * a % m
    b >>= 1
  end
  return r
end

def isprime(n)
  return true if n == 2
  return false if n == 1 || n & 1 == 0
  d = n-1
  d >>= 1 while d & 1 == 0
  20.times do
    a = rand(n-2) + 1
    t = d
    y = modpow(a,t,n)
    while t != n-1 && y != 1 && y != n-1
      y = (y * y) % n
      t <<= 1
    end
    return false if y != n-1 && t & 1 == 0
  end
  return true
end

def solve(n,gn)
  # puts "solve #{n}"
  while true
    x = rand(1...n)
    x2 = x * x % gn
    puts "sqrt #{x2}"
    STDOUT.flush
    y = gets.chomp.to_i % n
    next if x == y
    gg = x - y
    gg = -gg if gg < 0
    q = n.gcd(gg)
    next if q == 1 or q == n
    # ok
    ret = []
    if isprime(q)
      ret.push(q)
    else
      ret = solve(q,gn)
    end
    q = n/q
    if isprime(q)
      ret.push(q)
    else
      ret.concat(solve(q,gn))
    end
    return ret
  end
end

n = gets.chomp.to_i
ans = solve(n,n)
ansstr = "! #{ans.length} #{ans.join(' ')}"
puts ansstr
STDOUT.flush

require 'openssl'
require 'prime'

$stdout.sync = true

def ask(x)
  puts "sqrt #{x}"
  gets.to_i
end

def run(n)
  loop do
    a = rand(2..n - 1)
    g = n.gcd(a)
    return g if g != 1
    a2 = a * a % n
    next if a2.gcd(n) != 1
    r = ask(a2) % n
    next if r == -1 || r == a || r == n - a
    g = n.gcd(n + r - a)
    next if g == 1
    return g
  end
end

n = gets.to_i
fac = [n]

until fac.all?{|f| f.to_bn.prime?}
  x = run(n)
  nfac = []
  fac.each do |y|
    g = x.gcd(y)
    if g == 1 || g == y
      nfac << y
    else
      nfac << g << y / g
      x /= g
    end
  end
  fac << x if x > 1
  fac = nfac
end

puts "! #{fac.size} #{fac * ' '}"

def modpow(a,b,m)
  r = 1
  while b > 0
    r = r * a % m if b % 2 == 1
    a = a * a % m
    b >>= 1
  end
  return r
end

def isprime(n)
  return true if n == 2
  return false if n == 1 || n & 1 == 0
  d = n-1
  d >>= 1 while d & 1 == 0
  20.times do
    a = rand(n-2) + 1
    t = d
    y = modpow(a,t,n)
    while t != n-1 && y != 1 && y != n-1
      y = (y * y) % n
      t <<= 1
    end
    return false if y != n-1 && t & 1 == 0
  end
  return true
end

def solve(n,gn)
  # puts "solve #{n}"
  while true
    x = rand(1...n)
    x2 = x * x % n
    puts "sqrt #{x2}"
    STDOUT.flush
    y = gets.chomp.to_i % n
    next if x == y
    gg = x - y
    gg = -gg if gg < 0
    q = n.gcd(gg)
    next if q == 1 or q == n
    # ok
    ret = []
    if isprime(q)
      ret.push(q)
    else
      ret = solve(q,gn)
    end
    q = n/q
    if isprime(q)
      ret.push(q)
    else
      ret.concat(solve(q,gn))
    end
    return ret
  end
end

n = gets.chomp.to_i
ans = solve(n,n)
ansstr = "! #{ans.length} #{ans.join(' ')}"
puts ansstr
STDOUT.flush

def modpow(a,b,m)
  r = 1
  while b > 0
    r = r * a % m if b % 2 == 1
    a = a * a % m
    b >>= 1
  end
  return r
end

def isprime(n)
  return true if n == 2
  return false if n == 1 || n & 1 == 0
  d = n-1
  d >>= 1 while d & 1 == 0
  20.times do
    a = rand(n-2) + 1
    t = d
    y = modpow(a,t,n)
    while t != n-1 && y != 1 && y != n-1
      y = (y * y) % n
      t <<= 1
    end
    return false if y != n-1 && t & 1 == 0
  end
  return true
end

def solve(n)
  while true
    x = rand(1...n)
    x2 = x * x % n
    puts "sqrt #{x2}"
    STDOUT.flush
    y = gets.chomp.to_i
    next if x == y
    gg = x - y
    gg = -gg if gg < 0
    q = n.gcd(gg)
    next if q == 1 or q == n
    # ok
    ret = []
    if isprime(q)
      ret.push(q)
    else
      ret = solve(q)
    end
    q = n/q
    if isprime(q)
      ret.push(q)
    else
      ret.concat(solve(q))
    end
    return ret
  end
end

n = gets.chomp.to_i
ans = solve(n)
m = 1
for i in 0...ans.length
  m = m * ans[i]
end
if m != n
  exit(1)
end
ansstr = "! #{ans.length} #{ans.join(' ')}"
puts ansstr
STDOUT.flush

def modpow(a,b,m)
  r = 1
  while b > 0
    r = r * a % m if b % 2 == 1
    a = a * a % m
    b >>= 1
  end
  return r
end

def isprime(n)
  return true if n == 2
  return false if n == 1 || n & 1 == 0
  d = n-1
  d >>= 1 while d & 1 == 0
  20.times do
    a = rand(n-2) + 1
    t = d
    y = modpow(a,t,n)
    while t != n-1 && y != 1 && y != n-1
      y = (y * y) % n
      t <<= 1
    end
    return false if y != n-1 && t & 1 == 0
  end
  return true
end

def solve(n)
  while true
    x = rand(1...n)
    x2 = x * x % n
    puts "sqrt #{x2}"
    STDOUT.flush
    y = gets.chomp.to_i
    next if x == y
    gg = x - y
    gg = -gg if gg < 0
    q = n.gcd(gg)
    next if q == 1 or q == n
    # ok
    ret = []
    if isprime(q)
      ret.push(q)
    else
      ret = solve(q)
    end
    q = n/q
    if isprime(q)
      ret.push(q)
    else
      ret.concat(solve(q))
    end
    return ret
  end
end

n = gets.chomp.to_i
ans = solve(n)
ansstr = "! #{ans.length} #{ans.join(' ')}"
puts ansstr

def modpow(a,b,m)
  r = 1
  while b > 0
    r = r * a % m if b % 2 == 1
    a = a * a % m
    b >>= 1
  end
  return r
end

def fa()
  n = 30
  while true
    n = n * n
    n = n % 252521
  end
  return n
end
cnt = 0

def isprime(n)
  return true if n == 2
  return false if n == 1 || n & 1 == 0
  d = n-1
  d >>= 1 while d & 1 == 0
  20.times do
    a = rand(n-2) + 1
    t = d
    y = modpow(a,t,n)
    while t != n-1 && y != 1 && y != n-1
      y = (y * y) % n
      t <<= 1
    end
    return false if y != n-1 && t & 1 == 0
  end
  return true
end

def solve(n)
  while true
    x = rand(1...n)
    x2 = x * x % n
    puts "sqrt #{x2}"
    STDOUT.flush
    y = gets.chomp.to_i % n
    next if x == y
    gg = x - y
    gg = -gg if gg < 0
    q = n.gcd(gg)
    next if q == 1 or q == n
    # ok
    ret = []
    if isprime(q)
      ret.push(q)
    else
      ret = solve(q)
    end
    q = n/q
    if isprime(q)
      ret.push(q)
    else
      ret.concat(solve(q))
    end
    return ret
  end
end

n = gets.chomp.to_i
ans = solve(n)
ansstr = "! #{ans.length} #{ans.join(' ')}"
puts ansstr
STDOUT.flush

require 'openssl'
require 'prime'

$stdout.sync = true
$sol = []
$memo = {}

def ask(x)
  return -1 if x.gcd($n) != 1
  return -1 if x < 0 || x >= $n
  return $memo[x] if $memo.include?(x)
  puts "sqrt #{x}"
  ans = gets.to_i
  $memo[x] = ans
  ans
end

def go(n)
  if n.to_bn.prime?
    $sol << n
    return
  end

  if n < 100000
    $sol += n.prime_division.map(&:first)
    return
  end

  loop do
    a = rand(2..n-1)
    g = n.gcd(a)
    if g != 1 && g != n
      go(g)
      go(n / g)
      break
    end
    a2 = a * a % n
    r = ask(a2)
    next if r == -1
    r %= n
    next unless r * r % n == a2
    next if r == a || r == n - a
    g = n.gcd(n + r - a)
    next if g == 1 || g == n
    go(g)
    go(n / g)
    break
  end
end

n = gets.to_i
$n = n
go(n)
puts "! #{$sol.size} #{$sol.sort.join(' ')}"

require 'openssl'
require 'prime'

$stdout.sync = true

def ask(x)
  puts "sqrt #{x}"
  gets.to_i
end

def run(n)
  loop do
    a = rand(2..n - 1)
    g = n.gcd(a)
    return g if g != 1
    a2 = a * a % n
    next if a2.gcd(n) != 1
    r = ask(a2) % n
    next if r == -1 || r == a || r == n - a
    g = n.gcd(n + r - a)
    next if g == 1
    return g
  end
end

n = gets.to_i
fac = [n]

until fac.all?{|f| f.to_bn.prime?}
  x = run(n)
  nfac = []
  fac.each do |y|
    g = x.gcd(y)
    if g == 1
      nfac << y
    else
      nfac << g << y / g
      x /= g
    end
  end
  fac = nfac
end

puts "! #{fac.size} #{fac * ' '}"

require 'openssl'
require 'prime'

$stdout.sync = true
$sol = []

def go(n)
  if n.to_bn.prime?
    $sol << n
    return
  end

  if n < 100000
    $sol += n.prime_division.map(&:first)
    return
  end

  loop do
    a = rand(2..n-1)
    g = n.gcd(a)
    if g != 1 && g != n
      go(g)
      go(n / g)
      break
    end
    a2 = a * a % n
    puts "sqrt #{a2}"
    r = gets.to_i
    next if r == -1
    r %= n
    next unless r * r % n == a2
    next if r == a || r == n - a
    g = n.gcd(n + r - a)
    next if g == 1 || g == n
    go(g)
    go(n / g)
    break
  end
end

n = gets.to_i
go(n)
puts "! #{$sol.size} #{$sol.sort.join(' ')}"

require 'openssl'
require 'prime'

$stdout.sync = true
$sol = []

def go(n)
  if n.to_bn.prime?
    $sol << n
    return
  end

  # if n < 100000
  #   $sol += n.prime_division.map(&:first)
  #   return
  # end

  loop do
    a = rand(2..n-1)
    a2 = a * a % n
    if a2 == 0
      g = n.gcd(a)
      next if g == 1 || g == n
      go(g)
      go(n / g)
      break
    end
    puts "sqrt #{a2}"
    r = gets.to_i
    next if r == -1
    r %= n
    next unless r * r % n == a2
    next if r == a || r == n - a
    g = n.gcd(n + r - a)
    next if g == 1 || g == n
    go(g)
    go(n / g)
    break
  end
end

n = gets.to_i
go(n)
puts "! #{$sol.size} #{$sol.sort.join(' ')}"

require 'openssl'
require 'prime'

$stdout.sync = true
$sol = []
$memo = {}

def ask(x)
  return -1 if x.gcd($n) != 1
  return $memo[x] if $memo.include?(x)
  puts "sqrt #{x}"
  ans = gets.to_i
  $memo[x] = ans
  ans
end

def go(n)
  if n.to_bn.prime?
    $sol << n
    return
  end

  if n < 100000
    $sol += n.prime_division.map(&:first)
    return
  end

  loop do
    a = rand(2..n-1)
    g = n.gcd(a)
    if g != 1 && g != n
      go(g)
      go(n / g)
      break
    end
    a2 = a * a % n
    r = ask(a2)
    next if r == -1
    r %= n
    next unless r * r % n == a2
    next if r == a || r == n - a
    g = n.gcd(n + r - a)
    next if g == 1 || g == n
    go(g)
    go(n / g)
    break
  end
end

n = gets.to_i
$n = n
go(n)
puts "! #{$sol.size} #{$sol.sort.join(' ')}"

require 'openssl'
require 'prime'

$stdout.sync = true
$sol = []

def ask(x)
  return -1 if x.gcd($n) != 1
  puts "sqrt #{x}"
  gets.to_i
end

def go(n)
  if n.to_bn.prime?
    $sol << n
    return
  end

  if n < 100000
    $sol += n.prime_division.map(&:first)
    return
  end

  loop do
    a = rand(2..n-1)
    g = n.gcd(a)
    if g != 1 && g != n
      go(g)
      go(n / g)
      break
    end
    a2 = a * a % n
    r = ask(a2)
    next if r == -1
    r %= n
    next unless r * r % n == a2
    next if r == a || r == n - a
    g = n.gcd(n + r - a)
    next if g == 1 || g == n
    go(g)
    go(n / g)
    break
  end
end

n = gets.to_i
$n = n
go(n)
puts "! #{$sol.size} #{$sol.sort.join(' ')}"

require 'openssl'
require 'prime'

$stdout.sync = true
$sol = []
$memo = {}

def ask(x)
  return -1 if x.gcd($n) != 1
  return -1 if x < 0 || x >= $n
  return $memo[x] if $memo.include?(x)
  puts "sqrt #{x}"
  ans = gets.to_i
  $memo[x] = ans
  ans
end

def go(n)
  if n.to_bn.prime?
    $sol << n
    return
  end

  if n < 1000000
    $sol += n.prime_division.map(&:first)
    return
  end

  loop do
    a = rand(2..n-1)
    g = n.gcd(a)
    if g != 1 && g != n
      go(g)
      go(n / g)
      break
    end
    a2 = a * a % n
    r = ask(a2)
    next if r == -1
    r %= n
    next unless r * r % n == a2
    next if r == a || r == n - a
    g = n.gcd(n + r - a)
    next if g == 1 || g == n
    go(g)
    go(n / g)
    break
  end
end

n = gets.to_i
$n = n
go(n)
puts "! #{$sol.size} #{$sol.sort.join(' ')}"

require 'openssl'
require 'prime'

$stdout.sync = true
$sol = []
$memo = {}

def ask(x)
  return -1 if x.gcd($n) != 1
  return -1 if x < 0 || x >= $n
  return $memo[x] if $memo.include?(x)
  puts "sqrt #{x}"
  ans = gets.to_i
  $memo[x] = ans
  ans
end

n = gets.to_i
$n = n

def chk(x)
  if x.to_bn.prime?
    $sol << x
    $sol.uniq!
    m = 1
    $sol.each{|t| m *= t}
    if m == $n
      puts "! #{$sol.size} #{$sol.sort.join(' ')}"
      exit
    end
  end
end

loop do
  a = rand(2..n-1)
  g = n.gcd(a)
  if g != 1 && g != n
    chk(g)
    chk(n / g)
    next
  end
  a2 = a * a % n
  r = ask(a2)
  next if r == -1
  r %= n
  next unless r * r % n == a2
  next if r == a || r == n - a
  g = n.gcd(n + r - a)
  next if g == 1 || g == n
  chk(g)
  chk(n / g)
end
puts "! #{$sol.size} #{$sol.sort.join(' ')}"

require 'openssl'
require 'prime'

$stdout.sync = true
$sol = []

def go(n)
  if n.to_bn.prime?
    $sol << n
    return
  end

  if n < 10000
    $sol += n.prime_division.map(&:first)
    return
  end

  loop do
    a = rand(2..n-1)
    a2 = a * a % n
    puts "sqrt #{a2}"
    r = gets.to_i
    next if r == -1 || r == a || r == n - a
    g = n.gcd(n + r - a)
    next if g == 1 || g == n
    go(g)
    go(n / g)
    break
  end
end

n = gets.to_i
go(n)
puts "! #{$sol.size} #{$sol.sort.join(' ')}"

require 'openssl'
require 'prime'

$stdout.sync = true
$sol = []

def go(n)
  if n.to_bn.prime?
    $sol << n
    return
  end

  if n < 10000
    $sol += n.prime_division.map(&:first)
    return
  end

  loop do
    a = rand(2..n-1)
    a2 = a * a % n
    puts "sqrt #{a2}"
    r = gets.to_i
    next if r == -1 || r == a || r == n - a
    g = n.gcd(n + r - a)
    next if g == 1 || g == n
    go(g)
    go(n / g)
    break
  end
end

n = gets.to_i
go(n)
puts "! #{$sol.sort.join(' ')}"


Greg has an array a = a1, a2, ..., an and m operations. Each operation looks as: li, ri, di, (1 ≤ li ≤ ri ≤ n). To apply operation i to the array means to increase all array elements with numbers li, li + 1, ..., ri by value di.Greg wrote down k queries on a piece of paper. Each query has the following form: xi, yi, (1 ≤ xi ≤ yi ≤ m). That means that one should apply operations with numbers xi, xi + 1, ..., yi to the array.Now Greg is wondering, what the array a will be after all the queries are executed. Help Greg.

The first line contains integers n, m, k (1 ≤ n, m, k ≤ 105). The second line contains n integers: a1, a2, ..., an (0 ≤ ai ≤ 105) — the initial array. Next m lines contain operations, the operation number i is written as three integers: li, ri, di, (1 ≤ li ≤ ri ≤ n), (0 ≤ di ≤ 105). Next k lines contain the queries, the query number i is written as two integers: xi, yi, (1 ≤ xi ≤ yi ≤ m). The numbers in the lines are separated by single spaces.

On a single line print n integers a1, a2, ..., an — the array after executing all the queries. Separate the printed numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.

n, m, k = gets.split.collect{|i| i.to_i}
a = gets.split.collect{|i| i.to_i}
op = Array.new(m)
(0...m).each{|i| op[i] = gets.split.collect{|j| j.to_i}}

q = Array.new(m,0)
k.times do
    tmp = gets.split.collect{|i| i.to_i-1}
    q[tmp[0]] += 1
    q[tmp[1]+1] -= 1 if tmp[1]+1 < m
end
(1...m).each{|i| q[i] += q[i-1]}

dp = Array.new(n,0)
(0...m).each do |i|
    dp[op[i][0]-1] += op[i][2]*q[i]
    dp[op[i][1]] -= op[i][2]*q[i] if op[i][1] < n
end
(1...n).each{|i| dp[i] += dp[i-1]}
puts (0...n).collect{|i| a[i]+dp[i]}.join(" ")


A permutation is a sequence of $$$n$$$ integers from $$$1$$$ to $$$n$$$, in which all the numbers occur exactly once. For example, $$$[1]$$$, $$$[3, 5, 2, 1, 4]$$$, $$$[1, 3, 2]$$$ are permutations, and $$$[2, 3, 2]$$$, $$$[4, 3, 1]$$$, $$$[0]$$$ are not.Polycarp was given four integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le l \le r \le n)$$$ and $$$s$$$ ($$$1 \le s \le \frac{n (n+1)}{2}$$$) and asked to find a permutation $$$p$$$ of numbers from $$$1$$$ to $$$n$$$ that satisfies the following condition:   $$$s = p_l + p_{l+1} + \ldots + p_r$$$. For example, for $$$n=5$$$, $$$l=3$$$, $$$r=5$$$, and $$$s=8$$$, the following permutations are suitable (not all options are listed):   $$$p = [3, 4, 5, 2, 1]$$$;  $$$p = [5, 2, 4, 3, 1]$$$;  $$$p = [5, 2, 1, 3, 4]$$$.  But, for example, there is no permutation suitable for the condition above for $$$n=4$$$, $$$l=1$$$, $$$r=1$$$, and $$$s=5$$$.Help Polycarp, for the given $$$n$$$, $$$l$$$, $$$r$$$, and $$$s$$$, find a permutation of numbers from $$$1$$$ to $$$n$$$ that fits the condition above. If there are several suitable permutations, print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$). Then $$$t$$$ test cases follow. Each test case consist of one line with four integers $$$n$$$ ($$$1 \le n \le 500$$$), $$$l$$$ ($$$1 \le l \le n$$$), $$$r$$$ ($$$l \le r \le n$$$), $$$s$$$ ($$$1 \le s \le \frac{n (n+1)}{2}$$$). It is guaranteed that the sum of $$$n$$$ for all input data sets does not exceed $$$500$$$.

For each test case, output on a separate line:    $$$n$$$ integers — a permutation of length $$$n$$$ that fits the condition above if such a permutation exists;  -1, otherwise.  If there are several suitable permutations, print any of them.

require 'set'

def tri(k)
	k*(k + 1)/2
end

def get(n, k, swaps)
	a = (1..k).to_a
	for i in 0...k
		j = k - i - 1
		max = n - i - a[j]
		a[j] += [max, swaps].min
		swaps -= [max, swaps].min
	end
	a
end

t = gets.to_i
t.times do
	n,l,r,s = gets.split.map &:to_i
	k = r - l + 1
	mi = tri(k)
	ma = tri(n) - tri(n - k)

	if s < mi || s > ma
		puts -1
		next
	end

	a = get(n, k, s - tri(k))
	bad = a.to_set

	get_next = ->(x){
		while bad.include?(x)
			x += 1
		end
		x
	}

	nxt = 0

	for i in 1...l do
		nxt = get_next.call(nxt + 1)
		print nxt, " "
	end

	print a.join(" ")

	for i in r...n do
		nxt = get_next.call(nxt + 1)
		print " ", nxt
	end

	puts ""
end


Polycarp came up with a new programming language. There are only two types of statements in it:   "x := s": assign the variable named x the value s (where s is a string). For example, the statement var := hello assigns the variable named var the value hello. Note that s is the value of a string, not the name of a variable. Between the variable name, the := operator and the string contains exactly one space each. "x = a + b": assign the variable named x the concatenation of values of two variables a and b. For example, if the program consists of three statements a := hello, b := world, c = a + b, then the variable c will contain the string helloworld. It is guaranteed that the program is correct and the variables a and b were previously defined. There is exactly one space between the variable names and the = and + operators. All variable names and strings only consist of lowercase letters of the English alphabet and do not exceed $$$5$$$ characters.The result of the program is the number of occurrences of string haha in the string that was written to the variable in the last statement.Polycarp was very tired while inventing that language. He asks you to implement it. Your task is — for given program statements calculate the number of occurrences of string haha in the last assigned variable.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^3$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of statements in the program. All variable names and strings are guaranteed to consist only of lowercase letters of the English alphabet and do not exceed $$$5$$$ characters. This is followed by $$$n$$$ lines describing the statements in the format described above. It is guaranteed that the program is correct.

For each set of input data, output the number of occurrences of the haha substring in the string that was written to the variable in the last statement.

4
6
a := h
b := aha
c = a + b
c = c + c
e = c + c
d = a + c
15
x := haha
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
1
haha := hah
5
haahh := aaaha
ahhhh = haahh + haahh
haahh = haahh + haahh
ahhhh = ahhhh + haahh
ahhaa = haahh + ahhhh

NoteIn the first test case the resulting value of d is hhahahaha.

def o (s)
  (0..(s.size - 1)).map {|i| s[i..i+3]}.select {|a| a == "haha"}.size
end

def add (s)
  [s, o(s)]
end

def m (s, t)
  x = s + t
  x = s[0..2] + 'x' + t.reverse[0..2].reverse if x.size > 6
  x
end

def cs (s, t)
  s.reverse[0..2].reverse + t[0..2]
end

def c (s, t)
  [m(s[0], t[0]), s[1] + t[1] + o(cs(s[0], t[0]))]
end

def solve (n, a)
  h = Hash.new
  last = []
  a.each {|s| last = h[s[0]] = (s[1] == ':=' ? add(s[2]) : c(h[s[2]], h[s[4]]))}
  last[1]
end

(1..(gets.to_i)).each { puts solve(n = gets.to_i, (1..n).map {|i| gets.split(' ')})}

def get_occ (s)
  (0..(s.size - 1)).map {|i| s[i..i+3]}.select {|a| a == "haha"}.size
end

def add (s)
  [s, get_occ(s)]
end

def merge_chars (s, t)
  x = s + t
  x = s[0..2] + 'x' + t[(t.size - [t.size, 3].min)..(t.size - 1)] if x.size >= 7
  x
end

def concat_sub_strings (s, t)
  s[(s.size - [s.size, 3].min)..(s.size - 1)] + t[0..2]
end

def concat (s, t)
  [merge_chars(s[0], t[0]), s[1] + t[1] + get_occ(concat_sub_strings(s[0], t[0]))]
end

def solve (n, a)
  mp = Hash.new
  last = []
  a.each {|s| last = mp[s[0]] = (s[1] == ':=' ? add(s[2]) : concat(mp[s[2]], mp[s[4]]))}
  last[1]
end

t = gets.to_i

(1..t).each do
  n = gets.to_i
  a = (1..n).map {|i| gets.split(' ')}
  puts solve(n, a)
end

t = gets.chomp.to_i

def count_em(string, substring)
  string.scan(/(?=#{substring})/).count
end

vars = Hash.new

(1..t).each do
  n = gets.chomp.to_i
  (1..n).each do |j|
    inp = gets.chomp.split(" ")
    if inp[1] == ":="
      l = inp[2].length
      vars[inp[0]] = {cnt: count_em(inp[2], "haha"),
                      s: inp[2][0..2], end: inp[2][[l - 3, 0].max..l - 1]}
    else
      tmp = (vars[inp[2]][:end] + vars[inp[4]][:s])
      sum = vars[inp[2]][:cnt] + vars[inp[4]][:cnt]
      cont = count_em(tmp, "haha")
      l = tmp.length
      s = vars[inp[2]][:s]
      if s.length < 3 then s = (s + vars[inp[4]][:s])[0..2] end
      endd = vars[inp[4]][:end]
      if endd.length < 3
        endd = vars[inp[2]][:end] + endd
        l = endd.length
        endd = endd[[l - 3, 0].max..l - 1]
      end
      vars[inp[0]] = {cnt: sum + cont,
                      s: s,
                      end: endd}
    end
    puts vars[inp[0]][:cnt] if j == n
  end
end

def get_occ (s)
  (0..(s.size - 1)).map {|i| s[i..i+3]}.select {|a| a =="haha"}.size
end

def add (s)
  [s, get_occ(s)]
end

def merge_chars (s, t)
  x = s + t
  x = s[0..2] + 'x' + t[(t.size - [t.size, 3].min)..(t.size - 1)] if x.size > 6
  x
end

def concat (s, t)
  [merge_chars(s[0], t[0]), s[1] + t[1] + [1, get_occ(s[0] + t[0])].min]
end

def solve (n, a)
  mp = Hash.new
  last = []
  a.each {|s| last = mp[s[0]] = (s[1] == ':=' ? add(s[2]):concat(mp[s[2]], mp[s[4]]))}
  last[1]
end

t = gets.to_i

(1..t).each do
  n = gets.to_i
  a = (1..n).map {|i| gets.split(' ')}
  puts solve(n, a)
end

def get_occ (s)
  result = 0
  (0..(s.size - 1)).each do |i|
    a = s[i..i+3]
    result += 1 if a =="haha"
  end
  result
end

def add (s)
  [s, get_occ(s), s]
end

def merge_chars (s, t)
  x = s + t
  x = s[0..3] + 'x' + t[(t.size - [t.size, 3].min)..(t.size - 1)] if x.size > 6
  [x, x]
end

def concat (s, t)
  pref, suff = merge_chars(s[0], t[-1])
  [pref, s[1] + t[1] + get_occ(s[-1] + t[0]), suff]
end

def solve (n, a)
  mp = Hash.new
  last = []
  a.each do |s|
    if s[1] == ':='
      mp[s[0]] = add(s[2])
    else
      mp[s[0]] = concat(mp[s[2]], mp[s[4]])
    end
    last = mp[s[0]]
  end
  last[1] + 1
end

t = gets.to_i

(1..t).each do
  n = gets.to_i
  a = (1..n).map{|i| gets.split(' ')}
  puts solve(n, a) >> 1

end


Alice got an array of length $$$n$$$ as a birthday present once again! This is the third year in a row! And what is more disappointing, it is overwhelmengly boring, filled entirely with zeros. Bob decided to apply some changes to the array to cheer up Alice.Bob has chosen $$$m$$$ changes of the following form. For some integer numbers $$$x$$$ and $$$d$$$, he chooses an arbitrary position $$$i$$$ ($$$1 \le i \le n$$$) and for every $$$j \in [1, n]$$$ adds $$$x + d \cdot dist(i, j)$$$ to the value of the $$$j$$$-th cell. $$$dist(i, j)$$$ is the distance between positions $$$i$$$ and $$$j$$$ (i.e. $$$dist(i, j) = |i - j|$$$, where $$$|x|$$$ is an absolute value of $$$x$$$).For example, if Alice currently has an array $$$[2, 1, 2, 2]$$$ and Bob chooses position $$$3$$$ for $$$x = -1$$$ and $$$d = 2$$$ then the array will become $$$[2 - 1 + 2 \cdot 2,~1 - 1 + 2 \cdot 1,~2 - 1 + 2 \cdot 0,~2 - 1 + 2 \cdot 1]$$$ = $$$[5, 2, 1, 3]$$$. Note that Bob can't choose position $$$i$$$ outside of the array (that is, smaller than $$$1$$$ or greater than $$$n$$$).Alice will be the happiest when the elements of the array are as big as possible. Bob claimed that the arithmetic mean value of the elements will work fine as a metric.What is the maximum arithmetic mean value Bob can achieve?

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of elements of the array and the number of changes. Each of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$d_i$$$ ($$$-10^3 \le x_i, d_i \le 10^3$$$) — the parameters for the $$$i$$$-th change.

Print the maximal average arithmetic mean of the elements Bob can achieve. Your answer is considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$.

N, M = gets.split.map(&:to_i)
min, max = 0, 0
N.times do |i|
    min += (i-N/2).abs
    max += i
end

ans = 0
M.times do
    x, d = gets.split.map(&:to_i)
    ans += N * x + d * (d>0 ? max : min)
end
puts ans.to_f/N

n, m = gets.strip.split.map(&:to_i)
aps = []
m.times do
  aps << gets.strip.split.map(&:to_i)
end

ps=0
po=0
aps.each do |ap|
  if ap[1]>=0
    po += ap[0]
    ps += ap[1]
  end
end

sum = 0
sum += (po * n)
sum += (ps * ((n*(n-1))/2))

ns=0
no=0
aps.each do |ap|
  if ap[1]<0
    no += ap[0]
    ns += ap[1]
  end
end

sum += (no * n)
if n%2==0
  an = n/2
  sum += (ns * ((an*(an+1))/2))
  sum += (ns * ((an*(an-1))/2))
else
  an = n/2
  sum += (ns * ((an*(an+1))/2))
  sum += (ns * ((an*(an+1))/2))
end

puts (1.0*sum)/(1.0*n)


Omkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible.Omkar currently has $$$n$$$ supports arranged in a line, the $$$i$$$-th of which has height $$$a_i$$$. Omkar wants to build his waterslide from the right to the left, so his supports must be nondecreasing in height in order to support the waterslide. In $$$1$$$ operation, Omkar can do the following: take any contiguous subsegment of supports which is nondecreasing by heights and add $$$1$$$ to each of their heights. Help Omkar find the minimum number of operations he needs to perform to make his supports able to support his waterslide!An array $$$b$$$ is a subsegment of an array $$$c$$$ if $$$b$$$ can be obtained from $$$c$$$ by deletion of several (possibly zero or all) elements from the beginning and several (possibly zero or all) elements from the end.An array $$$b_1, b_2, \dots, b_n$$$ is called nondecreasing if $$$b_i\le b_{i+1}$$$ for every $$$i$$$ from $$$1$$$ to $$$n-1$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 100$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the number of supports Omkar has. The second line of each test case contains $$$n$$$ integers $$$a_{1},a_{2},...,a_{n}$$$ $$$(0 \leq a_{i} \leq 10^9)$$$ — the heights of the supports. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer — the minimum number of operations Omkar needs to perform to make his supports able to support his waterslide.

NoteThe subarray with which Omkar performs the operation is bolded.In the first test case:First operation:$$$[5, 3, \textbf{2}, 5] \to [5, 3, \textbf{3}, 5]$$$Second operation:$$$[5, \textbf{3}, \textbf{3}, 5] \to [5, \textbf{4}, \textbf{4}, 5]$$$Third operation:$$$[5, \textbf{4}, \textbf{4}, 5] \to [5, \textbf{5}, \textbf{5}, 5]$$$In the third test case, the array is already nondecreasing, so Omkar does $$$0$$$ operations.

# your code goes here

t = gets.chomp.to_i
for tc in 1..t
	n = gets.chomp.to_i;
	a = gets.split
	for i in 0..(n-1)
		a[i] = a[i].to_i
	end
	b = Array.new(n, 0)
	max = a[0]
	for i in 1..(n-1)
		if a[i] > max
			max = a[i]
		end
		b[i] = max - a[i]
	end
	ans = 0
	for i in 1..(n-1)
		if b[i] > b[i-1]
			ans += b[i] - b[i-1]
		end
	end
	puts ans
end

t = gets.chomp.to_i
for tc in 1..t
	n = gets.chomp.to_i;
	a = gets.split
	for i in 0..(n-1)
		a[i] = a[i].to_i
	end
	ans = 0
	for i in 1..(n-1)
		if a[i] > a[i-1]
			ans += a[i] - a[i-1]
		end
	end
	puts ans
end


You have an axis-aligned rectangle room with width $$$W$$$ and height $$$H$$$, so the lower left corner is in point $$$(0, 0)$$$ and the upper right corner is in $$$(W, H)$$$.There is a rectangular table standing in this room. The sides of the table are parallel to the walls, the lower left corner is in $$$(x_1, y_1)$$$, and the upper right corner in $$$(x_2, y_2)$$$.You want to place another rectangular table in this room with width $$$w$$$ and height $$$h$$$ with the width of the table parallel to the width of the room.The problem is that sometimes there is not enough space to place the second table without intersecting with the first one (there are no problems with tables touching, though).You can't rotate any of the tables, but you can move the first table inside the room.   Example of how you may move the first table. What is the minimum distance you should move the first table to free enough space for the second one?

The first line contains the single integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of the test cases. The first line of each test case contains two integers $$$W$$$ and $$$H$$$ ($$$1 \le W, H \le 10^8$$$) — the width and the height of the room. The second line contains four integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$ and $$$y_2$$$ ($$$0 \le x_1 < x_2 \le W$$$; $$$0 \le y_1 < y_2 \le H$$$) — the coordinates of the corners of the first table. The third line contains two integers $$$w$$$ and $$$h$$$ ($$$1 \le w \le W$$$; $$$1 \le h \le H$$$) — the width and the height of the second table.

For each test case, print the minimum distance you should move the first table, or $$$-1$$$ if there is no way to free enough space for the second table. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$.

NoteThe configuration of the first test case is shown in the picture. But the movement of the first table is not optimal. One of the optimal movement, for example, is to move the table by $$$(0, -1)$$$, so the lower left corner will move from $$$(2, 1)$$$ to $$$(2, 0)$$$. Then you can place the second table at $$$(0, 3)-(4, 5)$$$.In the second test case, there is no way to fit both tables in the room without intersecting.In the third test case, you can move the first table by $$$(0, 2)$$$, so the lower left corner will move from $$$(0, 3)$$$ to $$$(0, 5)$$$.

gets.to_i.times.each do
  w0, h0 = gets.split.map(&:to_i)
  x1, y1, x2, y2 = gets.split.map(&:to_i)
  w, h = gets.split.map(&:to_i)
  dw = [w - [x1, w0 - x2].max, 0].max
  dh = [h - [y1, h0 - y2].max, 0].max
  nw = w0 < x2 - x1 + w
  nh = h0 < y2 - y1 + h
  puts case
    when nw && nh then -1
    when nw then dh
    when nh then dw
    else [dw, dh].min
  end
end

MOD = 10 ** 9 + 7
def gs; gets.chomp; end
def gi; gets.to_i; end
def gli; gets.split.map(&:to_i); end
def cyesno(x); puts x ? :Yes : :No; end
def uyesno(x); puts x ? :YES : :NO; end
def array_to_hash_by_count(c); Hash.new(0).tap { |x| c.each { |z| x[z] += 1 } }; end

def solve
  w, h = gli
  x1, y1, x2, y2 = gli
  wq, hq = gli
  w1 = x2 - x1
  h1 = y2 - y1
  if w1 + wq > w && h1 + hq > h
    puts (-1) ** 1
  else
    d = []
    d << [wq - x1, 0].max if w1 + wq <= w
    d << [hq - y1, 0].max if h1 + hq <= h
    d << [y2 - (h - hq), 0].max if h1 + hq <= h
    d << [x2 - (w - wq), 0].max if w1 + wq <= w
    puts d.min
  end
end

def main
  gi.times { solve }
end

main

gets.to_i.times.each do
  w0, h0 = gets.split.map(&:to_i)
  x1, y1, x2, y2 = gets.split.map(&:to_i)
  w, h = gets.split.map(&:to_i)
  dw = w - [x1, w0 - x2].max
  dh = h - [y1, h0 - y2].max
  nw = w0 < x2 - x1 + w
  nh = h0 < y2 - y1 + h
  puts case
    when nw && nh then -1
    when nw then dh
    when nh then dw
    else [dh, dw].min
  end
end


We have a secret array. You don't know this array and you have to restore it. However, you know some facts about this array:  The array consists of $$$n$$$ distinct positive (greater than $$$0$$$) integers.  The array contains two elements $$$x$$$ and $$$y$$$ (these elements are known for you) such that $$$x < y$$$.  If you sort the array in increasing order (such that $$$a_1 < a_2 < \ldots < a_n$$$), differences between all adjacent (consecutive) elements are equal (i.e. $$$a_2 - a_1 = a_3 - a_2 = \ldots = a_n - a_{n-1})$$$. It can be proven that such an array always exists under the constraints given below.Among all possible arrays that satisfy the given conditions, we ask you to restore one which has the minimum possible maximum element. In other words, you have to minimize $$$\max(a_1, a_2, \dots, a_n)$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$2 \le n \le 50$$$; $$$1 \le x < y \le 50$$$) — the length of the array and two elements that are present in the array, respectively.

For each test case, print the answer: $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of the required array. If there are several answers, you can print any (it also means that the order of elements doesn't matter). It can be proven that such an array always exists under the given constraints.

def solve
  n, x, y = gets.strip.split(' ').map(&:to_i)
  my_stack = []

  51.times { |i|
    next if i.zero?
    el = x
    count = n - 1
    flg = false
    while el < y
      if count.zero? || el + i > y
        flg = true
        break
      end
      el += i
      count -= 1
    end
    next if flg == true
    my_stack << i
  }

  res = []
  mn = 1e9 + 1
  my_stack.each do |e|
    list = [x]
    count = n - 1
    el = x
    while el + e <= y && !count.zero?
      el += e
      list.append(el)
      count -= 1
    end
    el = x
    while el - e > 0 && !count.zero?
      el -= e
      list.prepend(el)
      count -= 1
    end
    el = y
    while !count.zero?
      el += e
      list.append(el)
      count -= 1
    end
    if list.max < mn
      mn = list.max
      res = list
    end
  end
  puts res.join(' ')
end

gets.strip.to_i.times { solve }

def solve
  n, x, y = gets.strip.split(' ').map(&:to_i)
  my_stack = []

  51.times { |i|
    next if i.zero?
    el = x
    count = n - 1
    flg = false
    while el < y
      if count.zero? || el + i > y
        flg = true
        break
      end
      el += i
      count -= 1
    end
    next if flg == true
    my_stack << i
  }

  res = []
  mn = 1e9 + 1
  my_stack.each do |e|
    list = [x]
    count = n - 1
    el = x
    while el - e > 0 && !count.zero?
      el -= e
      list.prepend(el)
      count -= 1
    end
    el = x
    while !count.zero?
      el += e
      list.append(el)
      count -= 1
    end
    if list.max < mn
      mn = list.max
      res = list
    end
  end
  puts res.join(' ')
end

gets.strip.to_i.times { solve }


Young wilderness explorers set off to their first expedition led by senior explorer Russell. Explorers went into a forest, set up a camp and decided to split into groups to explore as much interesting locations as possible. Russell was trying to form groups, but ran into some difficulties...Most of the young explorers are inexperienced, and sending them alone would be a mistake. Even Russell himself became senior explorer not long ago. Each of young explorers has a positive integer parameter $$$e_i$$$ — his inexperience. Russell decided that an explorer with inexperience $$$e$$$ can only join the group of $$$e$$$ or more people.Now Russell needs to figure out how many groups he can organize. It's not necessary to include every explorer in one of the groups: some can stay in the camp. Russell is worried about this expedition, so he asked you to help him.

The first line contains the number of independent test cases $$$T$$$($$$1 \leq T \leq 2 \cdot 10^5$$$). Next $$$2T$$$ lines contain description of test cases. The first line of description of each test case contains the number of young explorers $$$N$$$ ($$$1 \leq N \leq 2 \cdot 10^5$$$). The second line contains $$$N$$$ integers $$$e_1, e_2, \ldots, e_N$$$ ($$$1 \leq e_i \leq N$$$), where $$$e_i$$$ is the inexperience of the $$$i$$$-th explorer. It's guaranteed that sum of all $$$N$$$ doesn't exceed $$$3 \cdot 10^5$$$.

Print $$$T$$$ numbers, each number on a separate line. In $$$i$$$-th line print the maximum number of groups Russell can form in $$$i$$$-th test case.

NoteIn the first example we can organize three groups. There will be only one explorer in each group. It's correct because inexperience of each explorer equals to $$$1$$$, so it's not less than the size of his group.In the second example we can organize two groups. Explorers with inexperience $$$1$$$, $$$2$$$ and $$$3$$$ will form the first group, and the other two explorers with inexperience equal to $$$2$$$ will form the second group.This solution is not unique. For example, we can form the first group using the three explorers with inexperience equal to $$$2$$$, and the second group using only one explorer with inexperience equal to $$$1$$$. In this case the young explorer with inexperience equal to $$$3$$$ will not be included in any group.

def f(x)
  return -100_000 if x < 0
  return $f[x]
end

1.upto(gets.to_i) do
  n = gets.to_i
  a = gets.split(' ').map(&:to_i).sort.unshift(0)
  $f = Array.new(n, 0)

  a.each_with_index do |e, i|
    next if i.zero?

    $f[i] = [f(i-1), f(i-e)+1].max
  end

  puts $f.last
end

1.upto(gets.to_i) do
  gets
  a = gets.split(' ').map(&:to_i).sort.reverse

  result = 0
  while !a.empty?
    break if a.first > a.size

    a.shift(a.first)
    result += 1
  end

  puts result
end


In this problem, a $$$n \times m$$$ rectangular matrix $$$a$$$ is called increasing if, for each row of $$$i$$$, when go from left to right, the values strictly increase (that is, $$$a_{i,1}<a_{i,2}<\dots<a_{i,m}$$$) and for each column $$$j$$$, when go from top to bottom, the values strictly increase (that is, $$$a_{1,j}<a_{2,j}<\dots<a_{n,j}$$$).In a given matrix of non-negative integers, it is necessary to replace each value of $$$0$$$ with some positive integer so that the resulting matrix is increasing and the sum of its elements is maximum, or find that it is impossible.It is guaranteed that in a given value matrix all values of $$$0$$$ are contained only in internal cells (that is, not in the first or last row and not in the first or last column).

The first line contains integers $$$n$$$ and $$$m$$$ ($$$3 \le n, m \le 500$$$) — the number of rows and columns in the given matrix $$$a$$$. The following lines contain $$$m$$$ each of non-negative integers — the values in the corresponding row of the given matrix: $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 8000$$$). It is guaranteed that for all $$$a_{i,j}=0$$$, $$$1 < i < n$$$ and $$$1 < j < m$$$ are true.

If it is possible to replace all zeros with positive numbers so that the matrix is increasing, print the maximum possible sum of matrix elements. Otherwise, print -1.

NoteIn the first example, the resulting matrix is as follows: 1 3 5 6 73 6 7 8 95 7 8 9 108 9 10 11 12In the second example, the value $$$3$$$ must be put in the middle cell.In the third example, the desired resultant matrix does not exist.

# https://codeforces.com/problemset/problem/1231/C

input = gets.split(' ').map(&:to_i)
n = input[0]
m = input[1]

answer = 0
matrix = []

n.times do
  matrix << gets.split(' ').map(&:to_i)
end

invalid = false

matrix.to_enum.with_index.reverse_each do |row, row_index|
  break if invalid
  row.to_enum.with_index.reverse_each do |number, col_index|
    break if invalid

    if number == 0
      number = matrix[row_index][col_index] =
        [matrix[row_index][col_index+1], matrix[row_index+1][col_index]].min - 1
    elsif (row_index != n-1 &&
          matrix[row_index][col_index] >= matrix[row_index+1][col_index]) ||
          (col_index != m-1 &&
          matrix[row_index][col_index] >= matrix[row_index][col_index+1])
            invalid = true
            answer = -1
            break
    end

    answer += number
  end
end

puts answer


Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rectangles.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given in two lines. The first line contains two integers $$$a_1$$$ and $$$b_1$$$ ($$$1 \le a_1, b_1 \le 100$$$) — the dimensions of the first one obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length). The second line contains two integers $$$a_2$$$ and $$$b_2$$$ ($$$1 \le a_2, b_2 \le 100$$$) — the dimensions of the second obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length).

Print $$$t$$$ answers, each of which is a string "YES" (in the case of a positive answer) or "NO" (in the case of a negative answer). The letters in words can be printed in any case (upper or lower).

gets.to_i.times do
    a = gets.split.map(&:to_i).sort
    b = gets.split.map(&:to_i).sort
    puts a[0] + b[0] == a[1] && a[1] == b[1] ? :Yes : :No
end

n = gets
n = n.to_i

while n > 0 do
  a = gets
  a = a.split
  a[0] = a[0].to_f
  a[1] = a[1].to_f

  area1 = a[0] * a[1]
  #puts area1

  b = gets
  b = b.split

  b[0] = b[0].to_f
  b[1] = b[1].to_f

  area2 = b[0] * b[1]

  area_total = area1 + area2

  if a[0] + b[0] == a[1] and a[0] + b[0] == b[1]
    puts "Yes"
  elsif a[0] + b[1] == a[1] and a[0] + b[1] == b[0]
    puts "Yes"
  elsif a[1] + b[0] == a[0] and a[1] + b[0] == b[1]
    puts "Yes"
  elsif a[1] + b[1] == a[0] and a[1] + b[1] == b[0]
    puts "Yes"
  else
    puts "No"
  end
  n = n - 1
end

t = gets.to_i
t.times do
	a, b = gets.split.map(&:to_i)
	c, d = gets.split.map(&:to_i)
	if (a == d && a == b + c) || (b == c && b == a + d) || (a == c && a == b + d) || (b == d && b == a + c)
		puts "Yes"
	else
		puts "No"
	end
end

i = gets.chomp.to_i

def isCube(b, c, d, e)
  if b + d == c && b + d == e
    return 1
  end

  if b + e == c && b + e == d
    return 1
  end

  if c + d == b && c + d == e
    return 1
  end

  if c + e == b && c + e == d
    return 1
  end

  return 0
end

while (i > 0)
  a1, a2 = gets.split.map(&:to_i)
  b1, b2 = gets.split.map(&:to_i)

  if isCube(a1, a2, b1, b2) == 1
    puts 'Yes'
  else
    puts 'No'
  end

  i -= 1
end

1.upto(gets.chomp.to_i) do

  a,b = gets.chomp.split.map(&:to_i)
  c,d = gets.chomp.split.map(&:to_i)

  if ([a,b].max == [c,d].max) && ([a,b].min + [c,d].min == [a,b].max)
    puts 'Yes'
  else
    puts 'No'
  end

end

t = gets.chomp.to_i
while t > 0
  r1 = gets.chomp.split(' ').map { |x| x.to_i }.sort
  r2 = gets.chomp.split(' ').map { |x| x.to_i }.sort

  if r1.last != r2.last
    puts 'No'
  elsif r1.last == r1.first + r2.first
    puts 'Yes'
  else
    puts 'No'
  end

  t -= 1
end

n = gets
n = n.to_i

while n > 0 do
  a = gets
  a = a.split
  a[0] = a[0].to_f
  a[1] = a[1].to_f

  area1 = a[0] * a[1]
  #puts area1

  b = gets
  b = b.split

  b[0] = b[0].to_f
  b[1] = b[1].to_f

  if a[0] + b[0] == a[1]
    puts "yes"
  elsif a[0] + b[1] == a[1]
    puts "yes"
  elsif a[1] + b[0] == a[0]
    puts "yes"
  elsif a[1] + b[1] == a[0]
    puts "yes"
  else
    puts "no"
  end
  n = n - 1
end

n = gets
n = n.to_i

while n > 0 do
  a = gets
  a = a.split
  a[0] = a[0].to_f
  a[1] = a[1].to_f

  area1 = a[0] * a[1]
  #puts area1

  b = gets
  b = b.split

  b[0] = b[0].to_f
  b[1] = b[1].to_f

  area2 = b[0] * b[1]

  area_total = area1 + area2

  if a[0] + b[0] == a[1] and a[0] + b[0] == b[1]
    puts "Yes"
  elsif a[0] + b[1] == a[1] and a[0] + b[1] == b[1]
    puts "Yes"
  elsif a[1] + b[0] == a[0] and a[1] + b[0] == b[0]
    puts "Yes"
  elsif a[1] + b[1] == a[0] and a[1] + b[1] == b[0]
    puts "Yes"
  else
    puts "No"
  end
  n = n - 1
end

n = gets
n = n.to_i

while n > 0 do
  a = gets
  a = a.split
  a[0] = a[0].to_f
  a[1] = a[1].to_f

  area1 = a[0] * a[1]
  #puts area1

  b = gets
  b = b.split

  b[0] = b[0].to_f
  b[1] = b[1].to_f

  if a[0] + b[0] == a[1]
    puts "Yes"
  elsif a[0] + b[1] == a[1]
    puts "Yes"
  elsif a[1] + b[0] == a[0]
    puts "Yes"
  elsif a[1] + b[1] == a[0]
    puts "Yes"
  else
    puts "No"
  end
  n = n - 1
end

n = gets
n = n.to_i

while n > 0 do
  a = gets
  a = a.split
  a[0] = a[0].to_f
  a[1] = a[1].to_f

  area1 = a[0] * a[1]

  b = gets
  b = b.split

  b[0] = b[0].to_f
  b[1] = b[1].to_f

  area2 = b[0] * b[1]

  area_total = area1 + area2

  if Math.sqrt(area_total) % 1 == 0
    if ( a[0] + b[0] != a[1] + b[1] ) or ( a[0] + b[1] != a[1] + b[0] )
      puts "no"
      break
    end
    puts "yes"
  else
    puts "no"
  end
  n = n - 1
end

n = gets
n = n.to_i

while n > 0 do
  a = gets
  a = a.split
  a[0] = a[0].to_f
  a[1] = a[1].to_f

  area1 = a[0] * a[1]
  #puts area1

  b = gets
  b = b.split

  b[0] = b[0].to_f
  b[1] = b[1].to_f

  area2 = b[0] * b[1]

  area_total = area1 + area2

  if Math.sqrt(area_total) % 1 == 0
    if (( a[0] + b[0] != a[1] + b[1] ) and ( a[0] + b[1] != a[1] + b[0] )) and Math.sqrt(area_total) % 2 == 0
      puts "no"
    else
      puts "yes"
    end

  else
    puts "no"
  end
  n = n - 1
end

n = gets
n = n.to_i

while n > 0 do
  a = gets
  a = a.split
  a[0] = a[0].to_f
  a[1] = a[1].to_f

  area1 = a[0] * a[1]
  #puts area1

  b = gets
  b = b.split

  b[0] = b[0].to_f
  b[1] = b[1].to_f

  area2 = b[0] * b[1]

  area_total = area1 + area2

  if Math.sqrt(area_total) % 1 == 0
    if ( a[0] + b[0] != a[1] + b[1] ) or ( a[0] + b[1] != a[1] + b[0] )
      puts "no"
      break
    end
    puts "yes"
  else
    puts "no"
  end
  n = n - 1
end

n = gets
n = n.to_i

while n > 0 do
  a = gets
  a = a.split
  a[0] = a[0].to_f
  a[1] = a[1].to_f

  area1 = a[0] * a[1]
  #puts area1

  b = gets
  b = b.split

  b[0] = b[0].to_f
  b[1] = b[1].to_f

  area2 = b[0] * b[1]

  area_total = area1 + area2

  if Math.sqrt(area_total) % 1 == 0
    if ( a[0] + b[0] != a[1] + b[1] ) or ( a[0] + b[1] != a[1] + b[0] )
      puts "no"
    else
      puts "yes"
    end

  else
    puts "no"
  end
  n = n - 1
end

n = gets
n = n.to_i

while n > 0 do
  a = gets
  a = a.split
  a[0] = a[0].to_f
  a[1] = a[1].to_f

  area1 = a[0] * a[1]
  #puts area1

  b = gets
  b = b.split

  b[0] = b[0].to_f
  b[1] = b[1].to_f

  area2 = b[0] * b[1]

  area_total = area1 + area2

  if Math.sqrt(area_total) % 1 == 0
    puts "yes"
  else
    puts "no"
  end
  n = n - 1
end

n = gets
n = n.to_i

while n > 0 do
  a = gets
  a = a.split
  a[0] = a[0].to_f
  a[1] = a[1].to_f

  area1 = a[0] * a[1]
  #puts area1

  b = gets
  b = b.split

  b[0] = b[0].to_f
  b[1] = b[1].to_f

  area2 = b[0] * b[1]

  area_total = area1 + area2

  if Math.sqrt(area_total) % 1 == 0
    if (( a[0] + b[0] != a[1] + b[1] ) or ( a[0] + b[1] != a[1] + b[0] )) and Math.sqrt(area_total) % 2 == 0
      puts "no"
    else
      puts "yes"
    end

  else
    puts "no"
  end
  n = n - 1
end

t = gets.to_i
t.times do
	a, b = gets.split.map(&:to_i)
	c, d = gets.split.map(&:to_i)
	if (a == d && a == b + c) || (b == c && b == a + d)
		puts "Yes"
	else
		puts "No"
	end
end

t = gets.to_i
t.times do
	a, b = gets.split.map(&:to_i)
	c, d = gets.split.map(&:to_i)
	if (a == d && a == b + c) || (b == c && b == a + d) || (a == c && a == b + d)
		puts "Yes"
	else
		puts "No"
	end
end

n = gets.to_i
for i in 1..n
    a1, b1 = gets.chomp.split(' ').map(&:to_i)
    a2, b2 = gets.chomp.split(' ').map(&:to_i)
    if a1 == a2
        if b1 + b2 == a1
            puts "YES"
        else
            puts "NO"
        end
    elsif a1 == b2
        if b1 + a2 == a1
            puts "YES"
        else
            puts "NO"
        end
    elsif a2 == b1
        if a1 + b2 == a2
            puts "YES"
        else
            puts "NO"
        end
    elsif b1 == b2
        if a1 + a2 == b2
            puts "YES"
        else
            puts "NO"
        end
    else
        puts "NO"
    end
end


You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. She/he can have no specialization, but can't have both at the same time.So the team is considered perfect if it includes at least one coder, at least one mathematician and it consists of exactly three members.You are a coach at a very large university and you know that $$$c$$$ of your students are coders, $$$m$$$ are mathematicians and $$$x$$$ have no specialization.What is the maximum number of full perfect teams you can distribute them into? Note that some students can be left without a team and each student can be a part of no more than one team.You are also asked to answer $$$q$$$ independent queries.

The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of queries.  Each of the next $$$q$$$ lines contains three integers $$$c$$$, $$$m$$$ and $$$x$$$ ($$$0 \le c, m, x \le 10^8$$$) — the number of coders, mathematicians and students without any specialization in the university, respectively. Note that the no student is both coder and mathematician at the same time.

Print $$$q$$$ integers — the $$$i$$$-th of them should be the answer to the $$$i$$$ query in the order they are given in the input. The answer is the maximum number of full perfect teams you can distribute your students into.

NoteIn the first example here are how teams are formed:  the only team of 1 coder, 1 mathematician and 1 without specialization;  all three teams consist of 1 coder and 2 mathematicians;  no teams can be formed;  no teams can be formed;  one team consists of 1 coder, 1 mathematician and 1 without specialization, the rest aren't able to form any team;  one team consists of 1 coder, 1 mathematician and 1 without specialization, one consists of 2 coders and 1 mathematician and one consists of 1 coder and 2 mathematicians.

n = gets.to_i
n.times do
	a, b, c = gets.split.map(&:to_i)
	if a < b
		x = a
	else
		x = b end
	m = a + b + c - 3 * x
	if m >= 0
		print "#{x}\n"
	else
		print "#{(3 * x + m) / 3}\n" end
end


Harry Potter has a difficult homework. Given a rectangular table, consisting of n × m cells. Each cell of the table contains the integer. Harry knows how to use two spells: the first spell change the sign of the integers in the selected row, the second — in the selected column. Harry's task is to make non-negative the sum of the numbers in each row and each column using these spells.Alone, the boy can not cope. Help the young magician!

The first line contains two integers n and m (1 ≤ n,  m ≤ 100) — the number of rows and the number of columns.  Next n lines follow, each contains m integers: j-th integer in the i-th line is ai, j (|ai, j| ≤ 100), the number in the i-th row and j-th column of the table. The rows of the table numbered from 1 to n. The columns of the table numbered from 1 to m.

In the first line print the number a — the number of required applications of the first spell. Next print a space-separated integers — the row numbers, you want to apply a spell. These row numbers must be distinct! In the second line print the number b — the number of required applications of the second spell. Next print b space-separated integers — the column numbers, you want to apply a spell. These column numbers must be distinct! If there are several solutions are allowed to print any of them.

n,m = gets.split.map(&:to_i)

r_ans = []
c_ans = []

a = []

0.upto(n - 1) do
  a.push(gets.split.map(&:to_i))
end

def row_sum(a, i)
  a[i].inject do |x,y|
    x + y
  end
end

def flip_row(a, i)
  a[i].map! {|x| -x }
end

def flip_col(a, j)
  for x in a
    x[j] = -x[j]
  end
end

def col_sum(a, j)
  ans = 0
  for x in a
    ans += x[j]
  end

  ans
end

loop do
  min_sum = 0
  r_dex = -1
  c_dex = -1

  0.upto(n - 1) do |i|
    r = row_sum(a, i)
    if r < min_sum
      min_sum = r
      r_dex = i
    end
  end

  0.upto(m - 1) do |j|
    r = col_sum(a,j)
    if r < min_sum
      min_sum = r
      r_dex = -1
      c_dex = j
    end
  end

  break if min_sum == 0

#  print "debug: ", r_dex, " ", c_dex," ", min_sum, "\n"

  if r_dex != -1
    flip_row(a, r_dex)
    r_ans.push(r_dex)
  else
    flip_col(a, c_dex)
    c_ans.push(c_dex)
  end

end

def print_it(ans)
  ht = Array.new(110,0)
  for x in ans
    ht[x] += 1
  end
  ans.clear
  ht.each_index do |i|
    ans.push(i) if ht[i] % 2 == 1
  end
end

print_it(r_ans)
print_it(c_ans)

p r_ans.size
for x in r_ans
  p x + 1
end

p c_ans.size
for x in c_ans
  p x + 1
end

n,m = gets.split.map(&:to_i)

r_ans = []
c_ans = []

a = []

0.upto(n - 1) do
  a.push(gets.split.map(&:to_i))
end

def row_sum(a, i)
  a[i].inject do |x,y|
    x + y
  end
end

def flip_row(a, i)
  a[i].map! {|x| -x }
end

def flip_col(a, j)
  for x in a
    x[j] = -x[j]
  end
end

def col_sum(a, j)
  ans = 0
  for x in a
    ans += x[j]
  end

  ans
end

loop do
  min_sum = 0
  r_dex = -1
  c_dex = -1

  0.upto(n - 1) do |i|
    r = row_sum(a, i)
    if r < min_sum
      min_sum = r
      r_dex = i
    end
  end

  0.upto(m - 1) do |j|
    r = col_sum(a,j)
    if r < min_sum
      min_sum = r
      r_dex = -1
      c_dex = j
    end
  end

  break if min_sum == 0

#  print "debug: ", r_dex, " ", c_dex," ", min_sum, "\n"

  if r_dex != -1
    flip_row(a, r_dex)
    r_ans.push(r_dex)
  else
    flip_col(a, c_dex)
    c_ans.push(c_dex)
  end

end

r_ans.uniq!
c_ans.uniq!

def print_it(ans)
  ht = Array.new(110,0)
  for x in ans
    ht[x] += 1
  end
  ans.clear
  ht.each_index do |i|
    ans.push(i) if ht[i] % 2 == 1
  end
end

print_it(r_ans)
print_it(c_ans)

p r_ans.size
for x in r_ans
  p x + 1
end

p c_ans.size
for x in c_ans
  p x + 1
end

n,m = gets.split.map(&:to_i)

r_ans = []
c_ans = []

a = []

0.upto(n - 1) do
  a.push(gets.split.map(&:to_i))
end

def row_sum(a, i)
  a[i].inject do |x,y|
    x + y
  end
end

def flip_row(a, i)
  a[i].map! {|x| -x }
end

def flip_col(a, j)
  for x in a
    x[j] = -x[j]
  end
end

def col_sum(a, j)
  ans = 0
  for x in a
    ans += x[j]
  end

  ans
end

loop do
  min_sum = 0
  r_dex = -1
  c_dex = -1

  0.upto(n - 1) do |i|
    r = row_sum(a, i)
    if r < min_sum
      min_sum = r
      r_dex = i
    end
  end

  0.upto(m - 1) do |j|
    r = col_sum(a,j)
    if r < min_sum
      min_sum = r
      r_dex = -1
      c_dex = j
    end
  end

  break if min_sum == 0

#  print "debug: ", r_dex, " ", c_dex," ", min_sum, "\n"

  if r_dex != -1
    flip_row(a, r_dex)
    r_ans.push(r_dex)
  else
    flip_col(a, c_dex)
    c_ans.push(c_dex)
  end

end

r_ans.uniq!
c_ans.uniq!

def print_it(ans)
  ht = Array.new(110,0)
  for x in ans
    ht[x] += 1
  end
  ans = []
  ht.each_index do |i|
    ans.push(i) if ht[i] % 2 == 1
  end
end

print_it(r_ans)
print_it(c_ans)

p r_ans.size
for x in r_ans
  p x + 1
end

p c_ans.size
for x in c_ans
  p x + 1
end

n,m = gets.split.map(&:to_i)

r_ans = []
c_ans = []

a = []

0.upto(n - 1) do
  a.push(gets.split.map(&:to_i))
end

def row_sum(a, i)
  a[i].inject do |x,y|
    x + y
  end
end

def flip_row(a, i)
  a[i].map! {|x| -x }
end

def flip_col(a, j)
  for x in a
    x[j] = -x[j]
  end
end

def col_sum(a, j)
  ans = 0
  for x in a
    ans += x[j]
  end

  ans
end

loop do
  min_sum = 0
  r_dex = -1
  c_dex = -1

  0.upto(n - 1) do |i|
    r = row_sum(a, i)
    if r < min_sum
      min_sum = r
      r_dex = i
    end
  end

  0.upto(m - 1) do |j|
    r = col_sum(a,j)
    if r < min_sum
      min_sum = r
      r_dex = -1
      c_dex = j
    end
  end

  break if min_sum == 0

#  p r_dex, c_dex, min_sum

  if r_dex != -1
    flip_row(a, r_dex)
    r_ans.push(r_dex)
  else
    flip_col(a, c_dex)
    c_ans.push(c_dex)
  end

end

r_ans.uniq!
c_ans.uniq!

p r_ans.size

for x in r_ans
  p x + 1
end

p c_ans.size
for x in c_ans
  p x + 1
end


Let's call left cyclic shift of some string $$$t_1 t_2 t_3 \dots t_{n - 1} t_n$$$ as string $$$t_2 t_3 \dots t_{n - 1} t_n t_1$$$.Analogically, let's call right cyclic shift of string $$$t$$$ as string $$$t_n t_1 t_2 t_3 \dots t_{n - 1}$$$.Let's say string $$$t$$$ is good if its left cyclic shift is equal to its right cyclic shift.You are given string $$$s$$$ which consists of digits 0–9.What is the minimum number of characters you need to erase from $$$s$$$ to make it good?

The first line contains single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ lines contains test cases — one per line. The first and only line of each test case contains string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$). Each character $$$s_i$$$ is digit 0–9. It's guaranteed that the total length of strings doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print the minimum number of characters you need to erase from $$$s$$$ to make it good.

NoteIn the first test case, you can erase any $$$3$$$ characters, for example, the $$$1$$$-st, the $$$3$$$-rd, and the $$$4$$$-th. You'll get string 51 and it is good.In the second test case, we can erase all characters except 0: the remaining string is 0000 and it's good.In the third test case, the given string $$$s$$$ is already good.

t = gets.to_i
ans = []
t.times do
  s = gets.chomp
  len = s.length
  arr = Array.new(10){Array.new(10,0)}
  prev = Array.new(10){Array.new(10,false)}
  num = Array.new(10,0)
  len.times do |i|
    x = s[i].to_i
    num[x] += 1
    10.times do |j|
      if prev[j][x]
        prev[j][x] = false
        arr[j][x] += 1
      end
      if !prev[x][j]
        prev[x][j] = true
      end
    end
  end
  10.times do |i|
    arr[i][i] = 0
  end
  max = 0
  10.times do |i|
    tmp = arr[i].max
    max = tmp if max < tmp
  end
  max *= 2
  ans << [len-max,len-num.max].min
end
t.times do |i|
  puts ans[i]
end

t = gets.to_i
ans = []
t.times do
  s = gets.chomp
  len = s.length
  arr = Array.new(10,0)
  len.times do |i|
    arr[s[i].to_i] += 1
  end
  max = arr.max
  m1 = arr.index(max)
  arr[m1] = 0
  max = arr.max
  m2 = arr.index(max)
  arr[m2] = 0
  m1m1 = 0
  m1m2 = 0
  m1m2_prev = -1
  m2m1 = 0
  m2m1_prev = -1
  max = arr.max
  m3 = arr.index(max)
  m2m3 = 0
  m2m3_prev = -1
  m3m2 = 0
  m3m2_prev = -1
  m1m3 = 0
  m1m3_prev = -1
  m3m1 = 0
  m3m1_prev = -1
  len.times do |i|
    if s[i].to_i == m1
      if m1m2_prev != m1
        m1m2_prev = m1
      else
        m1m2 += 1
      end
      if m2m1_prev == m2
        m2m1_prev = -1
      else
        m2m1 += 1
      end

      if m1m3_prev != m1
        m1m3_prev = m1
      else
        m1m3 += 1
      end
      if m3m1_prev == m3
        m3m1_prev = -1
      else
        m3m1 += 1
      end

      m2m3 += 1
      m3m2 += 1
    elsif s[i].to_i == m2
      if m1m2_prev == m1
        m1m2_prev = -1
      else
        m1m2 += 1
      end
      if m2m1_prev != m2
        m2m1_prev = m2
      else
        m2m1 += 1
      end
      m1m1 += 1
      m1m3 += 1
      m3m1 += 1

      if m3m2_prev == m3
        m3m2_prev = -1
      else
        m3m2 += 1
      end
      if m2m3_prev != m2
        m2m3_prev = m2
      else
        m2m3 += 1
      end
    elsif s[i].to_i == m3
      if m2m3_prev == m2
        m2m3_prev = -1
      else
        m2m3 += 1
      end
      if m3m2_prev != m3
        m3m2_prev = m3
      else
        m3m2 += 1
      end
      if m1m3_prev == m1
        m1m3_prev = -1
      else
        m1m3 += 1
      end
      if m3m1_prev != m3
        m3m1_prev = m3
      else
        m3m1 += 1
      end

      m1m1 += 1
      m1m2 += 1
      m2m1 += 1
    else
      m1m1 += 1
      m1m2 += 1
      m2m1 += 1
      m2m3 += 1
      m3m2 += 1
      m1m3 += 1
      m3m1 += 1
    end
  end
  m1m2 += 1 if m1m2_prev != -1
  m2m1 += 1 if m2m1_prev != -1
  m2m3 += 1 if m2m3_prev != -1
  m3m2 += 1 if m3m2_prev != -1
  m1m3 += 1 if m1m3_prev != -1
  m3m1 += 1 if m3m1_prev != -1
  ans << [m1m1,m1m2,m2m1,m2m3,m3m2,m1m3,m3m1].min
end
t.times do |i|
  puts ans[i]
end

t = gets.to_i
ans = []
t.times do
  s = gets.chomp
  len = s.length
  arr = Array.new(10,0)
  len.times do |i|
    arr[s[i].to_i] += 1
  end
  max = arr.max
  m1 = arr.index(max)
  arr[m1] = 0
  max = arr.max
  m2 = arr.index(max)
  arr[m2] = 0
  m1m1 = 0
  m1m2 = 0
  m1m2_prev = -1
  m2m1 = 0
  m2m1_prev = -1
  m3 = arr.index(max)
  m2m3 = 0
  m2m3_prev = -1
  m3m2 = 0
  m3m2_prev = -1
  len.times do |i|
    if s[i].to_i == m1
      if m1m2_prev != m1
        m1m2_prev = m1
      else
        m1m2 += 1
      end
      if m2m1_prev == m2
        m2m1_prev = -1
      else
        m2m1 += 1
      end
      m2m3 += 1
      m3m2 += 1
    elsif s[i].to_i == m2
      if m1m2_prev == m1
        m1m2_prev = -1
      else
        m1m2 += 1
      end
      if m2m1_prev != m2
        m2m1_prev = m2
      else
        m2m1 += 1
      end
      m1m1 += 1

      if m3m2_prev == m3
        m3m2_prev = -1
      else
        m3m2 += 1
      end
      if m2m3_prev != m2
        m2m3_prev = m2
      else
        m2m3 += 1
      end
    elsif s[i].to_i == m3
      if m2m3_prev == m2
        m2m3_prev = -1
      else
        m2m3 += 1
      end
      if m3m2_prev != m3
        m3m2_prev = m3
      else
        m3m2 += 1
      end
      m1m1 += 1
      m1m2 += 1
      m2m1 += 1
    else
      m1m1 += 1
      m1m2 += 1
      m2m1 += 1
      m2m3 += 1
      m3m2 += 1
    end
  end
  m1m2 += 1 if m1m2_prev != -1
  m2m1 += 1 if m2m1_prev != -1
  m2m3 += 1 if m2m3_prev != -1
  m3m2 += 1 if m3m2_prev != -1
  ans << [m1m1,m1m2,m2m1,m2m3,m3m2].min
end
t.times do |i|
  puts ans[i]
end

t = gets.to_i
ans = []
t.times do
  s = gets.chomp
  len = s.length
  arr = Array.new(10,0)
  len.times do |i|
    arr[s[i].to_i] += 1
  end
  max = arr.max
  m1 = arr.index(max)
  arr[m1] = 0
  max = arr.max
  m2 = arr.index(max)
  arr[m2] = 0
  m1m1 = 0
  m1m2 = 0
  m1m2_prev = -1
  m2m1 = 0
  m2m1_prev = -1
  m3 = arr.index(max)
  m2m3 = 0
  m2m3_prev = -1
  m3m2 = 0
  m3m2_prev = -1
  len.times do |i|
    if s[i].to_i == m1
      if m1m2_prev != m1
        m1m2_prev = m1
      else
        m1m2 += 1
      end
      if m2m1_prev == m2
        m2m1_prev = -1
      else
        m2m1 += 1
      end
      m2m3 += 1
      m3m2 += 1
    elsif s[i].to_i == m2
      if m1m2_prev == m1
        m1m2_prev = -1
      else
        m1m2 += 1
      end
      if m2m1_prev != m2
        m2m1_prev = m2
      else
        m2m1 += 1
      end
      m1m1 += 1

      if m3m2_prev == m3
        m3m2_prev = -1
      else
        m3m2 += 1
      end
      if m2m3_prev != m2
        m2m3_prev = m2
      else
        m2m3 += 1
      end
    elsif s[i].to_i == m3
      if m2m3_prev == m2
        m2m3_prev = -1
      else
        m2m3 += 1
      end
      if m3m2_prev != m3
        m3m2_prev = m3
      else
        m3m2 += 1
      end
      m1m1 += 1
      m1m2 += 1
      m2m1 += 1
    else
      m1m1 += 1
      m1m2 += 1
      m2m1 += 1
      m2m3 += 1
      m3m2 += 1
    end
  end
  m1m2 += 1 if m1m2_prev != -1
  m2m1 += 1 if m2m1_prev != -1
  ans << [m1m1,m1m2,m2m1,m2m3,m3m2].min
end
t.times do |i|
  puts ans[i]
end

t = gets.to_i
ans = []
t.times do
  s = gets.chomp
  len = s.length
  arr = Array.new(10,0)
  len.times do |i|
    arr[s[i].to_i] += 1
  end
  max = arr.max
  m1 = arr.index(max)
  arr[m1] = 0
  max = arr.max
  m2 = arr.index(max)
  m1m1 = 0
  m1m2 = 0
  m1m2_prev = -1
  m2m1 = 0
  m2m1_prev = -1
  len.times do |i|
    if s[i].to_i == m1
      if m1m2_prev != m1
        m1m2_prev = m1
      else
        m1m2 += 1
      end
      if m2m1_prev == m2
        m2m1_prev = -1
      else
        m2m1 += 1
      end
    elsif s[i].to_i == m2
      if m1m2_prev == m1
        m1m2_prev = -1
      else
        m1m2 += 1
      end
      if m2m1_prev != m2
        m2m1_prev = m2
      else
        m2m1 += 1
      end
      m1m1 += 1
    else
      m1m1 += 1
      m1m2 += 1
      m2m1 += 1
    end
  end
  m1m2 += 1 if m1m2_prev != -1
  m2m1 += 1 if m2m1_prev != -1
  ans << [m1m1,m1m2,m2m1].min
end
t.times do |i|
  puts ans[i]
end

t = gets.to_i
ans = []
t.times do
  s = gets.chomp
  len = s.length
  arr = Array.new(10,0)
  len.times do |i|
    arr[s[i].to_i] += 1
  end
  max = arr.max
  m1 = arr.index(max)
  arr[m1] = 0
  max = arr.max
  m2 = arr.index(max)
  arr[m2] = 0
  m1m1 = 0
  m1m2 = 0
  m1m2_prev = -1
  m2m1 = 0
  m2m1_prev = -1
  m3 = arr.index(max)
  m2m3 = 0
  m2m3_prev = -1
  m3m2 = 0
  m3m2_prev = -1
  m1m3 = 0
  m1m3_prev = -1
  m3m1 = 0
  m3m1_prev = -1
  len.times do |i|
    if s[i].to_i == m1
      if m1m2_prev != m1
        m1m2_prev = m1
      else
        m1m2 += 1
      end
      if m2m1_prev == m2
        m2m1_prev = -1
      else
        m2m1 += 1
      end

      if m1m3_prev != m1
        m1m3_prev = m1
      else
        m1m3 += 1
      end
      if m3m1_prev == m3
        m3m1_prev = -1
      else
        m3m1 += 1
      end

      m2m3 += 1
      m3m2 += 1
    elsif s[i].to_i == m2
      if m1m2_prev == m1
        m1m2_prev = -1
      else
        m1m2 += 1
      end
      if m2m1_prev != m2
        m2m1_prev = m2
      else
        m2m1 += 1
      end
      m1m1 += 1
      m1m3 += 1
      m3m1 += 1

      if m3m2_prev == m3
        m3m2_prev = -1
      else
        m3m2 += 1
      end
      if m2m3_prev != m2
        m2m3_prev = m2
      else
        m2m3 += 1
      end
    elsif s[i].to_i == m3
      if m2m3_prev == m2
        m2m3_prev = -1
      else
        m2m3 += 1
      end
      if m3m2_prev != m3
        m3m2_prev = m3
      else
        m3m2 += 1
      end
      if m1m3_prev == m1
        m1m3_prev = -1
      else
        m1m3 += 1
      end
      if m3m1_prev != m3
        m3m1_prev = m3
      else
        m3m1 += 1
      end

      m1m1 += 1
      m1m2 += 1
      m2m1 += 1
    else
      m1m1 += 1
      m1m2 += 1
      m2m1 += 1
      m2m3 += 1
      m3m2 += 1
      m1m3 += 1
      m3m1 += 1
    end
  end
  m1m2 += 1 if m1m2_prev != -1
  m2m1 += 1 if m2m1_prev != -1
  m2m3 += 1 if m2m3_prev != -1
  m3m2 += 1 if m3m2_prev != -1
  m1m3 += 1 if m1m3_prev != -1
  m3m1 += 1 if m3m1_prev != -1
  ans << [m1m1,m1m2,m2m1,m2m3,m3m2,m1m3,m3m1].min
end
t.times do |i|
  puts ans[i]
end