Molly Hooper has n different kinds of chemicals arranged in a line. Each of the chemicals has an affection value, The i-th of them has affection value ai.Molly wants Sherlock to fall in love with her. She intends to do this by mixing a contiguous segment of chemicals together to make a love potion with total affection value as a non-negative integer power of k. Total affection value of a continuous segment of chemicals is the sum of affection values of each chemical in that segment.Help her to do so in finding the total number of such segments.

The first line of input contains two integers, n and k, the number of chemicals and the number, such that the total affection value is a non-negative power of this number k. (1 ≤ n ≤ 105, 1 ≤ |k| ≤ 10). Next line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — affection values of chemicals.

Output a single integer — the number of valid segments.

NoteDo keep in mind that k0 = 1.In the first sample, Molly can get following different affection values:  2: segments [1, 1], [2, 2], [3, 3], [4, 4]; 4: segments [1, 2], [2, 3], [3, 4]; 6: segments [1, 3], [2, 4]; 8: segments [1, 4]. Out of these, 2, 4 and 8 are powers of k = 2. Therefore, the answer is 8.In the second sample, Molly can choose segments [1, 2], [3, 3], [3, 4].

n, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
as = [0]
n.times.each{|i| as[i + 1] = a[i] + as[i]}

ks = []
if k.abs == 1
  ks << 1
  ks << -1 if k == -1
else
  l = as.max - as.min
  mx = 1
  while mx.abs <= l
    ks << mx
    mx *= k
  end
end

ans = 0
shows = Hash.new(0)
as.each do |x|
  shows[x] += 1
  ks.each do |kk|
    ans += shows[x - kk]
  end
end

p ans

n, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
as = [0]
n.times.each{|i| as[i + 1] = a[i] + as[i]}

ans = 0
kk = 1
if k == 1
  ks = [1]
elsif k == -1
  ks = [-1, 1]
else
  l = as.max - as.min
  ks = (Math.log(l.abs, k.abs).to_i + 1).times.map{|i| k ** i}
end
shows = Hash.new(0)
as.each do |x|
  shows[x] += 1
  ks.each do |kk|
    ans += shows[x - kk]
  end
end

p ans

n, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
as = [0]
n.times.each{|i| as[i + 1] = a[i] + as[i]}

ans = 0
kk = 1
if k.abs == 1
  ks = [0, k]
else
  l = as.max - as.min
  ks = (Math.log(l.abs, k.abs).to_i + 1).times.map{|i| k ** i}
end
shows = Hash.new(0)
as.each do |x|
  shows[x] += 1
  ks.each do |kk|
    ans += shows[x - kk]
  end
end

p ans


Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places.The robber girl was angry at first, but then she decided to arrange the animals herself. She repeatedly names numbers l and r such that r - l + 1 is even. After that animals that occupy positions between l and r inclusively are rearranged as follows: the animal at position l swaps places with the animal at position l + 1, the animal l + 2 swaps with the animal l + 3, ..., finally, the animal at position r - 1 swaps with the animal r.Help the robber girl to arrange the animals in the order of non-decreasing height. You should name at most 20 000 segments, since otherwise the robber girl will become bored and will start scaring the animals again.

The first line contains a single integer n (1 ≤ n ≤ 100) — number of animals in the robber girl's zoo. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the height of the animal occupying the i-th place.

Print the sequence of operations that will rearrange the animals by non-decreasing height. The output should contain several lines, i-th of the lines should contain two space-separated integers li and ri (1 ≤ li < ri ≤ n) — descriptions of segments the robber girl should name. The segments should be described in the order the operations are performed. The number of operations should not exceed 20 000. If the animals are arranged correctly from the start, you are allowed to output nothing.

NoteNote that you don't have to minimize the number of operations. Any solution that performs at most 20 000 operations is allowed.

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

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

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


Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each individual letter all its positions in the string are written out in the increasing order. This results in 26 lists of numbers; some of them can be empty. A string is considered lucky if and only if in each list the absolute difference of any two adjacent numbers is a lucky number. For example, let's consider string "zbcdzefdzc". The lists of positions of equal letters are: b: 2 c: 3, 10 d: 4, 8 e: 6 f: 7 z: 1, 5, 9 Lists of positions of letters a, g, h, ..., y are empty.This string is lucky as all differences are lucky numbers. For letters z: 5 - 1 = 4, 9 - 5 = 4, for letters c: 10 - 3 = 7, for letters d: 8 - 4 = 4. Note that if some letter occurs only once in a string, it doesn't influence the string's luckiness after building the lists of positions of equal letters. The string where all the letters are distinct is considered lucky.Find the lexicographically minimal lucky string whose length equals n.

The single line contains a positive integer n (1 ≤ n ≤ 105) — the length of the sought string.

Print on the single line the lexicographically minimal lucky string whose length equals n.

