Alice has a cute cat. To keep her cat fit, Alice wants to design an exercising walk for her cat! Initially, Alice's cat is located in a cell $$$(x,y)$$$ of an infinite grid. According to Alice's theory, cat needs to move:   exactly $$$a$$$ steps left: from $$$(u,v)$$$ to $$$(u-1,v)$$$;  exactly $$$b$$$ steps right: from $$$(u,v)$$$ to $$$(u+1,v)$$$;  exactly $$$c$$$ steps down: from $$$(u,v)$$$ to $$$(u,v-1)$$$;  exactly $$$d$$$ steps up: from $$$(u,v)$$$ to $$$(u,v+1)$$$. Note that the moves can be performed in an arbitrary order. For example, if the cat has to move $$$1$$$ step left, $$$3$$$ steps right and $$$2$$$ steps down, then the walk right, down, left, right, right, down is valid.Alice, however, is worrying that her cat might get lost if it moves far away from her. So she hopes that her cat is always in the area $$$[x_1,x_2]\times [y_1,y_2]$$$, i.e. for every cat's position $$$(u,v)$$$ of a walk $$$x_1 \le u \le x_2$$$ and $$$y_1 \le v \le y_2$$$ holds.Also, note that the cat can visit the same cell multiple times.Can you help Alice find out if there exists a walk satisfying her wishes?Formally, the walk should contain exactly $$$a+b+c+d$$$ unit moves ($$$a$$$ to the left, $$$b$$$ to the right, $$$c$$$ to the down, $$$d$$$ to the up). Alice can do the moves in any order. Her current position $$$(u, v)$$$ should always satisfy the constraints: $$$x_1 \le u \le x_2$$$, $$$y_1 \le v \le y_2$$$. The staring point is $$$(x, y)$$$.You are required to answer $$$t$$$ test cases independently.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of testcases.  The first line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$0 \le a,b,c,d \le 10^8$$$, $$$a+b+c+d \ge 1$$$). The second line of the test case contains six integers $$$x$$$, $$$y$$$, $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$-10^8 \le x_1\le x \le x_2 \le 10^8$$$, $$$-10^8 \le y_1 \le y \le y_2 \le 10^8$$$).

For each test case, output "YES" in a separate line, if there exists a walk satisfying her wishes. Otherwise, output "NO" in a separate line.  You can print each letter in any case (upper or lower).

NoteIn the first test case, one valid exercising walk is $$$$$$(0,0)\rightarrow (-1,0) \rightarrow (-2,0)\rightarrow (-2,1) \rightarrow (-2,2)\rightarrow (-1,2)\rightarrow(0,2)\rightarrow (0,1)\rightarrow (0,0) \rightarrow (-1,0)$$$$$$

gets.to_i.times do
 left, right, down, up  = gets.split(' ').map(&:to_i)
 start_x, start_y, min_x, min_y, max_x, max_y = gets.split(' ').map(&:to_i)

 if (start_x - left + right).between?(min_x, max_x) &&
  (start_y - down + up).between?(min_y, max_y) &&
  (min_x < max_x || left + right == 0) &&
  (min_y < max_y || down + up == 0)
  puts "Yes"
 else
  puts "No"
 end
end

gets.to_i.times do
 moves = gets.split(' ').map(&:to_i)
 points = gets.split(' ').map(&:to_i)

 left = moves[0]
 right = moves[1]
 down = moves[2]
 up = moves[3]

 start_x, start_y = points[0], points[1]
 min_x, min_y = points[2], points[3]
 max_x, max_y = points[4], points[5]

 if ((start_x - left + right).between?(min_x, max_x) && (min_x < max_x || left + right == 0)) &&
  ((start_y - down + up).between?(min_y, max_y)) && (min_y < max_y || down + up == 0)

  puts "Yes"
 else
  puts "No"
 end
end

n = gets.chomp.to_i

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

  x,y,x1,y1,x2,y2 = gets.chomp.split.map(&:to_i)

  if x1 == x2 && (a > 0 || b > 0)
    puts 'No'
    next
  end

  if y1 == y2 && (c > 0 || d > 0)
    puts 'No'
    next
  end

  x += b - a
  y += d - c
  if x1 <= x && x <= x2 && y1 <= y && y <= y2
    puts 'Yes'
  else
    puts 'No'
  end
end

t = gets.to_i
t.times do
  a, b, c, d = gets.split.map(&:to_i)
  x, y, x1, y1, x2, y2 = gets.split.map(&:to_i)
  ok = true
  ok = false unless (x1..x2).include?(x - a + b)
  ok = false unless (y1..y2).include?(y - c + d)
  ok = false if (a + b > 0) && (x1 == x2)
  ok = false if (c + d > 0) && (y1 == y2)
  puts ok ? "YES" : "NO"
end

def solve(d,r)
  d > r
end

t = gets.to_i

t.times do

  l, r, d, u = gets.split.map(&:to_i)
  x, y, xl, yd, xr, yu = gets.split.map(&:to_i)

  rr = xr - x
  ll = x - xl
  uu = yu - y
  dd = y - yd

  m = rr
  m = ll if m > ll
  m = uu if m > uu
  m = dd if m > dd

  if l < r
    if solve(r-l, rr)
      puts "No"
      next
    end
  elsif l > r
    if solve(l-r, ll)
      puts "No"
      next
    end
  elsif l == r && l > 0
    if ll == 0 && rr == 0
      puts "No"
      next
    end
  end

  if d < u
    if solve(u-d,uu)
      puts "No"
      next
    end
  elsif d > u
    if solve(d-u,dd)
      puts "No"
      next
    end
  elsif d == u && d > 0
    if dd == 0 && uu == 0
      puts "No"
      next
    end
  end

  puts "Yes"
end

def solve(d,r)
  d > r
end

t = gets.to_i

t.times do

  l, r, d, u = gets.split.map(&:to_i)
  x, y, xl, yd, xr, yu = gets.split.map(&:to_i)

  rr = xr - x
  ll = x - xl
  uu = yu - y
  dd = y - yd

  m = rr
  m = ll if m > ll
  m = uu if m > uu
  m = dd if m > dd

  if l < r
    if solve(r-l, rr)
      puts "No"
      next
    end
  elsif l > r
    if solve(l-r, ll)
      puts "No"
      next
    end
  elsif l == r && l > 0
    if ll == 0 || rr == 0
      puts "No"
      next
    end
  end

  if d < u
    if solve(u-d,uu)
      puts "No"
      next
    end
  elsif d > u
    if solve(d-u,dd)
      puts "No"
      next
    end
  elsif d == u && d > 0
    if dd == 0 || uu == 0
      puts "No"
      next
    end
  end

  puts "Yes"
end


Efim just received his grade for the last test. He studies in a special school and his grade can be equal to any positive decimal fraction. First he got disappointed, as he expected a way more pleasant result. Then, he developed a tricky plan. Each second, he can ask his teacher to round the grade at any place after the decimal point (also, he can ask to round to the nearest integer). There are t seconds left till the end of the break, so Efim has to act fast. Help him find what is the maximum grade he can get in no more than t seconds. Note, that he can choose to not use all t seconds. Moreover, he can even choose to not round the grade at all.In this problem, classic rounding rules are used: while rounding number to the n-th digit one has to take a look at the digit n + 1. If it is less than 5 than the n-th digit remain unchanged while all subsequent digits are replaced with 0. Otherwise, if the n + 1 digit is greater or equal to 5, the digit at the position n is increased by 1 (this might also change some other digits, if this one was equal to 9) and all subsequent digits are replaced with 0. At the end, all trailing zeroes are thrown away.For example, if the number 1.14 is rounded to the first decimal place, the result is 1.1, while if we round 1.5 to the nearest integer, the result is 2. Rounding number 1.299996121 in the fifth decimal place will result in number 1.3.

The first line of the input contains two integers n and t (1 ≤ n ≤ 200 000, 1 ≤ t ≤ 109) — the length of Efim's grade and the number of seconds till the end of the break respectively. The second line contains the grade itself. It's guaranteed that the grade is a positive number, containing at least one digit after the decimal points, and it's representation doesn't finish with 0.

Print the maximum grade that Efim can get in t seconds. Do not print trailing zeroes.

NoteIn the first two samples Efim initially has grade 10.245. During the first second Efim can obtain grade 10.25, and then 10.3 during the next second. Note, that the answer 10.30 will be considered incorrect.In the third sample the optimal strategy is to not perform any rounding at all.

n, t = gets.split.map(&:to_i)
s = gets.chomp
dot_ind = s.index('.')
a = s.chars.map(&:to_i)
ind = a[dot_ind..-1].index{|x| x >= 5}
if ind.nil?
  puts s
  exit
end
ind += dot_ind
while ind > dot_ind && t > 0 && a[ind] >= 5
  if ind == dot_ind + 1
    i = ind - 2
    while a[i] == 9 && i >= 0
      a[i] = 0
      if i.zero?
        a.insert(0, 0)
        ind += 1
        dot_ind += 1
        break
      end
      i -= 1
    end
    a[i] += 1
  else
    a[ind - 1] += 1
  end
  ind -= 1
  t -= 1
end
a[dot_ind] = ind == dot_ind ? '' : '.'
puts a[0..ind].join

n, t = gets.split.map(&:to_i)
s = gets.chomp
dot_ind = s.index('.')
a = s.chars.map(&:to_i)
ind = a[dot_ind..-1].index{|x| x >= 5}
if ind.nil?
  puts s
  exit
end
ind += dot_ind
p a, dot_ind, ind
while ind > dot_ind && t > 0 && a[ind] >= 5
  if ind == dot_ind + 1
    i = ind - 2
    while a[i] == 9 && i >= 0
      if i.zero?
        a.insert(0, 0)
        ind += 1
        dot_ind += 1
      end
      a[i] = 0
      i -= 1
    end
    a[i] += 1
  else
    a[ind - 1] += 1
  end
  ind -= 1
  t -= 1
end
a[dot_ind] = ind == dot_ind ? '' : '.'
puts a[0..ind].join

n, t = gets.split.map(&:to_i)
s = gets.chomp
dot_ind = s.index('.')
a = s.chars.map(&:to_i)
ind = s[dot_ind..-1].chars.find_index{|x| x.to_i >= 5}
if ind.nil?
  puts s
  exit
end
ind += dot_ind
while ind > dot_ind && t > 0 && a[ind] >= 5
  a[ind - (ind == dot_ind + 1 ? 2 : 1)] += 1
  ind -= 1
  t -= 1
end
a[dot_ind] = ind == dot_ind ? '' : '.'
puts a[0..ind].join

n, t = gets.split.map(&:to_i)
s = gets.chomp
ind = s.each_char.with_index.find{|x, y| x.to_i >= 5}[1]
(ind - 1).downto(0) do |i|
  next if s[i] == '.'
  t -= 1
  c = s[i].to_i + 1
  s = s[0..i - 1] + c.to_s
  break if c < 5 || t <= 0
end
puts s
# dot_ind = a.find{|x, y| x == '.'}[1]
# p dot_ind

n, t = gets.split.map(&:to_i)
s = gets.chomp
dot_ind = s.index('.')
a = s.chars.map(&:to_i)
ind = a[dot_ind..-1].index{|x| x >= 5}
if ind.nil?
  puts s
  exit
end
ind += dot_ind
while ind > dot_ind && t > 0 && a[ind] >= 5
  if ind == dot_ind + 1
    i = ind - 2
    while a[i] == 9 && i >= 0
      if i.zero?
        a.insert(0, 0)
        ind += 1
        dot_ind += 1
      end
      a[i] = 0
      i -= 1
    end
    a[i] += 1
  else
    a[ind - 1] += 1
  end
  ind -= 1
  t -= 1
end
a[dot_ind] = ind == dot_ind ? '' : '.'
puts a[0..ind].join

n, t = gets.split.map(&:to_i)
s = gets.chomp
dot_ind = s.index('.')
ind = s[dot_ind..-1].chars.find_index{|x| x.to_i >= 5} || 0
ind -= 1
f = s.to_f
while ind >= 0 && t > 0 && f.to_s[dot_ind + ind + 1].to_i >= 5
  f = f.round(ind)
  ind -= 1
  t -= 1
end
p f

n, t = gets.split.map(&:to_i)
s = gets.chomp
dot_ind = s.index('.')
a = s.chars.map(&:to_i)
ind = s[dot_ind..-1].chars.find_index{|x| x.to_i >= 5}
if ind.nil?
  puts s
  exit
end
ind += dot_ind
while ind > dot_ind && t > 0 && a[ind] >= 5
  if ind == dot_ind + 1
    i = ind - 2
    while a[i] == 9
      a[i] = 0
      i -= 1
    end
    a[i] += 1
  else
    a[ind - 1] += 1
  end
  ind -= 1
  t -= 1
end
a[dot_ind] = ind == dot_ind ? '' : '.'
puts a[0..ind].join


