Ilya is very fond of graphs, especially trees. During his last trip to the forest Ilya found a very interesting tree rooted at vertex 1. There is an integer number written on each vertex of the tree; the number written on vertex i is equal to ai.Ilya believes that the beauty of the vertex x is the greatest common divisor of all numbers written on the vertices on the path from the root to x, including this vertex itself. In addition, Ilya can change the number in one arbitrary vertex to 0 or leave all vertices unchanged. Now for each vertex Ilya wants to know the maximum possible beauty it can have.For each vertex the answer must be considered independently.The beauty of the root equals to number written on it.

First line contains one integer number n — the number of vertices in tree (1 ≤ n ≤ 2·105). Next line contains n integer numbers ai (1 ≤ i ≤ n, 1 ≤ ai ≤ 2·105). Each of next n - 1 lines contains two integer numbers x and y (1 ≤ x, y ≤ n, x ≠ y), which means that there is an edge (x, y) in the tree.

Output n numbers separated by spaces, where i-th number equals to maximum possible beauty of vertex i.

#!/usr/bin/env ruby
# encoding: utf-8
n = gets.to_i
a = gets.split.map(&:to_i)
g = Array.new(n) { [] }

(n-1).times do
    u, v = gets.split.map(&:to_i)
    u, v = u-1, v-1
    g[u] << v
    g[v] << u
end

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

dp = Array.new(n) { Array.new(2) { [] } }
dp[0] = [[a[0]], [0]]
par = [-1]*n

st = [0]
until st.empty?
    u = st.pop
    g[u].each do |v|
        next if v == par[u]
        par[v] = u
        st.push(v)
        dp[v][0] += dp[u][0].map{|x| GCD(x,a[v])}
        dp[v][1] += dp[u][0]
        dp[v][1] += dp[u][1].map{|x| GCD(x,a[v]) }
        2.times do |i|
            dp[v][i].uniq!
        end
    end
end

print a[0]
for u in 1...n do
    print " #{dp[u][1].max}"
end

n = gets.to_i
a = gets.split.map &:to_i
g = Array.new(n) { [] }

(n-1).times do
    u, v = gets.split.map &:to_i
    u, v = u-1, v-1
    g[u] << v
    g[v] << u
end

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

dp = Array.new(n) { Array.new(2) { [] } }
dp[0] = [[a[0]], [0]]
par = [-1]*n

q = [0]
until q.empty?
    u = q.shift
    g[u].each do |v|
        next if v == par[u]
        par[v] = u
        q.unshift(v)
        dp[u][0].each do |x|
            dp[v][0] << GCD(x, a[v]);
            dp[v][1] << x
        end
        dp[u][1].each do |x|
            dp[v][1] << GCD(x, a[v])
        end
        for i in 0..1 do
            dp[v][i].uniq!
        end
    end
end

print a[0]
for u in 1...n do
    print " #{dp[u][1].max}"
end


Vanya wants to pass n exams and get the academic scholarship. He will get the scholarship if the average grade mark for all the exams is at least avg. The exam grade cannot exceed r. Vanya has passed the exams and got grade ai for the i-th exam. To increase the grade for the i-th exam by 1 point, Vanya must write bi essays. He can raise the exam grade multiple times.What is the minimum number of essays that Vanya needs to write to get scholarship?

The first line contains three integers n, r, avg (1 ≤ n ≤ 105, 1 ≤ r ≤ 109, 1 ≤ avg ≤ min(r, 106)) — the number of exams, the maximum grade and the required grade point average, respectively. Each of the following n lines contains space-separated integers ai and bi (1 ≤ ai ≤ r, 1 ≤ bi ≤ 106).

In the first line print the minimum number of essays.

NoteIn the first sample Vanya can write 2 essays for the 3rd exam to raise his grade by 2 points and 2 essays for the 4th exam to raise his grade by 1 point.In the second sample, Vanya doesn't need to write any essays as his general point average already is above average.

n, r, avg = gets.split.map(&:to_i)
total = avg * n

arr = []
n.times do
   ai, bi = gets.split.map(&:to_i)
   total -= ai
   if r > ai
       arr << [bi, r - ai]
   end
end

res = 0
if total > 0
    arr = arr.sort
    arr.each do |item|
        tmp = [total, item[1]].min
        res += tmp * item[0]
        total -= tmp
    end
end

puts res

n, r, avg = gets.split.collect {|x| x.to_i}
total = avg * n

arr = []
n.times do
   ai, bi = gets.split.collect {|x| x.to_i}
   total -= ai
   arr.push [bi, ai]
end

res = 0
if total > 0
    arr = arr.sort
    arr.each do |item|
        tmp = [total, r - item[1]].min
        res += tmp * item[0]
        total -= tmp
    end
end

puts res

n, r, avg = gets.split(" ").collect {|x| x.to_i}
total = avg * n

arr = []
n.times do
   ai, bi = gets.split(" ").collect {|x| x.to_i}
   total -= ai
   arr.push [bi, ai]
end

res = 0
if total > 0
    arr = arr.sort
    arr.each do |item|
        tmp = [total, r - item[1]].min
        res += tmp * item[0]
        total -= tmp
    end
end

puts res

n, r, avg = gets.split.map(&:to_i)
total = avg * n

arr = []
n.times do
   ai, bi = gets.split.map(&:to_i)
   total -= ai
   arr.push [bi, ai]
end

res = 0
if total > 0
    arr = arr.sort
    arr.each do |item|
        tmp = [total, r - item[1]].min
        res += tmp * item[0]
        total -= tmp
    end
end

puts res

n, r, avg = gets.split(' ').map(&:to_i)
total = avg * n

arr = []
n.times do
   ai, bi = gets.split(' ').map(&:to_i)
   total -= ai
   arr.push [bi, ai]
end

res = 0
if total > 0
    arr = arr.sort
    arr.each do |item|
        tmp = [total, r - item[1]].min
        res += tmp * item[0]
        total -= tmp
    end
end

puts res

n, r, avg = gets.split.map(&:to_i)
total = avg * n

arr = []
n.times do
   ai, bi = gets.split.map(&:to_i)
   total -= ai
   arr << [bi, ai]
end

res = 0
if total > 0
    arr = arr.sort
    arr.each do |item|
        tmp = [total, r - item[1]].min
        res += tmp * item[0]
        total -= tmp
    end
end

puts res

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

n, r, avg = gets.chomp.split.map(&:to_i)
req = n * avg

s = []
n.times do
  tmp = gets.split.map(&:to_i)
  req -= tmp[0]
  unless r <= tmp[0]
    tmp[0] = r - tmp[0]
    s << tmp
  end
end

if req <= 0
  puts 0
  exit 0
end

s.sort_by! { |a| a[1] }

i = 0
essays = 0
while 0 < req and i < n
  a = s[i][0]
  essay = s[i][1]
  if req <= a
    essays += req * essay
    break
  end
  essays += a * essay
  i += 1
  req -= a
end

puts essays

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

n, r, avg = gets.chomp.split.map(&:to_i)
req = n * avg

s = []
n.times do
  tmp = gets.split.map(&:to_i)
  req -= tmp[0]
  unless r <= tmp[0]
    #tmp[0] = r - tmp[0]
    s << tmp
  end
end

if req <= 0
  puts 0
  exit 0
end

s.sort_by! { |a| a[1] }

i = 0
essays = 0
while 0 < req and i < n
  grade = s[i][0]
  essay = s[i][1]
  a = (r - grade)
  if req <= a
    essays += req * essay
    break
  end
  essays += a * essay
  i += 1
  req -= a
end

puts essays

class Point
  def initialize(a,b)
    @a = a
    @b = b
  end
  def a
    @a
  end
  def b
    @b
  end
end

p= Array.new
n , r , avg = gets.split.map(&:to_i)
sum, ans, i= 0, 0, 0
n.times do
  x, y= gets.split.map(&:to_i)
  p<<Point.new(x,y)
  sum += x
end

p.sort_by!{|x| x.b}

  until sum>=avg*n
    sum += r-p[i].a
    ans += (r-p[i].a)*p[i].b
    i += 1
  end
  r=ans-(sum-avg*n)*p[i-1].b
  puts r>0?r:0

def read_ints; STDIN.gets.split.map(&:to_i); end

n, r, avg = read_ints
avg *= n
a = []
cur_avg = 0
n.times do
  a << read_ints
  cur_avg += a[-1][0]
end
ans = 0
a.sort_by!{|x| x[1]}
a.each do |x|
  break if cur_avg >= avg
  mn =[r - x[0], avg - cur_avg].min
    ans += mn * x[1]
    cur_avg += mn
end
puts ans

def read_ints; STDIN.gets.split.map(&:to_i); end

n, r, avg = read_ints
avg *= n
a = []
cur_avg = 0
n.times do
  a << read_ints
  cur_avg += a[-1][0]
end
if cur_avg >= avg
  puts 0
  exit 0
end
ans = 0
a.sort_by!{|x| x[1]}
a.each do |x|
  if r - x[0] >= avg - cur_avg
    ans += x[1] * (avg - cur_avg)
    break
  end
    ans += (r - x[0]) * x[1]
    cur_avg += (r - x[0])
end

puts ans

def read_ints; STDIN.gets.split.map(&:to_i); end

n, r, avg = read_ints
avg *= n
a = []
cur_avg = 0
n.times do
  a << read_ints
  cur_avg += a[-1][0]
end
if cur_avg >= avg
  puts 0
  exit 0
end
ans = 0
a.sort_by{|x| x[1]}.each do |x|
  if r - x[0] >= avg - cur_avg
    ans += x[1] * (avg - cur_avg)
    break
  end
    ans += (r - x[0]) * x[1]
    cur_avg += (r - x[0])
end

puts ans

#$stdin = File.open("input.txt")

n, r, avg = gets.split.map &:to_i
exams = gets(nil).split("\n").map { |line| line.split.map &:to_i }

need = avg * n
have = exams.transpose.first.inject(:+)

exams.sort! { |a, b| a.last <=> b.last }

essays = 0
while have < need
	a, b = exams.first

	up = [need - have, r - a].min

	have   += up
	essays += up * b

	exams.shift
end

puts essays

def read_ints; STDIN.gets.split.map(&:to_i); end
n, r, avg = read_ints
a = []
i = 0
curSum = 0
n.times do
  a << read_ints
  a[i].reverse!
  curSum+= a[i][1]
  i+=1
end
a.sort!
avgSum = avg*n
resEssays = 0
i=0
while(curSum<avgSum)
  j = [avgSum - curSum, r - a[i][1]]
  curEssays = j.min
  resEssays+= curEssays * a[i][0];
  curSum += curEssays
  i+=1
end
puts resEssays

class Stu
  attr_accessor:a
  attr_accessor:b
end

pa=Array.new
pb=Array.new

str=gets.to_s
pa=str.split
n=pa[0].to_i
r=pa[1].to_i
avg=pa[2].to_i
s=n*avg

for i in 0..n-1
  str=gets.to_s
  pa=str.split
  pb[i]=Stu.new
  s-=pa[0].to_i
  pb[i].a=r-pa[0].to_i
  pb[i].b=pa[1].to_i
end

if s<0
  s=0
end
pb=pb.sort_by{|x| x.b}
#p pb

k=0
for i in 0..n-1
  if pb[i].a>=s
    k+=pb[i].b*s
    break
  else
    s-=pb[i].a
    k+=pb[i].b*pb[i].a
  end
end

puts k

class Stu
  attr_accessor:a,:b
end

pa=Array.new
pb=Array.new

str=gets.to_s
pa=str.split
n=pa[0].to_i
r=pa[1].to_i
avg=pa[2].to_i
s=n*avg

for i in 0..n-1
  str=gets.to_s
  pa=str.split
  pb[i]=Stu.new
  s-=pa[0].to_i
  pb[i].a=r-pa[0].to_i
  pb[i].b=pa[1].to_i
end

if s<0
  s=0
end

pb.sort! {|x,y| x.b<=>y.b }
#p pb

k=0
for i in 0..n-1
  if pb[i].a>=s
    k+=pb[i].b*s
    break
  else
    s-=pb[i].a
    k+=pb[i].b*pb[i].a
  end
end

puts k

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

n, r, avg = gets.chomp.split.map(&:to_i)
req = n * avg

s = []
n.times do
  tmp = gets.split.map(&:to_i)
  req -= tmp[0]
  unless r <= tmp[0]
    tmp[0] = r - tmp[0]
    s << tmp
  end
end

s.sort_by! { |a| a[1] }

essays = 0
s.each do |a|
  is_break = false
  a[0].times do |i|
    req -= 1
    essays += a[1]
    is_break = true and break if req <= 0
  end
  break if is_break