NoteThe lexical comparison of strings is performed by the < operator in modern programming languages. String a is lexicographically less than string b if exists such i (1 ≤ i ≤ n), that ai < bi, and for any j (1 ≤ j < i) aj = bj.

#!/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.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

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


As you very well know, the whole Universe traditionally uses three-dimensional Cartesian system of coordinates. In this system each point corresponds to three real coordinates (x, y, z). In this coordinate system, the distance between the center of the Universe and the point is calculated by the following formula: . Mushroom scientists that work for the Great Mushroom King think that the Universe isn't exactly right and the distance from the center of the Universe to a point equals xa·yb·zc.To test the metric of mushroom scientists, the usual scientists offered them a task: find such x, y, z (0 ≤ x, y, z; x + y + z ≤ S), that the distance between the center of the Universe and the point (x, y, z) is maximum possible in the metric of mushroom scientists. The mushroom scientists aren't good at maths, so they commissioned you to do the task.Note that in this problem, it is considered that 00 = 1.

The first line contains a single integer S (1 ≤ S ≤ 103) — the maximum sum of coordinates of the sought point. The second line contains three space-separated integers a, b, c (0 ≤ a, b, c ≤ 103) — the numbers that describe the metric of mushroom scientists.

Print three real numbers — the coordinates of the point that reaches maximum value in the metrics of mushroom scientists. If there are multiple answers, print any of them that meets the limitations. A natural logarithm of distance from the center of the Universe to the given point in the metric of mushroom scientists shouldn't differ from the natural logarithm of the maximum distance by more than 10 - 6. We think that ln(0) =  - ∞.

S = gets.to_f
a, b, c = gets.chomp.split.map{|x| x.to_i}
a=1 if a+b+c == 0
print S*a/(a+b+c)
print ' '
print S*b/(a+b+c)
print ' '
print S*c/(a+b+c)
puts

S = gets.to_f
a, b, c = gets.chomp.split.map{|x| x.to_i}
print S*a/(a+b+c)
print ' '
print S*b/(a+b+c)
print ' '
print S*c/(a+b+c)
puts


Vasily the bear has got a sequence of positive integers a1, a2, ..., an. Vasily the Bear wants to write out several numbers on a piece of paper so that the beauty of the numbers he wrote out was maximum. The beauty of the written out numbers b1, b2, ..., bk is such maximum non-negative integer v, that number b1 and b2 and ... and bk is divisible by number 2v without a remainder. If such number v doesn't exist (that is, for any non-negative integer v, number b1 and b2 and ... and bk is divisible by 2v without a remainder), the beauty of the written out numbers equals -1. Tell the bear which numbers he should write out so that the beauty of the written out numbers is maximum. If there are multiple ways to write out the numbers, you need to choose the one where the bear writes out as many numbers as possible.Here expression x and y means applying the bitwise AND operation to numbers x and y. In programming languages C++ and Java this operation is represented by "&", in Pascal — by "and".

The first line contains integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ a1 < a2 < ... < an ≤ 109).

In the first line print a single integer k (k > 0), showing how many numbers to write out. In the second line print k integers b1, b2, ..., bk — the numbers to write out. You are allowed to print numbers b1, b2, ..., bk in any order, but all of them must be distinct. If there are multiple ways to write out the numbers, choose the one with the maximum number of numbers to write out. If there still are multiple ways, you are allowed to print any of them.

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)
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)
m=1<<Math.log2(a.last).to_i
a=a.select{|x|x>=m}
puts a.size,a.join(' ')


Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.

The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.  The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.

Output one of the four words without inverted commas:    «forward» — if Peter could see such sequences only on the way from A to B;  «backward» — if Peter could see such sequences on the way from B to A;  «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A;  «fantasy» — if Peter could not see such sequences.

NoteIt is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B.

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;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)]

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

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

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+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


Last year the world's largest square was built in Berland. It is known that the square can be represented as an infinite plane with an introduced Cartesian system of coordinates. On that square two sets of concentric circles were painted. Let's call the set of concentric circles with radii 1, 2, ..., K and the center in the point (z, 0) a (K, z)-set. Thus, on the square were painted a (N, x)-set and a (M, y)-set. You have to find out how many parts those sets divided the square into.

The first line contains integers N, x, M, y. (1 ≤ N, M ≤ 100000,  - 100000 ≤ x, y ≤ 100000, x ≠ y).

n,x,m,y = gets.chomp.split(/ /).map!{|x| x.to_i}
if x > y
	x,y = y,x
	n,m = m,n
end

ret = n+1
for i in 1..m
    ly=y-i-x
	ry=y+i-x
    if (ly>=n || ly<=-n)
		ret+=1
	elsif (ly>=0 && ry>=0)
	  ry=[n,ry-1].min
      ret+=2*(ry-ly)
    else
      ry=[n,ry-1].min
      ret +=2*(ry+ly)+1
    end
