You're given an array $$$a$$$ of length $$$n$$$. You can perform the following operations on it:  choose an index $$$i$$$ $$$(1 \le i \le n)$$$, an integer $$$x$$$ $$$(0 \le x \le 10^6)$$$, and replace $$$a_j$$$ with $$$a_j+x$$$ for all $$$(1 \le j \le i)$$$, which means add $$$x$$$ to all the elements in the prefix ending at $$$i$$$.  choose an index $$$i$$$ $$$(1 \le i \le n)$$$, an integer $$$x$$$ $$$(1 \le x \le 10^6)$$$, and replace $$$a_j$$$ with $$$a_j \% x$$$ for all $$$(1 \le j \le i)$$$, which means replace every element in the prefix ending at $$$i$$$ with the remainder after dividing it by $$$x$$$. Can you make the array strictly increasing in no more than $$$n+1$$$ operations?

The first line contains an integer $$$n$$$ $$$(1 \le n \le 2000)$$$, the number of elements in the array $$$a$$$. The second line contains $$$n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\dots$$$, $$$a_n$$$ $$$(0 \le a_i \le 10^5)$$$, the elements of the array $$$a$$$.

On the first line, print the number of operations you wish to perform. On the next lines, you should print the operations. To print an adding operation, use the format "$$$1$$$ $$$i$$$ $$$x$$$"; to print a modding operation, use the format "$$$2$$$ $$$i$$$ $$$x$$$". If $$$i$$$ or $$$x$$$ don't satisfy the limitations above, or you use more than $$$n+1$$$ operations, you'll get wrong answer verdict.

NoteIn the first sample, the array is already increasing so we don't need any operations.In the second sample:In the first step: the array becomes $$$[8,6,3]$$$.In the second step: the array becomes $$$[0,2,3]$$$.

n = gets.to_i
ary = gets.strip.split.map(&:to_i)
# tmp = ary.dup

sum = 0
ops = []
mod = 2100 # 500000

(n-1).downto(0).each do |i|
  v = ary[i]+sum
  v %= mod
  target = mod - (n-i)
  # puts "target:#{target}, v:#{v}"
  next if v == target
  xs = 0
  if target > v
    xs = target-v
  elsif target < v
    xs = mod+target-v
  end
  ops << "1 #{i+1} #{xs}"
  sum += xs
end
ops << "2 #{n} #{mod}"
puts ops.size
puts ops.join("\n")

n = gets.to_i
arr = gets.chomp.split(" ").map(&:to_i)

puts n+1

def getdiff(elem,n,modn)
  k = elem/n
  req = k*n + modn
  if req<elem
    req += n
  end

  return req-elem
end

i = n-1
while(i>=0)
  toadd = getdiff(arr[i],n,i)
  j = 0
  while(j<=i)
    arr[j]+= toadd
    j = j+1
  end
  puts "1 #{i+1} #{toadd}"
  i = i-1
end

puts "2 #{n} #{n}"

=begin
(0..n-1).each do |i|
   arr[i] = arr[i]%n
end
p arr
=end

n = gets.to_i
ary = gets.strip.split.map(&:to_i)
# tmp = ary.dup

sum = 0
ops = []
mod = 2100 # 500000

(n-1).downto(0).each do |i|
  v = ary[i]+sum
  v %= mod
  target = mod - (n-i)
  # puts "target:#{target}, v:#{v}"
  next if v == target
  xs = 0
  if target > v
    xs = target-v
  elsif target < v
    xs = mod+target-v
  end
  ops << "1 #{i+1} #{xs}"
  sum += xs
end
ops << "2 #{n} #{mod}"
puts ops.join("\n")

n = gets.to_i
ary = gets.strip.split.map(&:to_i)
# tmp = ary.dup

sum = 0
ops = []
mod = 500000

(n-1).downto(0).each do |i|
  v = ary[i]+sum
  v %= mod
  target = mod - (n-i)
  # puts "target:#{target}, v:#{v}"
  next if v == target
  xs = 0
  if target > v
    xs = target-v
  elsif target < v
    xs = mod+target-v
  end
  ops << "1 #{i+1} #{xs}"
  sum += xs
end
ops << "2 #{n} #{mod}"
puts ops.join("\n")


Bob programmed a robot to navigate through a 2d maze.The maze has some obstacles. Empty cells are denoted by the character '.', where obstacles are denoted by '#'.There is a single robot in the maze. Its start position is denoted with the character 'S'. This position has no obstacle in it. There is also a single exit in the maze. Its position is denoted with the character 'E'. This position has no obstacle in it.The robot can only move up, left, right, or down.When Bob programmed the robot, he wrote down a string of digits consisting of the digits 0 to 3, inclusive. He intended for each digit to correspond to a distinct direction, and the robot would follow the directions in order to reach the exit. Unfortunately, he forgot to actually assign the directions to digits.The robot will choose some random mapping of digits to distinct directions. The robot will map distinct digits to distinct directions. The robot will then follow the instructions according to the given string in order and chosen mapping. If an instruction would lead the robot to go off the edge of the maze or hit an obstacle, the robot will crash and break down. If the robot reaches the exit at any point, then the robot will stop following any further instructions.Bob is having trouble debugging his robot, so he would like to determine the number of mappings of digits to directions that would lead the robot to the exit.

The first line of input will contain two integers n and m (2 ≤ n, m ≤ 50), denoting the dimensions of the maze. The next n lines will contain exactly m characters each, denoting the maze. Each character of the maze will be '.', '#', 'S', or 'E'. There will be exactly one 'S' and exactly one 'E' in the maze. The last line will contain a single string s (1 ≤ |s| ≤ 100) — the instructions given to the robot. Each character of s is a digit from 0 to 3.

Print a single integer, the number of mappings of digits to directions that will lead the robot to the exit.

NoteFor the first sample, the only valid mapping is , where D is down, L is left, U is up, R is right.

def valid_perm(n,m,arr,start_i,start_j,ends_i,ends_j,perm,str)

cur_i = start_i
cur_j = start_j

str.each do |c|

		ind =  perm.index(c)
		if ind==0 #up
			if cur_i - 1 <0 or arr[cur_i - 1][cur_j] == '#'
				return false
			elsif cur_i - 1 == ends_i and cur_j == ends_j
				return true
			end
			cur_i-=1
		elsif ind == 1 #down
			if cur_i + 1 >=n or arr[cur_i + 1][cur_j] == '#'
				return false
			elsif cur_i + 1 == ends_i and cur_j == ends_j

				return true
			end
			cur_i+=1

		elsif ind== 2 #left
			if cur_j - 1 <0 or arr[cur_i][cur_j-1] == '#'
				return false
			elsif cur_i  == ends_i and cur_j-1 == ends_j

				return true
			end
			cur_j-=1

		elsif ind==3 #right
			if c == "0" and perm.index(c)==3
	 		end
			if cur_j + 1 >=m or arr[cur_i ][cur_j+1] == '#'
				return false
			elsif cur_i  == ends_i and cur_j+1 == ends_j
				return true
			end
			cur_j+=1
		end
	end
return false
end

n,m = gets.chomp.split
n = n.to_i
m = m.to_i

arr = []
start_i=0
start_j=0
ends_i=0
ends_j=0
(0...n).each do |i|
	s = gets.chomp.split('')
	if s.include?("S")
		start_i = i
		start_j = s.index("S")
	end
	if s.include?("E")
		ends_i = i
		ends_j = s.index("E")
	end
	arr<<s
end

str=gets.chomp.split('')
all_perm=["0","1","2","3"].permutation
count=0
all_perm.each do |perm|
	if valid_perm(n,m,arr,start_i,start_j,ends_i,ends_j,perm,str)

		count+=1
	end

end
puts count

#0:up,1:down,2:left,3:right

# Codeforces My Practice
# author: Leonardone @ NEETSDKASU

def gs() gets.strip end
def gss() gs.split end
def gis() gss.map &:to_i end

H, W = gis
F = H.times.map do gs end
C = gs

x, y = 0, 0
H.times do |i|
    W.times do |j|
        if F[i][j] == 'S'
            x, y = j, i
        end
    end
end
SX, SY = x, y

MV = [:L, :U, :D, :R]

ans = MV.permutation.reduce(0) do |a, mv|
    x, y = SX, SY
    C.each_char do |ch|
        case mv[ch.to_i]
        when :L
            x -= 1
        when :U
            y -= 1
        when :D
            y += 1
        when :R
            x += 1
        end
        if !(0...W).include? x
            break
        end
        if !(0...H).include? y
            break
        end
        if F[y][x] == '#'
            break
        end
        if F[y][x] == 'E'
            a += 1
            break
        end
    end
    a
end

puts ans

$dr = [0, 0, -1, 1]
$dc = [-1, 1, 0, 0]
p = [0, 1, 2, 3].permutation.to_a
$s = []
def check
  r = $sr
  c = $sc
  for i in (0...$x.length)
    if r == $er && c == $ec
      return true
    end
    r += $dr[$f[$x[i].to_i]]
    c += $dc[$f[$x[i].to_i]]
    if r < 0 || c < 0 || r >= $n || c >= $m || $s[r][c] == '#'
      return false
    end
  end
  return r == $er && c == $ec
end

g = gets.chomp.split(' ')
$n = g[0].to_i
$m = g[1].to_i
for i in (0...$n)
  g = gets.chomp
  $s.push(g)
  for j in (0...$m)
    if g[j] == 'S'
      $sr = i
      $sc = j
    end
    if g[j] == 'E'
      $er = i
      $ec = j
    end
  end
end
$x = gets.chomp
ans = 0
for i in (0...p.length)
  $f = p[i]
  ans += check ? 1 : 0
end
puts ans

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

maze = Array.new(n)
n.times do |i|
  maze[i] = gets.chomp
  S = [i, maze[i].index(?S)] if maze[i].include?(?S)
  G = [i, maze[i].index(?E)] if maze[i].include?(?E)
end

s = gets.chomp

ans = 0
%w(U D R L).permutation(4) do |a, b, c, d|

  R = S.dup
  i = [a, b, c, d]

  s.each_char do |c|

    d = i[c.to_i]

    if d == ?U
      R[0] += 1
    elsif d == ?D
      R[0] -= 1
    elsif d == ?R
      R[1] += 1
    else
      R[1] -= 1
    end

    break if R[0] < 0 ||  n <= R[0] || R[1] < 0 || m <= R[1] || maze[R[0]][R[1]] == ?#

    if R == G
      ans += 1
      break
    end
  end
end

puts ans

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

maze = Array.new(n)
n.times do |i|
  maze[i] = gets.chomp
  if maze[i].include?(?S)
    S = [i, maze[i].index(?S)]
  end
  if maze[i].include?(?E)
    G = [i, maze[i].index(?E)]
  end
end

# p [n,m]
# p [S, G]

s = gets.chomp

maze

ans = 0
%w(U D R L).permutation(4) do |a, b, c, d|

  R = S.dup
  # is_next = false

  i = [a, b, c, d]

  s.each_char do |c|

    d = i[c.to_i]

    if d == ?U
      R[0] += 1
    elsif d == ?D
      R[0] -= 1
    elsif d == ?R
      R[1] += 1
    else
      R[1] -= 1
    end

    if R[0] < 0 ||  n <= R[0] || R[1] < 0 || m <= R[1] || maze[R[0]][R[1]] == ?#
      # is_next = true
      break
    end

    if R == G
      ans += 1
      break
    end
  end

  # next if is_next
  # p R
  # if G == R
  #   ans += 1
  # end
end

puts ans


Igor has been into chess for a long time and now he is sick of the game by the ordinary rules. He is going to think of new rules of the game and become world famous.Igor's chessboard is a square of size n × n cells. Igor decided that simple rules guarantee success, that's why his game will have only one type of pieces. Besides, all pieces in his game are of the same color. The possible moves of a piece are described by a set of shift vectors. The next passage contains a formal description of available moves.Let the rows of the board be numbered from top to bottom and the columns be numbered from left to right from 1 to n. Let's assign to each square a pair of integers (x, y) — the number of the corresponding column and row. Each of the possible moves of the piece is defined by a pair of integers (dx, dy); using this move, the piece moves from the field (x, y) to the field (x + dx, y + dy). You can perform the move if the cell (x + dx, y + dy) is within the boundaries of the board and doesn't contain another piece. Pieces that stand on the cells other than (x, y) and (x + dx, y + dy) are not important when considering the possibility of making the given move (for example, like when a knight moves in usual chess).Igor offers you to find out what moves his chess piece can make. He placed several pieces on the board and for each unoccupied square he told you whether it is attacked by any present piece (i.e. whether some of the pieces on the field can move to that cell). Restore a possible set of shift vectors of the piece, or else determine that Igor has made a mistake and such situation is impossible for any set of shift vectors.

