Sereja is a coder and he likes to take part in Codesorfes rounds. However, Uzhland doesn't have good internet connection, so Sereja sometimes skips rounds.Codesorfes has rounds of two types: Div1 (for advanced coders) and Div2 (for beginner coders). Two rounds, Div1 and Div2, can go simultaneously, (Div1 round cannot be held without Div2) in all other cases the rounds don't overlap in time. Each round has a unique identifier — a positive integer. The rounds are sequentially (without gaps) numbered with identifiers by the starting time of the round. The identifiers of rounds that are run simultaneously are different by one, also the identifier of the Div1 round is always greater.Sereja is a beginner coder, so he can take part only in rounds of Div2 type. At the moment he is taking part in a Div2 round, its identifier equals to x. Sereja remembers very well that he has taken part in exactly k rounds before this round. Also, he remembers all identifiers of the rounds he has taken part in and all identifiers of the rounds that went simultaneously with them. Sereja doesn't remember anything about the rounds he missed.Sereja is wondering: what minimum and what maximum number of Div2 rounds could he have missed? Help him find these two numbers.

The first line contains two integers: x (1 ≤ x ≤ 4000) — the round Sereja is taking part in today, and k (0 ≤ k < 4000) — the number of rounds he took part in. Next k lines contain the descriptions of the rounds that Sereja took part in before. If Sereja took part in one of two simultaneous rounds, the corresponding line looks like: "1 num2 num1" (where num2 is the identifier of this Div2 round, num1 is the identifier of the Div1 round). It is guaranteed that num1 - num2 = 1. If Sereja took part in a usual Div2 round, then the corresponding line looks like: "2 num" (where num is the identifier of this Div2 round). It is guaranteed that the identifiers of all given rounds are less than x.

Print in a single line two integers — the minimum and the maximum number of rounds that Sereja could have missed.

NoteIn the second sample we have unused identifiers of rounds 1, 6, 7. The minimum number of rounds Sereja could have missed equals to 2. In this case, the round with the identifier 1 will be a usual Div2 round and the round with identifier 6 will be synchronous with the Div1 round. The maximum number of rounds equals 3. In this case all unused identifiers belong to usual Div2 rounds.

x, k = gets.split.map(&:to_i)
c_min, c_max = 0
x -= 1
was = [false] * x
was[x] = true
for i in 1..k
  d = gets.split.map(&:to_i)
  for j in 1..d.length-1
    was[d[j] - 1] = true
  end
end
c_max = was.count { |x| not x }
i = 0
while i < x
  if not was[i]
    was[i] = was[i + 1] = true
    c_min += 1
  end
  i += 1
end
puts "#{c_min} #{c_max}"

class ProblemA
  def initialize
    @dats = STDIN.read.split("\n")
    @current_round_iden, @num_of_took_rounds = @dats[0].split(" ").map{|x| x.to_i}
  end

  def solve
    if @num_of_took_rounds == 0
      max = @current_round_iden-1
      min = @current_round_iden % 2 == 0 ? @current_round_iden / 2 : (@current_round_iden) / 2
    else

      @unused_indentifiers = []
      @remember_rounds = []
      (1..@dats.length-1).each do |line_num|
        line = @dats[line_num]
        line = line.split(" ")
        line.shift
        line.each { |elem| @remember_rounds.push(elem.to_i) }
      end

      (@current_round_iden-1).downto(1) do |elem|
        @unused_indentifiers.push(elem) if not @remember_rounds.include?(elem)
      end

      min = find_min_possible(@unused_indentifiers)
      max = find_max_possible(@unused_indentifiers)
    end
    print "#{min} #{max}"
  end

  def find_min_possible(indentifier_array)
    ret = 0
    idx = 0
    indentifier_array.sort!

    while idx < indentifier_array.length
      if idx == indentifier_array.length - 1
        ret += 1
        return ret
      elsif indentifier_array[idx+1] == indentifier_array[idx]+1
        ret += 1
        idx += 2
      else
        ret += 1
        idx += 1
      end
    end
    return ret
  end

  def find_max_possible(indentifier_array)
    indentifier_array.length
  end
end

solver = ProblemA.new
solver.solve

def rsm(&block)
   readline.split.map{|i| block.yield(i)}
end

def rsmi
   rsm {|i| i.to_i}
end

x, k = rsmi
a = Array.new(x - 1, 0)
k.times {
   r = rsmi
   t, x = r[0], r[1]
   a[x - 1] = 2
   if t == 1
      y = r[2]
      a[y - 1] = 1
   end

}

s1 = a.count {|i| i == 0}
s2 = 0
a.length.times { |i|
   if a[i] == 0
      s2 += 1
      a[i] = 2
      if i + 1 < a.length
         a[i + 1] = 1 if a[i + 1] == 0
      end
   end
}
printf("%d %d", s2, s1)

n,k = gets.chomp!.split.map { |e|  e.to_i}

A = Array.new(n) { |i|  0}

k.times {
   c,d1,d2 =  gets.chomp!.split.map { |e|  e.to_i}
   A[d1-1] = 1
   if d2 != nil
     A[d2-1] = 1
   end
}

mx=0
mi=0
cur=0
(n-1).times do |i|
   if A[i] == 0
        cur += 1
   else
       mx += cur
       mi += (cur+1)/2
       cur = 0
   end
end

mx += cur
mi += (cur+1)/2

puts "#{mi} #{mx}"

x, k = gets.split.collect{|i| i.to_i}
mark = Array.new(x-1,0)
(1..k).each do
    tmp = gets.split.collect{|i| i.to_i}
    mark[tmp[1]-1] = 1
    mark[tmp[2]-1] = 1 if tmp.size == 3
end
maxans = mark.count(0)
minans = maxans
tmp = 1
while tmp < x
    if mark[tmp] == 0 and mark[tmp-1] == 0
        minans -= 1
        tmp += 1
    end
    tmp += 1
end
print minans, " ", maxans, "\n"

def get_pair_num(diff_ary,pair_num)
	if diff_ary.empty?
		return pair_num
	else
		if diff_ary.length > 1
			if (diff_ary[0] == diff_ary[1] - 1)
				diff_ary.delete_at(0)
				diff_ary.delete_at(0)
				return get_pair_num(diff_ary,pair_num+1)
			else
				diff_ary.shift
				return get_pair_num(diff_ary,pair_num)
			end
		end
		return pair_num
	end
end

def check_diff(id_ary,max_id)
	pair_num = 0
	full_ary = []
	for i in 1..max_id
		full_ary << i
	end
	diff_ary = full_ary - id_ary
	diff_ary.sort!
	pair_num = get_pair_num(diff_ary.clone, 0)
	max_num = diff_ary.length
	min_num = diff_ary.length - pair_num

	return [min_num, max_num]

end

first_line = (gets()).split()
current_id = (first_line.shift).to_i
part_in_num = (first_line.pop).to_i
id_ary = []
for i in 1..part_in_num
	ary = []
	(gets().split).each { |e| ary << e.to_i }
	ary.shift
	ary.each { |e| id_ary << e }
end
result = check_diff(id_ary, current_id-1)
puts result[0].to_s + " " + result[1].to_s

def solve(x, a)
  ids = Array.new(x + 1, false)
  a.each { |id|
    ids[id[1]] = true
    ids[id[2]] = true if id[0] == 1
  }
  ids[x] = true

  div1 = div2 = 0
  i = 1
  while i < x
    unless ids[i]
      if ids[i + 1]
        div2 += 1
      else
        div1 += 1
        i += 1
      end
    end
    i += 1
  end
  [div1 + div2, div1 * 2 + div2]
end

def read_next_line
  gets.chomp.split.map(&:to_i)
end

if __FILE__ == $0
  x, k = read_next_line
  a = (0...k).map { read_next_line }
  puts solve(x, a) * ' '
end

#f = File.open('test1.txt', 'r')
f = STDIN
x, k = f.gets.chomp.split.map(&:to_i)
a = Array.new(x, false)
a[0] = true
k.times do
  tmp = f.gets.chomp.split.map(&:to_i)
  if tmp[0] == 1
    a[tmp[1]], a[tmp[2]] = true
  else
    a[tmp[1]] = true
  end
end
maximum = a.count false
minimum = 0
(0...x).each do |i|
  if a[i] == false
    minimum += 1
    a[i+1] = true
  end
end
puts "#{minimum} #{maximum}"

class ProblemA
  def initialize
    @dats = STDIN.read.split("\n")
    @current_round_iden, @num_of_took_rounds = @dats[0].split(" ").map{|x| x.to_i}
  end

  def solve
    if @num_of_took_rounds == 0
      max = @current_round_iden-1
      min = @current_round_iden % 2 == 0 ? @current_round_iden / 2 : @current_round_iden / 2 + 1
    else

      @unused_indentifiers = []
      @remember_rounds = []
      (1..@dats.length-1).each do |line_num|
        line = @dats[line_num]
        line = line.split(" ")
        line.shift
        line.each { |elem| @remember_rounds.push(elem.to_i) }
      end

      (@current_round_iden-1).downto(1) do |elem|
        @unused_indentifiers.push(elem) if not @remember_rounds.include?(elem)
      end

      min = find_min_possible(@unused_indentifiers)
      max = find_max_possible(@unused_indentifiers)
    end
    print "#{min} #{max}"
  end

  def find_min_possible(indentifier_array)
    ret = 0
    idx = 0
    indentifier_array.sort!

    while idx < indentifier_array.length
      if idx == indentifier_array.length - 1
        ret += 1
      end
      if indentifier_array[idx+1] == indentifier_array[idx]+1
        ret += 1
        idx += 2
      else
        ret += 1
        idx += 1
      end
    end
    return ret
  end

  def find_max_possible(indentifier_array)
    indentifier_array.length
  end
end

solver = ProblemA.new
solver.solve

class ProblemA
  def initialize
    @dats = STDIN.read.split("\n")
    @cards_num, @max_abs = @dats[0].split(" ").map{|x| x.to_i}
    @cards = @dats[1].split(" ").map{|x| x.to_i}
  end

  def solve
    sum = @cards.inject(:+).abs
    return 1 if sum <= @max_abs
    return 0 if @max_abs == 0

    count_ret = 0
    (@max_abs-1).downto(1) do |elem|
      if sum >= elem
        count_ret += 1
        sum -= elem
      elsif sum == 1
        return count_ret+1
      elsif sum == 0
        return count_ret
      end
    end
    return count_ret
  end
end

solver = ProblemA.new
p solver.solve

class ProblemA
  def initialize
    @dats = STDIN.read.split("\n")
    @current_round_iden, @num_of_took_rounds = @dats[0].split(" ").map{|x| x.to_i}
  end

  def solve
    if @num_of_took_rounds == 0
      max = @current_round_iden-1
      min = @current_round_iden % 2 == 0 ? @current_round_iden / 2 : @current_round_iden / 2 + 1
    else

      @unused_indentifiers = []
      @remember_rounds = []
      (1..@dats.length-1).each do |line_num|
        line = @dats[line_num]
        line = line.split(" ")
        line.shift
        line.each { |elem| @remember_rounds.push(elem.to_i) }
      end

      (@current_round_iden-1).downto(1) do |elem|
        @unused_indentifiers.push(elem) if not @remember_rounds.include?(elem)
      end

      min = find_min_possible(@unused_indentifiers)
      max = find_max_possible(@unused_indentifiers)
    end
    print "#{min} #{max}"
  end

  def find_min_possible(indentifier_array)
    ret = 0
    idx = 0
    indentifier_array.sort!

    while idx < indentifier_array.length
      if idx == indentifier_array.length - 1
        ret += 1
        return ret
      elsif indentifier_array[idx+1] == indentifier_array[idx]+1
        ret += 1
        idx += 2
      else
        ret += 1
        idx += 1
      end
    end
    return ret
  end

  def find_max_possible(indentifier_array)
    indentifier_array.length
  end
end

solver = ProblemA.new
solver.solve

class ProblemA
  def initialize
    @dats = STDIN.read.split("\n")
    @current_round_iden, @num_of_took_rounds = @dats[0].split(" ").map{|x| x.to_i}
  end

  def solve
    if @num_of_took_rounds == 0
      max = @current_round_iden-1
      min = @current_round_iden % 2 == 0 ? @current_round_iden / 2 : (@current_round_iden-1) / 2 + 1
    else

      @unused_indentifiers = []
      @remember_rounds = []
      (1..@dats.length-1).each do |line_num|
        line = @dats[line_num]
        line = line.split(" ")
        line.shift
        line.each { |elem| @remember_rounds.push(elem.to_i) }
      end

      (@current_round_iden-1).downto(1) do |elem|
        @unused_indentifiers.push(elem) if not @remember_rounds.include?(elem)
      end

      min = find_min_possible(@unused_indentifiers)
      max = find_max_possible(@unused_indentifiers)
    end
    print "#{min} #{max}"
  end

  def find_min_possible(indentifier_array)
    ret = 0
    idx = 0
    indentifier_array.sort!

    while idx < indentifier_array.length
      if idx == indentifier_array.length - 1
        ret += 1
        return ret
      elsif indentifier_array[idx+1] == indentifier_array[idx]+1
        ret += 1
        idx += 2
      else
        ret += 1
        idx += 1
      end
    end
    return ret
  end

  def find_max_possible(indentifier_array)
    indentifier_array.length
  end
end

solver = ProblemA.new
solver.solve

