Alice's hair is growing by leaps and bounds. Maybe the cause of it is the excess of vitamins, or maybe it is some black magic...To prevent this, Alice decided to go to the hairdresser. She wants for her hair length to be at most $$$l$$$ centimeters after haircut, where $$$l$$$ is her favorite number. Suppose, that the Alice's head is a straight line on which $$$n$$$ hairlines grow. Let's number them from $$$1$$$ to $$$n$$$. With one swing of the scissors the hairdresser can shorten all hairlines on any segment to the length $$$l$$$, given that all hairlines on that segment had length strictly greater than $$$l$$$. The hairdresser wants to complete his job as fast as possible, so he will make the least possible number of swings of scissors, since each swing of scissors takes one second.Alice hasn't decided yet when she would go to the hairdresser, so she asked you to calculate how much time the haircut would take depending on the time she would go to the hairdresser. In particular, you need to process queries of two types:  $$$0$$$ — Alice asks how much time the haircut would take if she would go to the hairdresser now.  $$$1$$$ $$$p$$$ $$$d$$$ — $$$p$$$-th hairline grows by $$$d$$$ centimeters. Note, that in the request $$$0$$$ Alice is interested in hypothetical scenario of taking a haircut now, so no hairlines change their length.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$l$$$ ($$$1 \le n, m \le 100\,000$$$, $$$1 \le l \le 10^9$$$) — the number of hairlines, the number of requests and the favorite number of Alice. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$) — the initial lengths of all hairlines of Alice. Each of the following $$$m$$$ lines contains a request in the format described in the statement. The request description starts with an integer $$$t_i$$$. If $$$t_i = 0$$$, then you need to find the time the haircut would take. Otherwise, $$$t_i = 1$$$ and in this moment one hairline grows. The rest of the line than contains two more integers: $$$p_i$$$ and $$$d_i$$$ ($$$1 \le p_i \le n$$$, $$$1 \le d_i \le 10^9$$$) — the number of the hairline and the length it grows by.

For each query of type $$$0$$$ print the time the haircut would take.

NoteConsider the first example:  Initially lengths of hairlines are equal to $$$1, 2, 3, 4$$$ and only $$$4$$$-th hairline is longer $$$l=3$$$, and hairdresser can cut it in $$$1$$$ second.  Then Alice's second hairline grows, the lengths of hairlines are now equal to $$$1, 5, 3, 4$$$  Now haircut takes two seonds: two swings are required: for the $$$4$$$-th hairline and for the $$$2$$$-nd.  Then Alice's first hairline grows, the lengths of hairlines are now equal to $$$4, 5, 3, 4$$$  The haircut still takes two seconds: with one swing hairdresser can cut $$$4$$$-th hairline and with one more swing cut the segment from $$$1$$$-st to $$$2$$$-nd hairline.  Then Alice's third hairline grows, the lengths of hairlines are now equal to $$$4, 5, 4, 4$$$  Now haircut takes only one second: with one swing it is possible to cut the segment from $$$1$$$-st hairline to the $$$4$$$-th.

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

ans = (ary[0]>l ? 1 : 0)
1.upto(n-1).each do |i|
  ans+=1 if ary[i]>l && ary[i-1]<=l
end

m.times do
  q = gets.strip.split.map(&:to_i)
  if q[0] == 0
    puts ans
  else
    hi = q[1]-1
    ha = q[2]
    if ary[hi] <=l && ary[hi]+ha > l
      if hi==0
        if hi+1 < n
          ans += 1 if ary[hi+1] <= l
        else
          ans += 1
        end
      elsif hi==n-1
        if hi-1 >= 0
          ans += 1 if ary[hi-1] <= l
        end
      else
        ans+=1 if ary[hi-1] <= l && ary[hi+1] <= l
        ans-=1 if ary[hi-1] > l && ary[hi+1] > l
      end
    end
    ary[hi] += ha
  end
end

n,m,l = gets.strip.split.map(&:to_i)
ary = gets.strip.split.map(&:to_i)
ans = 0
ary.each { |x| ans+=1 if x>l }
m.times do
  q = gets.strip.split.map(&:to_i)
  if q[0] == 0
    puts ans
  else
    hi = q[1]-1
    ha = q[2]
    if ary[hi] <=l && ary[hi]+ha > l
      if hi==0
        if hi+1 < n
          ans += 1 if ary[hi+1] <= l
        else
          ans += 1
        end
      elsif hi==n-1
        if hi-1 >= 0
          ans += 1 if ary[hi-1] <= l
        end
      else
        ans+=1 if ary[hi-1] <= l && ary[hi+1] <= l
        ans-=1 if ary[hi-1] > l && ary[hi+1] > l
      end
    end
    ary[hi] += ha
  end
end


Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him.  The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square . Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads.    To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square  has ai lights.Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads.

The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and . All numbers ai are positive integers, not exceeding 100.

Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe.

NotePicture for the sample test. Green color denotes the additional street lights.

n = gets.to_i
a = gets.strip.split(" ").map(&:to_i)
answer = 0
count = Array.new
(2**(n+1)-2).downto(2**n-1) do |i|
  count[i] = 0
end
(2**n-2).downto(0) do |i|
  candidates = [count[i*2+1]+a[i*2], count[i*2+2]+a[i*2+1]]
  count[i] = candidates.max
  answer += candidates.max - candidates.min
end
puts answer

$gl = 0
$h = []
$n
def f(v)

	if(v >= 2**$n and v < 2**($n+1)) then
		return 0
	end

	a = f(2*v) + $h[2*v-2]
	b = f(2*v+1) +  $h[2*v-1]
	$gl += (a-b).abs

	return  [a,b].max
end

$n = gets.to_i
$h = gets.split.collect{|i| i.to_i}

f(1)
puts $gl

lays = gets.to_i
lights = [0, 0] + gets.split(' ').map(&:to_i)

calc_addit = lambda do |root|
  return [0, 0] if 2*root >= lights.size

  l, l_add = calc_addit.(2*root)
  l += lights[2*root]
  r, r_add = calc_addit.(2*root+1)
  r += lights[2*root+1]
  if l == r
    [l, l_add+r_add]
  elsif l > r
    [l, l_add + r_add + (l-r)]
  else
    [r, l_add + r_add + (r-l)]
  end
end

puts calc_addit.(1).last


Polycarp and his friends want to visit a new restaurant. The restaurant has $$$n$$$ tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from $$$1$$$ to $$$n$$$ in the order from left to right. The state of the restaurant is described by a string of length $$$n$$$ which contains characters "1" (the table is occupied) and "0" (the table is empty).Restaurant rules prohibit people to sit at a distance of $$$k$$$ or less from each other. That is, if a person sits at the table number $$$i$$$, then all tables with numbers from $$$i-k$$$ to $$$i+k$$$ (except for the $$$i$$$-th) should be free. In other words, the absolute difference of the numbers of any two occupied tables must be strictly greater than $$$k$$$.For example, if $$$n=8$$$ and $$$k=2$$$, then:  strings "10010001", "10000010", "00000000", "00100000" satisfy the rules of the restaurant;  strings "10100100", "10011001", "11111111" do not satisfy to the rules of the restaurant, since each of them has a pair of "1" with a distance less than or equal to $$$k=2$$$. In particular, if the state of the restaurant is described by a string without "1" or a string with one "1", then the requirement of the restaurant is satisfied.You are given a binary string $$$s$$$ that describes the current state of the restaurant. It is guaranteed that the rules of the restaurant are satisfied for the string $$$s$$$.Find the maximum number of free tables that you can occupy so as not to violate the rules of the restaurant. Formally, what is the maximum number of "0" that can be replaced by "1" such that the requirement will still be satisfied?For example, if $$$n=6$$$, $$$k=1$$$, $$$s=$$$ "100010", then the answer to the problem will be $$$1$$$, since only the table at position $$$3$$$ can be occupied such that the rules are still satisfied.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case starts with a line containing two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2\cdot 10^5$$$) — the number of tables in the restaurant and the minimum allowed distance between two people. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$ consisting of "0" and "1" — a description of the free and occupied tables in the restaurant. The given string satisfy to the rules of the restaurant — the difference between indices of any two "1" is more than $$$k$$$. The sum of $$$n$$$ for all test cases in one test does not exceed $$$2\cdot 10^5$$$.

For each test case output one integer — the number of tables that you can occupy so as not to violate the rules of the restaurant. If additional tables cannot be taken, then, obviously, you need to output $$$0$$$.

NoteThe first test case is explained in the statement.In the second test case, the answer is $$$2$$$, since you can choose the first and the sixth table.In the third test case, you cannot take any free table without violating the rules of the restaurant.

t = gets.to_i
t.times do
	n, k = gets.split.map(&:to_i)
	s = "1" + "0" * k + gets.chomp + "0" * k + "1" # append sentinel

	occupy = 0

	# count continous 0s and check
	count = 0
	s.each_char do |c|
		case c
		when "0"
			count += 1
		when "1"
			avail = [(count + 1) / (k+1) - 1, 0].max
			occupy += avail
			#puts "  #{count} -> #{avail}"
			count = 0
		end
	end

	p occupy
end

results = []
t = gets.chomp
(1..t.to_i).each do
	tables_count, k = gets.chomp.split(' ').map{|e| e.to_i}
	tabels_map = gets.chomp
	index  = 0
	empty_places_counts = []
	empty_places_count = 0
	while index < tables_count do
		if tabels_map[index] == '0'
			empty_places_count += 1
			index += 1
		else
			empty_places_count -= k
			if empty_places_count > 0
				empty_places_counts.push(empty_places_count)
			end
			empty_places_count = 0
			index += k + 1
		end
	end
	if empty_places_count > 0
		empty_places_counts.push(empty_places_count)
	end
	optimal_tables = 0
	empty_places_counts.each do |el|
		optimal_tables += el / (k + 1)
		optimal_tables += 1 if el % (k + 1) > 0
	end

	results.push(optimal_tables)
end

results.each do |res|
	puts res
end

results = []

t = gets.chomp
(1..t.to_i).each do |iteration|
	n, k = gets.chomp.split(' ').map{|e| e.to_i}
	rest = gets.chomp
	index  = 0
	fragments = []
	places_count = 0
	while index < rest.length do
		if rest[index] == '0'
			places_count += 1
			index += 1
		else
			places_count -= k
			if places_count > 0
				fragments.push(places_count)
			end
			places_count = 0
			index += k + 1
		end
	end
	if places_count > 0
		fragments.push(places_count)
	end

	optimal_tables = 0
	fragments.each do |el|
		optimal_tables += el / (k + 1)
		optimal_tables += 1 if el % (k + 1) > 0
	end

	results.push(optimal_tables)
end

results.each do |result|
	puts result
end

def solve(arr_str, k)
	parts = arr_str
		.scan(/1+|0+/)
		.map { |i| i[0] == '0' ? i.size : 0}

	parts.map.with_index
		.reduce(0) do |res, (i, ind)|
			without_borders = i
			without_borders -= k unless ind == 0
			without_borders -= k unless ind == parts.size - 1
			if without_borders > 0
				res += 1 + (without_borders - 1) / (k + 1)
			end

			res
		end
end

total_qty = ARGF.gets.to_i
total_qty.times do
	_n, k = ARGF.gets.split.map(&:to_i)
	a = ARGF.gets.strip
	puts solve(a, k)
end

data_lines = gets.chomp
result = []
(1..data_lines.to_i).each do
	allows = gets.chomp.split(" ")
	tables_count = allows.first.to_i
	k = allows.last.to_i
	map = gets.chomp
	reserved_count = 0
	(0..(map.length-1)).each do |index|
		if map[index] == '1'
			reserved_count += 1
			if reserved_count == 1
				ost = index % (k+1)
				if  ost > 0
					tables_count -= ost
				end
			end
		end
	end
	if tables_count <= k
		result.push(1 - reserved_count)
		next
	end
	all_possible_tables = tables_count / (k + 1)
	if tables_count % (k + 1) > 0
		all_possible_tables += 1
	end
	res = all_possible_tables - reserved_count
	result.push(res)
end
result.each do |res|
	puts res
end

data_lines = gets.chomp
result = []
(1..data_lines.to_i).each do
	allows = gets.chomp.split(" ")
	tables_count = allows.first.to_i
	k = allows.last.to_i
	map = gets.chomp
	reserved_count = 0
	(0..(map.length-1)).each do |index|
		if map[index] == '1'
			reserved_count += 1
			if reserved_count == 1
				ost = index % (k+1)
				if  ost > 0
					tables_count -= ost
				end
			end
		end
	end
	all_possible_tables = tables_count / (k + 1)
	if tables_count % (k + 1) > 0
		all_possible_tables += 1
	end
	res = all_possible_tables - reserved_count
	if res < 0
		result.push(1)
		next
	end
	if reserved_count == 0 && res < 1
		result.push(1)
		next
	end
	result.push(res)
end
result.each do |res|
	puts res
end

