Polycarp has an integer $$$n$$$ that doesn't contain the digit 0. He can do the following operation with his number several (possibly zero) times: Reverse the prefix of length $$$l$$$ (in other words, $$$l$$$ leftmost digits) of $$$n$$$. So, the leftmost digit is swapped with the $$$l$$$-th digit from the left, the second digit from the left swapped with ($$$l-1$$$)-th left, etc. For example, if $$$n=123456789$$$ and $$$l=5$$$, then the new value of $$$n$$$ will be $$$543216789$$$.Note that for different operations, the values of $$$l$$$ can be different. The number $$$l$$$ can be equal to the length of the number $$$n$$$ — in this case, the whole number $$$n$$$ is reversed.Polycarp loves even numbers. Therefore, he wants to make his number even. At the same time, Polycarp is very impatient. He wants to do as few operations as possible.Help Polycarp. Determine the minimum number of operations he needs to perform with the number $$$n$$$ to make it even or determine that this is impossible.You need to answer $$$t$$$ independent test cases.

The first line contains the number $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each of the following $$$t$$$ lines contains one integer $$$n$$$ ($$$1 \le n < 10^9$$$). It is guaranteed that the given number doesn't contain the digit 0.

Print $$$t$$$ lines. On each line print one integer — the answer to the corresponding test case. If it is impossible to make an even number, print -1.

NoteIn the first test case, $$$n=3876$$$, which is already an even number. Polycarp doesn't need to do anything, so the answer is $$$0$$$.In the second test case, $$$n=387$$$. Polycarp needs to do $$$2$$$ operations: Select $$$l=2$$$ and reverse the prefix $$$\underline{38}7$$$. The number $$$n$$$ becomes $$$837$$$. This number is odd. Select $$$l=3$$$ and reverse the prefix $$$\underline{837}$$$. The number $$$n$$$ becomes $$$738$$$. This number is even.It can be shown that $$$2$$$ is the minimum possible number of operations that Polycarp needs to do with his number to make it even.In the third test case, $$$n=4489$$$. Polycarp can reverse the whole number (choose a prefix of length $$$l=4$$$). It will become $$$9844$$$ and this is an even number.In the fourth test case, $$$n=3$$$. No matter how hard Polycarp tried, he would not be able to make an even number.

inputs = STDIN.read.strip.split("\n")
inputs.shift

inputs.each do |inp|
    if inp.to_i % 2 == 0
        puts "0"
        next
    end
    if !inp.chars.any?{|c| c.to_i % 2 == 0}
        puts "-1"
        next
    end
    if inp[0].to_i % 2 == 0
        puts "1"
        next
    end

    puts "2"
end

t = gets.to_i
ans = []
t.times do |i|
  n = gets.chomp.split("").map(&:to_i)
  if n[-1] % 2 == 0
    ans << 0
  elsif n[0] % 2 == 0
    ans << 1
  elsif n.any?{|v| v%2==0}
    ans << 2
  else
    ans << -1
  end
end
puts ans

def solve
  n = gets.strip.split('').map(&:to_i)
  if n.last.even?
    puts 0
  elsif n.first.even?
    puts 1
  elsif n.any?(&:even?)
    puts 2
  else
    puts '-1'
  end
end

gets.strip.to_i.times { solve }

t = gets.to_i
t.times do
  s = gets.chomp.chars.map(&:to_i)
  if s.all?(&:odd?)
    puts -1
  elsif s[-1].even?
    puts 0
  elsif s[0].even?
    puts 1
  else
    puts 2
  end
end

t = gets.split
t = t[0].to_i

for i in 0..t-1 do
  b = gets.split
  a = b[0].split("")
  if b[0].to_i % 2 == 0
    puts 0
  elsif a[0].to_i % 2 == 0
    puts 1
  else
    n = a.length
    s = 0
    for j in 1..n-1 do
      if a[j].to_i % 2 == 0
        puts 2
        s = 1
        break
      end
    end
    if s==0
      puts -1
    end
  end
end

def gs() = gets.chomp
def gi() = gets.to_i
def gli() = gets.split.map(&:to_i)
def cyesno(x) = x ? :Yes : :No
def uyesno(x) = x ? :YES : :NO

T = gi
T.times do
  s = gs.split("").map(&:to_i)
  if s.count { |x| x.even? }.zero?
    puts '-1'
  else
    if s[-1].even?
      puts 0
    elsif s[0].even?
      puts 1
    else
      puts 2
    end
  end
end

inputs = STDIN.read.strip.split("\n")
inputs.shift

inputs.each do |inp|
    if inp.to_i % 2 == 0
        puts "0"
        next
    end
    if inp.length == 1
        puts "-1"
        next
    end
    if inp[0].to_i % 2 == 0
        puts "1"
        next
    end

    puts "2"
end


You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum.Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.You should write a program which finds sum of the best subsequence.