def answer(id_ary,max_id)
	pair_num = 0
	full_ary = []
	for i in 1..max_id
		full_ary << i
	end
	diff_ary = full_ary - id_ary
	if diff_ary.empty?
		return [0,0]
	else
		for i in 0..(diff_ary.length-1)
			if (i != diff_ary.length-1)
				if diff_ary[i] == diff_ary[i+1] - 1
					pair_num += 1
				end
			end
		end
	end
	max_num = diff_ary.length
	min_num = diff_ary.length - pair_num

	return [min_num, max_num]

end

first_line = (gets()).split()
current_id = (first_line.shift).to_i
part_in_num = (first_line.pop).to_i
id_ary = []
for i in 1..part_in_num
	ary = []
	(gets().split).each { |e| ary << e.to_i }
	ary.shift
	ary.each { |e| id_ary << e }
end
result = answer(id_ary, current_id-1)
puts result[0].to_s + " " + result[1].to_s

def answer(id_ary,max_id)
	pair_num = 0
	full_ary = []
	for i in 1..max_id
		full_ary << i
	end
	diff_ary = full_ary - id_ary
	if diff_ary.empty?
		return [0,0]
	else
		for i in 0..(diff_ary.length-1)
			if (i != diff_ary.length-1)
				if diff_ary[i] == diff_ary[i+1] - 1
					pair_num += 1
				end
			end
		end
	end
	max_num = diff_ary.length
	min_num = diff_ary.length - pair_num

	return [min_num, max_num]

end

first_line = (gets()).split()
current_id = (first_line.shift).to_i
part_in_num = (first_line.pop).to_i
id_ary = []
for i in 1..part_in_num
	ary = []
	(gets().split).each { |e| ary << e.to_i }
	ary.shift
	ary.each { |e| id_ary << e }
end
result = answer(id_ary, current_id-1)
puts result[0].to_s + result[1].to_s

i=->(x){x.split.map(&:to_i)}
n,_=i[gets]
a=$<.drop(0).collect{|x|i[x][1..-1]}.flatten.push(n).sort
x,y=0,0
(a.size-1).times do |k|
	z=a[k+1]-a[k]
	next if z == 1
	x,y=x+(z+1)/2,y+z
end
puts "#{x} #{y}"

i=->(x){x.split.map(&:to_i)}
n,_=i[gets]
a=$<.drop(0).collect{|x|i[x][1..-1]}.flatten.push(n).push(1).sort
x,y=0,0
(a.size-1).times do |k|
	z=a[k+1]-a[k]
	next if z <= 1
	x,y=x+(z+1)/2,y+z
end
puts "#{x} #{y}"


The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows:  If x = 1, exit the function.  Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order.

A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation.

In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists.

n = gets.to_i
print n,' ', (1...n).to_a.join(' ')

print n = gets.to_i,' ', (1...n).to_a.join(' ')

def main()
  n = gets.chomp.to_i
  p = [n]

  1.upto(n - 1) do |i|
    p << i
  end

  puts p.join(" ")

end

main()

n = gets.to_i

if n == 1
  puts 1
else
  print "#{n} "
  puts (1..(n-1)).to_a.map(&:to_s).join(" ")
end

n = gets.to_i
$arr = (1..n).to_a
def f(x)
  $arr[x-2], $arr[x-1] = $arr[x-1], $arr[x-2]
  f(x-1) if x-1>1
end
if n == 1
  puts n
  exit
end
f(n)
puts $arr.join(" ")

n=gets.to_i
print n
1.upto(n-1) {|i| print ' ',i}
puts

n=gets.to_i
if n==1 then
	p 1
else
	print n
	1.upto(n-1) {|i| print ' ',i}
	puts
end

print n=gets.to_i
1.upto(n-1) {|i| print ' ',i}

n = gets.to_i
if n==1
puts 1
elsif n==2
puts '2 1'
else
puts(([n,1]+(2...n).to_a).join ' ')
end

def f(x)
  return if x == 0
  f(x - 1)
  tmp = $a[x]
  $a[x] = $a[x - 1]
  $a[x - 1] = tmp
end

n = gets.to_i
ans = (1..n-1).to_a
ans.unshift n

puts ans.join ' '

n = STDIN.readline.to_i
ans = [n]
n -= 1
1.upto n do |i|
  ans << i
end

puts ans.join ' '

a = gets.to_i
print a
1.upto(a - 1) { |i| print ' ',i }

a=gets.to_i

print a
1.upto(a-1){|i| print ' ',i}

n = Integer(gets.chomp)
puts(([n] + (1..n - 1).to_a) * ' ')

a = gets.to_i
b = ""
c = 1
while(c<a)

b = b +c.to_s + " ";
c = c+1
end
puts a.to_s+" " + b

n = gets.to_i

p = Array.new(n) { |i, v| v = i + 1 }

(n - 1).downto(1) do |i|
	p[i - 1], p[i] = p[i], p[i - 1]
end
puts p.join ' '

def main()
  n = gets.chomp.to_i
  p = []

  n.downto(1) do |i|
    p << i
  end

  puts p.join(" ")

end

main()

n = gets.to_i

if n == 1
  puts 1
else
  puts (2..n).to_a.push(1).map(&:to_s).join(" ")
end

a=[]
n=gets.to_i
n.times{|i|a<<i+1}
a.push(a.shift)
n.times{|i|
	print a[i]
	if i != n-1 then print ' ' end}
puts

n = gets.to_i
puts RUBY_VERSION
if n==1
puts 1
elsif n==2
puts '2 1'
else
puts(([1,n]+(2...n).to_a).join ' ')
end

n = gets.to_i
if n==1
puts 1
elsif n==2
puts '2 1'
else
puts(([1,n]+(2...n).to_a).join ' ')
end

n = gets.to_i
puts ((1..n).to_a.reverse)

n = gets.to_i
if n==1
puts 1
elsif n==2
puts '1 2'
else
puts(([1,n]+(2...n).to_a).join ' ')
end

a = gets.to_i
print a
1.upto(a) { |i| print ' ',i }

a = geta = gets.to_i
b = ""
c = 2
while(c<=a)

b = b +c.to_s + " ";
c = c+1
end
puts b+"1"

n = gets.to_i

p = Array.new(n) { |i, v| v = i + 1 }

1.upto(n - 1) do |i|
	p[i - 1], p[i] = p[i], p[i - 1]
end
puts p.join ' '


In a building where Polycarp lives there are equal number of flats on each floor. Unfortunately, Polycarp don't remember how many flats are on each floor, but he remembers that the flats are numbered from 1 from lower to upper floors. That is, the first several flats are on the first floor, the next several flats are on the second and so on. Polycarp don't remember the total number of flats in the building, so you can consider the building to be infinitely high (i.e. there are infinitely many floors). Note that the floors are numbered from 1.Polycarp remembers on which floors several flats are located. It is guaranteed that this information is not self-contradictory. It means that there exists a building with equal number of flats on each floor so that the flats from Polycarp's memory have the floors Polycarp remembers.Given this information, is it possible to restore the exact floor for flat n?

The first line contains two integers n and m (1 ≤ n ≤ 100, 0 ≤ m ≤ 100), where n is the number of the flat you need to restore floor for, and m is the number of flats in Polycarp's memory. m lines follow, describing the Polycarp's memory: each of these lines contains a pair of integers ki, fi (1 ≤ ki ≤ 100, 1 ≤ fi ≤ 100), which means that the flat ki is on the fi-th floor. All values ki are distinct. It is guaranteed that the given information is not self-contradictory.

Print the number of the floor in which the n-th flat is located, if it is possible to determine it in a unique way. Print -1 if it is not possible to uniquely restore this floor.

NoteIn the first example the 6-th flat is on the 2-nd floor, while the 7-th flat is on the 3-rd, so, the 6-th flat is the last on its floor and there are 3 flats on each floor. Thus, the 10-th flat is on the 4-th floor.In the second example there can be 3 or 4 flats on each floor, so we can't restore the floor for the 8-th flat.

def divCeil(dd, dr)
	(dd + dr - 1) / dr
end

n, m = gets.split.map{|x| x.to_i}

l = 1
r = 200

m.times do
	k, f = gets.split.map{|x| x.to_i}

	nl = divCeil(k, f)
	nr = f > 1 ? (k - 1) / (f - 1) : 200

	l = [nl, l].max
	r = [nr, r].min
end

p divCeil(n, l) == divCeil(n, r) ? divCeil(n, l) : -1

def divCeil(dd, dr)
	(dd + dr - 1) / dr
end

n, m = gets.split.map{|x| x.to_i}

if m == 0
	p n == 1 ? 1 : -1
	exit(0)
end

kf = []
m.times{kf << gets.split.map{|x| x.to_i}}
kf.sort!

l = divCeil(kf[0][0], kf[0][1])
r = 200

(1...kf.size).each do |i|
	l = [l, divCeil(kf[i][0], kf[i][1])].max
	if kf[i][1] > kf[i - 1][1]
		r = [r, (kf[i][0] - 1) / [1, kf[i][1] - 1].max].min
	end
end

p divCeil(n, l) == divCeil(n, r) ? divCeil(n, l) : -1

def divCeil(dd, dr)
	(dd + dr - 1) / dr
end

n, m = gets.split.map{|x| x.to_i}

if m == 0
	p n == 1 ? 1 : -1
	exit(0)
end

kf = []
m.times{kf << gets.split.map{|x| x.to_i}}
kf.sort!

l = divCeil(kf[0][0], kf[0][1])
r = (kf[-1][0] - 1) / [1, kf[-1][1] - 1].max

(1...kf.size).each do |i|
	l = [l, divCeil(kf[i][0], kf[i][1])].max
	if kf[i][1] > kf[i - 1][1]
		r = [r, (kf[i][0] - 1) / [1, kf[i][1] - 1].max].min
	end
end

p r > 0 && divCeil(n, l) == divCeil(n, r) ? divCeil(n, l) : -1

def divCeil(dd, dr)
	(dd + dr - 1) / dr
end

n, m = gets.split.map{|x| x.to_i}

if m == 0
	p -1
	exit(0)
end

kf = []
m.times{kf << gets.split.map{|x| x.to_i}}
kf.sort!

l = divCeil(kf[0][0], kf[0][1])
r = 200

(1...kf.size).each do |i|
	l = [l, divCeil(kf[i][0], kf[i][1])].max
	if kf[i][1] > kf[i - 1][1]
		r = [r, (kf[i][0] - 1) / [1, kf[i][1] - 1].max].min
	end
end

p divCeil(n, l) == divCeil(n, r) ? divCeil(n, l) : -1

def divCeil(dd, dr)
	(dd + dr - 1) / dr
end

n, m = gets.split.map{|x| x.to_i}

if m == 0 || n == 1
	p n == 1 ? 1 : -1
	exit(0)
end

kf = []
m.times{kf << gets.split.map{|x| x.to_i}}
kf.sort!

l = divCeil(kf[0][0], kf[0][1])
r = (kf[-1][0] - 1) / [1, kf[-1][1] - 1].max

(1...kf.size).each do |i|
	l = [l, divCeil(kf[i][0], kf[i][1])].max
	if kf[i][1] > kf[i - 1][1]
		r = [r, (kf[i][0] - 1) / [1, kf[i][1] - 1].max].min
	end
end

p r > 0 && divCeil(n, l) == divCeil(n, r) ? divCeil(n, l) : -1

def divCeil(dd, dr)
	(dd + dr - 1) / dr
end

n, m = gets.split.map{|x| x.to_i}

kf = []
m.times{kf << gets.split.map{|x| x.to_i}}
kf.sort!

l = divCeil(kf[0][0], kf[0][1])
r = 200

(1...kf.size).each do |i|
	l = [l, divCeil(kf[i][0], kf[i][1])].max
	if kf[i][1] > kf[i - 1][1]
		r = [r, (kf[i][0] - 1) / [1, kf[i][1] - 1].max].min
	end
end

p l == r ? divCeil(n, l) : -1

def divCeil(dd, dr)
	(dd + dr - 1) / dr
end

n, m = gets.split.map{|x| x.to_i}

if m == 0 || n == 1
	p n == 1 ? 1 : -1
	exit(0)
end

kf = []
m.times{kf << gets.split.map{|x| x.to_i}}
kf.sort!

l = divCeil(kf[0][0], kf[0][1])
r = (kf[-1][0] - 1) / [1, kf[-1][1] - 1].max

(1...kf.size).each do |i|
	if n == kf[i][0]
		p kf[i][1]
		exit(0)
	end
	l = [l, divCeil(kf[i][0], kf[i][1])].max
	if kf[i][1] > kf[i - 1][1]
		r = [r, (kf[i][0] - 1) / [1, kf[i][1] - 1].max].min
	end
end

p r > 0 && divCeil(n, l) == divCeil(n, r) ? divCeil(n, l) : -1


You are given a string $$$s$$$ of length $$$n$$$ consisting only of the characters 0 and 1.You perform the following operation until the string becomes empty: choose some consecutive substring of equal characters, erase it from the string and glue the remaining two parts together (any of them can be empty) in the same order. For example, if you erase the substring 111 from the string 111110, you will get the string 110. When you delete a substring of length $$$l$$$, you get $$$a \cdot l + b$$$ points.Your task is to calculate the maximum number of points that you can score in total, if you have to make the given string empty.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of testcases. The first line of each testcase contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 100; -100 \le a, b \le 100$$$) — the length of the string $$$s$$$ and the parameters $$$a$$$ and $$$b$$$. The second line contains the string $$$s$$$. The string $$$s$$$ consists only of the characters 0 and 1.

For each testcase, print a single integer — the maximum number of points that you can score.