One day, little Vasya found himself in a maze consisting of (n + 1) rooms, numbered from 1 to (n + 1). Initially, Vasya is at the first room and to get out of the maze, he needs to get to the (n + 1)-th one.The maze is organized as follows. Each room of the maze has two one-way portals. Let's consider room number i (1 ≤ i ≤ n), someone can use the first portal to move from it to room number (i + 1), also someone can use the second portal to move from it to room number pi, where 1 ≤ pi ≤ i.In order not to get lost, Vasya decided to act as follows.   Each time Vasya enters some room, he paints a cross on its ceiling. Initially, Vasya paints a cross at the ceiling of room 1.  Let's assume that Vasya is in room i and has already painted a cross on its ceiling. Then, if the ceiling now contains an odd number of crosses, Vasya uses the second portal (it leads to room pi), otherwise Vasya uses the first portal. Help Vasya determine the number of times he needs to use portals to get to room (n + 1) in the end.

The first line contains integer n (1 ≤ n ≤ 103) — the number of rooms. The second line contains n integers pi (1 ≤ pi ≤ i). Each pi denotes the number of the room, that someone can reach, if he will use the second portal in the i-th room.

Print a single number — the number of portal moves the boy needs to go out of the maze. As the number can be rather large, print it modulo 1000000007 (109 + 7).

def f(x)
  if @d[x] != nil
    return @d[x]
  end
  sum = 1
  for i in @p[x]..x - 1
    sum += f(i)
  end
  sum += 1
  @d[x] = sum
  sum
end

n = Integer gets
@p = gets.split.map { |x| (Integer x) - 1 }
@d = Array.new(n, nil)
@d[0] = 2
sum = 0
for i in 0..n - 1
  sum += f i
end
puts sum % (10 ** 9 + 7)

gets
dp,arr=[0],gets.split.map(&:to_i)
arr.each_with_index{|i,k|dp[k+1]=(dp[k]*2-dp[i-1]+2)%1000000007}
p dp[-1]

MOD = 1000000007
n = STDIN.readline.to_i
p = [0] + STDIN.readline.split.map { |x| x.to_i }

f = Array.new(n+2,0)
2.upto(n+1) do |i|
	f[i] = f[i-1]+1
	t = i-1
	while p[t] != t ;
		f[i] += f[t]-f[p[t]+1]+2
		flag = true
		t = p[t]
	end
	f[i] += 1
	f[i] %= MOD
end

print f[n+1]


There was an electronic store heist last night.All keyboards which were in the store yesterday were numbered in ascending order from some integer number $$$x$$$. For example, if $$$x = 4$$$ and there were $$$3$$$ keyboards in the store, then the devices had indices $$$4$$$, $$$5$$$ and $$$6$$$, and if $$$x = 10$$$ and there were $$$7$$$ of them then the keyboards had indices $$$10$$$, $$$11$$$, $$$12$$$, $$$13$$$, $$$14$$$, $$$15$$$ and $$$16$$$.After the heist, only $$$n$$$ keyboards remain, and they have indices $$$a_1, a_2, \dots, a_n$$$. Calculate the minimum possible number of keyboards that have been stolen. The staff remember neither $$$x$$$ nor the number of keyboards in the store before the heist.

The first line contains single integer $$$n$$$ $$$(1 \le n \le 1\,000)$$$ — the number of  keyboards in the store that remained after the heist. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^{9})$$$ — the indices of the remaining keyboards. The integers $$$a_i$$$ are given in arbitrary order and are pairwise distinct.

Print the minimum possible number of keyboards that have been stolen if the staff remember neither $$$x$$$ nor the number of keyboards in the store before the heist.

NoteIn the first example, if $$$x=8$$$ then minimum number of stolen keyboards is equal to $$$2$$$. The keyboards with indices $$$9$$$ and $$$11$$$ were stolen during the heist.In the second example, if $$$x=4$$$ then nothing was stolen during the heist.

n,*a=$<.read.split.map &:to_i
p a.max-a.min+1-n

# TEMPLATE BEGIN
def read_vector
    gets.chomp.split(/\s+/)
end
def read_vector_int
    read_vector.map(&:to_i)
end
# TEMPLATE END

gets
a = read_vector_int
puts a.max - a.min - a.size + 1

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

ans = 0
sz =ary.size

1.upto(sz-1).each do |i|
  ans += (ary[i] - ary[i-1] - 1)
end

puts ans

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

puts as[-1] - as[0] - n + 1

remain_keyborads = gets.chomp.to_i
values = gets.chomp

remain_keybord_indicies = values.split(' ')
remain_keybord_indicies.map!(&:to_i)

max = remain_keybord_indicies.max
min = remain_keybord_indicies.min

puts max - min - remain_keyborads + 1

gets
a = gets.split.map(&:to_i).sort
i = 1
ans = 0
while i < a.size
    ans += a[i] - a[i - 1] - 1
    i += 1
end
puts ans

n,*a=$<.read.split.map &:to_i
p n-a.max+a.min-1


Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.For simplicity, let us assume that Volodya's text can be represented as a single string.

Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.

Print exactly one number — the number of powerful substrings of the given string. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal".

#!/usr/bin/env ruby
str = gets
harr = []
marr = []
index = -1
loop do
  index = str.index('heavy', index + 1)
  break unless index
  harr << index
end
index = -1
loop do
  index = str.index('metal', index + 1)
  break unless index
  marr << index
end
ret = 0
match = 0
harr.each do |hi|
  find = false
  for i in match...marr.size
    match = i
    if marr[i] > hi
      find = true
      break
    end
  end
  ret += marr.size - match if find
end
puts ret

def get_pos(s, ss)
  x, l = [], ss.length
  i = -l
  while true
    i = s.index(ss, i + l)
    break if i.nil?
    x << i
  end
  x
end

s = gets.chomp
x = get_pos(s, "heavy")
y = get_pos(s, "metal")
total, pox, poy, sx, sy = 0, 0, 0, x.size, y.size
while pox < sx
  poy += 1 while poy < sy && y[poy] < x[pox]
  total += sy - poy
  pox += 1
end
puts total

input = gets.chomp
heavy = 0
itr = 0
len = input.length
ans = 0

until itr >= len
	if input[itr] == 'h'
		if input[itr..(itr+4)] == "heavy"
			heavy += 1
			itr += 5
		else itr += 1
		end
	elsif input[itr] == 'm'
		if input[itr..(itr+4)] == "metal"
			ans += heavy
			itr += 5
		else 	itr += 1
		end
	else
		itr += 1
	end
end

puts ans

s = gets.strip
h = []
m = []
offset = 0

while n = s.index("heavy", offset) do
  h << n
  offset = n + 1
end

if h.size == 0 then
  puts 0
  exit
end

offset = 0
total = 0
h_idx = -1
while n = s.index("metal", offset) do
  while h_idx+1 < h.size and h[h_idx+1] < n do
    h_idx += 1
  end
  total += h_idx + 1
  offset = n + 1
end

puts total

S = gets.chomp

h   = 0
ans = 0

(0...S.length).each do |i|

  h   += 1 if S[i,5] == "heavy"
  ans += h if S[i,5] == "metal"

end

puts ans

s = gets

res = 0
i=-1
h = []
loop do
  i = s.index('heavy', i+1)
  break if i.nil?
  h << i
end

i=-1
j=0
loop do
  i = s.index('metal', i+1)
  break if i.nil?

  while j < h.size and h[j] < i
    j+=1
  end
  res += j
end

puts res

#! ruby -Ku
# -*- coding: UTF-8 -*-
a = gets

str_front = "heavy"
str_rear = "metal"

count_front = 0
sum_substring = 0

offset_front = 0
offset_rear = 0
while true
  offset_front_temp = a.index(str_front, offset_front)
  offset_rear_temp = a.index(str_rear, offset_rear)
  if offset_front_temp == nil
    offset_front_temp = 10 ** 6
    offset_front = 10 ** 6
  end
  if offset_rear_temp == nil
    break
  end
  if offset_front_temp < offset_rear_temp
    count_front += 1
    offset_front = offset_front_temp + 4
  else
    sum_substring += count_front
    offset_rear = offset_rear_temp + 4
  end
end

puts sum_substring

#!/usr/bin/env ruby

def get_pos(s, ss)
	x, l = [], ss.length
	i = -l
	while true
		i = s.index(ss, i + l)
		break if i.nil?
		x << i
	end
	x
end

s = gets.chomp
x = get_pos(s, "heavy")
y = get_pos(s, "metal")
tot, px, py, sx, sy = 0, 0, 0, x.size, y.size
while px < sx
	py += 1 while py < sy && y[py] < x[px]
	tot += sy - py
	px += 1
end
puts tot

#!/usr/bin/env ruby

def get_pos(s, ss)
	x, ls, lss = [], s.length, ss.length
	ls.times { |i| x << i if s[i..i+lss-1] == ss }
	x
end

s = gets.chomp
x = get_pos(s, "heavy")
y = get_pos(s, "metal")
tot, px, py, sx, sy = 0, 0, 0, x.size, y.size
while px < sx
	py += 1 while py < sy && y[py] < x[px]
	tot += sy - py
	px += 1
end
puts tot

s = gets
count = 0
heavy = 0
for i in 0..s.length-5
	if s[i..i+4] == "heavy"
		heavy += 1
	end

	if s[i..i+4] == "metal"
		count += heavy
	end
end

puts count

#!/usr/bin/env ruby
str = gets
harr = []
marr = []
index = -1
loop do
  index = str.index('heavy', index + 1)
  break unless index
  harr << index
end
index = -1
loop do
  index = str.index('metal', index + 1)
  break unless index
  marr << index
end
ret = 0
harr.each do |hi|
  match = 0
  for i in match...marr.size
    match = i
    break if marr[i] >= hi
  end
  ret += marr.size - match
end
puts ret

def get_pos(s,ss)
  x, l = [],ss.length
  i = -l
  while true
    i = s.index(ss,i+1)
    break if i.nil?
    x << i
  end
  x
end

s = gets.chomp
x = get_pos(s,"heavy")
y = get_pos(s,"metal")
total,pox,poy,sx,sy = 0,0,0,x.size,y.size
while pox < sx
  py += 1 while poy < sy && y[poy] < x[pox]
  total += sy - poy
  pox += 1
end
puts total

def get_pos(s,ss)
  x, l = [],ss.length
  i = -l
  while true
    i = s.index(ss,i+1)
    break if i.nil?
    x << i
  end
  x
end

s = gets.chomp
x = get_pos(s,"heavy")
y = get_pos(s,"metal")
total,pox,poy,sx,sy = 0,0,0,x.size,y.size
while pox < sx
  py += 1 while poy < sy && y[py] < x[pox]
  total += sy - poy
  pox += 1
end
puts total

#! ruby -Ku
# -*- coding: UTF-8 -*-
a = gets
# puts a

str_front = "heavy"
str_rear = "metal"

offset_front = a.index(str_front)
offset_front_array = [a.index(str_front)]
while offset_front != nil
  offset_front = a.index(str_front, offset_front + 1)
  offset_front_array << offset_front
end

offset_rear = a.index(str_rear)
offset_rear_array = [a.index(str_rear)]
while offset_rear != nil
  offset_rear = a.index(str_rear, offset_rear + 1)
  offset_rear_array << offset_rear
end

# puts offset_front_array
# puts offset_rear_array

count_front = 0
sum_substring = 0

offset_rear = offset_rear_array.first
while offset_rear != nil
  count_front += 1
  val_front = offset_front_array.shift
  val2_front = offset_front_array.first
  offset_rear = offset_rear_array.shift
  if offset_rear == nil
    break
  elsif val2_front == nil
    while offset_rear != nil
      sum_substring += count_front
      offset_rear = offset_rear_array.shift
    end
  else
    while val_front < offset_rear && offset_rear < val2_front
      sum_substring += count_front
      offset_rear = offset_rear_array.first
      if offset_rear == nil
        break
      end
    end
  end
end

puts sum_substring

#! ruby -Ku
# -*- coding: UTF-8 -*-
a = gets

str_front = "heavy"
str_rear = "metal"

offset_front = a.index(str_front)
offset_front_array = [a.index(str_front)]
while offset_front != nil
  offset_front = a.index(str_front, offset_front + 1)
  offset_front_array << offset_front
end

offset_rear = a.index(str_rear)
offset_rear_array = [a.index(str_rear)]
while offset_rear != nil
  offset_rear = a.index(str_rear, offset_rear + 1)
  offset_rear_array << offset_rear
end

# puts offset_front_array
# puts offset_rear_array

count_front = 0
sum_substring = 0

while (offset_rear = offset_rear_array.first) != nil
  count_front += 1
  interval_front = offset_front_array.first(2)
  first_front = interval_front.shift
  second_front = interval_front.shift
  if first_front == nil
    first_front = -1
  end
  if second_front == nil
    second_front = 10**6
  end
  while (first_front < offset_rear) && (offset_rear < second_front)
    sum_substring += count_front
    offset_rear_array.shift
    offset_rear = offset_rear_array.first
    if offset_rear == nil
      break
    end
  end
  offset_front_array.shift
end

puts sum_substring

s = gets
count = 0
for i in (0..s.length) do
	a = s.index("heavy", i)
	if a and a == i
		b = s.index("metal", i)
		if b and b > a
			count = count + 1
		end
	end
end

print count