The first line contains integer number n (1 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an ( - 104 ≤ ai ≤ 104). The sequence contains at least one subsequence with odd sum.

NoteIn the first example sum of the second and the fourth elements is 3.

_n = STDIN.gets.chomp.to_i
xs = STDIN.gets.chomp.split.map { |x| x.to_i }

def sum(arr)
  arr.inject(0) { |sum, x| sum + x }
end

p_even_sum = xs.select { |x| x > 0 && x % 2 == 0 }.inject(0) { |sum, x| sum + x }
p_odds = xs.select { |x| x > 0 && x % 2 == 1 }.sort
m_odd = xs.select { |x| x < 0 && x % 2 == 1 }.max

answer = p_even_sum

if p_odds.length == 0
  answer += m_odd
else
  if p_odds.length % 2 == 0
    if !m_odd.nil? && m_odd + p_odds.first > 0
      answer += m_odd
    else
      p_odds.shift
    end
  end
  # p_odds.shift if p_odds.length % 2 == 0
  answer += sum(p_odds)
end

puts answer

# -6004 4882 9052 413 6056 4306 9946 -4616 -6135 906 -1718 5252 -2866 9061 4046

def ascan; gets.split.map(&:to_i); end
def scan; gets.to_i; end

gets
aa = ascan.sort!

ao = []
ae = []
aa.each{|e| if e.odd? ; ao << e ; else ; ae << e ; end }

best = ae.inject(0){|s,e| 0 < e ? s+e : s}

best += ao.pop

while 2<=ao.size
    x,y = ao.pop(2)
    break if x+y <= 0
    best += x+y
end

p best

n = gets.strip.to_i
data = gets.split.map(&:to_i)

even = data.select { |x| x > 0 and x % 2 == 0 }
odd_pos = data.select { |x| x > 0 and x % 2 == 1 }
odd_neg = data.select { |x| x < 0 and x % 2 == 1 }

if odd_pos.length > 0
    odd_neg.push(-odd_pos.min)
    exchange = (odd_pos.length % 2 == 0 ? [-odd_pos.min, odd_neg.max].max : 0)
    puts (even.reduce(0, :+) + odd_pos.reduce(:+) + exchange)
else
    puts (even.reduce(0, :+) + odd_neg.max)
end

gets
res, aa = 0, []
gets.split.map(&:to_i).each do |a|
  if a & 1 == 1
    aa.push(a)
  elsif a > 0
    res += a
  end
end
aa.sort!
aa.shift if aa.length & 1 == 0
res += aa.pop
until aa.empty? do
  a = aa.pop + aa.pop
  break if a <= 0
  res += a
end
p res

gets
res, aa = 0, []
gets.split.map(&:to_i).each do |a|
  if a & 1 == 1
    aa.push(a)
  elsif a > 0
    res += a
  end
end
aa.sort!
aa.shift if aa.length & 1 == 0
res += aa.pop
until aa.empty? || (a = aa.pop + aa.pop) <= 0
  res += a
end
p res

_n = STDIN.gets.chomp.to_i
xs = STDIN.gets.chomp.split.map { |x| x.to_i }

def sum(arr)
  arr.inject(0) { |sum, x| sum + x }
end

p_even_sum = xs.select { |x| x > 0 && x % 2 == 0 }.inject(0) { |sum, x| sum + x }
p_odds = xs.select { |x| x > 0 && x % 2 == 1 }.sort
m_odd = xs.select { |x| x < 0 && x % 2 == 1 }.first

answer = p_even_sum

if p_odds.length == 0
  answer += m_odd
else
  p_odds.shift if p_odds.length % 2 == 0
  answer += sum(p_odds)
end

puts answer

# -6004 4882 9052 413 6056 4306 9946 -4616 -6135 906 -1718 5252 -2866 9061 4046

_n = STDIN.gets.chomp.to_i
xs = STDIN.gets.chomp.split.map { |x| x.to_i }

def sum(arr)
  arr.inject(0) { |sum, x| sum + x }
end

p_even_sum = xs.select { |x| x > 0 && x % 2 == 0 }.inject(0) { |sum, x| sum + x }
p_odds = xs.select { |x| x > 0 && x % 2 == 1 }.sort
m_odd = xs.select { |x| x < 0 && x % 2 == 1 }.max

answer = p_even_sum

if p_odds.length == 0
  answer += m_odd
else
  p_odds.shift if p_odds.length % 2 == 0
  answer += sum(p_odds)
end

puts answer

# -6004 4882 9052 413 6056 4306 9946 -4616 -6135 906 -1718 5252 -2866 9061 4046

_n = STDIN.gets.chomp.to_i
xs = STDIN.gets.chomp.split.map { |x| x.to_i }

max_odd = nil
max_even = 0

xs.each do |x|
  if x % 2 == 1
    if max_odd.nil?
      max_odd = x
    else
      max_odd = [ max_odd, max_even + x ].max
      max_even = [ max_even, max_odd + x ].max
    end
  else
    max_even = [ max_even, max_even + x ].max
  end
end

puts max_odd

def ascan; gets.split.map(&:to_i); end
def scan; gets.to_i; end

gets
aa = ascan.sort!

ao = []
ae = []
aa.each{|e| if e.odd? ; ao << e ; else ; ae << e ; end }

best = ae.inject(0){|s,e| 0 < e ? e : 0}

best += ao.pop

while 2<=ao.size
    x,y = ao.pop(2)
    break if x+y <= 0
    best += x+y
end

p best

n = gets.strip.to_i
data = gets.split.map(&:to_i)

even = data.select { |x| x > 0 and x % 2 == 0 }
odd_pos = data.select { |x| x > 0 and x % 2 == 1 }
odd_neg = data.select { |x| x < 0 and x % 2 == 1 }

if odd_pos.length > 0
    puts (even.reduce(0, :+) + odd_pos.reduce(:+) - (odd_pos.length % 2 == 0 ? odd_pos.min : 0))
else
    puts (even.reduce(0, :+) + odd_neg.max)
end

n = gets.strip.to_i
data = gets.split.map(&:to_i)

even = data.select { |x| x > 0 and x % 2 == 0 }
odd_pos = data.select { |x| x > 0 and x % 2 == 1 }
odd_neg = data.select { |x| x < 0 and x % 2 == 1 }

if odd_pos.length > 0
    puts (even.reduce(0, :+) + odd_pos.reduce(:+))
else
    puts (even.reduce(0, :+) + odd_neg.max)
end

gets
res, aa = 0, []
"-2 2 -3 1".split.map(&:to_i).each do |a|
  if a & 1 == 1
    aa.push(a)
  elsif a > 0
    res += a
  end
end
aa.sort!
aa.shift if aa.length & 1 == 0
res += aa.pop
until aa.empty? do
  a = aa.pop + aa.pop
  break if a <= 0
  res += a
end
p res


Maxim always goes to the supermarket on Sundays. Today the supermarket has a special offer of discount systems.There are m types of discounts. We assume that the discounts are indexed from 1 to m. To use the discount number i, the customer takes a special basket, where he puts exactly qi items he buys. Under the terms of the discount system, in addition to the items in the cart the customer can receive at most two items from the supermarket for free. The number of the "free items" (0, 1 or 2) to give is selected by the customer. The only condition imposed on the selected "free items" is as follows: each of them mustn't be more expensive than the cheapest item out of the qi items in the cart.Maxim now needs to buy n items in the shop. Count the minimum sum of money that Maxim needs to buy them, if he use the discount system optimally well.Please assume that the supermarket has enough carts for any actions. Maxim can use the same discount multiple times. Of course, Maxim can buy items without any discounts.

The first line contains integer m (1 ≤ m ≤ 105) — the number of discount types. The second line contains m integers: q1, q2, ..., qm (1 ≤ qi ≤ 105).  The third line contains integer n (1 ≤ n ≤ 105) — the number of items Maxim needs. The fourth line contains n integers: a1, a2, ..., an (1 ≤ ai ≤ 104) — the items' prices. The numbers in the lines are separated by single spaces.

In a single line print a single integer — the answer to the problem.

NoteIn the first sample Maxim needs to buy two items that cost 100 and get a discount for two free items that cost 50. In that case, Maxim is going to pay 200.In the second sample the best strategy for Maxim is to buy 3 items and get 2 items for free using the discount. In that case, Maxim is going to pay 150.

def run
  lines = ARGF.readlines

  m = lines.shift.chomp.to_i
  q = lines.shift.chomp.split(" ").map {|x| x.to_i }
  n = lines.shift.chomp.to_i
  a = lines.shift.chomp.split(" ").map {|x| x.to_i }

  a.sort_by! { |x| -x }
  q.sort!

  ans = 0
  a.each_slice(q.first + 2) do |items|
    ans += items[0, q.first].reduce(&:+)
  end

  puts ans
end

run if $0 == __FILE__

class Pair
    attr_reader :pos,:val

    def initialize(pos, val)
        @pos=pos
        @val=val
    end

    def <=>(other)
        val<=>other.val
    end
end

pairs=[nil]*10
10.times {|i| pairs[i]=Pair.new(0,0)}

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

a=gets.split.map(&:to_i).sort {|a,b| b<=>a}

i=0
ans=0
while i<n
  min.times {
      break if i==n
      ans+=a[i]
      i+=1
  }

  i+=2
end

puts ans

class Pair
    attr_reader :pos,:val

    def initialize(pos, val)
        @pos=pos
        @val=val
    end

    def <=>(other)
        val<=>other.val
    end
end

pair=Pair.new(0,0)
m=gets.to_i
min=gets.split.map(&:to_i).min
n=gets.to_i

a=gets.split.map(&:to_i).sort {|a,b| b<=>a}

i=0
ans=0
while i<n
  min.times {
      break if i==n
      ans+=a[i]
      i+=1
  }

  i+=2
end

puts ans

class Pair
    attr_reader :pos,:val

    def initialize(pos, val)
        @pos=pos
        @val=val
    end

    def <=>(other)
        val<=>other.val
    end
end

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

a=gets.split.map(&:to_i).sort {|a,b| b<=>a}

i=0
ans=0
while i<n
  min.times {
      break if i==n
      ans+=a[i]
      i+=1
  }

  i+=2
end

puts ans

BEGIN{
	def gint()
		return gets.split.map(&:to_i)
	end
	def main()
		m = gint
		p = gint
		w = p.min
		n = gint
		a = gint
		a.sort!
		sum = 0
		n = a.length - 1
		i = n
		#print a
		#puts
#		puts "START_ALL"
		while i >= 0 do
#			puts "START"
#			puts i
			w.times do |u|
#				puts u
				sum += a[i - u] if i - u >= 0
			end
			i -= w
			i -= 2
		end
#			puts "ENDS"
		puts sum
	end
	Test_case = 1
	Test_case.times do
		main()
	end
}

m = gets.to_i

q = gets.split(" ").collect{|x| x.to_i}
n = gets.to_i
a = gets.split(" ").collect{|x| x.to_i}

result = 0

a.sort! { |a, b| b <=> a }
qm = q.min

t = qm
k = 0

a.each_index { |i|
	if t > 0
		result += a[i]
		t -= 1
		k = 2
	elsif k > 0
		k -= 1
		if k == 0
			t= qm
		end
	end
}

puts result

def run
  lines = ARGF.readlines

  m = lines.shift.chomp.to_i
  q = lines.shift.chomp.split(" ").map {|x| x.to_i }
  n = lines.shift.chomp.to_i
  a = lines.shift.chomp.split(" ").map {|x| x.to_i }

  a.sort_by! { |x| -x }
  costs = []

  sum = 0
  a.length.times do |i|
    sum += a[i]
    costs[i] = sum
  end
  costs.unshift(0)

  a.length.times do |i|
    q.each do |item|
      if item <= (a.length - i)
        sum = costs[i]

        item.times do |c|
          sum += a[i + c]
        end

        costs[i + item + 0] = sum if costs[i + item + 0] and costs[i + item + 0] > sum
        costs[i + item + 1] = sum if costs[i + item + 1] and costs[i + item + 1] > sum
        costs[i + item + 2] = sum if costs[i + item + 2] and costs[i + item + 2] > sum
      end
    end
  end

  puts costs[a.length]
end

run if $0 == __FILE__


You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills:  the matrix has a row with prime numbers only;  the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got.

The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces.

Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0.

NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2.

# -*- encoding: utf-8 -*-
require 'prime'

n, m = gets.chomp.split(" ").map{ |e| e.to_i }
matrix = []
n.times do
  matrix << gets.chomp.split(" ").map{ |e| e.to_i }
end
primes = Prime.each(100000 + 1000).to_a
min = 100000 * [n, m].max

memo = []
idx = 0
for i in 0 .. 100000 do
  if not i <= primes[idx]
    idx += 1
  end
  memo << primes[idx]
end

matrix.concat matrix.transpose

for i in 0 .. (n + m - 1) do
  col = matrix[i]

  num = 0
  col.each do |n|
    num += memo[n] - n
  end
  min = [min, num].min
end

puts min

#!/usr/bin/ruby1.9

def eratosthenes(n)
	primes = []
	sieve = (0..n).collect {|x| x}
	start = 2
	while true
		while sieve[start] == 0
			return primes if start == n
			start += 1
		end
		primes.push(start)
		pos = 2*start
		while pos <= n
			sieve[pos] = 0
			pos += start
		end
		sieve[start] = 0
	end
end

primes = eratosthenes(101*1000)
up = Array.new(100*1000+1)
prime_ix = 0
prime = primes[prime_ix]
up.length.times do |i|
	if i <= prime
		up[i] = prime
	else
		prime_ix += 1
		prime = up[i] = primes[prime_ix]
	end
end

r_num, c_num = STDIN.readline.split.collect {|s| s.to_i}
r_totals = Array.new(r_num, 0)
c_totals = Array.new(c_num, 0)

r_num.times do |r|
	row = STDIN.readline.split.collect {|s| s.to_i}
	c_num.times do |c|
		x = row[c]
		r_totals[r] += up[x]-x
		c_totals[c] += up[x]-x
	end
end

puts [r_totals.min, c_totals.min].min

require 'mathn'
MAX = 10 ** 5 + 10

flag = Array.new(MAX, true)
flag[0] = false
flag[1] = false
2.upto(Math::sqrt(MAX)) do |i|
  if flag[i]
    (2 * i).upto(MAX) do |j|
      flag[j] = false if j % i == 0
    end
  end
end

$diff = Array.new(MAX, 0)
prev = MAX
MAX.downto(0) do |i|
  prev = i if flag[i]
  $diff[i] = prev - i
end

def run
  m, n = ARGF.readline.split.map(&:to_i)

  ary = []
  ARGF.readlines.each do |line|
    ary << line.split.map(&:to_i)
  end

  list = []
  list += ary.map           { |x| x.reduce(0) { |sum, y| sum + $diff[y] } }
  list += ary.transpose.map { |x| x.reduce(0) { |sum, y| sum + $diff[y] } }
  puts list.min
end

run if $0 == __FILE__

require 'mathn'

MAX = 10 ** 5 + 10

flag = Array.new(MAX, true)
flag[0] = false
flag[1] = false
2.upto(Math::sqrt(MAX)) do |i|
  if flag[i]
    (2 * i).upto(MAX) do |j|
      flag[j] = false if j % i == 0
    end
  end
end

$diff = Array.new(MAX, 0)
$diff[0] = 2
$diff[1] = 1

prev = MAX
MAX.downto(2) do |i|
  if flag[i]
    prev = i
    $diff[i] = 0
  else
    $diff[i] = prev - i
  end
end

def run
  m, n = ARGF.readline.split.map(&:to_i)

  ary = []
  ARGF.readlines.each do |line|
    ary << line.split.map(&:to_i)
  end

  min = 1 << 30
  m.times do |i|
    sum = 0
    n.times do |j|
      sum += $diff[ary[i][j]]
    end

    min = [min, sum].min
  end

  n.times do |i|
    sum = 0
    m.times do|j|
      sum += $diff[ary[j][i]]
    end

    min = [min, sum].min
  end

  puts min
end

run if $0 == __FILE__

require 'mathn'

MAX = 10 ** 5 + 10

flag = Array.new(MAX, true)
flag[0] = false
flag[1] = false
2.upto(Math::sqrt(MAX)) do |i|
  if flag[i]
    (2 * i).upto(MAX) do |j|
      flag[j] = false if j % i == 0
    end
  end
end

$diff = Array.new(MAX, 0)
prev = MAX
MAX.downto(0) do |i|
  if flag[i]
    prev = i
    $diff[i] = 0
  else
    $diff[i] = prev - i
  end
end

def run
  m, n = ARGF.readline.split.map(&:to_i)

  ary = []
  ARGF.readlines.each do |line|
    ary << line.split.map(&:to_i)
  end

  list = []
  list += ary.map           { |x| x.reduce(0) { |sum, y| sum + $diff[y] } }
  list += ary.transpose.map { |x| x.reduce(0) { |sum, y| sum + $diff[y] } }
  puts list.min
end

run if $0 == __FILE__

require 'prime'

n, m = gets.split(' ').collect!{|i| i.to_i}

k = []
n.times do |j|
	k[j] = gets.split(' ').collect!{|i| i.to_i}
end

min = 100000
column = Array.new(m, 0)

arr = []
pr = []
Prime.each(100010) do |prime|
  pr << prime
end
# p = pr[0]
i = 0
(1..100000).each do |y|
	i += 1 if y > pr[i]
	arr[y] = pr[i]
end

n.times do |i|
	row = 0
	m.times do |j|
		# x = 0
		# y = k[i][j]
		# while !y.prime?
		# 	x += 1
		# 	y += 1
		# end
		x = arr[k[i][j]] - k[i][j]
		row += x
		column[j] += x
	end
	min = row if row < min
end

column.each do |x|
	min = x if x < min
end

p min

# -*- encoding: utf-8 -*-
require 'prime'

class Array
  def binary_search(val, left = 0, right = nil)
    right = self.size - 1 unless right
    mid = (left + right) / 2

    return nil if left > right

    a = (mid > 0) ? self[mid - 1] : 0
    if val < self[mid] and val > a
      return self[mid]
    elsif val > self[mid]
      binary_search(val, mid + 1, right)
    else
      binary_search(val, left, mid - 1)
    end
  end
end

n, m = gets.chomp.split(" ").map{ |e| e.to_i }
matrix = []
n.times do
  matrix << gets.chomp.split(" ").map{ |e| e.to_i }
end
# 行列を入れ替えたものを結合
matrix.concat matrix.transpose
primes = Prime.each(100000).to_a
min = 100000 * [n, m].max
memo = {}

for i in 0 .. (n + m - 1) do
  col = matrix[i]

  num = 0
  col.each do |n|
    if not primes.include? n
      if memo.include? n
        num += memo[n]
      else
        tmp = primes.binary_search(n)
        memo[n] = tmp

        num += tmp - n
      end
    end
  end
  min = [min, num].min
end

puts min


A string $$$s$$$ of length $$$n$$$ ($$$1 \le n \le 26$$$) is called alphabetical if it can be obtained using the following algorithm:  first, write an empty string to $$$s$$$ (i.e. perform the assignment $$$s$$$ := "");  then perform the next step $$$n$$$ times;  at the $$$i$$$-th step take $$$i$$$-th lowercase letter of the Latin alphabet and write it either to the left of the string $$$s$$$ or to the right of the string $$$s$$$ (i.e. perform the assignment $$$s$$$ := $$$c+s$$$ or $$$s$$$ := $$$s+c$$$, where $$$c$$$ is the $$$i$$$-th letter of the Latin alphabet). In other words, iterate over the $$$n$$$ first letters of the Latin alphabet starting from 'a' and etc. Each time we prepend a letter to the left of the string $$$s$$$ or append a letter to the right of the string $$$s$$$. Strings that can be obtained in that way are alphabetical.For example, the following strings are alphabetical: "a", "ba", "ab", "bac" and "ihfcbadeg". The following strings are not alphabetical: "z", "aa", "ca", "acb", "xyz" and "ddcba".From the given string, determine if it is alphabetical.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case is written on a separate line that contains one string $$$s$$$. String $$$s$$$ consists of lowercase letters of the Latin alphabet and has a length between $$$1$$$ and $$$26$$$, inclusive.

Output $$$t$$$ lines, each of them must contain the answer to the corresponding test case. Output YES if the given string $$$s$$$ is alphabetical and NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive answer).