NoteIn the first example, it is enough to delete the entire string, then we will get $$$2 \cdot 3 + 0 = 6$$$ points.In the second example, if we delete characters one by one, then for each deleted character we will get $$$(-2) \cdot 1 + 5 = 3$$$ points, i. e. $$$15$$$ points in total.In the third example, we can delete the substring 00 from the string 100111, we get $$$1 \cdot 2 + (-4) = -2$$$ points, and the string will be equal to 1111, removing it entirely we get $$$1 \cdot 4 + (-4) = 0$$$ points. In total, we got $$$-2$$$ points for $$$2$$$ operations.

t = gets.chomp.to_i

t.times do
  n, a, b = gets.chomp.split(' ').map(&:to_i)
  str = gets.chomp
  if b >= 0
    puts "#{n*(a+b)}\n"
  else
    first_char = str[0].to_i
    other_char = 1 - first_char
    ans = 0
    cnt = Hash.new(0)
    for i in 0...(str.size) do
      cnt[str[i].to_i] += 1
    end
    ans += a * cnt[first_char] + b

    ptr = 0
    while ptr < str.size do
      while ptr < str.size && str[ptr].to_i == first_char do
        ptr += 1
      end
      tmp = 0
      while ptr < str.size && str[ptr].to_i == other_char do
        ptr += 1
        tmp += 1
      end
      ans += a * tmp + b if tmp > 0
    end

    puts "#{ans}\n"
  end
end


You are given a function $$$f$$$ written in some basic language. The function accepts an integer value, which is immediately written into some variable $$$x$$$. $$$x$$$ is an integer variable and can be assigned values from $$$0$$$ to $$$2^{32}-1$$$. The function contains three types of commands:  for $$$n$$$ — for loop;  end — every command between "for $$$n$$$" and corresponding "end" is executed $$$n$$$ times;  add — adds 1 to $$$x$$$. After the execution of these commands, value of $$$x$$$ is returned.Every "for $$$n$$$" is matched with "end", thus the function is guaranteed to be valid. "for $$$n$$$" can be immediately followed by "end"."add" command can be outside of any for loops.Notice that "add" commands might overflow the value of $$$x$$$! It means that the value of $$$x$$$ becomes greater than $$$2^{32}-1$$$ after some "add" command. Now you run $$$f(0)$$$ and wonder if the resulting value of $$$x$$$ is correct or some overflow made it incorrect.If overflow happened then output "OVERFLOW!!!", otherwise print the resulting value of $$$x$$$.

The first line contains a single integer $$$l$$$ ($$$1 \le l \le 10^5$$$) — the number of lines in the function. Each of the next $$$l$$$ lines contains a single command of one of three types:   for $$$n$$$ ($$$1 \le n \le 100$$$) — for loop;  end — every command between "for $$$n$$$" and corresponding "end" is executed $$$n$$$ times;  add — adds 1 to $$$x$$$.

If overflow happened during execution of $$$f(0)$$$, then output "OVERFLOW!!!", otherwise print the resulting value of $$$x$$$.

9
add
for 43
end
for 10
for 15
add
end
add
end

11
for 100
for 100
for 100
for 100
for 100
add
end
end
end
end
end

NoteIn the first example the first "add" is executed 1 time, the second "add" is executed 150 times and the last "add" is executed 10 times. Note that "for $$$n$$$" can be immediately followed by "end" and that "add" can be outside of any for loops.In the second example there are no commands "add", thus the returning value is 0.In the third example "add" command is executed too many times, which causes $$$x$$$ to go over $$$2^{32}-1$$$.

l = gets.to_i
lines = (0...l).map { gets.strip }
ans = 0
cur = 1
stk = []
ptr = 0
until ptr == l
  if lines[ptr].match(/^for/)
    b = lines[ptr].match(/\d+/)[0].to_i
    cur *= b
    stk.push(b)
  elsif lines[ptr].match(/^add/)
    ans += cur
  else
    cur /= stk.pop
  end
  ptr += 1
  until cur < 1e10
    if lines[ptr].match(/^for/)
      stk.push(1)
    elsif lines[ptr].match(/^add/)
      puts "OVERFLOW!!!"
      exit
    else
      cur /= stk.pop
    end
    ptr += 1
  end
end
if ans < 2**32 - 0
  puts ans
else
  puts "OVERFLOW!!!"
end

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

t = gets.to_i
curr = 1

arr = []
t.times do
	str = gets.chomp
	if(str[0]=='f')
		arr.push str.split(" ")[-1].to_i
	elsif(str[0]=='a')
		arr.push 0
	else
		arr.push -1
	end
end

max = 2**32-1

list = []
workslist = []
ans=0
works = true

arr.each do |x|

#	p list
#	p workslist

	if(x==0)
		if(!works)
			puts "OVERFLOW!!!"
			exit
		end
		ans+=curr
	elsif(x>0)
		list.push x
		newmax = curr*x
		if(works && newmax < max)
			curr = newmax
			workslist.push works
		else
			works = false
			workslist.push works
		end
	else
		workslist.pop
		a = list.pop
		if(works)
			curr/=a
		end
		if(workslist.size>0)
			works = workslist[-1]
		else
			works = true
		end
	end

	if(ans>max)
		puts "OVERFLOW!!!"
		exit
	end
end

puts ans

l = gets.to_i
lines = (0...l).map { gets.strip }
ans = 0
cur = 1
stk = []
ptr = 0
until ptr == l
  if lines[ptr].match(/^for/)
    b = lines[ptr].match(/\d+/)[0].to_i
    cur *= b
    stk.push(b)
  elsif lines[ptr].match(/^add/)
    ans += cur
  else
    cur /= stk.pop
  end
  ptr += 1
  until cur < 1e10
    if lines[ptr].match(/^for/)
      stk.push(1)
    elsif lines[ptr].match(/^add/)
      puts "OVERFLOW!!!"
      exit
    else
      cur /= stk.pop
    end
    ptr += 1
  end
end
if ans < 2**32 - 1
  puts ans
else
  puts "OVERFLOW!!!"
end

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

t = gets.to_i
curr = 1

arr = []
t.times do
	str = gets.chomp
	if(str[0]=='f')
		arr.push str.split(" ")[-1].to_i
	elsif(str[0]=='a')
		arr.push 0
	else
		arr.push -1
	end
end

max = 2**32-1

list = []
workslist = []
ans=0
works = true

arr.each do |x|
	if(x==0)
		if(!works)
			puts "OVERFLOW!!!"
			exit
		end
		ans+=curr
	elsif(x>0)
		list.push x

		newmax = curr*x
		if(newmax < max)
			curr = newmax
			workslist.push true
		else
			works = false
			workslist.push false
		end
	else
		works = workslist.pop
		a = list.pop
		if(works)
			curr/=a
		end
	end

	if(ans>max)
		puts "OVERFLOW!!!"
		exit
	end
end

puts ans

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

t = gets.to_i
curr = 1

arr = []
t.times do
	str = gets.chomp
	if(str[0]=='f')
		arr.push str.split(" ")[-1].to_i
	elsif(str[0]=='a')
		arr.push 0
	else
		arr.push -1
	end
end

max = 2**32-1

list = []
workslist = []
ans=0
works = true

arr.each do |x|
	if(x==0)
		if(!works)
			puts "OVERFLOW!!!"
			exit
		end
		ans+=curr
	elsif(x>0)
		list.push x

		newmax = curr*x
		if(works && newmax < max)
			curr = newmax
			workslist.push works
		else
			works = false
			workslist.push works
		end
	else
		works = workslist.pop
		a = list.pop
		if(works)
			curr/=a
		end
	end

	if(ans>max)
		puts "OVERFLOW!!!"
		exit
	end
end

puts ans


Little girl Susie went shopping with her mom and she wondered how to improve service quality. There are n people in the queue. For each person we know time ti needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time when all the people who stand in the queue in front of him are served. Susie thought that if we swap some people in the queue, then we can decrease the number of people who are disappointed. Help Susie find out what is the maximum number of not disappointed people can be achieved by swapping people in the queue.

The first line contains integer n (1 ≤ n ≤ 105). The next line contains n integers ti (1 ≤ ti ≤ 109), separated by spaces.

Print a single number — the maximum number of not disappointed people in the queue.

NoteValue 4 is achieved at such an arrangement, for example: 1, 2, 3, 5, 15. Thus, you can make everything feel not disappointed except for the person with time 5.

# coding: utf-8

# if __FILE__ == $0
# end

n = gets.to_i
ts = gets.split.map(&:to_i)
ts.sort!
acc = ts[0]
satisfied = 1
# p ts
ts[1..-1].each { |i|
    # p "Satisfied? #{i} #{acc}"
    if acc <= i
        satisfied += 1
        acc += i
    else
        # 다음 사람이 만족할 수 있는 고객이라면,
        # 다가올 고객을 제일 뒤로 보낸다고 생각하자.
        # 스킵해도 무방하다.
        next
    end
}

puts satisfied

n = Integer(gets)
nums = gets.chomp.split
queue = []
for i in 0...n
    queue[i] = Integer(nums[i])
end

queue.sort!
sum = 0
count = 0
for i in 0...n
    if sum <= queue[i]
        sum += queue[i]
        count += 1
    else
        queue.push(queue[i])
        queue[i] = 0
    end
end
puts count

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

count = 1
a = a.sort
t = a[0]
arr = []
for i in (1..a.size-1)
	x = i
	while a[x] < t && x < n-1
		x += 1
	end
	if a[x] != nil && a[x] >= t
		count += 1
		t += a[x]
	else
		break
	end
end
print count

n = gets.to_i
a = gets.split.map(&:to_i)
a.sort!
res = 0
sum = 0
a.each do
  |x|
  if(sum <= x)
  sum+=x
  res+=1
  end
end
print res

gets
pleased = 0
time = 0
gets.split(' ').map(&:to_i).sort.each do |wait|
  if time <= wait
    pleased += 1
    time += wait
  end
end
puts pleased

n = gets.to_i
t = gets.split.collect{|i| i.to_i}.sort
sum = 0
ans = 0
t.each do |tt|
    if tt >= sum
        sum += tt
        ans += 1
    end
end
puts ans

def test(ary)
  sum = 0
  res = 0

  ary.sort.each do |el|
    next unless el >= sum
    sum += el
    res += 1
  end

  res
end

a = Kernel.gets
puts test(Kernel.gets.split.map(&:to_i))

n = gets.to_i
t = gets.split.map(&:to_i)
sum = 0
ans = 0
t.sort.each do |x|
    if x >= sum
        sum += x
        ans += 1
    end
end
puts ans

gets
x=gets.split.map{|e| e.to_i}.sort
sum=0
ans=0

x.each{|e|
	if sum<=e then
		sum+=e
		ans+=1
	end
}
puts ans

# coding: utf-8

# if __FILE__ == $0
# end

n = gets.to_i
ts = gets.split.map(&:to_i)
ts.sort!
acc = ts[0]
satisfied = 1
ts[1..-1].each { |i|
    if acc <= i
        satisfied += 1
    end

    acc += i
}

puts satisfied

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

t = 0
a = a.sort
count = 1
for i in (1..n-1)
	t += a[i-1]
	if a[i] >= t
		count += 1
	end
end
print count

def test(ary)
  sum = 0
  res = 0

  ary.sort.each do |el|
    next unless el > sum
    sum += el
    res += 1
  end

  res
end

a = Kernel.gets
puts test(Kernel.gets.split.map(&:to_i))

# coding: utf-8

# if __FILE__ == $0
# end

n = gets.to_i
ts = gets.split.map(&:to_i)
ts.sort!
acc = ts[0]
satisfied = 1
p ts
ts[1..-1].each { |i|
    # p "Satisfied? #{i} #{acc}"
    if acc <= i
        satisfied += 1
        acc += i
    else
        # 다음 사람이 만족할 수 있는 고객이라면,
        # 다가올 고객을 제일 뒤로 보낸다고 생각하자.
        # 스킵해도 무방하다.
        next
    end
}

puts satisfied


Gleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust.The pizza is a circle of radius r and center at the origin. Pizza consists of the main part — circle of radius r - d with center at the origin, and crust around the main part of the width d. Pieces of sausage are also circles. The radius of the i -th piece of the sausage is ri, and the center is given as a pair (xi, yi).Gleb asks you to help determine the number of pieces of sausage caught on the crust. A piece of sausage got on the crust, if it completely lies on the crust.

First string contains two integer numbers r and d (0 ≤ d < r ≤ 500) — the radius of pizza and the width of crust. Next line contains one integer number n — the number of pieces of sausage (1 ≤ n ≤ 105). Each of next n lines contains three integer numbers xi, yi and ri ( - 500 ≤ xi, yi ≤ 500, 0 ≤ ri ≤ 500), where xi and yi are coordinates of the center of i-th peace of sausage, ri — radius of i-th peace of sausage.

Output the number of pieces of sausage that lay on the crust.

NoteBelow is a picture explaining the first example. Circles of green color denote pieces of sausage lying on the crust.

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

ans = 0
n.times do
    x, y, r = gets.split.map(&:to_i)
    if R - d <= Math.hypot(x, y) - r and Math.hypot(x, y) + r <= R
        ans += 1
    end
end

puts ans

r, d = gets.split.map(&:to_i)
n = gets.to_i
ans = 0
r2 = (r - d)
n.times do |i|
    x, y, z = gets.split.map(&:to_i)
    hoge = x ** 2 + y ** 2
    if (r2 + z) * (r2 + z) <= hoge && hoge <= (r - z) * (r - z)
        ans += 1
    end
end
puts ans

R, D = gets.split.map &:to_i
n = gets.to_i
EPS = 1e-9

