n,m,k = gets.split
arr=[];
while a=gets do
	arr.push(a.to_i)
end
c=arr.pop
A=0
arr.each{|x| A=A+(((x^c).to_s(2).count('1') > k.to_i)?'0':'1').to_i}
puts A

def byte_count(num = 0)
  c = 0
  while true
    if (num - (num.div(2) * 2)) == 1
      c += 1
    end
    num = num.div(2)
    if num < 2
      c += 1
      break
    end
  end

  return c
end

nums = []
arr = []

c = 0
main = 0

gets.split(" ").each {|a| nums << a.to_i}

for i in (0..nums[1] - 1)
  arr[i] = gets.to_i
end

main = gets.to_i

for i in (0..nums[1] - 1)
  if byte_count(arr[i] ^ main) <= nums[2]
    c += 1
  end
end

puts c

n, m, k = gets.chomp.split(' ').map {|x| x.to_i}
arr = []
(m).times do
  arr << gets.chomp.to_i
end
fedor = gets.chomp.to_i
total = 0
arr.each do |x|
  s = (fedor ^ x).to_s(2)
  count = 0;
  (0...s.length).each { |i| count += 1 if s[i]=='1' }
  total += 1 if count<=k
end
puts total

#!/usr/bin/ruby

n, m, k = STDIN.readline.split.map {|s| s.to_i }
players = []
m.times { players.push STDIN.readline.to_i }
fedor = STDIN.readline.to_i
count = 0
players.each do |player|
	bits = (player ^ fedor)
	diff = 0
	while bits != 0
		diff += (bits & 1)
		bits >>= 1
	end
	count += 1 if diff <= k
end
puts count

n,m,k=gets.chomp.split.map(&:to_i)
ar,ans=[],0
(m+1).times {ar<<gets.to_i}
for i in 0...m do
	a,b,c=ar[i],ar[m],0
	while a>0 || b>0
		c+=1 if a&1 != b&1
		a/=2
		b/=2
	end
	ans+=1 if c<=k
end
puts ans

require 'pp'
n,m,k= STDIN.gets.chomp.split(/ /).map(&:to_i)

ans = 0
xs = []
m.times do |i|
  xs.push STDIN.gets.chomp.to_i
end

fedor = STDIN.gets.chomp.to_i