end

puts ret


Polycarp found under the Christmas tree an array $$$a$$$ of $$$n$$$ elements and instructions for playing with it:   At first, choose index $$$i$$$ ($$$1 \leq i \leq n$$$) — starting position in the array. Put the chip at the index $$$i$$$ (on the value $$$a_i$$$).  While $$$i \leq n$$$, add $$$a_i$$$ to your score and move the chip $$$a_i$$$ positions to the right (i.e. replace $$$i$$$ with $$$i + a_i$$$).  If $$$i > n$$$, then Polycarp ends the game. For example, if $$$n = 5$$$ and $$$a = [7, 3, 1, 2, 3]$$$, then the following game options are possible:   Polycarp chooses $$$i = 1$$$. Game process: $$$i = 1 \overset{+7}{\longrightarrow} 8$$$. The score of the game is: $$$a_1 = 7$$$.  Polycarp chooses $$$i = 2$$$. Game process: $$$i = 2 \overset{+3}{\longrightarrow} 5 \overset{+3}{\longrightarrow} 8$$$. The score of the game is: $$$a_2 + a_5 = 6$$$.  Polycarp chooses $$$i = 3$$$. Game process: $$$i = 3 \overset{+1}{\longrightarrow} 4 \overset{+2}{\longrightarrow} 6$$$. The score of the game is: $$$a_3 + a_4 = 3$$$.  Polycarp chooses $$$i = 4$$$. Game process: $$$i = 4 \overset{+2}{\longrightarrow} 6$$$. The score of the game is: $$$a_4 = 2$$$.  Polycarp chooses $$$i = 5$$$. Game process: $$$i = 5 \overset{+3}{\longrightarrow} 8$$$. The score of the game is: $$$a_5 = 3$$$. Help Polycarp to find out the maximum score he can get if he chooses the starting index in an optimal way.

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

For each test case, output on a separate line one number — the maximum score that Polycarp can get by playing the game on the corresponding array according to the instruction from the statement. Note that Polycarp chooses any starting position from $$$1$$$ to $$$n$$$ in such a way as to maximize his result.

NoteThe first test case is explained in the statement.In the second test case, the maximum score can be achieved by choosing $$$i = 1$$$.In the third test case, the maximum score can be achieved by choosing $$$i = 2$$$.In the fourth test case, the maximum score can be achieved by choosing $$$i = 1$$$.

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

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

#!/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


Given $$$n$$$ strings, each of length $$$2$$$, consisting of lowercase Latin alphabet letters from 'a' to 'k', output the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and the $$$i$$$-th string and the $$$j$$$-th string differ in exactly one position.In other words, count the number of pairs $$$(i, j)$$$ ($$$i < j$$$) such that the $$$i$$$-th string and the $$$j$$$-th string have exactly one position $$$p$$$ ($$$1 \leq p \leq 2$$$) such that $$${s_{i}}_{p} \neq {s_{j}}_{p}$$$.The answer may not fit into 32-bit integer type, so you should use 64-bit integers like long long in C++ to avoid integer overflow.

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 a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of strings. Then follows $$$n$$$ lines, the $$$i$$$-th of which containing a single string $$$s_i$$$ of length $$$2$$$, consisting of lowercase Latin letters from 'a' to 'k'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print a single integer — the number of pairs $$$(i, j)$$$ ($$$i < j$$$) such that the $$$i$$$-th string and the $$$j$$$-th string have exactly one position $$$p$$$ ($$$1 \leq p \leq 2$$$) such that $$${s_{i}}_{p} \neq {s_{j}}_{p}$$$.  Please note, that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).

4
6
ab
cb
db
aa
cc
ef
7
aa
bb
cc
ac
ca
bb
aa
4
kk
kk
ab
ab
5
jf
jf
jk
jk
jk

NoteFor the first test case the pairs that differ in exactly one position are: ("ab", "cb"), ("ab", "db"), ("ab", "aa"), ("cb", "db") and ("cb", "cc").For the second test case the pairs that differ in exactly one position are: ("aa", "ac"), ("aa", "ca"), ("cc", "ac"), ("cc", "ca"), ("ac", "aa") and ("ca", "aa").For the third test case, the are no pairs satisfying the conditions.

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

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


Inna loves digit 9 very much. That's why she asked Dima to write a small number consisting of nines. But Dima must have misunderstood her and he wrote a very large number a, consisting of digits from 1 to 9.Inna wants to slightly alter the number Dima wrote so that in the end the number contained as many digits nine as possible. In one move, Inna can choose two adjacent digits in a number which sum equals 9 and replace them by a single digit 9.For instance, Inna can alter number 14545181 like this: 14545181 → 1945181 → 194519 → 19919. Also, she can use this method to transform number 14545181 into number 19991. Inna will not transform it into 149591 as she can get numbers 19919 and 19991 which contain more digits nine.Dima is a programmer so he wants to find out how many distinct numbers containing as many digits nine as possible Inna can get from the written number. Help him with this challenging task.