cnt = 0
n.times do
    x, y, r = gets.split.map &:to_i
    d = (x**2 + y**2)**0.5
    # puts("#{R} #{D} #{d} #{r} #{R-D-EPS} #{r-d} #{r+d} #{R+EPS}")
    cnt += 1 if R-D-EPS < d-r && d+r < R+EPS
end

puts cnt

R, D = gets.chomp.split.map(&:to_i)
n = gets.to_i
ans = 0

n.times do
  x, y, r = gets.chomp.split.map(&:to_i)
  hypot = x * x + y * y
  outer = (hypot <= (R - r) ** 2 && (R - r) > 0)
  inner = ((R - D + r) <=0 || (R - D + r) ** 2 <= hypot)
  ans += 1 if outer and inner
end

p ans


Recently, you found a bot to play "Rock paper scissors" with. Unfortunately, the bot uses quite a simple algorithm to play: he has a string $$$s = s_1 s_2 \dots s_{n}$$$ of length $$$n$$$ where each letter is either R, S or P.While initializing, the bot is choosing a starting index $$$pos$$$ ($$$1 \le pos \le n$$$), and then it can play any number of rounds. In the first round, he chooses "Rock", "Scissors" or "Paper" based on the value of $$$s_{pos}$$$:   if $$$s_{pos}$$$ is equal to R the bot chooses "Rock";  if $$$s_{pos}$$$ is equal to S the bot chooses "Scissors";  if $$$s_{pos}$$$ is equal to P the bot chooses "Paper"; In the second round, the bot's choice is based on the value of $$$s_{pos + 1}$$$. In the third round — on $$$s_{pos + 2}$$$ and so on. After $$$s_n$$$ the bot returns to $$$s_1$$$ and continues his game.You plan to play $$$n$$$ rounds and you've already figured out the string $$$s$$$ but still don't know what is the starting index $$$pos$$$. But since the bot's tactic is so boring, you've decided to find $$$n$$$ choices to each round to maximize the average number of wins.In other words, let's suggest your choices are $$$c_1 c_2 \dots c_n$$$ and if the bot starts from index $$$pos$$$ then you'll win in $$$win(pos)$$$ rounds. Find $$$c_1 c_2 \dots c_n$$$ such that $$$\frac{win(1) + win(2) + \dots + win(n)}{n}$$$ is maximum possible.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain test cases — one per line. The first and only line of each test case contains string $$$s = s_1 s_2 \dots s_{n}$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$s_i \in \{\text{R}, \text{S}, \text{P}\}$$$) — the string of the bot. It's guaranteed that the total length of all strings in one test doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print $$$n$$$ choices $$$c_1 c_2 \dots c_n$$$ to maximize the average number of wins. Print them in the same manner as the string $$$s$$$. If there are multiple optimal answers, print any of them.

NoteIn the first test case, the bot (wherever it starts) will always choose "Rock", so we can always choose "Paper". So, in any case, we will win all $$$n = 4$$$ rounds, so the average is also equal to $$$4$$$.In the second test case:   if bot will start from $$$pos = 1$$$, then $$$(s_1, c_1)$$$ is draw, $$$(s_2, c_2)$$$ is draw and $$$(s_3, c_3)$$$ is draw, so $$$win(1) = 0$$$;  if bot will start from $$$pos = 2$$$, then $$$(s_2, c_1)$$$ is win, $$$(s_3, c_2)$$$ is win and $$$(s_1, c_3)$$$ is win, so $$$win(2) = 3$$$;  if bot will start from $$$pos = 3$$$, then $$$(s_3, c_1)$$$ is lose, $$$(s_1, c_2)$$$ is lose and $$$(s_2, c_3)$$$ is lose, so $$$win(3) = 0$$$;  The average is equal to $$$\frac{0 + 3 + 0}{3} = 1$$$ and it can be proven that it's the maximum possible average.A picture from Wikipedia explaining "Rock paper scissors" game:

def fun(k)
	if(k == "R")
		return "P"
	elsif(k == "S")
		return "R"
	elsif (k == "P")
		return "S"
	end
end

t = gets.to_i
t.times do
	s = gets.chomp
	l = s.size
	c = Hash.new(0)
	s.each_char do |x|
		c[x] += 1
	end

	puts fun(c.max_by{|k,v| v}[0])*l

end

def fun(k)
	if(k == "R")
		return "P"
	elsif(k == "S")
		return "R"
	elsif (k == "P")
		return "S"
	end
end

t = gets.to_i
t.times do
	s = gets.chomp
	l = s.size
	c = Hash.new(0)
	s.each_char do |x|
		c[x] += 1
	end
	pos = s.index(c.max[0])
	(pos...l).each do |i|
		print(fun(s[i]))
	end
	(0...pos).each do |i|
		print(fun(s[i]))
	end
	puts ""
end

def fun(k)
	if(k == "R")
		return "P"
	elsif(k == "S")
		return "R"
	elsif (k == "P")
		return "S"
	end
end

t = gets.to_i
t.times do
	s = gets.chomp
	l = s.size
	c = Hash.new(0)
	s.each_char do |x|
		c[x] += 1
	end
	puts fun(c.max[0])*l

end

def fun(k)
	if(k == "R")
		return "P"
	elsif(k == "S")
		return "R"
	elsif (k == "P")
		return "S"
	end
end

t = gets.to_i
t.times do
	s = gets.chomp
	l = s.size
	arr = Array.new(l) {1}
	(1...l).each do |i|
		if s[i] == s[i-1]
			arr[i] += arr[i-1]
		end
	end
	# print(arr)
	mele ,mpos = 1,0
	(1...l).each do |i|
		if(arr[i] > mele)
			mele = arr[i]
			mpos = i
		end
	end
	pos = mpos - arr[mpos]+1
	# print(pos)
	(pos...l).each do |i|
		print(fun(s[i]))
	end
	(0...pos).each do |i|
		print(fun(s[i]))
	end
	puts("")
end

t = gets.to_i
t.times do
	s = gets.chomp

	s.each_char do |x|
		if x == 'R'
			print 'P'
		elsif x == 'S'
			print 'R'
		elsif x == 'P'
			print 'S'
		end
	end
	puts ""
end


When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it?You're given a sequence of n data points a1, ..., an. There aren't any big jumps between consecutive data points — for each 1 ≤ i < n, it's guaranteed that |ai + 1 - ai| ≤ 1.A range [l, r] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let M be the maximum and m the minimum value of ai for l ≤ i ≤ r; the range [l, r] is almost constant if M - m ≤ 1.Find the length of the longest almost constant range.

The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of data points. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000).

Print a single number — the maximum length of an almost constant range of the given sequence.

NoteIn the first sample, the longest almost constant range is [2, 5]; its length (the number of data points in it) is 4.In the second sample, there are three almost constant ranges of length 4: [1, 4], [6, 9] and [7, 10]; the only almost constant range of the maximum length 5 is [6, 10].

n = gets.chomp.to_i
nums = gets.split.map { |s| s.to_i }
#puts nums
prev = 0
prev_pos = 0
next_pos = 0
ans = 0
curr = []
curr_pos = []
start = []

nums.size.times do |i|
    if curr.size < 2 and not curr.include? nums[i] then
        curr << nums[i]
        curr_pos << i
        start << i
    elsif not curr.include? nums[i] then
        curr = curr.drop(1)
        if curr_pos[0] > start[1] then
            start[1] = curr_pos[0] + 1
        end
        curr_pos = curr_pos.drop(1)
        start = start.drop(1)
        curr << nums[i]
        curr_pos << i
        start << i
    else
        if curr[0] == nums[i] then
            curr = curr.drop(1)
            curr_pos = curr_pos.drop(1)
            z = start[0]
            start = start.drop(1)
            curr << nums[i]
            curr_pos << i
            start << z
        else
            curr_pos[1] = i
        end
    end
    ans = [ans,curr_pos.max - start.min + 1].max
    #print curr
    #print curr_pos
    #print start
    #puts ans
end

puts ans

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

def gi(); gets.to_i; end
def gis(); gets.chomp.split.map(&:to_i); end

$stdout = STDERR

n = gi
a = gis

mx = a[0]
mn = a[0]
bf = a[0]
pos = 0
ans = 1
len = 1
1.upto(n - 1) do |i|
    x = a[i]
    puts "i=%d x=%d bf=%d mn=%d mx=%d len=%d pos=%d ans=%d" % [i,x,bf,mn,mx,len,pos,ans]
    if bf == x
        len += 1
        puts "bf==x"
    else
        if (mx - x).abs <= 1 && (mn - x).abs <= 1
            len += 1
            if mx == mn
                mn, mx = [mx, x].minmax
            end
            puts "swap mx mn"
        else
            ans = len if len > ans
            if (bf - x).abs <= 1
                len = i - pos + 1
                mn, mx = [bf, x].minmax
                puts "continue bf=%d" % [bf]
            else
                len = 1
                mx = mn = x
                puts "new state"
            end
        end
        pos = i
        bf = x
    end
end

STDOUT.puts [ans, len].max

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

m = 0

current_m = a.shift
b = [current_m]

until a.empty?
  candidate = a.shift
  if candidate > current_m + 1 # candidate == current_m + 2
    last_one = b.rindex(current_m)
    b.slice!(0..last_one)
    current_m += 1
  elsif candidate < current_m # candidate == current_m - 1
    last_one = b.rindex(current_m + 1)
    b.slice!(0..last_one) if last_one
    current_m -= 1
  end
  b << candidate
  m = b.size if b.size > m
end

puts m

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

bs = as.map { |a| a / 2 }
cs = as.map { |a| (a + 1) / 2 }
cntb = 1
cntc = 1
ans = 2
for i in 1...n
  if bs[i] == bs[i - 1]
    cntb += 1
    ans = [ans, cntb].max
  else
    cntb = 1
  end
  if cs[i] == cs[i - 1]
    cntc += 1
    ans = [ans, cntc].max
  else
    cntc = 1
  end
end

puts ans

n = gets.chomp.to_i
a = gets.split(" ").map(&:to_i)
u = max = 1
amin = amax = a[0]
imin = imax = 0
for i in 1...n
	if a[i] == a[i-1]
		u += 1
	else
		if amin <= a[i] and a[i]<= amax
			u += 1
			if a[i] == amin
				imin = i
			else
				imax = i
			end
		elsif a[i] > amax
			amin = amax
			amax = a[i]
			u = i - imax + 1
			imin = imax
			imax = i
		else
			amax = amin
			amin = a[i]
			u = i - imin + 1
			imax = imin
			imin = i
		end
	end
	if u > max
		max = u
	end
end
puts max

def main(numbers)
    odds = numbers.map { |n| n.odd? ? n : n + 1 }
    odds_length = find_greatest(odds)
    evens = numbers.map { |n| n.even? ? n : n + 1 }
    evens_length = find_greatest(evens)
    puts [odds_length, evens_length].max
end

def find_greatest(numbers)
    last_number = -100000
    in_a_row = 0
    max_in_a_row = 0
    numbers.each do |n|
        if n == last_number
            in_a_row += 1
        else
            last_number = n
            in_a_row = 1
        end
        max_in_a_row = [max_in_a_row, in_a_row].max
    end
    max_in_a_row
end

ARGF.each_with_index do |line, index|
    if index == 1
        main(line.chomp.split(' ').map(&:to_i))
    end
end

N = gets.to_i
an = gets.split.map(&:to_i)

l = r = n = 0
ans = 0
while l < N && r < N
  r = l = n
  max = an[r]
  min = an[r]
  until max-min > 1
    r += 1
    break if r >= N
    min, max = [min, max, an[r]].minmax
    n = r if n == l && an[l] != an[r]
  end
  ans = [ans, r - l].max
end

puts ans

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

left = 0
prev = 0
ans = 1
tmp = 0
(1...n).each do |i|
  d = a[i] - a[i-1]
  if d != 0 then
    if d == tmp then
      left = prev + 1
    end
    tmp = d
    prev = i - 1
  end
  ans = [ans, i - left + 1].max
end
puts ans

n = gets.chomp.to_i
nums = gets.split.map { |s| s.to_i }
#puts nums
prev = 0
prev_pos = 0
next_pos = 0
ans = 0
curr = []
curr_pos = []
start = []

nums.size.times do |i|
    if curr.size < 2 then
        curr << nums[i]
        curr_pos << i
        start << i
    elsif not curr.include? nums[i] then
        curr = curr.drop(1)
        if curr_pos[0] > start[1] then
            start[1] = curr_pos[0] + 1
        end
        curr_pos = curr_pos.drop(1)
        start = start.drop(1)
        curr << nums[i]
        curr_pos << i
        start << i
    else
        if curr[0] == nums[i] then
            curr = curr.drop(1)
            curr_pos = curr_pos.drop(1)
            z = start[0]
            start = start.drop(1)
            curr << nums[i]
            curr_pos << i
            start << z
        else
            curr_pos[1] = i
        end
    end
    ans = [ans,curr_pos.max - start.min + 1].max
    #print curr
    #print curr_pos
    #print start
    #puts ans
end

puts ans

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

m = 0

current_m = a.shift
b = [current_m]

until a.empty?
  candidate = a.shift
  if candidate > current_m + 1 # candidate == current_m + 2
    last_one = b.index(current_m)
    b.slice!(0..last_one)
    current_m = b.min
  elsif candidate < current_m # candidate == current_m - 1
    last_one = b.index(current_m + 1)
    b.slice!(0..last_one) if last_one
    current_m = b.min
  end
  b << candidate
  m = b.size if b.size > m
end

puts m

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

m = 0

current_m = a.shift
b = [current_m]