11
a
ba
ab
bac
ihfcbadeg
z
aa
ca
acb
xyz
ddcba

NoteThe example contains test cases from the main part of the condition.

def is_alph(s)
  s = s.chars
  cur = ('a'.ord + s.size - 1).chr

  while !s.empty? && cur >= 'a'
    if s.first == cur
      s = s[1..]
    elsif s.last == cur
      s = s[0..-2]
    else
      break
    end
    cur = (cur.ord - 1).chr
  end

  s.empty? && (cur.ord + 1).chr == 'a'
end

gets.to_i.times {
  s = gets.strip
  puts(is_alph(s) ? 'YES' : 'NO')
}

ALL_CHARS = 'abcdefghijklmnopqrstuvwxyz'.freeze

def solve(inp)
  orig_size = inp.size
  ptr = 0
  chars = ALL_CHARS[0...orig_size].reverse

  while inp.size > 0 do
    return false unless inp[0] == chars[ptr] || inp[-1] == chars[ptr]
    inp = inp.sub(chars[ptr], '')
    ptr += 1
  end

  orig_size == ptr
end

t = gets.chomp.to_i
t.times do
  inp = gets.chomp
  solve(inp) ? puts("YES\n") : puts("NO\n")
end


You are given a permutation $$$a_1, a_2, \ldots, a_n$$$ of size $$$n$$$, where each integer from $$$1$$$ to $$$n$$$ appears exactly once.You can do the following operation any number of times (possibly, zero):  Choose any three indices $$$i, j, k$$$ ($$$1 \le i < j < k \le n$$$).  If $$$a_i > a_k$$$, replace $$$a_i$$$ with $$$a_i + a_j$$$. Otherwise, swap $$$a_j$$$ and $$$a_k$$$. Determine whether you can make the array $$$a$$$ sorted in non-descending order.

Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 10$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$1 \le a_i \le n$$$, $$$a_i \neq a_j$$$ if $$$i \neq j$$$) — the elements of the array $$$a$$$.