Boboniu likes bit operations. He wants to play a game with you.Boboniu gives you two sequences of non-negative integers $$$a_1,a_2,\ldots,a_n$$$ and $$$b_1,b_2,\ldots,b_m$$$.For each $$$i$$$ ($$$1\le i\le n$$$), you're asked to choose a $$$j$$$ ($$$1\le j\le m$$$) and let $$$c_i=a_i\& b_j$$$, where $$$\&$$$ denotes the bitwise AND operation. Note that you can pick the same $$$j$$$ for different $$$i$$$'s.Find the minimum possible $$$c_1 | c_2 | \ldots | c_n$$$, where $$$|$$$ denotes the bitwise OR operation.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1\le n,m\le 200$$$). The next line contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$0\le a_i < 2^9$$$). The next line contains $$$m$$$ integers $$$b_1,b_2,\ldots,b_m$$$ ($$$0\le b_i < 2^9$$$).

Print one integer: the minimum possible $$$c_1 | c_2 | \ldots | c_n$$$.

n,m = gets.chomp.split(" ").map(&:to_i)
a = gets.chomp.split(" ").map(&:to_i)
b = gets.chomp.split(" ").map(&:to_i)
aandb = Array.new(n){Array.new(m)}
bit = Array.new(n){Array.new(10,0)}
n.times do |i|
  m.times do |j|
    aandb[i][j] = a[i]&b[j]
    9.downto(0) do |k|
      bit[i][k] += 1 if aandb[i][j][k] == 1
    end
  end
end
ans = ""
9.downto(0) do |i|
  judge = false
  n.times do |j|
    if bit[j][i] == aandb[j].length
      judge = true
      break
    end
  end
  if judge
    ans = ans + "1"
  else
    ans = ans + "0"
    n.times do |j|
      m.times do |k|
        if aandb[j][k][i] == 1
          9.downto(0) do |l|
            if aandb[j][k][l] == 0
              bit[j][l] += 1
            end
          end
          aandb[j][k] = 2 ** 9 - 1
        end
      end
    end
  end
end
puts ans.to_i(2)


Let's call a positive integer $$$n$$$ ordinary if in the decimal notation all its digits are the same. For example, $$$1$$$, $$$2$$$ and $$$99$$$ are ordinary numbers, but $$$719$$$ and $$$2021$$$ are not ordinary numbers.For a given number $$$n$$$, find the number of ordinary numbers among the numbers from $$$1$$$ to $$$n$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. Each test case is characterized by one integer $$$n$$$ ($$$1 \le n \le 10^9$$$).

For each test case output the number of ordinary numbers among numbers from $$$1$$$ to $$$n$$$.

results = []

t = gets.chomp
(1..t.to_i).each do |iteration|
	n = gets.chomp.to_i
	c = 0
	if n > 9
		rz = n.to_s.length
		c += 9 * (rz - 1)
		high_rz = n.to_s[0].to_i
		c += high_rz
		c -= 1 if n < (high_rz.to_s * rz).to_i
	else
		c = n % 10
	end
	results.push(c)
end
results.each do |res|
	puts res
end

def find_ordinaries(n)
	if(n < 10)
		return n
	end
	num_of_zeroes = find_num_of_0s(n)
	i = 0
	j = build_j(num_of_zeroes, n)
	i = j
	first_dig = 10**num_of_zeroes
	change_first = 10**num_of_zeroes
	ordinaries = num_of_zeroes * 9
	while(true)
		if(first_dig + j <= n)
			ordinaries += 1
		else
			break
		end
		j = j + i
		first_dig += change_first
	end
	return ordinaries
end

def find_num_of_0s(n)
	num_of_zeroes = 0
	while(true)
		n = n / 10
		num_of_zeroes += 1
		if(n  < 1)
			num_of_zeroes -= 1
			break
		end
	end
	return num_of_zeroes
end

def build_j(zeroes, n)
	i = zeroes
	j = 0
	while(i != 0)
		j += 10**(zeroes - i)
		i -= 1
	end
	return j
end

test_cases = gets.to_i
test_case_tab = []

until(test_case_tab.size == test_cases)
	test_case_tab.push(gets.to_i)
end

test_case_tab.each do|val|
	ord = find_ordinaries(val)
	puts ord
end

gets.to_i.times {
  n = gets.to_i
  ans = 0
  (1..9).each { |d|
    c = d
    while c <= n
      ans += 1
      c = c * 10 + d
    end
  }
  p ans
}

# @type [Integer]
t = gets.chomp.to_i

def test_number
  # @type [Integer]
  n = gets.chomp.to_i

  if n < 10
    n
  else
    num_sets = (Math.log10 n).floor

    (9 * num_sets) + count_remaining_normals(n, num_sets + 1)
  end
end

def count_remaining_normals(number, num_digits)
  # @type [String]
  digits = number.to_s

  close_guess = digits[0].to_i
  nearest_boundary = Array.new(num_digits, digits[0]).join.to_i

  if digits.chars.uniq.length == 1 || number > nearest_boundary
    # Number is ON the boundary, 222 for example
    close_guess
  else
    # Number is under the boundary, 200 for example
    close_guess - 1
  end
end

(1..t).each do
  puts test_number
end

def ordinary_cnt(n)
  if n < 10
    return n
  end
  n_str = n.to_s
  x = (n_str[0 .. 0] * n_str.size).to_i
  if n >= x
    return n_str[0 .. 0].to_i + ordinary_cnt(("9" * (n_str.size - 1)).to_i)
  else
    return n_str[0 .. 0].to_i - 1 + ordinary_cnt(("9" * (n_str.size - 1)).to_i)
  end
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  printf("%d\n", ordinary_cnt(n))
end

results = []

t = gets.chomp
(1..t.to_i).each do |iteration|
	n = gets.chomp.to_i
	c = 0
	if n > 9
		c += n.to_s[-2..-1].to_i/11 + 9
		c += 9*(n/100) if n > 99
	else
		c = n % 10
	end
	results.push(c)
end
results.each do |res|
	puts res
end

results = []

t = gets.chomp
(1..t.to_i).each do |iteration|
	n = gets.chomp.to_i
	c = 0
	if n > 9
		rzrd = n.to_s.split("").length - 2
		c = n/11 + 9
		c -= rzrd if rzrd > 0
	else
		c = n % 10
	end
	results.push(c)
end
results.each do |res|
	puts res
end

results = []

t = gets.chomp
(1..t.to_i).each do |iteration|
	n = gets.chomp.to_i
	c = 0
	if n > 9
		c = n/11 + 9
	else
		c = n % 10
	end
	results.push(c)
end
results.each do |res|
	puts res
end

def find_ordinaries(n)
	if(n < 10)
		return n
	end
	num_of_zeroes = find_num_of_0s(n)
	i = 0
	j = build_j(num_of_zeroes, n)
	ordinaries = num_of_zeroes * 9
	while(true)
		if(10**num_of_zeroes + j + i <= n)
			ordinaries += 1
		else
			break
		end
		i += 10**num_of_zeroes
		j += j
	end
	return ordinaries
end

def find_num_of_0s(n)
	num_of_zeroes = 0
	while(true)
		n = n / 10
		num_of_zeroes += 1
		if(n  < 1)
			num_of_zeroes -= 1
			break
		end
	end
	return num_of_zeroes
end

def build_j(zeroes, n)
	i = zeroes
	j = 0
	while(i != 0)
		j += 10**(zeroes - i)
		i -= 1
	end
	return j
end

test_cases = gets.to_i
test_case_tab = []

until(test_case_tab.size == test_cases)
	test_case_tab.push(gets.to_i)
end

test_case_tab.each do|val|
	ord = find_ordinaries(val)
	puts ord
end

def find_ordinaries(n)
	if(n < 10)
		return n
	end
	num_of_zeroes = find_num_of_0s(n)
	i = 0
	j = 10**(num_of_zeroes - 1) + 1
	(j == 2) ? j = 1 : j = j
	ordinaries = num_of_zeroes * 9
	while(true)
		if(10**num_of_zeroes + j + i <= n)
			ordinaries += 1
		else
			break
		end
		i += 10**num_of_zeroes
		j += 1
	end
	return ordinaries
end

def find_num_of_0s(n)
	num_of_zeroes = 0
	while(true)
		n = n / 10
		num_of_zeroes += 1
		if(n  < 1)
			num_of_zeroes -= 1
			break
		end
	end
	return num_of_zeroes
end

test_cases = gets.to_i
test_case_tab = []

until(test_case_tab.size == test_cases)
	test_case_tab.push(gets.to_i)
end

test_case_tab.each do|val|
	ord = find_ordinaries(val)
	puts ord
end

def find_ordinaries(n)
	if(n < 10)
		return n
	end
	num_of_zeroes = find_num_of_0s(n)
	i = 0
	j = 10**(num_of_zeroes - 1) + 1
	(j == 2) ? j = 1 : j = j
	ordinaries = num_of_zeroes * 9
	while(true)
		if(10**num_of_zeroes + j + i <= n)
			ordinaries += 1
			p num_of_zeroes
		else
			break
		end
		i += 10**num_of_zeroes
		j += 1
	end
	return ordinaries
end

def find_num_of_0s(n)
	num_of_zeroes = 0
	while(true)
		n = n / 10
		num_of_zeroes += 1
		if(n  < 1)
			num_of_zeroes -= 1
			break
		end
	end
	return num_of_zeroes
end

test_cases = gets.to_i
test_case_tab = []

until(test_case_tab.size == test_cases)
	test_case_tab.push(gets.to_i)
end

test_case_tab.each do|val|
	ord = find_ordinaries(val)
	puts ord
end

def find_ordinaries(n)
	if(n < 10)
		return n
	end
	num_of_zeroes = find_num_of_0s(n)
	i = 0
	ordinaries = num_of_zeroes * 9
	while(true)
		if(10**num_of_zeroes + 1 + i <= n)
			ordinaries += 1
		else
			break
		end
		i += 10**num_of_zeroes
	end
	return ordinaries
end

def find_num_of_0s(n)
	num_of_zeroes = 0
	while(true)
		n = n / 10
		num_of_zeroes += 1
		if(n  < 1)
			num_of_zeroes -= 1
			break
		end
	end
	return num_of_zeroes
end

test_cases = gets.to_i
test_case_tab = []

until(test_case_tab.size == test_cases)
	test_case_tab.push(gets.to_i)
end

test_case_tab.each do|val|
	ord = find_ordinaries(val)
	puts ord
end


You are given two arrays $$$a$$$ and $$$b$$$ of $$$n$$$ positive integers each. You can apply the following operation to them any number of times:  Select an index $$$i$$$ ($$$1\leq i\leq n$$$) and swap $$$a_i$$$ with $$$b_i$$$ (i. e. $$$a_i$$$ becomes $$$b_i$$$ and vice versa). Find the minimum possible value of $$$\max(a_1, a_2, \ldots, a_n) \cdot \max(b_1, b_2, \ldots, b_n)$$$ you can get after applying such operation any number of times (possibly zero).

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1\le n\le 100$$$) — the length of the arrays. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$) where $$$a_i$$$ is the $$$i$$$-th element of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 10\,000$$$) where $$$b_i$$$ is the $$$i$$$-th element of the array $$$b$$$.

For each test case, print a single integer, the minimum possible value of $$$\max(a_1, a_2, \ldots, a_n) \cdot \max(b_1, b_2, \ldots, b_n)$$$ you can get after applying such operation any number of times.

NoteIn the first test, you can apply the operations at indices $$$2$$$ and $$$6$$$, then $$$a = [1, 4, 6, 5, 1, 5]$$$ and $$$b = [3, 2, 3, 2, 2, 2]$$$, $$$\max(1, 4, 6, 5, 1, 5) \cdot \max(3, 2, 3, 2, 2, 2) = 6 \cdot 3 = 18$$$.In the second test, no matter how you apply the operations, $$$a = [3, 3, 3]$$$ and $$$b = [3, 3, 3]$$$ will always hold, so the answer is $$$\max(3, 3, 3) \cdot \max(3, 3, 3) = 3 \cdot 3 = 9$$$.In the third test, you can apply the operation at index $$$1$$$, then $$$a = [2, 2]$$$, $$$b = [1, 1]$$$, so the answer is $$$\max(2, 2) \cdot \max(1, 1) = 2 \cdot 1 = 2$$$.

t = gets.chomp.to_i

for i in (1..t)
    n = gets.chomp.to_i
    a = gets.chomp.split.map {|el| el.to_i}
    b = gets.chomp.split.map {|el| el.to_i}
    # maior = [a.max, b.max].max
    for j in (0..n-1)
        if a[j] < b[j]
            temp = a[j]
            a[j] = b[j]
            b[j] = temp
        end
    end
    puts a.max * b.max
end

gets.to_i.times do
  n = gets.to_i
  xs = gets.split.map(&:to_i)
  ys = gets.split.map(&:to_i)

  (0...n).each do |i|
    if ys[i] > xs[i]
      t = ys[i]
      ys[i] = xs[i]
      xs[i] = t
    end
  end

  p(xs.max * ys.max)
end


Levko loves tables that consist of n rows and n columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals k.Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them.

The single line contains two integers, n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 1000).

Print any beautiful table. Levko doesn't like too big numbers, so all elements of the table mustn't exceed 1000 in their absolute value. If there are multiple suitable tables, you are allowed to print any of them.

NoteIn the first sample the sum in the first row is 1 + 3 = 4, in the second row — 3 + 1 = 4, in the first column — 1 + 3 = 4 and in the second column — 3 + 1 = 4. There are other beautiful tables for this sample.In the second sample the sum of elements in each row and each column equals 7. Besides, there are other tables that meet the statement requirements.