end

puts essays

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

n, r, avg = gets.chomp.split.map(&:to_i)
req = n * avg

s = []
n.times do
  tmp = gets.split.map(&:to_i)
  req -= tmp[0]
  unless r <= tmp[0]
    tmp[0] = r - tmp[0]
    s << tmp
  end
end

if req <= 0
  puts 0
  exit 0
end

s.sort_by! { |a| a[1] }

essays = 0
s.each do |a|
  if 0 <= req - a[0]
    req -= a[0]
    essays += a[0] * a[1]
    break if req <= 0
    next
  end
  req -= 1
  essays += a[1]
  break if req <= 0
end

puts essays

def read_ints; STDIN.gets.split.map(&:to_i); end

n, r, avg = read_ints
avg *= n
a = []
cur_avg = 0
n.times do
  a << read_ints
  cur_avg += a[-1][0]
end
if cur_avg > avg
  puts 0
  exit 0
end
ans = 0
a.each do |x|
  if r - x[0] >= avg - cur_avg
    ans += x[1] * (avg - cur_avg)
    break
  end
    ans += (r - x[0]) * x[1]
    cur_avg += (r - x[0])
end

puts ans

n, r, avg = gets.split.map &:to_i
exams = gets(nil).split("\n").map { |line| line.split.map &:to_i }

need = avg * n
have = exams.transpose.first.inject(:+)

exams.sort! { |a, b| a.last <=> b.last }

essays = 0
while have < need
    a, b = exams.first

    up = [need - have, r - a].min

    have   += up
    essays += up * b

    exams.unshift
end

puts essays


Pasha has recently bought a new phone jPager and started adding his friends' phone numbers there. Each phone number consists of exactly n digits.Also Pasha has a number k and two sequences of length n / k (n is divisible by k) a1, a2, ..., an / k and b1, b2, ..., bn / k. Let's split the phone number into blocks of length k. The first block will be formed by digits from the phone number that are on positions 1, 2,..., k, the second block will be formed by digits from the phone number that are on positions k + 1, k + 2, ..., 2·k and so on. Pasha considers a phone number good, if the i-th block doesn't start from the digit bi and is divisible by ai if represented as an integer. To represent the block of length k as an integer, let's write it out as a sequence c1, c2,...,ck. Then the integer is calculated as the result of the expression c1·10k - 1 + c2·10k - 2 + ... + ck.Pasha asks you to calculate the number of good phone numbers of length n, for the given k, ai and bi. As this number can be too big, print it modulo 109 + 7.

The first line of the input contains two integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ min(n, 9)) — the length of all phone numbers and the length of each block, respectively. It is guaranteed that n is divisible by k. The second line of the input contains n / k space-separated positive integers — sequence a1, a2, ..., an / k (1 ≤ ai < 10k). The third line of the input contains n / k space-separated positive integers — sequence b1, b2, ..., bn / k (0 ≤ bi ≤ 9).

Print a single integer — the number of good phone numbers of length n modulo 109 + 7.

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

block = n / k

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

answer = 1

for i in 0..(block - 1)
  ans = (10**k - 1) / a[i] + 1

  degree =  10**(k - 1)
  ans -= ((b[i] + 1) * degree - 1) / a[i]
  ans += (b[i] * degree - 1) / a[i]

  answer *= ans
  answer %= 1000000007
end

puts answer

#! ruby
# Try Codeforces
# author: Leonardone @ NEETSDKASU

n, k = gets.chomp.split.map(&:to_i)
a = gets.chomp.split
b = gets.chomp.split

x = 10 ** k
xx = 10 ** k.pred
md = (10 ** 9) + 7

f = "%0" + k.to_s + "d"
ans = 1

a.size.times do |i|
    c = 0
    v = 0
    ai = a[i].to_i
    bi = b[i].to_i
    if a[i].size == k
        while v < x
            if (f % [v])[0] != b[i]
                c += 1
            end
            v += ai
        end
    else
        c = x.pred.div(ai).succ
        if bi == 0
            c -= xx.pred.div(ai).succ
        else
            c -= bi.succ.*(xx).pred.div(ai).succ - bi.*(xx).pred.div(ai).succ
        end
    end
    ans *= c
    ans %= md
end

puts ans.%(md)

#!/usr/bin/env ruby
phone_length, block_length = gets.split(' ').map(&:to_i)

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

possibilities_in_each_block = a.zip(b).map do |a_i, b_i|
  vsego_kratnix = (10**(block_length) - 1).div(a_i)

  #require 'byebug'
  #debugger
  kratnix_i_startujut_s_b_itogo = ((b_i+1)*(10**(block_length-1)) - 1).div(a_i) - (b_i*(10**(block_length-1)) - 1).div(a_i)

  nulevoi_element = 1

  nulevoi_element + vsego_kratnix - kratnix_i_startujut_s_b_itogo
end

big_modulo = 10**9 + 7

def fast_product_stupid(int_arr_product, big_modulo)
  total = 1
  int_arr_product.each do |num|
    total = (num*total).modulo(big_modulo)
  end
  total
end

puts fast_product_stupid(possibilities_in_each_block, big_modulo)

n, k = gets.chomp.split.map(&:to_i)
as = gets.chomp.split.map(&:to_i)
bs = gets.chomp.split.map(&:to_i)
mod = (1E9 + 7).to_i

ans = 1
for i in 0...(n / k)
  ans = ans * ((10**k - 1) / as[i] + 1 - (bs[i] * 10**(k - 1) + 10**(k - 1) - 1) / as[i] + (bs[i] * 10**(k - 1) - 1) / as[i]) % mod
end

puts ans

#!/usr/bin/ruby

n, k = gets.strip().split(" ")
n = n.to_i
k = k.to_i
a = gets.strip().split(" ")
a = a.map(&:to_i)
b = gets.strip().split(" ")
b = b.map(&:to_i)
m = n / k;
ans = 1;
for i in 0..m - 1
    if b[i] == 0
        tmp = 10 ** (k - 1)
        mul = (tmp * 10 - 1) / a[i] - tmp / a[i] + 1
        if tmp % a[i] > 0
            mul -= 1
        end
    else
        tmp = 10 ** (k - 1)
        mul = (tmp * 10 - 1) / a[i] - tmp * (b[i] + 1) / a[i] + 1 + (tmp * b[i] - 1) / a[i] + 1
        if tmp * (b[i] + 1) % a[i] > 0
            mul -= 1
        end
    end
    ans = ans * mul
    ans %= 10 ** 9 + 7
end
print ans, "\n"

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

block = n / k

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

answer = 1

for i in 0..(block - 1)
  degree =  10**(k - 1)

  ans = (10**k - 1) / a[i] + 1

  ans -= ((b[i] + 1) * degree - 1) / a[i]
  ans += (b[i] * degree - 1) / a[i]

  answer *= ans
end

puts answer

#! ruby
# Try Codeforces
# author: Leonardone @ NEETSDKASU

n, k = gets.chomp.split.map(&:to_i)
a = gets.chomp.split
b = gets.chomp.split

x = 10 ** k
xx = 10 ** k.pred

f = "%0" + k.to_s + "d"
ans = 1

n.div(k).times do |i|
    c = 0
    v = 0
    ai = a[i].to_i
    bi = b[i].to_i
    if a[i].size == k
        while v < x
            if (f % v)[0] != b[i]
                c += 1
            end
            v += ai
        end
    else
        c = x.pred.div(ai).succ
        if bi == 0
            c -= xx.pred.div(ai).succ
        else
            c -= bi.*(xx).div(ai).succ - bi.pred.*(xx).div(ai).succ
        end
    end
    ans *= c
end

puts ans.%((10 ** 9) + 7)

#!/usr/bin/env ruby
phone_length, block_length = gets.split(' ').map(&:to_i)

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

possibilities_in_each_block = a.zip(b).map do |a_i, b_i|
  valid_parts_in_block = ('9'*block_length).to_i.div(a_i)
  next 1 if valid_parts_in_block == 0

  valid_parts_in_block.downto(1).take_while do |kratnoe|
    num = (kratnoe*a_i).to_s

    longest_kratnoe = num.length == block_length
    if (longest_kratnoe && num[0] == b_i)
      valid_parts_in_block -= 1
    end

    longest_kratnoe
  end

  next valid_parts_in_block+1 # zero
end

big_modulo = 10**9 + 7

def fast_product_stupid(int_arr_product, big_modulo)
  total = 1
  int_arr_product.each do |num|
    total = (num*total).modulo(big_modulo)
  end
  total
end

puts fast_product_stupid(possibilities_in_each_block, big_modulo)

n, k = gets.chomp.split.map(&:to_i)
as = gets.chomp.split.map(&:to_i)
bs = gets.chomp.split.map(&:to_i)
mod = (1E9 + 7).to_i
ans = 1
for i in 0...(n / k)
  ans = ans * (99 / as[i] - ((bs[i] * 10 + 9) / as[i]) + (bs[i] * 10 - 1) / as[i] + 1) % mod
end

puts ans

#!/usr/bin/ruby

n, k = gets.strip().split(" ")
n = n.to_i
k = k.to_i
a = gets.strip().split(" ")
a = a.map(&:to_i)
b = gets.strip().split(" ")
b = b.map(&:to_i)
m = n / k;
ans = 1;
for i in 0..m - 1
    if b[i] == 0
        tmp = 10 ** (k - 1)
        mul = (tmp * 10 - 1) / a[i] - tmp / a[i] + 1
        if tmp % a[i] > 0
            mul -= 1
        end
    else
        tmp = 10 ** (k - 1)
        mul = (tmp * 10 - 1) / a[i] - tmp * (b[i] + 1) / a[i] + 1 + (tmp * b[i] - 1) / a[i] + 1
        if tmp * (b[i] + 1) % a[i]
            mul -= 1
        end
    end
    ans = ans * mul
    ans %= 10 ** 9 + 7
end
print ans, "\n"


Limak is a little polar bear. He doesn't have many toys and thus he often plays with polynomials.He considers a polynomial valid if its degree is n and its coefficients are integers not exceeding k by the absolute value. More formally:Let a0, a1, ..., an denote the coefficients, so . Then, a polynomial P(x) is valid if all the following conditions are satisfied:  ai is integer for every i;  |ai| ≤ k for every i;  an ≠ 0. Limak has recently got a valid polynomial P with coefficients a0, a1, a2, ..., an. He noticed that P(2) ≠ 0 and he wants to change it. He is going to change one coefficient to get a valid polynomial Q of degree n that Q(2) = 0. Count the number of ways to do so. You should count two ways as a distinct if coefficients of target polynoms differ.

The first line contains two integers n and k (1 ≤ n ≤ 200 000, 1 ≤ k ≤ 109) — the degree of the polynomial and the limit for absolute values of coefficients. The second line contains n + 1 integers a0, a1, ..., an (|ai| ≤ k, an ≠ 0) — describing a valid polynomial . It's guaranteed that P(2) ≠ 0.

Print the number of ways to change one coefficient to get a valid polynomial Q that Q(2) = 0.

NoteIn the first sample, we are given a polynomial P(x) = 10 - 9x - 3x2 + 5x3.Limak can change one coefficient in three ways:  He can set a0 =  - 10. Then he would get Q(x) =  - 10 - 9x - 3x2 + 5x3 and indeed Q(2) =  - 10 - 18 - 12 + 40 = 0.  Or he can set a2 =  - 8. Then Q(x) = 10 - 9x - 8x2 + 5x3 and indeed Q(2) = 10 - 18 - 32 + 40 = 0.  Or he can set a1 =  - 19. Then Q(x) = 10 - 19x - 3x2 + 5x3 and indeed Q(2) = 10 - 38 - 12 + 40 = 0. In the second sample, we are given the same polynomial. This time though, k is equal to 12 instead of 109. Two first of ways listed above are still valid but in the third way we would get |a1| > k what is not allowed. Thus, the answer is 2 this time.

n, k = gets.split(" ").map(&:to_i)
c = gets.split(" ").map(&:to_i)
# n = 200000
# k = 87425
# c = [0]*200000+[1]

$c=c
def calc(i, n)
    return $c[i] if n == 1
    return calc(i, n/2) + (calc(i+n/2, n-n/2) << (n/2))
end
y = calc(0, $c.size)
# p y

bits = y.abs.to_s(2).reverse

ans = 0
i = 0
while i <= n
    x = y - c[i]
    if x.abs > 2**1000
        i += 200
        y = y >> 200
        next
    end
    if -k <= x && x <= k && (i < n || x != 0)
        ans += 1
    end
    break if bits[i] == '1'
    y /= 2
    i += 1