The first line contains a single integer n (1 ≤ n ≤ 50). The next n lines contain n characters each describing the position offered by Igor. The j-th character of the i-th string can have the following values:  o — in this case the field (i, j) is occupied by a piece and the field may or may not be attacked by some other piece; x — in this case field (i, j) is attacked by some piece; . — in this case field (i, j) isn't attacked by any piece. It is guaranteed that there is at least one piece on the board.

If there is a valid set of moves, in the first line print a single word 'YES' (without the quotes). Next, print the description of the set of moves of a piece in the form of a (2n - 1) × (2n - 1) board, the center of the board has a piece and symbols 'x' mark cells that are attacked by it, in a format similar to the input. See examples of the output for a full understanding of the format. If there are several possible answers, print any of them. If a valid set of moves does not exist, print a single word 'NO'.

NoteIn the first sample test the piece is a usual chess rook, and in the second sample test the piece is a usual chess knight.

n = gets.to_i
board = Array.new
pieces = Array.new
empties = Array.new
n.times do |i|
  board[i] = gets.strip
  n.times do |j|
    if board[i][j] == "o"
      pieces.push [i, j]
    elsif board[i][j] == "."
      empties.push [i, j]
    end
  end
end

moves = Array.new
(2*n-1).times do |i|
  moves.push "x"*(2*n-1)
end
moves[n-1][n-1] = "o"
pieces.each do |piece|
  empties.each do |empty|
    dr = empty[0] - piece[0]
    dc = empty[1] - piece[1]
    moves[n-1+dr][n-1+dc] = "."
  end
end

possible = true
n.times do |i|
  n.times do |j|
    if board[i][j] == "x"
      attacked = false
      pieces.each do |piece|
        dr = i - piece[0]
        dc = j - piece[1]
        attacked = true if moves[n-1+dr][n-1+dc] == "x"
      end
      possible = false if not attacked
    end
  end
end

if possible
  puts "YES"
  puts moves
else
  puts "NO"
end


Haiku is a genre of Japanese traditional poetry.A haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syllables). A haiku masterpiece contains a description of a moment in those three phrases. Every word is important in a small poem, which is why haiku are rich with symbols. Each word has a special meaning, a special role. The main principle of haiku is to say much using a few words.To simplify the matter, in the given problem we will consider that the number of syllable in the phrase is equal to the number of vowel letters there. Only the following letters are regarded as vowel letters: "a", "e", "i", "o" and "u".Three phases from a certain poem are given. Determine whether it is haiku or not.

The input data consists of three lines. The length of each line is between 1 and 100, inclusive. The i-th line contains the i-th phrase of the poem. Each phrase consists of one or more words, which are separated by one or more spaces. A word is a non-empty sequence of lowercase Latin letters. Leading and/or trailing spaces in phrases are allowed. Every phrase has at least one non-space character. See the example for clarification.

Print "YES" (without the quotes) if the poem is a haiku. Otherwise, print "NO" (also without the quotes).

on  codeforces
beta round is running
   a rustling of keys

how many gallons
of edo s rain did you drink
                                cuckoo

c = Array.new
3.times do |i|
	s = STDIN.gets
	c[i] = s.count('aiueo')
end
if c[0] == 5 && c[1] == 7 && c[2] == 5 then
	print "YES"
else
	print "NO"
end

v = 'aeiou'
if gets.count(v) == 5 && gets.count(v) == 7 && gets.count(v) == 5
  puts 'YES'
else
  puts 'NO'
end

[5, 7, 5].each { |c|
  unless gets.chomp.scan(/[aeiou]/).size == c
    puts 'NO'
    exit
  end
}
puts 'YES'

i=j=k=0
gets.chomp.gsub(/[aeiou]/){i+=1}
gets.chomp.gsub(/[aeiou]/){j+=1}
gets.chomp.gsub(/[aeiou]/){k+=1}
puts (i==5 and j==7 and k==5)?"YES":"NO"

input, heiku = STDIN.read.split("\n"), [5, 7, 5]
input.each_with_index { |v, k| (print :NO; exit) if v.count("aeiou") != heiku[k] }
print :YES

a = 3.times.map{gets.count('aeiou')}
puts a == [5, 7, 5] ? :YES : :NO

n = []
3.times do
n.push gets.tr('^aeiou', '').size
end
print n == [5, 7, 5] ? "YES" : "NO"

a=[gets,gets,gets]
l=[]
a.each{ |s|
        l.push(s.length)
}
for i in 0..2
        a[i]=a[i].gsub("a","")
        a[i]=a[i].gsub("o","")
        a[i]=a[i].gsub("u","")
        a[i]=a[i].gsub("i","")
        a[i]=a[i].gsub("e","")
end
if l[0]-a[0].length==5 && l[1]-a[1].length==7 && l[2]-a[2].length==5 then
        puts "YES"
else
        puts "NO"
end

def function
strings=Array.new(3)
counters=Array.new(3)
3.times do |i|
strings[i]=gets.chomp
end
t=/[aeiou]/
if strings[0].scan(t).length==5 && strings[1].scan(t).length==7 && strings[2].scan(t).length==5
print "YES"
else
print "NO"
end
end
function

a = gets.chomp
b = gets.chomp
c = gets.chomp
Vowels = ['a', 'e', 'i', 'o', 'u']
a_s = 0
for char in a.split('')
	a_s += 1 if Vowels.include?char
end
b_s = 0
for char in b.split('')
	b_s += 1 if Vowels.include?char
end
c_s = 0
for char in c.split('')
	c_s += 1 if Vowels.include?char
end
if a_s == 5 && b_s == 7 && c_s == 5
	puts "YES"
else
	puts "NO"
end

a=gets.chomp.split('')
b=gets.chomp.split('')
c=gets.chomp.split('')
x=0
y=0
z=0
a.each do |i|
	if i=='a' || i=='e' || i=='i' || i=='o' || i=='u'
		x+=1
	end
end
b.each do |i|
	if i=='a' || i=='e' || i=='i' || i=='o' || i=='u'
		y+=1
	end
end
c.each do |i|
	if i=='a' || i=='e' || i=='i' || i=='o' || i=='u'
		z+=1
	end
end
if x==5 && y==7 && z==5
	puts "YES"
else
	puts "NO"
end

a = readlines.map(&:strip)
if a[0].gsub(/[aeiou]/).to_a.size == 5 and a[1].gsub(/[aeiou]/).to_a.size == 7 and a[2].gsub(/[aeiou]/).to_a.size == 5
  puts :YES
else
  puts :NO
end

#!/usr/bin/env ruby
# -*- coding: utf-8 -*-

a = 3.times.map{ gets.count('aeiou') }
puts a == [5,7,5] ? "YES" : "NO"

str = gets.split

first = 0
second = 0
third = 0

str.each{|s|
  loop{
    if s =~ /[aiueo]/
      s.sub!($&, "")
      first += 1
    else
      break
    end
  }
}

str = gets.split

str.each{|s|
  loop{
    if s =~ /[aiueo]/
      s.sub!($&, "")
      second += 1
    else
      break
    end
  }
}

str = gets.split

str.each{|s|
  loop{
    if s =~ /[aiueo]/
      s.sub!($&, "")
      third += 1
    else
      break
    end
  }
}

if first == 5
  if second == 7
    if third == 5
      puts "YES"
      exit
    end
  end
end

puts "NO"

a = gets().chomp
b = gets().chomp
c = gets().chomp

def check( c )
    if( c == "a" || c == "i" || c == "u" || c == "e" || c == "o" )
        return true
    else
        return false
    end
end

