Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.

The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).

The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.

n = gets.chomp.to_i

ans = []
if n.even?
  ans = [2] * (n / 2)
else
  ans = [2] * (n / 2 - 1) + [3]
end
puts ans.length
puts ans.join(" ")

n = gets.to_i

if(n%2==0)
    puts n/2
    (n/2).times{print 2.to_s + " "}
else
    puts (n-1)/2
    ((n/2)-1).times{print 2.to_s + " "}
    print 3.to_s

end

n = gets.to_i
ans = n / 2
puts ans
if (n % 2 == 1)
    print 3, " "
    n -= 3
end

(0...n / 2).each do
    print 2, " "
end

n = gets.to_i
if n.even?
  k = n/2
  puts k
  puts ([2] * k).join(" ")
else
  k = 1
  n -= 3
  ps = [3]
  k += n/2
  ps << ([2] * (k-1))
  puts k
  puts ps.join(" ")
end

given_number = gets.chomp.to_i

k = given_number / 2

md = given_number % 2
ary = [2]
if md == 1
  ary *= k - 1
  ary << 3
else
  ary *= k
end

puts k
puts ary.join(' ')

n = gets.to_i
count3 = n%2
count2 = n/2 - count3
puts count2 + count3
(1..count2).each do
  print 2, ' '
end
print count3==1? 3 : ''

require 'prime'
require 'set'
a=["","","1\n2","1\n3","2\n2 2","2\n2 3"]
n=gets.to_i

if n<6 then
	puts a[n]
else
	if n%2==0 then
		puts n/2
		(n/2).times{|i|
			print " " if i>0
			print "2"
		}
		print "\n"
	else
		d=n-3
		puts d/2+1
		(d/2).times{|i|
			print " " if i>0
			print "2"
		}
		print " 3\n"
	end
end

n=gets.to_i
if n==3
    puts "1\n3"
elsif n.even?
    puts n/2
    puts ([2]*(n/2))*' '
else
    puts n/2
    puts (([2]*(n/2-1))<<3)*' '
end

# coding: utf-8

# if __FILE__ == $0
# end

n = gets.to_i # n >= 2 and n <= 100_000
was_odd = n.odd?
ans_len = 0
if was_odd
    ans_len += 1
    n -= 3
end

ans_len += n / 2

puts ans_len
if was_odd
    print "3 "
end
(n/2).times {
    print "2 "
}
puts ""

class Memo
  attr_reader(:i)
  def initialize(i, state)
    @i =i
    @state = state
  end

  def yes!
    @state = true
  end

  def no!
    @state = false
  end

  def yes?
    @state
  end

  def to_s
    "#{@i} => #{@state}"
  end
end
class Sieve
  attr_reader(:n)
  def initialize(n)
    @n = n
    @memo = Array.new(n + 100){|i| Memo.new(i, true)}
    @run = false
  end

  def run!
    return if @run
    @run = true
    @memo[0].yes!
    @memo[1].yes!
    @memo[2].yes!
    @memo.drop(2).each do |m|
      if(m.yes?)
        start = m.i * m.i
        start.step(@n + 1, m.i) do |i|
          @memo[i].no!
        end
      end
    end
  end

  def primes
    @primes ||= run!.select{|m| m.yes? }
  end

  def prime_values
    @prime_values ||= primes.map(&:i)
  end

  def get_data
    run!
    @memo
  end
end

def main
  g = gets.strip.to_i
  n = g / 2
  puts n
  if(g % 2 == 0)
    puts Array.new(n){ 2 }.join(" ")
  else
    x = Array.new(n - 1){ 2 }
    x << 3
    puts x.join(" ")
  end
end

main

n = gets.chomp.to_i

if n%2 == 0
	puts n/2
	print "2 " * (n/2)
else
	if n == 3
		puts 1
		print 3
	else
		puts n/2
		print "2 " * ((n/2)-1)
		print 3
	end
end

#!/usr/bin/env ruby
n=gets.chomp.to_i
if n&1==0 then
  puts "#{n/2}"
  (n/2).times do
    print "2 "
  end
else puts "#{n/2 }"
  print "3 "
  ((n/2)-1).times do
    print "2 "
  end
end

n = gets.to_i
if n % 2 == 0 then
	puts n / 2
	puts "2 " * (n / 2 - 1) + "2"
else
	puts n / 2
	puts "2 " * (n / 2 - 1) + "3"
end

n = gets.to_i

result = Array.new(n.div(2)-1, 2)
result << (n.even? ? 2 : 3)

puts result.size
puts result.join(' ')

k = gets.chomp.to_i
n = k / 2
out = ["2"] * n
if k.odd?
	out.pop
	out += ["3"]
end
puts out.size
puts out.join(" ")

number = gets.strip.to_i
even = false

even = true if number % 2 == 0

if even
  output = ''
  (number/2).times { output << '2 ' }
  puts number/2
  puts output.strip
else
  if number == 3
    puts 1
    puts number
  else
    balance = number - 3
    output = ''
    (balance/2).times { output << '2 ' }
    output << '3'
    puts(balance/2 + 1)
    puts output
  end
end

n = gets.to_i

if (n % 2 == 1)
    print 3, " "
    n -= 3
end

(0...n / 2).each do
    print 2, " "
end

given_number = gets.chomp.to_i

k = given_number / 2

md = given_number % 2
ary = [2]
if md == 1
  ary *= k - 1
  ary << 3
else
  ary *= k
end

puts ary.join(' ')

n = gets.to_i
count3 = n%2
count2 = n/2 - count3
(1..count2).each do
  print 2, ' '
end
print count3==1? 3 : ''

require 'prime'
require 'set'
a=["","","1\n2","1\n3","2\n2 2","2\n2 3"]
x=Prime.each(10**5).to_a
y=SortedSet.new(x)
n=gets.to_i

if n<6 then
	puts a[n]
elsif y.member?(n) then
	puts "1\n#{n}"
else
	ok=false
	x.size.times{|i|
		i.upto(x.size-1){|j|
			t=n-x[i]-x[j]
			break if t<x[j]

			if (t==0) || y.member?(t) then
				if t==0 then
					puts 2
					puts [x[i],x[j]]*" "
				else
					puts 3
					puts [x[i],x[j],t]*" "
				end
				ok=true
				break
			end
		}
		break if ok==true
	}
end

k = gets.chomp.to_i
n = k / 2
out = ["2"] * n
out += ["3"] if k.odd?
puts out.size
puts out.join(" ")


Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up — when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow, each represented by three lines. The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m \le n \le 10^5$$$) — the number of presents in the stack and the number of presents Santa wants to send, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le n$$$, all $$$a_i$$$ are unique) — the order of presents in the stack. The third line contains $$$m$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$ ($$$1 \le b_i \le n$$$, all $$$b_i$$$ are unique) — the ordered list of presents Santa has to send. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print one integer — the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.

def solve(presents, to_give)
  indexes = Array.new(presents.size)
  presents.each_with_index { |e, i| indexes[e] = i }

  p_idx = 0
  p = 0
  sum = 0
  to_give.each do |e|
    if indexes[e] <= p_idx
      sum += 1
      p += 1
    else
      sum += (indexes[e] - p) * 2 + 1
      p_idx = indexes[e]
      p += 1
    end
  end
  sum
end

# gets.strip.split(' ').map(&:to_i)
gets.strip.to_i.times do
  n, m = gets.strip.split(' ').map(&:to_i)
  presents = gets.strip.split(' ').map(&:to_i)
  to_give = gets.strip.split(' ').map(&:to_i)
  puts solve(presents, to_give)
end

def solve
    gets.strip
    n = gets.strip.split(' ').map(&:to_i)
    m = gets.strip.split(' ').map(&:to_i)
    pc = {}
    n.each_with_index { |e, i| pc[e] = i }
    sum = 0
    out = 0
    cur = -1
    m.each { |e|
        if pc[e] < cur
            sum += 1
        else
            cur = pc[e]
            sum += (2 * (cur - out) + 1)
        end
        out += 1
    }
    puts sum
end

gets.strip.to_i.times {
    solve
}


Let's consider the famous game called Boom (aka Hat) with simplified rules.There are n teams playing the game. Each team has two players. The purpose of the game is to explain the words to the teammate without using any words that contain the same root or that sound similarly. Player j from team i (1 ≤ i ≤ n, 1 ≤ j ≤ 2) is characterized by two numbers: aij and bij. The numbers correspondingly represent the skill of explaining and the skill of understanding this particular player has. Besides, m cards are used for the game. Each card has a word written on it. The card number k (1 ≤ k ≤ m) is characterized by number ck — the complexity of the word it contains.Before the game starts the cards are put in a deck and shuffled. Then the teams play in turns like that: the 1-st player of the 1-st team, the 1-st player of the 2-nd team, ... , the 1-st player of the n-th team, the 2-nd player of the 1-st team, ... , the 2-nd player of the n-th team, the 1-st player of the 1-st team and so on.Each turn continues for t seconds. It goes like that: Initially the time for each turn is t. While the time left to a player is more than 0, a player takes a card from the top of the deck and starts explaining the word it has to his teammate. The time needed for the j-th player of the i-th team to explain the word from the card k to his teammate (the q-th player of the i-th team) equals max(1, ck - (aij + biq) - dik) (if j = 1,  then q = 2,  else q = 1). The value dik is the number of seconds the i-th team has already spent explaining the word k during the previous turns. Initially, all dik equal 0. If a team manages to guess the word before the end of the turn, then the time given above is substracted from the duration of the turn, the card containing the guessed word leaves the game, the team wins one point and the game continues. If the team doesn't manage to guess the word, then the card is put at the bottom of the deck, dik increases on the amount of time of the turn, spent on explaining the word. Thus, when this team gets the very same word, they start explaining it not from the beginning, but from the point where they stopped. The game ends when words from all m cards are guessed correctly.You are given n teams and a deck of m cards. You should determine for each team, how many points it will have by the end of the game and which words the team will have guessed.

The first line contains two integers n, t (1 ≤ n, t ≤ 100), which correspondingly denote the number of teams and a turn's duration. Next n lines of the input file contain four integers each: ai1, bi1, ai2, bi2 (1 ≤ aij, bij ≤ 100) — the skills of the first and the second player of the i-th team. The teams are given in the order in which they play. The next line of the input file contains integer m (1 ≤ m ≤ 100) the number of cards. Next 2m lines contain the cards' descriptions. Two lines describe each card. The first line of the description contains the word that consists of no more than 20 characters. The words only contain small Latin letters. The second line of the description contains an integer ck (1 ≤ ck ≤ 100) — the complexity of the word written on the k-th card. The cards are listed in the order in which the lie in the deck from top to bottom. The words on all cards are different.

Print n lines. On the i-th line first print number si the number of points the i-th team wins. Then print si space-separated words — the words from the cards guessed by team i in the order in which they were guessed.

2 2
1 1 1 1
1 1 1 1
3
home
1
car
1
brother
1

2 4
1 2 2 1
2 3 2 2
4
armchair
3
quetzalcoatl
10
pilotage
5
defibrillator
7

2 armchair quetzalcoatl
2 pilotage defibrillator

a, b, n, t, words = nil
File.open("input.txt") do |f|
  n, t = f.gets.split.map(&:to_i)
  a = []*(2*n)
  b = []*(2*n)
  n.times do |i|
    a[i], b[i], a[i+n], b[i+n] = f.gets.split.map(&:to_i)
  end

  words = []
  f.gets.to_i.times do
    words << [f.gets.strip, f.gets.to_i]
  end
end

result = Array.new(n){[]}
du = Hash.new(0)
th = 0
tm = t
while !words.empty?
  w, c = words.shift
  d = du[[w, th%n]]

  reqt = [1, c-(a[th]+b[(th+n)%(2*n)])-d].max
  if reqt <= tm
    result[th%n] << w
    tm -= reqt
  else
    du[[w, th%n]] += tm
    tm = 0
    words << [w, c]
  end

  if tm == 0
    tm = t
    th = (th+1)%(2*n)

  end
end