end
puts ans

n, k = gets.split(" ").map(&:to_i)
c = gets.split(" ").map(&:to_i)

y = 0
(n+1).times do |i|
    y += c[i] * (2 ** i)
    # puts (c[i] * (2 ** i)).to_s(2).reverse
end
y = y.abs

s = y.to_s(2).reverse
# puts y
# puts s

ans = 0
n.times do |i|

    if y <= k
        ans += 1
    end

    y /= 4
    y *= 2

    if s[i] == "1"
        puts ans
        exit
    end
end
puts ans

n, k = gets.split(" ").map(&:to_i)
c = gets.split(" ").map(&:to_i)

def calc(c)
    y = 0
    c.size.times do |i|
        y += c[i] * (2 ** i)
    end
    y
end
y = calc(c)

ans = 0
n.times do |i|
    # p [y, c[i]]
    x = []#c.dup
    x[i] = -(y-c[i])
    # p [x[i], calc(x)]
    if x[i].abs <= k
        ans += 1
    end

    break if y%2 == 1
    y /= 2
end
puts ans

n, k = gets.split(" ").map(&:to_i)
c = gets.split(" ").map(&:to_i)

y = 0
(n+1).times do |i|
    y += c[i] * (2 ** i)
    # puts (c[i] * (2 ** i)).to_s(2).reverse
end

s = y.abs.to_s(2).reverse + "0"*n
# puts y
# puts s

ans = 0
n.times do |i|
    # p [y, c[i]]
    if (y - c[i]).abs <= k
        ans += 1
    end

    y /= 2

    if s[i] == "1"
        puts ans
        exit
    end
end
puts ans

n, k = gets.split(" ").map(&:to_i)
c = gets.split(" ").map(&:to_i)
n = 200000
k = 87425
c = [0]*200000+[1]

$c=c
def calc(i, n)
    return $c[i] if n == 1
    return calc(i, n/2) + (calc(i+n/2, n-n/2) << (n/2))
end
y = calc(0, $c.size)
# p y

bits = y.abs.to_s(2).reverse

ans = 0
i = 0
while i <= n
    x = y - c[i]
    if x.abs > 2**1000
        i += 200
        y = y >> 200
        next
    end
    if -k <= x && x <= k && (i < n || x != 0)
        ans += 1
    end
    break if bits[i] == '1'
    y /= 2
    i += 1
end
puts ans


Vova plans to go to the conference by train. Initially, the train is at the point $$$1$$$ and the destination point of the path is the point $$$L$$$. The speed of the train is $$$1$$$ length unit per minute (i.e. at the first minute the train is at the point $$$1$$$, at the second minute — at the point $$$2$$$ and so on).There are lanterns on the path. They are placed at the points with coordinates divisible by $$$v$$$ (i.e. the first lantern is at the point $$$v$$$, the second is at the point $$$2v$$$ and so on).There is also exactly one standing train which occupies all the points from $$$l$$$ to $$$r$$$ inclusive.Vova can see the lantern at the point $$$p$$$ if $$$p$$$ is divisible by $$$v$$$ and there is no standing train at this position ($$$p \not\in [l; r]$$$). Thus, if the point with the lantern is one of the points covered by the standing train, Vova can't see this lantern.Your problem is to say the number of lanterns Vova will see during the path. Vova plans to go to $$$t$$$ different conferences, so you should answer $$$t$$$ independent queries.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of queries. Then $$$t$$$ lines follow. The $$$i$$$-th line contains four integers $$$L_i, v_i, l_i, r_i$$$ ($$$1 \le L, v \le 10^9$$$, $$$1 \le l \le r \le L$$$) — destination point of the $$$i$$$-th path, the period of the lantern appearance and the segment occupied by the standing train.

Print $$$t$$$ lines. The $$$i$$$-th line should contain one integer — the answer for the $$$i$$$-th query.

NoteFor the first example query, the answer is $$$3$$$. There are lanterns at positions $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$ and $$$10$$$, but Vova didn't see the lanterns at positions $$$4$$$ and $$$6$$$ because of the standing train.For the second example query, the answer is $$$0$$$ because the only lantern is at the point $$$51$$$ and there is also a standing train at this point.For the third example query, the answer is $$$1134$$$ because there are $$$1234$$$ lanterns, but Vova didn't see the lanterns from the position $$$100$$$ to the position $$$199$$$ inclusive.For the fourth example query, the answer is $$$0$$$ because the standing train covers the whole path.

gets.to_i.times do
	n, v, l, r = gets.split.map(&:to_i)
	puts n / v - (r / v - l.pred / v)
end

def go
  l, v, s, e = read_ints

  count = 0
  # interval before train
  from = v
  to = s - 1
  count += ((to-from)/v) + 1 if from <= to

  # interval after train
  from = e + 1
  to = (l.to_f / v).floor * v
  count += ((to-from)/v) + 1 if from <= to

  puts count
end

def solution
  n = read_int
  n.times do
    go
  end
end

def read_int
  gets.to_i
end

def read_ints
  gets.split.map(&:to_i)
end

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']

def solve
  t = gets.strip.to_i
  t.times do
    d, v, l, r = gets.strip.split.map(&:to_i)
    puts (d / v) - ( (r / v) - (l / v) + (l % v == 0 ? 1 : 0))
  end
end

solve

gets.to_i.times do
  a,v,l,r = gets.split.map(&:to_i)
  puts a/v-r/v+(l-1)/v
end

# https://codeforces.com/problemset/problem/1066/A
def solution(d, v, l, r)
  return (d / v) - (r / v) + ((l - 1) / v)
end

n = gets.chomp.to_i
n.times do
  d, v, l, r = gets.chomp.split(" ").map(&:to_i)
  puts solution(d, v, l, r)
end

def lights(len, v)
	(len + v)/v - 1
end
n = gets.chomp
n.to_i.times do |i|
	line = gets.chomp
	len, v, l, r = line.split.map(&:to_i)
	res = lights(len, v)
	#puts res
	res = res - ( lights(r,v) - lights(l - 1,v) )
	puts res
end

n = gets.strip.to_i

out = []
n.times do
    arr = gets.strip.split(' ').map(&:to_i)
    start = arr[2] - 1

    start2 = arr[3] + 1
    end2 = arr[0]

    final = (start / arr[1]).floor + (end2 / arr[1]).floor - (start2 / arr[1]).floor
    if (start2 % arr[1] == 0 && end2 % arr[1] == 0)
        final += 1
    elsif (start2 % arr[1] == 0 && end2 % arr[1] != 0)
        final += 1
    end
    out << final
end

out.each do |o|
    puts o
end

n = gets.strip.to_i

out = []
n.times do
    arr = gets.strip.split(' ').map(&:to_i)
    start = arr[2] - 1

    start2 = arr[3] + 1
    end2 = arr[0]

    final = (start / arr[1]).floor + (end2 / arr[1]).floor - (start2 / arr[1]).floor
    if (start2 % arr[1] == 0 && end2 % arr[1] == 0)
        final += 1
    end
    out << final
end

out.each do |o|
    puts o
end

n = gets.strip.to_i

out = []
n.times do
    arr = gets.strip.split(' ').map(&:to_i)
    start = arr[2] - 1

    start2 = arr[3] + 1
    end2 = arr[0]

    final = (start / arr[1]).floor + (end2 / arr[1]).floor - (start2 / arr[1]).floor
    if (start2 % arr[1] == 0 || end2 % arr[1] == 0)
        final += 1
    end
    out << final
end

out.each do |o|
    puts o
end


Monocarp is playing yet another computer game. In this game, his character has to kill a dragon. The battle with the dragon lasts $$$100^{500}$$$ seconds, during which Monocarp attacks the dragon with a poisoned dagger. The $$$i$$$-th attack is performed at the beginning of the $$$a_i$$$-th second from the battle start. The dagger itself does not deal damage, but it applies a poison effect on the dragon, which deals $$$1$$$ damage during each of the next $$$k$$$ seconds (starting with the same second when the dragon was stabbed by the dagger). However, if the dragon has already been poisoned, then the dagger updates the poison effect (i.e. cancels the current poison effect and applies a new one).For example, suppose $$$k = 4$$$, and Monocarp stabs the dragon during the seconds $$$2$$$, $$$4$$$ and $$$10$$$. Then the poison effect is applied at the start of the $$$2$$$-nd second and deals $$$1$$$ damage during the $$$2$$$-nd and $$$3$$$-rd seconds; then, at the beginning of the $$$4$$$-th second, the poison effect is reapplied, so it deals exactly $$$1$$$ damage during the seconds $$$4$$$, $$$5$$$, $$$6$$$ and $$$7$$$; then, during the $$$10$$$-th second, the poison effect is applied again, and it deals $$$1$$$ damage during the seconds $$$10$$$, $$$11$$$, $$$12$$$ and $$$13$$$. In total, the dragon receives $$$10$$$ damage.Monocarp knows that the dragon has $$$h$$$ hit points, and if he deals at least $$$h$$$ damage to the dragon during the battle — he slays the dragon. Monocarp has not decided on the strength of the poison he will use during the battle, so he wants to find the minimum possible value of $$$k$$$ (the number of seconds the poison effect lasts) that is enough to deal at least $$$h$$$ damage to the dragon.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of the test case contains two integers $$$n$$$ and $$$h$$$ ($$$1 \le n \le 100; 1 \le h \le 10^{18}$$$) — the number of Monocarp's attacks and the amount of damage that needs to be dealt. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 10^9; a_i < a_{i + 1}$$$), where $$$a_i$$$ is the second when the $$$i$$$-th attack is performed.

For each test case, print a single integer — the minimum value of the parameter $$$k$$$, such that Monocarp will cause at least $$$h$$$ damage to the dragon.

NoteIn the first example, for $$$k=3$$$, damage is dealt in seconds $$$[1, 2, 3, 5, 6, 7]$$$.In the second example, for $$$k=4$$$, damage is dealt in seconds $$$[2, 3, 4, 5, 6, 7, 10, 11, 12, 13]$$$.In the third example, for $$$k=1$$$, damage is dealt in seconds $$$[1, 2, 4, 5, 7]$$$.

gets.to_i.times do
  n, h = gets.split.map(&:to_i)
  as = gets.split.map(&:to_i)
  check = ->k {
    k + as.each_cons(2).map { |a, b| [(b - a), k].min }.sum >= h
  }
  p (1..10 ** 18).bsearch { |k| check[k] }
end


Timur's grandfather gifted him a chessboard to practice his chess skills. This chessboard is a grid $$$a$$$ with $$$n$$$ rows and $$$m$$$ columns with each cell having a non-negative integer written on it. Timur's challenge is to place a bishop on the board such that the sum of all cells attacked by the bishop is maximal. The bishop attacks in all directions diagonally, and there is no limit to the distance which the bishop can attack. Note that the cell on which the bishop is placed is also considered attacked. Help him find the maximal sum he can get.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains the integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 200$$$, $$$1 \leq m \leq 200$$$). The following $$$n$$$ lines contain $$$m$$$ integers each, the $$$j$$$-th element of the $$$i$$$-th line $$$a_{ij}$$$ is the number written in the $$$j$$$-th cell of the $$$i$$$-th row $$$(0\leq a_{ij} \leq 10^6)$$$ It is guaranteed that the sum of $$$n\cdot m$$$ over all test cases does not exceed $$$4\cdot10^4$$$.

For each test case output a single integer, the maximum sum over all possible placements of the bishop.

NoteFor the first test case here the best sum is achieved by the bishop being in this position:

gets.to_i.times do
  n, m = gets.split.map(&:to_i)
  ass = n.times.map { gets.split.map(&:to_i) }
  answer = 0.upto(n - 1).map do |i|
    0.upto(m - 1).map do |j|
      sum = ass[i][j]
      [[-1, -1], [-1, 1], [1, -1], [1, 1]].map do |di, dj|
        ii, jj = i + di, j + dj
        while ii >= 0 && ii <= n - 1 && jj >= 0 && jj <= m - 1
          sum += ass[ii][jj]
          ii += di
          jj += dj
        end
      end
      sum
    end.max
  end.max
  p answer
end

Pointer = Struct.new(:value)