For each test case, output "Yes" (without quotes) if the array can be sorted in non-descending order, and "No" (without quotes) otherwise. You can output "Yes" and "No" in any case (for example, strings "YES", "yEs" and "yes" will be recognized as a positive response).

NoteIn the first test case, $$$[1,2,3]$$$ is already sorted in non-descending order.In the second test case, we can choose $$$i = 1,j = 2,k = 3$$$. Since $$$a_1 \le a_3$$$, swap $$$a_2$$$ and $$$a_3$$$, the array then becomes $$$[1,2,3]$$$, which is sorted in non-descending order.In the seventh test case, we can do the following operations successively:  Choose $$$i = 5,j = 6,k = 7$$$. Since $$$a_5 \le a_7$$$, swap $$$a_6$$$ and $$$a_7$$$, the array then becomes $$$[1,2,6,7,4,5,3]$$$.  Choose $$$i = 5,j = 6,k = 7$$$. Since $$$a_5 > a_7$$$, replace $$$a_5$$$ with $$$a_5+a_6=9$$$, the array then becomes $$$[1,2,6,7,9,5,3]$$$.  Choose $$$i = 2,j = 5,k = 7$$$. Since $$$a_2 \le a_7$$$, swap $$$a_5$$$ and $$$a_7$$$, the array then becomes $$$[1,2,6,7,3,5,9]$$$.  Choose $$$i = 2,j = 4,k = 6$$$. Since $$$a_2 \le a_6$$$, swap $$$a_4$$$ and $$$a_6$$$, the array then becomes $$$[1,2,6,5,3,7,9]$$$.  Choose $$$i = 1,j = 3,k = 5$$$. Since $$$a_1 \le a_5$$$, swap $$$a_3$$$ and $$$a_5$$$, the array then becomes $$$[1,2,3,5,6,7,9]$$$, which is sorted in non-descending order. In the third, the fourth, the fifth and the sixth test cases, it can be shown that the array cannot be sorted in non-descending order.