The first line of the input contains integer a (1 ≤ a ≤ 10100000). Number a doesn't have any zeroes.

In a single line print a single integer — the answer to the problem. It is guaranteed that the answer to the problem doesn't exceed 263 - 1. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteNotes to the samplesIn the first sample Inna can get the following numbers: 369727 → 99727 → 9997, 369727 → 99727 → 9979.In the second sample, Inna can act like this: 123456789987654321 → 12396789987654321 → 1239678998769321.

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


Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $$$t$$$ matches of a digit game...In each of $$$t$$$ matches of the digit game, a positive integer is generated. It consists of $$$n$$$ digits. The digits of this integer are numerated from $$$1$$$ to $$$n$$$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with $$$n$$$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of $$$t$$$ matches find out, which agent wins, if both of them want to win and play optimally.

First line of input contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$  — the number of matches. The first line of each match description contains an integer $$$n$$$ $$$(1 \le n \le 10^3)$$$  — the number of digits of the generated number. The second line of each match description contains an $$$n$$$-digit positive integer without leading zeros.

For each match print $$$1$$$, if Raze wins, and $$$2$$$, if Breach wins.

NoteIn the first match no one can make a turn, the only digit left is $$$2$$$, it's even, so Breach wins.In the second match the only digit left is $$$3$$$, it's odd, so Raze wins.In the third match Raze can mark the last digit, after that Breach can only mark $$$0$$$. $$$1$$$ will be the last digit left, it's odd, so Raze wins.In the fourth match no matter how Raze plays, Breach can mark $$$9$$$, and in the end there will be digit $$$0$$$. It's even, so Breach wins.

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

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


You are given $$$n$$$ strings $$$s_1, s_2, \dots, s_n$$$ of length at most $$$\mathbf{8}$$$. For each string $$$s_i$$$, determine if there exist two strings $$$s_j$$$ and $$$s_k$$$ such that $$$s_i = s_j + s_k$$$. That is, $$$s_i$$$ is the concatenation of $$$s_j$$$ and $$$s_k$$$. Note that $$$j$$$ can be equal to $$$k$$$.Recall that the concatenation of strings $$$s$$$ and $$$t$$$ is $$$s + t = s_1 s_2 \dots s_p t_1 t_2 \dots t_q$$$, where $$$p$$$ and $$$q$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively. For example, concatenation of "code" and "forces" is "codeforces".

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of strings. Then $$$n$$$ lines follow, the $$$i$$$-th of which contains non-empty string $$$s_i$$$ of length at most $$$\mathbf{8}$$$, consisting of lowercase English letters. Among the given $$$n$$$ strings, there may be equal (duplicates). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case, output a binary string of length $$$n$$$. The $$$i$$$-th bit should be $$$\texttt{1}$$$ if there exist two strings $$$s_j$$$ and $$$s_k$$$ where $$$s_i = s_j + s_k$$$, and $$$\texttt{0}$$$ otherwise. Note that $$$j$$$ can be equal to $$$k$$$.

3

5

abab

ab

abc

abacb

c

3

x

xx

xxx

8

codeforc

es

codes

cod

forc

forces

e

code

NoteIn the first test case, we have the following:   $$$s_1 = s_2 + s_2$$$, since $$$\texttt{abab} = \texttt{ab} + \texttt{ab}$$$. Remember that $$$j$$$ can be equal to $$$k$$$.  $$$s_2$$$ is not the concatenation of any two strings in the list.  $$$s_3 = s_2 + s_5$$$, since $$$\texttt{abc} = \texttt{ab} + \texttt{c}$$$.  $$$s_4$$$ is not the concatenation of any two strings in the list.  $$$s_5$$$ is not the concatenation of any two strings in the list.  Since only $$$s_1$$$ and $$$s_3$$$ satisfy the conditions, only the first and third bits in the answer should be $$$\texttt{1}$$$, so the answer is $$$\texttt{10100}$$$.

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


In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick.He is too selfish, so for a given n he wants to obtain a string of n characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substring. For example, the strings "abc" and "abca" suit him, while the string "aba" doesn't. He also want the number of letters 'c' in his string to be as little as possible.

The first line contains single integer n (1 ≤ n ≤ 2·105) — the length of the string.

Print the string that satisfies all the constraints. If there are multiple answers, print any of them.

NoteA palindrome is a sequence of characters which reads the same backward and forward.

# 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

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

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