gets.to_i.times do
  n, m = gets.split.map(&:to_i)
  ass = n.times.map { gets.split.map(&:to_i) }
  go = ->(i, j, di, dj, map) {
    pointer = Pointer.new(0)
    while i < n && j < m && i >= 0 && j >= 0
      map[[i, j]] = pointer
      pointer.value += ass[i][j]
      i += di
      j += dj
    end
  }
  ltr, rtl = {}, {}
  0.upto(n - 1) { |i| go[i, 0, 1, 1, ltr] }
  0.upto(m - 1) { |j| go[0, j, 1, 1, ltr] }
  0.upto(n - 1) { |i| go[i, m - 1, 1, -1, rtl] }
  0.upto(m - 1) { |j| go[0, j, 1, -1, rtl] }
  answer = 0.upto(n - 1).map do |i|
    0.upto(m - 1).map do |j|
      ltr[[i, j]].value + rtl[[i, j]].value - ass[i][j]
    end.max
  end.max
  p answer
end

gets.to_i.times do
  n, m = gets.split.map(&:to_i)
  diag = {}
  rdiag = {}

  as = Array.new(n) { gets.split.map(&:to_i) }

  n.times { |i|
    m.times { |j|
      di = j - i
      diag[di] ||= 0
      diag[di]  += as[i][j]

      rdi = m - 1 - j - i
      rdiag[rdi] ||= 0
      rdiag[rdi]  += as[i][j]
    }
  }

  ans = nil
  n.times { |i|
    m.times { |j|
      cur = diag[j - i] + rdiag[m - 1 - j - i] - as[i][j]
      ans = cur if !ans || cur > ans
    }
  }

  p ans
end

def solve
  h, w = gli
  b = []
  h.times { b << gli }
  ans = 0
  (0...h).each do |i|
    (0...w).each do |j|
      tmp = b[i][j]
      (1..i).each do |q|
        break if i - q < 0 || j - q < 0

        tmp += b[i - q][j - q]
      end
      (1..i).each do |q|
        break if i - q < 0 || j + q >= w

        tmp += b[i - q][j + q]
      end
      (i + 1...h).each do |q|
        break if j - (q - i) < 0

        tmp += b[q][j - (q - i)]
      end
      (i + 1...h).each do |q|
        break if j + (q - i) >= w

        tmp += b[q][j + (q - i)]
      end

      ans = [ans, tmp].max
    end
  end
  puts ans
end

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

gets.to_i.times { solve }

main = -> {
  t = int
  t.times do
      n, m = ints
      a = rep(n) { ints }
      sum_x = Hash.new(0)
      sum_y = Hash.new(0)
      n.times do |i|
          m.times do |j|
              sum_x[i + j] += a[i][j]
              sum_y[i - j] += a[i][j]
          end
      end
      ans = 0
      n.times do |i|
          m.times do |j|
              ans = [ans, sum_x[i + j] + sum_y[i - j] - a[i][j]].max
          end
      end
      puts ans
  end
}

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

require "set"
require "prime"

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

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

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

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

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

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

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

main[]


Little Susie, thanks to her older brother, likes to play with cars. Today she decided to set up a tournament between them. The process of a tournament is described in the next paragraph.There are n toy cars. Each pair collides. The result of a collision can be one of the following: no car turned over, one car turned over, both cars turned over. A car is good if it turned over in no collision. The results of the collisions are determined by an n × n matrix А: there is a number on the intersection of the і-th row and j-th column that describes the result of the collision of the і-th and the j-th car:    - 1: if this pair of cars never collided.  - 1 occurs only on the main diagonal of the matrix.  0: if no car turned over during the collision.  1: if only the i-th car turned over during the collision.  2: if only the j-th car turned over during the collision.  3: if both cars turned over during the collision. Susie wants to find all the good cars. She quickly determined which cars are good. Can you cope with the task?

The first line contains integer n (1 ≤ n ≤ 100) — the number of cars. Each of the next n lines contains n space-separated integers that determine matrix A.  It is guaranteed that on the main diagonal there are  - 1, and  - 1 doesn't appear anywhere else in the matrix. It is guaranteed that the input is correct, that is, if Aij = 1, then Aji = 2, if Aij = 3, then Aji = 3, and if Aij = 0, then Aji = 0.

Print the number of good cars and in the next line print their space-separated indices in the increasing order.

n, c, s = Integer(gets), 0, ""

(1..n).each do |i|
	x = gets.split(" ")
	unless x.include? "1" or x.include? "3"
		c += 1
		s += "#{i} "
	end
end

puts c
if c > 0
	puts s
end

n = gets.to_i
ans = []
(1..n).each do |i|
    row = gets.split.map &:to_i
    ans.push i if not row.include? 1 and not row.include? 3
end
puts ans.size
ans.each do |a|
    print a.to_s + ' '
end
puts

# http://codeforces.com/contest/545/problem/A
n = gets.chomp.to_i
matrix = [].tap do |arr|
  n.times { arr << gets.chomp.split.map(&:to_i) }
end

good_cars = []
matrix.transpose.each.with_index do |row, idx|
  good_cars << idx + 1 unless (row.include?(2) || row.include?(3))
end

puts good_cars.length
puts good_cars.join(" ") unless good_cars.empty?

arr = []
gets.to_i.times do
  arr << gets.split.map { |x| x.to_i }.to_a
end
indices = []
count = 0
arr.each do |i|
  if !i.include?(1) && !i.include?(3)
    count += 1
    indices << arr.index(i) + 1
  end
end
puts count
indices.each { |x| print x, " " }

n=gets.to_i

ans=[]
n.times{|i|
	ans<<i+1
}

n.times{
	x=gets.split.map{|e| e.to_i}
	n.times{|i|
		ans[i]=0 if x[i]==2 || x[i]==3
	}
}
c=ans.count{|e| e!=0}
puts c
if c>0 then
puts ans.select{|e| e>0}*" "
end

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

# a.rb

def main()
    n = gets.to_i
    r = []
    n.times do |i|
        a = gets.chomp.split(" ").map{|s| next s.to_i }
        r << (i + 1) if !(a.index(1) || a.index(3))
    end
    puts r.size
    puts r * " " if r.size > 0
end

if __FILE__ == $0 then
    main()
end

n = gets.to_i
goodCars = []
amountOfGoodCar = 0
n.times do |i|
    crashes = gets.split(' ')
                  .map{|x| x.to_i}
                  .select{|x| x > 0 && x % 2 == 1}
    next if crashes.size > 0
    amountOfGoodCar += 1
    goodCars << i + 1
end

puts amountOfGoodCar
goodCars.each {|car| print "#{car} "}

n = gets.to_i
cars = 1.upto(n).select do |_|
  collisions = gets.split(' ').map(&:to_i)
  !collisions.include?(1) && !collisions.include?(3)
end

puts cars.length
puts cars.join(' ')

n = gets.to_i
ans = Array.new
n.times do |i|
    tmp = gets.split
    ans.push(i+1) if not tmp.include?("1") and not tmp.include?("3")
end
puts ans.size
puts ans.join(" ") unless ans.empty?

n = gets.chomp.to_i
ans = [*1..n]
ar = Array.new(n) { Array.new(n) }
for i in 0...n
  ar[i] = gets.split(" ").map{|i| i.to_i}
end
for i in 0...n
	for j in 0...n
		if ar[i][j] == 3
			ans.delete(i + 1)
			ans.delete(j + 1)
		elsif ar[i][j] == 1
			ans.delete(i + 1)
		elsif ar[i][j] == 2
			ans.delete(j + 1)
		end
	end
end
puts ans.size
puts ans.join(" ")


Implication is a function of two logical arguments, its value is false if and only if the value of the first argument is true and the value of the second argument is false. Implication is written by using character '', and the arguments and the result of the implication are written as '0' (false) and '1' (true). According to the definition of the implication:   When a logical expression contains multiple implications, then when there are no brackets, it will be calculated from left to fight. For example,. When there are brackets, we first calculate the expression in brackets. For example,.For the given logical expression  determine if it is possible to place there brackets so that the value of a logical expression is false. If it is possible, your task is to find such an arrangement of brackets.

The first line contains integer n (1 ≤ n ≤ 100 000) — the number of arguments in a logical expression. The second line contains n numbers a1, a2, ..., an (), which means the values of arguments in the expression in the order they occur.

Print "NO" (without the quotes), if it is impossible to place brackets in the expression so that its value was equal to 0. Otherwise, print "YES" in the first line and the logical expression with the required arrangement of brackets in the second line. The expression should only contain characters '0', '1', '-' (character with ASCII code 45), '>' (character with ASCII code 62), '(' and ')'. Characters '-' and '>' can occur in an expression only paired like that: ("->") and represent implication. The total number of logical arguments (i.e. digits '0' and '1') in the expression must be equal to n. The order in which the digits follow in the expression from left to right must coincide with a1, a2, ..., an. The expression should be correct. More formally, a correct expression is determined as follows:   Expressions "0", "1" (without the quotes) are correct.  If v1, v2 are correct, then v1->v2 is a correct expression.  If v is a correct expression, then (v) is a correct expression.  The total number of characters in the resulting expression mustn't exceed 106. If there are multiple possible answers, you are allowed to print any of them.

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

def dofail
    puts "NO"
    exit
end

def dook(s)
    puts "YES"
    puts s
    exit
end

n = gets.to_i
a = read_vector_int

# len >= 1
dofail if a.last == 1
dook(a.join('->')) if a.grep(1).empty? && a.size % 2 == 1
# len >= 2
dofail if a == [0, 0]
dook('1->0') if a == [1, 0]
# len >= 3
dook(a.join('->')) if a[-2] == 1
dook('0->(' + a[1...-1].join('->') + ')->0') if a[0] == 0
id = a[0...-2].index(0)
dofail if id.nil?
dook(a[0...id].join('->') + '->0->(' + a[(id+1)...-1].join('->') + ')->0')

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

def dofail
    puts "NO"
    exit
end

def dook(s)
    puts "YES"
    puts s
    exit
end

n = gets.to_i
a = read_vector_int

# len >= 1
dofail if a.last == 1
dook(a.join('->')) if a.grep(1).empty? && a.size % 2 == 1
# len >= 2
dofail if a == [0, 0]
dook('1->0') if a == [1, 0]
# len >= 3
dook(a.join('->')) if a[-2] == 1
id = a[0...-2].index(0)
dofail if id.nil?
dook(a[0...id].join('->') + '->0->(' + a[(id+1)...-1].join('->') + ')->0')


Adilbek was assigned to a special project. For Adilbek it means that he has $$$n$$$ days to run a special program and provide its results. But there is a problem: the program needs to run for $$$d$$$ days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends $$$x$$$ ($$$x$$$ is a non-negative integer) days optimizing the program, he will make the program run in $$$\left\lceil \frac{d}{x + 1} \right\rceil$$$ days ($$$\left\lceil a \right\rceil$$$ is the ceiling function: $$$\left\lceil 2.4 \right\rceil = 3$$$, $$$\left\lceil 2 \right\rceil = 2$$$). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to $$$x + \left\lceil \frac{d}{x + 1} \right\rceil$$$.Will Adilbek be able to provide the generated results in no more than $$$n$$$ days?

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 50$$$) — the number of test cases. The next $$$T$$$ lines contain test cases – one per line. Each line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le n \le 10^9$$$, $$$1 \le d \le 10^9$$$) — the number of days before the deadline and the number of days the program runs.

Print $$$T$$$ answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in $$$n$$$ days or NO (case insensitive) otherwise.

NoteIn the first test case, Adilbek decides not to optimize the program at all, since $$$d \le n$$$.In the second test case, Adilbek can spend $$$1$$$ day optimizing the program and it will run $$$\left\lceil \frac{5}{2} \right\rceil = 3$$$ days. In total, he will spend $$$4$$$ days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program $$$2$$$ days, it'll still work $$$\left\lceil \frac{11}{2+1} \right\rceil = 4$$$ days.

t=gets.to_i
while t>0
t-=1
n,d=gets.split.map(&:to_i)
i=0
ok=0
while i<n
if i+(d+i)/(i+1)<=n
puts "YES"
ok=1
break;
end
i+=1
end
if ok==0
puts "NO"
end
end


Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim.The killer starts with two potential victims on his first day, selects one of these two, kills selected victim and replaces him with a new person. He repeats this procedure each day. This way, each day he has two potential victims to choose from. Sherlock knows the initial two potential victims. Also, he knows the murder that happened on a particular day and the new person who replaced this victim.You need to help him get all the pairs of potential victims at each day so that Sherlock can observe some pattern.

First line of input contains two names (length of each of them doesn't exceed 10), the two initials potential victims. Next line contains integer n (1 ≤ n ≤ 1000), the number of days. Next n lines contains two names (length of each of them doesn't exceed 10), first being the person murdered on this day and the second being the one who replaced that person. The input format is consistent, that is, a person murdered is guaranteed to be from the two potential victims at that time. Also, all the names are guaranteed to be distinct and consists of lowercase English letters.