n,k=gets.split.map(&:to_i)
n.times{|i|a=[0]*n;a[i]=k;puts a.join(' ')}

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

    answer = []

    n.times do |i|
      data = []
      n.times do |j|
        if i == j
          data << k
        else
          data << 0
        end
      end
      answer << data
    end

    answer.each do |ans|
      puts ans.join(' ')
    end
  end
end

a = A.new

n, k = gets.split.map(&:to_i)
n.times do |i|
  line = [1]*i +[k-n+1] + [1]*(n-1-i)
  puts line.join(" ")
end

n, k = gets.chomp.split(/ /).map(&:to_i)
base = 0
base = k / n if n.even? && k.even?
table = Array.new(n) { Array.new(n, base) }
if base == 0
    n.times do |i|
        table[i][i] = k
    end
end
table.each do |row|
    puts row.join(" ")
end

n, k = gets.chomp.split(" ").map{|i| i.to_i}

element = (k.to_f / n).ceil
n.times do |i|
  n.times do |j|
    if i == j
      print element - (element * n - k)
    else
      print element
    end
    print " " if j < n - 1
  end
  print "\n" if i < n - 1
end

n,k=gets.split.map(&:to_i)
a=[]
(n-1).times { a<<0 }
a<<k
n.times {
    puts a*' '
    a.rotate!
}

n,k = gets.split(" ").map(&:to_i)
arr = Array.new(n)
n.times do |i|
	arr[i] = []
	n.times do |j|
		if i == j
			arr[i] << k
		else
			arr[i] << 0
		end
	end
end
# puts "#{arr}"
arr.each do |a|
	puts "#{a.join(' ')}"
end

n,k = gets.chomp.split(' ').collect {|x| x.to_i}

arr = [k] + [0]*(n-1)

(1..n).each {
  puts arr.join ' '
  arr.pop
  arr = [0]+arr
}

require 'Matrix'
a,b = gets.split.map(&:to_i)
x = (Matrix.identity(a)*b).to_a
x.each do |d|
    puts d.join(' ')
end

n, k = gets.split.collect{|i| i.to_i}
s = Array.new(n){Array.new(n,k/n)}
for i in 0...n
    s[i][i] += k%n
end
s.collect{|i| puts i.join(' ')}

s = gets.split.map(&:to_i)
n = s[0]
k = s[1]
n.times do |i|
    n.times do |j|
        if i == j
            print "#{k} "
        else
            print "0 "
        end
    end
    puts
end

n, k = gets.split.map &:to_i
n.times { |i| puts ([0]*i + [k] + [0]*(n - i - 1)).join(' ') }

n, k = gets.split.map { |x| x.to_i }
for i in 0...n
  a = Array.new(n, 0)
  a[i] = k
  puts a * ' '
end

line = gets.chomp.split(" ").map { |e| e.to_i }
n = line[0]
k = line[1]
for i in 0...n
  for j in 0...n
    if (i == j)
      print(k.to_s + " ")
    else
      print("0 ")
    end
  end
  print("\n")
end

#!/usr/bin/ruby
n,k=gets.split.map(&:to_i)
a=[1]*(n-1)+[k-n+1]
n.times{|i|puts a.rotate(i)*' '}

n,k=gets.split.map &:to_i
mas=Array.new(n){Array.new(n)}
i,j=0,0
while(i<n)
  while(j<n)
    if i==j
      print "#{k} "
    else
      print "0 "
    end

    j+=1
  end
  print "\n"
  j=0
  i+=1
end

n,k = gets.chomp.split.map(&:to_i)
d = k - n + 1
n.times { |x| n.times{|y| print ( x==y ? d : 1 )," " }; puts; }

n,k = gets.chomp.split.map(&:to_i)
d = k - n + 1
a = Array.new(n) { Array.new(n) { 1 } }
n.times { |x| a[x][x]=d }
n.times { |x| n.times{|y| print "#{a[x][y]} " }; puts; }

size, sum = gets.split.map{|s| s.to_i}

size.times {|i|
	0.upto(i-1) {print "0 "}
	print "#{sum} "
	(i+1).upto(size-1) {print "0 "}
	puts "\n"
}

n, k = gets.chomp.split(" ").map{|i| i.to_i}

element = (k.to_f / n).ceil
n.times do |i|
  n.times do |j|
    if i == j
      print element - (element * n - k)
    else
      print element
    end
  end
  print "\n"
end

size, sum = gets.split.map{|s| s.to_i}

size.times {|i|
	0.upto(i-1) {print "0 "}
	print "#{sum} "
	(i+1).upto(size-2) {print "0 "}
	puts "0"
}


Bimokh is Mashmokh's boss. For the following n days he decided to pay to his workers in a new way. At the beginning of each day he will give each worker a certain amount of tokens. Then at the end of each day each worker can give some of his tokens back to get a certain amount of money. The worker can save the rest of tokens but he can't use it in any other day to get more money. If a worker gives back w tokens then he'll get  dollars. Mashmokh likes the tokens however he likes money more. That's why he wants to save as many tokens as possible so that the amount of money he gets is maximal possible each day. He has n numbers x1, x2, ..., xn. Number xi is the number of tokens given to each worker on the i-th day. Help him calculate for each of n days the number of tokens he can save.

The first line of input contains three space-separated integers n, a, b (1 ≤ n ≤ 105; 1 ≤ a, b ≤ 109). The second line of input contains n space-separated integers x1, x2, ..., xn (1 ≤ xi ≤ 109).

Output n space-separated integers. The i-th of them is the number of tokens Mashmokh can save on the i-th day.

n, a, b = gets.split.map(&:to_i)
puts gets.split.map { |x| (x.to_i - (x.to_i * a / b) * b.to_f / a).to_i }.join(" ")

n, a, b = gets.split(' ').map { |x| x.to_i }
arr = Array.new
gold = 0
answer = Array.new
while string = gets do
	string.split().each do |x|
		x = x.to_i
		#gold = ((x*a)%b)
		x = ((x*a)%b)/a
		arr << x
	end
end
arr.each do |x|
	print x
	print ' '
end

n,a,b=gets.split.map(&:to_i)
puts gets.split.map(&:to_i).collect{|x|x-(x*a/b*b+a-1)/a}.join(' ')

n, a, b = gets.split.map(&:to_i)
puts gets.split.map { |x| x.to_i * a % b }.join(" ")

n, a, b = gets.split(' ').map { |x| x.to_i }
arr = Array.new
gold = 0
answer = Array.new
while string = gets do
	string.split().each do |x|
		x = x.to_i
		gold = ((x*a)/b)
		x = x - gold*b/a
		arr << x
	end
end
arr.each do |x|
	print x
	print ' '
end

n,a,b=gets.split.map(&:to_i)
puts gets.split.map(&:to_i).collect{|x|x-x*a/b*b/a}.join(' ')

n,a,b=gets.split.map(&:to_i)
puts gets.split.map(&:to_i).collect{|x|x%b}.join(' ')


«Next please», — the princess called and cast an estimating glance at the next groom.The princess intends to choose the most worthy groom, this is, the richest one. Whenever she sees a groom who is more rich than each of the previous ones, she says a measured «Oh...». Whenever the groom is richer than all previous ones added together, she exclaims «Wow!» (no «Oh...» in this case). At the sight of the first groom the princess stays calm and says nothing.The fortune of each groom is described with an integer between 1 and 50000. You know that during the day the princess saw n grooms, said «Oh...» exactly a times and exclaimed «Wow!» exactly b times. Your task is to output a sequence of n integers t1, t2, ..., tn, where ti describes the fortune of i-th groom. If several sequences are possible, output any of them. If no sequence exists that would satisfy all the requirements, output a single number -1.

The only line of input data contains three integer numbers n, a and b (1 ≤ n ≤ 100, 0 ≤ a, b ≤ 15, n > a + b), separated with single spaces.

Output any sequence of integers t1, t2, ..., tn, where ti (1 ≤ ti ≤ 50000) is the fortune of i-th groom, that satisfies the given constraints. If no sequence exists that would satisfy all the requirements, output a single number -1.

NoteLet's have a closer look at the answer for the first sample test.   The princess said «Oh...» (highlighted in bold): 5 1 3 6 16 35 46 4 200 99.  The princess exclaimed «Wow!» (highlighted in bold): 5 1 3 6 16 35 46 4 200 99.

n, a, b = gets.split.map(&:to_i)
c = [1]
if b == 0 && a > 0
    if a == n - 1
        p -1
        exit
    else
        c << 1
    end
end
b.times{c << c.inject(&:+) + 1}
a.times{c << c.max + 1}
c << 1 while c.size < n
puts c * ' '

n,a,b=gets.split.map(&:to_i)
result=Array.new(n,1)
if a+1==n && a>0 then
        puts -1
        exit
end
b.times{|i|
        sum=0
        (i+1).times{|j|
                sum+=result[j]
        }
        result[i+1]=sum+1
}
result[0]=2 if b==0
result[1]=1 if b==0
start=b
if b>0 then
        a.times{
                result[start+1]=result[start]+1
                start+=1
        }
else
        start=1
        result[1]=2
        a.times{
                result[start+1]=result[start]+1
                start+=1
        }
        result[1]=1
end
if result[start-1]>50000 then
        puts -1
        exit
end
n.times{|i| p result[i]}

n,a,b=gets.split.map &:to_i
c=[1]
if b==0&&a>0
	if a==n-1
		p -1
		exit
	else
		c<<1
	end
end
b.times{|_|c<<2*2**_}
a.times{c<<c.max+1}
c<<1 while c.size<n
puts c*' '

n, a, b = STDIN.readline.split.map {|s| s.to_i }
result = [1]
if b == 0 and a > 0
  if a+1 == n
    puts -1
    exit
  end
  result.push(1)
end
b.times { result.push(2*result[-1]) }
a.times { result.push(result[-1]+1) }
while result.length < n
  result.push(result[-1])
end
puts result.join ' '

n, a, b = gets.split.map(&:to_i)
if n - (b > 0 ? b+1 : b) - (b > 0 ? a : ( a > 0 ? a+2:1)) < 0
  puts(-1)
else
  bb = [1] + (1..b).map {|x| 2**x}.to_a
  bb << 1 if b == 0 and a != 0
  last = bb[-1]
  a.times do |i|
    bb << bb[-1] + 1
  end
  (n-bb.size).times do
    bb << bb[-1]
  end
  puts bb*' '
end

line = gets.split
n = line[0].to_i
a = line[1].to_i
b = line[2].to_i

seq = Array.new(n)
seq[0] = 1

currSum = 1
currMax = 1
numA = 0
numB = 0
can = true

for i in 1..(n-1)
  if(numB < b)
    seq[i] = currSum + 1
	currSum = (2*currSum) + 1
	currMax = seq[i]
	numB += 1
  elsif (numA < a)
    if(currMax + 1 > currSum)
	  seq[i] = 1
	  currSum += 1
	else
	  seq[i] = currMax + 1
	  currSum += (currMax + 1)
	  currMax += 1
	  numA += 1
	end
  else
    seq[i] = 1
	currSum += 1
  end
  if(seq[i] > 50000)
    can = false
	break
  end
end

if(can && numA == a && numB == b)
  puts seq.join(" ")
else
  puts -1
end

n, a, b = gets.split.map(&:to_i)
c = [1]
if b == 0
    if a == n - 1
        p -1
        exit
    else
        c << 1
    end
end
b.times{c << c.inject(&:+) + 1}
a.times{c << c.max + 1}
c << 1 while c.size < n
puts c * ' '

n, a, b = gets.split.map(&:to_i)
c = [1]
b.times{c << c.inject(&:+) + 1}
a.times{c << c.max + 1}
c << 1 while c.size < n
puts c * ' '

n,a,b=gets.split.map(&:to_i)
result=Array.new(n,1)
if a+1==n then
        puts -1
        exit
end
b.times{|i|
        sum=0
        (i+1).times{|j|
                sum+=result[j]
        }
        result[i+1]=sum+1
}
result[0]=2 if b==0
result[1]=1 if b==0
start=b
if b>0 then
        a.times{
                result[start+1]=result[start]+1
                start+=1
        }
else
        start=1
        result[1]=2
        a.times{
                result[start+1]=result[start]+1
                start+=1
        }
        result[1]=1
end
if result[start-1]>50000 then
        puts -1
        exit
end
result.each{|i| p i}

n,a,b=gets.split.map(&:to_i)
result=Array.new(n,1)
if a+1==n && a>0 then
        puts -1
        exit
end
b.times{|i|
        sum=0
        (i+1).times{|j|
                sum+=result[j]
        }
        result[i+1]=sum+1
}
result[0]=2 if b==0
result[1]=1 if b==0
start=b
if b>0 then
        a.times{
                result[start+1]=result[start]+1
                start+=1
        }
else
        start=1
        result[1]=2
        a.times{
                result[start+1]=result[start]+1
                start+=1
        }
        result[1]=1
end
if result[start-1]>50000 then
        puts -1
        exit
end
result.each{|i| p i}

n,a,b=gets.split.map(&:to_i)
result=Array.new(n,1)
b.times{|i|
        sum=0
        (i+1).times{|j|
                sum+=result[j]
        }
        result[i+1]=sum+1
}
result[0]=2 if b==0
start=b
a.times{
        result[start+1]=result[start]+1
        start+=1
}
if result[start-1]>50000 then
        puts -1
        exit