Monocarp has got an array $$$a$$$ consisting of $$$n$$$ integers. Let's denote $$$k$$$ as the mathematic mean of these elements (note that it's possible that $$$k$$$ is not an integer). The mathematic mean of an array of $$$n$$$ elements is the sum of elements divided by the number of these elements (i. e. sum divided by $$$n$$$).Monocarp wants to delete exactly two elements from $$$a$$$ so that the mathematic mean of the remaining $$$(n - 2)$$$ elements is still equal to $$$k$$$.Your task is to calculate the number of pairs of positions $$$[i, j]$$$ ($$$i < j$$$) such that if the elements on these positions are deleted, the mathematic mean of $$$(n - 2)$$$ remaining elements is equal to $$$k$$$ (that is, it is equal to the mathematic mean of $$$n$$$ elements of the original array $$$a$$$).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array. The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{9}$$$), where $$$a_i$$$ is the $$$i$$$-th element of the array. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

Print one integer — the number of pairs of positions $$$[i, j]$$$ ($$$i < j$$$) such that if the elements on these positions are deleted, the mathematic mean of $$$(n - 2)$$$ remaining elements is equal to $$$k$$$ (that is, it is equal to the mathematic mean of $$$n$$$ elements of the original array $$$a$$$).

NoteIn the first example, any pair of elements can be removed since all of them are equal.In the second example, there is no way to delete two elements so the mathematic mean doesn't change.In the third example, it is possible to delete the elements on positions $$$1$$$ and $$$3$$$, or the elements on positions $$$4$$$ and $$$5$$$.

gets.to_i.times do
  n=gets.to_i
  a=gets.split.map(&:to_i).sort
  s=a.sum
  if 2*s%n!=0
    puts 0
    next
  end
  k2=2*s/n

  b=[]
  bb=[]
  q=-1
  a.each do |aa|
    if aa!=q
      b << aa
      bb << 1
      q=aa
    else
      bb[-1]+=1
    end
  end

  bz=b.size
  c=0
  i=0
  j=bz-1
  while i<=j
    bibj=b[i]+b[j]
    if bibj==k2
      if i!=j
        c+=bb[i]*bb[j]
        i+=1
      else
        c+=bb[i]*(bb[i]-1)/2
        i+=1
      end
    elsif bibj<k2
      i+=1
    else
      j-=1
    end
  end
  puts c
end


Let's call a list of positive integers $$$a_0, a_1, ..., a_{n-1}$$$ a power sequence if there is a positive integer $$$c$$$, so that for every $$$0 \le i \le n-1$$$ then $$$a_i = c^i$$$.Given a list of $$$n$$$ positive integers $$$a_0, a_1, ..., a_{n-1}$$$, you are allowed to:  Reorder the list (i.e. pick a permutation $$$p$$$ of $$$\{0,1,...,n - 1\}$$$ and change $$$a_i$$$ to $$$a_{p_i}$$$), then  Do the following operation any number of times: pick an index $$$i$$$ and change $$$a_i$$$ to $$$a_i - 1$$$ or $$$a_i + 1$$$ (i.e. increment or decrement $$$a_i$$$ by $$$1$$$) with a cost of $$$1$$$. Find the minimum cost to transform $$$a_0, a_1, ..., a_{n-1}$$$ into a power sequence.

The first line contains an integer $$$n$$$ ($$$3 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_0, a_1, ..., a_{n-1}$$$ ($$$1 \le a_i \le 10^9$$$).

Print the minimum cost to transform $$$a_0, a_1, ..., a_{n-1}$$$ into a power sequence.

NoteIn the first example, we first reorder $$$\{1, 3, 2\}$$$ into $$$\{1, 2, 3\}$$$, then increment $$$a_2$$$ to $$$4$$$ with cost $$$1$$$ to get a power sequence $$$\{1, 2, 4\}$$$.

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 < 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.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


You are given an array $$$a$$$ consisting of $$$n$$$ positive integers.Initially, you have an integer $$$x = 0$$$. During one move, you can do one of the following two operations:  Choose exactly one $$$i$$$ from $$$1$$$ to $$$n$$$ and increase $$$a_i$$$ by $$$x$$$ ($$$a_i := a_i + x$$$), then increase $$$x$$$ by $$$1$$$ ($$$x := x + 1$$$).  Just increase $$$x$$$ by $$$1$$$ ($$$x := x + 1$$$). The first operation can be applied no more than once to each $$$i$$$ from $$$1$$$ to $$$n$$$.Your task is to find the minimum number of moves required to obtain such an array that each its element is divisible by $$$k$$$ (the value $$$k$$$ is given).You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5; 1 \le k \le 10^9$$$) — the length of $$$a$$$ and the required divisior. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer — the minimum number of moves required to obtain such an array that each its element is divisible by $$$k$$$.