Output n + 1 lines, the i-th line should contain the two persons from which the killer selects for the i-th murder. The (n + 1)-th line should contain the two persons from which the next victim is selected. In each line, the two names can be printed in any order.

ross rachel
4
ross joey
rachel phoebe
phoebe monica
monica chandler

ross rachel
joey rachel
joey phoebe
joey monica
joey chandler

NoteIn first example, the killer starts with ross and rachel.   After day 1, ross is killed and joey appears.  After day 2, rachel is killed and phoebe appears.  After day 3, phoebe is killed and monica appears.  After day 4, monica is killed and chandler appears.

#!/usr/bin/ruby
a,b=gets.split
puts [a,b]*' '
gets
$<.each{|e|
	x,y=e.split
	if a==x
		a=y
	elsif b==x
		b=y
	end
	puts [a,b]*' '
}

ab = gets.split(' ')
initial1 = ab[0]
initial2 = ab[1]
n = gets.to_i()
puts "#{initial1} #{initial2}"
for i in 1..n do
  ab = gets.split(' ')
  if initial1 == ab[0]
    initial1 = ab[1]
  else
    initial2 = ab[1]
  end
  puts "#{initial1} #{initial2}"
end

#在ruby里我都不需要关心字符串的长度了！
name=gets.chomp.split(" ")
a=name[0]
b=name[1]
n=gets.chomp.to_i
puts "#{a} #{b}"
n.times do
    name=gets.chomp.split(" ")
    x=name[0]
    y=name[1]
    if x==a
        puts "#{b} #{y}"
        a=y
    else
        puts "#{a} #{y}"
        b=y
    end
end

a = gets.split
puts a * ' '
gets.to_i.times{
	x, y = gets.split
	a[a.index(x)] = y
	puts a * ' '
}

p = gets.split
n = gets.to_i
ans = [p]
n.times do
  a, b = gets.split
  p = p - [a] + [b]
  ans << p
end
puts ans.map{|x| x.join(' ')}

x = gets.split
n = gets.to_i
ans = [[*x]]
n.times do
  a1, a2 = gets.split
  if x.delete(a1)
    x.push(a2)
  elsif x.delete(a2)
    x.push(a1)
  end
  ans << x.flatten
end
puts ans.map{|x| x.join(' ')}

l = gets.split
puts l * ' '
gets.to_i.times {
  a, b = gets.split
  l[(l[0] == a) ? 0 : 1] = b
  puts l * ' '
}

a, b = gets.split
print(a, ' ', b)
gets.to_i.times do
  c, d = gets.split
  if a == c
    a = d
  else
    b = d
  end
  print("\n", a, ' ', b)
end

#!/usr/bin/ruby
a,b=gets.split
gets
$<.each{|e|
	x,y=e.split
	if a==x
		a=y
	elsif b==x
		b=y
	end
}
puts [a,b]*' '


You are policeman and you are playing a game with Slavik. The game is turn-based and each turn consists of two phases. During the first phase you make your move and during the second phase Slavik makes his move.There are $$$n$$$ doors, the $$$i$$$-th door initially has durability equal to $$$a_i$$$.During your move you can try to break one of the doors. If you choose door $$$i$$$ and its current durability is $$$b_i$$$ then you reduce its durability to $$$max(0, b_i - x)$$$ (the value $$$x$$$ is given).During Slavik's move he tries to repair one of the doors. If he chooses door $$$i$$$ and its current durability is $$$b_i$$$ then he increases its durability to $$$b_i + y$$$ (the value $$$y$$$ is given). Slavik cannot repair doors with current durability equal to $$$0$$$.The game lasts $$$10^{100}$$$ turns. If some player cannot make his move then he has to skip it.Your goal is to maximize the number of doors with durability equal to $$$0$$$ at the end of the game. You can assume that Slavik wants to minimize the number of such doors. What is the number of such doors in the end if you both play optimally?

The first line of the input contains three integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 100$$$, $$$1 \le x, y \le 10^5$$$) — the number of doors, value $$$x$$$ and value $$$y$$$, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th door.

Print one integer — the number of doors with durability equal to $$$0$$$ at the end of the game, if you and Slavik both play optimally.

NoteClarifications about the optimal strategy will be ignored.

n, x, y = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
if x > y
	puts n
else
	puts a.count { _1 <= x }.succ / 2
end

# Input
n, x, y = gets.split(" ").map { |e| e.to_i }
a = gets.split(" ").map { |e| e.to_i }

# total_moves = 10**100, and maximum_hp = 100 * 10**5 = 10**7 => If we are stronger then everything will be destroyed *evil laugh*

# Processing
d = x - y
one_hit = a.count { |n| n <= x }
case
when d > 0
  result = n
when d <= 0
  result = one_hit / 2 + one_hit % 2
end

# Output
puts result

n, x, y = gets.split.map(&:to_i)
arr = gets.split.map(&:to_i)
if x > y
  puts n
  exit
end
if x == y
  puts (arr.select{|a| a <= x}.size / 2.0).ceil
  exit
end
if x < y
  puts (arr.select{|a| a <= x}.size / 2.0).ceil
  exit
end

N,X,Y = gets.split.map &:to_i
A = gets.split.map &:to_i
if X > Y
  p N; exit
end

p (A.count{ |a| a <= X }+1)/2

# Input
n, k = gets.split(" ").map { |e| e.to_i }
a = gets.split(" ").map { |e| e }

# Processing
count = Hash.new(0)
current_color = Hash.new

a.each do |n|
  count[n] += 1
end

count.each do |n, amount|
  if amount > k
    puts "NO"
    #puts "#{n} amount > k"
    exit
  end
  current_color[n] = (current_color.length % k) + 1
end

c = Array.new(n) do |i|
  #puts current_color
  color = current_color[a[i]]
  current_color[a[i]] = current_color[a[i]] % k + 1
  color
end

# Output
puts "YES"
puts c.join(" ")

# Input
n, x, y = gets.split(" ").map { |e| e.to_i }
a = gets.split(" ").map { |e| e.to_i }

# total_moves = 10**100, and maximum_hp = 100 * 10**5 = 10**7 => If we are stronger then everything will be destroyed *evil laugh*

# Processing
d = x - y
one_hit = a.count { |n| n < x }
case
when d > 0
  result = n
when d <= 0
  result = one_hit / 2 + one_hit % 2
end

# Output
puts result


In a far away kingdom lived the King, the Prince, the Shoemaker, the Dressmaker and many other citizens. They lived happily until great trouble came into the Kingdom. The ACMers settled there.Most damage those strange creatures inflicted upon the kingdom was that they loved high precision numbers. As a result, the Kingdom healers had already had three appointments with the merchants who were asked to sell, say, exactly 0.273549107 beer barrels. To deal with the problem somehow, the King issued an order obliging rounding up all numbers to the closest integer to simplify calculations. Specifically, the order went like this: If a number's integer part does not end with digit 9 and its fractional part is strictly less than 0.5, then the rounded up number coincides with the number’s integer part.  If a number's integer part does not end with digit 9 and its fractional part is not less than 0.5, the rounded up number is obtained if we add 1 to the last digit of the number’s integer part. If the number’s integer part ends with digit 9, to round up the numbers one should go to Vasilisa the Wise. In the whole Kingdom she is the only one who can perform the tricky operation of carrying into the next position. Merchants found the algorithm very sophisticated and they asked you (the ACMers) to help them. Can you write a program that would perform the rounding according to the King’s order?

The first line contains a single number to round up — the integer part (a non-empty set of decimal digits that do not start with 0 — with the exception of a case when the set consists of a single digit — in this case 0 can go first), then follows character «.» (a dot), and then follows the fractional part (any non-empty set of decimal digits). The number's length does not exceed 1000 characters, including the dot. There are no other characters in the input data.

If the last number of the integer part is not equal to 9, print the rounded-up number without leading zeroes. Otherwise, print the message "GOTO Vasilisa." (without the quotes).

ss = gets.chomp.split(/\./)
i = ss[0].to_i

s = ss[0]
ch = s[s.length-1]
if ch == "9" then
  puts "GOTO Vasilisa."
else
  rnd = ss[1][0].to_i
  if rnd < 5 then
    puts i
  else
    puts i+1
  end
end

n=gets
s=n.split('\n')[0].split('.')
s[0]=s[0].to_i

if s[0]%10 == 9 then
        puts "GOTO Vasilisa."
else
        if s[1].slice(0)>='5' then
                s[0]+=1
        end
        puts s[0]
end

int,frac = gets.split('.')
if int[-1] == '9'
    puts "GOTO Vasilisa."
elsif frac[0].to_i < 5
    puts int
else
    puts int.to_i+1
end

num = gets
the_dot = num.index('.')
if num[the_dot-1] == '9'
	puts "GOTO Vasilisa."
else
	if num[the_dot+1].to_i >= 5
		puts ((num[0...the_dot].to_i)+1).to_s
	else
		puts num[0...the_dot]
	end
end

s = gets.chomp
t = s.index(".")
if s[t-1] == '9'
  puts "GOTO Vasilisa."
  exit
end
puts s[t+1] <= "4" ? s[0...t] : s[0...t].succ

a,b = gets.chomp.split('.')
if a.to_i % 10 == 9 then puts "GOTO Vasilisa."
else if b[0].to_i >= 5 then p a.to_i + 1
else p a.to_i end end

a,b=gets.split('.')

ch1, ch2 = a[-1,1], b[0,1]

if ch1!='9' && ch2<'5'
	puts a
elsif ch1!='9' && ch2>='5'
	puts a.to_i+1
else
	puts "GOTO Vasilisa."
end

def help_far_away_kingdom
  i, f = gets.split('.')

  if i[i.length-1] == '9'
    puts 'GOTO Vasilisa.'
  else
    if f.nil? or f[0].to_i < 5
      puts i.to_i
    else
      puts i.to_i+1
    end
  end
end
help_far_away_kingdom

int, frac = gets.split('.')
if int[-1] == '9'
    puts "GOTO Vasilisa."
elsif frac[0].to_i < 5
    puts int
else
    puts int.to_i+1
end

while !gets.nil?

integer, float = $_.split('.')

if integer[-1] == '9'
  puts "GOTO Vasilisa."
elsif float[0].to_i <= 4
  puts integer
else
  integer[-1] = integer[-1].succ
  puts integer
end

end

inp = gets.split('.')

int_part = inp[0]

if int_part.rindex('9') == int_part.size-1
  puts "GOTO Vasilisa."
elsif inp[1][0..0].to_i >= 5
  puts inp[0].to_i + 1
else
  puts inp[0]
end

i, f = gets.chomp.split(".")
if i[-1] == "9"
    puts "GOTO Vasilisa."
elsif f[0] < "5"
    puts i
else
    puts i.to_i+1
end

s = gets
case s
when /9\./
  puts 'GOTO Vasilisa.'
when /(\d+)\.[0-4]/
  puts $1.to_i
else
  puts s.to_i + 1
end

#!/usr/bin/ruby
s = $stdin.gets.strip.split(".")
int = s[0].to_i
flt = s[1][0].to_i
Blah = "GOTO Vasilisa."
if int % 10 == 9 then
  puts "#{Blah}"
else
  int += 1 if flt >= 5
  puts "#{int}"
end

x = gets.strip

if x =~ /9\./
	print :"GOTO Vasilisa."
else
	x =~ /(\d+)\.(\d)/
	print $2.to_i < 5 ? $1 : $1.to_i + 1
end

a,b = gets.chomp.split('.')
if a.to_i % 9 == 0 then puts "GOTO Vasilisa."
else if b[0].to_i >= 5 then p a.to_i + 1
else p a.to_i end end

def help_far_away_kingdom
  n = gets.strip
  r, ind = '', 0

  while ind < n.length
    if n[ind+1] == '.'
      if n[ind] == '9'
        puts 'GOTO Vasilisa.'
      else
        fraction = ("0.#{n[ind+2..-1]}").to_f
        if fraction < 0.5
          puts n[0..ind].to_i
        else
          puts n[0..ind].to_i + 1
        end
      end
      break
    end
    ind += 1
  end
  puts n if ind == n.length
end

help_far_away_kingdom

def help_far_away_kingdom
  n = gets.strip
  r, ind = '', 0

  while ind < n.length
    if n[ind+1] == '.'
      if n[ind] == '9'
        puts 'GOTO Vasilisa.'
      else
        fraction = ("0.#{n[ind+2..-1]}").to_f
        if fraction < 0.5
          puts n[0..ind].to_i
        else
          puts n[0..ind].to_i + 1
        end
      end
      break
    end
    ind += 1
  end