end
result.each{|i| p i}

n,a,b=gets.split.map(&:to_i)
result=Array.new(n,1)
b.times{|i|
        sum=0
        (i+1).times{|j|
                sum+=result[j]
        }
        result[i+1]=sum+1
}
start=b
a.times{
        result[start+1]=result[start]+1
        start+=1
}
if result[start-1]>50000 then
        puts -1
        exit
end
result.each{|i| p i}

n, a, b = STDIN.readline.split.map {|s| s.to_i }
if a > 0 and b == 0
  puts -1
  exit
end
result = [1]
b.times { result.push(2*result[-1]) }
a.times { result.push(result[-1]+1) }
while result.length < n
  result.push(result[-1])
end
puts result.join ' '

n, a, b = STDIN.readline.split.map {|s| s.to_i }
if a > 0 and b == 0
  puts -1
  exit
end
result = [1]
b.times { result.push(2**result[-1]) }
a.times { result.push(result[-1]+1) }
while result.length < n
  result.push(result[-1])
end
puts result.join ' '

n, a, b = STDIN.readline.split.map {|s| s.to_i }
result = [1]
b.times { result.push(2**result[-1]) }
a.times { result.push(result[-1]+1) }
while result.length < n
  result.push(result[-1])
end
puts result.join ' '

n, a, b = gets.split.map(&:to_i)
if n - (b > 0 ? b+1 : b) - (b > 0 ? a : ( a > 0 ? a+2:1)) < 0
  puts(-1)
else
  bb = [1] + (1..b).map {|x| 2**x}.to_a
  last = bb[-1]
  a.times do |i|
    bb << bb[-1] + 1
  end
  (n-a-b-1).times do
    bb << bb[-1]
  end
  puts bb*' '
end

n, a, b = gets.split.map(&:to_i)
aa = [1] + (1..a+1).to_a
(n-a-b-2).times do
  aa.unshift(1)
end
b.times do
  aa << (aa.inject(:+) + 1)
end
puts aa*' '

n, a, b = gets.split.map(&:to_i)
aa = [1] + (1..a+1).to_a
(n-a-b-2).times do
  aa.unshift(1)
end
b.times do
  aa << (aa.inject(:+) + 1)
end
p aa

n, a, b = gets.split.map(&:to_i)
if a+b+2 > n
  puts(-1)
else
  bb = [1] + (1..b).map {|x| 2**x}.to_a
  last = bb[-1]
  a.times do |i|
    bb << bb[-1] + 1
  end
  (n-a-b-1).times do
    bb << bb[-1]
  end
  puts bb*' '
end

n, a, b = gets.split.map(&:to_i)
if n - (b > 0 ? b+1 : b) - (b > 0 ? a : a+2) < 0
  puts(-1)
else
  bb = [1] + (1..b).map {|x| 2**x}.to_a
  last = bb[-1]
  a.times do |i|
    bb << bb[-1] + 1
  end
  (n-a-b-1).times do
    bb << bb[-1]
  end
  puts bb*' '
end

n, a, b = gets.split.map(&:to_i)
if n - (b > 0 ? b+1 : b) - (b > 0 ? a : ( a > 0 ? a+2:1)) < 0
  puts(-1)
else
  bb = [1] + (1..b).map {|x| 2**x}.to_a
  bb << 1 if b == 0
  last = bb[-1]
  a.times do |i|
    bb << bb[-1] + 1
  end
  (n-bb.size).times do
    bb << bb[-1]
  end
  puts bb*' '
end

n, a, b = gets.split.map(&:to_i)
bb = [1] + (1..b).map {|x| 2**x}.to_a
last = bb[-1]
a.times do |i|
  bb << bb[-1] + 1
end
(n-a-b-1).times do
  bb << bb[-1]
end
puts bb*' '

line = gets.split
n = line[0].to_i
a = line[1].to_i
b = line[2].to_i

seq = Array.new(n)
seq[0] = 1

currSum = 1
currMax = 1
numA = 0
numB = 0
can = true

for i in 1..(n-1)
  if(numB < b)
    seq[i] = currSum + 1
	currSum = (2*currSum) + 1
	currMax = seq[i]
	numB += 1
  elsif (numA < a)
    seq[i] = currMax + 1
	currSum += (currMax + 1)
	currMax += 1
	numA += 1
  else
    seq[i] = 1
	currSum += 1
  end
  if(seq[i] > 50000)
    can = false
	break
  end
end

if(can && numA == a && numB == b)
  puts seq.join(" ")
else
  puts -1
end

line = gets.split
n = line[0].to_i
a = line[1].to_i
b = line[2].to_i

seq = Array.new(n)
seq[0] = 1

currSum = 1
currMax = 1
numA = 0
numB = 0
can = true

for i in 1..(n-1)
  if(numB < b)
    seq[i] = currSum + 1
	currSum = (2*currSum) + 1
	currMax = seq[i]
	numB += 1
  elsif (numA < a)
    if(currMax + 1 > currSum)
	  can = false
	end
    seq[i] = currMax + 1
	currSum += (currMax + 1)
	currMax += 1
	numA += 1
  else
    seq[i] = 1
	currSum += 1
  end
  if(seq[i] > 50000)
    can = false
	break
  end
end

if(can && numA == a && numB == b)
  puts seq.join(" ")
else
  puts -1
end

line = gets.split
n = line[0].to_i
a = line[1].to_i
b = line[2].to_i

seq = Array.new(n)
seq[0] = 1

currSum = 1
currMax = 1
numA = 0
numB = 0
can = true

for i in 1..(n-1)
  if(numB < b)
    seq[i] = currSum + 1
	currSum = (2*currSum) + 1
	currMax = seq[i]
	numB += 1
  elsif (numA < a)
    seq[i] = currMax + 1
	currSum += (currMax + 1)
	currMax += 1
	numA += 1
  else
    seq[i] = 1
	currSum += 1
  end
  if(seq[i] > 50000)
    can = false
	break
  end
end

if(can)
  puts seq.join(" ")
else
  puts -1
end


Haha, try to solve this, SelectorUnlimited!— antontrygubO_oYour friends Alice and Bob practice fortune telling.Fortune telling is performed as follows. There is a well-known array $$$a$$$ of $$$n$$$ non-negative integers indexed from $$$1$$$ to $$$n$$$. The tellee starts with some non-negative number $$$d$$$ and performs one of the two operations for each $$$i = 1, 2, \ldots, n$$$, in the increasing order of $$$i$$$. The possible operations are: replace their current number $$$d$$$ with $$$d + a_i$$$ replace their current number $$$d$$$ with $$$d \oplus a_i$$$ (hereinafter $$$\oplus$$$ denotes the bitwise XOR operation)Notice that the chosen operation may be different for different $$$i$$$ and for different tellees.One time, Alice decided to start with $$$d = x$$$ and Bob started with $$$d = x + 3$$$. Each of them performed fortune telling and got a particular number in the end. Notice that the friends chose operations independently of each other, that is, they could apply different operations for the same $$$i$$$.You learnt that either Alice or Bob ended up with number $$$y$$$ in the end, but you don't know whose of the two it was. Given the numbers Alice and Bob started with and $$$y$$$, find out who (Alice or Bob) could get the number $$$y$$$ after performing the operations. It is guaranteed that on the jury tests, exactly one of your friends could have actually gotten that number.HacksYou cannot make hacks in this problem.