t = gets.to_i

t.times do
  n = gets.to_i
  arr = gets.split(' ').map(&:to_i)

  puts arr[0] == arr.sort[0] ? 'YES' : 'NO'
end

gets.to_i.times do
    _=gets.chomp.to_i
    arr=gets.chomp.split.map(&:to_i)
    if arr[0]==1
        puts "Yes"
    else
        puts "No"
    end
end


You are given four positive integers $$$n$$$, $$$m$$$, $$$a$$$, $$$b$$$ ($$$1 \le b \le n \le 50$$$; $$$1 \le a \le m \le 50$$$). Find any such rectangular matrix of size $$$n \times m$$$ that satisfies all of the following conditions:  each row of the matrix contains exactly $$$a$$$ ones;  each column of the matrix contains exactly $$$b$$$ ones;  all other elements are zeros. If the desired matrix does not exist, indicate this.For example, for $$$n=3$$$, $$$m=6$$$, $$$a=2$$$, $$$b=1$$$, there exists a matrix satisfying the conditions above:$$$$$$ \begin{vmatrix} 0 & 1 & 0 & 0 & 0 & 1 \\ 1 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 & 1 & 0 \end{vmatrix} $$$$$$

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case is described by four positive integers $$$n$$$, $$$m$$$, $$$a$$$, $$$b$$$ ($$$1 \le b \le n \le 50$$$; $$$1 \le a \le m \le 50$$$), where $$$n$$$ and $$$m$$$ are the sizes of the matrix, and $$$a$$$ and $$$b$$$ are the number of ones for rows and columns, respectively.