NoteConsider the first test case of the example:  $$$x=0$$$, $$$a = [1, 2, 1, 3]$$$. Just increase $$$x$$$;  $$$x=1$$$, $$$a = [1, 2, 1, 3]$$$. Add $$$x$$$ to the second element and increase $$$x$$$;  $$$x=2$$$, $$$a = [1, 3, 1, 3]$$$. Add $$$x$$$ to the third element and increase $$$x$$$;  $$$x=3$$$, $$$a = [1, 3, 3, 3]$$$. Add $$$x$$$ to the fourth element and increase $$$x$$$;  $$$x=4$$$, $$$a = [1, 3, 3, 6]$$$. Just increase $$$x$$$;  $$$x=5$$$, $$$a = [1, 3, 3, 6]$$$. Add $$$x$$$ to the first element and increase $$$x$$$;  $$$x=6$$$, $$$a = [6, 3, 3, 6]$$$. We obtained the required array. Note that you can't add $$$x$$$ to the same element more than once.

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

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

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


The Central Company has an office with a sophisticated security system. There are $$$10^6$$$ employees, numbered from $$$1$$$ to $$$10^6$$$.The security system logs entrances and departures. The entrance of the $$$i$$$-th employee is denoted by the integer $$$i$$$, while the departure of the $$$i$$$-th employee is denoted by the integer $$$-i$$$.The company has some strict rules about access to its office:  An employee can enter the office at most once per day.  He obviously can't leave the office if he didn't enter it earlier that day.  In the beginning and at the end of every day, the office is empty (employees can't stay at night). It may also be empty at any moment of the day. Any array of events satisfying these conditions is called a valid day.Some examples of valid or invalid days:  $$$[1, 7, -7, 3, -1, -3]$$$ is a valid day ($$$1$$$ enters, $$$7$$$ enters, $$$7$$$ leaves, $$$3$$$ enters, $$$1$$$ leaves, $$$3$$$ leaves).  $$$[2, -2, 3, -3]$$$ is also a valid day.  $$$[2, 5, -5, 5, -5, -2]$$$ is not a valid day, because $$$5$$$ entered the office twice during the same day.  $$$[-4, 4]$$$ is not a valid day, because $$$4$$$ left the office without being in it.  $$$[4]$$$ is not a valid day, because $$$4$$$ entered the office and didn't leave it before the end of the day. There are $$$n$$$ events $$$a_1, a_2, \ldots, a_n$$$, in the order they occurred. This array corresponds to one or more consecutive days. The system administrator erased the dates of events by mistake, but he didn't change the order of the events.You must partition (to cut) the array $$$a$$$ of events into contiguous subarrays, which must represent non-empty valid days (or say that it's impossible). Each array element should belong to exactly one contiguous subarray of a partition. Each contiguous subarray of a partition should be a valid day.For example, if $$$n=8$$$ and $$$a=[1, -1, 1, 2, -1, -2, 3, -3]$$$ then he can partition it into two contiguous subarrays which are valid days: $$$a = [1, -1~ \boldsymbol{|}~ 1, 2, -1, -2, 3, -3]$$$.Help the administrator to partition the given array $$$a$$$ in the required way or report that it is impossible to do. Find any required partition, you should not minimize or maximize the number of parts.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$ and $$$a_i \neq 0$$$).

If there is no valid partition, print $$$-1$$$. Otherwise, print any valid partition in the following format:   On the first line print the number $$$d$$$ of days ($$$1 \le d \le n$$$).  On the second line, print $$$d$$$ integers $$$c_1, c_2, \ldots, c_d$$$ ($$$1 \le c_i \le n$$$ and $$$c_1 + c_2 + \ldots + c_d = n$$$), where $$$c_i$$$ is the number of events in the $$$i$$$-th day.  If there are many valid solutions, you can print any of them. You don't have to minimize nor maximize the number of days.

NoteIn the first example, the whole array is a valid day.In the second example, one possible valid solution is to split the array into $$$[1, -1]$$$ and $$$[1, 2, -1, -2, 3, -3]$$$ ($$$d = 2$$$ and $$$c = [2, 6]$$$). The only other valid solution would be to split the array into $$$[1, -1]$$$, $$$[1, 2, -1, -2]$$$ and $$$[3, -3]$$$ ($$$d = 3$$$ and $$$c = [2, 4, 2]$$$). Both solutions are accepted.In the third and fourth examples, we can prove that there exists no valid solution. Please note that the array given in input is not guaranteed to represent a coherent set of events.

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

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
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

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(' ')


Bob has a string $$$s$$$ consisting of lowercase English letters. He defines $$$s'$$$ to be the string after removing all "a" characters from $$$s$$$ (keeping all other characters in the same order). He then generates a new string $$$t$$$ by concatenating $$$s$$$ and $$$s'$$$. In other words, $$$t=s+s'$$$ (look at notes for an example).You are given a string $$$t$$$. Your task is to find some $$$s$$$ that Bob could have used to generate $$$t$$$. It can be shown that if an answer exists, it will be unique.

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