File.open("output.txt", "w") do |f|
  result.each do |a|
    f.puts [a.size, a]*" "
  end
end

a, b, n, t, words = nil
File.open("input.txt") do |f|
  n, t = f.gets.split.map(&:to_i)
  a = []*(2*n)
  b = []*(2*n)
  n.times do |i|
    a[i], b[i], a[i+n], b[i+n] = f.gets.split.map(&:to_i)
  end

  words = []
  f.gets.to_i.times do
    words << [f.gets.strip, f.gets.to_i]
  end
end

result = Array.new(n){[]}
du = Hash.new(0)
th = 0
tm = t
while !words.empty?
  w, c = words.shift
  d = du[[w, th%n]]

  reqt = [1, c-(a[th]+b[th])-d].max
  if reqt <= tm
    result[th%n] << w
    tm -= reqt
  else
    du[[w, th%n]] += tm
    tm = 0
    words << [w, c]
  end

  if tm == 0
    tm = t
    th = (th+1)%(2*n)

  end
end

File.open("output.txt", "w") do |f|
  result.each do |a|
    f.puts [a.size, a]*" "
  end
end


You are given two arrays $$$a$$$ and $$$b$$$ of length $$$n$$$. Array $$$a$$$ contains each odd integer from $$$1$$$ to $$$2n$$$ in an arbitrary order, and array $$$b$$$ contains each even integer from $$$1$$$ to $$$2n$$$ in an arbitrary order.You can perform the following operation on those arrays:   choose one of the two arrays  pick an index $$$i$$$ from $$$1$$$ to $$$n-1$$$  swap the $$$i$$$-th and the $$$(i+1)$$$-th elements of the chosen array  Compute the minimum number of operations needed to make array $$$a$$$ lexicographically smaller than array $$$b$$$.For two different arrays $$$x$$$ and $$$y$$$ of the same length $$$n$$$, we say that $$$x$$$ is lexicographically smaller than $$$y$$$ if in the first position where $$$x$$$ and $$$y$$$ differ, the array $$$x$$$ has a smaller element than the corresponding element in $$$y$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the arrays. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2n$$$, all $$$a_i$$$ are odd and pairwise distinct) — array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 2n$$$, all $$$b_i$$$ are even and pairwise distinct) — array $$$b$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print one integer: the minimum number of operations needed to make array $$$a$$$ lexicographically smaller than array $$$b$$$. We can show that an answer always exists.

NoteIn the first example, the array $$$a$$$ is already lexicographically smaller than array $$$b$$$, so no operations are required.In the second example, we can swap $$$5$$$ and $$$3$$$ and then swap $$$2$$$ and $$$4$$$, which results in $$$[3, 5, 1]$$$ and $$$[4, 2, 6]$$$. Another correct way is to swap $$$3$$$ and $$$1$$$ and then swap $$$5$$$ and $$$1$$$, which results in $$$[1, 5, 3]$$$ and $$$[2, 4, 6]$$$. Yet another correct way is to swap $$$4$$$ and $$$6$$$ and then swap $$$2$$$ and $$$6$$$, which results in $$$[5, 3, 1]$$$ and $$$[6, 2, 4]$$$.

module AtCoder
  class FenwickTree
    def initialize(n = 0)
      @n = n
      @data = Array.new(n, 0).unshift(nil)
    end

    def add(idx, x)
      idx += 1
      while idx <= @n
        @data[idx] += x
        idx += idx & -idx
      end
      self
    end

    def sum(l, r)
      __sum__(r) - __sum__(l)
    end

    private

    def __sum__(r)
      s = 0
      while r > 0
        s += @data[r]
        r ^= r & -r
      end
      s
    end
  end
end

gets.to_i.times do

n = gets.to_i
a = gets.split.map!(&:to_i)
b = gets.split.map!(&:to_i)

ft = AtCoder::FenwickTree.new(n)
s = Array.new(n)
a.each_with_index do |ai, i|
  ai >>= 1
  s[ai] = i - ft.sum(0, ai)
  ft.add(ai, 1)
end
x = s[0]; s.map! { |si| x = (x < si) ? x : si }
t = b.map.with_index do |bj, j|
  bj >>= 1
  bj -= 1
  j + s[bj]
end

puts t.min

end

gets.to_i.times do
  n=gets.to_i
  a=gets.split.map(&:to_i).map{|x|x/2}
  b=gets.split.map(&:to_i).map{|x|x/2-1}
  l=[]
  i=0
  n.times do |j|
    while i<=b[j]
      l << j
      i+=1
    end
  end
  ans=2*n
  n.times do |j|
    if ans>j+l[a[j]]
      ans=j+l[a[j]]
    end
  end
  puts ans
end

module AtCoder
  class FenwickTree
    def initialize(n = 0)
      @n = n
      @data = Array.new(n, 0).unshift(nil)
    end

    def add(idx, x)
      idx += 1
      while idx <= @n
        @data[idx] += x
        idx += idx & -idx
      end
      self
    end

    def sum(l, r)
      __sum__(r) - __sum__(l)
    end

    private

    def __sum__(r)
      s = 0
      while r > 0
        s += @data[r]
        r ^= r & -r
      end
      s
    end
  end
end

gets.to_i.times do

n = gets.to_i
a = gets.split.map!(&:to_i)
b = gets.split.map!(&:to_i)

ft = AtCoder::FenwickTree.new(n)
s = Array.new(n)
a.each_with_index do |ai, i|
  ai >>= 1
  s[ai] = i - ft.sum(0, ai)
  ft.add(ai, 1)
end
t = b.map.with_index do |bj, j|
  bj >>= 1
  bj -= 1
  j + s[bj]
end

puts t.min

end

gets.to_i.times do

n = gets.to_i
a = gets.split.map!(&:to_i)
b = gets.split.map!(&:to_i)

b0 = b[0]
c = a.index { |ai| ai < b0 }

puts c

end


Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions:  She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her .  Let ui be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her . For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy.

The first line contains an integer n (1 ≤ n ≤ 105). The second line contains n integers: v1, v2, ..., vn (1 ≤ vi ≤ 109) — costs of the stones.  The third line contains an integer m (1 ≤ m ≤ 105) — the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r (1 ≤ l ≤ r ≤ n; 1 ≤ type ≤ 2), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one.

Print m lines. Each line must contain an integer — the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input.

NotePlease note that the answers to the questions may overflow 32-bit integer type.

n = gets
stone = gets.split.map(&:to_i)
sorted = stone.sort
for i in 1...stone.length
  stone[i] += stone[i-1]
  sorted[i] += sorted[i-1]
end
stone << 0
sorted << 0
q = gets.to_i
for i in 1..q
  a, b, c = gets.split.map(&:to_i)
  b -= 2
  c -= 1
  sum = 0
  if a == 1
    sum = stone[c]-stone[b]
  else
    sum = sorted[c]-sorted[b]
  end
  puts sum
end

n=gets
stone=gets.split.map &:to_i
sorted = stone.sort
for i in 1...stone.length
  stone[i] += stone[i-1]
  sorted[i] += sorted[i-1]
end
stone << 0
sorted << 0
q=gets.to_i
for i in 1..q
  a,b,c = gets.split.map &:to_i
  b-=2
  c-=1
  sum=0
  if a==1
    sum=stone[c]-stone[b]
  else
    sum=sorted[c]-sorted[b]
  end
  puts sum

end

# coding: utf-8

# if __FILE__ = $0
# end

# Kuriyama Mirai? <피림이: 이뭔씹...>

n = gets.to_i
v = gets.split.map(&:to_i) # stones
temp = 0
sv = [0] + v.map { |i|
    temp += i
    temp
}
ov = [0] + v.sort # ordered
temp = 0
ov = ov.map { |i|
    temp += i
    temp
}
#p sv
#p ov
questions = gets.to_i
questions.times {
    type, l, r = gets.split.map(&:to_i)
    if type == 1
        puts sv[r] - sv[l-1]
    else
        puts ov[r] - ov[l-1]
    end
}

def solution(costs, questions)
  sorted_costs = costs.sort
  prefix_sorted_costs, prefix_costs = [0], [0]
  for i in 0...costs.size do
    prefix_sorted_costs << prefix_sorted_costs.last + sorted_costs[i]
    prefix_costs << prefix_costs.last + costs[i]
  end

  questions.each do |question|
    if question[0] == 1
      puts prefix_costs[question[2]] - prefix_costs[question[1]-1]
    else
      puts prefix_sorted_costs[question[2]] - prefix_sorted_costs[question[1]-1]
    end
  end
end

_ = gets
costs = gets.split.map(&:to_i)
m = gets.to_i
questions = []
m.times do
  questions << gets.split.map(&:to_i)
end

solution(costs, questions)

n = gets.to_i
v = [0] + gets.split.collect{|i| i.to_i}
u = v.sort
(1..n).each do |i|
    v[i] += v[i-1]
    u[i] += u[i-1]
end
m = gets.to_i
(0...m).each do
    type, l, r = gets.split.collect{|i| i.to_i}
    if type == 1
        puts v[r]-v[l-1]
    else
        puts u[r]-u[l-1]
    end
end

# 433B

def read_line
  gets.chomp.split.map &:to_i
end

n = gets.to_i
a = read_line
b = a.sort
sums = [nil, Array.new(n), Array.new(n)]
sums[1][0] = a[0]
sums[2][0] = b[0]
(1...n).each do |i|
  sums[1][i] = sums[1][i - 1] + a[i]
  sums[2][i] = sums[2][i - 1] + b[i]
end
gets.to_i.times do
  type, l, r = read_line
  puts sums[type][r - 1] - (l > 1 ? sums[type][l - 2] : 0)
end

n = gets.to_i
v = [0] + gets.split.collect{|i| i.to_i}
u = v.sort
(1..n).each do |i|
	v[i] += v[i - 1]
	u[i] += u[i - 1]
end
m = gets.to_i
(0...m).each do
	t, left, right = gets.split.collect{|i| i.to_i}
	if 1 == t
		puts v[right]-v[left - 1]
	else
		puts u[right]-u[left - 1]
	end
end


Given an array $$$a$$$ of length $$$n$$$, tell us whether it has a non-empty subsequence such that the product of its elements is not a perfect square.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^4$$$) — the elements of the array $$$a$$$.

If there's a subsequence of $$$a$$$ whose product isn't a perfect square, print "YES". Otherwise, print "NO".

NoteIn the first example, the product of the whole array ($$$20$$$) isn't a perfect square.In the second example, all subsequences have a perfect square product.

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  a = gets.to_s.split.map {|x| x.to_i }
  imperfect = false
  a.each do |x|
    tmp = Integer.sqrt(x)
    if tmp * tmp != x
      imperfect = true
      break
    end
  end
  printf("%s\n", imperfect ? "YES" : "NO")
end


You are given the following concurrent program. There are N processes and the i-th process has the following pseudocode: repeat ni times    yi := y    y := yi + 1end repeatHere y is a shared variable. Everything else is local for the process. All actions on a given row are atomic, i.e. when the process starts executing a row it is never interrupted. Beyond that all interleavings are possible, i.e. every process that has yet work to do can be granted the rights to execute its next row. In the beginning y = 0. You will be given an integer W and ni, for i = 1, ... , N. Determine if it is possible that after all processes terminate, y = W, and if it is possible output an arbitrary schedule that will produce this final value.

In the first line of the input you will be given two space separated integers N (1 ≤ N ≤ 100) and W ( - 109 ≤ W ≤ 109). In the second line there are N space separated integers ni (1 ≤ ni ≤ 1000).

On the first line of the output write Yes if it is possible that at the end y = W, or No otherwise. If the answer is No then there is no second line, but if the answer is Yes, then on the second line output a space separated list of integers representing some schedule that leads to the desired result. For more information see note.

NoteFor simplicity, assume that there is no repeat statement in the code of the processes, but the code from the loop is written the correct amount of times. The processes are numbered starting from 1. The list of integers represent which process works on its next instruction at a given step. For example, consider the schedule 1 2 2 1 3. First process 1 executes its first instruction, then process 2 executes its first two instructions, after that process 1 executes its second instruction, and finally process 3 executes its first instruction. The list must consists of exactly 2·Σ i = 1...N ni numbers.