until a.empty?
  candidate = a.shift
  if candidate > current_m + 1
    last_one = b.index(current_m)
    b.slice!(0..last_one)
    current_m += 1
  elsif candidate < current_m
    last_one = b.index(current_m + 1)
    b.slice!(0..last_one) if last_one
    current_m -= 1
  end
  b << candidate
  m = b.size if b.size > m
end

puts m

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

m = 0

current_m = a.shift
b = [current_m]

until a.empty?
  candidate = a.shift
  if candidate > current_m + 1 # candidate == current_m + 2
    last_one = b.index(current_m)
    b.slice!(0..last_one)
    current_m = b.min
  elsif candidate < current_m # candidate == current_m - 1
    last_one = b.index(current_m + 1)
    b.slice!(0..last_one) if last_one
    current_m = b.min - 1
  end
  b << candidate
  m = b.size if b.size > m
end

puts m

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

bs = (1...n).map { |i| as[i] - as[i - 1] }
ans = 0
im, iz, ip = [n, n, n]
if bs[0] == -1
  im = 0
elsif bs[0] == 1
  ip = 0
else
  iz = 0
end
for i in 1...n - 1
  if bs[i] == -1
    if bs[i - 1] == 0
      if ip == iz - 1
        ans = [ans, i - ip + 2].max
      else
        ans = [ans, i - iz + 2].max
      end
    elsif ip == i - 1
      ans = [ans, 3].max
    elsif im == i - 1
      ans = [ans, 2].max
    end
    im = i
  elsif bs[i] == 1
    if bs[i - 1] == 0
      if im == iz - 1
        ans = [ans, i - im + 2].max
      else
        ans = [ans, i - iz + 2].max
      end
    elsif im == i - 1
      ans = [ans, 3].max
    elsif ip == i - 1
      ans = [ans, 2].max
    end
    ip = i
  else
    if bs[i - 1] == 0
      if iz == 0
        ans = [ans, i - iz + 2].max
      else
        ans = [ans, i - iz + 3].max
      end
    else
      ans = [ans, 2].max
      iz = i
    end
  end
end

puts ans

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

bs = (1...n).map { |i| as[i] - as[i - 1] }
ans = 0
im, iz, ip = [n, n, n]
if bs[0] == -1
  im = 0
elsif bs[0] == 1
  ip = 0
else
  iz = 0
end
for i in 1...n - 1
  if bs[i] == -1
    if bs[i - 1] == 0
      if ip == iz - 1
        ans = [ans, i - ip + 2].max
      else
        ans = [ans, i - iz + 2].max
      end
    elsif ip == i - 1
      ans = [ans, 3].max
    elsif im == i - 1
      ans = [ans, 2].max
    end
    im = i
  elsif bs[i] == 1
    if bs[i - 1] == 0
      if im == iz - 1
        ans = [ans, i - im + 2].max
      else
        ans = [ans, i - iz + 2].max
      end
    elsif im == i - 1
      ans = [ans, 3].max
    elsif ip == i - 1
      ans = [ans, 2].max
    end
    ip = i
  else
    if bs[i - 1] == 0
      if iz == 0
        ans = [ans, i - iz + 2].max
      else
        ans = [ans, i - iz + 3].max
      end
    else
      ans = [ans, 3].max
      iz = i
    end
  end
end

puts ans


A binary string is a string consisting only of the characters 0 and 1. You are given a binary string $$$s$$$.For some non-empty substring$$$^\dagger$$$ $$$t$$$ of string $$$s$$$ containing $$$x$$$ characters 0 and $$$y$$$ characters 1, define its cost as:  $$$x \cdot y$$$, if $$$x > 0$$$ and $$$y > 0$$$;  $$$x^2$$$, if $$$x > 0$$$ and $$$y = 0$$$;  $$$y^2$$$, if $$$x = 0$$$ and $$$y > 0$$$. Given a binary string $$$s$$$ of length $$$n$$$, find the maximum cost across all its non-empty substrings.$$$^\dagger$$$ A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.

Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print a single integer — the maximum cost across all substrings.

NoteIn the first test case, we can take a substring $$$111$$$. It contains $$$3$$$ characters 1 and $$$0$$$ characters 0. So $$$a = 3$$$, $$$b = 0$$$ and its cost is $$$3^2 = 9$$$.In the second test case, we can take the whole string. It contains $$$4$$$ characters 1 and $$$3$$$ characters 0. So $$$a = 4$$$, $$$b = 3$$$ and its cost is $$$4 \cdot 3 = 12$$$.In the third test case, we can can take a substring $$$1111$$$ and its cost is $$$4^2 = 16$$$.In the fourth test case, we can take the whole string and cost is $$$4 \cdot 3 = 12$$$.In the fifth test case, we can take a substring $$$000$$$ and its cost is $$$3 \cdot 3 = 9$$$.In the sixth test case, we can only take the substring $$$0$$$ and its cost is $$$1 \cdot 1 = 1$$$.

def aaa(_n, s)
  s.delete!("\n")
  max0 = s.split(/0+/).map(&:length).sort.reverse[0].to_i
  max1 = s.split(/1+/).map(&:length).sort.reverse[0].to_i
  arr = [s.delete('0').length * s.delete('1').length, max0*max0, max1*max1]

  puts arr.sort[2]
end

t = gets.to_i

t.times do
  n = gets.to_i
  s = gets
  aaa(n, s)
end

gets.to_i.times do
    n=gets.chomp.to_i
    s=gets.chomp
    zeros,ones,maxZeros,maxOnes,currentZeros,currentOnes=0,0,0,0,0,0
    s.each_char do |c|
        if c=='0'
            zeros+=1
            currentZeros+=1
            maxZeros=[maxZeros,currentZeros].max
            currentOnes=0
        else
            ones+=1
            currentOnes+=1
            maxOnes=[maxOnes,currentOnes].max
            currentZeros=0
        end
    end
    puts [zeros*ones,maxZeros*maxZeros, maxOnes*maxOnes].max
end


You are given two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ positive integers, and an integer $$$x$$$. Please determine if one can rearrange the elements of $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$).

The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. $$$t$$$ blocks follow, each describing an individual test case. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 50$$$; $$$1 \leq x \leq 1000$$$) — the length of arrays $$$a$$$ and $$$b$$$, and the parameter $$$x$$$, described in the problem statement. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_1 \le a_2 \le \dots \le a_n \leq x$$$) — the elements of array $$$a$$$ in non-descending order. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_1 \le b_2 \le \dots \le b_n \leq x$$$) — the elements of array $$$b$$$ in non-descending order. Test cases are separated by a blank line.

For each test case print Yes if one can rearrange the corresponding array $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$) or No otherwise. Each character can be printed in any case.

NoteIn the first test case, one can rearrange $$$b$$$ so it'll look like $$$[1, 2, 1]$$$. In this case, $$$1 + 1 \leq 4$$$; $$$2 + 2 \leq 4$$$; $$$3 + 1 \leq 4$$$.In the second test case, one can set $$$b$$$ to $$$[5, 2]$$$, then $$$1 + 5 \leq 6$$$; $$$4 + 2 \leq 6$$$.In the third test case, no matter how one shuffles array $$$b$$$, $$$a_4 + b_4 = 4 + b_4 > 4$$$.In the fourth test case, there is only one rearrangement of array $$$b$$$ and it doesn't satisfy the condition since $$$5 + 5 > 5$$$.

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

def can(a, b, x)
  a.each_with_index do |e, i|
    return false if e + b[i] > x
  end
  true
end

gets.strip.to_i.times do
  n, x = read_array
  a = read_array
  b = read_array
  gets

  a.sort!
  b = b.sort.reverse
  if can(a, b, x)
    puts "Yes"
  else
    puts "No"
  end
end

def read
  gets.split.map &:to_i
end
q = gets.to_i
q.times do |t|
  n, x = read
  a, b = read, read
  a.sort!
  b.sort!.reverse!
  ok = true
  (0...n).each do |i|
    ok = false if a[i] + b[i] > x
  end
  puts ok ? "YES" : "NO"
  if t < q - 1
    gets
  end
end

def read
  gets.split.map &:to_i
end
q = gets.to_i
q.times do |t|
  n, x = read
  a, b = read, read
  a.sort!
  b.sort!.reverse!
  ok = true
  (0...n).each do |i|
    ok = false if a[i] + b[i] > x
  end
  print(ok ? "YES" : "NO")
  if t < q - 1
    gets
  end
end


Vasya had a strictly increasing sequence of positive integers a1, ..., an. Vasya used it to build a new sequence b1, ..., bn, where bi is the sum of digits of ai's decimal representation. Then sequence ai got lost and all that remained is sequence bi.Vasya wonders what the numbers ai could be like. Of all the possible options he likes the one sequence with the minimum possible last number an. Help Vasya restore the initial sequence.It is guaranteed that such a sequence always exists.

The first line contains a single integer number n (1 ≤ n ≤ 300). Next n lines contain integer numbers b1, ..., bn  — the required sums of digits. All bi belong to the range 1 ≤ bi ≤ 300.

Print n integer numbers, one per line — the correct option for numbers ai, in order of following in sequence. The sequence should be strictly increasing. The sum of digits of the i-th number should be equal to bi.  If there are multiple sequences with least possible number an, print any of them. Print the numbers without leading zeroes.

#!/usr/bin/env ruby

cur=[0]
gets.to_i.times{
	n=gets.to_i
	s=0
	idx=(cur.size.times.find{|i|s+=cur[i];s>=n}||cur.size)-1
	if idx==-1
		a=[1]+cur.map{|e|0}
	else
		a=cur.dup
		while a[idx]==9
			idx-=1
		end
		if idx>=0
			a[idx]+=1
		else
			a=[1]+a
			idx=0
		end
		(idx+1).upto(a.size-1){|i|a[i]=0}
	end
	#p a
	fill=n-a.reduce(:+)
	idx=a.size-1
	while idx>=0
		a[idx]+=fill
		fill=0
		if a[idx]>9
			fill=a[idx]-9
			a[idx]=9
		end
		idx-=1
	end
	d,r=fill.divmod(9)
	a=(r==0?[]:[r])+[9]*d+a
	cur=a
	puts cur*''
}

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

cur = [0]
gets.to_i.times {
  n = gets.to_i
  s = 0
  idx = (cur.size.times.find{|i|
    s += cur[i]
    s >= n
  } || cur.size) - 1
  if idx == -1
    x = [1] + [0] * cur.size
  else
    x = cur.dup
    while x[idx] == 9
      idx -= 1
    end
    if idx >= 0
      x[idx] += 1
    else
      x = [1] + x
      idx = 0
    end
    (idx + 1).upto(x.size - 1) {|i|
      x[i] = 0
    }
  end
  tot = n - x.reduce(:+)
  idx = x.size - 1
  while idx >= 0
    x[idx] += tot
    tot = 0
    if x[idx] > 9
      tot = x[idx] - 9
      x[idx] = 9
    end
    idx -= 1
  end
  l, r = tot.divmod(9)
  x = (r == 0 ? [] : [r]) + [9] * l + x
  cur = x
  puts cur.join
}

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

cur = [0]
gets.to_i.times {
  n = gets.to_i
  s = 0
  idx = (cur.size.times.find{|i|
    s += cur[i]
    s >= n
  } || cur.size) - 1
  x = cur.dup
  while x[idx] == 9
    idx -= 1
  end
  if idx >= 0
    x[idx] += 1
  else
    x = [1] + x
    idx = 0
  end
  (idx + 1).upto(x.size - 1) {|i|
    x[i] = 0
  }
  tot = n - x.reduce(:+)
  idx = x.size - 1
  while idx >= 0
    x[idx] += tot
    tot = 0
    if x[idx] > 9
      tot = x[idx] - 9
      x[idx] = 9
    end
    idx -= 1
  end
  l, r = tot.divmod(9)
  x = (r == 0 ? [] : [r]) + [9] * l + x
  cur = x
  puts cur.join
}

#!/usr/bin/env ruby

cur=[0]
gets.to_i.times{
	n=gets.to_i
	s=0
	idx=(cur.size.times.find{|i|s+=cur[i];s>n}||cur.size)-1
	if idx==-1
		a=[1]+cur.map{|e|0}
	else
		a=cur.dup
		while a[idx]==9
			idx-=1
		end
		if idx>=0
			a[idx]+=1
		else
			a=[1]+a
			idx=0
		end
		(idx+1).upto(a.size-1){|i|a[i]=0}
	end

	fill=n-a.reduce(:+)
	idx=a.size-1
	while idx>=0
		a[idx]+=fill
		fill=0
		if a[idx]>9
			fill=a[idx]-9
			a[idx]=9
		end
		idx-=1
	end
	d,r=fill.divmod(9)
	a=(r==0?[]:[r])+[9]*d+a
	cur=a
	puts cur*''
}

#!/usr/bin/env ruby
def gen(n)
	return to_enum(:gen,n) if !block_given?
	d,r=n.divmod(9)
	a=(r==0?[]:[r])+[9]*d
	digits=a.size
	loop{
		yield a.join.to_i
		idx_down=(a.size-1).downto(0).find{|i|a[i]!=0}
		if idx_down!=0 && idx_up=(idx_down-1).downto(0).find{|i|a[i]<9}
			a[idx_down]-=1
			a[idx_up]+=1
		else
			digits+=1
			d,r=(n-1).divmod(9)
			a=(r==0?[]:[r])+[9]*d
			while a.size<digits-1
				a.unshift(0)
			end
			a=[1]+a
		end
	}
end
cur=0
gets.to_i.times{
	n=gets.to_i
	nxt=gen(n).find{|e|e>cur}
	p nxt
	cur=nxt
}