data_lines = gets.chomp
result = []
(1..data_lines.to_i).each do
	allows = gets.chomp.split(" ")
	tables_count = allows.first.to_i
	k = allows.last.to_i
	map = gets.chomp
	reserved_count = 0
	(0..(map.length-1)).each do |index|
		if map[index] == '1'
			reserved_count += 1
			if reserved_count == 1
				ost = index % (k+1)
				if  ost > 0
					tables_count -= ost
				end
			end
		end
	end
	all_possible_tables = tables_count / (k + 1)
	if tables_count % (k + 1) > 0
		all_possible_tables += 1
	end
	result.push(all_possible_tables - reserved_count)
end
result.each do |res|
	puts res
end

def solve(arr_str, k)
	parts = arr_str
		.split('1')
		.map(&:size)
		.reject(&:zero?)

	parts.map.with_index
		.reduce(0) do |res, (i, ind)|
			without_borders = i
			without_borders -= k unless ind == 0
			without_borders -= k unless ind == parts.size - 1
			if without_borders > 0
				res += 1 + (without_borders - 1) / (k + 1)
			end

			res
		end
end

total_qty = ARGF.gets.to_i
total_qty.times do
	_n, k = ARGF.gets.split.map(&:to_i)
	a = ARGF.gets.strip
	puts solve(a, k)
end


You are given two positive integers $$$n$$$ and $$$k$$$. Print the $$$k$$$-th positive integer that is not divisible by $$$n$$$.For example, if $$$n=3$$$, and $$$k=7$$$, then all numbers that are not divisible by $$$3$$$ are: $$$1, 2, 4, 5, 7, 8, 10, 11, 13 \dots$$$. The $$$7$$$-th number among them is $$$10$$$.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Next, $$$t$$$ test cases are given, one per line. Each test case is two positive integers $$$n$$$ ($$$2 \le n \le 10^9$$$) and $$$k$$$ ($$$1 \le k \le 10^9$$$).

For each test case print the $$$k$$$-th positive integer that is not divisible by $$$n$$$.

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

    # solution 3

    if n == k
      puts n + 1
      next
    end
    if k < n
      puts k
      next
    end
    # puts n*(k/n) + (k-1)
    # puts n*(k/n-1) + (k-1)
    # 5 12
    ra = k / (n - 1)
    re = k % (n - 1)
    koef = re == 0 ? -1 : re
    puts n * ra + koef
  end

t = gets.to_i

(1).upto(t) do
  x = gets.split(' ')
  n = x[0].to_i
  k = x[1].to_i
  val = k/(n-1)
  val+=k
  val-= (k.modulo(n-1)==0?1:0)
  puts val
end

# Created by IntelliJ IDEA.
# User: gautam.roy
# Date: 5/10/20
# Time: 1:25 PM
# To change this template use File | Settings | File Templates.

# if n > k -> k
# return k/n + k
t = gets.to_i
for i in 1..t do
  n, k = gets.split(' ').map { |s| s.to_i }
  if n > k
    puts k
    next
  end
  puts (k - 1) / (n-1) + k
end

def func(n, k)
    res=2**40-1
    a=2**39
    while a>0
        t=res^a
        cnt=t-t/n
        res=t if cnt>=k
        a>>=1
    end
    res
end

gets.to_i.times{
    n, k=gets.split.map &:to_i
    puts func(n, k)
}

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

  puts k.div(n-1)*n + (k.modulo(n-1).zero? ? -1 : k.modulo(n-1))
end

  t = gets.to_i
  t.times do
    n, k = gets.split(' ').map(&:to_i)
    if n == k
      puts n + 1
      next
    end
    if k < n
      puts k
      next
    end
    ra = k / (n - 1)
    re = k % ra
    koef = re == 0 ? -1 : re
    puts n * ra + koef
end


You were dreaming that you are traveling to a planet named Planetforces on your personal spaceship. Unfortunately, its piloting system was corrupted and now you need to fix it in order to reach Planetforces.  Space can be represented as the $$$XY$$$ plane. You are starting at point $$$(0, 0)$$$, and Planetforces is located in point $$$(p_x, p_y)$$$.The piloting system of your spaceship follows its list of orders which can be represented as a string $$$s$$$. The system reads $$$s$$$ from left to right. Suppose you are at point $$$(x, y)$$$ and current order is $$$s_i$$$:   if $$$s_i = \text{U}$$$, you move to $$$(x, y + 1)$$$;  if $$$s_i = \text{D}$$$, you move to $$$(x, y - 1)$$$;  if $$$s_i = \text{R}$$$, you move to $$$(x + 1, y)$$$;  if $$$s_i = \text{L}$$$, you move to $$$(x - 1, y)$$$. Since string $$$s$$$ could be corrupted, there is a possibility that you won't reach Planetforces in the end. Fortunately, you can delete some orders from $$$s$$$ but you can't change their positions.Can you delete several orders (possibly, zero) from $$$s$$$ in such a way, that you'll reach Planetforces after the system processes all orders?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case consists of two lines. The first line in each test case contains two integers $$$p_x$$$ and $$$p_y$$$ ($$$-10^5 \le p_x, p_y \le 10^5$$$; $$$(p_x, p_y) \neq (0, 0)$$$) — the coordinates of Planetforces $$$(p_x, p_y)$$$. The second line contains the string $$$s$$$ ($$$1 \le |s| \le 10^5$$$: $$$|s|$$$ is the length of string $$$s$$$) — the list of orders. It is guaranteed that the sum of $$$|s|$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print "YES" if you can delete several orders (possibly, zero) from $$$s$$$ in such a way, that you'll reach Planetforces. Otherwise, print "NO". You can print each letter in any case (upper or lower).

6
10 5
RRRRRRRRRRUUUUU
1 1
UDDDRLLL
-3 -5
LDLDLDDDR
1 2
LLLLUU
3 -2
RDULRLLDR
-1 6
RUDURUUUUR

NoteIn the first case, you don't need to modify $$$s$$$, since the given $$$s$$$ will bring you to Planetforces.In the second case, you can delete orders $$$s_2$$$, $$$s_3$$$, $$$s_4$$$, $$$s_6$$$, $$$s_7$$$ and $$$s_8$$$, so $$$s$$$ becomes equal to "UR".In the third test case, you have to delete order $$$s_9$$$, otherwise, you won't finish in the position of Planetforces.

t= gets.chomp.to_i
while t > 0
 flag = false
 x, y = 	gets.chomp.split(' ')
 s = gets.chomp
 x = x.to_i
 y = y.to_i
 count_u = s.count('U')
 count_r = s.count('R')
 count_l = s.count('L')
 count_d = s.count('D')
 if (x >= 0 && y >= 0)
   if (count_r >= x.abs && count_u >= y.abs)
     puts "YES"
     flag = true
   end
 elsif  (x >= 0 && y < 0)
   if (count_r >= x.abs && count_d >= y.abs)
   	 puts "YES"
     flag = true
   end
 elsif  (x < 0 && y >= 0)
 	if (count_l >= x.abs && count_u >= y.abs)
 		 puts "YES"
     flag = true
   end
 elsif  (x < 0 && y < 0)
   if (count_l >= x.abs && count_d >= y.abs)
   	 puts "YES"
     flag = true
   end
 end
 if(!flag)
   puts "NO"
 end
 t = t - 1
end

gets.to_i.times do
    x, y = gets.split.map &:to_i
    s = gets.chomp
    l, r, d, u = 0, 0, 0, 0
    s.each_char do |c|
        case c
            when 'L'
                l += 1
            when 'R'
                r += 1
            when 'D'
                d += 1
            else
                u += 1
        end
    end
    x = 0 if x > 0 && r >= x || x < 0 && l >= -x
    y = 0 if y > 0 && u >= y || y < 0 && d >= -y
    puts x == 0 && y == 0 ? "YES" : "NO"
end

def solve
  x, y = ints
  s = string.chars.tally
  enough = true
  enough = false if x > 0 and (s[?R] || 0) < x.abs
  enough = false if x < 0 and (s[?L] || 0) < x.abs
  enough = false if y > 0 and (s[?U] || 0) < y.abs
  enough = false if y < 0 and (s[?D] || 0) < y.abs
  yesno enough
end

def main
  t = int
  t.times do
    solve
  end
end

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

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

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

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

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

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

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

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

main

t = gets.chomp.to_i
t.times do
  px, py = gets.chomp.split(' ').map(&:to_i)
  s = gets.chomp.split('')
  lx = rx = uy = ly = 0
  s.each do |el|
    case el
    when "U"
      uy += 1
    when "D"
      ly -= 1
    when "R"
      rx += 1
    when "L"
      lx -= 1
    end
  end
  resx = px > 0 && px <= rx || px < 0 && px >= lx || px == 0
  resy = py > 0 && py <= uy || py < 0 && py >= ly || py == 0
  puts resx && resy ? "YES" : "NO"
end

gets.to_i.times do
  x,y=gets.split.map(&:to_i)
  s=gets.chomp.chars
  s.each do |ss|
    if ss=="U"&&y>0
      y-=1
    elsif ss=="D"&&y<0
      y+=1
    elsif ss=="R"&&x>0
      x-=1
    elsif ss=="L"&&x<0
      x+=1
    end
  end
  if [x,y]==[0,0]
    puts "YES"
  else
    puts "NO"
  end
end

t= gets.chomp.to_i
while t > 0
 flag = false
 x, y = 	gets.chomp.split(' ')
 s = gets.chomp
 x = x.to_i
 y = y.to_i
 count_u = s.count('U')
 count_r = s.count('R')
 count_l = s.count('L')
 count_d = s.count('D')
 if (x > 0 && y > 0)
   if (count_r >= x.abs && count_u >= y.abs)
     puts "YES"
     flag = true
   end
 elsif  (x > 0 && y < 0)
   if (count_r >= x.abs && count_d >= y.abs)
   	 puts "YES"
     flag = true
   end
 elsif  (x < 0 && y > 0)
 	if (count_l >= x.abs && count_u >= y.abs)
 		 puts "YES"
     flag = true
   end
 elsif  (x < 0 && y < 0)
   if (count_l >= x.abs && count_d >= y.abs)
   	 puts "YES"
     flag = true
   end
 end
 if(!flag)
   puts "NO"
 end
 t = t - 1
end


n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.

The first line contains two integers: n and k (2 ≤ n ≤ 500, 2 ≤ k ≤ 1012) — the number of people and the number of wins. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n) — powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.

Output a single integer — power of the winner.

NoteGames in the second sample:3 plays with 1. 3 wins. 1 goes to the end of the line.3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner.

n,m=gets.split.map{|e| e.to_i}
x=gets.split.map{|e| e.to_i}
y=x.max
c=m
while true
	if x[0]==y
		break
	end
	if x[0]>x[1]
		a=x.shift
		b=x.shift
		x.unshift(a)
		x.push(b)
		c-=1
	else
		a=x.shift
		x.push(a)
		c=m-1
	end
	break if c==0
end
puts x[0]

n, k = gets.split.map &:to_i
b, c = 0, 0
gets.split.map(&:to_i).each{|v|
	c = b > 0 ? (b > v ? c + 1 : 1) : 0
	b = [b, v].max
	c == k && break
}
p b

n, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
cnt = 0
cur = a[0]
1.upto(n - 1) do |i|
    if cur == n
        puts n
        break
    elsif cur > a[i]
        cnt += 1
        if cnt == k
            puts cur
            break
        end
    else
        cnt = 1
        cur = a[i]
        if cnt == k || cur == n
            puts cur
            break
        end
    end
end

n,m=gets.split.map{|e| e.to_i}
x=gets.split.map{|e| e.to_i}
y=x.max
hs=Hash.new(0)
while true
	if x[0]==y
		hs[y]+=m
		break
	end
	if x[0]>x[1]
		a=x.shift
		b=x.shift
		x.unshift(a)
		x.push(b)
		hs[a]+=1
	else
		a=x.shift
		x.push(a)
		hs[x[0]]+=1
	end
	m-=1
end
ans=-1
ansV=-1
hs.each{|k,v|
	if v>ansV
		ansV=v
		ans=k
	end
}
puts ans

n,m=gets.split.map{|e| e.to_i}
x=gets.split.map{|e| e.to_i}
y=x.max
hs=Hash.new(0)
while true
	if x[0]==y
		break
	end
	if x[0]>x[1]
		a=x.shift
		b=x.shift
		x.unshift(a)
		x.push(b)
		hs[a]+=1
	else
		a=x.shift
		x.push(a)
		hs[x[0]]+=1
	end
end
puts x[0]

n,m=gets.split.map{|e| e.to_i}
x=gets.split.map{|e| e.to_i}
y=x.max
hs=Hash.new(0)
while true
	break if m==0
	if x[0]==y
		break
	end
	if x[0]>x[1]
		a=x.shift
		b=x.shift
		x.unshift(a)
		x.push(b)
		hs[a]+=1
	else
		a=x.shift
		x.push(a)
		hs[x[0]]+=1
	end
	m-=1