# solve for the case that a_min <= w <= sum(a_i)
def solve_normal_case(a, w)
  result = []
  w -= a[0][0]
  (1..a.size-1).each do |i|
    break if w == 0
    if w > a[i][0]
      (2 * a[i][0]).times {result.push(a[i][1])}
      w -= a[i][0]
      a[i][0] = 0
    else
      (2 * w).times {result.push(a[i][1])}
      a[i][0] -= w
      w = 0
    end
  end
  (2*a[0][0]-1).times {result.unshift(a[0][1])}
  (1..a.size-1).each do |i|
    (2*a[i][0]).times {result.unshift(a[i][1])}
  end
  result.unshift(a[0][1])
end

n, w = gets.split.map(&:to_i)
a = gets.split.map(&:to_i).map.with_index(1).to_a
a.sort_by!{|x, i| x}
sum = a.inject(0) {|s, item| s + item[0]}
if w <= 0 or w > sum
  puts "No"
  exit
end

result = []
if a[0][0] <= w and w <= sum
  result = solve_normal_case(a, w)
elsif w >= 2 and a.size >= 2
  suffix = []
  suffix.push(a[1][1])
  diff = a[0][0] - w + 1
  (2*diff).times {suffix.unshift(a[0][1])}
  suffix.unshift(a[1][1])
  a[0][0] -= diff
  a[1][0] -= 1
  prefix = solve_normal_case(a, w-1)
  result = prefix + suffix
else
  puts "No"
  exit
end

puts "Yes"
puts result.join(' ')

# solve for the case that a_min <= w <= sum(a_i)
def solve_normal_case(a, w)
  result = []
  w -= a[0][0]
  (1..a.size-1).each do |i|
    break if w == 0
    if w > a[i][0]
      (2 * a[i][0]).times {result.push(a[i][1])}
      w -= a[i][0]
      a[i][0] = 0
    else
      (2 * w).times {result.push(a[i][1])}
      a[i][0] -= w
      w = 0
    end
  end
  (2*a[0][0]-1).times {result.unshift(a[0][1])}
  (1..a.size-1).each do |i|
    (2*a[i][0]).times {result.unshift(a[i][1])}
  end
  result.unshift(a[0][1])
end

n, w = gets.split.map(&:to_i)
a = gets.split.map(&:to_i).map.with_index(1).to_a
a.sort_by{|x, i| x}
sum = a.inject(0) {|s, item| s + item[0]}
if w <= 0 or w > sum
  puts "No"
  exit
end

result = []
if a[0][0] <= w and w <= sum
  result = solve_normal_case(a, w)
elsif w >= 2 and a.size >= 2
  suffix = []
  suffix.push(a[1][1])
  diff = a[0][0] - w + 1
  (2*diff).times {suffix.unshift(a[0][1])}
  suffix.unshift(a[1][1])
  a[0][0] -= diff
  a[1][0] -= 1
  prefix = solve_normal_case(a, w-1)
  result = prefix + suffix
else
  puts "No"
  exit
end

puts "Yes"
puts result.join(' ')

# solve for the case that a_min <= w <= sum(a_i)
def solve_normal_case(a, w)
  result = []
  w -= a[0][0]
  (1..a.size-1).each do |i|
    break if w == 0
    if w > a[i][0]
      (2 * a[i][0]).times {result.push(a[i][1])}
      w -= a[i][0]
      a[i][0] = 0
    else
      (2 * w).times {result.push(a[i][1])}
      a[i][0] -= w
      w = 0
    end
  end
  (2*a[0][0]-1).times {result.unshift(a[0][1])}
  (1..a.size-1).each do |i|
    (2*a[i][0]).times {result.unshift(a[i][1])}
  end
  result.unshift(a[0][1])
end

n, w = gets.split.map(&:to_i)
a = gets.split.map(&:to_i).map.with_index(1).to_a
a.sort_by!{|x, i| x}
sum = a.inject(0) {|s, item| s + item[0]}
if w <= 0 or w > sum
  puts "No"
  exit
end

printf("a0=%d w=%d\n", a[0][0], w)
result = []
if a[0][0] <= w and w <= sum
  result = solve_normal_case(a, w)
elsif w >= 2 and a.size >= 2
  suffix = []
  suffix.push(a[1][1])
  diff = a[0][0] - w + 1
  (2*diff).times {suffix.unshift(a[0][1])}
  suffix.unshift(a[1][1])
  a[0][0] -= diff
  a[1][0] -= 1
  prefix = solve_normal_case(a, w-1)
  result = prefix + suffix
else
  puts "No"
  exit
end

puts "Yes"
puts result.join(' ')


Let's call a positive integer composite if it has at least one divisor other than $$$1$$$ and itself. For example:  the following numbers are composite: $$$1024$$$, $$$4$$$, $$$6$$$, $$$9$$$;  the following numbers are not composite: $$$13$$$, $$$1$$$, $$$2$$$, $$$3$$$, $$$37$$$. You are given a positive integer $$$n$$$. Find two composite integers $$$a,b$$$ such that $$$a-b=n$$$.It can be proven that solution always exists.

The input contains one integer $$$n$$$ ($$$1 \leq n \leq 10^7$$$): the given integer.

Print two composite integers $$$a,b$$$ ($$$2 \leq a, b \leq 10^9, a-b=n$$$). It can be proven, that solution always exists. If there are several possible solutions, you can print any.

n = gets.to_i

if n == 1
  puts "9 8"
else
  puts "#{n*2+n} #{n*2}"
end

n = gets.to_i

if n == 1
  puts "9 8"
else
  puts "#{n*n+n} #{n*n}"
end


Let's call an array good if there is an element in the array that equals to the sum of all other elements. For example, the array $$$a=[1, 3, 3, 7]$$$ is good because there is the element $$$a_4=7$$$ which equals to the sum $$$1 + 3 + 3$$$.You are given an array $$$a$$$ consisting of $$$n$$$ integers. Your task is to print all indices $$$j$$$ of this array such that after removing the $$$j$$$-th element from the array it will be good (let's call such indices nice).For example, if $$$a=[8, 3, 5, 2]$$$, the nice indices are $$$1$$$ and $$$4$$$:   if you remove $$$a_1$$$, the array will look like $$$[3, 5, 2]$$$ and it is good;  if you remove $$$a_4$$$, the array will look like $$$[8, 3, 5]$$$ and it is good. You have to consider all removals independently, i. e. remove the element, check if the resulting array is good, and return the element into the array.

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — elements of the array $$$a$$$.

In the first line print one integer $$$k$$$ — the number of indices $$$j$$$ of the array $$$a$$$ such that after removing the $$$j$$$-th element from the array it will be good (i.e. print the number of the nice indices). In the second line print $$$k$$$ distinct integers $$$j_1, j_2, \dots, j_k$$$ in any order — nice indices of the array $$$a$$$. If there are no such indices in the array $$$a$$$, just print $$$0$$$ in the first line and leave the second line empty or do not print it at all.

NoteIn the first example you can remove any element with the value $$$2$$$ so the array will look like $$$[5, 1, 2, 2]$$$. The sum of this array is $$$10$$$ and there is an element equals to the sum of remaining elements ($$$5 = 1 + 2 + 2$$$).In the second example you can remove $$$8$$$ so the array will look like $$$[3, 5, 2]$$$. The sum of this array is $$$10$$$ and there is an element equals to the sum of remaining elements ($$$5 = 3 + 2$$$). You can also remove $$$2$$$ so the array will look like $$$[8, 3, 5]$$$. The sum of this array is $$$16$$$ and there is an element equals to the sum of remaining elements ($$$8 = 3 + 5$$$).In the third example you cannot make the given array good by removing exactly one element.

n = gets.chomp.to_i

arr = gets.split(" ")

arr = arr.map { |element|  element.to_i }

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

sorted = arr.sort.reverse

answer = []

arr.each_with_index do |element,i|

	if element == sorted[0]
		mx = sorted[1]
	else
		mx = sorted[0]
	end
	answer<<(i+1) if sum - mx - element == mx

end

puts answer.length
puts answer.join(' ')

n = gets.strip.to_i
a = gets.strip.split.map(&:to_i)
sum = a.inject(:+)
sorted = a.sort.reverse
nice = []
a.each_with_index do |e, i|
  mx = e == sorted.first ? sorted[1] : sorted.first
  nice << (i + 1) if (sum - e) - mx == mx
end
puts nice.size
puts nice.join(' ')

n = gets.chomp.to_i

arr = gets.split(" ")
arr = arr.map { |element|  element.to_i }

sum = arr.inject(0){|sum,x| sum + x }
max = arr.max
nums = []

temp = arr.uniq
temp.each_with_index do |element,i|
	nums<<[sum-2*element,i]
end

nums.delete_if { |x| x[0] > max || x[0] < 1 }
nums = nums.uniq
answer = []

nums.each do |element|
	temp_arr = arr.each_index.select { |i| arr[i] == element[0] && i!=element[1] }.compact
	answer.concat(temp_arr)
end

answer = answer.uniq

puts answer.length
answer.each { |x| print (x+1).to_s+" "}

n = gets.chomp.to_i

arr = gets.split(" ")
arr = arr.map { |element|  element.to_i }
sum = arr.inject(0){|sum,x| sum + x }
max = arr.max
nums = []
arr.each do |element|
	nums<<sum-2*element
end

nums.delete_if { |x| x > max || x < 1 }
nums = nums.uniq
answer = []
nums.each do |element|
	temp_arr = arr.each_index.select { |i| arr[i] == element}.compact
	answer.concat(temp_arr)
end

answer = answer.uniq

puts answer.length
answer.each { |x| print (x+1).to_s+" "}


You've got a undirected tree s, consisting of n nodes. Your task is to build an optimal T-decomposition for it. Let's define a T-decomposition as follows.Let's denote the set of all nodes s as v. Let's consider an undirected tree t, whose nodes are some non-empty subsets of v, we'll call them xi . The tree t is a T-decomposition of s, if the following conditions holds:  the union of all xi equals v;  for any edge (a, b) of tree s exists the tree node t, containing both a and b;  if the nodes of the tree t xi and xj contain the node a of the tree s, then all nodes of the tree t, lying on the path from xi to xj also contain node a. So this condition is equivalent to the following: all nodes of the tree t, that contain node a of the tree s, form a connected subtree of tree t. There are obviously many distinct trees t, that are T-decompositions of the tree s. For example, a T-decomposition is a tree that consists of a single node, equal to set v.Let's define the cardinality of node xi as the number of nodes in tree s, containing in the node. Let's choose the node with the maximum cardinality in t. Let's assume that its cardinality equals w. Then the weight of T-decomposition t is value w. The optimal T-decomposition is the one with the minimum weight.Your task is to find the optimal T-decomposition of the given tree s that has the minimum number of nodes.

The first line contains a single integer n (2 ≤ n ≤ 105), that denotes the number of nodes in tree s. Each of the following n - 1 lines contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi), denoting that the nodes of tree s with indices ai and bi are connected by an edge. Consider the nodes of tree s indexed from 1 to n. It is guaranteed that s is a tree.

In the first line print a single integer m that denotes the number of nodes in the required T-decomposition. Then print m lines, containing descriptions of the T-decomposition nodes. In the i-th (1 ≤ i ≤ m) of them print the description of node xi of the T-decomposition. The description of each node xi should start from an integer ki, that represents the number of nodes of the initial tree s, that are contained in the node xi. Then you should print ki distinct space-separated integers — the numbers of nodes from s, contained in xi, in arbitrary order. Then print m - 1 lines, each consisting two integers pi, qi (1 ≤ pi, qi ≤ m; pi ≠ qi). The pair of integers pi, qi means there is an edge between nodes xpi and xqi of T-decomposition. The printed T-decomposition should be the optimal T-decomposition for the given tree s and have the minimum possible number of nodes among all optimal T-decompositions. If there are multiple optimal T-decompositions with the minimum number of nodes, print any of them.