#!/usr/bin/env ruby
def gen(n)
	return to_enum(:gen,n) if !block_given?
	d,r=n.divmod(9)
	a=(r==0?[]:[r])+[9]*d
	digits=a.size
	loop{
		yield a.join.to_i
		idx_down=(a.size-1).downto(0).find{|i|a[i]!=0}
		if idx_down!=0 && idx_up=(idx_down-1).downto(0).find{|i|a[i]<9}
			a[idx_down]-=1
			a[idx_up]+=1
			a=a[0,idx_down]+a[idx_down..-1].reverse
		else
			digits+=1
			d,r=(n-1).divmod(9)
			a=(r==0?[]:[r])+[9]*d
			while a.size<digits-1
				a.unshift(0)
			end
			a=[1]+a
		end
	}
end
cur=0
gets.to_i.times{
	n=gets.to_i
	nxt=gen(n).find{|e|e>cur}
	p nxt
	cur=nxt
}

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

cur = [0]
gets.to_i.times {
  n = gets.to_i
  s = 0
  idx = (cur.size.times.find{|i|
    s += cur[i]
    s >= n
  } || cur.size) - 1
  x = cur.dup
  while x[idx] == 9
    idx -= 1
  end
  if idx >= 0
    x[idx] += 1
  else
    x = [1] + x
    idx = 0
  end
  (idx + 1).upto(x.size - 1) {|i|
    x[i] = 0
  }
  tot = n - x.reduce(:+)
  idx = 0
  while idx < x.size
    x[idx] += tot
    tot = 0
    if x[idx] > 9
      tot = x[idx] - 9
      x[idx] = 9
    end
    idx += 1
  end
  l, r = tot.divmod(9)
  x = (r == 0 ? [] : [r]) + [9] * l + x
  cur = x
  puts cur.join
}

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

cur = [0]
gets.to_i.times {
  n = gets.to_i
  s = 0
  idx = (cur.size.times.find{|i|
    s += cur[i]
    s >= n
  } || cur.size) - 1
  if idx == -1
    x = [1] + [0] * cur.size
  else
    x = cur.dup
    while x[idx] == 9
      idx -= 1
    end
    if idx >= 0
      x[idx] += 1
    else
      x = [1] + x
      idx = 0
    end
    (idx + 1).upto(x.size - 1) {|i|
      x[i] = 0
    }
  end
  tot = n - x.reduce(:+)
  idx = x.size - 1
  while idx >= 0
    x[idx] += tot
    tot = 0
    if x[idx] > 9
      tot = x[idx] - 9
      x[idx] = 9
    end
    idx -= 1
  end
  l, r = tot.divmod(9)
  x = (r == 0 ? [] : [r]) + [9] * l + x
  cur = x
  puts cur.to_s
}


Denis was very sad after Nastya rejected him. So he decided to walk through the gateways to have some fun. And luck smiled at him! When he entered the first courtyard, he met a strange man who was selling something. Denis bought a mysterious item and it was... Random permutation generator! Denis could not believed his luck.When he arrived home, he began to study how his generator works and learned the algorithm. The process of generating a permutation consists of $$$n$$$ steps. At the $$$i$$$-th step, a place is chosen for the number $$$i$$$ $$$(1 \leq i \leq n)$$$. The position for the number $$$i$$$ is defined as follows:  For all $$$j$$$ from $$$1$$$ to $$$n$$$, we calculate $$$r_j$$$  — the minimum index such that $$$j \leq r_j \leq n$$$, and the position $$$r_j$$$ is not yet occupied in the permutation. If there are no such positions, then we assume that the value of $$$r_j$$$ is not defined.  For all $$$t$$$ from $$$1$$$ to $$$n$$$, we calculate $$$count_t$$$  — the number of positions $$$1 \leq j \leq n$$$ such that $$$r_j$$$ is defined and $$$r_j = t$$$.  Consider the positions that are still not occupied by permutation and among those we consider the positions for which the value in the $$$count$$$ array is maximum.  The generator selects one of these positions for the number $$$i$$$. The generator can choose any position. Let's have a look at the operation of the algorithm in the following example:  Let $$$n = 5$$$ and the algorithm has already arranged the numbers $$$1, 2, 3$$$ in the permutation. Consider how the generator will choose a position for the number $$$4$$$:  The values of $$$r$$$ will be $$$r = [3, 3, 3, 4, \times]$$$, where $$$\times$$$ means an indefinite value.  Then the $$$count$$$ values will be $$$count = [0, 0, 3, 1, 0]$$$.  There are only two unoccupied positions in the permutation: $$$3$$$ and $$$4$$$. The value in the $$$count$$$ array for position $$$3$$$ is $$$3$$$, for position $$$4$$$ it is $$$1$$$.  The maximum value is reached only for position $$$3$$$, so the algorithm will uniquely select this position for number $$$4$$$. Satisfied with his purchase, Denis went home. For several days without a break, he generated permutations. He believes that he can come up with random permutations no worse than a generator. After that, he wrote out the first permutation that came to mind $$$p_1, p_2, \ldots, p_n$$$ and decided to find out if it could be obtained as a result of the generator.Unfortunately, this task was too difficult for him, and he asked you for help. It is necessary to define whether the written permutation could be obtained using the described algorithm if the generator always selects the position Denis needs.

The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^5)$$$  — the number of test cases. Then the descriptions of the test cases follow. The first line of the test case contains a single integer $$$n$$$ $$$(1 \leq n \leq 10^5)$$$  — the size of the permutation. The second line of the test case contains $$$n$$$ different integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$)  — the permutation written by Denis. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

Print "Yes" if this permutation could be obtained as a result of the generator. Otherwise, print "No". All letters can be displayed in any case.

NoteLet's simulate the operation of the generator in the first test.At the $$$1$$$ step, $$$r = [1, 2, 3, 4, 5], count = [1, 1, 1, 1, 1]$$$. The maximum value is reached in any free position, so the generator can choose a random position from $$$1$$$ to $$$5$$$. In our example, it chose $$$5$$$.At the $$$2$$$ step, $$$r = [1, 2, 3, 4, \times], count = [1, 1, 1, 1, 0]$$$. The maximum value is reached in positions from $$$1$$$ to $$$4$$$, so the generator can choose a random position among them. In our example, it chose $$$1$$$.At the $$$3$$$ step, $$$r = [2, 2, 3, 4, \times], count = [0, 2, 1, 1, 0]$$$. The maximum value is $$$2$$$ and is reached only at the $$$2$$$ position, so the generator will choose this position.At the $$$4$$$ step, $$$r = [3, 3, 3, 4, \times], count = [0, 0, 3, 1, 0]$$$. The maximum value is $$$3$$$ and is reached only at the $$$3$$$ position, so the generator will choose this position.At the $$$5$$$ step, $$$r = [4, 4, 4, 4, \times], count = [0, 0, 0, 4, 0]$$$. The maximum value is $$$4$$$ and is reached only at the $$$4$$$ position, so the generator will choose this position.In total, we got a permutation of $$$2, 3, 4, 5, 1$$$, that is, a generator could generate it.

def naive(arr)
  possible = "YES"
  hash = {}
  arr.each_with_index{|e,i| hash[e] = i+1}
  rj = Array.new(arr.size+1){|e| e>0 ? e : -1}
  puts hash.inspect
  puts rj.inspect
  (1..arr.size).each do |e|
    count = [-1]
    rj.each{|e| count[e]=(count[e]||0)+1 if e>0}
    puts count.inspect
    if count.max == count[hash[e]]
      pos = hash[e]
      rj.each_with_index do |e,i|
      end
      hash.delete(e)
    else
      break
    end
  end
  possible
end

def solve(arr)
  solvable = "YES"
  arr.each_with_index do |e,i|
    if i>0 and arr[i-1]<arr[i]-1
      solvable="NO"
      break
    end
  end
  solvable
end

tc = gets.chomp.to_i
while tc>0
  size = gets.chomp.to_i
  arr = gets.chomp.split(" ").map{|e| e.to_i}
  puts solve(arr)
  tc -= 1
end


Let's denote a $$$k$$$-step ladder as the following structure: exactly $$$k + 2$$$ wooden planks, of which  two planks of length at least $$$k+1$$$ — the base of the ladder;  $$$k$$$ planks of length at least $$$1$$$ — the steps of the ladder; Note that neither the base planks, nor the steps planks are required to be equal.For example, ladders $$$1$$$ and $$$3$$$ are correct $$$2$$$-step ladders and ladder $$$2$$$ is a correct $$$1$$$-step ladder. On the first picture the lengths of planks are $$$[3, 3]$$$ for the base and $$$[1]$$$ for the step. On the second picture lengths are $$$[3, 3]$$$ for the base and $$$[2]$$$ for the step. On the third picture lengths are $$$[3, 4]$$$ for the base and $$$[2, 3]$$$ for the steps.   You have $$$n$$$ planks. The length of the $$$i$$$-th planks is $$$a_i$$$. You don't have a saw, so you can't cut the planks you have. Though you have a hammer and nails, so you can assemble the improvised "ladder" from the planks.The question is: what is the maximum number $$$k$$$ such that you can choose some subset of the given planks and assemble a $$$k$$$-step ladder using them?

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. The queries are independent. Each query consists of two lines. The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of planks you have. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$) — the lengths of the corresponding planks. It's guaranteed that the total number of planks from all queries doesn't exceed $$$10^5$$$.

Print $$$T$$$ integers — one per query. The $$$i$$$-th integer is the maximum number $$$k$$$, such that you can choose some subset of the planks given in the $$$i$$$-th query and assemble a $$$k$$$-step ladder using them. Print $$$0$$$ if you can't make even $$$1$$$-step ladder from the given set of planks.

NoteExamples for the queries $$$1-3$$$ are shown at the image in the legend section.The Russian meme to express the quality of the ladders:

t = gets.to_i
t.times do |i|
    n = gets.to_i
    a = gets.split.map(&:to_i)
    b = c = 0
    n.times do |i|
        c = a[i] if c < a[i]
        b,c = c,b if c > b
    end
    puts (c-1 < n-2 ? c-1 : n-2)
end

gets.to_i.times do
  n = gets.to_i
  a, b = gets.split.map(&:to_i).sort.reverse
  p [a-1, b-1, n-2].min
end


Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally.

The first line of the input contains three integers n, m, k (1 ≤ n, m, k ≤ 1000) — the number of the planned days, the number of clean bowls and the number of clean plates. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish.

Print a single integer — the minimum number of times Valera will need to wash a plate/bowl.

NoteIn the first sample Valera will wash a bowl only on the third day, so the answer is one.In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once.In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl.

n, m, k = gets.split(' ').map(&:to_i)
wash = 0
gets.split(' ',n).map(&:to_i).each do |x|
  if x == 1
    m > 0  ? m -= 1 : wash += 1
  elsif k > 0
    k -= 1
  elsif m > 0
    m -= 1
  else
    wash += 1
  end
end
puts wash

n, m, k = gets.split.map(&:to_i)
n = 0
gets.split.map(&:to_i).each do |a|
  if a == 2 and k > 0
    k -= 1
  else
    (m > 0) ? m -= 1 : n += 1
  end
end
puts n

n, m, k = gets.chomp.split.map(&:to_i);
arr = gets.chomp.split.map(&:to_i);
ans = 0;

arr.each do |x|
  if (x == 1) then
    if (m > 0)
      m -= 1;
    else
      ans += 1;
    end
  elsif (k > 0)
    k -= 1;
  elsif (m > 0)
    m -= 1;
  else
    ans += 1;
  end
end
p ans;

#!/usr/bin/ruby

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

r = 0
a.each do |x|
  if x == 1
    m -= 1
  else # x == 2
    if k > 0
      k -= 1
    else
      m -= 1
    end
  end

  if m < 0
    m += 1
    r += 1
  elsif k < 0
    k += 1
    r += 1
  end
end

puts r

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

    type_list.each do |type|
      if type == 1
        if m > 0
          m -= 1
        else
          cnt += 1
        end
      else
        if k > 0
          k -= 1
        elsif m > 0
          m -= 1
        else
          cnt += 1
        end
      end
    end

    puts cnt
  end
end

A.new

n,m,k=gets.split.map{|e| e.to_i}
xs=gets.split.map{|e| e.to_i}
ans=0
c1=xs.count{|e|
	e==1
}
c2=xs.count{|e|
	e==2
}
ans=0
if c1>m
	ans=c1-m
else
	k=m+k-c1
end
ans+=c2-k if c2>k
puts ans

l = gets.split(" ").map { |e| e.to_i }
glub = l[1]
plos = l[2]
ans = 0
mas = gets.split(" ").map { |e| e.to_i }
mas.each { |e|
	if e == 1 then
		if glub > 0 then
			glub -= 1
		else
			ans +=1
		end
	else
		if plos > 0 then
				plos -= 1
		elsif glub > 0
			glub -= 1
		else
			ans +=1
		end
	end
}
puts ans

def read_next_line
  gets.split.map { |x| x.to_i }
end

_, m, k = read_next_line
a = read_next_line.inject(Hash.new(0)) { |h, e| h[e] += 1; h }
d = 0
c = m - a[1]
if c > 0
  k += c
else
  d = -c
end
d += [a[2] - k, 0].max
puts d


Berland shop sells $$$n$$$ kinds of juices. Each juice has its price $$$c_i$$$. Each juice includes some set of vitamins in it. There are three types of vitamins: vitamin "A", vitamin "B" and vitamin "C". Each juice can contain one, two or all three types of vitamins in it.Petya knows that he needs all three types of vitamins to stay healthy. What is the minimum total price of juices that Petya has to buy to obtain all three vitamins? Petya obtains some vitamin if he buys at least one juice containing it and drinks it.