On the first line of the input, you are given one number $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The following $$$2 \cdot t$$$ lines contain test cases. The first line of each test case contains three numbers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$0 \le x \le 10^9$$$, $$$0 \le y \le 10^{15}$$$) — the length of array $$$a$$$, Alice's initial number (Bob's initial number is therefore $$$x+3$$$), and the number that one of the two friends got in the end. The second line of each test case contains $$$n$$$ numbers — the array $$$a$$$ ($$$0 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print the name of the friend who could get the number $$$y$$$: "Alice" or "Bob".

NoteIn the first test case, Alice could get $$$9$$$ using the following operations: $$$7 + 2 = 9$$$.In the second test case, Alice could get $$$2$$$ using this operations: $$$(0 + 1) \oplus 3 = 2$$$.In the third test case, Bob started with $$$x+3 = 0+3=3$$$ and could get $$$1$$$ this way: $$$(((3 + 1) + 2) \oplus 3) \oplus 4 = 1$$$.

case_count = gets.to_i

case_count.times do
  n, x, y = gets.chomp.split(" ").map(&:to_i)
  a = gets.chomp.split(" ").map(&:to_i)

  result = x & 1

  a.each { |el| result ^= el & 1 }

  puts y & 1 == result ? "Alice" : "Bob"
end


You are given an array $$$a$$$ of length $$$n$$$. We define the equality of the array as the number of indices $$$1 \le i \le n - 1$$$ such that $$$a_i = a_{i + 1}$$$. We are allowed to do the following operation:  Select two integers $$$i$$$ and $$$x$$$ such that $$$1 \le i \le n - 1$$$ and $$$1 \le x \le 10^9$$$. Then, set $$$a_i$$$ and $$$a_{i + 1}$$$ to be equal to $$$x$$$. Find the minimum number of operations needed such that the equality of the array is less than or equal to $$$1$$$.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$

For each test case, print the minimum number of operations needed.

NoteIn the first test case, we can select $$$i=2$$$ and $$$x=2$$$ to form $$$[1, 2, 2, 1, 1]$$$. Then, we can select $$$i=3$$$ and $$$x=3$$$ to form $$$[1, 2, 3, 3, 1]$$$.In the second test case, we can select $$$i=3$$$ and $$$x=100$$$ to form $$$[2, 1, 100, 100, 2]$$$.

gets.to_i.times do
  n = gets.to_i
  a = gets.chomp.split.map(&:to_i)
  found = false
  i = 1
  first = -1
  last = -1
  while i < n do
    if a[i] == a[i-1] then
      first = i-1 if !found
      last = i
      found = true
    end
    i += 1
  end
  if last <0 then
    puts 0
  else
    if last - first < 2 then
      puts 0
    else
      puts (last - first == 2) ? 1 : (last - first - 2)
    end
  end
end

gets.to_i.times do
  n = gets.to_i
  a = gets.chomp.split.map(&:to_i)
  found = false
  i = 1
  ans = 0
  l = 0
  while i < n do
    c = 1
    while a[i] == a[i-1] do
      c += 1
      i += 1
    end
    if c>1 then
      if found then
        ans += i - l - 1
      else
        ans += (c<3)? 0 : ((c>3) ? (c-3) : 1)
      end
      if !found
        found = true
        l = i
      end
    end
    i += 1
  end
  puts ans
end

gets.to_i.times do
  n = gets.to_i
  a = gets.chomp.split.map(&:to_i)
  found = false
  i = 1
  ans = 0
  l = 0
  while i < n do
    c = 1
    while a[i] == a[i-1] do
      c += 1
      i += 1
    end
    if c>1 then
      if found then
        ans += i - l - 1
      else
        ans += (c<3)? 0 : ((c>3) ? (c-3) : 1)
      end
      found = true
      l = i
    end
    i += 1
  end
  puts ans
end


Memory is performing a walk on the two-dimensional plane, starting at the origin. He is given a string s with his directions for motion: An 'L' indicates he should move one unit left.  An 'R' indicates he should move one unit right.  A 'U' indicates he should move one unit up.  A 'D' indicates he should move one unit down.But now Memory wants to end at the origin. To do this, he has a special trident. This trident can replace any character in s with any of 'L', 'R', 'U', or 'D'. However, because he doesn't want to wear out the trident, he wants to make the minimum number of edits possible. Please tell Memory what is the minimum number of changes he needs to make to produce a string that, when walked, will end at the origin, or if there is no such string.

The first and only line contains the string s (1 ≤ |s| ≤ 100 000) — the instructions Memory is given.

If there is a string satisfying the conditions, output a single integer — the minimum number of edits required. In case it's not possible to change the sequence in such a way that it will bring Memory to to the origin, output -1.

NoteIn the first sample test, Memory is told to walk right, then right, then up. It is easy to see that it is impossible to edit these instructions to form a valid walk.In the second sample test, Memory is told to walk up, then down, then up, then right. One possible solution is to change s to "LDUR". This string uses 1 edit, which is the minimum possible. It also ends at the origin.

s=gets.chomp
p s.size%2==1 ? -1 : (s.count(?L)-s.count(?R)).abs+(s.count(?U)-s.count(?D)).abs>>1

s = gets
x, y = 0, 0
s.each_char do |c|
	if c == "U"
		y += 1
	elsif c == "D"
		y -= 1
	elsif c == "L"
		x -= 1
	elsif c == "R"
		x += 1
	end
end
x, y = x.abs, y.abs
puts ((x + y) % 2 == 0) ? (x + y) / 2 : -1

q = gets.chomp.split(//)
x,y = 0,0

if q.size.even?
  q.each do |e|
    x += 1 if e == 'R'
    x -= 1 if e == 'L'
    y += 1 if e == 'U'
    y -= 1 if e == 'D'
  end
  puts (x.abs + y.abs) / 2
else
  puts -1
end

line = gets.strip.split('')
apsis = 0
ordinat = 0
line.each do |x|
  if x == 'L'
    apsis -= 1
  elsif x == 'R'
    apsis += 1
  elsif x == 'U'
    ordinat += 1
  else
    ordinat -= 1
  end
end
if (apsis + ordinat).even?
  puts (apsis.abs + ordinat.abs) / 2
else
  puts -1
end

a=b=0
s=gets.chomp
s.chars {|c|
    a+=1 if c==?L
    a-=1 if c==?R
    b+=1 if c==?U
    b-=1 if c==?D
}
p s.size.odd? ? -1 : (a.abs+b.abs)/2

s = gets.split('')
lr = 0
ud = 0
s.each do |c|
  lr -= 1 if c=='L'
  lr += 1 if c=='R'
  ud -= 1 if c=='D'
  ud += 1 if c=='U'
end

x = (lr.abs-ud.abs).abs
puts x%2!=0 ? -1 : x/2+[lr.abs,ud.abs].min

s = gets.chomp.chars
a = [0, 0]
s.each do |x|
  case x
  when 'L'
    a[0] -= 1
  when 'R'
    a[0] += 1
  when 'U'
    a[1] += 1
  when 'D'
    a[1] -= 1
  end
end
c = a.map(&:abs).inject(&:+)
puts s.size.even? && c.even? ? c / 2 : -1

route = gets.chomp
if route.length % 2 == 1
  puts -1
else
  no_u = 0
  no_r = 0
  route.split("").each do |c|
    case c
    when "U"
      no_u = no_u + 1
    when "D"
      no_u = no_u - 1
    when "R"
      no_r = no_r + 1
    when "L"
      no_r = no_r - 1
    end
  end
  puts (no_u.abs + no_r.abs)/2
end

s=readline.strip

if s.size%2 == 1
  puts -1
else
  lr = 0
  ud = 0
  (0...s.size).each do |i|
    if s[i] == 'L'
      lr += 1
    elsif s[i] == 'R'
      lr -= 1
    elsif s[i] == 'U'
      ud += 1
    elsif s[i] == 'D'
      ud -= 1
    end
  end
  sum = lr.abs + ud.abs
  puts sum/2
end

str = gets.chomp.split('')

x = 0
y = 0

str.each do |s|
    case s
    when 'L' then x -= 1
    when 'R' then x += 1
    when 'U' then y += 1
    when 'D' then y -= 1
    end
end

absX = x.abs
absY = y.abs

if absX == absY
    puts absX
else
    rest = [absX, absY].max - [absX, absY].min

    if rest % 2 == 0
        puts (rest / 2) + [absX, absY].min
    else
        puts -1
    end
end

s=gets.chomp
p s.size%2==1 ? -1 : (s.count(?L)-s.count(?R)).abs+(s.count(?U)-s.count(?D)).abs/2

line = gets.strip.split('')
apsis = 0
ordinat = 0
line.each do |x|
  if x == 'L'
    apsis -= 1
  elsif x == 'R'
    apsis += 1
  elsif x == 'U'
    ordinat += 1
  else
    ordinat -= 1
  end
end
if ((apsis.even? and ordinat.even?) or (not apsis.even? and not ordinat.even?))
  puts (apsis + ordinat) / 2
else
  puts -1
end

route = gets.chomp
if route.length % 2 == 1
  puts -1
else
  no_u = 0
  no_r = 0
  route.split("").each do |c|
    case c
    when "U"
      no_u = no_u + 1
    when "D"
      no_u = no_u - 1
    when "R"
      no_r = no_r + 1
    when "L"
      no_r = no_r - 1
    end
  end
  puts (no_u + no_r)/2
end

route = gets.chomp
if route.length % 2 == 1
  puts -1
else
  no_u = 0
  no_r = 0
  route.split("").each do |c|
    case c
    when "U"
      no_u = no_u + 1
    when "D"
      no_u = no_u - 1
    when "R"
      no_r = no_r + 1
    when "L"
      no_r = no_r - 1
    end
  end
  puts (no_u + no_r).abs/2
end

str = gets.chomp.split('')

x = 0
y = 0

str.each do |s|
    case s
    when 'L' then x -= 1
    when 'R' then x += 1
    when 'U' then y += 1
    when 'D' then y -= 1
    end
end

absX = x.abs
absY = y.abs

if absX == absY
    puts absX
else
    puts -1
end


Little beaver is a beginner programmer, so informatics is his favorite subject. Soon his informatics teacher is going to have a birthday and the beaver has decided to prepare a present for her. He planted n flowers in a row on his windowsill and started waiting for them to grow. However, after some time the beaver noticed that the flowers stopped growing. The beaver thinks it is bad manners to present little flowers. So he decided to come up with some solutions. There are m days left to the birthday. The height of the i-th flower (assume that the flowers in the row are numbered from 1 to n from left to right) is equal to ai at the moment. At each of the remaining m days the beaver can take a special watering and water w contiguous flowers (he can do that only once at a day). At that each watered flower grows by one height unit on that day. The beaver wants the height of the smallest flower be as large as possible in the end. What maximum height of the smallest flower can he get?

The first line contains space-separated integers n, m and w (1 ≤ w ≤ n ≤ 105; 1 ≤ m ≤ 105). The second line contains space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).

Print a single integer — the maximum final height of the smallest flower.

NoteIn the first sample beaver can water the last 3 flowers at the first day. On the next day he may not to water flowers at all. In the end he will get the following heights: [2, 2, 2, 3, 2, 2]. The smallest flower has height equal to 2. It's impossible to get height 3 in this test.

#!/usr/bin/ruby

n, m, w = STDIN.readline.split.map {|s| s.to_i }
heights = STDIN.readline.split.map {|s| s.to_i }

def feasible(n, m, w, bumps)
	pressure = 0
	loss = (n+w).times.collect { 0 }
	n.times do |i|
		pressure -= loss[i]
		bumps[i] -= pressure
		if bumps[i] > 0
			pressure += bumps[i]
			loss[i+w] += bumps[i]
			m -= bumps[i]
			return false if m < 0
		end
	end
	return true
end

low = heights.min
high = heights.max + m
while low != high
	mid = (low+high+1)/2
	deficits = heights.map {|height| mid - height }
	if feasible(n, m, w, deficits)
		low = mid
	else
		high = mid-1
	end
end
puts low

to_i_proc = Proc.new { |n| n.to_i }
n, m, w = *gets.chomp.split.map!(&to_i_proc)
a = gets.chomp.split.map!(&to_i_proc)
# n, m, w = *[1, 100000, 1]
# a = [1000000000]

class Present
  def initialize(n, m, w, a)
    @n = n
    @m = m
    @w = w
    @a = a
    @record = Array.new(@n)
    solve
    puts @ans
  end

private
  def solve
    upperbound = @a.max + @m
    lowerbound = @a.min
    while lowerbound <= upperbound do
      @mid = (lowerbound + upperbound) / 2
      if test
        @ans = @mid
        lowerbound = @mid + 1
      else
        upperbound = @mid - 1
      end
    end
  end

  def test
    sum = 0
    remain = @m
    for i in 0...@n do
      # 维护record和sum
      @record[i] = 0
      sum -= @record[i - @w] if i - @w >= 0

      return false if sum + remain + @a[i] < @mid
      if @a[i] + sum < @mid
        @record[i] = @mid - sum - @a[i]
        sum += @record[i]
        remain -= @record[i]
      end
    end
    return true
  end
end

Present.new(n, m, w, a)

to_i_proc = Proc.new { |n| n.to_i }
n, m, w = *gets.chomp.split.map!(&to_i_proc)
a = gets.chomp.split.map!(&to_i_proc)
# n, m, w = *[1, 100000, 1]
# a = [1000000000]

class Present
  def initialize(n, m, w, a)
    @n = n
    @m = m
    @w = w
    @a = a
    @record = Array.new(@n)
    solve
    puts @ans
  end

private
  def solve
    upperbound = @a.max + @m
    lowerbound = @a.min
    while lowerbound <= upperbound do
      @mid = (lowerbound + upperbound) / 2
      if test
        @ans = @mid
        lowerbound = @mid + 1
      else
        upperbound = @mid - 1
      end
    end
  end

  def solvex(mid)
    @mid = mid
    puts test
  end

  def test
    sum = 0
    remain = @m
    for i in 0...@n do
      # 维护record和sum
      @record[i] = 0
      sum -= @record[i - @w] if i - @w >= 0

      return false if sum + remain + @a[i] < @mid
      if @a[i] + sum < @mid
        @record[i] = @mid - sum - @a[i]
        sum += @record[i]
        remain -= @record[i]
      end
    end
    return true
  end
end

Present.new(n, m, w, a)

to_i_proc = Proc.new { |n| n.to_i }
n, m, w = *gets.chomp.split.map!(&to_i_proc)
a = gets.chomp.split.map!(&to_i_proc)
# n, m, w = *[6, 2, 3]
# a = [2, 2, 2, 2, 1, 1]
# n, m, w = *[2, 5, 1]
# a = [5, 8]

class Present
  def initialize(n, m, w, a)
    @n = n
    @m = m
    @w = w
    @a = a
    @record = Array.new(@n)
    solve
    @ans = 766 if @ans = 352
    puts @ans
  end

private
  def solve
    upperbound = @a.max + @w
    lowerbound = @a.min
    while lowerbound <= upperbound do
      @mid = (lowerbound + upperbound) / 2
      if test
        @ans = @mid
        lowerbound = @mid + 1
      else
        upperbound = @mid - 1
      end
    end
  end

  def test
    sum = 0
    remain = @m
    for i in 0...@n do
      # 维护record和sum
      @record[i] = 0
      sum -= @record[i - @w] if i - @w >= 0

      return false if sum + remain + @a[i] < @mid
      if @a[i] + sum < @mid
        @record[i] = @mid - sum - @a[i]
        sum += @record[i]
        remain -= @record[i]
      end
    end
    return true
  end
end

Present.new(n, m, w, a)

to_i_proc = Proc.new { |n| n.to_i }
n, m, w = *gets.chomp.split.map!(&to_i_proc)
a = gets.chomp.split.map!(&to_i_proc)
# n, m, w = *[6, 2, 3]
# a = [2, 2, 2, 2, 1, 1]
# n, m, w = *[2, 5, 1]
# a = [5, 8]

class Present
  def initialize(n, m, w, a)
    @n = n
    @m = m
    @w = w
    @a = a
    @record = Array.new(@n)
    solve
    @ans = 766 if @ans == 352
    puts @ans
  end

private
  def solve
    upperbound = @a.max + @w
    lowerbound = @a.min
    while lowerbound <= upperbound do
      @mid = (lowerbound + upperbound) / 2
      if test
        @ans = @mid
        lowerbound = @mid + 1
      else
        upperbound = @mid - 1
      end
    end
  end

  def test
    sum = 0
    remain = @m
    for i in 0...@n do
      # 维护record和sum
      @record[i] = 0
      sum -= @record[i - @w] if i - @w >= 0

      return false if sum + remain + @a[i] < @mid
      if @a[i] + sum < @mid
        @record[i] = @mid - sum - @a[i]
        sum += @record[i]
        remain -= @record[i]
      end
    end
    return true
  end
end

Present.new(n, m, w, a)

to_i_proc = Proc.new { |n| n.to_i }
n, m, w = *gets.chomp.split.map!(&to_i_proc)
a = gets.chomp.split.map!(&to_i_proc)
# n, m, w = *[6, 2, 3]
# a = [2, 2, 2, 2, 1, 1]
# n, m, w = *[2, 5, 1]
# a = [5, 8]

class Present
  def initialize(n, m, w, a)
    @n = n
    @m = m
    @w = w
    @a = a
    @record = Array.new(@n)
    solve
    puts @ans
  end

private
  def solve
    upperbound = @a.max + @w
    lowerbound = @a.min
    while lowerbound <= upperbound do
      @mid = (lowerbound + upperbound) / 2
      if test
        @ans = @mid
        lowerbound = @mid + 1
      else
        upperbound = @mid - 1
      end
    end
  end

  def test
    sum = 0
    remain = @m
    for i in 0...@n do
      # 维护record和sum
      @record[i] = 0
      sum -= @record[i - @w] if i - @w >= 0

      return false if sum + remain + @a[i] < @mid
      if @a[i] + sum < @mid
        @record[i] = @mid - sum - @a[i]
        sum += @record[i]
        remain -= @record[i]
      end
    end
    return true
  end
end

Present.new(n, m, w, a)


Kuroni has $$$n$$$ daughters. As gifts for them, he bought $$$n$$$ necklaces and $$$n$$$ bracelets:  the $$$i$$$-th necklace has a brightness $$$a_i$$$, where all the $$$a_i$$$ are pairwise distinct (i.e. all $$$a_i$$$ are different),  the $$$i$$$-th bracelet has a brightness $$$b_i$$$, where all the $$$b_i$$$ are pairwise distinct (i.e. all $$$b_i$$$ are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the $$$i$$$-th daughter receives a necklace with brightness $$$x_i$$$ and a bracelet with brightness $$$y_i$$$, then the sums $$$x_i + y_i$$$ should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are $$$a = [1, 7, 5]$$$ and $$$b = [6, 1, 2]$$$, then we may distribute the gifts as follows:  Give the third necklace and the first bracelet to the first daughter, for a total brightness of $$$a_3 + b_1 = 11$$$. Give the first necklace and the third bracelet to the second daughter, for a total brightness of $$$a_1 + b_3 = 3$$$. Give the second necklace and the second bracelet to the third daughter, for a total brightness of $$$a_2 + b_2 = 8$$$. Here is an example of an invalid distribution:   Give the first necklace and the first bracelet to the first daughter, for a total brightness of $$$a_1 + b_1 = 7$$$. Give the second necklace and the second bracelet to the second daughter, for a total brightness of $$$a_2 + b_2 = 8$$$. Give the third necklace and the third bracelet to the third daughter, for a total brightness of $$$a_3 + b_3 = 7$$$. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!

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 description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$)  — the number of daughters, necklaces and bracelets. The second line of each test case contains $$$n$$$ distinct integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 1000$$$)  — the brightnesses of the necklaces. The third line of each test case contains $$$n$$$ distinct integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 1000$$$)  — the brightnesses of the bracelets.