For each test case print:   "YES" (without quotes) and the required matrix (if there are several answers, print any) if it exists, or  "NO" (without quotes) if it does not exist.  To print the matrix $$$n \times m$$$, print $$$n$$$ rows, each of which consists of $$$m$$$ numbers $$$0$$$ or $$$1$$$ describing a row of the matrix. Numbers must be printed without spaces.

gets.to_i.times do
	h, w, a, b = gets.split.map(&:to_i)
	if h * a == w * b
		puts 'YES'
		ans = Array.new(h) { %w[0] * w }
		h.times { |y| (a * y...a * (y + 1)).each { |x| ans[y][x % w] = '1' } }
		puts ans.map(&:join).join("\n")
	else
		puts 'NO'
	end
end

gets.to_i.times do
	h, w, a, b = gets.split.map(&:to_i)
	if h * a == w * b
		puts 'YES'
		ans = Array.new(h) { %w[0] * w }
		(h / b).times do |i|
			(0...b).each do |y|
				(0...a).each { |x| ans[y + i * b][x + i * a] = '1' }
			end
		end
		puts ans.map(&:join).join("\n")
	else
		puts 'NO'
	end
end


Timur has $$$n$$$ candies. The $$$i$$$-th candy has a quantity of sugar equal to $$$a_i$$$. So, by eating the $$$i$$$-th candy, Timur consumes a quantity of sugar equal to $$$a_i$$$.Timur will ask you $$$q$$$ queries regarding his candies. For the $$$j$$$-th query you have to answer what is the minimum number of candies he needs to eat in order to reach a quantity of sugar greater than or equal to $$$x_j$$$ or print -1 if it's not possible to obtain such a quantity. In other words, you should print the minimum possible $$$k$$$ such that after eating $$$k$$$ candies, Timur consumes a quantity of sugar of at least $$$x_j$$$ or say that no possible $$$k$$$ exists.Note that he can't eat the same candy twice and queries are independent of each other (Timur can use the same candy in different queries).