aa = 0
a.split(//).each{|chr| aa += 1 if(check(chr)) }

bb = 0
b.split(//).each{|chr| bb += 1 if(check(chr)) }

cc = 0
c.split(//).each{|chr| cc += 1 if(check(chr)) }

if( aa == 5 && bb == 7 && cc == 5 )
    puts "YES"
elsif
    puts "NO"
end

a = [ gets.count("aeiou"), gets.count("aeiou"), gets.count("aeiou") ]
puts a==[5,7,5] ?"YES":"NO"

phrases = Array.new
phrases.push(gets.split(""))
phrases.push(gets.split(""))
phrases.push(gets.split(""))
if phrases[0].count("a") + phrases[0].count("e") + phrases[0].count("i") + phrases[0].count("o") + phrases[0].count("u") == 5 and\
   phrases[1].count("a") + phrases[1].count("e") + phrases[1].count("i") + phrases[1].count("o") + phrases[1].count("u") == 7 and\
   phrases[2].count("a") + phrases[2].count("e") + phrases[2].count("i") + phrases[2].count("o") + phrases[2].count("u") == 5
    puts "YES"
else
    puts "NO"
end

v = 'aeiou'
if gets.count(v) == 5 || gets.count(v) == 7 || gets.count(v) == 5
  puts 'YES'
else
  puts 'NO'
end


Sean is trying to save a large file to a USB flash drive. He has n USB flash drives with capacities equal to a1, a2, ..., an megabytes. The file size is equal to m megabytes. Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives.

The first line contains positive integer n (1 ≤ n ≤ 100) — the number of USB flash drives. The second line contains positive integer m (1 ≤ m ≤ 105) — the size of Sean's file. Each of the next n lines contains positive integer ai (1 ≤ ai ≤ 1000) — the sizes of USB flash drives in megabytes. It is guaranteed that the answer exists, i. e. the sum of all ai is not less than m.

Print the minimum number of USB flash drives to write Sean's file, if he can split the file between drives.

NoteIn the first example Sean needs only two USB flash drives — the first and the third.In the second example Sean needs all three USB flash drives.In the third example Sean needs only one USB flash drive and he can use any available USB flash drive — the first or the second.

a=(1..gets.to_i)
b=gets.to_i
a=a.map{gets.to_i}.sort
c=0
while b > 0
  c += 1
  b -= a.pop
end
p c

n = gets.chomp.to_i
m = gets.chomp.to_i
a = []
for i in 1..n do
  a.push(gets.chomp.to_i)
end

a = a.sort.reverse
count = 0
while m > 0 do
  m -= a[count]
  count += 1
end

puts count

#! ruby
# Try Codeforces
# author: Leonardone @ NEETSDKASU
############################################################
def gs() gets.chomp end
def gi() gets.to_i end
def gss() gs.split end
def gis() gss.map(&:to_i) end
def nmapf(n,f) n.times.map{ __send__ f } end
def arr2d(h,w,v=0) h.times.map{[v] * w} end
def ngs(n) nmapf n,:gs end
def ngi(n) nmapf n,:gi end
def ngss(n) nmapf n,:gss end
def ngis(n) nmapf n,:gis end
def for2p(hr,wr,&pr) hr.each{|i|wr.each{|j| yield(i,j)}} end
def nsum(n) n * (n + 1) / 2 end
############################################################

n, m = ngi 2
a = ngi(n).sort.reverse
c = 0
s = 0
a.each do |v|
    s += v
    c += 1
    break if s >= m
end
puts c

n = gets.chomp.to_i
m = gets.chomp.to_i
arr = Array.new(n)
n.times do |i|
  arr[i] = gets.chomp.to_i
end
arr = arr.sort ; arr = arr.reverse
sum = 0 ; res = 0
while sum < m
  sum+=arr[0] ; arr.shift ; res+=1
end
puts res

n=gets.chomp.to_i
size=gets.chomp.to_i
file_arry=[]
0.upto(n-1) do |i|
	file_arry[i]=gets.chomp.to_i
end
file_arry=file_arry.sort.reverse
k=0
output=0
loop do
	k=k+file_arry[output]
	output+=1
	break if k>=size
end
puts output

n = gets.to_i
m = gets.to_i
as = []
n.times do
  as << gets.to_i
end
as.sort!.reverse!
p = 0
while m > 0 do
  m -= as[p]
  p += 1
end
puts p

n=gets.chomp.to_i
size=gets.chomp.to_i

data=[]

a=0
while a<n
	b=gets.chomp.to_i
	data.push(b)
	a+=1
end

data.sort!

k=data.length-1
sum=0
x=0
for i in(0..data.length-1)
	sum+=data[k-i]
	x+=1
	if sum>=size
		break
	end
end

puts x

n=gets.to_i
m=gets.to_i
xs=[]
n.times{
	xs<<(gets.to_i)
}
ans=0
xs.sort.reverse.each{|e|
	m-=e
	ans+=1
	break if m<=0
}
puts ans

#!usr/bin/env ruby

a = []
n = gets.to_i
m = gets.to_i
n.times {
  a << gets.to_i
}

a.sort!
a.reverse!

b = 0
c = 0
while b < m
  c += 1
  b += a.shift
end

puts c

t = gets.to_i
m = gets.to_i
arr1 = Array.new(t)
index=0
t.times do
	arr1[index] = gets.to_i
	index+=1
end

arr1.sort!
sum=m
index=t-1
count=0
while m>0
	count+=1
	m = m - arr1[index]
	index-=1
end
puts count

# coding: utf-8

n = gets.to_i
m = gets.to_i
ar = []
n.times {
    ar << gets.to_i
}
ar.sort!
sticks = 0
while m > 0
    cap = ar.pop
    sticks += 1
    m -= cap
end
puts sticks

carts = gets.to_i
file_mb = gets.to_i

cart = Array.new(carts)

for i in 0..carts-1
	cart[i]= gets.chomp.to_i
end

cart = cart.sort.reverse

sum = 0
num = 0
for i in 0..carts-1
	sum += cart[i]
	num +=1
	if sum >= file_mb
		puts num
		exit
	end
end

n = gets.to_i
m = gets.to_i
a = []
(1..n).each do
  a.push gets.to_i
end

a.sort!
t = 0
tmp = 0
(0...n).each do |i|
  tmp +=a[n-i-1]
  t +=1
  break if tmp >= m
end

puts t

n = gets.chomp.to_i
m = gets.chomp.to_i
a = []
n.times do
  a << gets.chomp.to_i
end
res = 0
a.sort.reverse.each do |i|
  break if m <= 0
  m -= i
  res += 1
end
puts res

n = gets.to_i
m = gets.to_i
a = Array.new(n)
for i in 0..n-1
    a[i] = gets.to_i
end
a = a.sort {|x,y| y <=> x}
k = 0
for item in a
    if m <= 0
        break
    end
    k += 1
    m -= item
end
puts k

n = gets.to_i
m = gets.to_i
arr = []
for i in 0..n-1
    arr[i] = gets.to_i
end

arr = arr.sort
count = 0
idx = n-1
while m > 0
    m -= arr[idx]
    idx -= 1
    count += 1
end

puts count

n = gets.to_i
m = gets.to_i
a = []
n.times { a << gets.to_i }
a.sort!.reverse!
s = 0
(0...a.size).each do |i|
  s += a[i]
  if s >= m
    puts i + 1
    exit
  end
end

n = gets.chomp.to_i
m = gets.chomp.to_i

flash_drives = Array.new
n.times {|i| flash_drives << gets.chomp.to_i}

flash_drives.sort!

k = 0
while m > 0 do
	m = m - flash_drives[n - k - 1]
	k = k + 1
end

print k

t = gets.chomp
t = t.to_i
n = gets.chomp
n = n.to_i
v = []
for i in 1 ..t do
 v << gets.chomp
end
v = v.map(&:to_i)
c=0
s=0
v.sort.reverse.each do |num|
s = s+num
if s >= n
c=c+1
break
else
c=c+1
end
end
puts c

class Solver
	def main
		n = gets.to_i
		m = gets.to_i
		a = []
		n.times do
			a << gets.to_i
		end
		a = a.sort.reverse
		ans = 0
		a.each do |x|
			if m > 0
				m -= x
				ans += 1
			end
		end
		puts ans
	end
end
Solver.new.main

a=(1..gets.to_i).map{gets.to_i}.sort.reverse
b=gets.to_i
c=0
while b > 0
  c += 1
  b -= a.shift
end
p c

input=gets.chomp.to_i
if input>5 && input%2==0
puts (input-2)/4
elsif input>5 && input%2==1
puts 0
else
puts 0
end


A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not.You are given a string $$$s$$$ of length $$$n$$$, consisting of digits.In one operation you can delete any character from string $$$s$$$. For example, it is possible to obtain strings 112, 111 or 121 from string 1121.You need to determine whether there is such a sequence of operations (possibly empty), after which the string $$$s$$$ becomes a telephone number.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of string $$$s$$$. The second line of each test case contains the string $$$s$$$ ($$$|s| = n$$$) consisting of digits.

For each test print one line. If there is a sequence of operations, after which $$$s$$$ becomes a telephone number, print YES. Otherwise, print NO.

NoteIn the first test case you need to delete the first and the third digits. Then the string 7818005553535 becomes 88005553535.

t = gets.to_i
t.times do
	s = gets.to_i
	n = gets
	flag = true
	for e in 0...s
		if(n[e] == '8')
			if(s-e >= 11)
				puts("YES")
				flag = false
				break
			end
		end
	end
	if(flag)
		puts("NO")
	end
end

gets.to_i.times do
  d = gets.to_i
  num = gets.chomp.index('8')
  puts num && d - num >= 11 ? 'YES' : 'NO'
end

gets.to_i.times do
  gets
  puts (gets =~ /8\d{10}/ ? :YES : :NO)
end

T = gets.to_i
T.times do
	n = gets.to_i
	str = gets.chomp
	if str.index('8')
		if str.size - str.index('8') >= 11
			puts "YES"
			next
		end
	end
	puts "NO"
end

t = gets.to_i
for i in 0...t do
  n = gets.to_i
  s = gets.chomp
  flag = false
  for j in 0..(n-11) do
    if s[j] == '8'
      flag = true
      break
    end
  end
  puts flag ? "YES" : "NO"
end

for x in 1..gets.to_i
    len = gets.to_i
    str = gets
    idx = str.index('8')
    if idx.nil? || len - idx < 11
        puts "NO"
    else
        puts "YES"
    end
end

t = gets.to_i
t.times do
	s = gets.to_i
	n = gets
	for e in 0...s
		flag = true
		if(n[e] == '8')
			if(s-e-1 >= 11)
				puts("YES")
				flag = false
				break
			end
		end
	end
	if(!flag)
		puts("NO")
	end
end

t = gets.to_i
t.times do
	s = gets.to_i
	n = gets
	flag = true
	for e in 0...s
		if(n[e] == '8')
			if(s-e-1 >= 11)
				puts("YES")
				flag = false
				break
			end
		end
	end
	if(flag)
		puts("NO")
	end
end

for x in 1..gets.to_i
    len = gets.to_i
    str = gets
    if str.index('8').nil? || len - str.index('8') < 10
        puts "NO"
    else
        puts "YES"
    end
end

cases = gets
for x in 1..cases.to_i
    len = gets.to_i
    str = gets
    if str.index('8').nil? || len - str.index('8') < 10
        puts "NO"
    else
        puts "YES"
    end
end


In some country live wizards. They love to ride trolleybuses.A city in this country has a trolleybus depot with n trolleybuses. Every day the trolleybuses leave the depot, one by one and go to the final station. The final station is at a distance of d meters from the depot. We know for the i-th trolleybus that it leaves at the moment of time ti seconds, can go at a speed of no greater than vi meters per second, and accelerate with an acceleration no greater than a meters per second squared. A trolleybus can decelerate as quickly as you want (magic!). It can change its acceleration as fast as you want, as well. Note that the maximum acceleration is the same for all trolleys.Despite the magic the trolleys are still powered by an electric circuit and cannot overtake each other (the wires are to blame, of course). If a trolleybus catches up with another one, they go together one right after the other until they arrive at the final station. Also, the drivers are driving so as to arrive at the final station as quickly as possible.You, as head of the trolleybuses' fans' club, are to determine for each trolley the minimum time by which it can reach the final station. At the time of arrival at the destination station the trolleybus does not necessarily have zero speed. When a trolley is leaving the depot, its speed is considered equal to zero. From the point of view of physics, the trolleybuses can be considered as material points, and also we should ignore the impact on the speed of a trolley bus by everything, except for the acceleration and deceleration provided by the engine.

The first input line contains three space-separated integers n, a, d (1 ≤ n ≤ 105, 1 ≤ a, d ≤ 106) — the number of trolleybuses, their maximum acceleration and the distance from the depot to the final station, correspondingly. Next n lines contain pairs of integers ti vi (0 ≤ t1 < t2... < tn - 1 < tn ≤ 106, 1 ≤ vi ≤ 106) — the time when the i-th trolleybus leaves the depot and its maximum speed, correspondingly. The numbers in the lines are separated by spaces.

For each trolleybus print a single line the time it arrives to the final station. Print the times for the trolleybuses in the order in which the trolleybuses are given in the input. The answer will be accepted if the absolute or relative error doesn't exceed 10 - 4.

NoteIn the first sample the second trolleybus will catch up with the first one, that will happen at distance 510.5 meters from the depot. The trolleybuses will go the remaining 9489.5 meters together at speed 10 meters per second. As a result, both trolleybuses will arrive to the final station by the moment of time 1000.5 seconds. The third trolleybus will not catch up with them. It will arrive to the final station by the moment of time 11000.05 seconds.

#!/usr/bin/ruby

n, a, d = $stdin.gets.chomp.split.map(&:to_i)
prev = 0.0
n.times do
  t, v = $stdin.gets.chomp.split.map(&:to_f)
  l = v*v/(2.0*a)
  x =
    if l < d
      u = v/a.to_f
      u + (d-l)/v.to_f
    else
      Math.sqrt(2.0*d/a.to_f)
    end
  ans = [x+t, prev].max
  printf "%.5f\n", ans
  prev = ans
end

# ProblemC
require 'bigdecimal'
require 'bigdecimal/math'
include BigMath
include Math
n, a, d = gets.split().map {|s| s.to_i}

prev = 0.0
tm = sqrt((2 * d) / a.to_f)

n.times do
  t, v = gets.split().map {|s| s.to_i}
  ti = v / a.to_f
  tt = t.to_f
  if tm <= ti
    tt += tm
  else
    dm = (a * ti * ti) / 2.0
    tr = (d - dm) / v.to_f
    tt += tr + ti
  end
  if prev > tt
    puts prev
  else
    puts tt
    prev = tt
  end
end

# ProblemC
include Math
n, a, d = gets.split().map {|s| s.to_i}

prev = 0.0
tm = sqrt((2 * d) / a.to_f)

n.times do
  t, v = gets.split().map {|s| s.to_i}
  ti = v / a.to_f
  tt = t.to_f
  if tm <= ti
    tt += tm
  else
    dm = (a * ti * ti) / 2.0
    tr = (d - dm) / v.to_f
    tt += tr + ti
  end
  if prev > tt
    puts prev
  else
    puts tt
  end
  prev = tt
end


Maria participates in a bicycle race.The speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west.Let's introduce a system of coordinates, directing the Ox axis from west to east, and the Oy axis from south to north. As a starting position of the race the southernmost point of the track is selected (and if there are several such points, the most western among them). The participants start the race, moving to the north. At all straight sections of the track, the participants travel in one of the four directions (north, south, east or west) and change the direction of movement only in bends between the straight sections. The participants, of course, never turn back, that is, they do not change the direction of movement from north to south or from east to west (or vice versa).Maria is still young, so she does not feel confident at some turns. Namely, Maria feels insecure if at a failed or untimely turn, she gets into the water. In other words, Maria considers the turn dangerous if she immediately gets into the water if it is ignored.Help Maria get ready for the competition — determine the number of dangerous turns on the track.

The first line of the input contains an integer n (4 ≤ n ≤ 1000) — the number of straight sections of the track. The following (n + 1)-th line contains pairs of integers (xi, yi) ( - 10 000 ≤ xi, yi ≤ 10 000). The first of these points is the starting position. The i-th straight section of the track begins at the point (xi, yi) and ends at the point (xi + 1, yi + 1). It is guaranteed that:   the first straight section is directed to the north;  the southernmost (and if there are several, then the most western of among them) point of the track is the first point;  the last point coincides with the first one (i.e., the start position);  any pair of straight sections of the track has no shared points (except for the neighboring ones, they share exactly one point);  no pair of points (except for the first and last one) is the same;  no two adjacent straight sections are directed in the same direction or in opposite directions.

Print a single integer — the number of dangerous turns on the track.

NoteThe first sample corresponds to the picture:  The picture shows that you can get in the water under unfortunate circumstances only at turn at the point (1, 1). Thus, the answer is 1.

def danger(x, y, xx, yy, xxx, yyy)
  dx, dy, ddx, ddy = xx - x, yy - y, xxx - xx, yyy - yy
  return ddx * dy - ddy * dx < 0
end

n = readline.to_i
x, y = readline.split(' ').collect(&:to_i)
xx, yy = readline.split(' ').collect(&:to_i)
ret = 0
(n - 1).times do
  xxx, yyy = readline.split(' ').collect(&:to_i)
  ret += 1 if danger(x, y, xx, yy, xxx, yyy)
  x, y, xx, yy = xx, yy, xxx, yyy
end

puts ret

def get_dir(dx, dy)
	return 0 if dy>0
	return 2 if dy<0
	return 1 if dx>0
	return 3 if dx<0
end

def calc(dir, last_dir)
	return 1 if last_dir == (dir+1)%4
	return 0
end

n=gets.to_i
p=Array.new
ans=dir=last_dir=0
for i in 0..n
	buf=gets.split(' ')
	p[i] = [buf[0].to_i, buf[1].to_i]
	dir = get_dir(p[i][0]-p[i-1][0], p[i][1] - p[i-1][1]) if i>0
	ans += calc(dir, last_dir) if i>1
	last_dir = dir
end
puts ans


Given a set of integers (it can contain equal elements).You have to split it into two subsets $$$A$$$ and $$$B$$$ (both of them can contain equal elements or be empty). You have to maximize the value of $$$mex(A)+mex(B)$$$.Here $$$mex$$$ of a set denotes the smallest non-negative integer that doesn't exist in the set. For example:   $$$mex(\{1,4,0,2,2,1\})=3$$$  $$$mex(\{3,3,2,1,3,0,0\})=4$$$  $$$mex(\varnothing)=0$$$ ($$$mex$$$ for empty set) The set is splitted into two subsets $$$A$$$ and $$$B$$$ if for any integer number $$$x$$$ the number of occurrences of $$$x$$$ into this set is equal to the sum of the number of occurrences of $$$x$$$ into $$$A$$$ and the number of occurrences of $$$x$$$ into $$$B$$$.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1\leq t\leq 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\leq n\leq 100$$$) — the size of the set. The second line of each testcase contains $$$n$$$ integers $$$a_1,a_2,\dots a_n$$$ ($$$0\leq a_i\leq 100$$$) — the numbers in the set.

For each test case, print the maximum value of $$$mex(A)+mex(B)$$$.

NoteIn the first test case, $$$A=\left\{0,1,2\right\},B=\left\{0,1,5\right\}$$$ is a possible choice.In the second test case, $$$A=\left\{0,1,2\right\},B=\varnothing$$$ is a possible choice.In the third test case, $$$A=\left\{0,1,2\right\},B=\left\{0\right\}$$$ is a possible choice.In the fourth test case, $$$A=\left\{1,3,5\right\},B=\left\{2,4,6\right\}$$$ is a possible choice.

gets.to_i.times do
  gets
  a = gets.split(" ").map(&:to_i)

  x = 0
  1000.times do |i|
    if a.include? i
      a[a.index(i)] = -999
    else
      x = i
      break
    end
  end

  y = 0
  1000.times do |i|
    if a.include? i
      a[a.index(i)] = -999
    else
      y = i
      break
    end
  end

  p x+y
end

gets.to_i.times{gets
t=gets.split.map &:to_i
p [1,2].map{|x|(0..t.max+1).map{|x|t.count x}.find_index{|y|y<x}}.sum}

gets;$<.map{t=gets.split.map &:to_i
p [1,2].map{|x|(0..200).map{|x|t.count x}.find_index{|y|y<x}}.sum}

T = gets.to_i

T.times do
  n = gets.to_i
  a = gets.split.map(&:to_i).sort
  counter = a.tally
  counter.default = 0

  if n <= 1
    if a.first == 0
      puts 1
    else
      puts 0
    end

    next
  end

  vals = [-1, -1]

  0.upto(101) do |x|
    next if counter[x] >= 2

    if counter[x] == 1
      vals[0] = x + 1
      vals[1] = x if vals[1] == -1
    else
      vals[0] = x
      vals[1] = x if vals[1] == -1

      break
    end
  end

  puts vals.sum
end


Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases:   They are equal.  If we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2, then one of the following is correct:   a1 is equivalent to b1, and a2 is equivalent to b2  a1 is equivalent to b2, and a2 is equivalent to b1  As a home task, the teacher gave two strings to his students and asked to determine if they are equivalent.Gerald has already completed this home task. Now it's your turn!

The first two lines of the input contain two strings given by the teacher. Each of them has the length from 1 to 200 000 and consists of lowercase English letters. The strings have the same length.

Print "YES" (without the quotes), if these two strings are equivalent, and "NO" (without the quotes) otherwise.

NoteIn the first sample you should split the first string into strings "aa" and "ba", the second one — into strings "ab" and "aa". "aa" is equivalent to "aa"; "ab" is equivalent to "ba" as "ab" = "a" + "b", "ba" = "b" + "a".In the second sample the first string can be splitted into strings "aa" and "bb", that are equivalent only to themselves. That's why string "aabb" is equivalent only to itself and to string "bbaa".

def min_rpst(x)
	if x.length.even?
		m = x.length / 2
		p = x[0...m]
		q = x[m..-1]
		p = min_rpst p
		q = min_rpst q
		x = p < q ? p + q : q + p
	end
	x
end

s1 = gets.strip
s2 = gets.strip
puts (min_rpst(s1) == min_rpst(s2)) ? "YES" : "NO"

$MOD = 1000000000000000003

def pow2?(n)
    return true if n == 0 || n == 1
    return false if n < 0 || n % 2 == 1
    return pow2?(n / 2)
end

def get_hash(s)
    #p s
    return s[0].ord if s.size == 1
    m = s.size / 2
    h1 = get_hash(s[0..m-1])
    h2 = get_hash(s[m..2 * m])
    return ((h1 + h2) * h1 * h2) % $MOD
end

def eq(s1,s2)
    return true if (s1 == s2)
    return false if (s1.size != s2.size) || (s1.size % 2 == 1)
    if pow2?(s1.size)
        return get_hash(s1) == get_hash(s2)
    end

    m = s1.size / 2
    s11 = s1[0..m - 1]
    s12 = s1[m, 2 * m]
    s21 = s2[0..m - 1]
    s22 = s2[m, 2 * m]
    return true if eq(s11,s21) && eq(s12,s22) || eq(s12,s21) && eq(s11,s22)
    return false
end

s1 = gets.strip
s2 = gets.strip
puts (eq(s1,s2) ? 'YES' : 'NO')

def eq_hash(s1,s2)
    base = 7
    mod = 1000000000000000003
    return true if s1 == s2
    return false if (s1.size % 2 == 1) || (s2.size % 2 == 1) ||
            (s1.size != s2.size)
    hash1 = 0
    hash2 = 0
    s1.size.times do |i|
            hash1 += base ** s1[i].ord
            hash2 += base ** s2[i].ord
            hash1 %= mod
            hash2 %= mod
    end

    return hash1 == hash2
end

#p prime? gets.to_i
#100.times {|i| p i if prime? i }
#n = 10 ** 18 + 1
#while !prime? n do
#    n += 2
#end
#p n
s1 = gets.strip
s2 = gets.strip
p (eq_hash(s1,s2) ? "YES" : "NO")

# def prime?(n)
#     return true if n == 2
#     return false if n < 2 || (n % 2 == 0)
#     i = 3
#     while i * i <= n do
# 	return false if n % i == 0
# 	i += 2
#     end
#     return true
# end

def eq_hash(s1,s2)
    base = 7
    mod = 1000000000000000003
    return true if s1 == s2
    return false if (s1.size % 2 == 1) || (s2.size % 2 == 1) ||
	    (s1.size != s2.size)
    hash1 = 0
    hash2 = 0
    s1.size.times do |i|
	    hash1 += base ** s1[i].ord
	    hash2 += base ** s2[i].ord
	    hash1 %= mod
	    hash2 %= mod
    end

    return hash1 == hash2
end

#p prime? gets.to_i
#100.times {|i| p i if prime? i }
#n = 10 ** 18 + 1
#while !prime? n do
#    n += 2
#end
#p n
s1 = gets.strip
s2 = gets.strip
puts (eq_hash(s1,s2) ? 'YES' : 'NO')


It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.

The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station.  Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.

Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.

NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.

n,t = gets.split.map(&:to_i)
min = 10 ** 6
ans = 0
n.times do |i|
  s,d = gets.split.map(&:to_i)
  if s > t
    tmp = s
  else
    tmp = ((t-s)/d.to_f).ceil * d + s
  end
  if tmp < min
    min = tmp
    ans = i+1
  end
  #p tmp
end
p ans

N, T = gets.split.map(&:to_i)

buses = N.times.map { gets.split.map(&:to_i) }

ans = -1
time = Float::INFINITY

buses.each.with_index(1) do |(s, d), i|
  t = if s >= T
        s
      else
        s + d * ((T - s) / d.to_f).ceil
      end

  if time > t
    time = t
    ans = i
  end
end

puts ans

n, t = gets.split.map(&:to_i)
mn = 2147483647
idx = -1

n.times do |i|
  s, d = gets.split.map(&:to_i)
  x = ((t-s).to_f/d).ceil

  if x < 0
    x = 0
  end

  if mn > s+d*x
    mn = s+d*x
    idx = i+1
  end
end

p idx

n, t = gets.chomp.split(" ").map(&:to_i)
ret = 10**5
ans = -1
n.times do |i|
  s, d = gets.chomp.split(" ").map(&:to_i)
  while true
    if s >= t
      st = s - t
      if ret > st
        ret = st
        ans = i + 1
      end
      break
    end
    s += d
  end
end
puts ans


Given an array $$$a$$$ of length $$$n$$$, you can do at most $$$k$$$ operations of the following type on it:  choose $$$2$$$ different elements in the array, add $$$1$$$ to the first, and subtract $$$1$$$ from the second. However, all the elements of $$$a$$$ have to remain non-negative after this operation. What is lexicographically the smallest array you can obtain?An array $$$x$$$ is lexicographically smaller than an array $$$y$$$ if there exists an index $$$i$$$ such that $$$x_i<y_i$$$, and $$$x_j=y_j$$$ for all $$$1 \le j < i$$$. Less formally, at the first index $$$i$$$ in which they differ, $$$x_i<y_i$$$.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 20$$$) – the number of test cases you need to solve. The first line of each test case contains $$$2$$$ integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 100$$$, $$$1 \le k \le 10000$$$) — the number of elements in the array and the maximum number of operations you can make. The second line contains $$$n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$0 \le a_i \le 100$$$) — the elements of the array $$$a$$$.