Print a string $$$s$$$ that could have generated $$$t$$$. It can be shown if an answer exists, it is unique. If no string exists, print ":(" (without double quotes, there is no space between the characters).

NoteIn the first example, we have $$$s = $$$ "aaaaa", and $$$s' = $$$ "".In the second example, no such $$$s$$$ can work that will generate the given $$$t$$$.In the third example, we have $$$s = $$$ "ababacac", and $$$s' = $$$ "bbcc", and $$$t = s + s' = $$$ "ababacacbbcc".

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


Two players decided to play one interesting card game.There is a deck of $$$n$$$ cards, with values from $$$1$$$ to $$$n$$$. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has at least one card. The game goes as follows: on each turn, each player chooses one of their cards (whichever they want) and puts on the table, so that the other player doesn't see which card they chose. After that, both cards are revealed, and the player, value of whose card was larger, takes both cards in his hand. Note that as all cards have different values, one of the cards will be strictly larger than the other one. Every card may be played any amount of times. The player loses if he doesn't have any cards.For example, suppose that $$$n = 5$$$, the first player has cards with values $$$2$$$ and $$$3$$$, and the second player has cards with values $$$1$$$, $$$4$$$, $$$5$$$. Then one possible flow of the game is:The first player chooses the card $$$3$$$. The second player chooses the card $$$1$$$. As $$$3>1$$$, the first player gets both cards. Now the first player has cards $$$1$$$, $$$2$$$, $$$3$$$, the second player has cards $$$4$$$, $$$5$$$.The first player chooses the card $$$3$$$. The second player chooses the card $$$4$$$. As $$$3<4$$$, the second player gets both cards. Now the first player has cards $$$1$$$, $$$2$$$. The second player has cards $$$3$$$, $$$4$$$, $$$5$$$.The first player chooses the card $$$1$$$. The second player chooses the card $$$3$$$. As $$$1<3$$$, the second player gets both cards. Now the first player has only the card $$$2$$$. The second player has cards $$$1$$$, $$$3$$$, $$$4$$$, $$$5$$$.The first player chooses the card $$$2$$$. The second player chooses the card $$$4$$$. As $$$2<4$$$, the second player gets both cards. Now the first player is out of cards and loses. Therefore, the second player wins.Who will win if both players are playing optimally? It can be shown that one of the players has a winning strategy.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). The description of the test cases follows. The first line of each test case contains three integers $$$n$$$, $$$k_1$$$, $$$k_2$$$ ($$$2 \le n \le 100, 1 \le k_1 \le n - 1, 1 \le k_2 \le n - 1, k_1 + k_2 = n$$$) — the number of cards, number of cards owned by the first player and second player correspondingly. The second line of each test case contains $$$k_1$$$ integers $$$a_1, \dots, a_{k_1}$$$ ($$$1 \le a_i \le n$$$) — the values of cards of the first player. The third line of each test case contains $$$k_2$$$ integers $$$b_1, \dots, b_{k_2}$$$ ($$$1 \le b_i \le n$$$) — the values of cards of the second player. It is guaranteed that the values of all cards are different.

For each test case, output "YES" in a separate line, if the first player wins. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).

NoteIn the first test case of the example, there is only one possible move for every player: the first player will put $$$2$$$, the second player will put $$$1$$$. $$$2>1$$$, so the first player will get both cards and will win.In the second test case of the example, it can be shown that it is the second player who has a winning strategy. One possible flow of the game is illustrated in the statement.

gets.to_i.times do
	n=gets.split[0]
	if gets.split.include?(n)
        puts 'YES'
	else
        puts'NO'
	end
    gets
end


One day Vasya got hold of information on the Martian dollar course in bourles for the next n days. The buying prices and the selling prices for one dollar on day i are the same and are equal to ai. Vasya has b bourles. He can buy a certain number of dollars and then sell it no more than once in n days. According to Martian laws, one can buy only an integer number of dollars. Which maximal sum of money in bourles can Vasya get by the end of day n?

The first line contains two integers n and b (1 ≤ n, b ≤ 2000) — the number of days and the initial number of money in bourles. The next line contains n integers ai (1 ≤ ai ≤ 2000) — the prices of Martian dollars.