The first line of input contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$)  — the number of test cases. The description of test cases follows. The first line contains $$$2$$$ integers $$$n$$$ and $$$q$$$ ($$$1 \leq n, q \leq 1.5\cdot10^5$$$) — the number of candies Timur has and the number of queries you have to print an answer for respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^4$$$) — the quantity of sugar in each of the candies respectively. Then $$$q$$$ lines follow.  Each of the next $$$q$$$ lines contains a single integer $$$x_j$$$ ($$$1 \leq x_j \leq 2 \cdot 10^9$$$) – the quantity Timur wants to reach for the given query. It is guaranteed that the sum of $$$n$$$ and the sum of $$$q$$$ over all test cases do not exceed $$$1.5 \cdot 10^5$$$.

For each test case output $$$q$$$ lines. For the $$$j$$$-th line output the number of candies Timur needs to eat in order to reach a quantity of sugar greater than or equal to $$$x_j$$$ or print -1 if it's not possible to obtain such a quantity.

NoteFor the first test case:For the first query, Timur can eat any candy, and he will reach the desired quantity.For the second query, Timur can reach a quantity of at least $$$10$$$ by eating the $$$7$$$-th and the $$$8$$$-th candies, thus consuming a quantity of sugar equal to $$$14$$$.For the third query, there is no possible answer.For the fourth query, Timur can reach a quantity of at least $$$14$$$ by eating the $$$7$$$-th and the $$$8$$$-th candies, thus consuming a quantity of sugar equal to $$$14$$$.For the second test case:For the only query of the second test case, we can choose the third candy from which Timur receives exactly $$$3$$$ sugar. It's also possible to obtain the same answer by choosing the fourth candy.

gets.to_i.times do
  n, q = gets.split.map(&:to_i)
  as = gets.split.map(&:to_i).sort.reverse
  sums = [0]
  as.each { |a| sums << sums.last + a }
  q.times do
    x = gets.to_i
    p sums.bsearch_index { |s| s >= x } || -1
  end
end

gets.to_i.times do
  n, q = gets.split.map(&:to_i)
  as = [0] + gets.split.map(&:to_i).sort_by { -_1 }
  (1...as.size).each { |i| as[i] += as[i - 1] }

  q.times do
    query = gets.to_i

    l = 0
    r = as.size
    while l + 1 < r
      m = (l + r) / 2
      if as[m] >= query
        r = m
      else
        l = m
      end
    end

    p -1 if r >  n
    p  r if r <= n
  end
end

def solve
  n, q = gli
  b = gli.sort.reverse
  (1...n).each { |i| b[i] += b[i - 1] }
  q.times do
    d = gi
    z = b.bsearch_index { |x| x >= d }
    if z
      puts z + 1
    else
      puts(-1)
    end
  end
end

MOD = 10**9 + 7
def gs = gets.chomp
def gi = gets.to_i
def gli = gets.split.map(&:to_i)
def cyesno(x) = x ? :Yes : :No
def uyesno(x) = x ? :YES : :NO

gets.to_i.times { solve }

main = -> {
  t = int
  t.times do
      n, q = ints
      a = ints
      a.sort!
      a.reverse!
      sum = [0]
      a.each do |x|
          sum << sum[-1] + x
      end
      q.times do
          x = int
          puts sum.bsearch_index { |s| s >= x } || -1
      end
  end
}

DEBUG = true
MOD = 10**9+7
$yesno = %w(No Yes)
YesNo = %w(No Yes)
YESNO = %w(NO YES)
INF = 10**18

require "set"
require "prime"

def int; gets.to_s.to_i end
def ints; gets.to_s.split.map { |s| s.to_i } end
def int1s; gets.to_s.split.map { |s| s.to_i - 1 } end
def float; gets.to_s.to_f end
def floats; gets.to_s.split.map { |s| s.to_f } end
def array_of(&convert); gets.to_s.split.map(&convert) end
def string; gets.to_s.chomp end
def strings; gets.to_s.split end
def rep(n, &b); Array.new(n, &b) end
def yes; puts $yesno[1] end
def no; puts $yesno[0] end
def yesno t; puts $yesno[t] end
def YesNo t; puts YesNo[t] end
def YESNO t; puts YESNO[t] end
def zip(xs, *yss); Enumerator.new { |y| xs.zip(*yss) { |a| y.yield(*a) } } end
def max(*xs, &block); block_given? ? xs.max_by(&block) : xs.max end
def min(*xs, &block); block_given? ? xs.min_by(&block) : xs.min end
def minmax(*xs, &block); block_given? ? xs.minmax_by(&block) : xs.minmax end
def gcd(*xs); xs.inject(0, :gcd) end
def matrix(h, w, fill=nil, &block); return Array.new(h) { Array.new(w, &block) } if block_given?; Array.new(h) { [fill] * w } end
def debug(x = nil); STDERR.puts (block_given? ? yield(x) : x).inspect if DEBUG; x end
def debug_grid(grid, width = 1); grid.each { |row| STDERR.puts row.map { |x| x.inspect.ljust(width) }.join("") } if DEBUG; grid end
def if_debug; yield if DEBUG end

module Boolean
  def coerce(other); [other, to_i] end
  def +@; to_i end
  def to_int; to_i end
  def *(other); to_i * other end
end

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

class Integer
  def div_ceil(y); (self + y - 1) / y end
  def mod_inv(mod = MOD); pow(mod-2, mod) end
  def mod_div(y, mod = MOD); self * y.mod_inv(mod) % mod end
  def mod_nCr(r, mod = MOD); x = y = 1; (1..r).each { |i| x = x * (self + 1 - i) % mod; y = y * i % mod }; x.mod_div(y, mod); end
  def factorial(mod = MOD); (2..self).inject(1) { |f, x| f * x % mod } end
  def popcount; x = self; c = 0; while x > 0; c += 1 if x & 1 == 1; x >>= 1 end; c end #TODO: faster
  def bitbrute(&block); (1<<self).times(&block) end
  def nCr(r); x = 1; (1..r).each { |i| x *= self + 1 - i; x /= i }; x; end
  def each_divisor; return Enumerator.new { |y| each_divisor { |k| y << k } } unless block_given?; k = 1; while k * k < self; if self % k == 0; yield k; yield self / k end; k += 1; end; yield k if k * k == self end
  def divisors; each_divisor.to_a end