end
puts x[0]


Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of $$$n$$$ strings $$$s_1, s_2, s_3, \ldots, s_{n}$$$ and $$$m$$$ strings $$$t_1, t_2, t_3, \ldots, t_{m}$$$. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings $$$x$$$ and $$$y$$$ as the string that is obtained by writing down strings $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings $$$s_1$$$ and $$$t_1$$$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if $$$n = 3, m = 4, s = $$${"a", "b", "c"}, $$$t =$$$ {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat.  You are given two sequences of strings of size $$$n$$$ and $$$m$$$ and also $$$q$$$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?

The first line contains two integers $$$n, m$$$ ($$$1 \le n, m \le 20$$$). The next line contains $$$n$$$ strings $$$s_1, s_2, \ldots, s_{n}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. The next line contains $$$m$$$ strings $$$t_1, t_2, \ldots, t_{m}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. Among the given $$$n + m$$$ strings may be duplicates (that is, they are not necessarily all different). The next line contains a single integer $$$q$$$ ($$$1 \le q \le 2\,020$$$). In the next $$$q$$$ lines, an integer $$$y$$$ ($$$1 \le y \le 10^9$$$) is given, denoting the year we want to know the name for.

Print $$$q$$$ lines. For each line, print the name of the year as per the rule described above.

10 12
sin im gye gap eul byeong jeong mu gi gyeong
yu sul hae ja chuk in myo jin sa o mi sin
14
1
2
3
4
10
11
12
13
73
2016
2017
2018
2019
2020

sinyu
imsul
gyehae
gapja
gyeongo
sinmi
imsin
gyeyu
gyeyu
byeongsin
jeongyu
musul
gihae
gyeongja

NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.

n,m=gets.split().map(&:to_i)
a=gets.split().map(&:to_s)
b=gets.split().map(&:to_s)
t=gets.to_i
    for i in 1..t do
    q=gets.to_i-1
    f1,f2=q % n,q % m
    puts a[f1]+b[f2]
end

n , m = gets.chomp.split(" ").map(&:to_i)
ns = gets.chomp.split(" ")
ms = gets.chomp.split(" ")
ngo = gets.chomp.to_i
ngo.times do |i|
	oil = gets.chomp.to_i - 1
	puts ns[oil % n] + ms[oil % m]
end

n, m = gets.split.map &:to_i
s = gets.split
t = gets.split
q = gets.to_i
q.times do
  y = gets.to_i - 1
  puts s[y%n] + t[y%m]
end

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

(0...q).each do |_|
  t = gets.chomp.to_i
  puts "#{a[(t-1) % n]}#{b[(t-1) % m]}"
end


Emuskald is addicted to Codeforces, and keeps refreshing the main page not to miss any changes in the "recent actions" list. He likes to read thread conversations where each thread consists of multiple messages.Recent actions shows a list of n different threads ordered by the time of the latest message in the thread. When a new message is posted in a thread that thread jumps on the top of the list. No two messages of different threads are ever posted at the same time.Emuskald has just finished reading all his opened threads and refreshes the main page for some more messages to feed his addiction. He notices that no new threads have appeared in the list and at the i-th place in the list there is a thread that was at the ai-th place before the refresh. He doesn't want to waste any time reading old messages so he wants to open only threads with new messages.Help Emuskald find out the number of threads that surely have new messages. A thread x surely has a new message if there is no such sequence of thread updates (posting messages) that both conditions hold:   thread x is not updated (it has no new messages);  the list order 1, 2, ..., n changes to a1, a2, ..., an.

The first line of input contains an integer n, the number of threads (1 ≤ n ≤ 105). The next line contains a list of n space-separated integers a1, a2, ..., an where ai (1 ≤ ai ≤ n) is the old position of the i-th thread in the new list. It is guaranteed that all of the ai are distinct.

Output a single integer — the number of threads that surely contain a new message.

NoteIn the first test case, threads 2 and 5 are placed before the thread 1, so these threads must contain new messages. Threads 1, 3 and 4 may contain no new messages, if only threads 2 and 5 have new messages.In the second test case, there may be no new messages at all, since the thread order hasn't changed.In the third test case, only thread 1 can contain no new messages.

gets
a = gets.split.map(&:to_i)
b = a.size - 1
while b > 0 do
  break if a[b - 1] > a[b]
  b -= 1
end
p b

n = gets.to_i
a = gets.split.map(&:to_i)
i = n-1
while i >= 1 and a[i] > a[i-1] do
	i -= 1
end
puts i

n = Integer(gets.chomp)
count = 1
input = gets.split.collect{|element| element.to_i}
(input.length-1).downto 1 do |i|
    if input[i-1]<input[i]
        count = count+1
    else
        break
    end
end
puts n-count

#!/usr/bin/ruby1.9

n = STDIN.readline.to_i
a = STDIN.readline.split.collect {|s| s.to_i }

i = n-1
while i > 0
	break if a[i-1] > a[i]
	i -= 1
end
puts i

n = gets.to_i
a = gets.split(" ").map(&:to_i)
j = 0
n.times{ |i|
    if ( i==n-1 || a[n-1-i] < a [n-2-i] ) then j = i; break; end;
}
puts n - j - 1

gets
a = gets.split.map{|e| e.to_i}
l = a.pop
ans = a.length
a.reverse.each do |e|
  if e < l
    ans -= 1
    l = e
  else
    break
  end
end
puts ans

def run
  n = ARGF.readline
  s = ARGF.readline.split.map(&:to_i)
  len = s.length

  cnt = 0
  (len - 1).times do |i|
    cnt = i + 1 if s[i] > s[i + 1]
  end

  puts cnt
end

run if $0 == __FILE__

n = gets.to_i
a = gets.split.map &:to_i
i = n-1
while (i > 0) && (a[i-1] < a[i]) do
  i -= 1
end
puts i

n=gets.to_i
a = gets.split(' ').collect!{|i| i.to_i}

x = 0
n.times do |i|
	break if i == n-1
	if a[n-i-1] < a[n-i-2]
		x = n-i-1
		break
	end
end
puts x

n = gets.chomp.to_i
line = gets.chomp.split(" ").collect! {|x| x.to_i}
p = n-1
ok = true
q = n
while p>0 and ok

	if line[p]<line[p-1]
		ok = false
	end
	p -= 1
	q -= 1
end

if ok
 q-=1
end
puts q

#!/usr/bin/env ruby

n, mn, tot = gets.to_i, 0x3f3f3f3f, 0
gets.split.map(&:to_i).reverse.each_with_index do |v, i|
	if v > mn
		tot = n - i
		break
	end
	mn = v
end
puts tot

n = gets.to_i

a = gets.split.collect{|x| x.to_i}

a.reverse!

l = 0
result = 0
ok = false

a.each do |i|
	if l == 0
		l = i
	else
		if ok
			result += 1
			next
		end
		if i > l
			ok = true
			result = 1
		else
			l = i
		end
	end
end

puts result

gets
a = gets.split.map(&:to_i)
b = a.size - 1
while b >= 0 do
  break if a[b - 1] > a[b]
  b -= 1
end
p b

n = gets.to_i
a = gets.split.map(&:to_i)
i = n-1
while i >= 1 and a[i] < a[i-1] do
	i -= 1
end
puts n-i-1

n = gets.to_i
a = gets.split.map(&:to_i)
ans = 0
i = 0
while a[i] != 1 do
	ans +=1
	i += 1
end
puts ans

n = gets.to_i
puts gets.split.map(&:to_i).index(1)

n = gets.to_i
a = gets.split.map(&:to_i)
i = 0
ans = 0
while a[i] != 1 and i <= n-1 do
	i += 1
	ans += 1
end
while i < n-2 do
	if a[i+1] > a[i+2] then
		ans += 1
	end
	i+=1
end

puts ans

n = gets.to_i
a = gets.split.map(&:to_i)
ans = 0
for i in 0...(n-1) do
	ans +=1  if a[i] > a[i+1]
end
puts ans

n = Integer(gets.chomp)
count = 1
input = gets
input = input.split
(input.length-1).downto 1 do |i|
    if input[i-1]<input[i]
        count = count+1
    else
        break
    end
end
puts n-count

n = Integer(gets)
count = 1
input = gets.split
(n-1).downto 1 do |i|
    if input[i-1]<input[i]
        count = count+1
    else
        break
    end
end
puts n-count

n = gets.to_i

a = gets.split(" ").map(&:to_i)
puts a.index(1)

gets
a = gets.split(" ").map(&:to_i)
puts a.index(a.min)

n = gets.to_i

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

puts a.index(a.min)

gets
a = gets.split.map{|e| e.to_i}
i = a.index(1)
puts a[0...i].length

def run
  n = ARGF.readline
  s = ARGF.readline.split.map(&:to_i)
  len = s.length

  cnt = 0
  (len - 1).times do |i|
    cnt += 1 if s[i] > s[i + 1]
  end

  puts cnt
end

run if $0 == __FILE__

n=gets.to_i
a = gets.split(' ')

x = 0
n.times do |i|
	if a[n-i-1] < a[n-i-2]
		x = n-i-1
		break
	end
end
puts x

_, mn, tot = gets, 0x3f3f3f3f, 0
gets.split.map(&:to_i).reverse.each { |i| i < mn ? mn = i : tot += 1 }
puts tot

n = gets.to_i

a = gets.split.collect{|x| x.to_i}

a.reverse!

l = 0
result = 0

a.each do |i|
	if l == 0
		l = i
	else
		if i > l
			result += 1
		end
		l = i
	end
end

puts result

n = gets.to_i

a = gets.split.collect{|x| x.to_i}

a.reverse!

l = 0
result = 0

a.each do |i|
	if l == 0
		l = i
	else
		if i > l
			result += 1
		else
			l = i
		end
	end
end

puts result


Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.  The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that?

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of disks on the combination lock. The second line contains a string of n digits — the original state of the disks. The third line contains a string of n digits — Scrooge McDuck's combination that opens the lock.

Print a single integer — the minimum number of moves Scrooge McDuck needs to open the lock.

NoteIn the sample he needs 13 moves:  1 disk:   2 disk:   3 disk:   4 disk:   5 disk:

num = gets.to_i
start = gets
finish = gets

# a > b
def cnt_forward(a, b)
 return a - b
end

# a > b
def cnt_backward(a, b)
 return (10 - a) + b
end

start_a = start.split('').map { |s| s.to_i }
finish_a = finish.split('').map { |s| s.to_i }
data = start_a.zip(finish_a)

result = 0

data.each { |pair|
 fcnt = cnt_forward(pair.max, pair.min)
 bcnt = cnt_backward(pair.max, pair.min)
 if fcnt > bcnt
 result += bcnt
 else
 result += fcnt
 end
}

puts result

# http://codeforces.com/contest/540/problem/A
n = gets.chomp.to_i
origin = gets.chomp.chars.map(&:to_i)
present = gets.chomp.chars.map(&:to_i)

arr = (0...n).map do |idx|
  a, b = [origin[idx], present[idx]].sort

  (b - a <= 10 - b + a) ? b - a : 10 - b + a
end

puts arr.inject(0, :+)

n = gets.to_i

a = gets
b = gets

s = 0

(0..n - 1).each do |i|
  ai = a[i].to_i
  bi = b[i].to_i
  x = (ai - bi).abs
  x = [x, (ai + 10 - bi).abs].min
  x = [x, (bi + 10 - ai).abs].min

  s += x
end

puts s

def count(currNum, targetNum)
	return (currNum - targetNum).abs if (currNum - targetNum).abs <= 5
	return ([currNum, targetNum].min + 10) - ([currNum, targetNum].max)
end

diskNum = gets.chomp.to_i
originState = gets.chomp.split('').map {|item| item.to_i}
correctState = gets.chomp.split('').map {|item| item.to_i}

result = 0
loopNum = 0

until loopNum == originState.length
	#puts originState[loopNum]
	#puts correctState[loopNum]
	result += count(originState[loopNum], correctState[loopNum])

	#puts "result is #{result}"
	loopNum += 1
end

puts result

n=gets.chomp.strip.to_i
#puts n
a=gets.chomp.strip
b=gets.chomp.strip
count=0
i=0
while i<n
	k=(a[i].to_i-b[i].to_i).abs
	#puts k
	if k>5
		count+=10-k
	else
		count+=k
	end
	i+=1
end
puts count

def f a
  a = -a if a < 0
  return 10 - a if a > 5
  a
end
n = gets.to_i; a = gets; b = gets;
sum = 0
n.times {|i| sum += f(a[i].to_i-b[i].to_i)}
puts sum

number = gets.to_i
origin = gets
final = gets
ans = 0
for i in 0...number
  c1 = origin[i]
  c2 = final[i]
  moves = (c1.to_i - c2.to_i).abs
  moves = 10 - moves if moves > 5
  ans = ans + moves
end
puts ans

n = gets.to_i
s = gets.chomp
t = gets.chomp

a = s.split(//).map{|r| r.to_i}
b = t.split(//).map{|r| r.to_i}

counter = 0
for i in 0..n-1
    counter+=[(a[i]-b[i]).abs,(10-a[i]+b[i]).abs,(10-b[i]+a[i]).abs].min
end
puts counter

mv = 0
gets
init = gets.chomp.split("").map &:to_i
pass = gets.chomp.split("").map &:to_i
init.each_with_index do |value, index|
  mv += [(value - pass[index]).abs,
         (10 - value).abs + pass[index],
         (10 - pass[index]).abs + value].min
end
puts mv

  n = gets.chomp.to_i
  a = gets.chomp ; b = gets.chomp
  res = 0
  n.times do |i|
    res += [(a[i].to_i - b[i].to_i).abs , 10 - (a[i].to_i - b[i].to_i).abs].min
  end
  puts res

n = gets.to_i
a = gets.split(//)
b = gets.split(//)
sum=0
(0..n-1).each{ |i|
  a[i]=a[i].to_i
  b[i]=b[i].to_i
  sum += [(a[i]-b[i]).abs,10-(a[i]-b[i]).abs].min
}
print sum

n = gets.to_i
origin = gets.chomp.chars.map(&:to_i)
after = gets.chomp.chars.map(&:to_i)

ans = 0
(0..n-1).each do |i|
  o = origin[i]
  a = after[i]
  ans += [(o-a).abs, (o+10-a).abs, (a+10-o)].min
end
puts ans

n=gets.chomp.to_i

position=gets.chomp.split(//)

pos=[]
position.each do |i|
	pos.push(i.to_i)
end

code=gets.chomp.split(//)

script=[]
code.each do |i|
	script.push(i.to_i)
end

change=0
for item in(0..script.length-1)
	b=(pos[item]-script[item]).abs
	if b>5
		change=change+10-b
	else
		change=change+b
	end
end

puts change

n=gets.to_i
s=gets.chomp
t=gets.chomp

ans=0
s.chars.zip(t.chars).each{|a|
	e1=a[0].to_i
	e2=a[1].to_i
	f1=(e1-e2).abs
	f2=([e1,e2].min+10-[e1,e2].max).abs
	ans=ans+[f1,f2].min
}
puts ans

t = gets.chomp.to_i
start = gets.chomp.split('').map(&:to_i)
stop = gets.chomp.split('').map(&:to_i)

r = 0
t.times.each do |i|
#  p [start[i],stop[i],(start[i]-stop[i]).abs]
  if ((start[i]-stop[i]).abs) > 5
    r += (10 - ((start[i]-stop[i]).abs))
  else
    r += (start[i]-stop[i]).abs
  end
end

puts r

gets
a = gets.chomp
b = gets.chomp
r = 0
0.upto(a.length) do |i|
	x = a[i].to_i
	y = b[i].to_i
	if x > y

		r += [ x - y, x + 10 - y, y + 10 - x ].min
	else
		r += [ y - x, y + 10 - y, x + 10 - y].min
	end
end
puts r

n = gets.chomp.to_i
orig = gets.chomp
combi = gets.chomp
first_state = orig.split("")
combination = combi.split("")

count = 0
for i in (0..n-1)
	if first_state[i].to_i - combination[i].to_i > 5
		count += (10 - (first_state[i].to_i - combination[i].to_i))
	elsif combination[i].to_i - first_state[i].to_i > 5
		count += (10 - (combination[i].to_i - first_state[i].to_i))
	else
		temp = combination[i].to_i - first_state[i].to_i
		if temp < 0
			temp = temp * -1
			count += temp
		else
			count += temp
		end
	end
end

puts count

n=gets.chomp.to_i
a=gets.chomp.split('').to_a.collect{|i| i.to_i}
b=gets.chomp.split('').to_a.collect{|i| i.to_i}
x=0
n.times{|i| t = (a[i]-b[i]).abs; x+=[t,10-t].min}
puts x

gets
p gets.chomp.split(//).zip(gets.chomp.split(//)).map { |x, y| [(x.to_i - y.to_i).abs, (x.to_i - y.to_i - 10).abs, (x.to_i - y.to_i + 10).abs].min }.reduce(:+)

n = gets.to_i
origin = gets.split("").collect{|i| i.to_i}
destin = gets.split("").collect{|i| i.to_i}
ans = 0
(0...n).each do |i|
    tmp = (origin[i]-destin[i]).abs
    ans += [tmp,10-tmp].min
end
puts ans

n = gets.to_i
a = gets.chomp.chars.map(&:to_i)
b = gets.chomp.chars.map(&:to_i)
ans = 0
n.times do |i|
  c = (a[i] - b[i]).abs
  if c > 5
    c = 10 - c
  end
  ans += c
end
puts ans

len = gets.to_i
curr = gets.strip
answ = gets.strip
acts = 0

for pos in 0...len
    if not curr[pos] == answ[pos]
        first = (curr[pos].to_i - answ[pos].to_i).abs
        acts += [first, 10 - first].min
    end
end

puts acts

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

puts(a.zip(b).inject(0) { |s, d| [d.max-d.min, 10-d.max+d.min].min + s })

n = gets.to_i
s = gets.chomp
t = gets.chomp

a = s.split(//).map{|r| r.to_i}
b = t.split(//).map{|r| r.to_i}

def MIN(q,w,c)
   if q>w && w<c
       mini = w
   elsif q<w && q<c
       mini = q
   else
       mini = c
   end
end

counter = 0
for i in 0..n-1
  counter+=MIN((a[i]-b[i]).abs, 10-a[i]+b[i], 10-b[i]+a[i])
end
counter

n = gets.to_i
s = gets.chomp
t = gets.chomp

a = s.split(//).map{|r| r.to_i}
b = t.split(//).map{|r| r.to_i}

def MIN(q,w,c)
   if q>w && w<c
       mini = w
   elsif q<w && q<c
       mini = q
   else
       mini = c
   end
end

counter = 0
for i in 0..n-1
  counter+=MIN((a[i]-b[i]).abs, 10-a[i]+b[i], 10-b[i]+a[i])
end
puts counter

n = gets.to_i
s = gets.chomp
t = gets.chomp

a = s.split(//).map{|r| r.to_i}
b = t.split(//).map{|r| r.to_i}

def MIN(q,w,c)
   if q>w && w<c
       mini = w
   elsif q<w && q<c
       mini = q
   else
       mini = c
   end
end

counter = 0
for i in 0..n-1
  if a[i] != b[i]
     counter+=MIN((a[i]-b[i]).abs, 10-a[i]+b[i], 10-b[i]+a[i])
  else
     counter+=0
  end
end
puts counter

n = gets.chomp.to_i
a = gets.chomp ; b = gets.chomp
res = 0
5.times do |i|
  res += [(a[i].to_i - b[i].to_i).abs , 10 - (a[i].to_i - b[i].to_i).abs].min
end
puts res

len = gets.to_i
beg_state = gets.strip
end_state = gets.strip
acts = 0

for pos in 0...len
    if not beg_state[pos] == end_state[pos]
        acts += [
            (beg_state[pos].to_i - end_state[pos].to_i).abs,
            10 - beg_state[pos].to_i
        ].min
    end
end

puts acts


Limak is a little polar bear. He likes nice strings — strings of length n, consisting of lowercase English letters only.The distance between two letters is defined as the difference between their positions in the alphabet. For example, , and .Also, the distance between two nice strings is defined as the sum of distances of corresponding letters. For example, , and .Limak gives you a nice string s and an integer k. He challenges you to find any nice string s' that . Find any s' satisfying the given conditions, or print "-1" if it's impossible to do so.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

The first line contains two integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 106). The second line contains a string s of length n, consisting of lowercase English letters.

If there is no string satisfying the given conditions then print "-1" (without the quotes). Otherwise, print any nice string s' that .

n, k = gets.split.map(&:to_i)
str = gets.strip
newStr = ""
str.each_char.with_index do |c, i|
  if c.ord >= 'n'.ord
    while k > 0 && c.ord > 'a'.ord
      k -= 1
      c = (c.ord - 1).chr
    end
  else
    while k > 0 && c.ord < 'z'.ord
      k -= 1
      c = c.ord.next.chr
    end
  end
  newStr += c
  if k == 0
    newStr += str[i+1..str.length]
    break
  end
end
if k == 0
  puts newStr
else
  puts -1
end

$an_str = ""

def solve1(el)
  if el.ord + $k < 'z'.ord + 1
    $an_str += (el.ord + $k).chr
    $k = 0
  else
    $an_str += 'z'
    $k -= ('z'.ord - el.ord)
  end
end

def solve2(el)
  if el.ord - $k >= 'a'.ord
    $an_str += (el.ord - $k).chr
    $k = 0
  else
    $an_str += 'a'
    $k -= (el.ord - 'a'.ord)
  end
end

_ , $k = gets.strip.split(' ').map(&:to_i)
str = gets.strip

str.each_char.with_index { |el, i|
  if $k == 0
    $an_str += str[i..str.length]
    break
  end
  if 'z'.ord - el.ord > el.ord - 'a'.ord
    solve1(el)
  else
    solve2(el)
  end
}

if !$k.zero?
  puts "-1"
else
  puts $an_str
end

n, k = gets.split.map(&:to_i)
str = gets.chomp
newStr = ""
str.each_char.with_index do |c, i|
  if c.ord > 'n'.ord
    while k > 0 && c.ord > 'a'.ord
      k -= 1
      c = (c.ord - 1).chr
    end
  else
    while k > 0 && c.ord < 'z'.ord
      k -= 1
      c = c.ord.next.chr
    end
  end
  newStr += c
  if k == 0
    newStr += str[i+1..str.length]
    break
  end
end
if k == 0
  puts newStr
else
  puts -1
end

n, k = gets.split.map(&:to_i)
str = gets
newStr = ""
str.each_char do |c|
  if c.ord > 'n'.ord
    while k > 0 && c.ord > 'a'.ord
      k -= 1
      c = (c.ord - 1).chr
    end
  else
    while k > 0 && c.ord < 'z'.ord
      k -= 1
      c = c.ord.next.chr
    end
  end
  newStr += c
end
if k == 0
  puts newStr
else
  puts -1
end

n, k = gets.split.map(&:to_i)
str = gets.strip
newStr = ""
str.each_char.with_index do |c, i|
  if c.ord > 'n'.ord
    while k > 0 && c.ord > 'a'.ord
      k -= 1
      c = (c.ord - 1).chr
    end
  else
    while k > 0 && c.ord < 'z'.ord
      k -= 1
      c = c.ord.next.chr
      puts "#{k} #{c}"
    end
  end
  newStr += c
  if k == 0
    newStr += str[i+1..str.length]
    break
  end
end
if k == 0
  puts newStr
else
  puts -1
end

n, k = gets.split.map(&:to_i)
str = gets.strip
newStr = ""
str.each_char.with_index do |c, i|
  if c.ord > 'n'.ord
    while k > 0 && c.ord > 'a'.ord
      k -= 1
      c = (c.ord - 1).chr
    end
  else
    while k > 0 && c.ord < 'z'.ord
      k -= 1
      c = c.ord.next.chr
    end
  end
  newStr += c
  if k == 0
    newStr += str[i+1..str.length]
    break
  end
end
if k == 0
  puts newStr
else
  puts -1
end

$an_str = ""

def solve1(el)
  if el.ord + $k < 'z'.ord + 1
    $an_str += (el.ord + $k).chr
    $k = 0
  else
    $an_str += 'z'
    $k -= ('z'.ord - el.ord)
  end
end

def solve2(el)
  if el.ord - $k >= 'a'.ord
    $an_str += (el.ord - $k).chr
    $k = 0
  else
    $an_str += 'a'
    $k -= (el.ord - 'a'.ord)
  end
end

_ , $k = gets.strip.split(' ').map(&:to_i)
str = gets.strip

str.each_char { |el|
  puts $k
  if 'z'.ord - el.ord > el.ord - 'a'.ord
    solve1(el)
  else
    solve2(el)
  end
}

if !$k.zero?
  puts "-1"
else
  puts $an_str
end

c = ('a'..'z').to_a

_ , k = gets.strip.split(' ').map(&:to_i)
str = gets.strip.split('')
an_str = ""

str.each { |el|
  mx = -1
  c.each { |el2|
    if (el2.ord - el.ord).abs <= k
      mx = [mx, (el2.ord - el.ord).abs].max
    end
  }
  an_str += (el.ord + mx).chr
  k -= mx
}

if !k.zero?
  puts "-1"
else
  puts an_str
end

c = ('a'..'z').to_a

_ , k = gets.strip.split(' ').map(&:to_i)
str = gets.strip.split('')
an_str = ""

str.each { |el|
  mx = -1
  c.each { |el2|
    if (el2.ord - el.ord).abs <= k

      mx = [mx, el2.ord - el.ord].max
    end
  }
  an_str += (el.ord + mx).chr
  k -= mx
}

if !k.zero?
  puts "-1"
else
  puts an_str
end


Igor has fallen in love with Tanya. Now Igor wants to show his feelings and write a number on the fence opposite to Tanya's house. Igor thinks that the larger the number is, the more chance to win Tanya's heart he has. Unfortunately, Igor could only get v liters of paint. He did the math and concluded that digit d requires ad liters of paint. Besides, Igor heard that Tanya doesn't like zeroes. That's why Igor won't use them in his number.Help Igor find the maximum number he can write on the fence.

The first line contains a positive integer v (0 ≤ v ≤ 106). The second line contains nine positive integers a1, a2, ..., a9 (1 ≤ ai ≤ 105).

Print the maximum number Igor can write on the fence. If he has too little paint for any digit (so, he cannot write anything), print -1.

m=gets.to_i
a=gets.chomp.split.map(&:to_i)
min,len=a.min,m/a.min
if len==0
	puts "-1"
	exit
end
mod=m%min
for i in 0...len
	j=8
	while j>=0
		if a[j]-min<=mod
			mod-=a[j]-min
			break
		end
		j-=1
	end
	print j+1
end
puts

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

min = arr.min
max = n/min
max_ind = arr.index(min)
digit = max_ind + 1
if max == 0
	ans = "-1"
else
	ans = "#{digit}" * max
	curr_paint = n - (max * arr[digit - 1])
	# puts "digit #{digit - 1}"
	# puts "#{curr_paint}"
	pos = 0
	while curr_paint >= 0
		replace = false
 		8.downto(digit).each do |ind|
 			# puts "rem #{ind} #{curr_paint + arr[a-1] - arr[ind]}"
 			x = arr[ind] - arr[digit-1]
 			if curr_paint >= x
 				ans[pos] = (ind + 1).to_s
 				curr_paint =  curr_paint - x
 				replace = true
 				break
 			end
 		end
 		break unless replace
 		pos += 1
 		break if pos == max
	end

end

puts ans

v=gets.to_i
a=gets.split.map(&:to_i)
b,c=a.each_with_index.to_a.min_by{|x,i|[x,-i]}
c+=1
d=v/b
(p -1;exit)if d==0
e=d*b
f=8
r=''
while true
  f-=1 while v-e+b<a[f]
  break if f==c-1
  r<<(f+1).to_s
  v-=a[f]-b
  d-=1
end
r<<c.to_s*d
puts r

v=gets.to_i
a=gets.split.map(&:to_i)
b,c=a.each_with_index.to_a.min_by{|x,i|[x,-i]}
c+=1
d=v/b
(p -1;exit)if d==0
e=d*b
f=8
r=''
while true
  f-=1 while v-e+b<a[f]
  break if f==c-1
  print f+1
  v-=a[f]-b
  d-=1
end
d.times{print c}

v=gets.to_i
a=gets.split.map(&:to_i)
b,c=a.each_with_index.to_a.min_by{|x,i|[x,-i]}
c+=1
d=v/b
(p -1;exit)if d==0
e=d*b
f=8
r=''
while true
  f-=1 while v-e+b<a[f]
  break if f==c-1
  print f+1
  v-=a[f]-b
  d-=1
end
puts c.to_s*d

p = gets.strip.to_i
a = gets.strip.split.map(&:to_i)
inp = a
a = (1..a.length).zip(a).sort_by{|d| [d[1], -d[0]]}
initp = p
can = false
ans = []
if p > 0
  best_digit = a.select{|d| d[1] <= p}.first
  can = true if best_digit
end
if !can
  puts -1
else
  ans = [best_digit[0]] * (p / best_digit[1])
  p -= best_digit[1] * ans.length
  # puts p
  a = a.sort_by{|d| -d[0]}
  ans.each_with_index do |dig_in_ans, ind|
    better_dig = a.select{|d| dig_in_ans < d[0] && d[1] - inp[dig_in_ans - 1] <= p}.first
    break if better_dig.nil?
    # puts better_dig.join(" - ")
    ans[ind] = better_dig[0]
    p -= better_dig[1] - inp[dig_in_ans - 1]
  end
  puts ans.join("")
end

#! /usr/bin/env ruby

paint = STDIN.gets.to_i
digits = STDIN.gets.to_s.split(' ').map(&:to_i).first(9)

def paint_fence(paint, digits)
  if paint == 0 || digits.min > paint
    puts '-1'
    return
  end

  min = 100000
  idx = nil
  digits.each_with_index do |require_digit, i|
    next if require_digit > min

    min = require_digit
    idx = i + 1
  end

  count = paint / min
  rest = paint % min
  suppl = []

  end_flg = false
  while rest > 0 && !end_flg
    digits.reverse.each_with_index do |require_digit, i|
      if (digit = 9 - i) <= idx
        end_flg = true
        break
      end
      if rest >= (require_digit - min)
        rest -= (require_digit - min)
        suppl << digit
        break
      end
    end
  end

  puts (idx.to_s * count).chars.map {|i|
    (alter = suppl.shift) ? alter : i
  }.join
end

paint_fence(paint, digits)

v = STDIN.readline().to_i
@costs = STDIN.readline().split().collect(&:to_i)

def solve(v)
  x, xv = @costs.rindex(@costs.min), @costs.min
  @costs.collect! { |y| y - xv }
  n, r = v / xv, v % xv

  if n == 0
    STDOUT.write(-1)
    return
  end

  while r > 0
    y = @costs.rindex {|y| y <= r}
    break if !y || @costs[y] == 0
    STDOUT.write(y + 1)
    r -= @costs[y]
    n -= 1
  end

  STDOUT.write ((x+1).to_s * n)
end

solve v

total = gets.to_i
a = gets.split(" ").map{|ai| ai.to_i}
res = []
digit = -1
minw = a.min
a.each_index{|i|
	if a[i] == minw
		digit = i
	end
}
mcnt = total / minw
if mcnt == 0
	print "-1"
elsif total % a[digit] == 0
	print (digit+1).to_s*mcnt
else
	result = ""
	rest = total % a[digit]
	quant = a[digit]
	8.downto(digit+1) {|i|
		n = 1
		while rest + quant*n >= a[i]*n
			n += 1
		end
		n -= 1
		if n > 0
			mcnt -= n
			result += (i+1).to_s * n
		end
		rest = rest + quant*n - a[i]*n
		break if rest == 0
	}
	result += (digit+1).to_s * mcnt
	print result
end

n = gets.to_i
arr = gets.split(" ").map(&:to_i)
dp = []
arr.each do |a|
	dp << n / a
end
max = dp.max
puts "#{dp}"
max_ind = dp.rindex(max)
digit = max_ind + 1
if max == 0
	ans = "-1"
else
	ans = "#{digit}" * max
	curr_paint = n - max * arr[digit - 1]
	puts "#{curr_paint}"
	ans.each_char.with_index do |a,i|
 		a = a.to_i
 		8.downto(0).each do |ind|
 			# puts "rem #{ind} #{curr_paint + arr[a-1] - arr[ind]}"
 			if curr_paint + arr[a-1] - arr[ind]  >= 0
 				ans[i] = (ind + 1).to_s
 				curr_paint =  curr_paint + arr[a-1] - arr[ind]
 				break
 			end
 		end
 	end
end

puts ans

n = gets.to_i
arr = gets.split(" ").map(&:to_i)
dp = []
arr.each do |a|
	dp << n / a
end
max = dp.max
# puts "#{dp}"
max_ind = dp.index(max)
digit = max_ind + 1
if max == 0
	ans = "-1"
else
	ans = "#{digit}" * max
	curr_paint = n - (max * arr[digit - 1])
	# puts "digit #{digit - 1}"
	# puts "#{curr_paint}"
	pos = 0
	while curr_paint > 0
		replace = false
 		8.downto(digit).each do |ind|
 			# puts "rem #{ind} #{curr_paint + arr[a-1] - arr[ind]}"
 			x = arr[ind] - arr[digit-1]
 			if curr_paint >= x
 				ans[pos] = (ind + 1).to_s
 				curr_paint =  curr_paint - x
 				replace = true
 				break
 			end
 		end
 		break unless replace
 		pos += 1
 		break if pos == max
	end

end

puts ans

n = gets.to_i
arr = gets.split(" ").map(&:to_i)
dp = []
arr.each do |a|
	dp << n / a
end
max = dp.max
# puts "#{dp}"
max_ind = dp.rindex(max)
digit = max_ind + 1
if max == 0
	ans = "-1"
else
	ans = "#{digit}" * max
	curr_paint = n - max * arr[digit - 1]
	# puts "#{curr_paint}"
	ans.each_char.with_index do |a,i|
 		a = a.to_i
 		8.downto(0).each do |ind|
 			# puts "rem #{ind} #{curr_paint + arr[a-1] - arr[ind]}"
 			if curr_paint + arr[a-1] - arr[ind]  >= 0
 				ans[i] = (ind + 1).to_s
 				curr_paint =  curr_paint + arr[a-1] - arr[ind]
 				break
 			end
 		end
 	end
end

puts ans

n = gets.to_i
arr = gets.split(" ").map(&:to_i)
dp = []
arr.each do |a|
	dp << n / a
end
max = dp.max
max_ind = dp.rindex(max)
digit = max_ind + 1
puts max == 0 ? "-1" : "#{digit}" * max

v=gets.to_i
a=gets.split.map(&:to_i)
b,c=a.each_with_index.to_a.min_by{|x,i|[x,-i]}
c+=1
d=v/b
(p -1;exit)if d==0
e=d*b
f=8
r=''
while true
  f-=1 while v-e+b<a[f]
  break if f==c-1
  r<<f+1
  v-=a[f]-b
  d-=1
end
r<<c.to_s*d
puts r

p = gets.strip.to_i
a = gets.strip.split.map(&:to_i)
a = (1..a.length).zip(a).sort_by{|d| [d[1], -d[0]]}
initp = p
can = false
while p > 0
  digit = a.select{|d| d[1] <= p}.first
  break if digit.nil?
  can = true
  p -= digit[1]
  printf("%d", digit[0])
end
if !can
  puts -1
else
  puts
end

p = gets.strip.to_i
a = gets.strip.split.map(&:to_i)
a = (1..a.length).zip(a).sort_by{|d| [d[1], -d[0]]}
initp = p
can = true
while p > 0
  digit = a.select{|d| d[1] <= p}.first
  if digit.nil? && p == initp
    can = false
    break
  end
  p -= digit[1]
  printf("%d", digit[0])
end
if can
  puts
else
  puts -1
end

p = gets.strip.to_i
a = gets.strip.split.map(&:to_i)
a = (1..a.length).zip(a).sort_by{|d| [d[1], -d[0]]}
initp = p
can = true
while p > 0
  digit = a.select{|d| d[1] <= p}.first
  if digit.nil? && p == initp
    can = false
    break
  end
  p -= digit[1]
  printf("%d", digit[0])
end
if !can || p == 0
  puts -1
else
  puts
end

v = STDIN.readline().to_i
@costs = STDIN.readline().split().collect(&:to_i)
@memo = {}

def solve(v)
  return -1 if v <= 0
  return @memo[v] if @memo[v]

  ret = 0
  @costs.each_with_index do |x, idx|
    if v >= x
      rest = solve(v - x) * 10
      ans = [0, rest].max + idx + 1
      ret = [ret, ans].max
    end
  end

  @memo[v] = ret
end

puts solve(v).to_s

v = STDIN.readline().to_i
@costs = STDIN.readline().split().collect(&:to_i)

#v = 1000000
#@costs = %w(1 1 1 1 1 1 1 1 1).collect(&:to_i)
#v = 898207
#@costs = %w(99745 99746 99748 99752 99760 99776 99808 99872 100000).collect(&:to_i)

def solve(v)
  x, xv = @costs.rindex(@costs.min), @costs.min
  @costs.collect! { |y| y - xv }
  n, r = v / xv, v % xv

  return -1 if n == 0

  while r > 0
    y = @costs.rindex {|y| y <= r}
    break if !y || @costs[y] == 0
    STDOUT.write(y + 1)
    r -= @costs[y]
    n -= 1
  end

  while n > 0
    STDOUT.write(x + 1)
    n -= 1
  end
end

solve v

v = STDIN.readline().to_i
@costs = STDIN.readline().split().collect(&:to_i)
#v = 5
#@costs = %w(5 4 3 2 1 2 3 4 5).collect(&:to_i)

def solve(v)
  x, xv = @costs.rindex(@costs.min), @costs.min
  @costs.collect! { |y| y - x }
  n, r = v / xv, v % xv

  return -1 if n == 0

  ans = []
  while r > 0
    y = @costs.rindex {|y| y <= x}
    break if !y || @costs[y] == 0
    ans << (y + 1)
    r -= @costs[y]
  end

  while ans.length < n
    ans << (x + 1)
  end

  ans.collect(&:to_s).join().to_i
end

puts solve(v).to_s

def iter1 t, arr, lh
	cnt = t/arr[0]
	digit = lh[arr[0]]
	arr[1..-1].each {|cl|
		ccnt = t/cl
		break if ccnt < cnt
		digit = lh[cl] if lh[cl] > digit
	}
	cnt == 0 ? -1 : digit
end

total = gets.to_i
a = gets.split(" ").map{|ai| ai.to_i}
ln = {}
a.each_index{|i| ln[a[i]] = i}
len = a.sort.uniq
res = []
while total>0
	cd = iter1(total, len, ln)
	break if cd == -1
	res << cd + 1
	total -= a[cd]
end

if res.size == 0
	print "-1"
else
	print res.sort.reverse.join
end

def iter t, arr
	mlen = 0
	digit = -1
	arr.each_index {|i|
		cml = t/arr[i]
		# digit weights are ordered from 1 to 9
		if cml >= mlen
			mlen = cml
			digit = i
		end
	}
	mlen == 0 ? -1 : digit
end

total = gets.to_i
a = gets.split(" ").map{|ai| ai.to_i}
exit if a.include?(0)
res = []
while total > 0
	cd = iter(total, a)
	break if cd == -1
	res << cd + 1
	total -= a[cd]
end

if res.size == 0
	print "-1"
else
	print res.sort.reverse.join
end


You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z".

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$.

Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$.

NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda".

n=gets.to_i
s=gets
i=(0...n).find{|i|s[i]>s[i+1]}
puts s[0,i]+s[i+1..-1].chomp


Dima got into number sequences. Now he's got sequence a1, a2, ..., an, consisting of n positive integers. Also, Dima has got a function f(x), which can be defined with the following recurrence:  f(0) = 0;  f(2·x) = f(x);  f(2·x + 1) = f(x) + 1. Dima wonders, how many pairs of indexes (i, j) (1 ≤ i < j ≤ n) are there, such that f(ai) = f(aj). Help him, count the number of such pairs.

The first line contains integer n (1 ≤ n ≤ 105). The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 109). The numbers in the lines are separated by single spaces.

In a single line print the answer to the problem. Please, don't use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample any pair (i, j) will do, so the answer is 3.In the second sample only pair (1, 2) will do.

def func(i)
  if i == 0
    0
  else
    func(i / 2) + i % 2
  end
end

def run
  n = ARGF.readline.to_i
  list = ARGF.readline.split.map(&:to_i)

  hash = Hash.new(0)
  list.each { |a| hash[func(a)] += 1 }

  cnt = 0
  hash.each do |key, val|
    cnt += (val * (val - 1)) / 2
  end

  puts cnt
end

run if $0 == __FILE__

def func(x)
  return 0 if x == 0
  return func(x / 2) if x % 2 == 0
  func(x / 2) + 1
end

n = gets.to_i
f = Array.new(100,0)
gets.split(' ').each { |i|
  f[func(i.to_i)] += 1
}
ans = 0
f.each { |i|
  j = i.to_i
  ans += j * (j - 1) / 2
}
p ans

def no_of_ones t
	p = 0
	while t>0
	  p += (t%2)
	  t = t/2
	end
	return p
end

n =gets.chomp.to_i
a = [0]*40
arr = gets.chomp.split(" ").collect! {|x| x.to_i}
arr.each { |k|
	a[no_of_ones(k)] += 1
}

s = 0
a.each { |p|
	s += (p*(p-1))/2
}

p s

def run
  n = ARGF.readline.to_i
  list = ARGF.readline.split.map(&:to_i)

  f = [0]
  1.upto(10 ** 5) {|i| f[i] = f[i / 2] + i % 2 }

  hash = Hash.new(0)
  list.each { |a| hash[f[a]] += 1 }

  cnt = 0
  hash.each do |key, val|
    cnt += (val * (val - 1)) / 2
  end

  puts cnt
end

run if $0 == __FILE__


A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count. The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to n clockwise and the child number 1 is holding the ball. First the first child throws the ball to the next one clockwise, i.e. to the child number 2. Then the child number 2 throws the ball to the next but one child, i.e. to the child number 4, then the fourth child throws the ball to the child that stands two children away from him, i.e. to the child number 7, then the ball is thrown to the child who stands 3 children away from the child number 7, then the ball is thrown to the child who stands 4 children away from the last one, and so on. It should be mentioned that when a ball is thrown it may pass the beginning of the circle. For example, if n = 5, then after the third throw the child number 2 has the ball again. Overall, n - 1 throws are made, and the game ends.The problem is that not all the children get the ball during the game. If a child doesn't get the ball, he gets very upset and cries until Natalia Pavlovna gives him a candy. That's why Natalia Pavlovna asks you to help her to identify the numbers of the children who will get the ball after each throw.

The first line contains integer n (2 ≤ n ≤ 100) which indicates the number of kids in the circle.

In the single line print n - 1 numbers which are the numbers of children who will get the ball after each throw. Separate the numbers by spaces.

n = gets.to_i
passer = 0
passed = []
(1...n).each do |i|
  passer += i
  passed << passer % n + 1
end
puts passed.join(" ")

n = gets.to_i

r = 1
res = []
1.upto(n-1) do |m|
 r += m
 r %= n
 r = n if r == 0
 res << r
 res << ' '
end
res.pop
res.each {|e| print e}

n = gets.to_i
i=1
(n-1).times{|x|i+=x;i%=n;i+=1;print i;print " "}

n=gets.to_i

c=[*1..n]
s=0
for i in 1..n-1
	s+=i
	if c[s].nil?
		print "#{c[s%n]} "
	else
		print "#{c[s]} "
	end
end

n = gets.to_i

curr = 0
result = ""
for i in 1..n-1
  curr = (curr + i) % n
  result += (curr+1).to_s + " "
end

puts(result)

n = gets.chomp.to_i

step = 1
last_child = 1
(n - 1).times do
  last_child += step
  step += 1
  ch = last_child % n
  print "#{ch == 0 ? n : ch} "
end
puts

n = gets.to_i

cur, step = 0, 0

(n - 1).times do
  step += 1
  cur = (cur + step) % n
  printf("%d ", cur + 1)
end

printf("\n")

n, c, str = gets.to_i, 1, ""
0.upto(n - 2) { |i| str << (c = ((c + i) % n) + 1).to_s << " " }
print str.chop

n = gets.chop.to_i
kids = Array.new
i = 0
a = 1
(n - 1).times do
  i += 1
  a += i
  (a > n)? a = a - n : a
  kids.push(a)
end

puts kids

n = gets.chop.to_i
i = 0
a = 1
(n - 1).times do
  i += 1
  a += i
  (a > n)? a = a - n : a
  print "#{a} "
end

n = gets.to_i
passer = 1
passed = []
(1...n).each do |i|
  passer = (passer + i) % n
  passed << passer
end
puts passed.join(" ")

n = gets.to_i

r = 1
res = []
1.upto(n-1) do |m|
 r += m
 r %= n
 res << r
 res << ' '
end
res.pop
res.each {|e| print e}

def f(n)
  l = [nil] * 5 + ['S','M','L','XL','XXL'] + [nil] * 5
  i = n+5
  r = []
  r << l[i]
  r << l[i+1]
  r << l[i-1]
  r << l[i+2]
  r << l[i-2]
  r << l[i+3]
  r << l[i-3]
  r << l[i+4]
  r << l[i-4]
  r << l[i+5]
  r << l[i-5]
  r.select {|e| e}
end

pr = []
l = ['S','M','L','XL','XXL']
1.upto(5) {|n| pr << f(n)}

a = gets.split(' ')
a = a.map{|e| e.to_i}

gets.to_i.times do
  size = gets.chomp
  tl = pr[l.index(size)]
  n = 0
  while a[l.index(tl[n])] == 0
    n += 1
  end
  a[l.index(tl[n])] -= 1
  puts tl[n]
end

n = gets.to_i

r = 1
1.upto(n-1) do |m|
 r += m
 r %= n
 print r," "
end

n=gets.to_i

man_id = 1
[*1..n-1].each do |v|
	man_id+=v

	rem=man_id%n
	rem+=1 if rem==0
	print "#{rem} "

	man_id=rem
end

n = gets.chomp.to_i
puts 2 or exit if n == 2
step = 1
last_child = 1
(n - 1).times do
  last_child += step
  step += 1
  print "#{last_child % n} "
end
puts

n, c, str = gets.to_i, 1, ""
1.upto(n - 1) { |i| str << (c = (c + i) % n).to_s << " " }
print str.chop

n, c, str = gets.to_i, 1, ""
1.upto(n - 1) do |i|
	c = (c + i) % n
	c = 4 if c == 0
	str << c.to_s << " "
end
print str.chop

n, c, str = gets.to_i, 0, ""
1.upto(n - 1) { |i| str << (c = (c + i) % n).to_s << " " }
print str.chop


During the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1).After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.

The first line contains integer n (2 ≤ n ≤ 2·105) — the number of students in the queue.  Then n lines follow, i-th line contains the pair of integers ai, bi (0 ≤ ai, bi ≤ 106), where ai is the ID number of a person in front of a student and bi is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist. The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order.

Print a sequence of n integers x1, x2, ..., xn — the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one.

NoteThe picture illustrates the queue for the first sample.

require 'set'
n = gets.to_i
a = Set.new
b = Set.new
map = Hash.new
(0...n).each do |i|
    aa, bb = gets.split.collect{|j| j.to_i}
    a.add(aa)
    b.add(bb)
    map[aa] = bb
end
ans = Array.new(n)
ans[0] = (a-b).to_a[0]
ans[1] = map[0]
for i in 2...n
    ans[i] = map[ans[i-2]]
end
puts ans.join(" ")

def get_array(hash, pos, array, ind)
  until pos.nil? or pos == 0
    array[ind] = pos
    pos = hash[pos]
    ind += 2
  end
end

n = gets.to_i
array = Array.new(n, 0)

prev = {}
for s in STDIN.each_line.take n
  p, n = s.split(' ').map &:to_i
  prev[p] = n
end

first = (prev.keys - prev.values)[0]
get_array(prev, first, array, 0)
get_array(prev, prev[0], array, 1)

puts array.join(" ")

def get_array(hash, pos)
  arr = []
  until pos.nil? or pos == 0
    arr << pos
    pos = hash[pos]
  end
  arr
end

n = gets.to_i

prev, after = {}, {}
for s in STDIN.each_line.take n
  p, n =s.split(' ').map &:to_i

  prev[p], after[n] = n, p
end

first = (prev.keys - after.keys)[0]
frs = get_array(prev, first)

scn = get_array(prev, prev[0])

puts frs.zip(scn).join(" ")

def get_array(hash, pos)
  arr = []
  until pos.nil? or pos == 0
    arr.push(pos)
    pos = hash[pos]
  end
  arr
end

n = gets.to_i

prev = {}
for s in STDIN.each_line.take n
  p, n = s.split(' ').map &:to_i
  prev[p] = n
end

first = (prev.keys - prev.values)[0]
frs = get_array(prev, first)
scn = get_array(prev, prev[0])

puts frs.zip(scn).join(" ")

def get_array(hash, pos)
  arr = []
  until pos.nil? or pos == 0
    arr << pos
    pos = hash[pos]
  end
  arr
end

n = gets.to_i

prev = {}
for s in STDIN.each_line.take n
  p, n =s.split(' ').map &:to_i

  prev[p] = n
end

first = (prev.keys - prev.values)[0]
frs = get_array(prev, first)

scn = get_array(prev, prev[0])

puts frs.zip(scn).join(" ")

n = gets.to_i
bef_s = {}
aft_s = {}

n.times do
  bef, aft = gets.split.map(&:to_i)
  bef_s[bef] = aft
  aft_s[aft] = bef
end

ans = []
start_id = 0
start_pos = 1
while true
  if bef_s[start_id] and start_pos < n
    ans[start_pos] = bef_s[start_id]
    start_id = bef_s[start_id]
    start_pos += 2
  else
    break
  end
end

bef_s.each_key do |k|
  is_break = false
  if !aft_s[k]
    start_id = k
    break
  end
end

ans[0] = start_id
start_pos = 2
while true
  if bef_s[start_id] and start_pos < n
    ans[start_pos] = bef_s[start_id]
    start_id = bef_s[start_id]
    start_pos += 2
  else
    break
  end
end

puts ans.join(' ')

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

def increment(i, a)
  i += 1
  i = 0 if a.length <= i
  i
end

n = gets.to_i

ans = Array.new(n, -1)
bef_s = []
aft_s = []
n.times do |i|
  bef, aft = gets.split.map(&:to_i)
  if (bef != 0 and aft != 0) and (!ans.index(bef) and !ans.index(aft))
    bef_s << bef
    aft_s << aft
    next
  else
    ans[1] = aft and next if bef == 0
    ans[-2] = bef and next if aft == 0

    if ans.index(bef)
      index = ans.index(bef)
      ans[index + 2] = aft
      next
    end

    if ans.index(aft)
      index = ans.index(aft)
      ans[index - 2] = bef
      next
    end
  end
end

formals = []
while 0 < bef_s.length
  bef = bef_s.shift
  aft = aft_s.shift

  if ans.index(bef)
    i = ans.index(bef)
    tmp_b = ans[0..(i + 1)]
    tmp_a = ans[(i + 2)..-1]
    tmp_a.unshift(aft)
    ans = tmp_b + tmp_a
    next
  end

  if ans.index(aft)
    i = ans.index(aft)
    tmp_b = nil
    tmp_a = nil
    if 0 <= i - 2
      tmp_b = ans[0..(i - 2)]
      tmp_a = ans[(i - 1)..-1]
      tmp_a.unshift(bef)
      ans = tmp_b + tmp_a
    else
      ans.unshift(bef)
    end
    next
  end

  if formals.length == 0
    formals << bef
    formals << aft
    next
  end

  if formals.index(bef)
    i = formals.index(bef)
    if i + 2 < formals.length
      tmp_b = formals[0..(i + 1)]
      tmp_a = formals[(i + 2)..-1]
      tmp_a.unshift(aft)
      formals = tmp_b + tmp_a
    else
      formals << aft
    end
    next
  end

  if formals.index(aft)
    i = formals.index(aft)
    tmp_b = nil
    tmp_a = nil
    if 0 <= i - 2
      tmp_b = formals[0..(i - 2)]
      tmp_a = formals[(i - 1)..-1]
      tmp_a.unshift(bef)
      formals = tmp_b + tmp_a
    else
      formals.unshift(bef)
    end
    next
  end

  bef_s << bef
  aft_s << aft
end

formals.each do |i|
  if ans.index(-1) and !ans.index(i)
    index = ans.index(-1)
    puts "#{ans}"
    ans[index] = i
  end
end

puts ans.uniq.select {|i| i != -1}.join(' ')

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

def increment(i, a)
  i += 1
  i = 0 if a.length <= i
  i
end

n = gets.to_i

ans = Array.new(n, -1)
bef_s = []
aft_s = []
n.times do |i|
  bef, aft = gets.split.map(&:to_i)
  if (bef != 0 and aft != 0) and (!ans.index(bef) and !ans.index(aft))
    bef_s << bef
    aft_s << aft
    next
  else
    ans[1] = aft and next if bef == 0
    ans[-2] = bef and next if aft == 0

    if ans.index(bef)
      index = ans.index(bef)
      ans[index + 2] = aft
      next
    end

    if ans.index(aft)
      index = ans.index(aft)
      ans[index - 2] = bef
      next
    end
  end
end

formals = []
while 0 < bef_s.length
  bef = bef_s.shift
  aft = aft_s.shift

  if ans.index(bef)
    i = ans.index(bef)
    tmp_b = ans[0..(i + 1)]
    tmp_a = ans[(i + 2)..-1]
    tmp_a.unshift(aft)
    ans = tmp_b + tmp_a
    next
  end

  if ans.index(aft)
    i = ans.index(aft)
    tmp_b = nil
    tmp_a = nil
    if 0 <= i - 2
      tmp_b = ans[0..(i - 2)]
      tmp_a = ans[(i - 1)..-1]
      tmp_a.unshift(bef)
      ans = tmp_b + tmp_a
    else
      ans.unshift(bef)
    end
    next
  end

  if formals.length == 0
    formals << bef
    formals << aft
    next
  end

  if formals.index(bef)
    i = formals.index(bef)
    if i + 2 < formals.length
      tmp_b = formals[0..(i + 1)]
      tmp_a = formals[(i + 2)..-1]
      tmp_a.unshift(aft)
      formals = tmp_b + tmp_a
    else
      formals << aft
    end
    next
  end

  if formals.index(aft)
    i = formals.index(aft)
    tmp_b = nil
    tmp_a = nil
    if 0 <= i - 2
      tmp_b = formals[0..(i - 2)]
      tmp_a = formals[(i - 1)..-1]
      tmp_a.unshift(bef)
      formals = tmp_b + tmp_a
    else
      formals.unshift(bef)
    end
    next
  end

  bef_s << bef
  aft_s << aft
end

formals.each do |i|
  if ans.index(-1) and !ans.index(i)
    index = ans.index(-1)
    ans[index] = i
  end
end

puts ans.select {|i| i != -1}.join(' ')

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

def increment(i, a)
  i += 1
  i = 0 if a.length <= i
  i
end

n = gets.to_i

ans = Array.new(n, -1)
bef_s = []
aft_s = []
n.times do |i|
  bef, aft = gets.split.map(&:to_i)
  if (bef != 0 and aft != 0) and (!ans.index(bef) and !ans.index(aft))
    bef_s << bef
    aft_s << aft
    next
  else
    ans[1] = aft and next if bef == 0
    ans[-2] = bef and next if aft == 0

    if ans.index(bef)
      index = ans.index(bef)
      ans[index + 2] = aft
      next
    end

    if ans.index(aft)
      index = ans.index(aft)
      ans[index - 2] = bef
      next
    end
  end
end

formals = []
while 0 < bef_s.length
  bef = bef_s.shift
  aft = aft_s.shift

  if ans.index(bef)
    i = ans.index(bef)
    tmp_b = ans[0..(i + 1)]
    tmp_a = ans[(i + 2)..-1]
    tmp_a.unshift(aft)
    ans = tmp_b + tmp_a
    next
  end

  if ans.index(aft)
    i = ans.index(aft)
    tmp_b = nil
    tmp_a = nil
    if 0 <= i - 2
      tmp_b = ans[0..(i - 2)]
      tmp_a = ans[(i - 1)..-1]
      tmp_a.unshift(bef)
      ans = tmp_b + tmp_a
    else
      ans.unshift(bef)
    end
    next
  end

  if formals.length == 0
    formals << bef
    formals << aft
    next
  end

  if formals.index(bef)
    i = formals.index(bef)
    if i + 2 < formals.length
      tmp_b = formals[0..(i + 1)]
      tmp_a = formals[(i + 2)..-1]
      tmp_a.unshift(aft)
      formals = tmp_b + tmp_a
    else
      formals << aft
    end
    next
  end

  if formals.index(aft)
    i = formals.index(aft)
    tmp_b = nil
    tmp_a = nil
    if 0 <= i - 2
      tmp_b = formals[0..(i - 2)]
      tmp_a = formals[(i - 1)..-1]
      tmp_a.unshift(bef)
      formals = tmp_b + tmp_a
    else
      formals.unshift(bef)
    end
    next
  end

  bef_s << bef
  aft_s << aft
end

puts "ans: #{ans}, formals: #{formals}"
formals.each do |i|
  if ans.index(-1) and !ans.index(i)
    index = ans.index(-1)
    ans[index] = i
  end
end

puts ans.select {|i| i != -1}.join(' ')

def find_pos(arr, pos, reverse = false)
  p = reverse ? 1 : 0

  arr.each_with_index do |x, i|
    if pos == x[p]
      return i
    end
  end

  -1
end

n = gets.to_i

arr = []
for s in STDIN.each_line.take n
  i, j = s.split(" ").map &:to_i

  arr << [i, j]
end

pos, start = 1, 0
result = Array.new(n, 0)
while pos < n
  p = find_pos(arr, start)

  if p != -1
    result[pos] = arr[p][1]
    start = arr[p][1]
    pos += 2
  else
    break
  end
end

pos = arr.length - 2
start = 0
while pos < n
  p = find_pos(arr, start, true)

  if p != -1
    result[pos] = arr[p][0]
    start = arr[p][0]
    pos -= 2
  else
    break
  end

end

puts result.inspect

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

def increment(i, a)
  i += 1
  i = 0 if a.length <= i
  i
end

n = gets.to_i

ans = Array.new(n, -1)
bef_s = []
aft_s = []
n.times do |i|
  bef, aft = gets.split.map(&:to_i)
  if (bef != 0 and aft != 0) and (!ans.index(bef) and !ans.index(aft))
    bef_s << bef
    aft_s << aft
    next
  else
    ans[1] = aft and next if bef == 0
    ans[-2] = bef and next if aft == 0

    if ans.index(bef)
      index = ans.index(bef)
      ans[index + 2] = aft
      next
    end

    if ans.index(aft)
      index = ans.index(aft)
      ans[index - 2] = bef
      next
    end
  end
end

formals = []
while 0 < bef_s.length
  bef = bef_s.shift
  aft = aft_s.shift

  if formals.length == 0
    formals << bef
    formals << aft
    next
  end

  if formals.index(bef)
    i = formals.index(bef)
    tmp_b = formals[0..(i + 1)]
    tmp_a = formals[(i + 2)..-1]
    tmp_a.unshift(aft)
    formals = tmp_b + tmp_a
    next
  end

  if formals.index(aft)
    i = formals.index(aft)
    tmp_b = nil
    tmp_a = nil
    if 0 <= i - 2
      tmp_b = formals[0..(i - 2)]
      tmp_a = formals[(i - 1)..-1]
      tmp_a.unshift(bef)
      formals = tmp_b + tmp_a
    else
      formals.unshift(bef)
    end
    next
  end
  bef_s << bef
  aft_s << aft
end

formals.each do |i|
  if ans.index(-1)
    index = ans.index(-1)
    ans[index] = i
  end
end

puts ans.join(' ')

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

def increment(i, a)
  i += 1
  i = 0 if a.length <= i
  i
end

n = gets.to_i

ans = Array.new(n, -1)
bef_s = []
aft_s = []
n.times do |i|
  bef, aft = gets.split.map(&:to_i)
  if (bef != 0 and aft != 0) and (!ans.index(bef) and !ans.index(aft))
    bef_s << bef
    aft_s << aft
    next
  else
    ans[1] = aft and next if bef == 0
    ans[-2] = bef and next if aft == 0

    if ans.index(bef)
      index = ans.index(bef)
      ans[index + 2] = aft
      next
    end

    if ans.index(aft)
      index = ans.index(aft)
      ans[index - 2] = bef
      next
    end
  end
end

formals = []
while 0 < bef_s.length
  bef = bef_s.shift
  aft = aft_s.shift

  if ans.index(bef)
    i = ans.index(bef)
    tmp_b = ans[0..(i + 1)]
    tmp_a = ans[(i + 2)..-1]
    tmp_a.unshift(aft)
    ans = tmp_b + tmp_a
    next
  end

  if ans.index(aft)
    i = ans.index(aft)
    tmp_b = nil
    tmp_a = nil
    if 0 <= i - 2
      tmp_b = ans[0..(i - 2)]
      tmp_a = ans[(i - 1)..-1]
      tmp_a.unshift(bef)
      ans = tmp_b + tmp_a
    else
      ans.unshift(bef)
    end
    next
  end

  if formals.length == 0
    formals << bef
    formals << aft
    next
  end

  if formals.index(bef)
    i = formals.index(bef)
    if i + 2 < formals.length
      tmp_b = formals[0..(i + 1)]
      tmp_a = formals[(i + 2)..-1]
      tmp_a.unshift(aft)
      formals = tmp_b + tmp_a
    else
      formals << aft
    end
    next
  end

  if formals.index(aft)
    i = formals.index(aft)
    tmp_b = nil
    tmp_a = nil
    if 0 <= i - 2
      tmp_b = formals[0..(i - 2)]
      tmp_a = formals[(i - 1)..-1]
      tmp_a.unshift(bef)
      formals = tmp_b + tmp_a
    else
      formals.unshift(bef)
    end
    next
  end

  bef_s << bef
  aft_s << aft
end

formals.each do |i|
  if ans.index(-1) and !ans.index(i)
    index = ans.index(-1)
    ans[index] = i
  end
end

puts ans.uniq.select {|i| i != -1}.join(' ')


A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees.He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one.It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum.

The first line of input contains the number of students n (2 ≤ n ≤ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks.

Output consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one.

class Fairness
    def initialize(num_students, directions)
        @num_students = num_students
        @directions = directions
        @toffees = (1..num_students).map { 1 }
    end

    def solve
        @directions.each_with_index { |direction, index| reward direction, index }
        reversed.each { |index| reward @directions[index], index }
    end

    def display
        @toffees.each {|n| print "#{n} "}
        print "\n"
    end

    private

    def reward(direction, index)
        reward_left(index)  if direction == 'L'
        reward_right(index) if direction == 'R'
        equalize(index)     if direction == '='
    end

    def reward_left(index)
        while @toffees[index] <= @toffees[index+1]
            @toffees[index] += 1
        end
    end

    def reward_right(index)
        while @toffees[index+1] <= @toffees[index]
            @toffees[index+1] += 1
        end
    end

    def equalize(index)
        max = [@toffees[index], @toffees[index+1]].max
        @toffees[index] = max
        @toffees[index+1] = max
    end

    def reversed
        (0...@directions.length).to_a.reverse
    end
end

fair = Fairness.new(gets.chomp.to_i, gets.chomp.split(""))
fair.solve()
fair.display()

n = gets.to_i
a = []
s = gets.chomp
(0...n).each { |i|
    l = r = 1
    j = i - 1
    while j < n - 2 && s[j += 1] != 'R'
        l += 1 if s[j] == 'L'
    end
    j = i
    while j > 0 && s[j -= 1] != 'L'
        r += 1 if s[j] == 'R'
    end
    a << [l, r].max
}
puts a.join(' ')

n = gets.to_i
a = []
s = gets.chomp
(0...n).each { |i|
    l = r = 1
    (i..n-2).each { |j|
        break if s[j] == 'R'
        l += 1 if s[j] == 'L'
    }
    (i-1).downto(0) { |j|
        break if s[j] == 'L'
        r += 1 if s[j] == 'R'
    }
    a << [l, r].max
}
puts a.join(' ')

n = gets.to_i
s = gets
a = []
for i in 0...n
    l = r = 1
    j = i - 1
    while j < n - 2 && s[j += 1] != 'R'
        l += s[j].ord / 70
    end
    j = i
    while j > 0 && s[j -= 1] != 'L'
        r += s[j].ord / 70
    end
    a << [l, r].max
end
puts a.join(' ')

class Fairness
    def initialize(num_students, directions)
        @num_students = num_students
        @directions = directions
        @toffees = (1..num_students).map { 1 }
    end

    def solve
        @directions.each_with_index do |direction, index|
            reward_left(index)  if direction == 'L'
            reward_right(index) if direction == 'R'
            equalize(index)     if direction == '='
        end

        @toffees.each do |toffee|
            print "#{toffee} "
        end
        print "\n"
    end

    def reward_left(index)
        while @toffees[index] <= @toffees[index+1]
            @toffees[index] += 1
        end
    end

    def reward_right(index)
        while @toffees[index+1] <= @toffees[index]
            @toffees[index+1] += 1
        end
    end

    def equalize(index)
        max = [@toffees[index], @toffees[index+1]].max
        @toffees[index] = max
        @toffees[index+1] = max
    end
end

fair = Fairness.new(gets.chomp.to_i, gets.chomp.split(""))
fair.solve()

gets
t = 1
a = [1]
gets.chomp.each_byte { |c|
    t += (c - 79) / 3 if c != 61
    a << t
}
t = a.min - 1
puts a.map{|x| x - t}.join(' ')

n = gets.to_i
a = []
s = gets.chomp
(0...n).each { |i|
    l = r = 1
    j = i - 1
    while j < n - 3 && s[j += 1] != 'R'
        l += 1 if s[j] == 'L'
    end
    j = i
    while j > 1 && s[j -= 1] != 'L'
        r += 1 if s[j] == 'R'
    end
    a << [l, r].max
}
puts a.join(' ')


They say "years are like dominoes, tumbling one after the other". But would a year fit into a grid? I don't think so.Limak is a little polar bear who loves to play. He has recently got a rectangular grid with h rows and w columns. Each cell is a square, either empty (denoted by '.') or forbidden (denoted by '#'). Rows are numbered 1 through h from top to bottom. Columns are numbered 1 through w from left to right.Also, Limak has a single domino. He wants to put it somewhere in a grid. A domino will occupy exactly two adjacent cells, located either in one row or in one column. Both adjacent cells must be empty and must be inside a grid.Limak needs more fun and thus he is going to consider some queries. In each query he chooses some rectangle and wonders, how many way are there to put a single domino inside of the chosen rectangle?

The first line of the input contains two integers h and w (1 ≤ h, w ≤ 500) – the number of rows and the number of columns, respectively. The next h lines describe a grid. Each line contains a string of the length w. Each character is either '.' or '#' — denoting an empty or forbidden cell, respectively. The next line contains a single integer q (1 ≤ q ≤ 100 000) — the number of queries. Each of the next q lines contains four integers r1i, c1i, r2i, c2i (1 ≤ r1i ≤ r2i ≤ h, 1 ≤ c1i ≤ c2i ≤ w) — the i-th query. Numbers r1i and c1i denote the row and the column (respectively) of the upper left cell of the rectangle. Numbers r2i and c2i denote the row and the column (respectively) of the bottom right cell of the rectangle.

Print q integers, i-th should be equal to the number of ways to put a single domino inside the i-th rectangle.

NoteA red frame below corresponds to the first query of the first sample. A domino can be placed in 4 possible ways.

h, w = gets.chomp.split.map(&:to_i)
board = []
h.times do
  board << gets.chomp
end

rs = Array.new(h).map {Array.new(w, 0)}
for r in 0...h
  cnt = 0
  for c in 1...w
    cnt += 1 if board[r][c] == '.' && board[r][c - 1] == '.'
    rs[r][c] = cnt
    rs[r][c] += rs[r - 1][c] if 0 < r
  end
end

cs = Array.new(h).map {Array.new(w, 0)}
for c in 0...w
  cnt = 0
  for r in 1...h
    cnt += 1 if board[r][c] == '.' && board[r - 1][c] == '.'
    cs[r][c] = cnt
    cs[r][c] += cs[r][c - 1] if 0 < c
  end
end

q = gets.chomp.to_i
q.times do
  cnt = 0
  r1, c1, r2, c2 = gets.chomp.split.map { |x| x.to_i - 1 }
  cnt += rs[r2][c2]
  cnt += rs[r1 - 1][c1] if 0 < r1
  cnt -= rs[r1 - 1][c2] if 0 < r1
  cnt -= rs[r2][c1]

  cnt += cs[r2][c2]
  cnt += cs[r1][c1 - 1] if 0 < c1
  cnt -= cs[r1][c2]
  cnt -= cs[r2][c1 - 1] if 0 < c1
  puts cnt
end


The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil").However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere.For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print "Still Rozdil", if he stays in Rozdil.

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of cities. The next line contains n integers, separated by single spaces: the i-th integer represents the time needed to go from town Rozdil to the i-th town. The time values are positive integers, not exceeding 109. You can consider the cities numbered from 1 to n, inclusive. Rozdil is not among the numbered cities.

Print the answer on a single line — the number of the town the Little Elephant will go to. If there are multiple cities with minimum travel time, print "Still Rozdil" (without the quotes).

NoteIn the first sample there are only two cities where the Little Elephant can go. The travel time for the first town equals 7, to the second one — 4. The town which is closest to Rodzil (the only one) is the second one, so the answer is 2.In the second sample the closest cities are cities two and five, the travelling time to both of them equals 4, so the answer is "Still Rozdil".

gets
a=gets.split.map &:to_i
puts(a.count(m=a.min)>1?"Still Rozdil":1+a.index(m))

n = gets.to_i
a = gets.split.map(&:to_i)
m = a.min
f = (0...n).find_all{|x| a[x]==m}
if f.size == 1
  puts f[0] + 1
else
  puts "Still Rozdil"
end

n = gets.to_i
a = gets.split.map(&:to_i)
if a.count(a.min)>1
  puts "Still Rozdil"
else
  puts a.index(a.min)+1
end

gets
a = gets.split.map { |i| i.to_i }
puts a.count(a.min) == 1 ? a.index(a.min) + 1 : "Still Rozdil"

gets
a=gets.split.map &:to_i
m=a.min
puts a.count(m)>1 ? "Still Rozdil" : a.index(m)+1

n = gets.to_i

city = gets.split.map{|i| i.to_i}

min = 10**9 + 1
i = -1
t = false
n.times do |k|
    if city[k] < min then
        min = city[k]
        t = false
        i = k
    elsif city[k] == min then
        t = true
    end
end

if t then
    puts "Still Rozdil"
else
    puts i+1
end

gets
a = gets.split.map &:to_i
m = a.min
i = a.index m
j = a.rindex m
puts (i != j ? "Still Rozdil" : i+1)

n = gets.chomp.to_i
times = gets.chomp.split(" ").map{|e| e.to_i}

min = times.min
if times.count(min) == 1
  puts times.index(min) + 1
else
  puts "Still Rozdil"
end

num_cities = gets
distances = gets.split.collect {|i| i.to_i}
min_distance = distances.min
num_occured = distances.count(min_distance)
if num_occured == 1
	puts distances.index(min_distance) + 1
else
	puts "Still Rozdil"
end

#!/usr/bin/ruby

num_entries = gets.to_i

line = gets

numbers = line.split(' ')
numbers.map! { |e| e.to_i}
min = numbers.min
counter = 0
numbers.each { |n|
  if(n == min) then
    counter += 1
  end
}

if (counter > 1) then
  puts "Still Rozdil"
else
  puts numbers.index(min) + 1
end

n = gets.to_i

city = gets.split.map{|i| i.to_i}

min = 10**5
i = -1
t = false
n.times do |k|
    if city[k] < min then
        min = city[k]
        t = false
        i = k
    elsif city[k] == min then
        t = true
    end
end

if t then
    puts "Still Rozdil"
else
    puts i+1
end

num_cities = gets
distances = gets.split.collect {|i| i.to_i}
min_distance = distances.min
num_occured = distances.count(min_distance)
if num_occured == 1
	puts min_distance.to_s
else
	puts "Still Rozdil"
end


Madoka finally found the administrator password for her computer. Her father is a well-known popularizer of mathematics, so the password is the answer to the following problem.Find the maximum decimal number without zeroes and with no equal digits in a row, such that the sum of its digits is $$$n$$$.Madoka is too tired of math to solve it herself, so help her to solve this problem!

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Description of the test cases follows. The only line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the required sum of the digits.

For each test case print the maximum number you can obtain.

NoteThe only numbers with the sum of digits equal to $$$2$$$ without zeros are $$$2$$$ and $$$11$$$. But the last one has two ones in a row, so it's not valid. That's why the answer is $$$2$$$.The only numbers with the sum of digits equal to $$$3$$$ without zeros are $$$111$$$, $$$12$$$, $$$21$$$, and $$$3$$$. The first one has $$$2$$$ ones in a row, so it's not valid. So the maximum valid number is $$$21$$$.The only numbers with the sum of digits equals to $$$4$$$ without zeros are $$$1111$$$, $$$211$$$, $$$121$$$, $$$112$$$, $$$13$$$, $$$31$$$, $$$22$$$, and $$$4$$$. Numbers $$$1111$$$, $$$211$$$, $$$112$$$, $$$22$$$ aren't valid, because they have some identical digits in a row. So the maximum valid number is $$$121$$$.


You are an upcoming movie director, and you have just released your first movie. You have also launched a simple review site with two buttons to press — upvote and downvote.However, the site is not so simple on the inside. There are two servers, each with its separate counts for the upvotes and the downvotes.$$$n$$$ reviewers enter the site one by one. Each reviewer is one of the following types:   type $$$1$$$: a reviewer has watched the movie, and they like it — they press the upvote button;  type $$$2$$$: a reviewer has watched the movie, and they dislike it — they press the downvote button;  type $$$3$$$: a reviewer hasn't watched the movie — they look at the current number of upvotes and downvotes of the movie on the server they are in and decide what button to press. If there are more downvotes than upvotes, then a reviewer downvotes the movie. Otherwise, they upvote the movie. Each reviewer votes on the movie exactly once.Since you have two servers, you can actually manipulate the votes so that your movie gets as many upvotes as possible. When a reviewer enters a site, you know their type, and you can send them either to the first server or to the second one.What is the maximum total number of upvotes you can gather over both servers if you decide which server to send each reviewer to?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of reviewers. The second line of each testcase contains $$$n$$$ integers $$$r_1, r_2, \dots, r_n$$$ ($$$1 \le r_i \le 3$$$) — the types of the reviewers in the same order they enter the site.

For each testcase print a single integer — the maximum total number of upvotes you can gather over both servers if you decide which server to send each reviewer to.

NoteIn the first testcase of the example you can send the only reviewer to either of the servers — they'll downvote anyway. The movie won't receive any upvotes.In the second testcase of the example you can send all reviewers to the first server:   the first reviewer upvotes;  the second reviewer downvotes;  the last reviewer sees that the number of downvotes is not greater than the number of upvotes — upvote themselves. There are two upvotes in total. Alternatevely, you can send the first and the second reviewers to the first server and the last reviewer — to the second server:   the first reviewer upvotes on the first server;  the second reviewer downvotes on the first server;  the last reviewer sees no upvotes or downvotes on the second server — upvote themselves.

t = gets.strip.to_i
t.times do
	n = gets.strip.to_i
	r = gets.strip.split.map(&:to_i)
	up_votes = ans = 0
	n.times do |i|
		current = r[i]
		ans += 1 if current == 1 || current == 3
	end
	puts ans
end

t = gets.to_s.to_i

1.upto(t) do |casenum|
  n = gets.to_s.split.map {|x| x.to_i }
  ar = gets.to_s.split.map {|x| x.to_i }

  vn = 0
  vp = 0

  ar.each do |r|
    if r == 1
      vp += 1
    elsif r == 2
      vn -= 1
    else
      vp += 1
    end
  end

  printf("%d\n", vp)
end