Print the single number — which maximal sum of money in bourles can Vasya get by the end of day n.

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

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.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(&: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


You are given an array $$$a$$$ consisting of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. You want to split it into exactly $$$k$$$ non-empty non-intersecting subsegments such that each subsegment has odd sum (i. e. for each subsegment, the sum of all elements that belong to this subsegment is odd). It is impossible to rearrange (shuffle) the elements of a given array. Each of the $$$n$$$ elements of the array $$$a$$$ must belong to exactly one of the $$$k$$$ subsegments.Let's see some examples of dividing the array of length $$$5$$$ into $$$3$$$ subsegments (not necessarily with odd sums): $$$[1, 2, 3, 4, 5]$$$ is the initial array, then all possible ways to divide it into $$$3$$$ non-empty non-intersecting subsegments are described below:  $$$[1], [2], [3, 4, 5]$$$;  $$$[1], [2, 3], [4, 5]$$$;  $$$[1], [2, 3, 4], [5]$$$;  $$$[1, 2], [3], [4, 5]$$$;  $$$[1, 2], [3, 4], [5]$$$;  $$$[1, 2, 3], [4], [5]$$$. Of course, it can be impossible to divide the initial array into exactly $$$k$$$ subsegments in such a way that each of them will have odd sum of elements. In this case print "NO". Otherwise, print "YES" and any possible division of the array. See the output format for the detailed explanation.You have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$) — the number of elements in the array and the number of subsegments, respectively. The second line of the query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each query, print the answer to it. If it is impossible to divide the initial array into exactly $$$k$$$ subsegments in such a way that each of them will have odd sum of elements, print "NO" in the first line. Otherwise, print "YES" in the first line and any possible division of the array in the second line. The division can be represented as $$$k$$$ integers $$$r_1$$$, $$$r_2$$$, ..., $$$r_k$$$ such that $$$1 \le r_1 < r_2 < \dots < r_k = n$$$, where $$$r_j$$$ is the right border of the $$$j$$$-th segment (the index of the last element that belongs to the $$$j$$$-th segment), so the array is divided into subsegments $$$[1; r_1], [r_1 + 1; r_2], [r_2 + 1, r_3], \dots, [r_{k - 1} + 1, n]$$$. Note that $$$r_k$$$ is always $$$n$$$ but you should print it anyway.

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


Arya has n opponents in the school. Each day he will fight with all opponents who are present this day. His opponents have some fighting plan that guarantees they will win, but implementing this plan requires presence of them all. That means if one day at least one of Arya's opponents is absent at the school, then Arya will beat all present opponents. Otherwise, if all opponents are present, then they will beat Arya.For each opponent Arya knows his schedule — whether or not he is going to present on each particular day. Tell him the maximum number of consecutive days that he will beat all present opponents.Note, that if some day there are no opponents present, Arya still considers he beats all the present opponents.

The first line of the input contains two integers n and d (1 ≤ n, d ≤ 100) — the number of opponents and the number of days, respectively. The i-th of the following d lines contains a string of length n consisting of characters '0' and '1'. The j-th character of this string is '0' if the j-th opponent is going to be absent on the i-th day.

Print the only integer — the maximum number of consecutive days that Arya will beat all present opponents.

NoteIn the first and the second samples, Arya will beat all present opponents each of the d days.In the third sample, Arya will beat his opponents on days 1, 3 and 4 and his opponents will beat him on days 2 and 5. Thus, the maximum number of consecutive winning days is 2, which happens on days 3 and 4.

#!/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

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, 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,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
		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)


You are given two positive integers $$$a$$$ and $$$b$$$. In one move you can increase $$$a$$$ by $$$1$$$ (replace $$$a$$$ with $$$a+1$$$). Your task is to find the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$. It is possible, that you have to make $$$0$$$ moves, as $$$a$$$ is already divisible by $$$b$$$. You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).

For each test case print the answer — the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$.

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

gets.to_i.times do
	a, b = gets.split.map &:to_i
	x = (a + b - 1) / b * b
	puts x - a
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


Young boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help.Artem wants to paint an $$$n \times m$$$ board. Each cell of the board should be colored in white or black. Lets $$$B$$$ be the number of black cells that have at least one white neighbor adjacent by the side. Let $$$W$$$ be the number of white cells that have at least one black neighbor adjacent by the side. A coloring is called good if $$$B = W + 1$$$. The first coloring shown below has $$$B=5$$$ and $$$W=4$$$ (all cells have at least one neighbor with the opposite color). However, the second coloring is not good as it has $$$B=4$$$, $$$W=4$$$ (only the bottom right cell doesn't have a neighbor with the opposite color).  Please, help Medina to find any good coloring. It's guaranteed that under given constraints the solution always exists. If there are several solutions, output any of them.

Each test contains multiple test cases.  The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 20$$$). Each of the next $$$t$$$ lines contains two integers $$$n, m$$$ ($$$2 \le n,m \le 100$$$) — the number of rows and the number of columns in the grid.

For each test case print $$$n$$$ lines, each of length $$$m$$$, where $$$i$$$-th line is the $$$i$$$-th row of your colored matrix (cell labeled with 'B' means that the cell is black, and 'W' means white). Do not use quotes. It's guaranteed that under given constraints the solution always exists.

NoteIn the first testcase, $$$B=3$$$, $$$W=2$$$.In the second testcase, $$$B=5$$$, $$$W=4$$$. You can see the coloring in the statement.

# 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)

  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

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