For each test case, print the lexicographically smallest array you can obtain after at most $$$k$$$ operations.

NoteIn the second test case, we start by subtracting $$$1$$$ from the first element and adding $$$1$$$ to the second. Then, we can't get any lexicographically smaller arrays, because we can't make any of the elements negative.

def solution(arr, n, k)
  i = 0

  while i < n - 1 && k > 0
    if arr[i] == 0
      i += 1
      next
    end

    arr[i] -= 1
    arr[n - 1] += 1
    k -= 1
  end

  arr
end

test_cases = gets.to_i

test_cases.times do |test_case|
  n, k = gets.split(' ').map(&:to_i)
  arr = gets.split(' ').map(&:to_i)
  res = solution(arr, n, k)

  puts res.join(' ')
end

t = Integer(gets.chomp)
t.times{
    n, k = gets.chomp.split().map!{|c| Integer(c)}
    a = gets.chomp.split().map!{|c| Integer(c)}

    l = 0
    until k == 0 || l == n-1 do
        if(a[l] > k)
            a[l] -= k
            a[n - 1] += k
            k = 0
        else
            k -= a[l]
            a[n-1] += a[l]
            a[l] = 0
            l += 1
        end
    end

    a.each do |e| print "#{e} " end
    puts ""
}

test_cases = gets.chomp.to_i
for i in 1..test_cases do
    line = gets.chomp.split(" ")
    n = line[0].to_i
    k = line[1].to_i
    a = gets.chomp.split(" ")
    b = Array.new(n)
    for j in 0..n - 1 do
        b[j] = a[j].to_i
    end
    for j in 0..n - 1 do
        d = [k, b[j]].min
        b[j] -= d
        b[n - 1] += d
        k -= d
        if k == 0
            break
        end
    end
    for j in 0..n - 1 do
        print "#{b[j]} "
    end
    puts ""
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n, k = gets.to_s.split.map {|x| x.to_i }
  a = gets.to_s.split.map {|x| x.to_i }
  i = 0
  k.times do
    while a[i] == 0 && i < a.size - 1
      i += 1
    end
    if a[i] > 0 && i < a.size - 1
      a[i] -= 1
      a[-1] += 1
    end
  end
  printf("%s\n", a.join(" "))
end

def solution(arr, n, k)
  i = 0

  while i < n - 1 && k > 0
    i += 1 if arr[i] == 0
    arr[i] -= 1
    arr[n - 1] += 1
    k -= 1
  end

  arr
end

test_cases = gets.to_i

test_cases.times do |test_case|
  n, k = gets.split(' ').map(&:to_i)
  arr = gets.split(' ').map(&:to_i)
  res = solution(arr, n, k)

  puts res.join(' ')
end

def solution(arr, n, k)
  i = 0

  while arr[i] >= 0 && k > 0 && i < n - 1
    break if arr[i] == 0
    arr[i] -= 1
    arr[n - i - 1] += 1
    k -= 1
    i += 1 if arr[i] < 1
  end

  arr
end