end

help_far_away_kingdom

while !gets.nil?

integer, float = $_.split('.')
if integer[-1] == '9'
  puts "GOTO Vasilisa."
elsif float[0].to_i < 4
  integer[-1] = integer[-1].succ
  puts integer
else
  puts integer
end

end

x = gets.strip
f = x.split('.')[1]
print f.count("9") == f.length ? :"GOTO Vasilisa." : x.to_f.round

x = gets.strip
l, r = x.split('.').map &:to_i

if l % 10 == 9
	print :"GOTO Vasilisa."
else
	l += 1 if r.to_s[0].to_i >= 5
	print l
end

x = gets.strip
print x[-1] == "9" ? :"GOTO Vasilisa." : x.to_f.round


Did you know you can download more RAM? There is a shop with $$$n$$$ different pieces of software that increase your RAM. The $$$i$$$-th RAM increasing software takes $$$a_i$$$ GB of memory to run (temporarily, once the program is done running, you get the RAM back), and gives you an additional $$$b_i$$$ GB of RAM (permanently). Each software can only be used once. Your PC currently has $$$k$$$ GB of RAM.Note that you can't use a RAM-increasing software if it takes more GB of RAM to use than what you currently have.Since RAM is the most important thing in the world, you wonder, what is the maximum possible amount of RAM achievable?

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains the integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$1 \le k \le 1000$$$). Then two lines follow, each containing $$$n$$$ integers describing the arrays $$$a$$$ and $$$b$$$ ($$$1 \le a_i, b_i \le 1000$$$).

For each test case, output a single line containing the largest amount of RAM you can achieve.

NoteIn the first test case, you only have enough RAM to run the third software initially, but that increases your RAM to $$$20$$$ GB, which allows you to use the first software, increasing your RAM to $$$29$$$ GB. The only software left needs $$$30$$$ GB of RAM, so you have to stop here.In the second test case, you can use the first, second, fourth and fifth software that need only $$$1$$$ GB of RAM per software to run to increase your RAM to $$$5$$$ GB, and then use the last remaining one to increase your RAM to $$$6$$$ GB.In the third test case, all the software need more than $$$1$$$ GB of RAM to run, so the amount of RAM you have stays at $$$1$$$ GB.

t = gets.chomp.to_i

for i in (1..t)
    n, k = gets.chomp.split.map {|e| e.to_i}
    a = gets.chomp.split.map {|e| e.to_i}
    b = gets.chomp.split.map {|e| e.to_i}
    c = (a.zip b).sort
    for j in (0..n-1)
        if k >= c[j][0]
            k += c[j][1]
        end
    end
    puts k
end

gets.to_i.times do
  n, k = gets.split.map(&:to_i)
  abs = gets.split.map(&:to_i).zip(gets.split.map(&:to_i)).sort_by(&:first)
  abs.each do |a, b|
    break if k < a
    k += b
  end
  p k
end

def solve(cur_ram, arr1, arr2)
  merge_arr = []
  for index in 0..(arr1.length-1)
    merge_arr << [arr1[index], arr2[index]]
  end

  merge_arr.sort_by! {|x, y| x}

  # puts "merge_arr = #{merge_arr}"

  for index in 0..(merge_arr.length-1)
    break if merge_arr[index][0] > cur_ram
    cur_ram += merge_arr[index][1]
  end
  cur_ram
end

testcases = gets.chomp.to_i

for testcase in 1..testcases
  n, k = gets.chomp.split(" ").map(&:to_i)
  arr1 = gets.chomp.split(" ").map(&:to_i)
  arr2 = gets.chomp.split(" ").map(&:to_i)
  # puts "n, k, arr1, arr2 = #{[n, k, arr1, arr2]}"
  res = solve(k, arr1, arr2)
  puts res
end


Young Timofey has a birthday today! He got kit of n cubes as a birthday present from his parents. Every cube has a number ai, which is written on it. Timofey put all the cubes in a row and went to unpack other presents.In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose the cubes are numbered from 1 to n in their order. Dima performs several steps, on step i he reverses the segment of cubes from i-th to (n - i + 1)-th. He does this while i ≤ n - i + 1.After performing the operations Dima went away, being very proud of himself. When Timofey returned to his cubes, he understood that their order was changed. Help Timofey as fast as you can and save the holiday — restore the initial order of the cubes using information of their current location.

The first line contains single integer n (1 ≤ n ≤ 2·105) — the number of cubes. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109), where ai is the number written on the i-th cube after Dima has changed their order.

Print n integers, separated by spaces — the numbers written on the cubes in their initial order. It can be shown that the answer is unique.

NoteConsider the first sample.  At the begining row was [2, 3, 9, 6, 7, 1, 4].  After first operation row was [4, 1, 7, 6, 9, 3, 2].  After second operation row was [4, 3, 9, 6, 7, 1, 2].  After third operation row was [4, 3, 7, 6, 9, 1, 2].  At fourth operation we reverse just middle element, so nothing has changed. The final row is [4, 3, 7, 6, 9, 1, 2]. So the answer for this case is row [2, 3, 9, 6, 7, 1, 4].

n,*a=$<.read.split.map &:to_i;(n/2).times{|i|a[i],a[n-i-1]=a[n-i-1],a[i]if i.even?};puts a*' '

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

(0...(n / 2)).each do |i|
  next if i.odd?
  t = a[i]
  a[i] = a[n - i - 1]
  a[n - i - 1] = t
end

puts a.join(" ")

TEST_MODE = ARGV[0] == 't'

def evaluate(actual, expected); actual == expected ? "OK" : "**NG**"; end
def tests(); yield if TEST_MODE; end
def to_array(val); val.kind_of?(Array) ? val : [val]; end
def parse_int_array(str); str.split(" ").collect{|s| s.to_i}; end

def t(input, expected_output)
  input = to_array(input)
  expected_output = to_array(expected_output)
  output = []
  solve(input, output)
  puts "#{evaluate(output, expected_output)} : input=#{input.to_s}, expected=#{expected_output.to_s}, actual=#{output.to_s}"
end

def solve(input, output)
  arr = parse_int_array(input[1])
  (0..arr.size/2-1).step(2) {|i|
    temp = arr[i]
    arr[i] = arr[arr.size-i-1]
    arr[arr.size-i-1] = temp
  }
  output << arr.join(" ")
end

tests do
  # test cases
  t(["7","4 3 7 6 9 1 2"], "2 3 9 6 7 1 4")
  t(["8","6 1 4 2 5 6 9 2"], "2 1 6 2 5 4 9 6")
end

puts solve(STDIN.read.split("\n"), []) unless TEST_MODE

n=gets.to_i
s=gets.chomp.split
(s.size/2).times{|i|
	if i%2==0 then
		s[i],s[n-i-1]=s[n-i-1],s[i]
	end
}
puts s*" "

n = gets.to_i
a = gets.split.map(&:to_i)
c = n / 2 + (n.even? ? 0 : 1) - 1
ans = []
c.times do |i|
  if i % 2 == 0
    ans[i] = a[n - 1 - i]
    ans[n - 1 - i] = a[i]
  else
    ans[i] = a[i]
    ans[n - 1 - i] = a[n - 1 - i]
  end
end
a2 = a[c..(n - 1 - c)]
a2.reverse!  if c % 2 == 0
ans[c..(n - 1 - c)] = a2
puts ans.join(' ')

n = gets.to_i
a = gets.split.map(&:to_i)
(n / 2).times do |i|
  a[i], a[-1 - i] = a[-1 - i], a[i] if i % 2 == 0
end
puts a.join(' ')

n=gets.to_i
a=gets.split.map &:to_i
for i in 0 ... n / 2
  if i % 2 == 0
    tmp = a[i]
    a[i] = a[n - 1 - i]
    a[n - 1 - i] = tmp
  end
end
puts a*' '


Let's call an array $$$a$$$ consisting of $$$n$$$ positive (greater than $$$0$$$) integers beautiful if the following condition is held for every $$$i$$$ from $$$1$$$ to $$$n$$$: either $$$a_i = 1$$$, or at least one of the numbers $$$a_i - 1$$$ and $$$a_i - 2$$$ exists in the array as well.For example:   the array $$$[5, 3, 1]$$$ is beautiful: for $$$a_1$$$, the number $$$a_1 - 2 = 3$$$ exists in the array; for $$$a_2$$$, the number $$$a_2 - 2 = 1$$$ exists in the array; for $$$a_3$$$, the condition $$$a_3 = 1$$$ holds;  the array $$$[1, 2, 2, 2, 2]$$$ is beautiful: for $$$a_1$$$, the condition $$$a_1 = 1$$$ holds; for every other number $$$a_i$$$, the number $$$a_i - 1 = 1$$$ exists in the array;  the array $$$[1, 4]$$$ is not beautiful: for $$$a_2$$$, neither $$$a_2 - 2 = 2$$$ nor $$$a_2 - 1 = 3$$$ exists in the array, and $$$a_2 \ne 1$$$;  the array $$$[2]$$$ is not beautiful: for $$$a_1$$$, neither $$$a_1 - 1 = 1$$$ nor $$$a_1 - 2 = 0$$$ exists in the array, and $$$a_1 \ne 1$$$;  the array $$$[2, 1, 3]$$$ is beautiful: for $$$a_1$$$, the number $$$a_1 - 1 = 1$$$ exists in the array; for $$$a_2$$$, the condition $$$a_2 = 1$$$ holds; for $$$a_3$$$, the number $$$a_3 - 2 = 1$$$ exists in the array. You are given a positive integer $$$s$$$. Find the minimum possible size of a beautiful array with the sum of elements equal to $$$s$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Then $$$t$$$ lines follow, the $$$i$$$-th line contains one integer $$$s$$$ ($$$1 \le s \le 5000$$$) for the $$$i$$$-th test case.

Print $$$t$$$ integers, the $$$i$$$-th integer should be the answer for the $$$i$$$-th testcase: the minimum possible size of a beautiful array with the sum of elements equal to $$$s$$$.

NoteConsider the example test:  in the first test case, the array $$$[1]$$$ meets all conditions;  in the second test case, the array $$$[3, 4, 1]$$$ meets all conditions;  in the third test case, the array $$$[1, 2, 4]$$$ meets all conditions;  in the fourth test case, the array $$$[1, 4, 6, 8, 10, 2, 11]$$$ meets all conditions.

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

def main
  gi.times do
    n = gi
    d = 1
    s = 0
    c = 0
    while n > s
      s += d
      c += 1
      d += 2
    end
    puts c
  end
end

main

t = gets.chomp.to_i

t.times do
  n = gets.chomp.to_i
  ans = 0
  curr_max = 1
  sum = 0
  while sum < n do
    ans += 1
    n -= curr_max
    curr_max += 2
  end

  ans += 1 if n > 0

  puts "#{ans}\n"
end


Polycarpus adores TV series. Right now he is ready to finish watching a season of a popular sitcom "Graph Theory". In total, the season has n episodes, numbered with integers from 1 to n.Polycarpus watches episodes not one by one but in a random order. He has already watched all the episodes except for one. Which episode has Polycaprus forgotten to watch?

The first line of the input contains integer n (2 ≤ n ≤ 100000) — the number of episodes in a season. Assume that the episodes are numbered by integers from 1 to n. The second line contains n - 1 integer a1, a2, ..., an (1 ≤ ai ≤ n) — the numbers of episodes that Polycarpus has watched. All values of ai are distinct.

Print the number of the episode that Polycarpus hasn't watched.

n=gets.to_i
mas=gets.split.map &:to_i
puts (n*(n+1)/2) - mas.inject(:+)

T=gets().to_i
line=gets().split(" ").map!{|x|x.to_i}
sum=(T*(T+1))/2
sb=line.inject(:+)
puts sum-sb


Facetook is a well known social network website, and it will launch a new feature called Facetook Priority Wall. This feature will sort all posts from your friends according to the priority factor (it will be described).This priority factor will be affected by three types of actions:   1. "X posted on Y's wall" (15 points),  2. "X commented on Y's post" (10 points),  3. "X likes Y's post" (5 points). X and Y will be two distinct names. And each action will increase the priority factor between X and Y (and vice versa) by the above value of points (the priority factor between X and Y is the same as the priority factor between Y and X).You will be given n actions with the above format (without the action number and the number of points), and you have to print all the distinct names in these actions sorted according to the priority factor with you.

The first line contains your name. The second line contains an integer n, which is the number of actions (1 ≤ n ≤ 100). Then n lines follow, it is guaranteed that each one contains exactly 1 action in the format given above. There is exactly one space between each two words in a line, and there are no extra spaces. All the letters are lowercase. All names in the input will consist of at least 1 letter and at most 10 small Latin letters.