The first line contains a single integer $$$n$$$ $$$(1 \le n \le 1\,000)$$$ — the number of juices. Each of the next $$$n$$$ lines contains an integer $$$c_i$$$ $$$(1 \le c_i \le 100\,000)$$$ and a string $$$s_i$$$ — the price of the $$$i$$$-th juice and the vitamins it contains. String $$$s_i$$$ contains from $$$1$$$ to $$$3$$$ characters, and the only possible characters are "A", "B" and "C". It is guaranteed that each letter appears no more than once in each string $$$s_i$$$. The order of letters in strings $$$s_i$$$ is arbitrary.

Print -1 if there is no way to obtain all three vitamins. Otherwise print the minimum total price of juices that Petya has to buy to obtain all three vitamins.

NoteIn the first example Petya buys the first, the second and the fourth juice. He spends $$$5 + 6 + 4 = 15$$$ and obtains all three vitamins. He can also buy just the third juice and obtain three vitamins, but its cost is $$$16$$$, which isn't optimal.In the second example Petya can't obtain all three vitamins, as no juice contains vitamin "C".

def solution

  n = gets.to_i

  prices = {}

  n.times do
    p, l = gets.chomp.split(' ')
    price = p.to_i
    vits = l.chars.sort.join

    prices[vits] = price if prices[vits].nil? || prices[vits] > price
  end

  def eval_price(prices, fragments)
    frag_prices = fragments.map{ |f| prices[f] }
    frag_prices.reduce(0, :+)
  rescue
    nil
  end

  possibilities = [
    %w"ABC",
    %w"A B C",
    %w"A BC",
    %w"AB C",
    %w"B AC",
    %w"AB AC",
    %w"AB BC",
    %w"AC AB",
    %w"AC BC",
  ]

  cheapest = possibilities.map{ |p| eval_price(prices, p) }.compact.min || -1

  puts cheapest
end

solution unless ENV['TEST__MODE']

n = gets.to_i
m = n.times.map{gets.split}
n.times do |i|
  m[i][0] = m[i][0].to_i
end

def clac_min(str,n,m)
  ret = 10**6
  for i in 0..n-1
    if str.size == 1
      if m[i][1].include?(str)
        ret = m[i][0] if m[i][0] < ret
      end
    elsif str.size == 2
      if m[i][1].include?(str[0]) && m[i][1].include?(str[1])
        ret = m[i][0] if m[i][0] < ret
      end
    else
      if m[i][1].include?(str[0]) && m[i][1].include?(str[1]) && m[i][1].include?(str[2])
        ret = m[i][0] if m[i][0] < ret
      end
    end
  end
  return ret
end

a,b,c = clac_min("A",n,m),clac_min("B",n,m),clac_min("C",n,m)
ab,bc,ca = [clac_min("AB",n,m),a+b].min,ab = [clac_min("BC",n,m),b+c].min,ab = [clac_min("CA",n,m),c+a].min
abc = [a+b+c,ab+c,a+bc,b+ca,clac_min("ABC",n,m)].min
puts abc == 10**6 ? -1 : abc

n = gets.to_i
array = Array.new

n.times do
  miniarr = gets.chomp.split(" ")
  miniarr[0] = miniarr[0].to_i
  miniarr[1] = miniarr[1].each_char.to_a.sort.join("")
  array.push miniarr
end
#p array

combcost = Hash.new(1000000)

array.each do |juice|
  cost = juice[0]
  type = juice[1]

  if cost < combcost[type]
    combcost[type] = cost
  end
end

ans = [combcost["A"]+combcost["B"]+combcost["C"],combcost["A"]+combcost["BC"],combcost["AB"]+combcost["C"],combcost["B"]+combcost["AC"],combcost["AB"]+combcost["BC"],combcost["AC"]+combcost["BC"],combcost["AB"]+combcost["AC"],combcost["ABC"]].min

if ans>300000
  ans = -1
end
puts ans


Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 ≤ u, v ≤ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.

The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 ≤ a, b ≤ n and a ≠ b).

nodes, edges = gets.split(' ').map(&:to_i)
g = {}
edges.times do
  from, to = gets.split(' ').map(&:to_i)
  g[from] ||= []
  g[from].push(to)
  g[to] ||= []
  g[to].push(from)
end

$g = g
$max = 0

n, = $g.find { |n, nxts| nxts.size <= 1 }
_stack = [[n, 0, 0]]
_entries = {}

while !_stack.empty?
  _entry = _stack.last
  node, path, prev = _entry

  all = true
  ($g[node] || []).each { |nxt|
    if nxt != prev
      e = [nxt, path+1, node]
      if !_entries[e]
        all = false
        _stack.push(e)
      end
    end
  }
  next unless all

  paths = ($g[node] || []).map { |nxt|
    if nxt == prev
      0
    else
      1 + _entries[[nxt, path + 1, node]]
    end
  }

  _entries[_entry] = paths.max
  _stack.pop

  paths.push(path)
  m1, i1 = paths.each_with_index.max_by(&:first)
  paths.delete_at(i1)
  $max = [m1 + paths.max, $max].max
end

puts $max

nodes, edges = gets.split(' ').map(&:to_i)
g = {}
edges.times do
  from, to = gets.split(' ').map(&:to_i)
  g[from] ||= []
  g[from].push(to)
  g[to] ||= []
  g[to].push(from)
end

$g = g
$visited = {}

$max = 0

def dfs(node, path)
  return 0 if $visited[node]
  $visited[node] = true

  paths = ($g[node] || []).map { |nxt|
    if $visited[nxt]
      0
    else
      1 + dfs(nxt, path + 1)
    end
  }
  m_next = paths.max

  paths.push(path)
  m1 = paths.max
  paths.delete(m1)
  $max = [m1 + paths.max, $max].max

  m_next
end

n, = $g.find { |n, nxts| nxts.size <= 1 }
puts dfs($g.first.first, 0)

nodes, edges = gets.split(' ').map(&:to_i)
g = {}
edges.times do
  from, to = gets.split(' ').map(&:to_i)
  g[from] ||= []
  g[from].push(to)
  g[to] ||= []
  g[to].push(from)
end

$g = g
$visited = {}

def dfs(node)
  return if $visited[node]
  $visited[node] = true

  max = 0
  ($g[node] || []).each { |nxt|
    if !$visited[nxt]
      max = [1 + dfs(nxt), max].max
    end
  }
  max
end

n, = $g.find { |n, nxts| nxts.size <= 1 }
puts dfs(n)

nodes, edges = gets.split(' ').map(&:to_i)
g = {}
edges.times do
  from, to = gets.split(' ').map(&:to_i)
  g[from] ||= []
  g[from].push(to)
  g[to] ||= []
  g[to].push(from)
end

$g = g
$visited = {}

def dfs(node)
  return 0 if $visited[node]
  $visited[node] = true

  max = 0
  ($g[node] || []).each { |nxt|
    if !$visited[nxt]
      max = [1 + dfs(nxt), max].max
    end
  }
  max
end

n, = $g.find { |n, nxts| nxts.size <= 1 }
puts dfs(n)

nodes, edges = gets.split(' ').map(&:to_i)
g = {}
edges.times do
  from, to = gets.split(' ').map(&:to_i)
  g[from] ||= []
  g[from].push(to)
  g[to] ||= []
  g[to].push(from)
end

$g = g
$visited = {}
$max = 0

n, = $g.find { |n, nxts| nxts.size <= 1 }
_stack = [[n, 0]]
_entries = {}

while !_stack.empty?
  _entry = _stack.last
  node, path = _entry

  $visited[node] = true

  all = true
  ($g[node] || []).each { |nxt|
    if !$visited[nxt]
      e = [nxt, path+1]
      if !_entries[e]
        all = false
        _stack.push(e)
      end
    end
  }
  next unless all

  paths = ($g[node] || []).map { |nxt|
    if $visited[nxt]
      0
    else
      1 + _entries[[nxt, path + 1]]
    end
  }

  _entries[_entry] = paths.max
  _stack.pop

  paths.push(path)
  m1, i1 = paths.each_with_index.max_by(&:first)
  paths.delete_at(i1)
  $max = [m1 + paths.max, $max].max
end

puts $max


Petya's friends made him a birthday present — a bracket sequence. Petya was quite disappointed with his gift, because he dreamed of correct bracket sequence, yet he told his friends nothing about his dreams and decided to fix present himself. To make everything right, Petya is going to move at most one bracket from its original place in the sequence to any other position. Reversing the bracket (e.g. turning "(" into ")" or vice versa) isn't allowed. We remind that bracket sequence $$$s$$$ is called correct if:   $$$s$$$ is empty;  $$$s$$$ is equal to "($$$t$$$)", where $$$t$$$ is correct bracket sequence;  $$$s$$$ is equal to $$$t_1 t_2$$$, i.e. concatenation of $$$t_1$$$ and $$$t_2$$$, where $$$t_1$$$ and $$$t_2$$$ are correct bracket sequences. For example, "(()())", "()" are correct, while ")(" and "())" are not. Help Petya to fix his birthday present and understand whether he can move one bracket so that the sequence becomes correct.

First of line of input contains a single number $$$n$$$ ($$$1 \leq n \leq 200\,000$$$) — length of the sequence which Petya received for his birthday. Second line of the input contains bracket sequence of length $$$n$$$, containing symbols "(" and ")".

Print "Yes" if Petya can make his sequence correct moving at most one bracket. Otherwise print "No".

NoteIn the first example, Petya can move first bracket to the end, thus turning the sequence into "()", which is correct bracket sequence.In the second example, there is no way to move at most one bracket so that the sequence becomes correct.In the third example, the sequence is already correct and there's no need to move brackets.

n = gets.to_i
s = gets.chomp

can=false
wrong=0
cnt=0
n.times do |i|
  c = s[i]
  if c=='('
    cnt+=1
  else
    cnt-=1
  end

  if cnt<0
    wrong+=1
    cnt=0
  end

  if wrong>1
    puts 'No'
    exit
  end
end

if cnt-wrong==0
  can=true
end
puts can ? 'Yes' : 'No'


Everything got unclear to us in a far away constellation Tau Ceti. Specifically, the Taucetians choose names to their children in a very peculiar manner.Two young parents abac and bbad think what name to give to their first-born child. They decided that the name will be the permutation of letters of string s. To keep up with the neighbours, they decided to call the baby so that the name was lexicographically strictly larger than the neighbour's son's name t.On the other hand, they suspect that a name tax will be introduced shortly. According to it, the Taucetians with lexicographically larger names will pay larger taxes. That's the reason abac and bbad want to call the newborn so that the name was lexicographically strictly larger than name t and lexicographically minimum at that.The lexicographical order of strings is the order we are all used to, the "dictionary" order. Such comparison is used in all modern programming languages to compare strings. Formally, a string p of length n is lexicographically less than string q of length m, if one of the two statements is correct:  n < m, and p is the beginning (prefix) of string q (for example, "aba" is less than string "abaa"),  p1 = q1, p2 = q2, ..., pk - 1 = qk - 1, pk < qk for some k (1 ≤ k ≤ min(n, m)), here characters in strings are numbered starting from 1. Write a program that, given string s and the heighbours' child's name t determines the string that is the result of permutation of letters in s. The string should be lexicographically strictly more than t and also, lexicographically minimum.

The first line contains a non-empty string s (1 ≤ |s| ≤ 5000), where |s| is its length. The second line contains a non-empty string t (1 ≤ |t| ≤ 5000), where |t| is its length. Both strings consist of lowercase Latin letters.

Print the sought name or -1 if it doesn't exist.

NoteIn the first sample the given string s is the sought one, consequently, we do not need to change the letter order there.

#!/usr/bin/ruby

def winning(list, target)
  str = ""
  list.keys.sort.reverse.each do |key|
    str << key*list[key]
  end
  str > target
end

def minstr(list)
  arr = []
  list.each_pair do |key,val|
    arr += [key]*val
  end
  arr.sort.join
end

def search(cur, max, list, target)
  substr = target[cur+1..-1] || ''
  tc = target[cur] || ''

  #puts "#{cur} #{list}"

  if list[tc] > 0
    list[tc] -= 1
    if winning(list, substr)
      res = search(cur+1, max, list, target)
      if res
        return tc+res
      end
    end
    list[tc] += 1
  end

  # find next char
  nc = list.keys.sort.find{|k| k>tc and list[k]>0}
  if nc
    list[nc] -= 1
    return nc+minstr(list)
  end

  nil
end

s = gets.chomp
t = gets.chomp

list = Hash.new(0)
s.each_char do |c|
  list[c] += 1
end

ans = search(0, s.size, list, t)
if ans.nil?
  ans = -1
end
puts ans

#!/usr/bin/ruby

def winning(list, target)
  arr = []
  list.each_pair do |key, val|
    arr += [key]*val
  end
  arr.sort.reverse.join > target
end

def minstr(list)
  arr = []
  list.each_pair do |key,val|
    arr += [key]*val
  end
  arr.sort.join
end

def search(cur, max, list, target)
  substr = target[cur+1..-1] || ''
  tc = target[cur] || ''

  #puts "#{cur} #{list}"

  if list[tc] > 0
    list[tc] -= 1
    if winning(list, substr)
      res = search(cur+1, max, list, target)
      if res
        return tc+res
      end
    end
    list[tc] += 1
  end

  # find next char
  nc = list.keys.find{|k| k>tc and list[k]>0}
  if nc
    list[nc] -= 1
    return nc+minstr(list)
  end

  nil
end

s = gets.chomp
t = gets.chomp

list = Hash.new(0)
s.each_char do |c|
  list[c] += 1
end