test_cases = gets.to_i

test_cases.times do |test_case|
  n, k = gets.split(' ').map(&:to_i)
  arr = gets.split(' ').map(&:to_i)
  res = solution(arr, n, k)

  puts res.join(' ')
end

def solution(arr, n, k)
  i = 0

  while arr[i] >= 0 && k > 0 && i < n - 1
    arr[i] -= 1
    arr[n - i - 1] += 1
    k -= 1
    i += 1 if arr[i] == 0
    # puts arr.join(' ')
  end

  arr
end

test_cases = gets.to_i

test_cases.times do |test_case|
  n, k = gets.split(' ').map(&:to_i)
  arr = gets.split(' ').map(&:to_i)
  res = solution(arr, n, k)

  puts res.join(' ')
end

def solution(arr, n, k)
  i = 0

  while i < n && arr[i] > 0 && k > 0
    arr[i] -= 1
    arr[n - i - 1] += 1
    k -= 1
    i += 1 if arr[i] == 1
  end

  arr
end

test_cases = gets.to_i

test_cases.times do |test_case|
  n, k = gets.split(' ').map(&:to_i)
  arr = gets.split(' ').map(&:to_i)
  res = solution(arr, n, k)

  puts res.join(' ')
end


You are given the array of integer numbers a0, a1, ..., an - 1. For each element find the distance to the nearest zero (to the element which equals to zero). There is at least one zero element in the given array.

The first line contains integer n (1 ≤ n ≤ 2·105) — length of the array a. The second line contains integer elements of the array separated by single spaces ( - 109 ≤ ai ≤ 109).

Print the sequence d0, d1, ..., dn - 1, where di is the difference of indices between i and nearest j such that aj = 0. It is possible that i = j.

n=gets.chomp
a=gets.chomp.split.map!{|x| x.to_i}
last=-a.size
a.each_index do |i|
    last = i if a[i]==0
    a[i]=i-last
end
a.reverse!

last=-a.size
a.each_index do |i|
    last = i if a[i]==0
    a[i]=i-last if a[i]>i-last
end
a.reverse!
puts a * ' '

#!/usr/bin/ruby
n,*a=$<.read.split.map &:to_i
z=[-Float::INFINITY]+(0...n).select{|i|a[i]==0}+[Float::INFINITY]
puts (0...n).map{|i|
	idx=((0...z.size).bsearch{|j|z[j]>=i}||z.size)-1
	[i-z[idx],z[idx+1]-i].min
}*' '

size = gets.chomp.to_i
values = gets.chomp.split(' ').map!(&:to_i)

indexes = values.each_with_object([]).with_index do |(value, obj), index|
  obj << index if value.zero?
end

result = []
left = nil
right = indexes.shift

size.times do |index|
  #puts "left: #{left} right: #{right} tested: #{index}"
  distance_to_left = (index - (left || right)).abs
  distance_to_right = (index - (right || left)).abs

  result << [distance_to_left, distance_to_right].min # pohybujeme se v mantinelu
  # mantinel posuneme jakmile prejdeme pres index
  if index == right
    left = right
    right = indexes.shift
  end
end

puts result.join(' ')

n=gets.to_i
a=gets.split(" ").map(&:to_i)
h=Hash.new
zeroIndex=-1
for i in 0...n
	if a[i]==0
		zeroIndex=i
		h[i]=0
	else
		if zeroIndex>=0
			h[i]=i-zeroIndex
		else
			h[i]=n
		end
	end
end
zeroIndex=-1
for i in (n-1).downto(0)
	if a[i]==0
		zeroIndex=i
	else
		if zeroIndex>=0
			h[i]=[h[i],zeroIndex-i].min
		end
	end
end
puts h.values.join(" ")

n=gets.chomp
a=gets.chomp.split.map!{|x| x.to_i}
last=-a.size
a.each_index do |i|
    last = i if a[i]=='0'
    a[i]=i-last
end
a.reverse!

last=-a.size
a.each_index do |i|
    last = i if a[i]==0
    a[i]=i-last if a[i]>i-last
end
a.reverse!
puts a

size = gets.chomp.to_i
values = gets.chomp.split(' ').map!(&:to_i)

indexes = values.each_with_object([]).with_index do |(value, obj), index|
  obj << index if value.zero?
end

result = []
left = nil
right = indexes.shift

size.times do |index|
  puts "left: #{left} right: #{right} tested: #{index}"
  distance_to_left = (index - (left || right)).abs
  distance_to_right = (index - (right || left)).abs

  result << [distance_to_left, distance_to_right].min # pohybujeme se v mantinelu
  # mantinel posuneme jakmile prejdeme pres index
  if index == right
    left = right
    right = indexes.shift
  end
end

puts result.join(' ')


Given an array $$$a$$$ of positive integers with length $$$n$$$, determine if there exist three distinct indices $$$i$$$, $$$j$$$, $$$k$$$ such that $$$a_i + a_j + a_k$$$ ends in the digit $$$3$$$.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$3 \leq n \leq 2 \cdot 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the elements of the array. The sum of $$$n$$$ across all test cases does not exceed $$$2 \cdot 10^5$$$.

Output $$$t$$$ lines, each of which contains the answer to the corresponding test case. Output "YES" if there exist three distinct indices $$$i$$$, $$$j$$$, $$$k$$$ satisfying the constraints in the statement, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

NoteIn the first test case, you can select $$$i=1$$$, $$$j=4$$$, $$$k=3$$$. Then $$$a_1 + a_4 + a_3 = 20 + 84 + 19 = 123$$$, which ends in the digit $$$3$$$.In the second test case, you can select $$$i=1$$$, $$$j=2$$$, $$$k=3$$$. Then $$$a_1 + a_2 + a_3 = 1 + 11 + 1 = 13$$$, which ends in the digit $$$3$$$.In the third test case, it can be proven that no such $$$i$$$, $$$j$$$, $$$k$$$ exist. Note that $$$i=4$$$, $$$j=4$$$, $$$k=4$$$ is not a valid solution, since although $$$a_4 + a_4 + a_4 = 1111 + 1111 + 1111 = 3333$$$, which ends in the digit $$$3$$$, the indices need to be distinct.In the fourth test case, it can be proven that no such $$$i$$$, $$$j$$$, $$$k$$$ exist.In the fifth test case, you can select $$$i=4$$$, $$$j=3$$$, $$$k=1$$$. Then $$$a_4 + a_3 + a_1 = 4 + 8 + 1 = 13$$$, which ends in the digit $$$3$$$.In the sixth test case, you can select $$$i=1$$$, $$$j=2$$$, $$$k=6$$$. Then $$$a_1 + a_2 + a_6 = 16 + 38 + 99 = 153$$$, which ends in the digit $$$3$$$.

def solve
    n = gets.to_i
    a = gets.split.map(&:to_i)
    cnt = Array.new(10)
    cnt2 = Array.new(10)
    i = 0
    while i < n
        a[i] = a[i] % 10
        i = i + 1
    end
    i = 0
    while i < 10
        cnt[i] = 0
        cnt2[i] = 0
        i = i + 1
    end
    a.each do |i|
        cnt[i] = cnt[i] + 1
    end
    ok = false
    i = 0
    while i < 10
        j = 0
        cnt2[i] = cnt2[i] + 1
        while j < 10
            cnt2[j] = cnt2[j] + 1
            k = 0
            while k < 10
                cnt2[k] = cnt2[k] + 1
                x = (i + j + k) % 10
                if cnt[i] >= cnt2[i] and cnt[j] >= cnt2[j] and cnt[k] >= cnt2[k] and x == 3
                    ok = true
                end
                cnt2[k] = cnt2[k] - 1
                k = k + 1
            end
            cnt2[j] = cnt2[j] - 1
            j = j + 1
        end
        cnt2[i] = cnt2[i] - 1
        i = i + 1
    end
    if ok == true
        puts "YES"
    else
        puts "NO"
    end
end

gets.to_i.times do
    solve
end

# 和が 3 になる組み合わせを列挙
combinations = []
(0 .. 9).each do |x|
    (x .. 9).each do |y|
        (y .. 9).each do |z|
            if (x + y + z) % 10 == 3
                counts = [0] * 10
                counts[x] += 1
                counts[y] += 1
                counts[z] += 1
                combinations << counts
            end
        end
    end
end

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

    counts = [0] * 10
    a.each do |x|
        counts[x % 10] += 1
    end

    ans = combinations.any? { |counts2| (0 .. 9).all? { |x| counts[x] >= counts2[x] } }
    puts ans ? "YES" : "NO"
end

main = -> {
    t = int
    t.times do
        n = int
        a = ints

        count = [0] * 10
        a.each do |x|
            count[x % 10] += 1
        end

        yesno ((0 ... 10).any? do |x|
            next false if count[x] == 0
            count[x] -= 1
            b = (x ... 10).any? do |y|
                next false if count[y] == 0
                count[y] -= 1
                c = (y ... 10).any? do |z|
                    next false if count[z] == 0
                    (x + y + z) % 10 == 3
                end
                count[y] += 1
                c
            end
            count[x] += 1
            b
        end)
    end
}

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

require "set"
require "prime"

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

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

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

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

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

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

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

main[]

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map{|e| e.to_i % 10}
  at = a.tally
  new_a = []
  at.each do |k,v|
    [v,3].min.times do
      new_a << k
    end
  end

  ans = false
  m = new_a.size
  m.times do |i|
    m.times do |j|
    next if i == j
      m.times do |k|
        next if i == k || k == j

        if (new_a[i]+new_a[j]+new_a[k])%10 == 3
          ans = true
          break
        end
      end
      break if ans
    end
    break if ans
  end

  puts ans ? "YES" : "NO"
end

def solve(a)
  arr = gets.split.map(&:to_i).map { |number| number.modulo(10) }

  hash = Hash.new(0)

  arr.each do |n|
    hash[n] = hash[n] > 3 ? 3 : hash[n].succ
  end

  numbers = []
  hash.each_key do |key|
    while hash[key] > 0
      numbers.push(key)
      hash[key] -= 1
    end
  end

  (0...numbers.size).each do |i|
    ((i + 1)...numbers.size).each do |j|
      ((j + 1)...numbers.size).each do |k|
        if (numbers[i] + numbers[j] + numbers[k]) % 10 == 3
          puts "YES"
          return
        end
      end
    end
  end

  puts "NO"
end

n = gets.to_i

n.times do
  a = gets.to_i
  solve(a)
end

array = []
0.upto(9) do |a|
  0.upto(9) do |b|
    0.upto(9) do |c|
      array << [a, b, c] if (a + b + c) % 10 == 3
    end
  end
end

gets.to_i.times do
  gets
  xs = gets.split.map(&:to_i)
  map = Hash.new(0)
  xs.each do |x|
    map[x % 10] += 1
  end
  ok = array.any? { |array| 0.upto(9).all? { |d| array.count(d) <= map[d] } }
  puts ok ? "YES" : "NO"
end

def solve
    n = gets.to_i
    a = gets.split.map(&:to_i)
    cnt = Array.new(10)
    cnt2 = Array.new(10)
    pairs = Array.new(n) {Array.new(10)}
    i = 0
    while i < n
        j = 0
        while j < 10
            pairs[i][j] = 0
            j = j + 1
        end
        i = i + 1
    end
    i = 0
    while i < 10
        cnt[i] = 0
        cnt2[i] = 0
        i = i + 1
    end
    a.each do |x|
        i = x % 10
        cnt[i] = cnt[i] + 1
    end
    id = 0
    a.each do |x|
        i = x % 10
        j = 0
        cnt[i] = cnt[i] - 1
        while j < 10
            k = (i + j) % 10
            cnt2[k] = cnt2[k] + cnt[j]
            pairs[id][k] = pairs[id][k] + cnt[j]
            j = j + 1
        end
        cnt[i] = cnt[i] + 1
        id = id + 1
    end
    id = 0
    ok = false
    a.each do |x|
        i = x % 10
        j = 0
        while j < 10
            cnt2[j] = cnt2[j] - pairs[id][j]
            j = j + 1
        end
        j = 0
        while j < 10
            k = (i + j) % 10
            if k == 3 and cnt2[j] > 0
                ok = true
            end
            j = j + 1
        end
        j = 0
        while j < 10
            cnt2[j] = cnt2[j] + pairs[id][j]
            j = j + 1
        end
        id = id + 1
    end
    if ok == true
        puts "YES"
    else
        puts "NO"
    end
end

gets.to_i.times do
    solve
end