n=gets.to_i
p n-1
c=[0]*100020
z=[]
1.upto(n-1){|i|
	x,y=gets.split.map &:to_i
	print "2 "+$_
	if c[x]==0
		c[x]=i
	else
		z<<[i,c[x]]*' '
	end
	if c[y]==0
		c[y]=i
	else
		z<<[i,c[y]]*' '
	end
}
puts z*"\n"


Cat Furrier Transform is a popular algorithm among cat programmers to create longcats. As one of the greatest cat programmers ever exist, Neko wants to utilize this algorithm to create the perfect longcat.Assume that we have a cat with a number $$$x$$$. A perfect longcat is a cat with a number equal $$$2^m - 1$$$ for some non-negative integer $$$m$$$. For example, the numbers $$$0$$$, $$$1$$$, $$$3$$$, $$$7$$$, $$$15$$$ and so on are suitable for the perfect longcats.In the Cat Furrier Transform, the following operations can be performed on $$$x$$$:  (Operation A): you select any non-negative integer $$$n$$$ and replace $$$x$$$ with $$$x \oplus (2^n - 1)$$$, with $$$\oplus$$$ being a bitwise XOR operator. (Operation B): replace $$$x$$$ with $$$x + 1$$$. The first applied operation must be of type A, the second of type B, the third of type A again, and so on. Formally, if we number operations from one in the order they are executed, then odd-numbered operations must be of type A and the even-numbered operations must be of type B.Neko wants to produce perfect longcats at industrial scale, thus for each cat Neko only wants to perform at most $$$40$$$ operations. Can you help Neko writing a transformation plan?Note that it is not required to minimize the number of operations. You just need to use no more than $$$40$$$ operations.

The only line contains a single integer $$$x$$$ ($$$1 \le x \le 10^6$$$).

The first line should contain a single integer $$$t$$$ ($$$0 \le t \le 40$$$) — the number of operations to apply. Then for each odd-numbered operation print the corresponding number $$$n_i$$$ in it. That is, print $$$\lceil \frac{t}{2} \rceil$$$ integers $$$n_i$$$ ($$$0 \le n_i \le 30$$$), denoting the replacement $$$x$$$ with $$$x \oplus (2^{n_i} - 1)$$$ in the corresponding step. If there are multiple possible answers, you can print any of them. It is possible to show, that there is at least one answer in the constraints of this problem.

NoteIn the first test, one of the transforms might be as follows: $$$39 \to 56 \to 57 \to 62 \to 63$$$. Or more precisely: Pick $$$n = 5$$$. $$$x$$$ is transformed into $$$39 \oplus 31$$$, or $$$56$$$.  Increase $$$x$$$ by $$$1$$$, changing its value to $$$57$$$.  Pick $$$n = 3$$$. $$$x$$$ is transformed into $$$57 \oplus 7$$$, or $$$62$$$.  Increase $$$x$$$ by $$$1$$$, changing its value to $$$63 = 2^6 - 1$$$. In the second and third test, the number already satisfies the goal requirement.

X = gets.to_i

def check(x)
  ans = []

  if x[0] == 0
    x += 1
    ans << 0
  end

  loop do
    flg = false
    l = x.to_s(2).size
    ml = 0

    (0...l).each do |i|
      if x[i] == 0
        ml = i + 1
        flg = true
      end
    end

    if flg
      mask = ('1' * ml).to_i(2)
      ans << ml

      x ^= mask
      x += 1
    else
      break
    end
  end

  ans
end

ans = check(X)

if ans.empty?
  puts 0
else
  puts ans.size * 2
  puts ans.join(' ')
end

def check(x,n,a,b)
    f = true
    for i in 0..n
        f = false if x[i] == 0
    end
    if f
        if b.empty?
            puts 0
        else
            puts a
            puts b.join(" ")
        end
        exit
    end
end

x = gets.to_i
a = 0
b = []
n = Math.log2(x).floor
while 1
    check(x,n,a,b)
    a += 1
    n.downto(0) do |i|
        if x[i] == 0
            x ^= ((1<<(i+1))-1)
            b << i+1
            check(x,n,a,b)
            break
        end
    end
    a += 1
    x += 1
    check(x,n,a,b)
end


Polycarp is writing the prototype of a graphic editor. He has already made up his mind that the basic image transformations in his editor will be: rotate the image 90 degrees clockwise, flip the image horizontally (symmetry relative to the vertical line, that is, the right part of the image moves to the left, and vice versa) and zooming on the image. He is sure that that there is a large number of transformations that can be expressed through these three.He has recently stopped implementing all three transformations for monochrome images. To test this feature, he asked you to write a code that will consecutively perform three actions with a monochrome image: first it will rotate the image 90 degrees clockwise, then it will flip the image horizontally and finally, it will zoom in twice on the image (that is, it will double all the linear sizes).Implement this feature to help Polycarp test his editor.

The first line contains two integers, w and h (1 ≤ w, h ≤ 100) — the width and height of an image in pixels. The picture is given in h lines, each line contains w characters — each character encodes the color of the corresponding pixel of the image. The line consists only of characters "." and "*", as the image is monochrome.

Print 2w lines, each containing 2h characters — the result of consecutive implementing of the three transformations, described above.

w,h = gets.strip.split(" ").map(&:to_i)

matrix = Array.new

h.times do |k|
    matrix[k] = gets.strip.split("")
end

matrix = matrix.transpose

(2*w).times do |i|
    m = (i/2.0).floor
    (2*h).times do |j|
        k = (j/2.0).floor
        print matrix[m][k]
    end
    print "\n"
end

(w, h) = gets.scan(/\d+/).map(&:to_i)
s = []
h.times do
  s << gets
end
w.times do |i|
  2.times do
    h.times do |j|
      print s[j][i], s[j][i]
    end
    print "\n"
  end
end

_, h = gets.split.map(&:to_i)
a = []
h.times do
  a << gets.chomp.split(//)
end
a = a.transpose.map { |x| x.zip(x).flatten }
puts a.zip(a).flatten(1).map(&:join)

a,b = gets.split.map{|x| x.to_i}
c = []
b.times do |x|
  c[x] = gets.chomp.split('')
end

for i in 0...2*a
  for j in 0...2*b
    print("#{c[j/2][i/2]}")
  end
  puts
end

# http://codeforces.ru/contest/523/problem/A

def img_to_s image
    image.map(&:join).join("\n")
end

initial = ARGF.read.split("\n")

image = initial[1..-1].map(&:chars)

# flip 90 degrees

image = image.transpose

# mirror

image = image.map { |i| i.map(&:reverse) }

# scaling

image = image.reduce([]) do |res, r|
    scaled = r.reduce([]) { |i_res, c| i_res << c; i_res << c; i_res }
    res << scaled
    res << scaled
end

puts img_to_s(image)

initial_num = ARGF.read

result = ''

initial_num.chars.each_with_index do |c, index|
	i = c.to_i
	if i >= 5
		if i == 9 and index == 0
			result << c
		else
			result << (9-i).to_s
		end
	else
		result << c
	end
end

puts result


Let's denote a function You are given an array a consisting of n integers. You have to calculate the sum of d(ai, aj) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n.

The first line contains one integer n (1 ≤ n ≤ 200000) — the number of elements in a. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — elements of the array.

Print one integer — the sum of d(ai, aj) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n.

NoteIn the first example:  d(a1, a2) = 0;  d(a1, a3) = 2;  d(a1, a4) = 0;  d(a1, a5) = 2;  d(a2, a3) = 0;  d(a2, a4) = 0;  d(a2, a5) = 0;  d(a3, a4) =  - 2;  d(a3, a5) = 0;  d(a4, a5) = 2.

#!/usr/bin/env ruby
# encoding: utf-8

n = gets.to_i
sum = 0
ans = 0
ary = gets.split.map(&:to_i)
hash = {}
ary.each do |v|
  sum += v
  hash[v] = hash[v].nil? ? 1 : hash[v] + 1
end
ary.each do |v|
  sum -= v
  n -= 1
  ans += (sum - n * v)
  hash[v] -= 1
  ans += hash[v - 1] unless hash[v - 1].nil?
  ans -= hash[v + 1] unless hash[v + 1].nil?
end
puts ans

# cook your code here

n = gets.to_i

nums = gets.split.map{ |x| x.to_i }

numap = Hash.new(0)
sum = 0

for i in 0...n
    sum += nums[i]
    numap[nums[i]] += 1
end

minsum=0
greatsum=0
=begin
for i in 0...n
    puts i
    #puts nums[i]
    puts numap[nums[i]]
end
=end
for i in 0...n
    sum -= nums[i]
    minsum = sum - (n-1-i)*nums[i] - numap[nums[i]+1] + numap[nums[i]-1]
    greatsum += minsum
    numap[nums[i]] -= 1
    # puts (i+1).to_s + " " + nums[i].to_s + " " + sum.to_s + " " + minsum.to_s + " " + greatsum.to_s
end

puts greatsum

N = gets.to_i
A = gets.split.map(&:to_i)

sum, ans = 0, 0
mp = Hash.new(0)
N.times do |i|
    res = sum
    num = i
    ((A[i]-1)..(A[i]+1)).each do |v|
        res -= v*mp[v]
        num -= mp[v]
    end
    ans += num*A[i] - res
    sum += A[i]
    mp[A[i]] += 1
end
puts ans

N = $stdin.gets.chomp.to_i
arr = $stdin.gets.chomp.split(" ").map{ |a| a.to_i }.reverse
nod = {}
#p arr

ans = 0
s = 0
arr.each_with_index do |a, i|
  ans += (s - (a*i)) - ((nod[a-1] || 0) * (a-1 - a) + (nod[a+1] || 0) * (a+1 - a))
  s += a
  nod[a] = (nod[a] || 0) + 1
end
puts ans

n, c, s, r = gets, Hash.new(0), 0, 0
gets.split.map(&:to_i).each_with_index {|a, i|
  r += a * i - s - c[a - 1] + c[a + 1]
  c[a] += 1
  s += a
}
p r


There is a string $$$s$$$ of length $$$3$$$, consisting of uppercase and lowercase English letters. Check if it is equal to "YES" (without quotes), where each letter can be in any case. For example, "yES", "Yes", "yes" are all allowable.

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of testcases. The description of each test consists of one line containing one string $$$s$$$ consisting of three characters. Each character of $$$s$$$ is either an uppercase or lowercase English letter.

For each test case, output "YES" (without quotes) if $$$s$$$ satisfies the condition, 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).

10

YES

yES

yes

Yes

YeS

Noo

orZ

yEz

Yas

XES

NoteThe first five test cases contain the strings "YES", "yES", "yes", "Yes", "YeS". All of these are equal to "YES", where each character is either uppercase or lowercase.

t = gets.to_i

t.times do
  ln = gets.chomp
  if ln.downcase == "yes"
    puts "YES"
  else
    puts "NO"
  end
end

gets.to_i.times { puts gets.chomp.upcase == "YES" ? "YES" : "NO" }

max_iterates = gets.to_i
result = []
for i in 1..max_iterates do
  val = gets.chomp.downcase == "yes" ? "YES" : "NO"
  result << val
end

result.each { |str| puts str }

#!/usr/bin/env ruby

numtests=gets.to_i
i=0
(1..numtests).each do |i|
  l=gets.chomp
  if !l.nil? && l.downcase == "yes"
    puts "YES"
  else
    puts "NO"
  end
end

n = gets.chomp.to_i
inputs = []
(0..n-1).each do |i|
  inputs.push(gets.chomp)
end
inputs.each do |i|
  if i.downcase == "yes"
    puts "YES"
  else
    puts "NO"
  end
end


An African crossword is a rectangular table n × m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.You are suggested to solve an African crossword and print the word encrypted there.

The first line contains two integers n and m (1 ≤ n, m ≤ 100). Next n lines contain m lowercase Latin letters each. That is the crossword grid.

Print the encrypted word on a single line. It is guaranteed that the answer consists of at least one letter.