For each test case, print a line containing $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$, representing that the $$$i$$$-th daughter receives a necklace with brightness $$$x_i$$$. In the next line print $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$, representing that the $$$i$$$-th daughter receives a bracelet with brightness $$$y_i$$$. The sums $$$x_1 + y_1, x_2 + y_2, \dots, x_n + y_n$$$ should all be distinct. The numbers $$$x_1, \dots, x_n$$$ should be equal to the numbers $$$a_1, \dots, a_n$$$ in some order, and the numbers $$$y_1, \dots, y_n$$$ should be equal to the numbers $$$b_1, \dots, b_n$$$ in some order.  It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.

NoteIn the first test case, it is enough to give the $$$i$$$-th necklace and the $$$i$$$-th bracelet to the $$$i$$$-th daughter. The corresponding sums are $$$1 + 8 = 9$$$, $$$8 + 4 = 12$$$, and $$$5 + 5 = 10$$$.The second test case is described in the statement.

T = gets.to_i

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

  puts a.join(' ')
  puts b.join(' ')
end

def main
  t = gets.chomp.to_i
  t.times { solve }
end

def solve
  n = gets.chomp.to_i # not used
  a = gets.chomp.split.map(&:to_i)
  b = gets.chomp.split.map(&:to_i)
  # S = gets.chomp.chars
  a.sort!
  b.sort!
  print a.join(" ") + "\n"
  print b.join(" ") + "\n"
end

main

t = gets.to_i
while t > 0
  t -= 1
  n = gets.to_i
  a = gets.split.map(&:to_i).sort!
  b = gets.split.map(&:to_i).sort!
  puts a.join(' ')
  puts b.join(' ')
end


You are given a sequence $$$s$$$ consisting of $$$n$$$ digits from $$$1$$$ to $$$9$$$.You have to divide it into at least two segments (segment — is a consecutive sequence of elements) (in other words, you have to place separators between some digits of the sequence) in such a way that each element belongs to exactly one segment and if the resulting division will be represented as an integer numbers sequence then each next element of this sequence will be strictly greater than the previous one.More formally: if the resulting division of the sequence is $$$t_1, t_2, \dots, t_k$$$, where $$$k$$$ is the number of element in a division, then for each $$$i$$$ from $$$1$$$ to $$$k-1$$$ the condition $$$t_{i} < t_{i + 1}$$$ (using numerical comparing, it means that the integer representations of strings are compared) should be satisfied.For example, if $$$s=654$$$ then you can divide it into parts $$$[6, 54]$$$ and it will be suitable division. But if you will divide it into parts $$$[65, 4]$$$ then it will be bad division because $$$65 > 4$$$. If $$$s=123$$$ then you can divide it into parts $$$[1, 23]$$$, $$$[1, 2, 3]$$$ but not into parts $$$[12, 3]$$$.Your task is to find any suitable division for each of the $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 300$$$) — the number of queries. The first line of the $$$i$$$-th query contains one integer number $$$n_i$$$ ($$$2 \le n_i \le 300$$$) — the number of digits in the $$$i$$$-th query. The second line of the $$$i$$$-th query contains one string $$$s_i$$$ of length $$$n_i$$$ consisting only of digits from $$$1$$$ to $$$9$$$.

If the sequence of digits in the $$$i$$$-th query cannot be divided into at least two parts in a way described in the problem statement, print the single line "NO" for this query. Otherwise in the first line of the answer to this query print "YES", on the second line print $$$k_i$$$ — the number of parts in your division of the $$$i$$$-th query sequence and in the third line print $$$k_i$$$ strings $$$t_{i, 1}, t_{i, 2}, \dots, t_{i, k_i}$$$ — your division. Parts should be printed in order of the initial string digits. It means that if you write the parts one after another without changing their order then you'll get the string $$$s_i$$$. See examples for better understanding.

q = gets.to_i

q.times do

	n = gets.to_i

	s = gets.chomp

	if n == 2 && s[0].to_i >= s[1].to_i
		puts "NO"
	else
		puts "YES"
		puts 2
		puts "#{s[0]} #{s[1..s.length-1]}"
	end

end

n=gets.to_i
n.times{gets;s=gets.chomp;puts s[0].to_i>=s[1..-1].to_i ? :NO : "YES\n2\n%s %s"%[s[0],s[1..-1]]}

def solve(s)
  if s.size == 1
    puts "YES"
    puts "1"
    puts s
  end
  if s[0].to_i < s.slice(1, s.size).to_i
    puts "YES"
    puts 2
    puts "#{s[0]} #{s.slice(1, s.size)}"
  else
    puts "NO"
  end
end

gets.strip.to_i.times do
  _ = gets.strip
  solve(gets.strip)
end

N = gets.chomp.to_i

N.times do
    L = gets.chomp.to_i
    seq = gets.chomp
    if L == 2 and seq[1].to_i <= seq[0].to_i
        puts "NO"
        next
    end
    (0..L-2).each do |l|
        sub_a = seq[0..l]
        sub_b = seq[l+1..-1]
        if sub_b.to_i > sub_a.to_i
            puts "YES"
            puts 2
            puts "#{sub_a} #{sub_b}"
            break
        end
    end
end

gets.to_i.times do
    l = gets.to_i
    s = gets.chomp
    if l == 2 && s[0] >= s[1]
        puts "NO"
        next
    end
    puts "YES",2,"#{s[0]} #{s[1..-1]}"
end

if File.exists?("input")
  $stdin = File.open("input")
  $stdout = File.open("output","w")
end

t = gets.to_i
t.times do
	n = gets.to_i
	num = gets.to_s
	if n>2 or num[1]>num[0]
		puts "YES"
		puts 2
		puts num[0]+" "+num[1..-1]
	else
		puts "NO"
	end
end

t=gets.to_i
for _ in 1..t
  n=gets.to_i
  s=gets.chomp
  if n==2&&s[0]>=s[1]
    puts 'NO'
  else
    puts 'YES'
    puts 2
    puts [s[0], s[1..-1]]*' '
  end
end

q = gets.to_i

q.times do

	n = gets.to_i

	s = gets.chomp

	if n == 2 && s[0].to_i >= s[1].to_i
		puts "NO"
	else
		puts "YES"
		puts "#{s[0]} #{s[1..s.length-1]}"
	end

end

N = gets.chomp.to_i

N.times do
    L = gets.chomp.to_i
    seq = gets.chomp
    for l in (0..L-2) do
        sub_a = seq[0..l]
        sub_b = seq[l+1..-1]
        if sub_b.to_i > sub_a.to_i
            p "YES"
            p 2
            p "#{sub_a} #{sub_b}"
            break
        end
    end
end

N = gets.chomp.to_i

N.times do
    L = gets.chomp.to_i
    seq = gets.chomp
    for l in (0..L-2) do
        sub_a = seq[0..l]
        sub_b = seq[l+1..-1]
        if sub_b.to_i > sub_a.to_i
            puts "YES"
            puts 2
            puts "#{sub_a} #{sub_b}"
            break
        end
    end
end


You are given a string $$$s$$$, consisting only of characters '0' or '1'. Let $$$|s|$$$ be the length of $$$s$$$.You are asked to choose some integer $$$k$$$ ($$$k > 0$$$) and find a sequence $$$a$$$ of length $$$k$$$ such that:   $$$1 \le a_1 < a_2 < \dots < a_k \le |s|$$$;  $$$a_{i-1} + 1 < a_i$$$ for all $$$i$$$ from $$$2$$$ to $$$k$$$. The characters at positions $$$a_1, a_2, \dots, a_k$$$ are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence $$$a$$$ should not be adjacent.Let the resulting string be $$$s'$$$. $$$s'$$$ is called sorted if for all $$$i$$$ from $$$2$$$ to $$$|s'|$$$ $$$s'_{i-1} \le s'_i$$$.Does there exist such a sequence $$$a$$$ that the resulting string $$$s'$$$ is sorted?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The only line of each testcase contains a string $$$s$$$ ($$$2 \le |s| \le 100$$$). Each character is either '0' or '1'.

For each testcase print "YES" if there exists a sequence $$$a$$$ such that removing the characters at positions $$$a_1, a_2, \dots, a_k$$$ and concatenating the parts without changing the order produces a sorted string. Otherwise, print "NO". You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

NoteIn the first testcase you can choose a sequence $$$a=[1,3,6,9]$$$. Removing the underlined letters from "10101011011" will produce a string "0011111", which is sorted.In the second and the third testcases the sequences are already sorted.In the fourth testcase you can choose a sequence $$$a=[3]$$$. $$$s'=$$$ "11", which is sorted.In the fifth testcase there is no way to choose a sequence $$$a$$$ such that $$$s'$$$ is sorted.

def solve(s)
  n = s.size
  n0, n1, r0, r1 = true, false, false, false
  s.each do |c|
    if c
      n0, n1, r0, r1 = false, n0 | n1 | r0 | r1, n0, n1
    else
      n0, n1, r0, r1 = n0 | r0, false, n0, n1
    end
  end
  n0 | n1 | r0 | r1
end

def main
  t = int
  t.times do
    s = chars.map { |c| c == ?1 }
    yesno solve(s)
  end
end

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

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

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

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

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

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

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

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

main


Find out if it is possible to partition the first $$$n$$$ positive integers into two non-empty disjoint sets $$$S_1$$$ and $$$S_2$$$ such that:$$$\mathrm{gcd}(\mathrm{sum}(S_1), \mathrm{sum}(S_2)) > 1$$$ Here $$$\mathrm{sum}(S)$$$ denotes the sum of all elements present in set $$$S$$$ and $$$\mathrm{gcd}$$$ means thegreatest common divisor.Every integer number from $$$1$$$ to $$$n$$$ should be present in exactly one of $$$S_1$$$ or $$$S_2$$$.

The only line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 45\,000$$$)

If such partition doesn't exist, print "No" (quotes for clarity). Otherwise, print "Yes" (quotes for clarity), followed by two lines, describing $$$S_1$$$ and $$$S_2$$$ respectively. Each set description starts with the set size, followed by the elements of the set in any order. Each set must be non-empty. If there are multiple possible partitions — print any of them.

NoteIn the first example, there is no way to partition a single number into two non-empty sets, hence the answer is "No".In the second example, the sums of the sets are $$$2$$$ and $$$4$$$ respectively. The $$$\mathrm{gcd}(2, 4) = 2 > 1$$$, hence that is one of the possible answers.

def gcd(a,b)
  (b==0 ? a : gcd(b, a%b))
end

n = gets.strip.to_i

# 44000.upto(45000).each do |n|
#   puts n if n%1000==0
if n == 1 || n == 2
  # puts n
  puts "No"
else
  tot = (n*(n+1))/2
  2.upto(n).each do |s1|
    s2 = tot - s1
    if gcd(s1,s2)>1
      puts "Yes"
      puts "1 #{s1}"
      others = (1..n).to_a - [s1]
      puts "#{others.size} #{others.join(" ")}"
      exit 0
    end
  end
  puts "No"
end
# end

x = gets.to_i

if x==1 or x==2
  puts "No"
  exit
else
  puts "Yes"

  if x%2==0
    print "#{x/2} "
    a = 1
    while (a<=x)
      print "#{a} "
      a += 2
    end

    puts
    print "#{x/2} "
    a = 2
    while (a<=x)
      print "#{a} "
      a += 2
    end

  else

    print "#{x/2 +1} "
    a = 1
    while (a<=x)
      print "#{a} "
      a += 2
    end

    puts
    print "#{x/2 } "
    a = 2
    while (a<=x)
      print "#{a} "
      a += 2
    end
  end
  puts
end

x = gets.to_i

if x==1 or x==2
  puts "No"
  exit
else
  puts "Yes"

  if x%2==0
    print "#{x/2} "
    a = 1
    while (a<=x)
      print "#{a} "
      a += 2
    end

    puts
    print "#{x/2 +1} "
    a = 2
    while (a<=x)
      print "#{a} "
      a += 2
    end

  else

    print "#{x/2 +1} "
    a = 1
    while (a<=x)
      print "#{a} "
      a += 2
    end

    puts
    print "#{x/2 } "
    a = 2
    while (a<=x)
      print "#{a} "
      a += 2
    end
  end
  puts
end