def solve
    n = gets.to_i
    a = gets.split.map(&:to_i)
    cnt = Array.new(10)
    cnt2 = Array.new(10)
    pairs = Array.new(n) {Array.new(10)}
    i = 0
    while i < n
        j = 0
        while j < 10
            pairs[i][j] = 0
            j = j + 1
        end
        i = i + 1
    end
    i = 0
    while i < 10
        cnt[i] = 0
        cnt2[i] = 0
        i = i + 1
    end
    a.each do |x|
        i = x % 10
        cnt[i] = cnt[i] + 1
    end
    id = 0
    a.each do |x|
        i = x % 10
        j = 0
        cnt[i] = cnt[i] - 1
        while j < 10
            k = (i + j) % 10
            cnt2[k] = cnt2[k] + cnt[j]
            pairs[id][k] = pairs[id][k] + cnt[j]
            j = j + 1
        end
        cnt[i] = cnt[i] + 1
        id = id + 1
    end
    id = 0
    ok = false
    a.each do |x|
        i = x % 10
        j = 0
        while j < 10
            cnt2[j] = cnt2[j] - pairs[id][j]
            j = j + 1
        end
        j = 0
        while j < 10
            k = (i + j) % 10
            if k == 3 and cnt2[j] > 0
                ok = true
            end
            j = j + 1
        end
        j = 0
        while j < 10
            cnt2[j] = cnt2[j] + pairs[id][j]
            j = j + 1
        end
    end
    if ok == true
        puts "YES"
    else
        puts "NO"
    end
end

gets.to_i.times do
    solve
end

def solve
    n = gets.to_i
    a = gets.split.map(&:to_i)
    cnt = Array.new(10)
    cnt2 = Array.new(10)
    pairs = Array.new(n) {Array.new(10)}
    i = 0
    while i < n
        j = 0
        while j < 10
            pairs[i][j] = 0
            j = j + 1
        end
        i = i + 1
    end
    i = 0
    while i < 10
        cnt[i] = 0
        cnt2[i] = 0
        i = i + 1
    end
    a.each do |x|
        i = x % 10
        cnt[i] = cnt[i] + 1
    end
    id = 0
    a.each do |x|
        i = x % 10
        j = 0
        cnt[i] = cnt[i] - 1
        while j < 10
            k = (i + j) % 10
            cnt2[k] = cnt2[k] + cnt[j]
            pairs[id][k] = pairs[id][k] + cnt[j]
            j = j + 1
        end
        cnt[i] = cnt[i] + 1
        id = id + 1
    end
    id = 0
    ok = false
    a.each do |x|
        i = x % 10
        j = 0
        while j < 10
            k = (i + j) % 10
            cnt2[k] = cnt2[k] - pairs[id][k]
            if k == 3 and cnt2[k] > 0
                ok = true
            end
            j = j + 1
        end
        j = 0
        while j < 10
            k = (i + j) % 10
            cnt2[k] = cnt2[k] + pairs[id][k]
            j = j + 1
        end
    end
    if ok == true
        puts "YES"
    else
        puts "NO"
    end
end

gets.to_i.times do
    solve
end

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map{|e| e.to_i % 10}
  at = a.tally
  new_a = []
  at.each do |k,v|
    [v,2].min.times do
      new_a << k
    end
  end

  ans = false
  m = new_a.size
  m.times do |i|
    m.times do |j|
      next if i == j
      k = new_a[i]+new_a[j]
      if k <= 3
        ans = true if !at[(3-k)].nil?
      elsif k <= 13
        ans = true if !at[(13-k)].nil?
      elsif k <= 23
        ans = true if !at[(23-k)].nil?
      end
      break if ans
    end
    break if ans
  end

  puts ans ? "YES" : "NO"
end


We just discovered a new data structure in our research group: a suffix three!It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in.It's super simple, 100% accurate, and doesn't involve advanced machine learning algorithms.Let us tell you how it works.  If a sentence ends with "po" the language is Filipino.  If a sentence ends with "desu" or "masu" the language is Japanese.  If a sentence ends with "mnida" the language is Korean. Given this, we need you to implement a suffix three that can differentiate Filipino, Japanese, and Korean.Oh, did I say three suffixes? I meant four.

The first line of input contains a single integer $$$t$$$ ($$$1 \leq t \leq 30$$$) denoting the number of test cases. The next lines contain descriptions of the test cases.  Each test case consists of a single line containing a single string denoting the sentence. Spaces are represented as underscores (the symbol "_") for ease of reading. The sentence has at least $$$1$$$ and at most $$$1000$$$ characters, and consists only of lowercase English letters and underscores. The sentence has no leading or trailing underscores and no two consecutive underscores. It is guaranteed that the sentence ends with one of the four suffixes mentioned above.

For each test case, print a single line containing either "FILIPINO", "JAPANESE", or "KOREAN" (all in uppercase, without quotes), depending on the detected language.

8
kamusta_po
genki_desu
ohayou_gozaimasu
annyeong_hashimnida
hajime_no_ippo
bensamu_no_sentou_houhou_ga_okama_kenpo
ang_halaman_doon_ay_sarisari_singkamasu
si_roy_mustang_ay_namamasu

FILIPINO
JAPANESE
JAPANESE
KOREAN
FILIPINO
FILIPINO
JAPANESE
JAPANESE

NoteThe first sentence ends with "po", so it is written in Filipino.The second and third sentences end with "desu" and "masu", so they are written in Japanese.The fourth sentence ends with "mnida", so it is written in Korean.

test=gets.strip.to_i

while test != 0
		n_str=gets.strip
		str = n_str.reverse();
		if str[0] == 'o' && str[1] == 'p'
			puts "FILIPINO"
		elsif str[0] == 'a' && str[1] == 'd' && str[2] == 'i' && str[3] == 'n' && str[4] == 'm'
			puts "KOREAN"
		else
			puts "JAPANESE"
		end
		test -= 1
end

T=gets.chomp.to_i
T.times do |x|
    string = gets.chomp
    puts "FILIPINO" if string.end_with? "po"
    puts "JAPANESE" if string.end_with? "masu"
    puts "JAPANESE" if string.end_with? "desu"
    puts "KOREAN" if string.end_with? "mnida"
end

t = gets.to_i
t.times do
	s = gets.chomp.reverse!
	if s.slice(0,2) == 'op'
		puts "FILIPINO"
	elsif ["used", "usam"].include?s.slice(0,4)
		puts "JAPANESE"
	else
		puts "KOREAN"
	end
end

N=STDIN.gets.strip.to_i
(0..N-1).each do |i|
  s=STDIN.gets.strip
  if s =~ /po$/
    puts 'FILIPINO'
  elsif s =~ /desu$/ || s =~ /masu$/
    puts 'JAPANESE'
  elsif s =~ /mnida$/
    puts 'KOREAN'
  end
end

number = gets.chomp.to_i
cases = []
number.times { cases << gets.chomp }
for line in cases
	if line[-5..-1] == 'mnida'
		puts("KOREAN")
	elsif line[-4..-1] == 'desu' || line[-4..-1] == 'masu'
		puts("JAPANESE")
	elsif line[-2..-1] == 'po'
		puts("FILIPINO")
	else
		puts("Just for safety, ya know :3")
	end
end

def solution
  n = gets.chomp.to_i
  data = []
  n.times do
    input = gets.chomp
    if input.size >= 2 && input[-2..-1] == 'po'
      data.push 'FILIPINO'
    elsif input.size >= 4 && input[-4..-1] == 'desu' || input[-4..-1] == 'masu'
      data.push 'JAPANESE'
    elsif input.size >= 5 && input[-5..-1] == 'mnida'
      data.push 'KOREAN'
    end
  end
  data.each { |e| puts e }
end

solution

gets.to_i.times do
    s = gets.chomp
    if s[-1] == "o"
        puts "FILIPINO"
    elsif s[-1] == "a"
        puts "KOREAN"
    elsif s[-1] == "u"
        puts "JAPANESE"
    end
end

nb = gets.to_i
nb.times do
  case gets.chomp[-1]
  when 'a'
    puts 'KOREAN'
  when 'u'
    puts 'JAPANESE'
  when 'o'
    puts 'FILIPINO'
  end
end

words = []
gets.chomp().to_i.times do |i|
  words << gets.chomp().to_s #input
end
words.length().times do |i|
  if(words[i][-1].eql? "o")
    puts "FILIPINO"
  elsif(words[i][-1].eql? "u")
    puts "JAPANESE"
  else
    puts "KOREAN"
  end
end

gets.to_i.times do
  s = gets.chop
  puts 'FILIPINO' if s[-2..-1] == 'po'
  puts 'JAPANESE' if s[-4..-1] == 'masu' or s[-4..-1] == 'desu'
  puts 'KOREAN' if s[-5..-1] == 'mnida'
end

gets.to_i.times do
  s = gets.chomp
  puts 'FILIPINO' if s[-2..-1] == 'po'
  puts 'JAPANESE' if s[-4..-1] == 'masu' or s[-4..-1] == 'desu'
  puts 'KOREAN' if s[-5..-1] == 'mnida'
end

if ARGV[0]=="LOCAL_DEV"
  define_method("debug") do |var|
    p var
  end
else
  define_method("debug") do |var|
  end
end

N=STDIN.gets.strip.to_i
(0..N-1).each do |i|
  s=STDIN.gets.strip
  if s =~ /^.+?po$/
    puts 'FILIPINO'
  elsif s =~ /^.+?desu$/ || s =~ /^.+?masu$/
    puts 'JAPANESE'
  elsif s =~ /^.+?mnida$/
    puts 'KOREAN'
  end
end


Phoenix has $$$n$$$ coins with weights $$$2^1, 2^2, \dots, 2^n$$$. He knows that $$$n$$$ is even.He wants to split the coins into two piles such that each pile has exactly $$$\frac{n}{2}$$$ coins and the difference of weights between the two piles is minimized. Formally, let $$$a$$$ denote the sum of weights in the first pile, and $$$b$$$ denote the sum of weights in the second pile. Help Phoenix minimize $$$|a-b|$$$, the absolute value of $$$a-b$$$.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$2 \le n \le 30$$$; $$$n$$$ is even) — the number of coins that Phoenix has.

NoteIn the first test case, Phoenix has two coins with weights $$$2$$$ and $$$4$$$. No matter how he divides the coins, the difference will be $$$4-2=2$$$.In the second test case, Phoenix has four coins of weight $$$2$$$, $$$4$$$, $$$8$$$, and $$$16$$$. It is optimal for Phoenix to place coins with weights $$$2$$$ and $$$16$$$ in one pile, and coins with weights $$$4$$$ and $$$8$$$ in another pile. The difference is $$$(2+16)-(4+8)=6$$$.

def solve n
  first = (1...(n/2)).to_a + [n]
  first = first.flatten
  second = ((n/2)...n).to_a
  a = first.map {|i| 2**i}.reduce(:+)
  b = second.map {|i| 2**i}.reduce(:+)
  (a-b).abs
end

t = STDIN.gets.chomp.to_i

t.times do |i|
  n = STDIN.gets.chomp.to_i
  res = solve n
  puts res
end

# require 'pry-byebug'

file = File.exist?('in.in') ? File.new('in.in','r') : STDIN
t = file.gets.chomp.to_i

t.times do
  n = file.gets.chomp.to_i

  a = 2**n
  min = 2**(n/2)-2

  b = 2**(n-1)
  min2 = 2**(n-1)-2-min

  puts (a+min)-(b+min2)
end

pw2 = Array.new(32,0);
pw2[0]=1
for i in 1..31
    pw2[i]=pw2[i-1]*2
end

t = gets.chomp.to_i
while t>0 do
    n = gets.chomp.to_i
    sum = 0
    for i in 1..(n/2-1)
        sum+=pw2[i]
    end
    sum+=pw2[n]
    puts sum - (pw2[n+1]-sum-2)
    t-=1

end

n = gets.to_i

n.times {
  v = gets.to_i
  puts 2 ** (v / 2 + 1) - 2
}

def min_weigth(n)
  f1 = (2 ** (n/2)) - 2
  (f1 + (2 ** n)) - ((2 ** n) - 2 - f1)
end

t = gets.chomp.to_i

t.times do
  n = gets.chomp.to_i
  puts min_weigth(n)
end

# Phoenix has 𝑛 coins with weights 21,22,…,2𝑛. He knows that 𝑛 is even.

# He wants to split the coins into two piles such that each pile has exactly 𝑛2
# coins and the difference of weights between the two piles is minimized.
# Formally, let 𝑎 denote the sum of weights in the first pile, and 𝑏 denote the
# sum of weights in the second pile. Help Phoenix minimize |𝑎−𝑏|, the absolute
# value of 𝑎−𝑏.

# Input
# The input consists of multiple test cases. The first line contains an integer
# 𝑡 (1≤𝑡≤100) — the number of test cases.

# The first line of each test case contains an
# integer 𝑛 (2≤𝑛≤30; 𝑛 is even) — the number of coins that Phoenix has.