Print m lines, where m is the number of distinct names in the input (excluding yourself). Each line should contain just 1 name. The names should be sorted according to the priority factor with you in the descending order (the highest priority factor should come first). If two or more names have the same priority factor, print them in the alphabetical (lexicographical) order. Note, that you should output all the names that are present in the input data (excluding yourself), even if that person has a zero priority factor. The lexicographical comparison is performed by the standard "<" operator in modern programming languages. The line a is lexicographically smaller than the line b, if either a is the prefix of b, or if exists such an i (1 ≤ i ≤ min(|a|, |b|)), that ai < bi, and for any j (1 ≤ j < i) aj = bj, where |a| and |b| stand for the lengths of strings a and b correspondently.

ahmed
3
ahmed posted on fatma's wall
fatma commented on ahmed's post
mona likes ahmed's post

h = Hash.new(0)
u = gets.chomp
gets.to_i.times do
	$_ = gets
	if /(\w+) posted on (\w+)'s wall/
		x, y, z = $1, $2, 15
	elsif /(\w+) commented on (\w+)'s post/
		x, y, z = $1, $2, 10
	elsif /(\w+) likes (\w+)'s post/
		x, y, z = $1, $2, 5
	else
		warn 555
	end
	if x == u
		h[y] += z
	elsif y == u
		h[x] += z
	else
		h[x] += 0
		h[y] += 0
	end
end
puts h.map{|k, v| [-v, k]}.sort.map{|a, b| b} * "\n"

regs = [/(\w+) posted on (\w+)'s wall/,
        /(\w+) commented on (\w+)'s post/,
        /(\w+) likes (\w+)'s post/]

myname = gets.chomp
action = gets.to_i
player = {}
action.times do |i|
  tmp = gets
  if tmp =~ regs[0]
 #  p $1,$2
    if myname == $1
      if myname != $2
        player.store($2,0) if player[$2] == nil
        player[$2] += 15
      end
    elsif myname == $2
      if myname != $1
        player.store($1,0) if player[$1] == nil
        player[$1] += 15
      end
    else
      player.store($1,0) if player[$1] == nil
      player.store($2,0) if player[$2] == nil
    end
  elsif tmp =~ regs[1]
#   p $1,$2
    if myname == $1
      if myname != $2
        player.store($2,0) if player[$2] == nil
        player[$2] += 10
      end
    elsif myname == $2
      if myname != $1
        player.store($1,0) if player[$1] == nil
        player[$1] += 10
      end
    else
      player.store($1,0) if player[$1] == nil
      player.store($2,0) if player[$2] == nil
    end
  elsif tmp =~ regs[2]
#   p $1,$2
    if myname == $1
      if myname != $2
        player.store($2,0) if player[$2] == nil
        player[$2] += 5
      end
    elsif myname == $2
      if myname != $1
        player.store($1,0) if player[$1] == nil
        player[$1] += 5
      end
    else
      player.store($1,0) if player[$1] == nil
      player.store($2,0) if player[$2] == nil
    end
  end
end
values = player.values
keys   = player.keys
while true do
    maxary = []
    max = values.max
    while true do
        maxpos = values.index(max)
        maxary << keys[maxpos].dup
        #p max,maxpos,maxary
        values.delete_at(maxpos)
        keys.delete_at(maxpos)
        break if values == []
        break if max > values.max
    end
    maxary.map{|item| item.extend Comparable}
    sorted = maxary
    sorted = maxary.sort if maxary.size > 1

    puts sorted
    break if values == []
end

MYNAME = gets.chomp
N = gets.to_i
persons = Hash.new(0)
N.times do
  str = gets.split(' ')
  add = 0
  x = str[0]
  y = str[3]
  if (str[1] == "posted")
    add = 15
  elsif (str[1] == "commented")
    add = 10
  else
    add = 5
    y = str[2]
  end
  y.gsub!("'s", "")
  if (x != MYNAME && y != MYNAME) # Priority factor according to me!
    add = 0 # but we have to print ALL persons
  end
  persons[x] += add
  persons[y] += add
end

result = persons.to_a.sort{|l, r|
  if (l[1] != r[1])
    r[1] <=> l[1]
  else
    l[0] <=> r[0]
  end
}

#p result

result.each {|e|
  puts e[0] if (e[0] != MYNAME)
}

name = gets.chomp
n = gets.to_i
priority = Hash.new(0)
n.times do
	v = gets.chomp.downcase
	arr = v.split(" ")
	a = arr[0]
	p = 0
	if arr[1].eql?("posted")
		p = 15
		b = arr[3]
	elsif arr[1].eql?("commented")
		p = 10
		b = arr[3]
	else
		p = 5
		b = arr[2]
	end
	b = b.sub("'s","")
	p = 0 unless (a.eql?(name) || b.eql?(name))
	priority[a] += p
	priority[b] += p
end

priority.keys.sort{|k1,k2| priority[k1] != priority[k2] ? -(priority[k1] <=> priority[k2]) : k1 <=> k2}.each do |k|
	puts k unless k.eql?(name)
end

my_name = STDIN.gets.strip
n = STDIN.gets.strip.to_i
actions = []
n.times do
  actions.push STDIN.gets.strip
end
persons = {}
regexps = [/(.*) posted on (.*)'s wall/,/(.*) commented on (.*)'s post/,/(.*) likes (.*)'s post/]
points = [15,10,5]
actions.each do |action|
  3.times do |i|
    if match = regexps[i].match(action)
      if match[1] == my_name || match[2] == my_name
        if persons[match[1]]
          persons[match[1]] += points[i]
        else
          persons[match[1]] = points[i]
        end
        if persons[match[2]]
          persons[match[2]] += points[i]
        else
          persons[match[2]] = points[i]
        end
      else
        if !persons[match[1]]
          persons[match[1]] = 0
        end
        if !persons[match[2]]
          persons[match[2]] = 0
        end
      end
    end
  end
end
persons.delete(my_name)
sorted = persons.to_a.sort_by{|x| [-x[1],x[0]]}
sorted.each do |person|
  puts person[0]
end

me = gets.chomp

map = Hash.new {|hash, key| hash[key] = 0 }

(gets.to_i).times do
  line = gets.chomp.split
  x = line[0]
  y = nil
  points = 0
  if line[1] == "posted"
    points = 15
    y = line[3]
  elsif line[1] == "commented"
    points = 10
    y = line[3]
  elsif line[1] == "likes"
    points = 5
    y = line[2]
  end
  y = y[0..y.size - 3]
  if x == me
    map[y] += points
  elsif y == me
    map[x] += points
  else
    map[y] += 0
    map[x] += 0
  end
end

(map.sort {|a, b| if a[1] == b[1]
   a[0] <=> b[0] else b[1] <=> a[1] end }).each do |m|
    puts m[0]
end

my_name = gets.chomp
names = Hash.new(0)
gets.to_i.times do
  gets.chomp =~ /^(\w+) (posted on|commented on|likes) (\w+)'s (wall|post)$/
  n1, n2 = $1, $3
  other_name = if n1 == my_name
    n2
  elsif n2 == my_name
    n1
  end
  if other_name
    point = case $2
    when "posted on"
      15
    when "commented on"
      10
    else # "likes"
      5
    end
    names[other_name] += point
  else
    names[n1] += 0
    names[n2] += 0
  end
end

names.sort{|a,b| (b[1] <=> a[1]).nonzero? || a[0] <=> b[0] }.each{|n| puts n[0]}

regs = [/(\w+) posted on (\w+)'s wall/,
        /(\w+) commented on (\w+)'s post/,
        /(\w+) likes (\w+)'s post/]

myname = gets.chomp
action = gets.to_i
player = {}
action.times do |i|
  tmp = gets
  if tmp =~ regs[0]
 #  p $1,$2
    if myname == $1
      if myname != $2
        player.store($2,0) if player[$2] == nil
        player[$2] += 15
      end
    elsif myname == $2
      if myname != $1
        player.store($1,0) if player[$1] == nil
        player[$1] += 15
      end
    else
      player.store($1,0) if player[$1] == nil
      player.store($2,0) if player[$2] == nil
    end
  elsif tmp =~ regs[1]
#   p $1,$2
    if myname == $1
      if myname != $2
        player.store($2,0) if player[$2] == nil
        player[$2] += 10
      end
    elsif myname == $2
      if myname != $1
        player.store($1,0) if player[$1] == nil
        player[$1] += 10
      end
    else
      player.store($1,0) if player[$1] == nil
      player.store($2,0) if player[$2] == nil
    end
  elsif tmp =~ regs[2]
#   p $1,$2
    if myname == $1
      if myname != $2
        player.store($2,0) if player[$2] == nil
        player[$2] += 5
      end
    elsif myname == $2
      if myname != $1
        player.store($1,0) if player[$1] == nil
        player[$1] += 5
      end
    else
      player.store($1,0) if player[$1] == nil
      player.store($2,0) if player[$2] == nil
    end
  end
end
values = player.values
keys   = player.keys

while true do
    while true do
        maxary = []
        max = values.max
        maxpos = values.index(values.max)
        maxary << keys[maxpos]
#       p max,maxpos,maxary
        values.delete_at(maxpos)
        keys.delete_at(maxpos)
        break if max > values.max.to_i
    end
    #maxary.sort_by!{|a,b| b <=> a} if maxary.size > 1
#   puts maxary
    break if values == []
end

MYNAME = gets.chomp
N = gets.to_i
persons = Hash.new(0)
N.times do
  str = gets.split(' ')
  add = 0
  x = str[0]
  y = str[3]
  if (str[1] == "posted")
    add = 15
  elsif (str[1] == "commented")
    add = 10
  else
    add = 5
    y = str[2]
  end
  y.gsub!("'s", "")
  persons[x] += add
  persons[y] += add
end

result = persons.to_a.sort{|l, r|
  if (l[1] != r[1])
    r[1] <=> l[1]
  else
    l[0] <=> r[0]
  end
}

#p result

result.each {|e|
  puts e[0] if (e[0] != MYNAME)
}

name = gets.chomp
n = gets.to_i
priority = Hash.new(0)
n.times do
	v = gets.chomp.downcase
	arr = v.split(" ")
	a = arr[0]
	p = 0
	if arr.include?("posted")
		p = 15
		b = arr[3]
	elsif arr.include?("commented")
		p = 10
		b = arr[3]
	else
		p = 5
		b = arr[2]
	end
	b = b.sub("'s","")
	p = 0 unless (a.eql?(name) || b.eql?(name))
	priority[a] += p
	priority[b] += p
end

priority.keys.sort{|k1,k2| priority[k1] != priority[k2] ? -(priority[k1] <=> priority[k2]) : k1 <=> k2}.each do |k|
	puts k unless k.eql?(name)
end

name = gets.chomp
n = gets.to_i
priority = Hash.new(0)
n.times do
	v = gets.chomp.downcase
	arr = v.split(" ")
	a = arr[0]
	p = 0
	if arr.include?("posted")
		p = 15
		b = arr[3]
	elsif arr.include?("commented")
		p = 10
		b = arr[3]
	else
		p = 5
		b = arr[2]
	end
	b = b.sub("'s","")
	p = 0 unless (a.include?(name) || b.include?(name))
	priority[a] += p
	priority[b] += p
end

priority.keys.sort{|k1,k2| priority[k1] != priority[k2] ? -(priority[k1] <=> priority[k2]) : k1 <=> k2}.each do |k|
	puts k unless k.eql?(name)
end

me = gets.chomp

map = Hash.new {|hash, key| hash[key] = 0 }

(gets.to_i).times do
  line = gets.chomp.split
  x = line[0]
  y = nil
  points = 0
  if line[1] == "posted"
    points = 15
    y = line[3]
  elsif line[1] == "commented"
    points = 10
    y = line[3]
  elsif line[1] == "likes"
    points = 5
    y = line[2]
  end
  y = y[0..y.size - 3]
  map[x] += points
  map[y] += points
end

(map.sort {|a, b| if a[1] == b[1]
   a[0] <=> b[0] else b[1] <=> a[1] end }).each do |m|
  if m[0] != me
    puts m[0]
  end
end

my_name = gets.chomp
names = Hash.new(0)
gets.to_i.times do
  gets.chomp =~ /^(\w+) (posted on|commented on|likes|) (\w+)'s (wall|post)$/
  n1, n2 = $1, $3
  other_name = if n1 == my_name
    n2
  elsif n2 == my_name
    n1
  end
  if other_name
    point = case $2
    when "posted on"
      15
    when "commented on"
      10
    else # "likes"
      5
    end
    names[other_name] += 5
  else
    names[n1] += 0
    names[n2] += 0
  end
end

names.sort{|a,b| (b[1] <=> a[1]).nonzero? || a[0] <=> b[0] }.each{|n| puts n[0]}


You are given three sequences: $$$a_1, a_2, \ldots, a_n$$$; $$$b_1, b_2, \ldots, b_n$$$; $$$c_1, c_2, \ldots, c_n$$$.For each $$$i$$$, $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$.Find a sequence $$$p_1, p_2, \ldots, p_n$$$, that satisfy the following conditions: $$$p_i \in \{a_i, b_i, c_i\}$$$ $$$p_i \neq p_{(i \mod n) + 1}$$$.In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements $$$i,i+1$$$ adjacent for $$$i<n$$$ and also elements $$$1$$$ and $$$n$$$) will have equal value.It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence.

The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 100$$$): the number of elements in the given sequences. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 100$$$). The fourth line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 100$$$). It is guaranteed that $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$ for all $$$i$$$.