n,m = gets.chomp.split(/ /).map!{|x| x.to_i}
bd = Array.new(n)
bdf = Array.new(n)
for i in 0..n-1
	bd[i] = gets.chomp.split(//)
	bdf[i] = Array.new(m)
end

for i in 0..n-1
	for j in 0..m-1
		bdf[i][j] = true
	end
end

for i in 0..n-1
	h = Hash.new
	for j in 0..m-1
		if h.key?(bd[i][j])
			h[bd[i][j]] += 1
		else
			h[bd[i][j]] = 1
		end
	end
	for j in 0..m-1
		bdf[i][j] = false if h[bd[i][j]] > 1
	end
end

for j in 0..m-1
	h = Hash.new
	for i in 0..n-1
		if h.key?(bd[i][j])
			h[bd[i][j]] += 1
		else
			h[bd[i][j]] = 1
		end
	end
	for i in 0..n-1
		bdf[i][j] = false if h[bd[i][j]] > 1
	end
end

for i in 0..n-1
	for j in 0..m-1
		print bd[i][j] if bdf[i][j] == true
	end
end

puts ""

def solve

    n , m = readline.split(' ')
    n = n.to_i; m = m.to_i

    s = Array.new; h = Hash.new(0)

    n.times {
        s << gets
    }

    s_ = s.dup

    (0...n).each{|x|
        s_[x] = s[x].dup
    }

    (0...n).each{|x|

        h.clear

        (0...m).each{|y|
            h[s[x][y]] += 1
        }

        (0...m).each{|y|
             s_[x][y] = '_' if (h[s[x][y]] > 1)
        }

    }

    (0...m).each{|y|

        h.clear

        (0...n).each{|x|
            h[s[x][y]] += 1
        }

        (0...n).each{|x|
             s_[x][y] = '_' if (h[s[x][y]] > 1)
        }

    }

    res = String.new

    (0...n).each{|x|
        (0...m).each{|y|
            res = res + s_[x][y].chr if (s_[x][y] != '_')
        }
    }

    return res

end

#$stdin = File.open("in.txt", "r")
puts solve

w=gets.to_i
m=[]
w.times{
    m.push(gets.split[0])
}
h=m[0].length
ans=""
w.times{|i|
    h.times{|j|
        ok=1
        w.times{|x|
            if i!=x && m[i][j]==m[x][j] then
                ok=0
                break
            end
        }
        h.times{|y|
            if j!=y && m[i][j]==m[i][y] then
                ok=0
                break
            end
        }
        if ok==1 then
            ans+=m[i][j]
        end
    }
}
puts ans

#!/usr/bin/env ruby
#$DEBUG = true
#$stdin = File.open '2.test' if $DEBUG
n, m = gets.split.map(&:to_i)
chars = [].tap{|chars| n.times{chars << gets.chomp.split("") } }
26.times { |c|
    c = (c+97).chr
    2.times {
        chars.each {|line|
            line.map!{|ci| ci == c ? "" : ci } if line.select{ |ci| ci == c || ci == "" }.size > 1
        }
        chars = chars.transpose
    }
    chars.each {|line| line.map!{|ci| ci == "" ? nil : ci } }
}
puts chars.flatten.compact.join

#=================================
# Better be sure than sorry.
#=================================
$stdin=File.open("./input.txt","r") if ENV["LOGNAME"]=="skydos"
require 'prime'
require 'mathn'
#=================================

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

board_main=[]
board_copy=[]
n.times{
	line = gets.strip.split(//)
	board_main << line
	board_copy << line.dup
}

for i in 0...n
	for j in 0...m
		ch = board_main[i][j]

		# rows
		count=0
		for row_index in 0...n
			count+=1 if board_main[row_index][j]==ch
		end

		if count!=1
			for row_index in 0...n
				board_copy[row_index][j]="" if board_main[row_index][j]==ch
			end
		end

		# cols
		count=0
		for col_index in 0...m
			count+=1 if board_main[i][col_index]==ch
		end

		if count!=1
			for col_index in 0...m
				board_copy[i][col_index]="" if board_main[i][col_index]==ch
			end
		end
	end
end

for i in 0...n
	for j in 0...m
		print board_copy[i][j]
	end
end

n, m = $stdin.readline.split(" ").collect { |i| i.to_i }
arr = []
for i in 0...n
	arr << $stdin.readline.chomp
end
tmph = Hash.new(0)
arr.each do |s|
	for i in 0...m
		s[i] = s[i].upcase if tmph[s[i]] > 1
		tmph[s[i].downcase] += 1
	end
	for i in 0...m
		s[i] = s[i].upcase if tmph[s[i]] > 1
	end
	tmph = Hash.new(0)
end
for i in 0...m
	arr.each do |s|
		s[i] = s[i].upcase if tmph[s[i].downcase] > 1
		tmph[s[i].downcase] += 1
	end
	arr.each do |s|
		s[i] = s[i].upcase if tmph[s[i].downcase] > 1
	end
	tmph = Hash.new(0)
end
arr.each do |s|
	for i in 0...m
		print s[i] if s[i] == s[i].downcase
	end
end
puts "\n"

n, m = gets.split.map(&:to_i)
R, C = [n, m].map { |i| Array.new(i) { Hash.new { |hash,key| hash[key] = 0 } } }
F = Array.new
(0...n).each do |r|
  t = gets.chomp
  (0...m).each do |c|
    R[r][t[c]] += 1
    C[c][t[c]] += 1
  end
  F << t
end
ret = ""
(0...n).each do |r|
  (0...m).each do |c|
    ret += F[r][c] if R[r][F[r][c]] + C[c][F[r][c]] <= 2
  end
end

puts ret

#Fuck U Codeforces :D
n,m=gets.split.map(&:to_i)
c=n.times.map{gets.chomp.bytes.to_a}
d=c.transpose
n.times{|i|m.times{|j|_=c[i][j];putc _ if c[i].count(_)<2&&d[j].count(_)<2}}
#Expected to be acc.
#YARAAAAAAB

def solve

    n , m = readline.split(' ')
    n = n.to_i; m = m.to_i

    s = Array.new; h = Hash.new

    n.times {
        s << gets
    }

    s_ = s.dup
=begin
    (0...n).each{|x|
        s_[x] = s[x].dup
    }

    (0...n).each{|x|

        h = Hash.new

        (0...m).each{|y|
            h[s[x][y].chr] += 1
        }

        (0...m).each{|y|
            s_[x][y] = 0 if (h[s[x][y].chr] > 1)
        }

    }

    (0...m).each{|y|

        h = Hash.new

        (0...n).each{|x|
            h[s[x][y].chr] += 1
        }

        (0...n).each{|x|
            s_[x][y] = 0 if (h[s[x][y].chr] > 1)
        }

    }
=end
    res = String.new

    (0...n).each{|x|
        (0...m).each{|y|
            res = res + s_[x][y].chr if (s_[x][y] != 0)
        }
    }

    return res

end

#$stdin = File.open("in.txt", "r")
puts solve

def solve

    n , m = readline.split(' ')
    n = n.to_i; m = m.to_i

    s = Array.new; h = Hash.new(0)

    n.times {
        s << gets
    }

    s_ = s.dup

    (0...n).each{|x|
        s_[x] = s[x].dup
    }

    (0...n).each{|x|

        h.clear

        (0...m).each{|y|
            h[s[x][y]] += 1
        }

        (0...m).each{|y|
            # s_[x][y] = 0 if (h[s[x][y]] > 1)
        }

    }

    (0...m).each{|y|

        h.clear

        (0...n).each{|x|
            h[s[x][y]] += 1
        }

        (0...n).each{|x|
            # s_[x][y] = 0 if (h[s[x][y]] > 1)
        }

    }

    res = String.new

    (0...n).each{|x|
        (0...m).each{|y|
            res = res + s_[x][y].chr if (s_[x][y] != 0)
        }
    }

    return res

end

#$stdin = File.open("in.txt", "r")
puts solve

def solve

    n , m = readline.split(' ')
    n = n.to_i; m = m.to_i

    s = Array.new; h = Hash.new(0)

    n.times {
        s << gets
    }

    s_ = s.dup

    (0...n).each{|x|
        s_[x] = s[x].dup
    }

    (0...n).each{|x|

        h.clear

        (0...m).each{|y|
            #        h[s[x][y].chr] += 1
        }

        (0...m).each{|y|
            # s_[x][y] = 0 if (h[s[x][y].chr] > 1)
        }

    }

    (0...m).each{|y|

        h.clear

        (0...n).each{|x|
            #      h[s[x][y].chr] += 1
        }

        (0...n).each{|x|
            #  s_[x][y] = 0 if (h[s[x][y].chr] > 1)
        }

    }

    res = String.new

    (0...n).each{|x|
        (0...m).each{|y|
            res = res + s_[x][y].chr if (s_[x][y] != 0)
        }
    }

    return res

end

#$stdin = File.open("in.txt", "r")
puts solve

def solve

    n , m = readline.split(' ')
    n = n.to_i; m = m.to_i

    s = Array.new; h = Hash.new

    n.times {
        s << gets
    }

    s_ = s.dup

    (0...n).each{|x|
        s_[x] = s[x].dup
    }

=begin
    (0...n).each{|x|

        h = Hash.new

        (0...m).each{|y|
            h[s[x][y].chr] += 1
        }

        (0...m).each{|y|
            s_[x][y] = 0 if (h[s[x][y].chr] > 1)
        }

    }

    (0...m).each{|y|

        h = Hash.new

        (0...n).each{|x|
            h[s[x][y].chr] += 1
        }

        (0...n).each{|x|
            s_[x][y] = 0 if (h[s[x][y].chr] > 1)
        }

    }
=end
    res = String.new

    (0...n).each{|x|
        (0...m).each{|y|
            res = res + s_[x][y].chr if (s_[x][y] != 0)
        }
    }

    return res

end

#$stdin = File.open("in.txt", "r")
puts solve

def solve

    a , b = readline.split(' ')
    a = a.to_i; b = b.to_i

    x = 0; sa = 0; sb = 0

    while true do
        t = a - x % a; w = b - x % b;
        break if (t == a && w == b && x > 0)

        if (t < w || t == w && a > b) then
            sa += t; x += t
            else
            sb += w; x += w;
        end
    end

        return 'Dasha' if (sa > sb)
        return 'Masha' if (sa < sb)
        return 'Equal'
    end

    #$stdin = File.open("in.txt", "r")
    puts solve

def solve

    n , m = readline.split(' ')
    n = n.to_i; m = m.to_i

    s = Array.new; h = Hash.new(0)

    n.times {
        s << gets
    }

    s_ = s.dup

    (0...n).each{|x|
        s_[x] = s[x].dup
    }

    (0...n).each{|x|

        h.clear

        (0...m).each{|y|
            #          h[(s[x][y].chr)] += 1
        }

        (0...m).each{|y|
             s_[x][y] = 0 if (h[s[x][y].chr] > 1)
        }

    }

    (0...m).each{|y|

        h.clear

        (0...n).each{|x|
            #  h[(s[x][y].chr)] += 1
        }

        (0...n).each{|x|
              s_[x][y] = 0 if (h[s[x][y].chr] > 1)
        }

    }

    res = String.new

    (0...n).each{|x|
        (0...m).each{|y|
            res = res + s_[x][y].chr if (s_[x][y] != 0)
        }
    }

    return res

end

#$stdin = File.open("in.txt", "r")
puts solve

#=================================
# Better be sure than sorry.
#=================================
$stdin=File.open("./input.txt","r") if ENV["LOGNAME"]=="skydos"
require 'prime'
require 'mathn'
#=================================

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

board_main=[]
board_copy=[]
n.times{
	line = gets.strip.split(//)
	board_main << line
	board_copy << line.dup
}

for i in 0...n
	for j in 0...m
		ch = board_main[i][j]

		# rows
		count=0
		for row_index in 0...n
			count+=1 if board_main[row_index][j]==ch
		end

		if count!=1
			for row_index in 0...n
				board_copy[row_index][j]="_" if board_main[row_index][j]==ch
			end
		end

		# cols
		count=0
		for col_index in 0...m
			count+=1 if board_main[i][col_index]==ch
		end

		if count!=1
			for col_index in 0...m
				board_copy[i][col_index]="_" if board_main[i][col_index]==ch
			end
		end
	end
end

for i in 0...n
	for j in 0...m
		print board_copy[i][j]
	end
	puts
end

n, m = $stdin.readline.split(" ").collect { |i| i.to_i }
arr = []
for i in 0...n
	arr << $stdin.readline.chomp
end
p arr
tmph = Hash.new(0)
arr.each do |s|
	for i in 0...m
		s[i] = s[i].upcase if tmph[s[i]] > 1
		tmph[s[i].downcase] += 1
	end
	for i in 0...m
		s[i] = s[i].upcase if tmph[s[i]] > 1
	end
	tmph = Hash.new(0)
end
for i in 0...m
	arr.each do |s|
		s[i] = s[i].upcase if tmph[s[i].downcase] > 1
		tmph[s[i].downcase] += 1
	end
	arr.each do |s|
		s[i] = s[i].upcase if tmph[s[i].downcase] > 1
	end
	tmph = Hash.new(0)
end
arr.each do |s|
	for i in 0...m
		print s[i] if s[i] == s[i].downcase
	end
end
puts "\n"


Let's call a number k-good if it contains all digits not exceeding k (0, ..., k). You've got a number k and an array a containing n numbers. Find out how many k-good numbers are in a (count each number every time it occurs in array a).

The first line contains integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ 9). The i-th of the following n lines contains integer ai without leading zeroes (1 ≤ ai ≤ 109).

Print a single integer — the number of k-good numbers in a.

#!/usr/bin/ruby
n,k=gets.split.map(&:to_i)
p n.times.count{
	a=gets.chomp.split('').map(&:to_i)
	(0..k).all?{|e|a.include?(e)}
}

n, k = STDIN.readline.split.map {|s| s.to_i }
count = 0
n.times do
	s = STDIN.readline.strip
	okay = true
	(0..k).each do |d|
		if s.index(d.to_s) == nil
			okay = false
			break
		end
	end
	count += 1 if okay
end
puts count

n, k = gets.split.map(&:to_i)
tot = 0
n.times do
  arr = gets.split(//)[0..-2].map(&:to_i).uniq.sort
  tot += 1 if arr.size > k && arr[0..k] == (0..k).to_a
end
puts tot

class A
  def initialize
    n, k = gets.chomp.split(' ').map(&:to_i)
    answer = 0

    n.times do
      check_list = Hash.new
      flag = true
      num = gets.chomp.split('').map(&:to_i).sort.uniq

      num.each do |val|
        check_list[val] = true if val <= k
      end

      answer += 1 if check_list.size == (k+1) && flag
    end

    puts answer
  end
end

a = A.new

ans=0
a=gets.chomp.split(" ")
inp=a[0].to_i
rng=a[1].to_i
inp.times do
a=gets.chomp
tempa=Hash.new(0)
a.each_char do |i|
tempa[i]+=1
end
trg=1
0.upto(rng) do |i|
if tempa["#{i}"]==0
trg=0
end
break if trg==0
end
if trg==1
ans+=1
end
end

puts "#{ans}"

t=0;n,k=gets.split.map &:to_i;p=(0..k).to_a;pl=p.length;n.times{m=gets.strip.split('').map &:to_i;t+=((p&m).length >= pl)?1:0};p t

n,k=gets.split.map &:to_i;p=(0..k).to_a.map &:to_s;p (((1..n).map{|i|((p&(gets.strip.split(''))).length >= p.length)?1:0}).count(1))

n,k=gets.split.map &:to_i;p=(0..k).to_a.map &:to_s;pl=p.length;p (((1..n).map{|i|((p&(gets.strip.split(''))).length >= pl)?1:0}).count(1))

n,k=gets.split.map &:to_i;p=(0..k).to_a.map &:to_s;q=p.length;p (((1..n).map{|i|((p&(gets.strip.split(''))).length >= q)?1:0}).count(1))

input = gets.chomp
nums = input.split
n = Integer(nums[0])
k = Integer(nums[1])
a =  Array.new
for i in 0...n
    input = gets.chomp
    a[i] = Array.new
    for j in 0...input.length
        a[i][j] = Integer(input[j])
    end
end

def good_number(x)
    x = x.sort
    y = Array.new
    y[0] = x[0]
    for i in 0...x.length - 1
        if x[i + 1] != x[i]
            y.push(x[i + 1])
        end
    end
    return y
end
ans = 0
for i in 0...n
    if good_number(a[i])[0] == 0
        if good_number(a[i]).length >= k + 1 && good_number(a[i])[k] == k
            ans += 1
        end
    end
end
puts ans

n, k = gets.chomp.split.map &:to_i
res = 0
n.times do
  s = gets.chomp
  # Check all digit in [0..k] appear in s
  t = true
  (0..k).to_a.each do |index|
    t = false and break if s.index((index + 48).chr).nil?
  end
  res += 1 if t
end
puts res

class A
  def initialize
    n, k = gets.chomp.split(' ').map(&:to_i)
    answer = 0

    n.times do
      check_list = Hash.new
      num = gets.chomp.split('').map(&:to_i)

      num.each do |val|
        check_list[val] = true
      end

      answer += 1 if check_list.size == (k+1)
    end

    puts answer
  end
end

a = A.new

class A
  def initialize
    n, k = gets.chomp.split(' ').map(&:to_i)
    answer = 0

    n.times do
      check_list = Hash.new
      flag = true
      num = gets.chomp.split('').map(&:to_i).sort.uniq

      num.each do |val|
        flag = false if val > k
        check_list[val] = true
      end

      answer += 1 if check_list.size == (k+1) && flag
    end

    puts answer
  end
end

a = A.new

class A
  def initialize
    n, k = gets.chomp.split(' ').map(&:to_i)
    answer = 0

    n.times do
      num = gets.chomp.split('').map(&:to_i)

      answer += 1 if k == num.count{|val| val < k }
    end

    puts answer
  end
end

a = A.new

class A
  def initialize
    n, k = gets.chomp.split(' ').map(&:to_i)
    answer = 0

    n.times do
      check_list = Hash.new
      flag = true
      num = gets.chomp.split('').map(&:to_i)

      num.each do |val|
        flag = false if val > k
        check_list[val] = true
      end

      answer += 1 if check_list.size == (k+1) && flag
    end

    puts answer
  end
end

a = A.new

class A
  def initialize
    n, k = gets.chomp.split(' ').map(&:to_i)
    answer = 0

    n.times do
      num = gets.chomp.split('').map(&:to_i)

      answer += 1 if num.all?{|val| val <= k }
    end

    puts answer
  end
end

a = A.new

t=0;n,k=gets.split.map &:to_i;n.times{px=(0..k).to_a.join;mx=gets.strip;t+=((mx.tr(px,'')=='' and px.tr(mx,'')=='')?1:0)};p t

t=0;n,k=gets.split.map &:to_i
n.times{
	px=(0..k).to_a.join
	mx=gets.strip
	t+=(mx.tr(px,'')=='' and px.tr(mx,'')=='')?1:0
}
p t

input = gets.chomp
nums = input.split
n = Integer(nums[0])
k = Integer(nums[1])
a =  Array.new
for i in 0...n
    input = gets.chomp
    a[i] = Array.new
    for j in 0...input.length
        a[i][j] = Integer(input[j])
    end
end

def good_number(x)
    x = x.sort
    y = Array.new
    y[0] = x[0]
    for i in 0...x.length - 1
        if x[i + 1] != x[i]
            y.push(x[i + 1])
        end
    end
    return y
end
ans = 0
for i in 0...n
    if (good_number(a[i])).length >= k + 1
        ans += 1
    end
end
puts ans

input = gets.chomp
nums = input.split
n = Integer(nums[0])
k = Integer(nums[1])
a =  Array.new
for i in 0...n
    input = gets.chomp
    a[i] = Array.new
    for j in 0...input.length
        a[i][j] = Integer(input[j])
    end
end

def good_number(x)
    x = x.sort
    y = Array.new
    y[0] = x[0]
    for i in 0...x.length - 1
        if x[i + 1] != x[i]
            y.push(x[i + 1])
        end
    end
    return y
end
ans = 0
for i in 0...n
    if (good_number(a[i])).length == k + 1
        ans += 1
    end
end
puts ans

input = gets.chomp
nums = input.split
n = Integer(nums[0])
k = Integer(nums[1])
a =  Array.new
for i in 0...n
    input = gets.chomp
    a[i] = Array.new
    for j in 0...input.length
        a[i][j] = Integer(input[j])
    end
end

def good_number(x)
    x = x.sort
    y = Array.new
    y[0] = x[0]
    for i in 0...x.length - 1
        if x[i + 1] != x[i]
            y.push(x[i + 1])
        end
    end
    return y
end
ans = 0
for i in 0...n
    if k != 0
        if (good_number(a[i])).length >= k + 1
            ans += 1
        end
    else
        if good_number(a[i])[0] == 0
            ans += 1
        end
    end
end
puts ans

input = gets.chomp
nums = input.split
n = Integer(nums[0])
k = Integer(nums[1])
a =  Array.new
for i in 0...n
    input = gets.chomp
    a[i] = Array.new
    for j in 0...input.length
        a[i][j] = Integer(input[j])
    end
end

def good_number(x)
    x = x.sort
    y = Array.new
    y[0] = x[0]
    for i in 0...x.length - 1
        if x[i + 1] != x[i]
            y.push(x[i + 1])
        end
    end
    return y
end
ans = 0
for i in 0...n
    if good_number(a[i])[0] == 0
        if good_number(a[i]).length >= k + 1
            ans += 1
        end
    end
end
puts ans


You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z'  'y'  'x'  'b'  'a'  'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'.What is the lexicographically minimum string that can be obtained from s by performing this shift exactly once?

The only line of the input contains the string s (1 ≤ |s| ≤ 100 000) consisting of lowercase English letters.

Print the lexicographically minimum string that can be obtained from s by shifting letters of exactly one non-empty substring.

NoteString s is lexicographically smaller than some other string t of the same length if there exists some 1 ≤ i ≤ |s|, such that s1 = t1, s2 = t2, ..., si - 1 = ti - 1, and si < ti.

class Array
  def r
    self.map { |q| q.to_i }
  end
end

def read_line
  STDIN.gets.split(" ")
end

def read_to_array
  read_line.to_a
end

def read_numbers_to_array
  read_to_array.r
end

s = read_to_array[0]
beg = false
ended = false
res = String.new
s.each_char do |c|
  if c == 'a'
    if beg
      beg = false
      ended = true
    end
  else
    if !ended
      beg = true
    end

    if beg
      c = c.ord - 1
    end
  end

  res << c
end

if beg == false && ended == false
  n = res[res.size - 1]
  res[res.size - 1] = 'z'
end

puts res

s=gets.chomp
n=s.size

i=s.index /[^a]/
unless i
    s[-1]=?z
    puts s
    exit
end

j=s.index(?a, i+1)||n

puts s[0, i]+s[i, j-i].tr!('b-z', 'a-y')+s[j, n-j]

class Array
  def r
    self.map { |q| q.to_i }
  end
end

def read_line
  STDIN.gets.split(" ")
end

def read_to_array
  read_line.to_a
end

def read_numbers_to_array
  read_to_array.r
end

s = read_to_array[0]
beg = false
ended = false
res = String.new
s.each_char do |c|
  if c == 'a'
    if beg
      beg = false
      ended = true
    end
  else
    if !ended
      beg = true
    end

    if beg
      c = (c.ord - 1)
    end
  end

  res << c
end

puts res

class Array
  def r
    self.map { |q| q.to_i }
  end
end

def read_line
  STDIN.gets.split(" ")
end

def read_to_array
  read_line.to_a
end

def read_numbers_to_array
  read_to_array.r
end

s = read_to_array[0]
beg = false
ended = false
res = String.new
s.each_char do |c|
  if c == 'a'
    if beg
      beg = false
      ended = true
    end
  else
    if !ended
      beg = true
    end

    if beg
      c = c.ord - 1
    end
  end

  res << c
end

if beg == false && ended == false
  n = res[res.size - 1]
  res[res.size - 1] = 'a'
end

puts res

s=gets.chomp
for i in 0..s.size-1
    next if s[i]==?a
    for j in i..s.size-1
        if s[j]!=?a
            s[j]=(s[j].ord-1).chr
        else
            break
        end
    end
    break
end
puts s


You are given an array $$$a_1, a_2, \dots, a_n$$$, consisting of $$$n$$$ positive integers. Initially you are standing at index $$$1$$$ and have a score equal to $$$a_1$$$. You can perform two kinds of moves:   move right — go from your current index $$$x$$$ to $$$x+1$$$ and add $$$a_{x+1}$$$ to your score. This move can only be performed if $$$x<n$$$.  move left — go from your current index $$$x$$$ to $$$x-1$$$ and add $$$a_{x-1}$$$ to your score. This move can only be performed if $$$x>1$$$. Also, you can't perform two or more moves to the left in a row. You want to perform exactly $$$k$$$ moves. Also, there should be no more than $$$z$$$ moves to the left among them.What is the maximum score you can achieve?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains three integers $$$n, k$$$ and $$$z$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le k \le n - 1$$$, $$$0 \le z \le min(5, k)$$$) — the number of elements in the array, the total number of moves you should perform and the maximum number of moves to the left you can perform. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^4$$$) — the given array. The sum of $$$n$$$ over all testcases does not exceed $$$3 \cdot 10^5$$$.

Print $$$t$$$ integers — for each testcase output the maximum score you can achieve if you make exactly $$$k$$$ moves in total, no more than $$$z$$$ of them are to the left and there are no two or more moves to the left in a row.

NoteIn the first testcase you are not allowed to move left at all. So you make four moves to the right and obtain the score $$$a_1 + a_2 + a_3 + a_4 + a_5$$$.In the second example you can move one time to the left. So we can follow these moves: right, right, left, right. The score will be $$$a_1 + a_2 + a_3 + a_2 + a_3$$$.In the third example you can move four times to the left but it's not optimal anyway, you can just move four times to the right and obtain the score $$$a_1 + a_2 + a_3 + a_4 + a_5$$$.

def read
    gets.split.map &:to_i
end
gets.to_i.times do
    n, k, z = read
    a = read
    res, s, mx = 0, 0, 0
    (0..k).each do |i|
        mx = [mx, a[i] + a[i + 1]].max if i < n - 1
        s += a[i]
        if i % 2 == k % 2
            cur = (k - i) / 2
            res = [res, s + cur * mx].max if cur <= z
        end
    end
    puts res
end


You finally woke up after this crazy dream and decided to walk around to clear your head. Outside you saw your house's fence — so plain and boring, that you'd like to repaint it.  You have a fence consisting of $$$n$$$ planks, where the $$$i$$$-th plank has the color $$$a_i$$$. You want to repaint the fence in such a way that the $$$i$$$-th plank has the color $$$b_i$$$.You've invited $$$m$$$ painters for this purpose. The $$$j$$$-th painter will arrive at the moment $$$j$$$ and will recolor exactly one plank to color $$$c_j$$$. For each painter you can choose which plank to recolor, but you can't turn them down, i. e. each painter has to color exactly one plank.Can you get the coloring $$$b$$$ you want? If it's possible, print for each painter which plank he must paint.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of planks in the fence and the number of painters. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the initial colors of the fence. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le n$$$) — the desired colors of the fence. The fourth line of each test case contains $$$m$$$ integers $$$c_1, c_2, \dots, c_m$$$ ($$$1 \le c_j \le n$$$) — the colors painters have. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$10^5$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$ over all test cases.

For each test case, output "NO" if it is impossible to achieve the coloring $$$b$$$. Otherwise, print "YES" and $$$m$$$ integers $$$x_1, x_2, \dots, x_m$$$, where $$$x_j$$$ is the index of plank the $$$j$$$-th painter should paint. You may print every letter in any case you want (so, for example, the strings "yEs", "yes", "Yes" and "YES" are all recognized as positive answer).

YES
1
YES
2 2
YES
1 1 1
YES
2 1 9 5 9
NO
NO

t = gets.chomp.to_i
t.times do
  n, m = gets.chomp.split(' ').map(&:to_i)
  arr = gets.chomp.split(' ').map(&:to_i)
  brr = gets.chomp.split(' ').map(&:to_i)
  crr = gets.chomp.split(' ').map(&:to_i)

  colors = Array.new(n + 1) {Array.new}
  missed = Array.new(n + 1) {Array.new}

  cur = arr.dup
  res = []

  n.times do |ind|
    if arr[ind] != brr[ind]
      missed[brr[ind]] << ind
    else
      colors[arr[ind]] << ind
    end
  end

  buff = []
  crr.each_with_index do |el, ind|
    # puts "Buff = #{buff}"
    # puts "res = #{res}"
    if missed[el].any?
      # puts "Iter1 = {#{[el, ind].to_s}}"
      t = missed[el].shift
      res << t + 1
      cur[t] = el
      if buff.any?
        buff.each do |i|
          res[i] = t + 1
        end
        buff = []
      end
      colors[el] << t
      next
    end
    if colors[el].any?
      # puts "Iter2 = {#{[el, ind].to_s}}"
      t = colors[el][0]
      res << t + 1
      cur[t] = el
      if buff.any?
        buff.each do |i|
          res[i] = t + 1
        end
        buff = []
      end
      next
    end
    # puts "Iter3 = {#{[el, ind].to_s}}"
    buff << ind
    res << -1
  end
  # puts "RES = #{res}"
  if buff.empty? && missed.all? {|el| el.empty?}
    puts "YES"
    puts res.join(' ')
  else
    puts "NO"
  end
end

def solve
  n, m = ints
  a = int1s
  b = int1s
  c = int1s
  colors = Array.new(n) { [] }
  has_color = [nil] * n

  b.each_with_index do |color, i|
    if a[i] != color
      colors[color] << i
    else
      has_color[color] = i
    end
  end

  painted = nil
  i = m-1
  plank = []
  c.reverse_each do |color|
    if not colors[color].empty?
      painted = colors[color].pop
    elsif painted
      painted = painted
    elsif has_color[color]
      painted = has_color[color]
    else
      no
      return
    end
    plank[i] = painted+1
    i -= 1
  end

  unless colors.all?(&:empty?)
    no
    return
  end

  yes
  puts plank * " "
end

def main
  t = int
  t.times do
    solve
  end
end

DEBUG = true
MOD = 10**9+7
YESNO = %w(NO YES)
INF = 10**9

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 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 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 * mod_inv(y, mod) % 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
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

t = gets.chomp.to_i
t.times do
  n, m = gets.chomp.split(' ').map(&:to_i)
  arr = gets.chomp.split(' ').map(&:to_i)
  brr = gets.chomp.split(' ').map(&:to_i)
  crr = gets.chomp.split(' ').map(&:to_i)

  colors = Array.new(n + 1) {Array.new}
  missed = Array.new(n + 1) {Array.new}

  cur = arr.dup
  res = []

  n.times do |ind|
    if arr[ind] != brr[ind]
      missed[brr[ind]] << ind
    else
      colors[arr[ind]] << ind
    end
  end

  buff = []
  crr.each_with_index do |el, ind|
    # puts "Buff = #{buff}"
    # puts "res = #{res}"
    if missed[el].any?
      # puts "Iter1 = {#{[el, ind].to_s}}"
      t = missed[el].shift
      res << t + 1
      cur[t] = el
      if buff.any?
        buff.each do |i|
          res[i] = t + 1
        end
        buff = []
      end
      colors[el] << t
      next
    end
    if colors[el].any?
      # puts "Iter2 = {#{[el, ind].to_s}}"
      t = colors[el][0]
      res << t + 1
      cur[t] = el
      if buff.any?
        buff.each do |i|
          res[i] = t + 1
        end
        buff = []
      end
      next
    end
    # puts "Iter3 = {#{[el, ind].to_s}}"
    buff << ind
    res << -1
  end
  # puts "RES = #{res}"
  if buff.empty?
    puts "YES"
    puts res.join(' ')
  else
    puts "NO"
  end
end

t = gets.chomp.to_i
t.times do
  n, m = gets.chomp.split(' ').map(&:to_i)
  arr = gets.chomp.split(' ').map(&:to_i)
  brr = gets.chomp.split(' ').map(&:to_i)
  crr = gets.chomp.split(' ').map(&:to_i)

  colors = Array.new(n + 1) {Array.new}
  missed = Array.new(n + 1) {Array.new}

  cur = arr.dup
  res = []

  n.times do |el|
    if arr[el] != brr[el]
      missed[brr[el]] << el
    else
      colors[arr[el]] << el
    end
  end

  buff = []
  crr.each_with_index do |el, ind|
    # puts "Buff = #{buff}"
    # puts "res = #{res}"
    if missed[el].any?
      # puts "Iter1 = {#{[el, ind].to_s}}"
      t = missed[el].shift
      res << t + 1
      cur[t] = el
      if buff.any?
        buff.each do |i|
          res[i] = t + 1
        end
        buff = []
      end
      next
    end
    if colors[el].any?
      # puts "Iter2 = {#{[el, ind].to_s}}"
      t = colors[el][0]
      res << t + 1
      cur[t] = el
      if buff.any?
        buff.each do |i|
          res[i] = t + 1
        end
        buff = []
      end
      next
    end
    # puts "Iter3 = {#{[el, ind].to_s}}"
    buff << ind
    res << -1
  end
  # puts "RES = #{res}"
  if buff.empty?
    puts "YES"
    puts res.join(' ')
  else
    puts "NO"
  end
end

t = gets.chomp.to_i
t.times do
  n, m = gets.chomp.split(' ').map(&:to_i)
  arr = gets.chomp.split(' ').map(&:to_i)
  brr = gets.chomp.split(' ').map(&:to_i)
  crr = gets.chomp.split(' ').map(&:to_i)

  colors = Array.new(n + 1) {Array.new}
  missed = Array.new(n + 1) {Array.new}

  cur = arr.dup
  res = []

  n.times do |el|
    if arr[el] != brr[el]
      missed[brr[el]] << el
    else
      colors[arr[el]] << el
    end
  end

  buff = []
  crr.each_with_index do |el, ind|
    if missed[el].any?
      t = missed[el].shift
      res << t + 1
      cur[t] = el
      if buff.any?
        i = buff.shift
        res[i] = t + 1
      end
      next
    end
    if colors[el].any?
      t = colors[el][0]
      res << t + 1
      cur[t] = el
      if buff.any?
        i = buff.shift
        res[i] = t + 1
      end
      next
    end
    buff << ind
    res << -1
  end
  if buff.empty?
    puts "YES"
    puts res.join(' ')
  else
    puts "NO"
  end
end


Kristina has two arrays $$$a$$$ and $$$b$$$, each containing $$$n$$$ non-negative integers. She can perform the following operation on array $$$a$$$ any number of times:   apply a decrement to each non-zero element of the array, that is, replace the value of each element $$$a_i$$$ such that $$$a_i > 0$$$ with the value $$$a_i - 1$$$ ($$$1 \le i \le n$$$). If $$$a_i$$$ was $$$0$$$, its value does not change. Determine whether Kristina can get an array $$$b$$$ from an array $$$a$$$ in some number of operations (probably zero). In other words, can she make $$$a_i = b_i$$$ after some number of operations for each $$$1 \le i \le n$$$?For example, let $$$n = 4$$$, $$$a = [3, 5, 4, 1]$$$ and $$$b = [1, 3, 2, 0]$$$. In this case, she can apply the operation twice:   after the first application of the operation she gets $$$a = [2, 4, 3, 0]$$$;  after the second use of the operation she gets $$$a = [1, 3, 2, 0]$$$. Thus, in two operations, she can get an array $$$b$$$ from an array $$$a$$$.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^4$$$). The second line of each test case contains exactly $$$n$$$ non-negative integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). The third line of each test case contains exactly $$$n$$$ non-negative integers $$$b_1, b_2, \dots, b_n$$$ ($$$0 \le b_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ values over all test cases in the test does not exceed $$$2 \cdot 10^5$$$.

For each test case, output on a separate line:   YES, if by doing some number of operations it is possible to get an array $$$b$$$ from an array $$$a$$$;  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 response).

NoteThe first test case is analyzed in the statement.In the second test case, it is enough to apply the operation to array $$$a$$$ once.In the third test case, it is impossible to get array $$$b$$$ from array $$$a$$$.

#require "prime"
#input of int(split by space)
def get_i()
    return gets.chomp.split(" ").map(&:to_i)
end
#input of float(split by space)
def get_f()
    return gets.chomp.split(" ").map(&:to_f)
end
#input of string(split by space)
def get()
    return gets.chomp.split(" ")
end
#input of string(split per one character)
def get_nsp()
    return gets.chomp.split("")
end
#yes or no decision
def yn_judge(bool,y="Yes",n="No")
    return bool ? y : n
end
#output grid(two dimensional array)
def puts_grid(grid,join_char="")
    grid.each do|line|
        puts line.join(join_char)
    end
end

Dirxy4=[[1,0],[-1,0],[0,1],[0,-1]]
Dirxy8=[[1,0],[1,-1],[1,1],[0,-1],[0,1],[-1,0],[-1,-1],[-1,1]]

INF=Float::INFINITY

#MOD=998_244_353
MOD=10**9+7
T=gets.to_i
T.times do
    n=gets.to_i
    a=get_i
    b=get_i
    f=true
    diff=-1
    n.times do |i|
        if b[i].zero?
            next
        end
        if a[i]-b[i]>=0
            diff=a[i]-b[i]
            break
        else
            f=false
            break
        end
    end
    if diff==-1
        puts yn_judge(f,"YES","NO")
    else
        n.times do |i|
            if b[i].zero?
                unless diff>=a[i]
                    f=false
                    break
                end
            else
                unless diff==a[i]-b[i]
                    f=false
                    break
                end
            end
        end
        puts yn_judge(f,"YES","NO")
    end
end

t = gets.to_i

t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  b = gets.split.map(&:to_i)

  s = -1
  n.times do |i|
    s = [s, a[i]-b[i]].max
  end

  ok = true
  n.times do |i|
    ai, bi = a[i], b[i]
    break ok = false if ai < bi

    k = ai - bi
    if bi == 0
      break ok = false if k > s
    else
      break ok = false if k != s
    end
  end

  puts ok ? "YES" : "NO"
end

t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  a = gets.chomp.split.map(&:to_i)
  b = gets.chomp.split.map(&:to_i)
  r = [0, 2000000000]
  n.times do |i|
    if b[i] > a[i]
      r = [1,0]
      break
    elsif b[i] == 0 # a[i]..
      r = [
        [a[i], r[0]].max,
        [2000000000, r[1]].min
      ]
    else # a[i] - b[i], a[i]-b[i]
      r = [
        [a[i]-b[i], r[0]].max,
        [a[i]-b[i], r[1]].min
      ]
    end
  end
  if r[0] <= r[1]
    puts 'YES'
  else
    puts 'NO'
  end
end

#require "prime"
#input of int(split by space)
def get_i()
    return gets.chomp.split(" ").map(&:to_i)
end
#input of float(split by space)
def get_f()
    return gets.chomp.split(" ").map(&:to_f)
end
#input of string(split by space)
def get()
    return gets.chomp.split(" ")
end
#input of string(split per one character)
def get_nsp()
    return gets.chomp.split("")
end
#yes or no decision
def yn_judge(bool,y="Yes",n="No")
    return bool ? y : n
end
#output grid(two dimensional array)
def puts_grid(grid,join_char="")
    grid.each do|line|
        puts line.join(join_char)
    end
end

Dirxy4=[[1,0],[-1,0],[0,1],[0,-1]]
Dirxy8=[[1,0],[1,-1],[1,1],[0,-1],[0,1],[-1,0],[-1,-1],[-1,1]]

INF=Float::INFINITY

#MOD=998_244_353
MOD=10**9+7
T=gets.to_i
T.times do
    n=gets.to_i
    a=get_i
    b=get_i
    if n==1
        if a[0]>=b[0] or b[0].zero?
            puts "YES"
        else
            puts "NO"
        end
        next
    end
    f=true
    (n-1).times do |i|
        if b[i].zero?
            next
        end
        if b[i+1].zero?
            unless a[i]-b[i]>=a[i+1]-b[i+1]
                f=false
                break
            end
        else
            unless a[i]-b[i]==a[i+1]-b[i+1]
                f=false
                break
            end
        end
    end
    puts yn_judge(f,"YES","NO")
end

#require "prime"
#input of int(split by space)
def get_i()
    return gets.chomp.split(" ").map(&:to_i)
end
#input of float(split by space)
def get_f()
    return gets.chomp.split(" ").map(&:to_f)
end
#input of string(split by space)
def get()
    return gets.chomp.split(" ")
end
#input of string(split per one character)
def get_nsp()
    return gets.chomp.split("")
end
#yes or no decision
def yn_judge(bool,y="Yes",n="No")
    return bool ? y : n
end
#output grid(two dimensional array)
def puts_grid(grid,join_char="")
    grid.each do|line|
        puts line.join(join_char)
    end
end

Dirxy4=[[1,0],[-1,0],[0,1],[0,-1]]
Dirxy8=[[1,0],[1,-1],[1,1],[0,-1],[0,1],[-1,0],[-1,-1],[-1,1]]

INF=Float::INFINITY

#MOD=998_244_353
MOD=10**9+7
T=gets.to_i
T.times do
    n=gets.to_i
    a=get_i
    b=get_i
    f=true
    (n-1).times do |i|
        if b[i].zero?
            next
        end
        if b[i+1].zero?
            unless a[i]-b[i]>=a[i+1]-b[i+1]
                f=false
                break
            end
        else
            unless a[i]-b[i]==a[i+1]-b[i+1]
                f=false
                break
            end
        end
    end
    puts yn_judge(f,"YES","NO")
end

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  b = gets.split.map(&:to_i)

  pair = []
  n.times do |i|
    pair << [a[i], b[i]]
  end

  pair.sort_by!{|e| [-e[0], -e[1]]}

  ok = true
  s = a[0]-b[0]
  n.times do |i|
    ai, bi = pair[i]
    if ai < bi
      ok = false
      break
    end

    if bi == 0
      k = ai - bi
      if k > s
        ok = false
        break
      end
    else
      k = ai - bi
      if k != s
        ok = false
        break
      end
    end
  end

  puts ok ? "YES" : "NO"
end


Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that aj < ai.A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.

The first line contains an integer n (1 ≤ n ≤ 105) — the number of cards Conan has.  The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number on the i-th card.

If Conan wins, print "Conan" (without quotes), otherwise print "Agasa" (without quotes).

NoteIn the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn.In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again.

gets
c=0
h=Hash.new 0
gets.split.each{|e|h[e]=d=h[e]+1;c+=d%2*2-1}
puts c>0 ? :Conan : :Agasa

n = gets.to_i
a = gets.split.map(&:to_i)
a.sort!
k = a.pop
flag = false # Conan wins
while !flag && k
  cnt = 1
  while k == (l = a.pop)
    cnt += 1
  end
  flag = cnt % 2 != 0
  k = l
end
puts flag ? "Conan" : "Agasa"

n = gets.to_i
a = gets.split.map(&:to_i).sort.reverse

oddcnt = a.group_by{|x| x}.map{|k,v| v.size}.select{|t|t%2==1}.size

puts (oddcnt>0)? 'Conan' : 'Agasa'

n = gets.to_i
a = gets.split.map(&:to_i)
a.sort!
k = a[-1]
flag = false # Conan wins
while !flag && k
  cnt = 0
  while k == (l = a.pop)
    cnt += 1
  end
  flag = cnt % 2 != 0
  k = l
end
puts flag ? "Conan" : "Agasa"

n = gets.to_i
a = gets.split.map(&:to_i)
a.sort!
k = a.pop
while k && (a.count(k) % 2 == 1)
  a.delete(k)
  k = a.pop
end
puts a.length == 0 ? "Agasa" : "Conan"


Xenia has a set of weights and pan scales. Each weight has an integer weight from 1 to 10 kilos. Xenia is going to play with scales and weights a little. For this, she puts weights on the scalepans, one by one. The first weight goes on the left scalepan, the second weight goes on the right scalepan, the third one goes on the left scalepan, the fourth one goes on the right scalepan and so on. Xenia wants to put the total of m weights on the scalepans.Simply putting weights on the scales is not interesting, so Xenia has set some rules. First, she does not put on the scales two consecutive weights of the same weight. That is, the weight that goes i-th should be different from the (i + 1)-th weight for any i (1 ≤ i < m). Second, every time Xenia puts a weight on some scalepan, she wants this scalepan to outweigh the other one. That is, the sum of the weights on the corresponding scalepan must be strictly greater than the sum on the other pan.You are given all types of weights available for Xenia. You can assume that the girl has an infinite number of weights of each specified type. Your task is to help Xenia lay m weights on the scales or to say that it can't be done.

The first line contains a string consisting of exactly ten zeroes and ones: the i-th (i ≥ 1) character in the line equals "1" if Xenia has i kilo weights, otherwise the character equals "0". The second line contains integer m (1 ≤ m ≤ 1000).

In the first line print "YES", if there is a way to put m weights on the scales by all rules. Otherwise, print in the first line "NO". If you can put m weights on the scales, then print in the next line m integers — the weights' weights in the order you put them on the scales. If there are multiple solutions, you can print any of them.

@s = '0'+gets.strip
@m = gets.to_i
@calced = []
@f = []
for i in 0..10 do
  @calced[i]=[]
  @f[i]=[]
  for j in 0..@m do
    @calced[i][j]=[]
    @f[i][j] = []
  end
end

def dp(delta,step,last)
  if !@calced[delta][step][last]
    @calced[delta][step][last]=true
    @f[delta][step][last]=false
    if step==@m
      @f[delta][step][last]=true
    else
      for i in delta+1..10 do
        if i!=last && @s[i]=='1' && dp(i-delta,step+1,i)
          @f[delta][step][last]=true
          break
        end
      end
    end
  end
  return @f[delta][step][last]
end

def show(delta,step,last)
  if step==@m
    puts last
  else
    if step==0
      puts 'YES'
    else
      print last,' '
    end
    for i in delta+1..10 do
      if i!=last && @s[i]=='1' && dp(i-delta,step+1,i)
        show(i-delta,step+1,i)
        break
      end
    end
  end
end

if !dp(0,0,0)
  puts 'NO'
else
  show(0,0,0)
end

#!/usr/bin/ruby1.9

s = STDIN.readline.strip
m = STDIN.readline.to_i
weights = []
10.times do |pos|
	if s[pos] == '1'
		weights.push(pos+1)
	end
end

def solve(solution, weights, left, right, ix, max, previous)
	return true if ix == max
	weights.each do |weight|
		next if weight == previous
		next if left+weight <= right
		solution.push(weight)
		if solve(solution, weights, right, left+weight, ix+1, max, weight)
			return true
		end
		solution.pop
	end
	return false
end

solution = []
if solve(solution, weights, 0, 0, 0, m, -1)
	puts 'YES'
	puts solution.join(' ')
else
	puts 'NO'
end

#!/usr/bin/ruby1.9

s = STDIN.readline.strip
m = STDIN.readline.to_i
weights = []
10.times do |pos|
	if s[pos] == '1'
		weights.push(pos+1)
	end
end

def solve(solution, weights, left, right, ix, max, previous)
	return true if ix == max
	weights.each do |weight|
		next if weight == previous
		next if left+weight <= right
		solution.push(weight)
		return true if solve(solution, weights, right, left, ix+1, max, weight)
		solution.pop
	end
	return false
end

solution = []
if solve(solution, weights, 0, 0, 0, m, -1)
	puts 'YES'
	puts solution.join(' ')
else
	puts 'NO'
end