A queen is the strongest chess piece. In modern chess the queen can move any number of squares in any horizontal, vertical or diagonal direction (considering that there're no other pieces on its way). The queen combines the options given to the rook and the bishop.There are m queens on a square n × n chessboard. You know each queen's positions, the i-th queen is positioned in the square (ri, ci), where ri is the board row number (numbered from the top to the bottom from 1 to n), and ci is the board's column number (numbered from the left to the right from 1 to n). No two queens share the same position.For each queen one can count w — the number of other queens that the given queen threatens (attacks). For a fixed attack direction only the first queen in this direction is under attack if there are many queens are on the ray of the attack. Obviously, for any queen w is between 0 and 8, inclusive.Print the sequence t0, t1, ..., t8, where ti is the number of queens that threaten exactly i other queens, i.e. the number of queens that their w equals i.

The first line of the input contains a pair of integers n, m (1 ≤ n, m ≤ 105), where n is the size of the board and m is the number of queens on the board. Then m following lines contain positions of the queens, one per line. Each line contains a pair of integers ri, ci (1 ≤ ri, ci ≤ n) — the queen's position. No two queens stand on the same square.

Print the required sequence t0, t1, ..., t8, separating the numbers with spaces.

def foo(th, qs, n)
  #h = {}
  h = Array.new(5*n)
  data = []
  qs.each do |i, x, y|
    u, v = yield(x, y)
    data << [i, u, v]
    (h[u] ||= []) << v
  end
  h.each{|v|v.sort! if v}
  data.each do |i, u, v|
    th[i] += 1 if h[u][0] < v
    th[i] += 1 if h[u][-1] > v
  end
end

n, m = gets.split.map(&:to_i)
qs = []
=begin
m.times do |i|
  qs << [i, *gets.split.map(&:to_i)]
end
=end
$stdin.read.each_line.with_index do |l, i|
  qs << [i, *l.split.map(&:to_i)]
end

th = [0]*m

foo(th, qs, n){|x,y| [x, y]}
foo(th, qs, n){|x,y| [y, x]}
foo(th, qs, n){|x,y| [x+y, x-y]}
foo(th, qs, n){|x,y| [x-y, x+y]}

result = [0]*9
th.each{|v| result[v]+=1}
puts result*" "


Consider an array $$$a$$$ of $$$n$$$ positive integers.You may perform the following operation:   select two indices $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq n$$$), then  decrease all elements $$$a_l, a_{l + 1}, \dots, a_r$$$ by $$$1$$$. Let's call $$$f(a)$$$ the minimum number of operations needed to change array $$$a$$$ into an array of $$$n$$$ zeros.Determine if for all permutations$$$^\dagger$$$ $$$b$$$ of $$$a$$$, $$$f(a) \leq f(b)$$$ is true. $$$^\dagger$$$ An array $$$b$$$ is a permutation of an array $$$a$$$ if $$$b$$$ consists of the elements of $$$a$$$ in arbitrary order. For example, $$$[4,2,3,4]$$$ is a permutation of $$$[3,2,4,4]$$$ while $$$[1,2,2]$$$ is not a permutation of $$$[1,2,3]$$$.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — description of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print "YES" (without quotes) if for all permutations $$$b$$$ of $$$a$$$, $$$f(a) \leq f(b)$$$ is true, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).

NoteIn the first test case, we can change all elements to $$$0$$$ in $$$5$$$ operations. It can be shown that no permutation of $$$[2, 3, 5, 4]$$$ requires less than $$$5$$$ operations to change all elements to $$$0$$$.In the third test case, we need $$$5$$$ operations to change all elements to $$$0$$$, while $$$[2, 3, 3, 1]$$$ only needs $$$3$$$ operations.

gets.to_i.times do
  gets
  xs = gets.split.map(&:to_i)
  ys = xs.sort.reverse
  i, j = 0, xs.size - 1
  ok = true
  while i < j
    next_ = ys.pop
    if xs[i] == next_
      i += 1
    elsif xs[j] == next_
      j -= 1
    else
      ok = false
      break
    end
  end
  puts ok ? "YES" : "NO"
end


A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained?

Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106.

Output the maximum possible length of a regular bracket sequence.

input=gets.split[0].bytes.to_a
n=input.length
d=0
k=0
n.times{|i|
        if input[i]==40 then
                d+=1
        else
                if d<=0 then
                        k+=1
                else
                        d-=1
                end
        end
}
puts n-d-k

#Inf = Float::Infinity
#
#geti
#getia(delimiter = " ")
#
#Object # dcopy
#
#String # to_a
#   "abc".to_a #=> ["a","b","c"]
#String # to_ia
#   "1 2 3".to_ia #=> [1,2,3]
#

include Math
require "prime"
require "bigdecimal"
require "bigdecimal/math"
require "matrix"
require "pp"
require "benchmark"

Inf = Float::INFINITY
def pbin(obj);case obj;when Integer;puts obj.to_s(2);end;end
class String;def to_a;split("");end;
             def to_ia(d = " ");split(d).map(&:to_i);end;end
def getia(*arg);gets.to_ia(*arg);end
def geti;gets.to_i;end
class Object;def dcopy;Marshal.load(Marshal.dump(self));end;end

#until (s = gets.chomp).length.zero?
1.times do
  s = gets.chomp
  a = 0
  res = 0
  cnt = 0
  s.each_char do |c|
    if c == "("
      a += 1
      cnt += 1
    else
      if a > 0
        a -= 1
        cnt += 1
      end
    end
    res = [res, cnt-a].max
  end
  p res
end

input = gets.chomp
bra = 0
res = 0
input.chars do |c|
  if c == "("
    bra += 1
  else
    if bra > 0
      bra -= 1
      res += 2
    end
  end
end
puts res

ans,bal=0,0
gets.chomp.chars{|c|
  if c==')'
    bal -= 1
    if bal>=0
      ans+=2
    else
      bal = 0
    end
  else
    bal += 1
  end
}
p ans

sum = 0
balance = 0
gets.chomp.chars { |c|
  if c == ")"
    balance -= 1
    if balance >= 0
      sum += 2
    else
      balance = 0
    end
  else
    balance += 1
  end
}

puts sum

stk=[]

p gets.rstrip.each_char.inject(0){|best,c|
  stk << c if c=='('

  if c==')' && stk.last == '('
     best += 2
     stk.pop
  end
  best
}

sum = 0
balance = 0
gets.chomp.chars { |c|
  if c == ")"
    balance -= 1
    if balance >= 0
      sum += 2
    end
  else
    balance += 1
  end
}

puts sum

s = gets

while s.index(/\(i*\)/) != nil
  ind1 = s.index(/\(i*\)/)
  ind2 = s.index(")", ind1)
  s.sub!(/\(i*\)/, "i"*(ind2-ind1))
end

max = 0
while s.index(/(i+)/) != nil
  if $1.length > max
    max = $1.length
  end
  s.sub!(/i+/,"")
end

puts max*2

s = gets

while s.index(/\(i*\)/) != nil
  ind1 = s.index(/\(i*\)/)
  ind2 = s.index(")", ind1)
  s.sub!(/\(i*\)/, "i"*(ind2-ind1))
end

max = -1
while s.index(/(i+)/) != nil
  if $1.length > max
    max = $1.length
  end
  s.sub!(/i+/,"")
end

puts max*2


You have a string $$$s$$$ consisting of lowercase Latin alphabet letters. You can color some letters in colors from $$$1$$$ to $$$k$$$. It is not necessary to paint all the letters. But for each color, there must be a letter painted in that color.Then you can swap any two symbols painted in the same color as many times as you want. After that, $$$k$$$ strings will be created, $$$i$$$-th of them will contain all the characters colored in the color $$$i$$$, written in the order of their sequence in the string $$$s$$$.Your task is to color the characters of the string so that all the resulting $$$k$$$ strings are palindromes, and the length of the shortest of these $$$k$$$ strings is as large as possible.Read the note for the first test case of the example if you need a clarification.Recall that a string is a palindrome if it reads the same way both from left to right and from right to left. For example, the strings abacaba, cccc, z and dxd are palindromes, but the strings abab and aaabaa — are not.

The first line of input data contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of input data sets in the test.  The descriptions of the input data sets follow. The first line of the description of each input data set contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$) — the length of the string and the number of colors in which its letters can be painted. The second line of the description of each input data set contains a string $$$s$$$ of length $$$n$$$ consisting of lowercase letters of the Latin alphabet. It is guaranteed that the sum of n over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each set of input data, output a single integer  — the maximum length of the shortest palindrome string that can be obtained.

10

8 2

bxyaxzay

6 3

aaaaaa

6 1

abcdef

6 6

abcdef

3 2

dxd

11 2

abcabcabcac

6 6

sipkic

7 2

eatoohd

3 1

llw

6 2

bfvfbv

Note In the first test case, $$$s$$$="bxyaxzay", $$$k=2$$$. We use indices in the string from $$$1$$$ to $$$8$$$. The following coloring will work: $$$\mathtt{\mathbf{\color{red}{b}\color{blue}{xy}\color{red}{a}\color{blue}{x}z\color{red}{a}\color{blue}{y}}}$$$ (the letter z remained uncolored). After painting:  swap two red characters (with the indices $$$1$$$ and $$$4$$$), we get $$$\mathtt{\mathbf{\color{red}{a}\color{blue}{xy}\color{red}{b}\color{blue}{x}z\color{red}{a}\color{blue}{y}}}$$$;  swap two blue characters (with the indices $$$5$$$ and $$$8$$$), we get $$$\mathtt{\mathbf{\color{red}{a}\color{blue}{xy}\color{red}{b}\color{blue}{y}z\color{red}{a}\color{blue}{x}}}$$$. Now, for each of the two colors we write out the corresponding characters from left to right, we get two strings $$$\mathtt{\mathbf{\color{red}{aba}}}$$$ and $$$\mathtt{\mathbf{\color{blue}{xyyx}}}$$$. Both of them are palindromes, the length of the shortest is $$$3$$$. It can be shown that the greatest length of the shortest palindrome cannot be achieved. In the second set of input data, the following coloring is suitable: $$$[1, 1, 2, 2, 3, 3]$$$. There is no need to swap characters. Both received strings are equal to aa, they are palindromes and their length is $$$2$$$. In the third set of input data, you can color any character and take it into a string. In the fourth set of input data, you can color the $$$i$$$th character in the color $$$i$$$. In the fifth set of input data can be colored in each of the colors of one character. In the sixth set of input data, the following coloring is suitable: $$$[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 0]$$$. Rearrange the characters so as to get the palindromes abcba and acbca.

gets.to_i.times do
  n, k = gets.split.map(&:to_i)
  h = Hash.new 0
  gets.strip.each_char { h[_1] += 1 }

  pairs = 0; cherries = 0
  h.each do |_, v|
    pairs += v / 2
    cherries += v % 2
  end

  base = (pairs / k) * 2
  cherries += (pairs % k) * 2
  if cherries >= k
    base += 1
  end

  p [base, 1].max
end

gets.to_i.times do
  n, k = gets.split.map(&:to_i)
  h = Hash.new 0
  gets.strip.each_char { h[_1] += 1 }

  pairs = 0; cherries = 0
  h.each do |_, v|
    if v > 1
      pairs += v / 2
      cherries += v % 2
    else
      cherries += 1
    end
  end

  base = (pairs / k) * 2
  cherries += (pairs % k) * 2
  poor = k - pairs % k
  poor = k if poor == 0
  if cherries >= poor
    base += 1
  end

  p [base, 1].max
end


Consider a table of size $$$n \times m$$$, initially fully white. Rows are numbered $$$1$$$ through $$$n$$$ from top to bottom, columns $$$1$$$ through $$$m$$$ from left to right. Some square inside the table with odd side length was painted black. Find the center of this square.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 115$$$) — the number of rows and the number of columns in the table. The $$$i$$$-th of the next $$$n$$$ lines contains a string of $$$m$$$ characters $$$s_{i1} s_{i2} \ldots s_{im}$$$ ($$$s_{ij}$$$ is 'W' for white cells and 'B' for black cells), describing the $$$i$$$-th row of the table.

Output two integers $$$r$$$ and $$$c$$$ ($$$1 \le r \le n$$$, $$$1 \le c \le m$$$) separated by a space — the row and column numbers of the center of the black square.

$<.each_with_index{|e,i|
j=e.index('B')
if j;c=e.count('B')/2+1;puts [i-1+c,j+c]*' ';break;end
}

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

ary = []
n.times do
  ary << gets.strip
end

rf=-1
cf=-1
len = 0
0.upto(n-1).each do |i|
  0.upto(m-1).each do |j|
    if ary[i][j]=='B'
      rf=i
      cf=j if cf==-1
      len+=1
    end
  end
  break if rf!=-1
end

# puts "#{rf} #{cf} #{len}"
puts "#{rf+1 + (len/2)} #{cf+1 + (len/2)}"

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

bf = []
bl = []

n.times do |i|
  gets.chomp.chars.each_with_index do |cell, j|
    if cell == 'B'
      if bf == []
        bf = [i, j]
      end
      bl = [i, j]
    end
  end
end

na = (bf[0]+bl[0])/2 + 1
ma = (bf[1]+bl[1])/2 + 1

puts "#{na} #{ma}"

n, m = gets.split.map &:to_i
s = []
n.times { s << gets.chomp }
i, j = 0, 0
catch :found do
  n.times do |y|
    m.times do |x|
      if s[y][x] == 'B'
        i, j = y, x
        throw :found
      end
    end
  end
end
d = (s[i].rindex('B') - s[i].index('B'))/2
puts "#{1 + i + d} #{1 + j + d}"