ans = search(0, s.size, list, t)
if ans.nil?
  ans = -1
end
puts ans

#!/usr/bin/ruby

def winning(list, target)
  arr = []
  list.each_pair do |key, val|
    arr += [key]*val
  end
  arr.sort.reverse.join > target
end

def minstr(list)
  arr = []
  list.each_pair do |key,val|
    arr += [key]*val
  end
  arr.sort.join
end

def search(cur, max, list, target)
  substr = target[cur+1..-1] || ''
  tc = target[cur] || ''

  #puts "#{cur} #{list}"
  if cur == max-1
    last = list.find{|v| v[1] == 1}
    return last[0]
  end

  if list[tc] > 0
    list[tc] -= 1
    if winning(list, substr)
      res = search(cur+1, max, list, target)
      if res
        return tc+res
      end
    end
    list[tc] += 1
  end

  # find next char
  nc = list.keys.find{|k| k>tc and list[k]>0}
  if nc
    list[nc] -= 1
    return nc+minstr(list)
  end

  nil
end

s = gets.chomp
t = gets.chomp

list = Hash.new(0)
s.each_char do |c|
  list[c] += 1
end

ans = search(0, s.size, list, t)
if ans.nil?
  ans = -1
end
puts ans


Nezzar's favorite digit among $$$1,\ldots,9$$$ is $$$d$$$. He calls a positive integer lucky if $$$d$$$ occurs at least once in its decimal representation. Given $$$q$$$ integers $$$a_1,a_2,\ldots,a_q$$$, for each $$$1 \le i \le q$$$ Nezzar would like to know if $$$a_i$$$ can be equal to a sum of several (one or more) lucky numbers.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 9$$$) — the number of test cases. The first line of each test case contains two integers $$$q$$$ and $$$d$$$ ($$$1 \le q \le 10^4$$$, $$$1 \le d \le 9$$$). The second line of each test case contains $$$q$$$ integers $$$a_1,a_2,\ldots,a_q$$$ ($$$1 \le a_i \le 10^9$$$).

For each integer in each test case, print "YES" in a single line if $$$a_i$$$ can be equal to a sum of lucky numbers. Otherwise, print "NO". You can print letters in any case (upper or lower).

YES
NO
YES
YES
YES
NO
YES
YES
YES
YES
YES
YES
NO

NoteIn the first test case, $$$24 = 17 + 7$$$, $$$27$$$ itself is a lucky number, $$$25$$$ cannot be equal to a sum of lucky numbers.

gets.to_i.times do
  q,d=gets.split.map(&:to_i)
  a=gets.split.map(&:to_i)
  a.each do |aa|
    if aa>=100
      puts "YES"
    else
      f=false
      while aa>0
        if aa/10==d||aa%10==d
          puts "YES"
          f=true
          break
        end
        aa-=d
      end
      puts "NO" if !f
    end
  end
end

gets.to_i.times do
  q,d=gets.split.map(&:to_i)
  a=gets.split.map(&:to_i)
  a.each do |aa|
    if d==1
      puts "YES"
    elsif d==2
      if aa>=20||aa.even?
        puts "YES"
      else
        puts "NO"
      end
    elsif d==3
      if aa>=21||aa%3==0||[13,16,19].include?(aa)
        puts "YES"
      else
        puts "NO"
      end
    elsif d==4
      if aa>=40||aa%4==0||aa>=14&&aa%4==2
        puts "YES"
      else
        puts "NO"
      end
    elsif d==5
      if aa>=50||aa%5==0
        puts "YES"
      else
        puts "NO"
      end
    elsif d==6
      if aa>=60||aa%6==0||aa>=22&&aa%2==0||aa==16
        puts "YES"
      else
        puts "NO"
      end
    elsif d==7
      if aa>=61||aa%7==0||aa>=17&&aa%7==3||aa>=27&&aa%7==6||aa>=37&&aa%7==2||[47,54,57].include?(aa)
        puts "YES"
      else
        puts "NO"
      end
    elsif d==8
      if aa>=80||aa%8==0||aa>=32&&aa%2==0||[18,26,28].include?(aa)
        puts "YES"
      else
        puts "NO"
      end
    elsif d==9
      if aa>=81||aa/10+aa%10>=9
        puts "YES"
      else
        puts "NO"
      end
    end
  end
end


The Little Elephant loves sortings.He has an array a consisting of n integers. Let's number the array elements from 1 to n, then the i-th element will be denoted as ai. The Little Elephant can make one move to choose an arbitrary pair of integers l and r (1 ≤ l ≤ r ≤ n) and increase ai by 1 for all i such that l ≤ i ≤ r.Help the Little Elephant find the minimum number of moves he needs to convert array a to an arbitrary array sorted in the non-decreasing order. Array a, consisting of n elements, is sorted in the non-decreasing order if for any i (1 ≤ i < n) ai ≤ ai + 1 holds.

The first line contains a single integer n (1 ≤ n ≤ 105) — the size of array a. The next line contains n integers, separated by single spaces — array a (1 ≤ ai ≤ 109). The array elements are listed in the line in the order of their index's increasing.

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

NoteIn the first sample the array is already sorted in the non-decreasing order, so the answer is 0.In the second sample you need to perform two operations: first increase numbers from second to third (after that the array will be: [3, 3, 2]), and second increase only the last element (the array will be: [3, 3, 3]).In the third sample you should make at least 6 steps. The possible sequence of the operations is: (2; 3), (2; 3), (2; 3), (3; 3), (3; 3), (3; 3). After that the array converts to [7, 7, 7, 47].

gets
a = gets.split.map &:to_i
s = 0
a.each_cons(2){ |i,j| s += i-j if j<i }
puts s

gets
s=0
gets.split.map(&:to_i).each_cons(2){|i,j|s+=i-j if j<i}
puts s

class Array
  def is_decreasing_order
    a = self.first
    for i in 1 .. (self.length - 1) do
      if a > self[i]
        return false
      end
      a = self[i]
    end
    return true
  end
end

n = gets.chomp.to_i
a = gets.chomp.split(" ").map{|e| e.to_i}
c = 0

for i in 1 .. (n - 1) do
  first = a[i - 1]
  second = a[i]

  if first > second
    d = first - second
    """
    for j in i .. (n -1) do
      a[j] += d
    end
    """
    c += d
  end
end

puts c

#!/usr/bin/ruby

num_entries = gets.to_i
line = gets

numbers = line.split(' ')
numbers.map! {|e| e.to_i}
counter = 0

numbers.each_index { |i|
  break if(i == numbers.length-1)
  if(numbers[i] > numbers[i+1])
    diff = numbers[i] - numbers[i+1]
    counter += diff
  end
}

puts counter

n=gets.to_i
b=gets.chomp.split.map(&:to_i)
a,ans=b.shift,0
b.each do |i|
	ans+= (a>i) ? a-i : 0
	a=i
end
puts ans

gets
a = gets.split.map(&:to_i)
r = 0
(1..a.length-1).each do |i|
  k = a[i-1]-a[i]
  r+=k if k>=0
end
puts r

n = gets.to_i
a = gets.split.map { |i| i.to_i }
r = 0
0.upto(n - 2) { |i|
   r += a[i] - a[i + 1] if(a[i] > a[i + 1])
}
puts r

n = gets.to_i
a = gets.split.map { |i| i.to_i }
puts (0..n - 2).inject(0) { |r, i|
   r + [0, a[i] - a[i + 1]].max
}

n=gets.to_i
a=gets.split.map &:to_i
s=0
(n-1).times{|i|s+=[0,a[i]-a[i+1]].max}
p s

n = gets.to_i
a = gets.split.map { |i| i.to_i }
c =  0
1.upto(n - 1) { |i|
   if a[i - 1] > a[i]
      c = [c, a[i - 1] - a[i]].max
      a[i] = a[i - 1]
   end
}
puts c

n = gets.to_i
a = gets.split.map { |i| i.to_i }
c, r = 0, 0
1.upto(n - 1) { |i|
   if a[i - 1] > a[i]
      c = [c, a[i - 1] - a[i]].max
      a[i] += c
      r = c
   end
}
puts c

n = gets.to_i
a = gets.split.map { |i| i.to_i }
c, d, r = 0, 1 << 40, 0
1.upto(n - 1) { |i|
   if a[i] < a[i - 1]
      c = [c, a[i - 1]].max
      d = [d, a[i]].min
   else
      r += c - d
      c, d = 0, 1 << 40
   end
}
puts r + [0, c - d].max

n = gets.to_i
a = gets.split.map { |i| i.to_i }
c, r = 0, 0
1.upto(n - 1) { |i|
   if a[i - 1] > a[i]
      c = [c, a[i - 1] - a[i]].max
      a[i] += c
      r += c
   end
}
puts c

n = gets.to_i
a = gets.split.map { |i| i.to_i }
puts (0..n - 2).inject { |r, i|
   r + [0, a[i] - a[i + 1]].max
}

n = gets.to_i
a = gets.split.map { |i| i.to_i }
c, r = 0, 0
1.upto(n - 1) { |i|
   if a[i] < a[i - 1]
      c = [c, a[i - 1] - a[i]].max
      a[i] = a[i - 1]
   else
      r += c
      c = 0
   end
}
puts r + c

n = gets.to_i
a = gets.split.map { |i| i.to_i }
c, r= 0, 0
1.upto(n - 1) { |i|
   if a[i - 1] > a[i]
      c = a[i - 1] - a[i]
      a[i] += c
      r += c
   end
}
puts c


You are given an integer a that consists of n digits. You are also given a sequence of digits s of length m. The digit in position j (1 ≤ j ≤ m) of sequence s means that you can choose an arbitrary position i (1 ≤ i ≤ n) in a and replace the digit in the chosen position i with sj. Each element in the sequence s can participate in no more than one replacing operation.Your task is to perform such sequence of replacements, that the given number a gets maximum value. You are allowed to use not all elements from s.

The first line contains positive integer a. Its length n is positive and doesn't exceed 105. The second line contains sequence of digits s. Its length m is positive and doesn't exceed 105. The digits in the sequence s are written consecutively without any separators. The given number a doesn't contain leading zeroes.

Print the maximum value that can be obtained from a after a series of replacements. You are allowed to use not all elements from s. The printed number shouldn't contain any leading zeroes.

a = gets.scan(/\d/).map(&:to_i)
c = [0] * 10
gets.scan(/\d/) do |_|
    c[_.to_i] += 1
end
a.size.times do |i|
    k = c.rindex{|_| _ > 0}
    if k && k > a[i]
        a[i] = k
        c[k] -= 1
    end
end
puts a * ''

given = STDIN.readline.strip.split('')
digits = STDIN.readline.strip.split('').sort.reverse
pos = 0
digits.each do |digit|
  while pos < given.length and given[pos] >= digit
    pos += 1
  end
  break if pos == given.length
  given[pos] = digit
  pos += 1
end
puts given.join

a = readline.strip.each_char.to_a
s = readline.strip.each_char.to_a.sort

ans = a.each.map { |ai| (ai.to_i >= s.last.to_i) ? ai : s.pop }
puts ans.join

# encoding: utf-8

def string_to_digit_array(s)
  ret = []
  s.each_char do |c|
    ret << c
  end
  ret
end

a = string_to_digit_array(readline.strip)
s = string_to_digit_array(readline.strip).sort

ans = []
a.each do |digit|
  if digit.to_i >= s.last.to_i
    ans << digit
  else
    ans << s.pop
  end
end

puts ans.join

# ProblemB.rb

a = gets.chomp.split(//)
s = gets.chomp

s = s.split(//).sort.reverse

j = 0
a.each_with_index do |c, i|
  if j == s.size
    break
  end
  if c < s[j]
    a[i] = s[j]
    j += 1
  end
end

puts a.join

n = gets.chomp.split("")
dlina = n.length
k = gets.chomp.split("")
dlina2 = k.length
k = k.sort
p = dlina2-1

for i in (0..dlina-1)
    n[i] = n[i].to_i
end

for i in (0..p)
    k[i] = k[i].to_i
end

for i in (0..dlina-1)
    if k[p] > n[i] then
        n[i] = k[p]
        p-=1
    end

    if p < 0 then
        break
    end
end

for i in 0..dlina-1 do
    print n[i]
end

# encoding: utf-8

a = readline
s = readline
puts (a+s)

# ProblemB.rb

a = gets.chomp.split(//)
s = gets.chomp

s = s.split(//).sort.reverse

j = 0
a.each_with_index do |c, i|
  if c < s[j]
    a[i] = s[j]
    j += 1
  end
end

p a.join


Marin wants you to count number of permutations that are beautiful. A beautiful permutation of length $$$n$$$ is a permutation that has the following property: $$$$$$ \gcd (1 \cdot p_1, \, 2 \cdot p_2, \, \dots, \, n \cdot p_n) > 1, $$$$$$ where $$$\gcd$$$ is the greatest common divisor.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3, 4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n \le 10^3$$$).

For each test case, print one integer — number of beautiful permutations. Because the answer can be very big, please print the answer modulo $$$998\,244\,353$$$.

NoteIn first test case, we only have one permutation which is $$$[1]$$$ but it is not beautiful because $$$\gcd(1 \cdot 1) = 1$$$.In second test case, we only have one beautiful permutation which is $$$[2, 1]$$$ because $$$\gcd(1 \cdot 2, 2 \cdot 1) = 2$$$.

t = gets.to_i
while t > 0
    t = t - 1
    n = gets.to_i
    if n & 1 == 1
        puts "0"
    else
        ans = 1
        for i in 1..n/2
            ans = (ans * (i * i))%998244353
        end
        puts ans
    end
end