xs.each do |x|
  xor = x ^ fedor
  ans += 1 if xor.to_s(2).split(//).select{|e| e == "1"}.count <= k
end

puts ans

input = STDIN.read.split("\n")
n, m, k = *input[0].split(' ').map(&:to_i)
players = input[1..m].map(&:to_i)
fedya = input[m + 1].to_i

print players[0..m].count { |p| (p ^ fedya).to_s(2).chars.map(&:to_i).inject(:+) <= k }

n, m, k = gets.strip.split(" ").map(&:to_i)
armies = []
(m + 1).times do |i|
  armies[i] = gets.strip.to_i
end
# puts armies
number_of_friends = 0
m.times do |i|
  num = armies[i] ^ armies[m]
  # puts num.to_s(2)
  count = 0
  while num != 0 do
    count += 1 if num & 1 == 1
    num = num >> 1
    # puts num.to_s(2)
  end
  number_of_friends += 1 if count <= k
end
puts number_of_friends

#http://codeforces.com/contest/467/B

n,m, k = gets.split.map(&:to_i)
arr = []
m.times do
  arr += [gets.to_i]
end
fedor = gets.to_i
 ans =0
arr.each  do |val|
  bits= fedor ^ val             # to find  how much differences are there.....
  if bits.to_s(2).count('1') <= k  # counting 1 shows how much the two bits differ .....
    ans +=1
  end
end

p ans

n,m,k=gets.split.map{|e| e.to_i}
arr=[]
m.times{
	arr<<gets.to_i
}
r=gets.to_i
puts arr.count{|e|
	e1=e^r
	e1.to_s(2).scan("1").count<=k
}

n, m, k = gets.split.map(&:to_i)
a = m.times.map{ gets.to_i.to_s(2)}
f = gets.to_i.to_s(2)
r = 0
a.each do |s|
	c = 0
	1.upto([f.length,s.length].max) do |i|
		if s[-i] == '1' and f[-i] != s[-i]
			c += 1
		elsif f[-i] == '1' and s[-i] != f[-i]
			c += 1
		end
	end
	if c <= k
		r += 1
	end
end
puts r

s=gets.chomp.to_s
s=s.split(" ")
n=s[0].to_i
m=s[1].to_i
k=s[2].to_i
a = Array.new(m+1)
(m+1).times{ |iter|
	a[iter]=gets.chomp.to_i
}
i=0
count=0
while i<m
	hold=a[-1]^a[i]
	hold=hold.to_s(2)
	if hold.to_s.count("1")<=k
		count+=1
	end
	i+=1
end
puts (count)

n, m, @k = gets.chomp.split.map { |x| x.to_i }
a = m.times.collect { gets.to_i }
f = gets.to_i
def valid(i)
  i.to_s(2).scan(/1/).length <= @k
end
puts a.select { |x| valid x^f }.length

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

def binarize(num)
  str = num.to_s(2)
  str.chars.reverse + ['0']*(@n-str.size)
end

@n, m, k = readline.chomp.split(/\s+/).map(&:to_i)
ary = []
m.times do
  ary << binarize(readline.to_i)
end
me = binarize(readline.to_i)
c = 0
ary.each do |x|
  f = 0
  x.each_with_index { |i, v| f += 1 if i != me[v] }
  if f <= k
    c += 1
  end
end

puts c

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

arr = []

m += 1
m.times do
	n = gets.to_i
	arr << n
end
fedor = arr[-1]
count = 0
(0..m-2).each do |i|
	n = arr[i] ^ fedor
	set = 0
	while n >0
		n &= (n-1)
		set += 1
	end
	count += 1 if set <= k
end

puts count

n, m, k = gets.split.map(&:to_i)
a = m.times.map{gets.to_i}
me = gets.to_i
ans = 0
a.each do |x|
  ans += 1 if (x ^ me).to_s(2).split("").count('1') <= k
end
puts ans

def nbits(n)
    nb = 0
    while n > 0
        nb += n%2
        n /= 2
    end
    nb
end

n, m, k = gets.split.map{|x| x.to_i}
x = []
(m + 1).times{x << gets.to_i}
f = 0
(0..m-1).each{|i| f += 1 if nbits(x[i]^x[m]) <= k}
puts f

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

a = 1.upto(m).map { gets.to_i }
x = gets.to_i

puts a.count { |y| (x ^ y).to_s(2).count('1') <= k }

n, m, k = gets.split.map(&:to_i)
a = (0..m).map { |_| gets.to_i }
puts a[0..-2].select { |x| (x ^ a[-1]).to_s(2).count('1') <= k }.size

n, m, k = gets.split.map(&:to_i)
xs = []
max = 0
m.times do
  t = gets.to_i
  xs << t
end
x = gets.to_i
count = 0
xs.each do |i|
  c = (i ^ x).to_s(2).split("").map(&:to_i).inject{|sum,x| sum + x }
  count += 1 if c <= k
end

puts count

class Players
  attr_reader :x
  def initialize(x)
    @x = x
  end

  def bitnum(i)
    n = 0
    while i > 0
      n += i % 2
      i >>= 1
    end
    return n
  end

  def friend?(k, other)
    return bitnum(@x ^ other.x) <= k
  end
end

n, m, k = gets.split.map(&:to_i)
list = []
m.times do
  list << Players.new(gets.to_i)
end
my = Players.new(gets.to_i)
fnum = 0
list.each do |e|
  if my.friend?(k, e)
    fnum += 1
  end
end
puts fnum

def byte_count(num = 0)
  c = 0
  s = ""
  while true
    if "1" == (num - (num.div(2) * 2)).to_s
      c += 1
    end
    num = num.div(2)
    if num < 2
      break
    end
  end

  return c
end

nums = []
arr = []

c = 0
main = 0

gets.split(" ").each {|a| nums << a.to_i}

for i in (0..nums[1] - 1)
  arr[i] = gets.to_i
end

main = gets.to_i

for i in (0..nums[1] - 1)
  if byte_count(arr[i] ^ main) <= nums[2]
    c += 1
  end
end

puts c

def byte_count(num = 0)
  c = 0
  s = ""
  while true
    if "1" == (num - (num.div(2) * 2)).to_s + s
      c += 1
    end
    num = num.div(2)
    if num < 2
      break
    end
  end

  return c
end

nums = []
arr = []

c = 0
main = 0

gets.split(" ").each {|a| nums << a.to_i}

for i in (0..nums[1] - 1)
  arr[i] = gets.to_i
end

main = gets.to_i

for i in (0..nums[1] - 1)
  if byte_count(arr[i] ^ main) <= nums[2]
    c += 1
  end
end

puts c

def byte_count(num = 0)
  c = 0
  s = ""
  while true
    s = (num - (num.div(2) * 2)).to_s + s
    num = num.div(2)
    if num < 2
      s = num.to_s + s
      break
    end
  end

  for i in (0..s.length - 1)
    if s[i] = "1"
      c += 1
    end
  end

  return c
end

nums = []
arr = []

c = 0
main = 0

gets.split(" ").each {|a| nums << a.to_i}

for i in (0..nums[1] - 1)
  arr[i] = gets.to_i
end

main = gets.to_i

for i in (0..nums[1] - 1)
  if byte_count(arr[i] ^ main) <= nums[2]
    c += 1
  end
end

puts c

n,m,k=gets.chomp.split.map(&:to_i)
ar,ans=[],0
(m+1).times {ar<<gets.to_i}
for i in 0...m do
	a,b,c=ar[0],ar[m],0
	while a>0 || b>0
		c+=1 if a%2!=b%2
		a/=2
		b/=2
	end
	ans+=1 if c<=k
end
puts ans

require 'pp'
n,m,k= STDIN.gets.chomp.split(/ /).map(&:to_i)

ans = 0
xs = []
m.times do |i|
  xs.push STDIN.gets.chomp.to_i.to_s(2).split(//).reverse
end

fedor = STDIN.gets.chomp.to_i.to_s(2).split(//).reverse

xs.each do |x|
  kake = fedor & x
  ans += 1 if kake.count <= k
end

puts ans

require 'pp'
n,m,k= STDIN.gets.chomp.split(/ /).map(&:to_i)

ans = 0
xs = []
m.times do |i|
  xs.push STDIN.gets.chomp.to_i.to_s(2).split(//).reverse
end

fedor = STDIN.gets.chomp.to_i.to_s(2).split(//).reverse

xs.each do |x|
  c = [fedor.count, x.count].min
  diff = (fedor.count - x.count).abs
  c.times do |i|
    if fedor[i] != x[i]
      diff += 1
      break
    end
  end
  ans += 1 if diff <= k
end

puts ans

n,m,k = gets.split.map(&:to_i)
a = []
r = 0
(m + 1).times do |i|
	a[i] = gets.to_i
end
0.upto(m - 1) do |i|
	if [ a[m] , a[i] ].max - [ a[m] , a[i]].min <= k
		r += 1
	end
end
p r

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

def binarize(num)
  str = num.to_s(2)
  str.chars.reverse + ['0']*(@n-str.size)
end

@n, m, k = readline.chomp.split(/\s+/).map(&:to_i)
ary = []
m.times do
  ary << binarize(readline.to_i)
end
me = binarize(readline.to_i)
c = 0
ary.each do |x|
  f = 0
  x.each_with_index { |i, v| f += 1 if i == me[v] }
  c += 1 if f <= k
end

puts c

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

def binarize(num)
  str = num.to_s(2)
  str.chars.reverse + ['0']*(@n-str.size)
end

@n, m, k = readline.chomp.split(/\s+/).map(&:to_i)
ary = []
m.times do
  ary << binarize(readline.to_i)
end
p me = binarize(readline.to_i)
c = 0
ary.each do |x|
  f = 0
  x.each_with_index { |i, v| f += 1 if i != me[v] }
  if f <= k
    c += 1
  end
end

puts c

n, m, k = gets.split.map(&:to_i)
a = m.times.map{gets.to_i.to_s(2).chars.reverse}
me = gets.to_i.to_s(2).chars.reverse
ans = 0
a.each do |x|
  diff = 0
  [x.size, me.size].min.times do |i|
    diff += 1 if x[i] != me[i]
  end
  ans += 1 if diff <= k
end
puts ans

n, m, k = gets.split.map(&:to_i)
a = m.times.map{gets.to_i.to_s(2).chars.reverse}
me = gets.to_i.to_s(2).chars.reverse
ans = 0
a.each do |x|
  diff = 0
  [x.size, me.size].max.times do |i|
    if (i >= [x.size, me.size].min && (x[i] == 1 || me[i] == 1)) || x[i] != me[i]
      diff += 1
    end
  end
  ans += 1 if diff <= k
end
puts ans

n, m, k = gets.split.map(&:to_i)
a = m.times.map{gets.to_i.to_s(2).chars.reverse}
me = gets.to_i.to_s(2).chars.reverse
ans = 0
a.each do |x|
  diff = 0
  [x.size, me.size].max.times do |i|
    diff += 1 if x[i] != me[i]
  end
  ans += 1 if diff <= k
end
puts ans

n, m, k = gets.split.map(&:to_i)
a = m.times.map{gets.to_i.to_s(2).chars.reverse}
me = gets.to_i.to_s(2).chars.reverse
ans = 0
a.each do |x|
  diff = 0
  [x.size, me.size].min.times do |i|
    diff += 1 if x[i] != me[i]
  end
  diff += (x.size - me.size).abs
  ans += 1 if diff <= k
end
puts ans

def nbits(n)
    nb = 0
    while n > 0
        nb += n%2
        n /= 2
    end
    nb
end

n, m, k = gets.split.map{|x| x.to_i}
x = []
(m + 1).times{x << gets.to_i}
f = 0
(0..m-1).each{|i| f += 1 if n - nbits(x[i]&x[m]) <= k}
puts f

n, m, k = gets.split.map(&:to_i)
xs = []
max = 0
m.times do
  t = gets[0..n].to_i.to_s(2)
  max = [t.length, max].max
  xs << t
end

x = gets[0..n].to_i.to_s(2)
max = [max, x.length].max
x.ljust(max, "0")

x = x.split("")
xs.map! do |r|
  r.ljust(max, "0").split("")
end

count = 0
xs.each do |i|
  c = 0
  i.each_with_index do |p, j|
    c += 1 if x[j] == p
  end

  count += 1 if c <= k && c > 0
end

puts count

n, m, k = gets.split.map(&:to_i)
xs = []
max = 0
m.times do
  t = gets.to_i
  xs << t
end
x = gets.to_i
count = 0
xs.each do |i|
  c = (i ^ x)
  c = c.to_s(2).split("").map(&:to_i).inject{|sum,x| sum + x }
  break
  count += 1 if c < k
end

puts count

n, m, k = gets.split.map(&:to_i)
xs = []
max = 0
m.times do
  t = gets[0..n].to_i.to_s(2)
  max = [t.length, max].max
  xs << t
end

x = gets[0..n].to_i.to_s(2)
max = [max, x.length].max
x.rjust(max, "0")

x = x.split("")
xs.map! do |r|
  r.rjust(max, "0").split("")
end

count = 0
xs.each do |i|
  c = 0
  i.each_with_index do |p, j|
    c += 1 if x[j] == p
  end

  count += 1 if c <= k && c > 0
end

puts count

n, m, k = gets.split.map(&:to_i)
xs = []
max = 0
m.times do
  t = gets.to_i
  xs << t
end
x = gets.to_i
count = 0
xs.each do |i|
  c = (i ^ x)
  c = c.to_s(2).split("").map(&:to_i).inject{|sum,x| sum + x }
  break
  count += 1 if c <= k
end

puts count

n, m, k = gets.split.map(&:to_i)
xs = []
max = 0
m.times do
  t = gets.to_i
  xs << t
end
x = gets.to_i
count = 0
xs.each do |i|
  c = (i ^ x).to_s(2).split("").map(&:to_i).inject{|sum,x| sum + x }
  count += 1 if c < k
end

puts count

n, m, k = gets.split.map(&:to_i)
xs = []
max = 0
m.times do
  t = gets[0..n].to_i.to_s(2)
  max = [t.length, max].max
  xs << t
end

x = gets[0..n].to_i.to_s(2)
max = [max, x.length].max
x.rjust(max, "0")

x = x.split("")
xs.map! do |r|
  r.rjust(max, "0").split("")
end

count = 0
xs.each do |i|
  c = 0
  i.each_with_index do |p, j|
    c += 1 if x[j] != p
  end
  count += 1 if c <= k && c > 0
end

puts count

n, m, k = gets.split.map(&:to_i)
xs = []
max = 0
m.times do
  t = gets[0..n].to_i.to_s(2)
  max = [t.length, max].max
  xs << t
end

x = gets[0..n].to_i.to_s(2)
max = [max, x.length].max

x = x.split("")
xs.map! do |r|
  r.split("")
end

count = 0
xs.each do |i|
  c = 0
  i.each_with_index do |p, j|
    c += 1 if x[j] != p
  end
  count += 1 if c <= k
end

puts count

n, m, k = gets.split.map(&:to_i)
xs = []
max = 0
m.times do
  t = gets[0..n].to_i.to_s(2)
  max = [t.length, max].max
  xs << t
end

x = gets[0..n].to_i.to_s(2)
max = [max, x.length].max
x.rjust(max, "0")

x = x.split("")
xs.map! do |r|
  r.rjust(max, "0").split("")
end

count = 0
xs.each do |i|
  c = 0
  i.each_with_index do |p, j|
    c += 1 if x[j] != p
  end
  count += 1 if c <= k
end

puts count

n, m, k = gets.split.map(&:to_i)
xs = []
max = 0
m.times do
  t = gets.to_i
  xs << t
end
x = gets.to_i
count = 0
xs.each do |i|
  c = (i ^ x) & i
  c = c.to_s(2).split("").map(&:to_i).inject{|sum,x| sum + x }
  count += 1 if c <= k
end

puts count

n, m, k = gets.split.map(&:to_i)
xs = []
max = 0
(m).times do
  t = gets[0..n].to_i.to_s(2)
  max = [t.length, max].max
  xs << t
end
x = gets[0..n].to_i.to_s(2)
max = [max, x.length].max
x.ljust(max, "0")

x = x.split("")

xs.map! do |r|
  r.ljust(max, "0").split("")
end

count = 0
xs.each do |i|
  c = 0
  i.each_with_index do |p, j|
    c += 1 if x[j] == p
  end

  count += 1 if c <= k
end

puts count

n, m, k = gets.split.map(&:to_i)
xs = []
max = 0
m.times do
  t = gets[0..n].to_i.to_s(2)
  max = [t.length, max].max
  xs << t
end

x = gets[0..n].to_i.to_s(2)
max = [max, x.length].max
x.ljust(max, "0")

x = x.split("")
xs.map! do |r|
  r.ljust(max, "0").split("")
end

count = 0
xs.each do |i|
  c = 0
  i.each_with_index do |p, j|
    c += 1 if x[j] != p
  end
  count += 1 if c <= k
end

puts count


def solution(n, m, x)
  x -= 1

  col = x / n
  row = x % n
  row * m + col + 1
end

test_cases = gets.to_i

test_cases.times do |test_case|
  arr = gets.split(' ').map(&:to_i)
  puts solution(arr[0], arr[1], arr[2])
end

t = gets().to_i
while(t!=0)
  ar = gets.chomp.split().map { |e| e.to_i  }
  n = ar[0]
  m = ar[1]
  x = ar[2]
  x-=1
  col = (x/n).to_i
  row = x%n
  ans = row*m + col + 1
  puts "#{ans}\n"
  t-=1
end

def solve_case
  n, m, x = gets.chomp.split(' ').map(&:to_i)

  c = (x.to_f / n.to_f).ceil
  r = x - (n * (c - 1))

  row_x = c + (m * (r - 1))
  puts row_x
end

t = gets.chomp.to_i
t.times do
  solve_case
end


t = gets.to_i

t.times do
  a, b, c = gets.split(' ').map(&:to_i)
  puts a + b == c || a + c == b || c + b == a ? 'YES' : 'NO'
end

n = gets.to_i
n.times do
  array = gets.split(' ').map(&:to_i).sort
  puts array[0] + array[1] == array[2] ? 'YES' : 'NO'
end

t=gets.to_i
while t>=1
	a,b,c=gets.split.map(&:to_i)
	if a+b==c
		puts "YES"
	elsif b+c==a
		puts "YES"
	elsif a+c==b
		puts "YES"
	else
		puts "NO"
	end
	t=t-1
end

n=gets.to_i
n.times do
    a=gets.split.map(&:to_i)
    a.sort!
    if a.sum==a[-1]*2
        puts "YES"
    else
        puts "NO"
    end
end

gets.to_i.times do
  a=gets.split.map(&:to_i).sort
  puts a[0]+a[1]==a[2] ? 'YES' : 'NO'
end

    n = gets.to_i
    n.times do
      array = gets.split(' ').map(&:to_i)
      puts ([array[0] + array[1], array[1] + array[2], array[0] + array[2]] - array).size < 3 ? "YES" : "NO"
    end

n = gets.to_i
n.times do
  array = gets.split(' ').map(&:to_i)
  print ([array[0] + array[1], array[1] + array[2], array[0] + array[2]] - array).size < 3 ? "YES" : "NO"
end

n = gets.to_i
n.times do
  array = gets.split(' ').map(&:to_i)
  print ([array[0] + array[1], array[1] + array[2], array[0] + array[2]] - array).size < 3
end


a=gets.chomp.to_i
negp=[]
posp=[]
neg=[]
pos=[]
ans=0
a.times do
temp=gets.chomp.split
0.upto(1) {|i| temp[i]=temp[i].to_i}
if temp[0]<0
negp<<temp
else
posp<<temp
end
ans+=temp[1]
end
negp=negp.sort_by{|x,y|x}
negp.reverse!
posp=posp.sort_by{|x,y|x}

negp.each {|i| neg << i[1]}
posp.each {|i| pos << i[1]}
n=neg.length
p=pos.length

if n==p
puts "#{ans}"
elsif n<p
a=0
(n+1).upto(p-1){|i| a+=pos[i]}
ans=ans-a
puts "#{ans}"
else
a=0
(p+1).upto(n-1){|i| a+=neg[i]}
ans=ans-a
puts "#{ans}"
end

n = gets.to_i
t = (1..n).map{ gets.split.map(&:to_i) }
t.sort_by!{|x, a| x}
i = t.index{|x, a| x > 0}

if i == nil
    p t[-1][1]
elsif i == 0
    p t[0][1]
else
    l_num = i
    r_num = t.size - i
    l_taken = [l_num, r_num+1].min
    r_taken = [r_num, l_num+1].min
    p (t[i-l_taken..i-1] + t[i..i+r_taken-1]).map{|x,a| a}.inject(:+)
end

ls=[]
rs=[]
gets.to_i.times{
	x,y=gets.split.map{|e| e.to_i}
	if x<0 then
		ls<<[x,y]
	else
		rs<<[x,y]
	end
}
ls.sort!.reverse!
rs.sort!
ans=0
while ls.empty? ==false && rs.empty? ==false
	ans+=ls.shift[1]+rs.shift[1]
end
ans+=ls.shift[1] if ls.empty? ==false
ans+=rs.shift[1] if rs.empty? ==false
puts ans

l = []
r = []
n = gets.chomp.to_i
n.times do
	pair = gets.chomp.split(" ").map &(lambda { |x| x.to_i })
	r <<= [pair[0], pair[1]] if pair[0] > 0
	l <<= [pair[0], pair[1]] if pair[0] <= 0
end

r.sort!
l.sort! &(lambda { |a,b| b <=> a })

best = 0
for i in 0..1 do
	reachl = 0
	reachr = 0
	score = 0
	left = i == 0
	while (left && reachl != l.size) || (!left && reachr != r.size)
		if !left
			score += r[reachr][1]
			reachr += 1
			left = !left
		else
			score += l[reachl][1]
			reachl += 1
			left = !left
		end
	end
	best = [best, score].max
end
print best

d = gets.to_i.times.map{gets.split.map(&:to_i)}
m = d.select{|a,b| a < 0}.sort
p = d.select{|a,b| a > 0}.sort.reverse
sum = 0
while(m!=[] && p!=[])
    sum += m.pop[1]+p.pop[1]
end
if m!=[]
    sum+=m.pop[1]
end
if p!=[]
    sum+=p.pop[1]
end
p sum

n = gets.to_i
a = n.times.map{gets.split.map(&:to_i)}.partition{|x| x[0] < 0}.map{|x| x.sort_by{|x| x[0].abs}}
m = [a[0].size, a[1].size].min
puts a[0][0..m].reduce(0){|s, x| s + x[1]} + a[1][0..m].reduce(0){|s, x| s + x[1]}

n = gets.to_i
a = n.times.map{gets.split.map(&:to_i)}
neg = []
pos = []
a.each do |x|
  neg << x if x[0] < 0
  pos << x if x[0] > 0
end
m = [neg.size, pos.size].min
puts neg.sort.reverse[0..m].reduce(0){|s, x| s + x[1]} + pos.sort[0..m].reduce(0){|s, x| s + x[1]}

def min(a,b)
	if a < b
		return a
	else
		return b
	end
end

def max(a,b)
	if a > b
		return a
	else
		return b
	end
end

n = gets.chomp.to_i

neg_arr = Array.new(100001){0}
pos_arr = Array.new(100001){0}

neg_size = 0
pos_size = 0

n.times do

x,a =  gets.chomp.split.map{|x| x.to_i}

if x < 0
	neg_arr[x*-1] = a
	neg_size+=1
else
	pos_arr[x] = a
	pos_size+=1
end

end
output = 0
if neg_size == pos_size
	(1..100000).each do |i|
	output+=neg_arr[i]
	output+=pos_arr[i]
	end
else

	min = min(neg_size,pos_size)
	max = max(neg_size,pos_size)

	if min == neg_size
		neg_arr.each do |v|
			output+=v
		end
		j = 0
		(1..100000).each do |i|
			if pos_arr[i]!=0
				output+=pos_arr[i]
				j+=1
			end
			if j==min+1
				break
			end
		end
	else
		pos_arr.each do |v|
			output+=v
		end
		j = 0
		(1..100000).each do |i|
			if neg_arr[i]!=0
				output+=neg_arr[i]
				j+=1
			end
			if j==min+1
				break
			end
		end
	end

end

puts output

#!/usr/bin/ruby
a,b=gets.to_i.times.map{
	gets.split.map(&:to_i)
}.partition{|e|
	e[0]>0
}.map{|e|
	e.sort_by{|f|f[0].abs}
}.sort_by(&:size)
p (a+b[0,a.size+1]).map(&:last).reduce(:+)

n = gets.to_i
pos = {}
neg = {}
n.times do
    arr = gets.split(' ')
    x = arr.first.to_i
    a = arr.last.to_i
    if x < 0
        neg[x.abs] = a
    else
        pos[x] = a
    end
end
t_size = [neg.size, pos.size].min
neg = neg.sort
pos = pos.sort
val = 0
t_size.times do |i|
    val+=neg[i].last
    val+=pos[i].last
end
if neg.size == pos.size
    puts val
else
    if neg.size < pos.size
        puts val+pos[t_size].last
    else
        puts val+neg[t_size].last
    end
end

n = gets.chomp.to_i

plus = []
minus = []
n.times do
  p,v = gets.split.map{ |x| x.to_i }
  minus << [-p,v] if p < 0
  plus << [p,v] if p > 0
end

plus.sort!
minus.sort!

sum = 0
if plus.size >= minus.size
  minus.size.times do |i|
    sum += plus[i][1];
    sum += minus[i][1];
  end
  if plus.size > minus.size
    sum += plus[minus.size][1];
  end
else
  plus.size.times do |i|
    sum += plus[i][1];
    sum += minus[i][1];
  end
  sum += minus[plus.size][1];
end
puts sum

n = gets.chomp.to_i
apples = [].tap do |arr|
  n.times { arr << gets.chomp.split.map(&:to_i) }
end

a, b = apples.partition { |e| e.first < 0 }.sort_by(&:size).map do |e|
  e.sort_by! { |e| e.first.abs }
end

puts (a + b[0..a.size]).map(&:last).inject(0, :+)

n = gets.to_i;
arr = Array.new();
ans = 0;

n.times {|x| arr[x] = gets.split.map(&:to_i)};
arr.push([0, 0]);
arr.sort!;
pos = arr.index([0, 0]);

s, e = 0, n;
if (pos > n - pos)
  s = pos - (n - pos) - 1;
elsif (pos < n - pos)
  e = pos + pos + 1;
end
# puts s, e;
(s..e).each {|x| ans += arr[x][1]};
puts ans;

def min(a,b)
	if a < b
		return a
	else
		return b
	end
end

def max(a,b)
	if a > b
		return a
	else
		return b
	end
end

n = gets.chomp.to_i

neg_arr = Array.new(100001){0}
pos_arr = Array.new(100001){0}

neg_size = 0
pos_size = 0

n.times do

x,a =  gets.chomp.split.map{|x| x.to_i}

if x < 0
	neg_arr[x*-1] = a
	neg_size+=1
else
	pos_arr[x] = a
	pos_size+=1
end

end
output = 0
if neg_size == pos_size
	(1..100).each do |i|
	output+=neg_arr[i]
	output+=pos_arr[i]
	end
else

	min = min(neg_size,pos_size)
	max = max(neg_size,pos_size)

	if min == neg_size
		neg_arr.each do |v|
			output+=v
		end
		j = 0
		(0..100).each do |i|
			if pos_arr[i]!=0
				output+=pos_arr[i]
				j+=1
			end
			if j==min+1
				break
			end
		end
	else
		pos_arr.each do |v|
			output+=v
		end
		j = 0
		(0..100).each do |i|
			if neg_arr[i]!=0
				output+=neg_arr[i]
				j+=1
			end
			if j==min+1
				break
			end
		end
	end

end

puts output

# http://codeforces.com/contest/558/problem/A

n = gets.chomp.to_i
apples = [].tap do |arr|
  n.times { arr << gets.chomp.split.map(&:to_i) }
end

a, b = apples.partition { |a| a.first < 0 }.sort_by(&:size)
c = a + b[0..a.size]
puts c.map(&:last).inject(0, :+)

n = gets.chomp.to_i
hash = {}
n.times do
  idx, num = gets.chomp.split.map(&:to_i)
  hash[idx] = num
end

min, max = hash.keys.min, hash.keys.max
right, left = [], []
(min..max).each do |idx|
  next unless hash.key?(idx)
  idx < 0 ? left << hash[idx] : right << hash[idx]
end

scores = []
scores << right.inject(0, :+) + left.last unless left.empty?
scores << left.inject(0, :+) + right.first unless right.empty?
scores << right.first if left.empty?
scores << left.last if right.empty?
puts scores.max

a=gets.chomp.to_i
negp=[]
posp=[]
neg=[]
pos=[]
ans=0
a.times do
temp=gets.chomp.split
0.upto(1) {|i| temp[i]=temp[i].to_i}
if temp[0]<0
negp<<temp
else
posp<<temp
end
ans+=temp[1]
end
negp.sort!
posp.sort!

negp.each {|i| neg << i[1]}
posp.each {|i| pos << i[1]}
n=neg.length
p=pos.length

if n==p
puts "#{ans}"
elsif n<p
a=0
(n+1).upto(p-1){|i| a+=pos[i]}
ans=ans-a
puts "#{ans}"
else
a=0
(p+1).upto(n-1){|i| a+=neg[i]}
ans=ans-a
puts "#{ans}"
end

a=gets.chomp.to_i
neg=[]
pos=[]
ans=0
a.times do
temp=gets.chomp.split(" ")
if temp[0].to_i<0
neg << temp[1].to_i
elsif temp[0].to_i>0
pos << temp[1].to_i
else
ans+=temp[1].to_i
end
end
l=neg.length
b=pos.length
if l<b
0.upto(l-1) {|i| ans=ans+neg[i]}
0.upto(l) {|i| ans=ans+pos[i]}
puts "#{ans}"
elsif b<l
0.upto(b-1) {|i| ans=ans+pos[i]}
0.upto(b) {|i| ans=ans+neg[i]}
puts "#{ans}"
else
0.upto(b-1) {|i| ans=ans+pos[i]}
0.upto(b-1) {|i| ans=ans+neg[i]}

puts "#{ans}"

end

n = gets.to_i
a = n.times.map{gets.split.map(&:to_i)}
neg = []
pos = []
a.each do |x|
  neg << x if x[0] < 0
  pos << x if x[0] > 0
end
m = [neg.size, pos.size].min
p neg.sort.reverse , pos.sort
puts neg.sort.reverse[0..m].reduce(0){|s, x| s + x[1]} + pos.sort[0..m].reduce(0){|s, x| s + x[1]}

n = gets.to_i
a = n.times.map{gets.split.map(&:to_i)}
neg = []
pos = []
a.each do |x|
  neg << x if x[0] < 0
  pos << x if x[0] > 0
end
m = [neg.size, pos.size].min
puts neg.reverse[0..m].reduce(0){|s, x| s + x[1]} + pos[0..m].reduce(0){|s, x| s + x[1]}

n = gets.to_i
a = n.times.map{gets.split.map(&:to_i)}
neg = []
pos = []
a.each do |x|
  neg << x if x[0] < 0
  pos << x if x[0] > 0
end
m = [neg.size, pos.size].min
puts neg[0..m].reduce(0){|a, b| a + b[1]} + pos[0..m].reduce(0){|a, b| a + b[1]}


n = gets.to_i
a = gets.split.map(&:to_i)
for i in 1..n
  for j in 1..n-i
    if a[j-1]>a[j]
      a[j-1],a[j] = a[j],a[j-1]
      puts "#{j} #{j+1}"
    end
  end
end

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

n.times do
  (0...(n - 1)).each do |idx|
    if arr[idx] > arr[idx + 1]
      arr[idx], arr[idx + 1] = arr[idx + 1], arr[idx]
      puts [idx + 1, idx + 2].join(" ")
    end
  end
end

n=gets.to_i
a=gets.split.map &:to_i
loop {
    changed=false
    for i in 1...n
        if a[i-1]>a[i]
            puts "#{i} #{i+1}"
            changed=true
            a[i-1], a[i]=a[i], a[i-1]
            break
        end
    end
    break unless changed
}

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

while as != bs
  for i in 0...n - 1
    if as[i] > as[i + 1]
      puts "#{i + 1} #{i + 2}"
      tmp = as[i + 1]
      as[i + 1] = as[i]
      as[i] = tmp
    end
  end
end

animalNumber = gets.chomp.to_i
heights = gets.chomp.split(' ').map(&:to_i)

sortedHeights = heights.sort

def pull target, source, heights
	index = source

	until index == target
		temp = heights[index - 1]
		heights[index - 1] = heights[index]
		heights[index] = temp

		puts "#{index} #{index + 1}"
		index -= 1
	end
end

for i in 0...(heights.length)
	if heights[i] != sortedHeights[i]
		index = heights[i...(heights.length)].index(sortedHeights[i]) + i
		pull i, index, heights
	end
end

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

n.times do
  (0...(n - 1)).each do |idx|
    if arr[idx] < arr[idx + 1]
      arr[idx], arr[idx + 1] = arr[idx + 1], arr[idx]
      puts [idx + 1, idx + 2].join(" ")
    end
  end
end


n=gets.to_i

data=Array.new(2*n)
str=[*?a..?z].join

n.times{|i|
	if i-4<0
		data[i]=str[i%26,1]
	else
		data[i]=data[i-4]
	end
}

puts data.join

#!/usr/bin/env ruby

ARGF.each_line do |s|
  num = s.to_i
  ret = 'abcd' * (1 + num / 4)

  puts ret[0..(num-1)]
end

n = gets.to_i
puts ('abcd' * (n/4+1))[0, n]

#!/usr/bin/ruby

n = gets.to_i
str = 'abcd' * (n / 4)
str << 'abcd'[0...(n%4)]
puts str

a="abcd"*25000
gets.to_i.times{|i| print "#{a[i]}"}

n = gets.chop.to_i
s = Array.new(n);
for i in 0..n-1
	print ((i%4)+'a'.ord).chr

end
print "\n"

def check(val)
  count = 0
  hash = Hash.new
  index = 1
  val.each_char  { |s|
    if hash[s] == nil
      hash[s] = Array.new
    end

    hash[s] << index
    index += 1
  }

  hash.delete_if {|key, value| value.length == 1 }

  if hash.length == 0
    return true
  end

  #p hash

  hash.each_value { |arr|
    #p arr
    for i in 1..arr.length-1
      diff = arr[i] - arr[i-1]
      #puts "#{arr[i]} - #{arr[i-1]} = #{diff}"
      if (diff != 4 and diff != 7)
        return false
      end
    end
  }
  return true
end

def inc(val, index)
  if (val[index] == 'z')
    val[index] = 'a'
    val = inc(val, index - 1)
  else
    val[index] = val[index].succ
  end
  return val
end

l = gets.chop.to_i
val = ''
#val = gets.chop
f = l/4
o = l % 4
val = 'abcd' * f
o.times { |i| val += 'a' }
#puts "#{f} #{o}"

#l.times { |i|
  #val += 'a'
  while check(val) == false
    val = inc(val, val.length-1)
  end
#}
puts val

ans = "abcd" * 25000
n = gets.to_i
puts ans[0..(n-1)]

#! /usr/bin/env ruby

n = STDIN.read.to_i

alpha = "abcd"
n.times { |i|
  print alpha[i % 4].chr
}
puts

arr = (0..STDIN.gets.to_i-1).map {|i| nil}

#charlist = %W[a b c d e f g h i j k l m n o p q r s t u v w x y z]
charlist = %W[a b c d]

idx = -1

while arr.index(nil)
  idx += 1
  ch = charlist[idx]
  pre = 0
  (0..arr.length-1).each do |i|
    if arr[i] == nil
      pre = i
      arr[pre] = ch
      break
    end
  end
  (0..arr.length-1).each do |i|
    diff = i-pre
    if diff == 4 or diff == 7 and arr[i] == nil
      pre = i
      arr[i] = ch
    end
  end
  #puts arr.to_s
end

puts arr.join

arr = (0..STDIN.gets.to_i-1).map {|i| nil}

charlist = %W[a b c d e f g h i j k l m n o p q r s t u v w x y z]

idx = -1

while arr.index(nil)
  idx += 1
  ch = charlist[idx]
  pre = 0
  (0..arr.length-1).each do |i|
    if arr[i] == nil
      pre = i
      arr[pre] = ch
      break
    end
  end
  (0..arr.length-1).each do |i|
    diff = i-pre
    if diff == 4 or diff == 7 and arr[i] == nil
      pre = i
      arr[i] = ch
    end
  end
  #puts arr.to_s
end

puts arr.join

n = gets.chomp.to_i
puts ("abcd" * ((n / 4.0).ceil.to_i)).chars.to_a.take(n).join('')

#!/usr/bin/env ruby

ARGF.each_line do |s|
  num = s.to_i
  ret = 'z' * num

  num.times do |i|
    tmp = (97 + (i % 4)).chr
    ret[i] = tmp if ret[i] > tmp

    tmp = (97 + (i % 7)).chr
    ret[i] = tmp if ret[i] > tmp
  end
  puts ret
end

ans = "abcdabc" * 15000
n = gets.to_i
puts ans[0..(n-1)]

#!/usr/bin/env ruby

n = STDIN.gets.to_i

count = n/7
while  count > -1
  if (n-7*count) % 4 == 0
    puts [[4]*((n-7*count)/4),[7]*count].flatten.join
    exit
  end
  count -= 1
end
puts -1

arr = (0..STDIN.gets.to_i-1).map {|i| nil}

%W[a b c d e f g h i j k l m n o p q r s t u v w x y z].each do |ch|
  pre = 0
  (0..arr.length-1).each do |i|
    if arr[i] == nil
      pre = i
      arr[pre] = ch
      break
    end
  end
  (0..arr.length-1).each do |i|
    diff = i-pre
    if diff == 4 or diff == 7 and arr[i] == nil
      pre = i
      arr[i] = "a"
    end
  end
  break unless arr.index(nil)
end

puts arr.join

arr = (0..STDIN.gets.to_i-1).map {|i| nil}

arr[0] = "a"
pre = 0
(0..arr.length-1).each do |i|
  diff = i-pre
  arr[i] = "a" if diff == 4 or diff == 7
end

if (arr.length > 1)
  c = "b"
  pre = 1
  arr[pre] = c
  (0..arr.length-1).each do |i|
    diff = i-pre
    arr[i] = c if (diff == 4 or diff == 7) and arr[i] == nil
  end
end

if (arr.length > 2)
  c = "c"
  pre = 2
  arr[pre] = c
  (0..arr.length-1).each do |i|
    diff = i-pre
    arr[i] = c if (diff == 4 or diff == 7) and arr[i] == nil
  end
end

if (arr.length > 3)
  c = "d"
  pre = 3
  arr[pre] = c
  (0..arr.length-1).each do |i|
    diff = i-pre
    arr[i] = c if (diff == 4 or diff == 7) and arr[i] == nil
  end
end

puts arr.join


n=gets.to_i
a=gets.split.map(&:to_i)
b=[]
30.downto(0) do |i|
  d=1<<i
  c=d-1
  a.each do |x|
    if x&d>0
      c&=x
      b<<x
    end
  end
  if c==0
    puts b.size, b.join(' ')
    exit
  end
  b.clear
end

n=gets.to_i
a=gets.split.map(&:to_i)
30.downto(0) do |i|
  d=1<<i
  c=d-1
  a.each do |x|
    if x&d>0
      c&=x
    end
  end
  if c==0
    b=a.select{|x|x&d>0}
    puts b.size, b.join(' ')
    exit
  end
end

n=gets.to_i
a=gets.split.map(&:to_i)
b=Array.new(31){|i|1<<i}
c=Array.new(31){[]}
d=Array.new(31){|i|(1<<i)-1}
a.each do |x|
  b.each_with_index do |y,i|
    if x&y>0
      c[i]<<x
      d[i]&=x
    end
  end
end
31.downto(0) do |i|
  if d[i]==0 and c[i].size>0
    puts c[i].size, c[i].join(' ')
    exit
  end
end

n=gets.to_i
a=gets.split.map(&:to_i)
Math.log2(a.last).to_i.downto(0) do |i|
  d=1<<i
  c=d-1
  a.each do |x|
    if x&d>0
      c&=x
    end
  end
  if c==0
    b=a.select{|x|x&d>0}
    puts b.size, b.join(' ')
    exit
  end
end

n=gets.to_i
a=gets.split.map(&:to_i)
m=1<<Math.log2(a.last).to_i
a=a.select{|x|x>=m}
puts a.size,a.join(' ')


a=gets;b=gets.chomp;c=gets.chomp;puts %w{fantasy forward backward both}[(a.match(b+'.*'+c)?1:0)|(a.match((b+'*.'+c).reverse)?2:0)]

a=gets.chomp
al=a.length
b=gets.chomp
bl=b.length
c=gets.chomp
cl=c.length
tr=0
if bl+cl<=al
intr=0
i=0
aka=b
akal=bl
loop do
if a[i..i+akal-1]==aka
i=i+akal-1
aka=c
akal=cl
intr+=1
end
i+=1
break if intr==2
break if i+akal>=al+1
end
if intr==2
tr=1
end
a.reverse!
intr=0
i=0
aka=b
akal=bl
loop do
if a[i..i+akal-1]==aka
i=i+akal-1
aka=c
akal=cl
intr+=1
end
i+=1
break if intr==2
break if i+akal>=al+1
end
if intr==2 && tr==1
tr+=2
elsif intr==2
tr=2
end
end
if tr==3
puts "both"
elsif tr==2
puts "backward"
elsif tr==1
puts "forward"
else
puts "fantasy"
end

def test(a, a1, a2)
  i = a.index(a1)
  if !i.nil? then
    b = a[i+a1.size..a.size]
    return true if !b[a2].nil?
  end
  return false
end
a = gets.strip
a1 = gets.strip
a2= gets.strip
t1 = test(a, a1, a2)
a.reverse!
t2 = test(a, a1, a2)
if t1 then
  if t2 then
    puts "both"
  else
    puts "forward"
  end
else
  if t2 then
    puts "backward"
  else
    puts "fantasy"
  end
end

flags = gets.chomp
line2 = gets.chomp
line3 = gets.chomp
flag2 = (flags =~ /#{line2}/)
flag3 = (flags[(flag2+line2.size)..-1] =~ /#{line3}/) if flag2
forward = true if flag2 && flag3

rflags = flags.reverse
flag2 = (rflags =~ /#{line2}/)
flag3 = (rflags[(flag2+line2.size)..-1] =~ /#{line3}/) if flag2
backward = true if flag2 && flag3

if forward && backward
  puts "both"
elsif forward
  puts "forward"
elsif backward
  puts "backward"
else
  puts "fantasy"
end

line, seq1, seq2, forward, backward = gets().chomp!, gets().chomp!, gets().chomp!, false, false
if /#{seq1}.*#{seq2}/.match(line) then forward = true end
if /#{seq2.reverse!}.*#{seq1.reverse!}/.match(line) then backward = true end
if forward && backward then puts( "both" ) elsif forward then puts( "forward" ) elsif backward then puts( "backward" ) else puts( "fantasy" ) end

sequence = gets.chomp
first = gets.chomp
second = gets.chomp

result = "fantasy"
index = sequence.index(first)
if index
	result = "forward" if sequence.index(second, index + first.length)
end

sequence.reverse!

index = sequence.index(first)
if index
	if sequence.index(second, index + first.length)
		result = (result == "forward") ? "both" : "backward"
	end
end

puts result

#!/usr/bin/env ruby

txt = gets.chomp
str1 = gets.chomp
str2 = gets.chomp

forward = backward = false

if txt =~ /#{str1}.*#{str2}/
  forward = true
end

txt.reverse!

if txt =~ /#{str1}.*#{str2}/
  backward = true
end

if forward == true and backward == true
  puts "both"
elsif forward == true and backward == false
  puts "forward"
elsif forward == false and backward == true
  puts "backward"
else
  puts "fantasy"
end

map = gets.strip
x = gets.strip
y = gets.strip

result = "fantasy"
i = map.index(x)
if i
  result = "forward" if map.index(y, i+x.length)
end
map.reverse!

i = map.index(x)
if i
  if map.index(y, i+x.length)
    if result == "forward"
      result = "both"
    else
      result = "backward"
    end
  end
end
puts result

flags = gets.chomp!

s1 = gets.chomp!
s2 = gets.chomp!

forward = false
backward = false
fantasy = false

if (flags.index(s1) != nil && flags.index(s2, flags.index(s1)+s1.length) != nil)
  forward = true
else
  forward = false
end

if (flags.reverse.index(s1) != nil && flags.reverse.index(s2, flags.reverse.index(s1)+s1.length))
  backward = true
else
  backward = false
end

if backward && forward
  puts "both"
else
  if forward
    puts "forward"
  else
    if backward
      puts "backward"
    else
      puts "fantasy"
    end
  end
end

a = gets.chomp
b = a.reverse

f = gets.chomp
s = gets.chomp

if (k = a.index(f)) && a.index(s,k+f.size) then
    n = "forward"
else
    n = 0
end

if (k = b.index(f)) && b.index(s,k+f.size) then
    if n == 0 then
        n = "backward"
    else
        n = "both"
    end
else
    if n == 0
        n = "fantasy"
    end
end

puts n

s, a, b = readlines.map(&:chop)
r = /#{a}.*#{b}/
puts %w(fantasy forward backward both)[(s =~ r ? 1 : 0) | (s.reverse =~ r ? 2 : 0)]

s, a, b = readlines.map(&:chop)
r, i = /#{a}.*#{b}/, 0
i |= 1 if s =~ r
i |= 2 if s.reverse =~ r
puts %w(fantasy forward backward both)[i]

str1 = gets.chomp!
str2 = gets.chomp!
str3 = gets.chomp!
forward = backward = false
if str1.match(/#{str2}\w*#{str3}/)
	forward = true
end
str11 = str1.reverse
if str11.match(/#{str2}\w*#{str3}/)
	backward = true
end
if forward && backward
	puts 'both'
elsif forward
	puts 'forward'
elsif backward
	puts 'backward'
else
	puts 'fantasy'
end

a=gets.chomp;b=gets.chomp;c=gets.chomp;
 puts %w[fantasy forward backward both][(a.match(b+'.*'+c)?1:0)|(a.match((b+'*.'+c).reverse)?2:0)]

def solve(data)
        q=data.index($a)
        if q==nil then
                return false
        end
        r=data.rindex($b)
        if r==nil then
                return false
        end
        return q+$a.length<=r
end

input=gets.split[0]
$a=gets.split[0]
$b=gets.split[0]
if solve(input) then
        if solve(input.reverse) then
                puts "both"
        else
                puts "forward"
        end
else
        if solve(input.reverse) then
                puts "backward"
        else
                puts "fantasy"
        end
end

#!/usr/bin/ruby -Ku

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

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

s = gets.chomp
a = gets.chomp
b = gets.chomp
f = (s =~ Regexp.new(a + ".*" + b))
s = s.reverse
b = (s =~ Regexp.new(a + ".*" + b))
if f && b
  puts "both"
elsif f
  puts "forward"
elsif b
  puts "backward"
else
  puts "fantasy"
end

a = gets.chomp
b = a.reverse

f = gets.chomp
s = gets.chomp

if (k = a.index(f)) && a.index(s,k+1) then
    n = "forward"
else
    n = 0
end

if (k = b.index(f)) && b.index(s,k+1) then
    if n == 0 then
        n = "backward"
    else
        n = "both"
    end
else
    if n == 0
        n = "fantasy"
    end
end

puts n

s, a, b = readlines.map(&:chop)
r, i = /#{gets}.*#{gets}/, 0
i |= 1 if s =~ r
i |= 2 if s.reverse =~ r
puts %w(fantasy forward backward both)[i]

a=gets.chomp;b=gets.chomp;c=gets.chomp;
 puts %w[fantasy foreward backward both][(a.match(b+'.*'+c)?1:0)|(a.match((b+'*.'+c).reverse)?2:0)]

a=gets.chomp
al=a.length
b=gets.chomp
bl=b.length
c=gets.chomp
cl=c.length
tr=0
if bl+cl<=cl
intr=0
i=0
aka=b
akal=bl
loop do
if a[i..i+akal-1]==b
aka=c
akal=cl
intr+=1
i=i+aka-1
end
i+=1
break if intr==2
break if i+akal==al+1
end
if intr==2
tr=1
end
a.reverse!
intr=0
loop do
if a[i..i+akal-1]==bl
aka=cl
akal=cl
intr+=1
i=i+aka-1
end
i+=1
break if intr==2
break if i+akal==al+1
end
if intr==2 && tr==1
tr+=2
else
tr=2
end
end
if tr==3
puts "both"
elsif tr==2
puts "backward"
elsif tr==1
puts "forward"
else
puts "fantasy"
end

a=gets.chomp
al=a.length
b=gets.chomp
bl=b.length
c=gets.chomp
cl=c.length
tr=0
if bl+cl<=al
intr=0
i=0
aka=b
akal=bl
loop do
if a[i..i+akal-1]==aka
aka=c
akal=cl
intr+=1
i=i+akal-1
end
i+=1
break if intr==2
break if i+akal==al+1
end
if intr==2
tr=1
end
a.reverse!
intr=0
i=0
aka=b
akal=bl
loop do
if a[i..i+akal-1]==aka
aka=cl
akal=cl
intr+=1
i=i+akal-1
end
i+=1
break if intr==2
break if i+akal==al+1
end
if intr==2 && tr==1
tr+=2
elsif intr==2
tr=2
end
end
if tr==3
puts "both"
elsif tr==2
puts "backward"
elsif tr==1
puts "forward"
else
puts "fantasy"
end

def test(a, a1, a2)
  i = a.index(a1)
  if !i.nil? then
    b = a[i+a1.size..a.size]
    return true if !b[a2].nil?
  end
  return false
end
a = gets.strip
a1 = gets.strip
a2= gets.strip
t1 = test(a,a1,a2)
a.reverse!
a1.reverse!
a2.reverse!
t2 = test(a, a2, a1)
if t1 then
  if t2 then
    puts "both"
  else
    puts "forward"
  end
else
  if t2 then
    puts "backward"
  else
    puts "fantasy"
  end
end

def test(a, a1, a2)
  i = a.index(a1)
  if !i.nil? then
    b = a[i+a1.size..a.size]
    return true if !b[a2].nil?
  end
  return false
end
a = gets.strip
a1 = gets.strip
a2= gets.strip
t1 = test(a,a1,a2)
a.reverse!
a1.reverse!
a.reverse!
t2 = test(a, a2, a1)
if t1 then
  if t2 then
    puts "both"
  else
    puts "forward"
  end
else
  if t2 then
    puts "backward"
  else
    puts "fantasy"
  end
end

def test(a, a1, a2)
  i = a.index(a1)
  if !i.nil? then
    b = a[i+a1.size..a.size]
    p b
    return true if !b[a2].nil?
  end
  return false
end
a = gets.strip
a1 = gets.strip
a2= gets.strip
t1 = test(a,a1,a2)
a.reverse!
a1.reverse!
a2.reverse!
t2 = test(a, a2, a1)
if t1 then
  if t2 then
    puts "both"
  else
    puts "forward"
  end
else
  if t2 then
    puts "backward"
  else
    puts "fantasy"
  end
end

#!/usr/bin/env ruby

txt = gets.chomp
str1 = gets.chomp
str2 = gets.chomp

forward = backward = false

if txt =~ /#{str1}.*#{str2}/
  forward = true
end

txt.reverse!
str1.reverse!
str2.reverse!

if txt =~ /#{str2}.*#{str1}/
  backward = true
end

if forward == true and backward == true
  puts "both"
elsif forward == true and backward == false
  puts "forward"
elsif forward == false and backward == true
  puts "backward"
else
  puts "fantasy"
end

#!/usr/bin/env ruby

txt = gets.chomp
str1 = gets.chomp
str2 = gets.chomp

forward = backward = false

if txt =~ /#{str1}.*#{str2}/
  forward = true
end

txt.reverse!
str1.reverse!
str2.reverse!

if txt =~ /#{str2}.*#{str2}/
  backward = true
end

if forward == true and backward == true
  puts "both"
elsif forward == true and backward == false
  puts "forward"
elsif forward == false and backward == true
  puts "backward"
else
  puts "fantasy"
end

#!/usr/bin/env ruby

txt = gets.chomp
str1 = gets.chomp
str2 = gets.chomp

forward = backward = false

if txt =~ /#{str1}.*#{str2}/
  forward = true
end

#txt.reverse!
#str1.reverse!
#str2.reverse!

if txt =~ /#{str2}.*#{str1}/
  backward = true
end

if forward == true and backward == true
  puts "both"
elsif forward == true and backward == false
  puts "forward"
elsif forward == false and backward == true
  puts "backward"
else
  puts "fantasy"
end

#$stdin = File.open('in.txt')
map = gets.strip
x = gets.strip
y = gets.strip

last_x = nil
result = "fantasy"
i = 0
j = 0

while i < map.length and j < x.length
  j += 1 if map[i] == x[j]
  i += 1
end

if j == x.length
  j = 0
  while i < map.length and j < y.length
    j += 1 if map[i] == y[j]
    i += 1
  end
  if j == y.length
    result = "forward"
  end
end

i = map.length-1
j = x.length-1

while i >= 0 and j >= 0
  j -= 1 if map[i] == x[j]
  i -= 1
end

if j == -1
  j = y.length-1
  while i >= 0 and j >= 0
    j -= 1 if map[i] == y[j]
    i -= 1
  end
  if j == -1
    if result == "forward"
      result = "both"
    else
      result = "backward"
    end
  end
end

puts result

#$stdin = File.open('in.txt')
map = gets.strip
x = gets.strip
y = gets.strip

result = "fantasy"
i = map.index(x)
if i
  result = "forward" if map.index(y, i+1)
end
x.reverse!
y.reverse!

i = map.rindex(x)
if i
  if map.rindex(y, y.length-(i+1))
    if result == "forward"
      result = "both"
    else
      result = "backward"
    end
  end
end
# i = 0
# j = 0
# find = false
# while i < map.length and !find
#   if map[i] == x[0]
#     j = 0
#     while i < map.length and j < x.length and map[i] == x[j]
#       i += 1
#       j += 1
#     end
#     find = j == x.length
#   else
#     i += 1
#   end
# end
#
# if find
#   find = false
#   while i < map.length and !find
#     if map[i] == y[0]
#       j = 0
#       while i < map.length and j < y.length and map[i] == y[j]
#         i += 1
#         j += 1
#       end
#       find = j == y.length
#     else
#       i += 1
#     end
#   end
#   if find
#     result = "forward"
#   end
# end
#
# i = map.length-1
# find = false
#
# while i >= 0 and !find
#   if map[i] == x[0]
#     j = 0
#     while i >=0 and j < x.length and map[i] == x[j]
#       i -= 1
#       j += 1
#     end
#     find = j == x.length
#   else
#     i -= 1
#   end
# end
#
# if find
#   find = false
#   while i >= 0 and !find
#     if map[i] == y[0]
#       j = 0
#       while i >=0 and j < y.length and map[i] == y[j]
#         i -= 1
#         j += 1
#       end
#       find = j == y.length
#     else
#       i -= 1
#     end
#   end
#   if find
#     if result == "forward"
#       result = "both"
#     else
#       result = "backward"
#     end
#   end
# end

puts result

#$stdin = File.open('in.txt')
map = gets.strip
x = gets.strip
y = gets.strip

result = "fantasy"
i = 0
j = 0
find = false
while i < map.length and !find
  if map[i] == x[0]
    j = 0
    while i < map.length and j < x.length and map[i] == x[j]
      i += 1
      j += 1
    end
    find = j == x.length
  else
    i += 1
  end
end

if find
  find = false
  while i < map.length and !find
    if map[i] == y[0]
      j = 0
      while i < map.length and j < y.length and map[i] == y[j]
        i += 1
        j += 1
      end
      find = j == y.length
    else
      i += 1
    end
  end
  if find
    result = "forward"
  end
end

i = map.length-1
find = false

while i >= 0 and !find
  if map[i] == x[0]
    j = 0
    while i >=0 and j < x.length and map[i] == x[j]
      i -= 1
      j += 1
    end
    find = j == x.length
  else
    i -= 1
  end
end

if find
  find = false
  while i >= 0 and !find
    if map[i] == y[0]
      j = 0
      while i >=0 and j < y.length and map[i] == y[j]
        i -= 1
        j += 1
      end
      find = j == y.length
    else
      i -= 1
    end
  end
  if find
    if result == "forward"
      result = "both"
    else
      result = "backward"
    end
  end
end

puts result

#$stdin = File.open('in.txt')
map = gets.strip
x = gets.strip
y = gets.strip

result = "fantasy"
i = 0
j = 0

while i < map.length and j < x.length
  j += 1 if map[i] == x[j]
  i += 1
end

if j == x.length
  j = 0
  while i < map.length and j < y.length
    j += 1 if map[i] == y[j]
    i += 1
  end
  if j == y.length
    result = "forward"
  end
end

i = map.length-1
j = 0

while i >= 0 and j < x.length
  j += 1 if map[i] == x[j]
  i -= 1
end

if j == x.length
  j = 0
  while i >= 0 and j < y.length
    j += 1 if map[i] == y[j]
    i -= 1
  end
  if j == y.length
    if result == "forward"
      result = "both"
    else
      result = "backward"
    end
  end
end

puts result

flags = gets.chomp!

s1 = gets.chomp!
s2 = gets.chomp!

forward = false
backward = false
fantasy = false

fi1 = flags.index(s1)
bi1 = flags.reverse.index(s1)

if (fi1 != nil)
  fi2 = flags.index(s2, fi1+s1.length)
  if (fi2 != nil && fi1 <= fi2)
    forward = true
  else
    forward = false
  end
else
  fantasy = true
end

if (bi1 != nil)
  bi2 = flags.reverse.index(s2, bi1+s1.length)
  if (bi2 != nil && bi1+s1.length <= bi2)
    backward = true
  else
    backward = false
  end
else
  fantasy = true
end

if fantasy
  puts "fantasy"
else
  if backward && forward
    puts "both"
  else
    if forward
      puts "forward"
    else
      if backward
        puts "backward"
      else
        puts "fantasy"
      end
    end
  end
end


t = gets.chomp.to_i
t.times do
    n = gets.chomp.to_i
    a = gets.chomp.split(" ").map(&:to_i)
    arr = Array.new(n,0)
    max = 0
    n.downto(1) do |i|
        ans = 0
        ii = i.dup
            ans = ii + a[ii-1]
            if ans > n
                arr[ii-1] += (ans - ii)
                max = [arr[i-1],max].max
            else
                arr[ii-1] += (ans + arr[ans-1] - ii)
                max = [arr[i-1],max].max
            end
        #end
    end
    puts max
end

gets.to_i.times {
  n = gets.to_i
  xs = gets.split.map!(&:to_i)
  ys = Array.new(n) { 0 }
  ans = 0
  (0...n).reverse_each { |i|
    ys[i] = xs[i]
    ys[i] += ys[i + xs[i]] if i + xs[i] < n
    ans = ys[i] if ys[i] > ans
  }
  p ans
}

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

  dp = Array.new(n + 1, 0)
  (n - 1).downto(0) do |i|
    dp[i] = a[i]
    dp[i] += dp[i + a[i]] if i + a[i] < n
  end
  # STDERR.puts dp.inspect
  puts dp.max
end

t = gets.to_i
t.times do
  solve
end

#!/usr/bin/env ruby

gets.to_i.times {
    n = gets.to_i
    nums = gets.split.map &:to_i
    max_num = 0
    dp = Array.new(n)
    (n - 1).downto(0).each do |index|
        nk = index + nums[index]
        if nk >= dp.size
            dp[index] = nums[index]
        else
            nk = index + nums[index]
            #puts "(#{index}, #{nk}) => (#{nums[index]}, #{nums[nk]})"
            dp[index] = nums[index] + dp[nk]
        end
    end
    #puts nums.to_s
    #puts dp.to_s
    puts dp.max
}

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map &:to_i
  dp = a
  (0...n - 1).reverse_each do |i|
    dp[i] += dp[i + a[i]] if i + a[i] < n
  end
  puts dp.max
end

require 'prime'
t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  arr = gets.chomp.split(' ').map(&:to_i)
  brr = [0] * (arr.size + 1)
  arr.each_with_index do |el, ind|
    new_ind = [ind + el, arr.size].min
    brr[new_ind] = [brr[new_ind], brr[ind] + el].max
  end
  puts brr.last
end

gets.to_i.times do
  n=gets.to_i
  a=gets.split.map(&:to_i)
  (n-1).downto(0) do |i|
    if i+a[i]<n
      a[i]+=a[i+a[i]]
    end
  end
  puts a.max
end


def solve
  a = Array.new(11) { Array.new(11) { 0 } }
  n = gets.to_i
  n.times do
    s = gets.chomp
    a[s[0].ord - 97][s[1].ord - 97] += 1
    # a[s[1].ord - 97][s[0].ord - 97] += 1 unless s[0] == s[1]
  end

  ans = 0
  (0..10).each do |i|
    (0..10).each do |j|
      (j + 1..10).each do |k|
        ans += a[i][k] * a[i][j]
        ans += a[k][i] * a[j][i]
      end
    end
  end
  puts ans
end

gets.to_i.times do
  solve
end

gets.to_i.times do
  n = gets.to_i
  ss = n.times.map { gets.chomp }
  tally = ss.tally
  count = 0
  tally.each do |k1, v1|
    tally.each do |k2, v2|
      if k1 < k2 && (k1[0] == k2[0] || k1[1] == k2[1])
        count += v1 * v2
      end
    end
  end
  p count
end


n = gets.chomp
arr = Array.new(n.length-1,0)

n.chars.each_cons(2).each_with_index do |a,i|
	# puts "#{a[0]} #{a[1]}"
	if a[0].to_i + a[1].to_i == 9
		arr[i] = 1
	end
end
# puts "#{arr}"
final = []
arr.chunk{|x| x}.each do |r|
	# puts "#{r}"
	l = r[1].length + 1
	if r[0] == 1
		# puts "#{r}"
		if l.odd?
			c = l/2 + 1
		else
			c = 1
		end
		final << c
	end
end
ans = 1
# puts "#{final}"
ans *= final.inject(1,:*) #if final.length > 1

# if n.index("8888888888888888888888888888888888888888888888888888888888888888")
# 	puts "#{final}"
# else
	puts ans
# end

# n = gets.chomp
# arr = Array.new(n.length-1,0)

# i = 1
# while i < n.length
# 	if n[i].to_i + n[i-1].to_i == 9
# 		arr[i] = 1
# 		i += 1
# 	end
# 	i += 1
# end

# puts "#{arr}"
# final = []
# arr.chunk{|x| x}.each do |r|
# 	# puts "#{r}"
# 	l = r[1].length
# 	if r[0] == 1
# 		puts "#{r}"
# 		if l.even?
# 			c = (l/2) + 1
# 		elsif l == 1
# 			c = 1
# 		else
# 			c = l/2
# 		end
# 		final << c
# 	end
# end
# ans = 1
# # puts "#{final}"
# ans *= final.inject(1,:*) if final.length > 1
# puts ans

def run(a)
  cnt = 0
  acm = 1
  a[0...-1].each_with_index do |x,i|
    if x + a[i+1] == 9
      cnt = cnt + 1
    elsif cnt > 0
      acm = acm*((cnt/2)+1) if cnt % 2 == 0
      cnt = 0
    end
  end
  acm = acm*((cnt/2)+1) if cnt > 0 and cnt % 2 == 0
  acm
end

STDIN.read.split("\n").each_with_index do |line,i|
  puts run(line.split(//).map{|x| x.to_i}).to_s
end

n = gets.chomp
arr = Array.new(n.length-1,0)

n.chars.each_cons(2).each_with_index do |a,i|
	# puts "#{a[0]} #{a[1]}"
	if a[0].to_i + a[1].to_i == 9
		arr[i] = 1
	end
end
# puts "#{arr}"
final = []
arr.chunk{|x| x}.each do |r|
	# puts "#{r}"
	l = r[1].length
	if r[0] == 1
		# puts "#{l}"
		if l.even?
			c = (l/2) + 1
		elsif l == 1
			c = 1
		else
			c = l/2
		end
		final << c
	end
end
ans = 1
# puts "#{final}"
ans *= final.inject(1,:*) if final.length > 1
puts ans

n = gets.chomp
arr = Array.new(n.length,0)

n.chars.each_cons(2).each_with_index do |a,i|
	# puts "#{a[0]} #{a[1]}"
	if a[0].to_i + a[1].to_i == 9
		arr[i] = 1
	end
end
# puts "#{arr}"
count = 1
arr.chunk{|x| x}.each do |r|
	# puts "#{r}"
	l = r[1].length
	if r[0] == 1 && l > 1
		# puts "#{l}"
		if l.even?
			count *= (l/2) + 1
		else
			count *= l/2
		end
	end
end
puts count

n = gets.chomp
arr = Array.new(n.length-1,0)

n.chars.each_cons(2).each_with_index do |a,i|
	# puts "#{a[0]} #{a[1]}"
	if a[0].to_i + a[1].to_i == 9
		arr[i] = 1
	end
end
# puts "#{arr}"
final = []
arr.chunk{|x| x}.each do |r|
	# puts "#{r}"
	l = r[1].length + 1
	if r[0] == 1
		# puts "#{r}"
		if l.odd?
			c = l/2 + 1
		else
			c = 1
		end
		final << c
	end
end
ans = 1
# puts "#{final}"
ans *= final.inject(1,:*) if final.length > 1

if n.index("8888888888888888888888888888888888888888888888888888888888888888")
	puts "#{final}"
else
	puts ans
end

# n = gets.chomp
# arr = Array.new(n.length-1,0)

# i = 1
# while i < n.length
# 	if n[i].to_i + n[i-1].to_i == 9
# 		arr[i] = 1
# 		i += 1
# 	end
# 	i += 1
# end

# puts "#{arr}"
# final = []
# arr.chunk{|x| x}.each do |r|
# 	# puts "#{r}"
# 	l = r[1].length
# 	if r[0] == 1
# 		puts "#{r}"
# 		if l.even?
# 			c = (l/2) + 1
# 		elsif l == 1
# 			c = 1
# 		else
# 			c = l/2
# 		end
# 		final << c
# 	end
# end
# ans = 1
# # puts "#{final}"
# ans *= final.inject(1,:*) if final.length > 1
# puts ans

n = gets.chomp
arr = Array.new(n.length-1,0)

n.chars.each_cons(2).each_with_index do |a,i|
	# puts "#{a[0]} #{a[1]}"
	if a[0].to_i + a[1].to_i == 9
		arr[i] = 1
	end
end
# puts "#{arr}"
final = []
arr.chunk{|x| x}.each do |r|
	# puts "#{r}"
	l = r[1].length + 1
	if r[0] == 1
		# puts "#{r}"
		if l.odd?
			c = l/2 + 1
		else
			c = 1
		end
		final << c
	end
end
ans = 1
# puts "#{final}"
ans *= final.inject(1,:*) if final.length > 1
puts ans

# n = gets.chomp
# arr = Array.new(n.length-1,0)

# i = 1
# while i < n.length
# 	if n[i].to_i + n[i-1].to_i == 9
# 		arr[i] = 1
# 		i += 1
# 	end
# 	i += 1
# end

# puts "#{arr}"
# final = []
# arr.chunk{|x| x}.each do |r|
# 	# puts "#{r}"
# 	l = r[1].length
# 	if r[0] == 1
# 		puts "#{r}"
# 		if l.even?
# 			c = (l/2) + 1
# 		elsif l == 1
# 			c = 1
# 		else
# 			c = l/2
# 		end
# 		final << c
# 	end
# end
# ans = 1
# # puts "#{final}"
# ans *= final.inject(1,:*) if final.length > 1
# puts ans

def run(a)
  cnt = 0
  acm = 1
  a[0...-1].each_with_index do |x,i|
    if x + a[i+1] == 9
      cnt = cnt + 1
    elsif cnt > 0
      acm = acm*cnt if cnt % 2 == 0
      cnt = 0
    end
  end
  acm = acm*cnt if cnt > 0 and cnt % 2 == 0
  acm
end

STDIN.read.split("\n").each_with_index do |line,i|
  puts run(line.split(//).map{|x| x.to_i}).to_s
end

def run(a)
  a = a.map{|x| x.to_i}
  cnt = 0
  acm = 1
  a[0...-1].each_with_index do |x,i|
    if x + a[i+1] == 9
      cnt = cnt + 1
    elsif cnt > 0
      acm = acm*cnt if cnt % 2 == 1
      cnt = 0
    end
  end
  acm = acm*cnt if cnt % 2 == 1
  acm
end

STDIN.read.split("\n").each_with_index do |line,i|
  #puts run(line.split(//).map{|x| x.to_i}).to_s
end

puts run("18".split(//)).to_s
puts run("181".split(//)).to_s
puts run("1818".split(//)).to_s
puts run("18181".split(//)).to_s
puts run("181818".split(//)).to_s
puts run("1818181".split(//)).to_s
puts run("18181818".split(//)).to_s
puts run("181818181".split(//)).to_s

def run(a)
  cnt = 0
  acm = 1
  a[0...-1].each_with_index do |x,i|
    if x + a[i+1] == 9
      cnt = cnt + 1
    elsif cnt > 0
      acm = acm*cnt
      cnt = 0
    end
  end
  acm = acm*cnt if cnt > 0
  acm
end

STDIN.read.split("\n").each_with_index do |line,i|
  puts run(line.split(//).map{|x| x.to_i}).to_s
end


t = gets.to_i
t.times do
	n = gets.to_i
	arr = gets.split('').map(&:to_i)
	checkment = n%2
	flag = false
	for i in 1..n
		flag = true if i%2 == checkment && arr[i-1]%2 == checkment
	end

	if checkment == 1
		if flag
			puts 1
		else
			puts 2
		end
	else
		if flag
			puts 2
		else
			puts 1
		end
	end
end

T = gets.to_i

T.times do
  l = gets.to_i
  n = gets.to_i

  if l.odd?
    exist_odd = false

    n.digits.reverse.each_with_index do |x, i|
      next if i.odd?

      exist_odd |= x.odd?
    end

    if exist_odd
      puts 1
    else
      puts 2
    end
  else
    exist_even = false

    n.digits.reverse.each_with_index do |x, i|
      next if i.even?

      exist_even |= x.even?
    end

    if exist_even
      puts 2
    else
      puts 1
    end
  end
end

t = gets.to_i
t.times do
  n = gets.to_i
  d = gets.chomp
  arr = d.split('').map(&:to_i)
  if arr.length == 1
    if arr[0].odd?
      puts 1
    else
      puts 2
    end
  else
    indexes = (1..arr.length).to_a
    r_positions = indexes.select(&:odd?)
    b_positions = indexes.select(&:even?)

    r_positions = r_positions.sort_by { |pos| arr[pos - 1].odd? ? 1 : -1 }
    b_positions = b_positions.sort_by { |pos| arr[pos - 1].even? ? 1 : -1 }

    key = if r_positions.length > b_positions.length
      arr[r_positions.last - 1]
    else
      arr[b_positions.last - 1]
    end
    if key.odd?
      puts 1
    else
      puts 2
    end
  end
end


def double_string(strs, n)
  hash = {}
  strs.each do |i|
    hash[i] = true
  end
  ans = ""
  strs.each do |str|
    j = 0
    len = str.length

    found = false
    while j < len
      x = str[0,j+1]
      y = str[j+1, len]
      if hash.key?(x) && hash.key?(y)
        ans << "1"
        found = true
        break
      end
      j += 1
    end
    if !found
      ans << "0"
    end
  end
  puts ans
  ans
end
t = gets.to_i
inputs = []
(0..t-1).each do
  n = gets.to_i
  arr = []
  (0..n-1).each do |j|
    s = gets.strip
    arr.push(s)
  end
  inputs.push([arr, n])
end

inputs.each do |input|
  double_string(input[0], input[1])
end

require 'set'

t = gets.to_i

t.times do
  n = gets.to_i
  a = Array.new(n) { gets.chomp }
  s = a.to_set
  ans = ""
  a.each do |x|
    flag = false
    (1 ... x.size).each do |l|
      if s.include? x[0, l] and s.include? x[l .. -1]
        ans << "1"
        flag = true
        break
      end
    end
    ans << "0" if not flag
  end
  puts ans
end

class StringLength
  attr_accessor :str, :len

  def initialize(str, len)
    @str = str
    @len = len
  end
end

def double_string(sorted, arr, n)
  ans = ""
  hash = arr.tally
  arr.each do |str|
    check = false
    l = str.length
    sorted.each do |obj|
      if obj.len < l
        sub = str.sub(obj.str, "")
        if obj.str.length == 1 && (obj.str+sub != str || sub+obj.str != str)
          next
        end
        if hash.key?(sub) && str!=sub
          ans << "1"
          check = true
          break
        end
      else
        break
      end
    end
    if !check
      ans << "0"
    end
  end
  puts ans
end
t = gets.to_i
inputs = []
(0..t-1).each do
  n = gets.to_i
  arr = []
  (0..n-1).each do |j|
    s = gets.strip
    arr.push(s)
  end
  inputs.push([arr, n])
end

inputs.each do |input|
  sorted = []
  input[0].each do |str|
    sorted.push(StringLength.new(str, str.length))
  end
  sorted = sorted.sort_by!{|obj| obj.len}
  double_string(sorted, input[0], input[1])
end


n = gets.to_i

s="aabb"
n.times{|i|
    print s[i%4]
}

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

n = gi

x = "aabb" * ((n + 3) / 4)

puts x[0...n]

# your code goes here
n=gets.to_i
if n==1 then
	puts "a"
elsif n==2 then
	puts "aa"
else
	n=n-2
	print "aa"
	["b","b","a","a"].cycle{|e|
		print e
		n-=1
		break if n==0
	}
	print "\n"
end

n=gets.to_i
s="aabb"*((n+3)/4)
puts s[0,n]

n=gets.to_i
m=n/4
r=n%4
s='aabb'*m+'aabb'[0...r]
puts s

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

n = gi

x = "aabc" * ((n + 3) / 4)

puts x[0...n]

n=gets.to_i
m=n/3
r=n%3
s='abc'*m+'abc'[0...r]
puts s


n = gets.to_i
a = gets.chomp.split(" ").map(&:to_i).sort
max = a.max
left = 0
right = (max ** (1/(n-1).to_f)).floor + 2
min_sum = 0
if n < 33
  while right - left > 1
    mid = left + (right - left) / 2
    sum1 = 0
    sum2 = 0
    v = 1
    v2 = 1
    n.times do |i|
      v *= mid if i != 0
      v2 *= (mid+1) if i != 0
      sum1 += (a[i]-v).abs
      sum2 += (a[i]-v2).abs
    end
    if sum1 > sum2
      left = mid
      min_sum = sum2
    else
      right = mid
      min_sum = sum1
    end
  end
else
  n.times do |i|
    min_sum += (a[i]-1).abs
  end
end
puts min_sum

n = gets.to_i
a = gets.split.map(&:to_i).sort!()
mx = 10 ** 18
if n <= 2
    puts a[0] - 1
else
    res = a.sum - n
    (1...10 ** 9).each do |i|
        cur, pow = 0, 1
        (0...n).each do |j|
            cur += (a[j] - pow).abs
            pow *= i
            break if pow > mx
        end
        break if pow > mx or pow / i > res + a[-1]
        res = [res, cur].min
    end
    puts res
end

n = gets.to_i
a = gets.chomp.split(" ").map(&:to_i).sort
max = a.max
left = 0
right = (max ** (1/(n-1).to_f)).floor + 2
min_sum = 0
if n < 32
  while right - left > 1
    mid = left + (right - left) / 2
    sum1 = 0
    sum2 = 0
    v = 1
    v2 = 1
    n.times do |i|
      v *= mid if i != 0
      v2 *= (mid+1) if i != 0
      sum1 += (a[i]-v).abs
      sum2 += (a[i]-v2).abs
    end
    if sum1 > sum2
      left = mid
      min_sum = sum2
    else
      right = mid
      min_sum = sum1
    end
  end
else
  n.times do |i|
    min_sum += (a[i]-1).abs
  end
end
puts min_sum

def pow(x,n)
  if n == 0
    1
  elsif n % 2 == 0
    pow((x+x), n/2)
  else
    x + pow(x, n-1)
  end
end
n = gets.to_i
a = gets.chomp.split(" ").map(&:to_i).sort
left = 0
right = (a.max ** 0.5).floor + 2
min_sum = 1000000000000000
while right - left > 1
  mid = left + (right - left) / 2

  sum = 0
  n.times do |i|
    v = mid.pow(i)
    sum += (a[i]-v).abs
  end

  if sum < min_sum
    min_sum = sum
    left = mid
  else
    right = mid
  end
end
puts min_sum


t = gets.to_i
t.times do
  n, k = gets.split.map(&:to_i)
  nums = gets.split.map(&:to_i)
  nums.map! {|num| k - (num % k)}
  nums.reject! {|num| num == k}

  if nums.count == 0
    puts 0
  else
    nums_t = nums.tally
    max_cnt = nums_t.values.max

    max_key = nums_t.select {|k, v| v == max_cnt}.map(&:first).max
    puts (max_cnt - 1) * k + max_key + 1
  end
end

def run
  n, k = gets.chomp.split(" ").map(&:to_i)
  a = gets.chomp.split(" ").map(&:to_i)
  b = a.group_by{ |e| e % k }.reduce(Hash::new()){|acc, (k, v)| acc[k] = v.size; acc}
  b.delete(0)

  if b.size == 0
    puts 0
    return
  end

  m = b.values.max
  m_key = b.keys.sort.find{|key| b[key] == m}

  c = (m - 1) * k + k - m_key + 1

  puts c
end

def main
  t = gets.chomp.to_i

  t.times do
    run
  end
end

main

gets.to_i.times do
	n, k = gets.split.map(&:to_i)
	a = gets.split.map(&:to_i)
	p a.map { -_1 % k }.tally.map { |val, cnt|
			val > 0 ? val + k * (cnt - 1) + 1 : 0
	  }.max
end


n = gets.to_i
a = gets.split.map &:to_i
m = {}
used = {}
nm = 0
c = 0
ans = []
a.each do |x|
  if x > 0
    if m[x] || used[x]
      puts -1
      exit
    end
    m[x] = true
    nm += 1
  end
  if x < 0
    if not m[-x]
      puts -1
      exit
    end
    m[-x] = false
    used[-x] = true
    nm -= 1
  end
  c += 1
  if nm == 0
    ans << c
    c = 0
    used = {}
  end
end
if nm == 0
  puts ans.size
  puts ans.join(' ')
else
  puts -1
end

d = gets.chomp.to_i
events = gets.split(" ")
cp = []
join = []
out = []
check = false
fix = 0

solution = []
events.map{|w|
w=w.to_i

if w.to_s[0]=="-"
if join[w.to_s.split("-")[1].to_i]
join[w.to_s.split("-")[1].to_i] = false
fix-=1
else
puts "-1"
check = true
exit
end

end

if w.to_s[0]!="-"
if join[w]
puts "-1"
check = true
exit
else
fix+=1
join[w] = true
end
end

cp.push(w)

if fix == 0
if cp.size == cp.uniq.size
solution.push(cp)
cp = []
else
puts "-1"
check = true
exit
end
end

}
if solution.size > 0 and cp.size == 0
puts solution.size
s=[]
solution.map{|w|
s.push(w.size)
}
puts s.join(" ")
check = true
exit
end
if !check then puts "-1" end

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

entered = {}
cnt = 0
len = 0
ans = []
n.times do |i|
  v = a[i]
  len += 1
  if v > 0
    if !entered[v].nil?
      p -1
      exit
    else
      entered[v] = 1
      cnt += 1
    end
  else
    if entered[-v].nil? || entered[-v] != 1
      p -1
      exit
    else
      entered[-v] = -1
      cnt -= 1
      if cnt == 0
        ans << len
        len = 0
        entered = {}
      end
    end
  end
end
if cnt > 0
  p -1
else
  p ans.length
  puts ans.join(" ")
end

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

entered = {}
cnt = 0
len = 0
ans = []
n.times do |i|
  v = a[i]
  len += 1
  if v > 0
    if !entered[v].nil?
      p -1
      exit
    else
      entered[v] = 1
      cnt += 1
    end
  else
    if entered[-v].nil? || entered[-v] != 1
      p -1
      exit
    else
      entered[-v] = -1
      cnt -= 1
      if cnt == 0
        ans << len
        len = 0
        entered = {}
      end
    end
  end
end
p ans.length
puts ans.join(" ")

d = gets.chomp.to_i
events = gets.split(" ").map{|x|x.to_i}
cp = []
join = []
out = []

solution = []
events.size.times{|w|
if events[w].to_s[0]=="-"
if join.include?(events[w].to_s.split("-")[1].to_i)
join.delete(events[w].to_s.split("-")[1].to_i)
else
puts "-1"
break
end
end

if events[w].to_s[0]!="-"
if join.include?(events[w])
puts "-1"
break
else
join.push(events[w])
end
end

cp.push(events[w])

if join.size == 0
if cp.size == cp.uniq.size
solution.push(cp)
cp = []
else
puts "-1"
break
end
end

}
if solution.size >  0
puts solution.size
s=[]
solution.size.times{|w|
s.push(solution[w].size)
}
puts s.join(" ")
end

d = gets.chomp.to_i
events = gets.split(" ").map{|x|x.to_s}
cp = []
join = []
out = []

solution = []
events.map{|w|
if w[0]=="-"
if join.include?(w.split("-")[1])
join.delete(w.split("-")[1])
else
puts "-1"
break
end
end

if w[0]!="-"
if join.include?(w)
puts "-1"
break
else
join.push(w)
end
end

cp.push(w)

if join.size == 0
if cp.size == cp.uniq.size
solution.push(cp)
cp = []
else
puts "-1"
break
end
end

}
if solution.size > 0 and cp.size == 0
puts solution.size
s=[]
solution.size.times{|w|
s.push(solution[w].size)
}
puts s.join(" ")
else
puts "-1"
end

d = gets.chomp.to_i
events = gets.split(" ").map{|x|x.to_i}
cp = []
join = []
out = []
check = false

solution = []
events.size.times{|w|
if events[w].to_s[0]=="-"
if join.include?(events[w].to_s.split("-")[1].to_i)
join.delete(events[w].to_s.split("-")[1].to_i)
else
puts "-1"
check = true
break
end
end

if events[w].to_s[0]!="-"
if join.include?(events[w])
puts "-1"
check = true
break
else
join.push(events[w])
end
end

cp.push(events[w])

if join.size == 0
if cp.size == cp.uniq.size
solution.push(cp)
cp = []
else
puts "-1"
check = true
break
end
end

}
if solution.size >  0
puts solution.size
s=[]
solution.size.times{|w|
s.push(solution[w].size)
}
puts s.join(" ")
check = true
end
if !check then puts "-1" end

n = gets.to_i
a = gets.split.map &:to_i
m = {}
used = {}
nm = 0
c = 0
ans = []
a.each do |x|
  if x > 0
    if m[x] || used[x]
      puts -1
      exit
    end
    m[x] = true
    nm += 1
  end
  if x < 0
    if not m[-x]
      puts -1
      exit
    end
    m[-x] = false
    used[-x] = true
    nm -= 1
  end
  c += 1
  if nm == 0
    ans << c
    c = 0
    used = {}
  end
end
puts ans.size
puts ans.join(' ')


t = readline.chomp;
ss = t.gsub("a", "");
k = ss.length;
if k % 2 == 0 && ss[0 ... k/2] == t[t.length - k/2 .. -1]
  puts t[0 ... t.length - k/2];
else
  puts ":("
end

s = gets.chomp
t = s.delete("a")
n = t.length
if n.even? && t[0,n/2] == t[n/2,n/2] && !s[s.length-n/2,n/2].include?("a")
  puts s[0,s.length-n/2]
else
  puts ":("
end


n,b = gets.split(" ").map(&:to_i)
arr = gets.split(" ").map(&:to_i)
s = 0
diff = []
(0..n-2).each do |i|
	a = arr[i]
	max = arr[(i+1)..-1].max
	if a <= b
		stocks = b/a
		left = b % a
		sell = stocks * max
		diff << sell + left
	end
end
diff << b
puts diff.max

n,b = gets.chomp.split(/ /).map!{|x| x.to_i}
a = gets.chomp.split(/ /).map!{|x| x.to_i}

ar = Array.new
for i in 1..n-1
	if a[i] > a[i-1]
		ar.push( [ a[i-1], a[i] ] )
	end
	for j in 0..ar.length-1
		ar[j][1] = a[i] if ar[j][1] < a[i]
	end
end

ar.sort!{|x,y| (b / y[0]) * (y[1]-y[0]) <=>  (b / x[0]) * (x[1]-x[0]) }

if ar.length > 0
	b += (b / ar[0][0]) * (ar[0][1]-ar[0][0])
end
puts b

n, b = gets.chomp.split.map(&:to_i)
a = gets.chomp.split.map(&:to_i)
mx = b
(1...a.length).each do |x|
	(0...x).each do |y|
		r = b % a[y]
		mx = [mx, r + (b / a[y]) * a[x]].max
	end
end
puts mx

n, b = gets.split.map { |v| v.to_i }
a = gets.split.map { |v| v.to_i }

best = b

n.times do |day|
  min, max = a[0, day + 1].min, a[day .. -1].max
  profit = max * (b / min) + b % min
  best = profit if profit > best
end

puts best


gets.to_i.times do
  n, k = gets.split.map(&:to_i)
  a = gets.split.map(&:to_i)
  s = []
  (0...n).each do |j|
    s << j + 1 if a[j] % 2 != 0
  end
  sz = s.size
  if sz >= k and sz % 2 == k % 2
    puts "YES"
    print s[0...k-1].join(' '), ' ', n
    puts
  else
    puts "NO"
  end
end

MOD=10**9+7
cnt=0; sum=0; prev=nil; can=true; h=Hash.new(0)
def gs() gets.chomp end
def gi() gets.to_i end
def gsmi() gets.chomp.split.map(&:to_i) end

def desc(ar) ar.sort!{|x,y|y<=>x} end
def min(a,b) a<=b ? a : b end
def max(a,b) a>=b ? a : b end
def sum(ar) ar.inject(:+) end
#def bs(ar,eq,n) en=(eq==1 ? :>= : :>); ar.bsearch_index{|x|x.send(en,n)} end

def puts_yesno(can) puts(can ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def debug(k,v) puts "#{k}:#{v}" end
########### ( ˘ω˘ )ｽﾔｧ… ###########
q = gi
ans = []
q.times do
  n, k = gsmi
  a = gsmi
  odd_c=0
  n.times do |i|
    odd_c+=1 if a[i]%2==1
  end
  str = ''
  if odd_c<k || (odd_c-k)%2 == 1
    ans << "NO"
    next
  else
    str << "YES\n"
  end

  ar = []
  j = -1
  (k-1).times do
    while true do
      j+=1
      if a[j]%2==1
        ar<<j+1
        break
      end
    end
  end
  ar<<n
  ans<< str+ar.join(" ")
end
puts ans


n, d = gets.strip.split.map(&:to_i)
cons = 0
ans = 0
d.times do
    day = gets.strip
    if day.include? '0'
        cons += 1
    else
        cons = 0
    end
    ans = [ans, cons].max
end
puts ans

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

ans = 0
days = 0

d.times do
    temp = gets.chomp
    k = 0
    for i in 0..temp.size do
        k=1 if temp[i] == '0'
    end

    days = 0 if k==0
    days+=1 if k==1

    ans = days if ans < days
end

ans-=1 if ans > d

print ans

n, m = gets.chomp.split.map(&:to_i)
arr = [].tap do |a|
  m.times { a << (gets.chomp.chars.any? { |b| b != '1' }) }
end

if arr.all? { |a| a != true }
  puts 0
else
  puts arr.chunk { |a| a }.select { |a, _| a }.map { |_, a| a.length }.max
end

gets
p $<.read.lines.chunk{|s| s[?0]}.map{|_, a| a.size}.max || 0

size , n = gets.split(" ").map(&:to_i)
won = false
  max_count = -999
steak  =  0
n.times do

  values = gets

  if values.count("0")>=1

    steak+=1

  else

    won =false
    steak = 0
  end
    if max_count<steak
      max_count = steak
    end
end

puts max_count

a=gets.chomp.split(" ").map{|i| i.to_i}
ma=0
t=0
temp=""
a[1].times do
temp=gets.chomp.split("")
if(temp.count('1')==a[0])

if(t>ma)
ma=t
end
t=0
else
t+=1
end
end
if (t>ma)
ma=t
end
puts ma.inspect

n,d = gets.split.map{|a| Integer(a)}
as = (1..d).map{|_| gets.chomp}
 .slice_before{|x| x=="1"*n}
 .to_a
 .collect
 .with_index{|x,i| if i!=0 then x.drop(1) else x end}

as[0].delete("1"*n)
puts as.map{|a| a.length}.max

n, d = gets.split.map(&:to_i)
ans = 0
con = 0
d.times do
  if gets.chomp.chars.include?('0')
    con += 1
  else
    con = 0
  end
  ans = [con, ans].max
end
puts ans

n,m=gets.split.map{|e| e.to_i}
ans=0
c=0
m.times{
	s=gets.chomp
	if s.index("0") then
		c=c+1
	else
		c=0
	end
	ans=[ans,c].max
}
puts ans

n, d = gets.split.map(&:to_i)
max = 0
current_streak = 0
d.times do |di|
	s = gets.chomp
	ones = s.count('1')
	zeros = s.count('0')
	# puts ones
	# puts zeros

	if ones != n
		current_streak += 1
	else
		current_streak = 0
	end

	if max < current_streak
		max = current_streak
	end
end

puts max

c=0;maxc=0;gets
while s=gets do
  if s.include?"0"
      c+=1
      maxc=c if c>maxc
  else
      c=0
  end
end
puts maxc

n, d = gets.chomp.split.map(&:to_i)
cnt = 0
ans = 0
d.times do
  str = gets.chomp
  if str == '1' * n
    ans = [ans, cnt].max
    cnt = 0
  else
    cnt += 1
  end
  ans = [ans, cnt].max
end

puts ans

nd = gets.chomp.split
d = nd[1].to_i

a = []
for i in (0..d-1)
	x = gets.chomp
	a[i] = x.split("")
end
count = 0
arr = []
for i in (0..d-1)
	if a[i].include?("0")
		count += 1
		arr << count
	else
		count = 0
		arr << count
	end
end

print arr.max

gets
p $<.chunk{|s| s.include? '0'}.select(&:first).map(&:last).map(&:size).max || 0

_, d = gets.split.map(&:to_i)
p d.times.map{gets}.chunk{|s| s[?0]}.map{|_, a| a.size}.max || 0

n, d = gets.split.map(&:to_i)
ans = 0
cur = 0
d.times do |i|
  cur = gets.chomp.include?('0') ? cur + 1 : 0
  ans = [ans, cur].max
end
puts ans

n, d = gets.split.map(&:to_i)
arr = []
cnt = 0
for i in 0...d
  opp = gets.chomp
  if opp =~ /[0]/
    cnt += 1
  else
    arr << cnt
    cnt = 0
  end
end
arr << cnt

puts arr.max

n, d = gets.split.map &:to_i
ans, c = 0, 0
d.times do
  if gets.strip == '1'*n
    c = 0
  else
    c += 1
  end
  ans = [ans, c].max
end
puts ans

n, d = gets.chomp.split(' ').map(&:to_i)
days = []

d.times do
	days << gets.chomp.split('').map(&:to_i)
end

con = []
num = 0

days.each do |day|
	if day.index(0) != nil
		num += 1
	else
		con << num
		num = 0
	end
end

con << num

puts con.max

#!/usr/bin/ruby
gets
a=$<.map{|e|e.count('0')==0}
r=c=0
a.each{|e|
	if e
		c=0
	else
		r=[r,c+=1].max
	end
}
p r

#!/usr/bin/ruby
gets
a=$<.map{|e|e.count('0')==0}
r=c=0
a.each{|e|
	if e
		r=max[r,c+=1]
	else
		c=0
	end
}
p r

n, m = gets.chomp.split.map(&:to_i)
arr = [].tap do |a|
  m.times { a << (gets.chomp.chars.any? { |b| b != '1' }) }
end

puts arr.chunk { |a| a }.select { |a, _| a }.map { |_, a| a.length }.max

a=gets.chomp.split(" ").map{|i| i.to_i}
ma=0
t=0
temp=""
a[1].times do
temp=gets.chomp.split("")
if(temp.count('1')==a[0])

if(t>ma)
ma=t
end
t=0
else
t+=1
end
end
puts ma.inspect

n,d = gets.split.map{|a| Integer(a)}
puts (1..d).map{|_| gets.chomp}
 .slice_before{|x| x=="1"*n}
 .to_a
 .collect
 .with_index{|x,i| if i!=0 then x.drop(1).length else x.length end}
 .max

gets
p $<.map{|s| s.chomp.chars.min}.join.split('1').map(&:size).max

gets
puts $<.chunk{|s| s.include? '0'}.select(&:first).map(&:last).map(&:size).max

gets
p $<.chunk{|s| s.include? '0'}.select(&:first).map(&:last).map(&:size).max rescue 0

n, d = gets.split.map(&:to_i)
arr = []
cnt = 0
for i in 0...d
  opp = gets.chomp
  if opp =~ /[0]/
    cnt += 1
  else
    arr << cnt
    cnt = 0
  end
end

puts (arr.empty? ? cnt : arr.max)


gets.to_i.times do
	a, b = gets.split.map &:to_i
	x = (a + b - 1) / b * b
	puts x - a
end

t = gets.chomp.to_i
t.times do
  a, b =  gets.split.map(&:to_i)
  res = 0
  if a%b ==0
    puts 0
  else
    puts b-a%b
  end
end

file = File.exist?('in.in') ? File.new('in.in', 'r') : STDIN

t = file.gets.to_i
i = 0

while i < t
  a, b = file.gets.split.map(&:to_i)

  if (a % b) == 0
    puts 0
  else
    factor = (a / b) + 1
    goal = factor * b
    moves = goal - a
    puts moves
  end
  i += 1
end

a = gets.to_i
while a > 0
 x, y = gets.split
 x = x.to_i
 y = y.to_i
 puts (y-(x%y))%y
 a = a-1
end

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

arr.each do |a|
    if a[0] % a[1] == 0
        puts 0
    else
        puts a[1] - a[0] % a[1]
    end
end

# Divisibility Problem
gets.to_i.times do
  mult = gets.rstrip.split

  a = mult[0].to_i
  b = mult[1].to_i
  if a%b == 0
    puts 0
  else
    puts b - a%b
  end
end

# coding: utf-8

t = gets.to_i
t.times {
    a, b = gets.split.map(&:to_i)
    q, r = a/b, a%b

    if r == 0
        puts "0"
    else
        puts (q+1)*b - a
    end
}

t = gets.to_i
t.times do
  a, b = gets.split.map(&:to_i)
  r = a % b
  puts (r == 0) ? 0 : (b - r)
end

n = gets.to_i

while n!=0
    split = gets.split
    a = split[0].to_i
    b = split[1].to_i
    puts a%b == 0 ? 0 : b-a%b
    n-=1
end

for run in 0...gets.to_i
	nums = gets.split(" ").map { |i| i.to_i }
	(nums[0] % nums[1] != 0) ? (puts nums[1] - (nums[0] % nums[1])) : (puts "0")
end

gets.to_i.times do
  a, b = gets.split.map &:to_i
  puts (b - a%b)%b
end

n = gets.to_i

1.upto(n) do
  a, b = gets.split(' ').map(&:to_i)
  puts a % b == 0 ? 0 : b - a%b
end

# frozen_string_literal: true

test = gets.to_i
test.times do
  a, b = gets.chomp.split.map(&:to_i)
  if (a % b).zero?
    puts 0
  else
    puts (a / b + 1) * b - a
  end
end

t = gets.to_i
(1..t).each do
  arr = gets.split(' ')
  a = arr[0].to_i
  b = arr[1].to_i
  puts (b-(a.modulo(b))).modulo(b)

end

n = gets.to_i

while n!=0
    split = gets.split
    a = split[0].to_i
    b = split[1].to_i
    k = 0
    while a%b != 0
        a+=1
        k+=1
    end
    puts k
    n-=1
    puts 'n= ' + n.to_s
end


STR = ('WB' * 51).freeze

1.upto(gets.to_i) do
  n, m = gets.split(' ').map(&:to_i)

  arr = 1.upto(n).map { |i| STR[i%2, m] }

  if arr.last.chars.last == 'W'
    arr.last[arr.last.length-1] = 'B'
  elsif arr.last.chars.first == 'W'
    arr.last[0] = 'B'
  end

  puts arr.join("\n")
end

# https://codeforces.com/problemset/problem/1333/A

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

 puts "B" * m
 (n-1).times do
  puts "B" * (m-1) + "W"
 end
end

1.upto(gets.chomp.to_i) do |t|
  n,m = gets.chomp.split.map(&:to_i)
  if n > 1 && m > 1
    puts 'W' + 'B' *(m-1)
    (n-1).times { puts 'B'*m }
  elsif n == 1 && m > 2
    puts 'BWB' + 'B'*(m-3)
  elsif m == 1 && n > 2
    puts %w(B W B) + ['B']*(n-3)
  end
end

t = gets.to_i
t.times do
  n, m = gets.split.map(&:to_i)
  for i in 0...n do
    s = ""
    for j in 0...m do
      if (n * m) % 2 == 0 && i == 0 && j == 1
        s += "B"
      else
        s += ((i + j) % 2 == 0) ? "B" : "W"
      end
    end
    puts s
  end
end

STR = ('WB' * 51).freeze

1.upto(gets.to_i) do
  n, m = gets.split(' ').map(&:to_i)

  1.upto(n) do |i|
    s = STR[i%2, m]

    s[s.size - 1] = 'B' if i==n && (n*m).even?

    puts s
  end
end


for i in gets.chomp.to_i.times do
        d = gets.chomp.to_i
        delta = d*d - 4*d
        if delta < 0
                puts 'N'
        else
                puts "Y " + ((d + Math.sqrt(delta))/2.0).to_s + " " + ((d - Math.sqrt(delta))/2.0).to_s
end
end

=begin
n = gets.chomp.to_i

arr = gets.split(" ")
arr = arr.map { |element|  element.to_i }
sum = arr.inject(0){|sum,x| sum + x }

=end

n = gets.chomp.to_i
arr = []

n.times do |x|
	arr<<gets.chomp.to_i
end

arr.each do |element|
	d = element
	x = d*d - 4*d
	if x >= 0
		b  = (d + Math.sqrt(x))/2
		a = d/b
		a = 0.0 if b == 0
		puts "Y "+a.to_s+" "+b.to_s
	else
		puts "N"
	end
end

=begin
n = gets.chomp.to_i

arr = gets.split(" ")
arr = arr.map { |element|  element.to_i }
sum = arr.inject(0){|sum,x| sum + x }

=end

n = gets.chomp.to_i
arr = []

n.times do |x|
	arr<<gets.chomp.to_i
end

arr.each do |element|
	d = element
	x = d*d - 4*d
	if x >= 0
		b  = (d + Math.sqrt(x))/2
		a = d/b
		a = 0.0 if b == 0
		p "Y "+a.to_s+" "+b.to_s
	else
		p "N"
	end
end

=begin
n = gets.chomp.to_i

arr = gets.split(" ")
arr = arr.map { |element|  element.to_i }
sum = arr.inject(0){|sum,x| sum + x }

=end

n = gets.chomp.to_i
arr = []

n.times do |x|
	arr<<gets.chomp.to_i
end

arr.each do |element|
	d = element
	x = d*d - 4*d
	if x >= 0
		b  = (d + Math.sqrt(x))/2
		a = d/b
		a = 0.0 if b == 0
		puts "Y "+a.to_s+" "+b.to_s
	else
		p "N"
	end
end


class Solver
	def main
		n = gets.to_i
		h = gets.split.map { |x| x.to_i }
		pre_max = Array.new(n + 2, 0)
		suf_min = Array.new(n + 2, 1e9.to_i)
		1.upto(n) do |i|
			pre_max[i] = [pre_max[i - 1], h[i - 1]].max
		end
		n.downto(1) do |i|
			suf_min[i] = [suf_min[i + 1], h[i - 1]].min
		end
		gap = (1...n).count { |i| pre_max[i] <= suf_min[i + 1] }
		puts gap + 1
	end
end

Solver.new.main

n = gets.chomp.to_i
hs = gets.chomp.split.map(&:to_i)
lmaxs = Array.new(n)
rmins = Array.new(n)

lmaxs[0] = hs[0]
rmins[-1] = hs[-1]
for i in 1...n
  ri = n - i - 1
  lmaxs[i] = [lmaxs[i - 1], hs[i]].max
  rmins[ri] = [rmins[ri + 1], hs[ri]].min
end

cnt = 1
for i in 0...n - 1
  f = true
  f &&= lmaxs[i] <= rmins[i + 1]
  cnt += 1 if f
end
puts cnt

n = gets.chomp.to_i
h = gets.split(" ").map{|i| i.to_i}
h = [0]+h
hmax = [0]*(n+1)
hmin = [0]*(n+1)
hmax[1] = h[1]
hmin[n] = h[n]
for i in 2..n
	hmax[i] = [hmax[i-1], h[i]].max
end
for i in (1..(n-1)).to_a.reverse
	hmin[i] = [hmin[i+1], h[i]].min
end
s = 1
for i in 1...n
	if hmax[i] <= hmin[i+1]
		s +=1
	end
end
puts s

n = gets.chomp.to_i
hs = gets.chomp.split.map(&:to_i)
lmins = Array.new(n)
lmaxs = Array.new(n)
rmins = Array.new(n)
rmaxs = Array.new(n)

lmins[0] = hs[0]
lmaxs[0] = hs[0]
rmins[-1] = hs[-1]
rmaxs[-1] = hs[-1]
for i in 1...n
  ri = n - i - 1
  lmins[i] = [lmins[i - 1], hs[i]].min
  lmaxs[i] = [lmaxs[i - 1], hs[i]].max
  rmins[ri] = [rmins[ri + 1], hs[ri]].min
  rmaxs[ri] = [rmaxs[ri + 1], hs[ri]].max
end

cnt = 1
for i in 0...n - 1
  if lmins[i] <= rmins[i + 1] && rmaxs[i] <= rmaxs[i + 1]
     cnt += 1
  end
end
puts cnt

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

is = Hash.new(-1)
hs.each.with_index do |h, i|
  is[h] = [is[h], i].max
end

cnt = 0
idx = -1
hs.sort.uniq.each do |h|
  if idx < is[h]
    cnt += 1
    idx = is[h]
  end
end

puts cnt


gets.to_i.times {
    a, b=gets.split.map(&:to_i).minmax
    puts [a+a, b].max**2
}

t = gets.to_i
t.times do
	a,b = gets.split.map(&:to_i)
	puts [[a,b].max, [a,b].min*2].max ** 2
end

gets.strip.to_i.times do |t|
  a, b = gets.strip.split(' ').map(&:to_i)
  puts [[2 * a, b].max ** 2, [2 * b, a].max ** 2].min
end

t = gets.chomp.to_i
t.times do |testcase|
  (a,b) = gets.split.map(&:to_i)
  puts [[2*a , b].max , [2*b , a].max].min ** 2
end

n = gets.to_i

1.upto n do
  a, b = gets.split.map(&:to_i)
  if a == b
    puts ((a * 2) ** 2)
  else
    if [a,b].max > ([a,b].min * 2)
      puts ([a,b].max ** 2)
    else
      puts (([a,b].min * 2) ** 2)
    end
  end
end

gets.to_i.times {
  a, b = gets.split.map { |v|
    v.to_i
  }
  if a == b
    puts (a * 2) ** 2
  else
    if a > b
      a, b = b, a
    end
    a2 = a * 2
    if a2 < b
      puts b * b
    else
      puts a2 * a2
    end
  end
}

i = gets.chomp.to_i

def minimalsquare(a, b)
  if a < b
    minimal = Math.sqrt((a * 2) ** 2).ceil
    minimal2 = Math.sqrt((a * b) * 2).ceil
    if (minimal * minimal) >= (minimal2 * minimal2)
      return minimal * minimal
    else
      if minimal2 >= b
        return minimal2 * minimal2
      else
        return b ** 2
      end
    end
  else
    minimal = Math.sqrt((b * 2) ** 2).ceil
    minimal2 = Math.sqrt((a * b) * 2).ceil
    if (minimal * minimal) >= (minimal2 * minimal2)
      return minimal * minimal
    else
      if minimal2 >= a
        return minimal2 * minimal2
      else
        return a ** 2
      end
    end
  end
end

while (i > 0)
  a, b = gets.split.map(&:to_i)

  puts minimalsquare(a, b)

  i -= 1
end

t = gets.to_i
t.times do
  a, b = gets.split.map(&:to_i).sort
  if a * 2 >= b
    puts (a * 2) ** 2
  else
    puts b ** 2
  end
end

gets.to_i.times do
    r = gets.split(' ').map(&:to_i)
    puts [2 * r.min, r.max].max ** 2
end

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

  puts [2*[a, b].min, [a, b].max].max ** 2
end

gets.to_i.times do
	a, b = gets.split.map(&:to_i).sort
	puts [a * 2, b].max**2
end

t = gets.chomp.to_i
t.times do |testcase|
  (a,b) = gets.split.map(&:to_i)
  puts [2*a , 2*b].min ** 2
end

n = gets.to_i

1.upto n do
  a, b = gets.split.map(&:to_i)
  if a == 1 and b == 1
    puts 4
  elsif a == 1 or b == 1
    puts ([a,b].max) ** 2
  else
    puts ([a,b].min * 2) ** 2
  end
end

i = gets.chomp.to_i

def minimalsquare(a, b)
  if a < b
    minimal = Math.sqrt((a * 2) ** 2).ceil
    if (minimal * minimal) >= ((a * b) * 2)
      return minimal * minimal
    else
      minimal = Math.sqrt((a * b) * 2).ceil
      return minimal * minimal
    end
  else
    minimal = Math.sqrt((b * 2) ** 2).ceil
    if (minimal * minimal) >= ((a * b) * 2)
      return minimal * minimal
    else
      minimal = Math.sqrt((a * b) * 2).ceil
      return minimal * minimal
    end
  end
end

while (i > 0)
  a, b = gets.split.map(&:to_i)

  puts minimalsquare(a, b)

  i -= 1
end

gets.to_i.times do
    r = gets.to_s.split(' ').map(&:to_i)
    l = r.max
    b = r.min
    if l == b || b*2 >= l
        puts b*b*4
    else
        puts ((l/b.to_f).ceil)**2
    end
end


a = gets.strip
# a = "00000000000000012000000000000001200000000000000120000000000001"
if a.length > 20
    rows = 1
    while a.length.to_f/rows > 20 do
        rows +=1
    end
    if a.length % rows == 0
        print "#{rows} #{a.length/rows}\n"
        a.split("").each_slice(a.length/rows).to_a.each do |x|
            print "#{x.join}\n"
        end
    else
        count_of_stars = 0
        while (a.length + count_of_stars) % rows != 0 do
            count_of_stars += 1
        end
        symbols_in_row = (a.length + count_of_stars)/rows
        print "#{rows} #{symbols_in_row}\n"
        row_num = 1
        n = count_of_stars
        a.split("").each_with_index do |x,i|
            if count_of_stars > 0
                # p "kek: #{row_num*(symbols_in_row-1)}"
                if i == row_num*(symbols_in_row-1)
                    row_num+=1
                    count_of_stars-=1
                    print "*\n"
                end
            else
                if i == row_num*symbols_in_row-n
                    row_num+=1
                    print "\n"
                end
            end
            print x
        end
    end
else
    print "1 #{a.length}\n"
    print a
end

text = gets.chomp
len = text.length

reqa = 0
reqb = 0

done = false

(1..5).each do |a|
  (1..20).each do |b|
    tot = a*b
    if tot<len
      next
    else
      reqa = a
      reqb = b
      done = true
      break
    end
  end
  break if done
end

delta = reqa*reqb - len

astperrow = delta/reqa
rowast = []
reqa.times {rowast.push astperrow}

(0..reqa-1).each do |i|
  if rowast.inject(:+)<delta
    rowast[i] += 1
  end
end

currchar = 0
printed = 0

puts "#{reqa} #{reqb}"
(0..reqa-1).each do |row|
  while printed<reqb
    if(printed<reqb-rowast[row])
      print text[currchar]
      currchar+=1
      printed += 1
    else
      print '*'
      printed += 1
    end
  end
  puts
  printed = 0
end