# Output
# For each test case, output one integer — the minimum possible difference of
# weights between the two piles.

# Example
# inputCopy
# 2
# 2
# 4
# outputCopy
# 2
# 6
# Note
# In the first test case, Phoenix has two coins with weights 2 and 4. No matter
# how he divides the coins, the difference will be 4−2=2.

# In the second test case, Phoenix has four coins of weight 2, 4, 8, and 16.
# It is optimal for Phoenix to place coins
# with weights 2 and 16 in one pile, and coins with weights 4 and 8 in another
# pile. The difference is (2+16)−(4+8)=6.

def phoenix(queries)
  queries.each do |query|
    query = query.split(' ')

    return 0 unless query.length == 1

    stack_a = 0
    stack_a_count = 0
    stack_b = 0
    stack_b_count = 0
    input_n = query.first.to_i
    half = input_n / 2

    (input_n).downto(1) do |operand|
      product = 2 ** operand

      if stack_a_count == half
        stack_b += product
        stack_b_count += 1
        next
      end

      if stack_b_count == half
        stack_a += product
        stack_a_count += 1
        next
      end

      if stack_a > stack_b
        stack_b += product
        stack_b_count += 1
      else
        stack_a += product
        stack_a_count += 1
      end
    end

    puts (stack_a - stack_b).abs
  end

  return nil
end

# Codeforces required setup
number_of_queries = gets.rstrip.to_i

queries = []

number_of_queries.times do |query|
  queries << gets.rstrip
end

result = phoenix queries
puts result

pw2 = Array.new(32,0);
pw2[0]=1
for i in 1..31
    pw2[i]=pw2[i-1]*2
end

t = gets.chomp.to_i
while t>0 do
    n = gets.chomp.to_i
    sum = 0
    for i in i..(n/2-1)
        sum+=pw[i]
    end
    sum+=pw2[n]

    puts sum - (pw2[n+1]-sum-2)
    t-=1

end

def min_weigth(n)
  f1 = (2 ** (n/2)) - 2
  (f1 + (2 ** n)) - ((2 ** n) - 2 - f1)
end

t = gets.chomp.to_i

t.times do
  n = gets.chomp.to_i
  min_weigth(n)
end

# Phoenix has 𝑛 coins with weights 21,22,…,2𝑛. He knows that 𝑛 is even.

# He wants to split the coins into two piles such that each pile has exactly 𝑛2 coins and the difference of weights
# between the two piles is minimized. Formally, let 𝑎 denote the sum of weights in the first pile, and 𝑏 denote the sum of
# weights in the second pile. Help Phoenix minimize |𝑎−𝑏|, the absolute value of 𝑎−𝑏.

# Input
# The input consists of multiple test cases. The first line contains an integer 𝑡 (1≤𝑡≤100) — the number of test cases.

# The first line of each test case contains an integer 𝑛 (2≤𝑛≤30; 𝑛 is even) — the number of coins that Phoenix has.

# Output
# For each test case, output one integer — the minimum possible difference of weights between the two piles.

# Example
# inputCopy
# 2
# 2
# 4
# outputCopy
# 2
# 6
# Note
# In the first test case, Phoenix has two coins with weights 2 and 4. No matter how he divides the coins, the difference will be 4−2=2.

# In the second test case, Phoenix has four coins of weight 2, 4, 8, and 16. It is optimal for Phoenix to place coins
# with weights 2 and 16 in one pile, and coins with weights 4 and 8 in another pile. The difference is (2+16)−(4+8)=6.

def phoenix(queries)
  queries.each do |query|
    query = query.split(' ')

    return 0 unless query.length == 1

    stack_a = 0
    stack_a_count = 0
    stack_b = 0
    stack_b_count = 0
    n = query.first.to_i

    (n).downto(1) do |operand|
      product = 2 ** operand

      if stack_b > stack_a
        if stack_a_count > stack_b_count
          stack_b_count += 1
          stack_b += product
          next
        end

        stack_a_count += 1
        stack_a += product
      else
        if stack_b_count > stack_a_count
          stack_a_count += 1
          stack_a += product
          break
        end

        stack_b_count += 1
        stack_b += product
      end
    end

    puts (stack_a - stack_b).abs
  end

  return nil
end

# Codeforces required setup
number_of_queries = gets.rstrip.to_i

queries = []

number_of_queries.times do |query|
  queries << gets.rstrip
end

result = phoenix queries
puts result


Devu is a dumb guy, his learning curve is very slow. You are supposed to teach him n subjects, the ith subject has ci chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously.Let us say that his initial per chapter learning power of a subject is x hours. In other words he can learn a chapter of a particular subject in x hours.Well Devu is not complete dumb, there is a good thing about him too. If you teach him a subject, then time required to teach any chapter of the next subject will require exactly 1 hour less than previously required (see the examples to understand it more clearly). Note that his per chapter learning power can not be less than 1 hour.You can teach him the n subjects in any possible order. Find out minimum amount of time (in hours) Devu will take to understand all the subjects and you will be free to do some enjoying task rather than teaching a dumb guy.Please be careful that answer might not fit in 32 bit data type.

The first line will contain two space separated integers n, x (1 ≤ n, x ≤ 105). The next line will contain n space separated integers: c1, c2, ..., cn (1 ≤ ci ≤ 105).

Output a single integer representing the answer to the problem.

NoteLook at the first example. Consider the order of subjects: 1, 2. When you teach Devu the first subject, it will take him 3 hours per chapter, so it will take 12 hours to teach first subject. After teaching first subject, his per chapter learning time will be 2 hours. Now teaching him second subject will take 2 × 1 = 2 hours. Hence you will need to spend 12 + 2 = 14 hours.Consider the order of subjects: 2, 1. When you teach Devu the second subject, then it will take him 3 hours per chapter, so it will take 3 × 1 = 3 hours to teach the second subject. After teaching the second subject, his per chapter learning time will be 2 hours. Now teaching him the first subject will take 2 × 4 = 8 hours. Hence you will need to spend 11 hours.So overall, minimum of both the cases is 11 hours.Look at the third example. The order in this example doesn't matter. When you teach Devu the first subject, it will take him 3 hours per chapter. When you teach Devu the second subject, it will take him 2 hours per chapter. When you teach Devu the third subject, it will take him 1 hours per chapter. In total it takes 6 hours.

#!/usr/bin/ruby
n,x=gets.split.map(&:to_i)
r=0
gets.split.map(&:to_i).sort.each_with_index{|e,i|
	r+=[x-i,1].max*e
}
p r

n,x=gets.split.map &:to_i
mas=gets.split.map(&:to_i).sort
k=0
mas.each { |m| k+=m*x; x-=1 if x!=1 }
puts k

n,m=gets.split.map{|e| e.to_i}
ans=0
gets.split.map{|e| e.to_i}.sort.each{|e|
	ans+=e*m
	m-=1
	m=1 if m<1
}
puts ans

num = gets.chomp.split
n = Integer(num[0])
x = Integer(num[1])
nums = gets.chomp.split
c = []
for i in 0...n
    c[i] = Integer(nums[i])
end

c.sort!
time = 0
for i in 0...n
    time += c[i] * x
    if x > 1
        x -= 1
    end
end
puts time

def read_ints; STDIN.gets.split.map(&:to_i); end
n,x = read_ints
a = read_ints
a.sort!
i=0
res = 0
n.times do
  res+=a[i]*x
  j = [x-1, 1]
  x = j.max
  i+=1
end
puts res

n, x = gets.split.map(&:to_i)
c = gets.split.map(&:to_i).sort
result = 0
c.each do |ci|
  result += ci * x
  x -= 1 if x > 1
end
puts result

n,x = gets.split.map(&:to_i)
c = gets.split.map(&:to_i).sort

puts c.inject([x,0]) { |now, subjects|
  [[1, now[0]-1].max, now[1] + now[0] * subjects]
}[1]

# http://codeforces.com/problemset/problem/439/B

n, x = gets.chomp.split.map(&:to_i)
c = gets.chomp.split.map(&:to_i).sort

min = 0
for i in 0..(n - 1)
  min += x * c[i]
  x -= 1 if x > 1
end

p min

class DumbGuy
  n,x = gets.chomp.split(/\s+/).map{|o| o.to_i}
  array = gets.chomp.split(/\s+/).map{|o| o.to_i}
  array.sort!
  res = 0
  for i in 0..n-1
    res += array[i] * x
    x = x - 1 < 1 ? 1 : x - 1
  end
  puts res
end


A boy named Vasya has taken part in an Olympiad. His teacher knows that in total Vasya got at least x points for both tours of the Olympiad. The teacher has the results of the first and the second tour of the Olympiad but the problem is, the results have only points, no names. The teacher has to know Vasya's chances.Help Vasya's teacher, find two numbers — the best and the worst place Vasya could have won. Note that the total results' table sorts the participants by the sum of points for both tours (the first place has the participant who has got the most points). If two or more participants have got the same number of points, it's up to the jury to assign places to them according to their choice. It is guaranteed that each participant of the Olympiad participated in both tours of the Olympiad.

The first line contains two space-separated integers n, x (1 ≤ n ≤ 105; 0 ≤ x ≤ 2·105) — the number of Olympiad participants and the minimum number of points Vasya earned. The second line contains n space-separated integers: a1, a2, ..., an (0 ≤ ai ≤ 105) — the participants' points in the first tour. The third line contains n space-separated integers: b1, b2, ..., bn (0 ≤ bi ≤ 105) — the participants' points in the second tour. The participants' points are given in the arbitrary order. It is guaranteed that Vasya was present in the Olympiad — there are two integers i, j (1 ≤ i, j ≤ n) such, that ai + bj ≥ x.

Print two space-separated integers — the best and the worst place Vasya could have got on the Olympiad.

NoteIn the first text sample all 5 participants earn 2 points each in any case. Depending on the jury's decision, Vasya can get the first (the best) as well as the last (the worst) fifth place.In the second test sample in the best case scenario Vasya wins again: he can win 12 points and become the absolute winner if the total results' table looks like that — {4:8, 6:4, 3:6, 4:4, 4:3, 5:0}.In this table all participants are sorted by decreasing points and we can see how much a participant earned in the first and in the second tour.In the worst case scenario Vasya can get the fifth place if the table looks like that — {4:8, 4:6, 6:4, 5:4, 4:3, 3:0}, and he earned 4 and 3 points in the first and second tours, correspondingly.

I =->{gets.split.map &:to_i}
n,x=I[]; a=I[]; b=I[]
a.sort!; b.sort!; r = n - 1; a.each{|ai|
	r -= 1 if ai + b[r] >= x
}
puts [1,n-r-1]*' '

n,x=gets.split.map &:to_i
a=gets.split.map &:to_i
b=gets.split.map &:to_i
a.sort!; b.sort!; r = n - 1; a.each{|ai|
	r -= 1 if ai + b[r] >= x
}
puts [1,n-r-1]*' '

n, x = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
b = gets.split.map(&:to_i)
a.sort! { |i, j| j <=> i }
b.sort!
worst = 0
j = 0;
for i in 0..a.size do
  while j < b.size && a[i] + b[j] < x do
    j = j + 1
  end
  worst += 1 if j < b.size
  j = j + 1
end

puts "1 #{worst}"

n,x=gets.split.map &:to_i
a=gets.split.map &:to_i
b=gets.split.map &:to_i
a.sort!;b.sort!;
z=0;n-=1;a.each{|_|
	if _+b[n]>=x then
		z+=1;n-=1;
	end
}
puts [1,z]*' '


The last contest held on Johnny's favorite competitive programming platform has been received rather positively. However, Johnny's rating has dropped again! He thinks that the presented tasks are lovely, but don't show the truth about competitors' skills.The boy is now looking at the ratings of consecutive participants written in a binary system. He thinks that the more such ratings differ, the more unfair is that such people are next to each other. He defines the difference between two numbers as the number of bit positions, where one number has zero, and another has one (we suppose that numbers are padded with leading zeros to the same length). For example, the difference of $$$5 = 101_2$$$ and $$$14 = 1110_2$$$ equals to $$$3$$$, since $$$0101$$$ and $$$1110$$$ differ in $$$3$$$ positions. Johnny defines the unfairness of the contest as the sum of such differences counted for neighboring participants.Johnny has just sent you the rating sequence and wants you to find the unfairness of the competition. You have noticed that you've got a sequence of consecutive integers from $$$0$$$ to $$$n$$$. That's strange, but the boy stubbornly says that everything is right. So help him and find the desired unfairness for received numbers.

The input consists of multiple test cases. The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. The following $$$t$$$ lines contain a description of test cases. The first and only line in each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^{18})$$$.

Output $$$t$$$ lines. For each test case, you should output a single line with one integer — the unfairness of the contest if the rating sequence equals to $$$0$$$, $$$1$$$, ..., $$$n - 1$$$, $$$n$$$.