end

class Range
  def end_open; exclude_end? ? self.end : self.end + 1 end
  def end_close; exclude_end? ? self.end - 1 : self.end end
  def upper_bound; ac, wa = self.begin, self.end_open; while wa - ac > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def lower_bound; ac, wa = self.end_open, self.begin; while ac - wa > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def shakutori(r2, &pred); Enumerator.new { |y| j, r = r2.begin, r2.end_open; each { |i| j += 1 while j + 1 < r and pred[i, j+1]; y.yield(i, j) } }; end
  def widest(&block); Enumerator.new { |y| j, n = self.begin, self.end_open; each { |i| j += 1 while j < n and block[i, j]; y.yield(i, j) if block[i, j] } } end
end

class Array
  def power(&block); (0 ... 1 << size).each(&block) end
  def sorted_merge(other); a = []; i = j = 0; n, m = size, other.size; if j < m and other[j] < self[i]; a << other[j]; j += 1 else; a << self[i]; i += 1 end while i < n; a.push(*other[j..-1]) if j < m; a end
  def upper_bound; ac, wa = 0, size; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def lower_bound; ac, wa = size, 0; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def cum(*xs, &op); a = []; a << xs[0] if xs.size > 0; a << x = self[0]; (1...size).each { |i| a << x = op[x, self[i]] }; a end
  def cumdiff(range); self[range.end_open] - self[range.begin]; end
  def compress(kinds = uniq.sort!); map { |x| kinds.bsearch_index { _1 >= x } }; end
end

module Enumerable
  def sorted_uniq; x = nil; filter { |y| c = x === y; x = y; !c } end
  def cumsum; ys = [0]; each { |x| ys << x + ys[-1] }; ys end
end

main[]


Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...$$$n$$$ friends live in a city which can be represented as a number line. The $$$i$$$-th friend lives in a house with an integer coordinate $$$x_i$$$. The $$$i$$$-th friend can come celebrate the New Year to the house with coordinate $$$x_i-1$$$, $$$x_i+1$$$ or stay at $$$x_i$$$. Each friend is allowed to move no more than once.For all friends $$$1 \le x_i \le n$$$ holds, however, they can come to houses with coordinates $$$0$$$ and $$$n+1$$$ (if their houses are at $$$1$$$ or $$$n$$$, respectively).For example, let the initial positions be $$$x = [1, 2, 4, 4]$$$. The final ones then can be $$$[1, 3, 3, 4]$$$, $$$[0, 2, 3, 3]$$$, $$$[2, 2, 5, 5]$$$, $$$[2, 1, 3, 5]$$$ and so on. The number of occupied houses is the number of distinct positions among the final ones.So all friends choose the moves they want to perform. After that the number of occupied houses is calculated. What is the minimum and the maximum number of occupied houses can there be?

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of friends. The second line contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le n$$$) — the coordinates of the houses of the friends.

Print two integers — the minimum and the maximum possible number of occupied houses after all moves are performed.

NoteIn the first example friends can go to $$$[2, 2, 3, 3]$$$. So friend $$$1$$$ goes to $$$x_1+1$$$, friend $$$2$$$ stays at his house $$$x_2$$$, friend $$$3$$$ goes to $$$x_3-1$$$ and friend $$$4$$$ goes to $$$x_4-1$$$. $$$[1, 1, 3, 3]$$$, $$$[2, 2, 3, 3]$$$ or $$$[2, 2, 4, 4]$$$ are also all valid options to obtain $$$2$$$ occupied houses.For the maximum number of occupied houses friends can go to $$$[1, 2, 3, 4]$$$ or to $$$[0, 2, 4, 5]$$$, for example.

#exec({'RUBY_THREAD_VM_STACK_SIZE'=>'100000000'},'/usr/bin/ruby', $0) if !ENV['RUBY_THREAD_VM_STACK_SIZE']

def inpf() a=gets.chomp.split(" ").map(&:to_f)end

def inps() a=gets.chomp.split(" ")end

def copy(a) Marshal.load(Marshal.dump(a)) end

def kaijo(n,r = 10**9+7)(n < 2)? 1 : (2..n).inject{|memo,u|memo=(memo*u)%r} end

def na(n,d=0) Array.new(n,d)end

def na2(n,m,d=0) Array.new(n){Array.new(m,d)}end

def na3(n,m,l,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end

def inp() a=gets.chomp.split(" ").map(&:to_i)end

def r_up(a, b) (a+b-1)/b end

def sum(a) a.inject(:+) end

def big(a,b) return (a>b)? a:b end

def small(a,b) return (a<b)? a:b end

n = inp[0]
t = inp.sort
min = 0
max = 0
h = {}
n.times do |i|
  if(h[t[i]-1])
  elsif(h[t[i]])
  elsif h[t[i]+1]
  else
    h[t[i]+1] = true
    min += 1
  end
end
h = {}
n.times do |i|
  if(!h[t[i]-1])
    h[t[i]-1] = true
    max += 1
  elsif(!h[t[i]])
    h[t[i]] = true
    max += 1
  elsif !h[t[i]+1]
    h[t[i]+1] = true
    max += 1
  end
end
puts "#{min} #{max}"