For each test case, print $$$n$$$ integers: $$$p_1, p_2, \ldots, p_n$$$ ($$$p_i \in \{a_i, b_i, c_i\}$$$, $$$p_i \neq p_{i \mod n + 1}$$$). If there are several solutions, you can print any.

T = gets.to_i

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

  ans = []

  n.times do |i|
    if i == 0
      ans << a[i]
    else
      3.times do |j|
        v = case j
            when 0
              a[i]
            when 1
              b[i]
            when 2
              c[i]
            end

        next if v == ans.last
        next if i == n - 1 && v == ans.first

        ans << v
        break
      end
    end
  end

  puts ans.join(' ')
end

T = gets.to_i

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

  idx = -1
  ans = []

  n.times do |i|
    if i == 0
      ans << a[i]
      idx = 0
    else
      3.times do |j|
        next if idx == j

        v = case j
            when 0
              a[i]
            when 1
              b[i]
            when 2
              c[i]
            end

        next if v == ans.last

        ans << v
        idx = j
        break
      end
    end
  end

  puts ans.join(' ')
end

T = gets.to_i

T.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  b = gets.split.map(&:to_i)
  c = gets.split.map(&:to_i)
  res = []

  3.times do |k|
    idx = -1
    ans = []

    n.times do |i|
      if i == 0
        case k
        when 0
          ans << a[i]
        when 1
          ans << b[i]
        when 2
          ans << c[i]
        end

        idx = k
      else
        3.times do |j|
          next if idx == j

          v = case j
              when 0
                a[i]
              when 1
                b[i]
              when 2
                c[i]
              end

          next if v == ans.last

          ans << v
          idx = j
          break
        end
      end
    end

    if ans[0] != ans[-1]
      res = ans
      break
    end
  end

  puts res.join(' ')
end


Alice and Bob play a game. They have a binary string $$$s$$$ (a string such that each character in it is either $$$0$$$ or $$$1$$$). Alice moves first, then Bob, then Alice again, and so on.During their move, the player can choose any number (not less than one) of consecutive equal characters in $$$s$$$ and delete them.For example, if the string is $$$10110$$$, there are $$$6$$$ possible moves (deleted characters are bold):  $$$\textbf{1}0110 \to 0110$$$;  $$$1\textbf{0}110 \to 1110$$$;  $$$10\textbf{1}10 \to 1010$$$;  $$$101\textbf{1}0 \to 1010$$$;  $$$10\textbf{11}0 \to 100$$$;  $$$1011\textbf{0} \to 1011$$$. After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $$$10\textbf{11}0 \to 1\textbf{00} \to 1$$$.The game ends when the string becomes empty, and the score of each player is the number of $$$1$$$-characters deleted by them.Each player wants to maximize their score. Calculate the resulting score of Alice.

The first line contains one integer $$$T$$$ ($$$1 \le T \le 500$$$) — the number of test cases. Each test case contains exactly one line containing a binary string $$$s$$$ ($$$1 \le |s| \le 100$$$).

For each test case, print one integer — the resulting score of Alice (the number of $$$1$$$-characters deleted by her).

NoteQuestions about the optimal strategy will be ignored.

gets.to_i.times do
  puts gets.chomp.split(/0+/).map(&:length).sort{ |a, b| b <=> a }.select.each_with_index{|_, index| index.even?}.sum
end

times = gets.to_i

def resolve(binary_s)
  game_a = binary_s.split("0").map(&:size).sort{|a,b| b <=> a}
  game_a.delete(0)
  alice_points = 0
  game_a.each_with_index {|e,i| alice_points += e if i % 2 == 0}
  alice_points
end

(1..times).each do |i|
  s = gets.chomp
  puts resolve(s)
end

t = gets.chomp.to_i
t.times do
    s = gets.chomp.split("")
    ookisa = s.size
    ans = 0
    count = 0
    arr = []
    (0..ookisa-1).each_with_index do |item,i|
        if item == "1" && s[i] == "1" && s[i-1] == "1" && i != 0
            count += 1
        elsif s[i] == "1"
            count += 1
        elsif s[i] == "0"
            arr << count
            count = 0
        end
        if ans <= count
            ans = count
            point = i
        end
    end
    arr << count
    arr = arr.sort
    arisa = 0
    bob = 0
    while true
        if arr != []
            arisa += arr.pop
        else
            break
        end
        if arr != []
            bob += arr.pop
        else
            break
        end
    end
    puts arisa
end

t = gets.chomp.to_i
t.times {
  str = gets.chomp
  index = -1
  (0...str.size).each do |ind|
    next if str[ind] == '0'

    index = ind
    break
  end

  list = []
  count = 1

  if index == -1
    puts '0'
    next
  end
  (index+1...str.size).each do |ind|
    if str[ind] == '1'
      count += 1
    else
      list << count if count != 0
      count = 0
    end
  end

  list << count if count != 0
  list.sort_by! {|ele| -1 * ele}

  ans = 0
  i = 0
  while ( i < list.size ) do
    ans += list[i]
    i += 2
  end
  puts ans
}

t = gets.to_i
ans = []
t.times do
  a = gets.chomp.split("").map(&:to_i)
  arr = []
  cnt = 0
  a.each do |v|
    if v == 1
      cnt += 1
    else
      if cnt > 0
        arr << cnt
        cnt = 0
      end
    end
  end
  if cnt > 0
    arr << cnt
  end
  arr = arr.sort.reverse
  len = arr.length
  value = 0
  len.times do |i|
    value += arr[i] if i%2 == 0
  end
  ans << value
end
ans.each do |x|
  puts x
end

gets.to_i.times do
  puts gets.split(/0+/).map(&:length).sort{ |a, b| b <=> a }.select.each_with_index{|_, index| index.even?}.sum
end

t = gets.chomp.to_i
t.times {
  str = gets.chomp
  index = -1
  (0...str.size).each do |ind|
    next if str[ind] == '0'

    index = ind
    break
  end

  list = []
  count = 1

  if index == -1
    puts '0'
    next
  end

  (index+1...str.size).each do |ind|
    if str[ind] == '1'
      count += 1
    else
      list << count if count != 0
      count = 0
    end
  end

  list << count if count != 0
  list.sort_by {|ele| -1 * ele}

  ans = 0
  i = 0
  while ( i < list.size ) do
    ans += list[i]
    i += 2
  end
  puts ans
}


Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC. For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers ti and ci — the receiving time (the second) and the number of the text messages, correspondingly.Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows:  If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x.  If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue. Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.

The first line contains a single integer n (1 ≤ n ≤ 103) — the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers ti and ci (1 ≤ ti, ci ≤ 106) — the time (the second) when the i-th task was received and the number of messages to send, correspondingly. It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, ti < ti + 1 for all integer i (1 ≤ i < n).

In a single line print two space-separated integers — the time when the last text message was sent and the maximum queue size at a certain moment of time.

NoteIn the first test sample:   second 1: the first message has appeared in the queue, the queue's size is 1;  second 2: the first message is sent, the second message has been received, the queue's size is 1;  second 3: the second message is sent, the queue's size is 0, Thus, the maximum size of the queue is 1, the last message was sent at the second 3.

num_tasks = gets.to_i
tasks = Array.new
for i in 0...num_tasks
  tasks << gets.split.collect{ |n| n.to_i }
end
current_task = tasks.shift
t = current_task[0]
to_send = current_task[1]
max_queries = to_send
if tasks.length < 1
  puts (t+to_send).to_s + " " + max_queries.to_s
  exit
end
current_task = tasks.shift
while true
  t = t+1
  to_send -= 1 if to_send > 0
  if t == current_task[0]
    to_send += current_task[1]
    if to_send > max_queries
      max_queries = to_send
    end
    if tasks.length < 1
      break
    end
    current_task = tasks.shift
  end
end
puts (t+to_send).to_s + " " + max_queries.to_s

class A
  def initialize
    n = $stdin.gets.chomp.to_i
    queue_size = 0
    b_time = 0
    next_time = 0
    max_size = 0

    n.times do
      time, task = $stdin.gets.chomp.split(' ').map(&:to_i)
      d_time = time - b_time

      queue_size = [0, queue_size-d_time].max

      b_time = time

      queue_size += task

      max_size = queue_size if max_size < queue_size
    end

    puts "#{b_time+queue_size} #{max_size}"
  end
end

a = A.new

n = gets.to_i

tc = n.times.map{ gets.split.map(&:to_i) }

t = 1
max = 0
prev = [0, 0]

tc.each do |i|
  t = (t < i[0] ? i[0] : t) + i[1]
  m = prev[1] + prev[0] - i[0]
  m = m > 0 ? m + i[1] : i[1]
  max = m if max < m
  prev = [i[0], m]
end

puts "#{t} #{max}"

n = gets.chomp.to_i

times = []
messages_count = []

max_queue = 1
queue = 0

ftime = true

r_queue = 0

n.times do |i|
  input = gets.chomp.split(" ")

  times << input[0].to_i
  messages_count << input[1].to_i

  if ftime == false
    queue = queue - (input[0].to_i - times[i-1])
  end

  if queue < 0
    queue = 0
  end

  queue += input[1].to_i

  if queue > max_queue
    max_queue = queue
  end

  r_queue = queue

  if ftime
    ftime = false
  end
end

time = times.last + r_queue

puts "#{time} #{max_queue}"

at_exit do
  task_count = get_numbers_from_line[0]
  tasks = []
  task_count.times do
    t,c = get_numbers_from_line[0..1]
    tasks << {t: t, sms_count: c}
  end

  time = 0
  max_queue_length = 0
  task_in_queue_count = 0
  while true
    next_task = tasks.shift
    if next_task != nil
      dt = next_task[:t] - time
      task_in_queue_count = [0, task_in_queue_count - dt].max
      task_in_queue_count += next_task[:sms_count]
      max_queue_length = task_in_queue_count if task_in_queue_count > max_queue_length
      time += dt
    elsif task_in_queue_count != 0
      time += task_in_queue_count
      break
    else
      break
    end
  end

  puts [time, max_queue_length].join(' ')
end

def get_numbers_from_line
  gets.strip.split.map(&:to_i)
end

n = gets.chomp.to_i

times = []
messages_count = []

max_queue = 1
queue = 0

r_queue = 0

n.times do
  input = gets.chomp.split(" ")

  times << input[0].to_i
  messages_count << input[1].to_i

  queue += input[1].to_i

  r_queue = queue

  if queue > max_queue
    max_queue = queue
  end

  queue -= input[0].to_i
  if queue < 0
    queue = 0
  end
end

time = times.last + r_queue

puts "#{time} #{max_queue}"

n = gets.chomp.to_i

times = []
messages_count = []

max_queue = 1
queue = 0

n.times do
  input = gets.chomp.split(" ")
  times << input[0].to_i
  messages_count << input[1].to_i
  queue += input[1].to_i

  if queue > max_queue
    max_queue = queue
  end

  queue -= 1
end

time = times.first + messages_count.inject(:+)

puts "#{time} #{max_queue}"

n = gets.chomp.to_i

times = []
messages_count = []

max_queue = 1
queue = 0

r_queue = 0

n.times do |i|
  input = gets.chomp.split(" ")

  times << input[0].to_i
  messages_count << input[1].to_i

  queue += input[1].to_i

  r_queue = queue

  if queue > max_queue
    max_queue = queue
  end

  queue = queue - (input[0].to_i - times[i-1])

  if queue < 0
    queue = 0
  end
end

time = times.last + r_queue

time -= 1 if times.size != 1
max_queue -= 1 if times.size != 1

puts "#{time} #{max_queue}"