NoteFor $$$n = 5$$$ we calculate unfairness of the following sequence (numbers from $$$0$$$ to $$$5$$$ written in binary with extra leading zeroes, so they all have the same length):   $$$000$$$  $$$001$$$  $$$010$$$  $$$011$$$  $$$100$$$  $$$101$$$ The differences are equal to $$$1$$$, $$$2$$$, $$$1$$$, $$$3$$$, $$$1$$$ respectively, so unfairness is equal to $$$1 + 2 + 1 + 3 + 1 = 8$$$.

def solve
  n = gets.strip.to_i
  an = 0
  (0..64).each { |i|
    if !(n & (1 << i)).zero?
      an += ((1 << (i + 1)) - 1)
    end
  }
  puts an
end

gets.strip.to_i.times do
  solve
end


Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming.It's known that they have worked together on the same file for $$$n + m$$$ minutes. Every minute exactly one of them made one change to the file. Before they started, there were already $$$k$$$ lines written in the file.Every minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines.Monocarp worked in total for $$$n$$$ minutes and performed the sequence of actions $$$[a_1, a_2, \dots, a_n]$$$. If $$$a_i = 0$$$, then he adds a new line to the end of the file. If $$$a_i > 0$$$, then he changes the line with the number $$$a_i$$$. Monocarp performed actions strictly in this order: $$$a_1$$$, then $$$a_2$$$, ..., $$$a_n$$$.Polycarp worked in total for $$$m$$$ minutes and performed the sequence of actions $$$[b_1, b_2, \dots, b_m]$$$. If $$$b_j = 0$$$, then he adds a new line to the end of the file. If $$$b_j > 0$$$, then he changes the line with the number $$$b_j$$$. Polycarp performed actions strictly in this order: $$$b_1$$$, then $$$b_2$$$, ..., $$$b_m$$$.Restore their common sequence of actions of length $$$n + m$$$ such that all actions would be correct — there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence $$$[a_1, a_2, \dots, a_n]$$$ and Polycarp's — subsequence $$$[b_1, b_2, \dots, b_m]$$$. They can replace each other at the computer any number of times.Let's look at an example. Suppose $$$k = 3$$$. Monocarp first changed the line with the number $$$2$$$ and then added a new line (thus, $$$n = 2, \: a = [2, 0]$$$). Polycarp first added a new line and then changed the line with the number $$$5$$$ (thus, $$$m = 2, \: b = [0, 5]$$$).Since the initial length of the file was $$$3$$$, in order for Polycarp to change line number $$$5$$$ two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be $$$[0, 2, 0, 5]$$$ and $$$[2, 0, 0, 5]$$$. Changes $$$[0, 0, 5, 2]$$$ (wrong order of actions) and $$$[0, 5, 2, 0]$$$ (line $$$5$$$ cannot be edited yet) are not correct.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$). Then $$$t$$$ test cases follow. Before each test case, there is an empty line. Each test case contains three lines. The first line contains three integers $$$k$$$, $$$n$$$, $$$m$$$ ($$$0 \le k \le 100$$$, $$$1 \le n, m \le 100$$$) — the initial number of lines in file and lengths of Monocarp's and Polycarp's sequences of changes respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 300$$$). The third line contains $$$m$$$ integers $$$b_1, b_2, \dots, b_m$$$ ($$$0 \le b_j \le 300$$$).

For each test case print any correct common sequence of Monocarp's and Polycarp's actions of length $$$n + m$$$ or -1 if such sequence doesn't exist.

gets.to_i.times {
  gets
  k, n, m = gets.split.map!(&:to_i)
  as = gets.split.map!(&:to_i)
  bs = gets.split.map!(&:to_i)
  xs = []
  i = 0; j = 0
  while i < n || j < m
    if i < n && (as[i] <= k)
      xs << as[i]
      k += 1 if as[i] == 0
      i += 1
    elsif j < m && (bs[j] <= k)
      xs << bs[j]
      k += 1 if bs[j] == 0
      j += 1
    else
      break
    end
  end

  if i == n && j == m
    puts xs.join(' ')
  else
    p -1
  end
}

def solve(first_sec, second_sec, k)
  first_ptr = 0
  second_ptr = 0
  solution = []
  while first_ptr < first_sec.size && second_ptr < second_sec.size do
    if first_sec[first_ptr] < second_sec[second_ptr]
      return -1 if first_sec[first_ptr] > k
      solution << first_sec[first_ptr]
      first_ptr += 1
    else
      return -1 if second_sec[second_ptr] > k
      solution << second_sec[second_ptr]
      second_ptr += 1
    end
    k += 1 if solution[-1] == 0
  end

  while first_ptr < first_sec.size do
    return -1 if first_sec[first_ptr] > k
    solution << first_sec[first_ptr]
    first_ptr += 1
    k += 1 if solution[-1] == 0
  end

  while second_ptr < second_sec.size do
    return -1 if second_sec[second_ptr] > k
    solution << second_sec[second_ptr]
    second_ptr += 1
    k += 1 if solution[-1] == 0
  end

  solution.join(' ')
end

t = gets.chomp.to_i
t.times do
  gets
  k, _ = gets.chomp.split(' ').map(&:to_i)
  first_sec = gets.chomp.split(' ').map(&:to_i)
  second_sec = gets.chomp.split(' ').map(&:to_i)

  puts "#{solve(first_sec, second_sec, k)}\n"
end


Mike and Ann are sitting in the classroom. The lesson is boring, so they decided to play an interesting game. Fortunately, all they need to play this game is a string $$$s$$$ and a number $$$k$$$ ($$$0 \le k < |s|$$$).At the beginning of the game, players are given a substring of $$$s$$$ with left border $$$l$$$ and right border $$$r$$$, both equal to $$$k$$$ (i.e. initially $$$l=r=k$$$). Then players start to make moves one by one, according to the following rules: A player chooses $$$l^{\prime}$$$ and $$$r^{\prime}$$$ so that $$$l^{\prime} \le l$$$, $$$r^{\prime} \ge r$$$ and $$$s[l^{\prime}, r^{\prime}]$$$ is lexicographically less than $$$s[l, r]$$$. Then the player changes $$$l$$$ and $$$r$$$ in this way: $$$l := l^{\prime}$$$, $$$r := r^{\prime}$$$. Ann moves first. The player, that can't make a move loses.Recall that a substring $$$s[l, r]$$$ ($$$l \le r$$$) of a string $$$s$$$ is a continuous segment of letters from s that starts at position $$$l$$$ and ends at position $$$r$$$. For example, "ehn" is a substring ($$$s[3, 5]$$$) of "aaaehnsvz" and "ahz" is not.Mike and Ann were playing so enthusiastically that they did not notice the teacher approached them. Surprisingly, the teacher didn't scold them, instead of that he said, that he can figure out the winner of the game before it starts, even if he knows only $$$s$$$ and $$$k$$$.Unfortunately, Mike and Ann are not so keen in the game theory, so they ask you to write a program, that takes $$$s$$$ and determines the winner for all possible $$$k$$$.

The first line of the input contains a single string $$$s$$$ ($$$1 \leq |s| \leq 5 \cdot 10^5$$$) consisting of lowercase English letters.

Print $$$|s|$$$ lines. In the line $$$i$$$ write the name of the winner (print Mike or Ann) in the game with string $$$s$$$ and $$$k = i$$$, if both play optimally

require 'stringio'
io = StringIO.new

str = gets.chomp

min_c = 'zz'

str.split('').each do |c|
	if c > min_c
		io.puts "Ann"
	else
		io.puts "Mike"
		min_c = c
	end
end

print io.string

require 'stringio'
io = StringIO.new

str = gets.chomp

min_c = 'z'.next

str.split('').each do |c|
	if c > min_c
		io.puts "Ann"
	else
		io.puts "Mike"
		min_c = c
	end
end

print io.string

str = gets.chomp
ks = str.length

ks.times do |k|
	l = r = k

	start = "Ann"

	while true
		if start == "Ann"
			start = "Mike"
		else
			start = "Ann"
		end

		if (l <= 0 || r >= str.length)
			p start
			break
		end

		old_str = str[l..r]

		if l - 1 > 0
			l_str = str[l-1..r]
		end

		if r + 1 < str.length
			r_str = str[l..r+1]
		end

		if (l_str.nil? && r_str.nil?) || ((l_str && l_str > old_str) && (r_str && r_str > old_str))
			p start
			break
		end

		if l_str && r_str
			if l_str < r_str
				l = l-1
			else
				r = r+1
			end
		else
			l = l-1 if l_str && r_str.nil?
			r = r+1 if r_str && l_str.nil?
		end

	end
end


Maxim wants to buy some games at the local game shop. There are $$$n$$$ games in the shop, the $$$i$$$-th game costs $$$c_i$$$.Maxim has a wallet which can be represented as an array of integers. His wallet contains $$$m$$$ bills, the $$$j$$$-th bill has value $$$a_j$$$.Games in the shop are ordered from left to right, Maxim tries to buy every game in that order.When Maxim stands at the position $$$i$$$ in the shop, he takes the first bill from his wallet (if his wallet is empty then he proceeds to the next position immediately) and tries to buy the $$$i$$$-th game using this bill. After Maxim tried to buy the $$$n$$$-th game, he leaves the shop.Maxim buys the $$$i$$$-th game if and only if the value of the first bill (which he takes) from his wallet is greater or equal to the cost of the $$$i$$$-th game. If he successfully buys the $$$i$$$-th game, the first bill from his wallet disappears and the next bill becomes first. Otherwise Maxim leaves the first bill in his wallet (this bill still remains the first one) and proceeds to the next game.For example, for array $$$c = [2, 4, 5, 2, 4]$$$ and array $$$a = [5, 3, 4, 6]$$$ the following process takes place: Maxim buys the first game using the first bill (its value is $$$5$$$), the bill disappears, after that the second bill (with value $$$3$$$) becomes the first one in Maxim's wallet, then Maxim doesn't buy the second game because $$$c_2 > a_2$$$, the same with the third game, then he buys the fourth game using the bill of value $$$a_2$$$ (the third bill becomes the first one in Maxim's wallet) and buys the fifth game using the bill of value $$$a_3$$$.Your task is to get the number of games Maxim will buy.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$) — the number of games and the number of bills in Maxim's wallet. The second line of the input contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le 1000$$$), where $$$c_i$$$ is the cost of the $$$i$$$-th game. The third line of the input contains $$$m$$$ integers $$$a_1, a_2, \dots, a_m$$$ ($$$1 \le a_j \le 1000$$$), where $$$a_j$$$ is the value of the $$$j$$$-th bill from the Maxim's wallet.

Print a single integer — the number of games Maxim will buy.

NoteThe first example is described in the problem statement.In the second example Maxim cannot buy any game because the value of the first bill in his wallet is smaller than the cost of any game in the shop.In the third example the values of the bills in Maxim's wallet are large enough to buy any game he encounter until he runs out of bills in his wallet.

_,a,b=$<.map{|e|e.split.map &:to_i}
r=0
a.each{|e|b[r].to_i>=e&&r+=1}
p r

N, M = gets.split.map(&:to_i)
cs = gets.split.map(&:to_i)
as = gets.split.map(&:to_i)
ans = 0
cs.each do |c|
    if c <= as[0]
        ans += 1
        as.shift
        break if as.length == 0
    end
end
puts ans

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

ans = 0
j = 0

0.upto(n-1).each do |i|
  if cost[i] <= bills[j]
    ans += 1
    j += 1
  end
  break if j >= m
end

puts ans

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

ans = 0
a = as.shift
(0..n-1).each do |i|
  if a >= cs[i]
    ans += 1
    a = as.shift
  end
  break unless a
end

puts ans

n, m = gets.split.map &:to_i
c = gets.split.map &:to_i
a = gets.split.map &:to_i
ngames = 0
(0...n).each do |i|
  if a[0] && a[0] >= c[i]
    ngames += 1
    a.shift
  end
end
puts ngames

tmp=gets.split
n=tmp[0].to_i
m=tmp[1].to_i
c=gets.split
a=gets.split
i=0
j=0
ans=0
while i<n and j<m
	#puts "#{i} #{n}/ #{j} #{m}"
	a[j]=a[j].to_i
	c[i]=c[i].to_i
	#puts a[j]>c[i]
	if a[j]>=c[i]
		ans=ans+1
		j=j+1
	end
	i=i+1
end
puts ans

n,m=gets.split.map(&:to_i)
c=gets.split.map(&:to_i)
a=gets.split.map(&:to_i)
ans=0
c.each{|v|
  break if a.empty?
  if v<=a.first
    ans+=1
    a.shift
  end
}

puts ans