This problem is actually a subproblem of problem G from the same contest.There are $$$n$$$ candies in a candy box. The type of the $$$i$$$-th candy is $$$a_i$$$ ($$$1 \le a_i \le n$$$).You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all distinct (i. e. for example, a gift having two candies of type $$$1$$$ and two candies of type $$$2$$$ is bad). It is possible that multiple types of candies are completely absent from the gift. It is also possible that not all candies of some types will be taken to a gift.Your task is to find out the maximum possible size of the single gift you can prepare using the candies you have.You have to answer $$$q$$$ independent queries.If you are Python programmer, consider using PyPy instead of Python when you submit your code.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. Each query is represented by two lines. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of candies. The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the type of the $$$i$$$-th candy in the box. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2 \cdot 10^5$$$.

For each query print one integer — the maximum possible size of the single gift you can compose using candies you got in this query with the restriction described in the problem statement.

NoteIn the first query, you can prepare a gift with two candies of type $$$8$$$ and one candy of type $$$5$$$, totalling to $$$3$$$ candies.Note that this is not the only possible solution — taking two candies of type $$$4$$$ and one candy of type $$$6$$$ is also valid.

q = gets.chomp.to_i

for ii in 1..q
  gets.chomp.to_i
  tab = gets.chomp.split(" ").map {|el| el.to_i}
  better = {}
  tab.each do |el|
    better[el] = 0 unless better.key?(el)
    better[el] += 1
  end

  better = better.sort_by {|k,v| -v}
  ans = 0
  last = 2000000

  better.each do |k, val|
    last = val >= last ? last-1 : val
    last = last < 0 ? 0 : last
    ans += last
  end

  print "#{ans}\n"
end

q = gets.to_i
(1..q).each do
  n = gets.to_i
  count = Array.new(n + 10, 0)
  candies = gets.split(" ").map{|c| c.to_i}
  candies.each {|candy| count[candy] += 1}
  hash = {}
  res = []
  count.each do |cnt|
    tmp = cnt
    while tmp > 0 && hash[tmp] == 1
      tmp -= 1
    end
    res << tmp
    hash[tmp] = 1
  end
  sum = 0
  res.each {|rs| sum += rs}
  puts sum
end

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

def desc(ar) ar.sort!{|x,y|y<=>x} end
def min(a,b) a<=b ? a : b end
def max(a,b) a>=b ? a : b end
def sum(ar) ar.inject(:+) end

def C(a,b) b==0||a==b ? 1 : (b=a-b if a/2<b;(a-b+1..a).inject(:*)/(1..b).inject(:*)) end

def puts_yesno(can) puts(can ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def debug(k,v) puts "#{k}:#{v}" end
########### ( ˘ω˘ )ｽﾔｧ… ###########
q=gi
q.times do
  n=gi
  a=gsmi
  h=Hash.new(0)
  a.each do |i|
    h[i]+=1
  end
  #puts h.to_s
  ar = desc(h.to_a.map{|j|j[1]})
  sum=0
  prev=2*10**5+1
  ar.size.times do |i|
    c=min(prev-1,ar[i])
    break if c<=0
    sum+=c
    prev=c
  end
  puts sum
end

q = gets.chomp.to_i

for ii in 1..q
  gets.chomp.to_i
  tab = gets.chomp.split(" ").map {|el| el.to_i}
  better = {}
  tab.each do |el|
    better[el] = 0 unless better.key?(el)
    better[el] += 1
  end

  # better = better.sort_by(&:last).reverse
  ans = 0
  last = 2000000

  better.each do |k, val|
    last = val >= last ? last-1 : val
    last = last < 0 ? 0 : last
    ans += last
  end

  print "#{ans}\n"
end

q = gets.to_i
(1..q).each do
  n = gets.to_i
  count = Array.new(1000000, 0)
  candies = gets.split(" ").map{|c| c.to_i}
  candies.each {|candy| count[candy] += 1}
  hash = Array.new(1000000, 0)
  res = Array.new(1, 0)
  count.each do |cnt|
    tmp = cnt
    while tmp > 0 && hash[tmp] == 1
      tmp -= 1
    end
    #res.append(tmp)
    hash[tmp] = 1
  end
  sum = 0
  res.each {|rs| sum += rs}
  puts sum
end


Ivan places knights on infinite chessboard. Initially there are $$$n$$$ knights. If there is free cell which is under attack of at least $$$4$$$ knights then he places new knight in this cell. Ivan repeats this until there are no such free cells. One can prove that this process is finite. One can also prove that position in the end does not depend on the order in which new knights are placed.Ivan asked you to find initial placement of exactly $$$n$$$ knights such that in the end there will be at least $$$\lfloor \frac{n^{2}}{10} \rfloor$$$ knights.

The only line of input contains one integer $$$n$$$ ($$$1 \le n \le 10^{3}$$$) — number of knights in the initial placement.

Print $$$n$$$ lines. Each line should contain $$$2$$$ numbers $$$x_{i}$$$ and $$$y_{i}$$$ ($$$-10^{9} \le x_{i}, \,\, y_{i} \le 10^{9}$$$) — coordinates of $$$i$$$-th knight. For all $$$i \ne j$$$, $$$(x_{i}, \,\, y_{i}) \ne (x_{j}, \,\, y_{j})$$$ should hold. In other words, all knights should be in different cells. It is guaranteed that the solution exists.

NoteLet's look at second example:Green zeroes are initial knights. Cell $$$(3, \,\, 3)$$$ is under attack of $$$4$$$ knights in cells $$$(1, \,\, 2)$$$, $$$(2, \,\, 1)$$$, $$$(4, \,\, 1)$$$ and $$$(5, \,\, 2)$$$, therefore Ivan will place a knight in this cell. Cell $$$(4, \,\, 5)$$$ is initially attacked by only $$$3$$$ knights in cells $$$(2, \,\, 6)$$$, $$$(5, \,\, 7)$$$ and $$$(6, \,\, 6)$$$. But new knight in cell $$$(3, \,\, 3)$$$ also attacks cell $$$(4, \,\, 5)$$$, now it is attacked by $$$4$$$ knights and Ivan will place another knight in this cell. There are no more free cells which are attacked by $$$4$$$ or more knights, so the process stops. There are $$$9$$$ knights in the end, which is not less than $$$\lfloor \frac{7^{2}}{10} \rfloor = 4$$$.

n=gets.to_i
(n-n/3).times do |i|
    print "0 #{i+1}\n"
end
(n/3).times do |i|
    print "3 #{(i+1)*2}\n"
end

n=gets.to_i
(n/3).times do |i|
    print "0 #{i+1}\n"
end
(n-n/3).times do |i|
    print "3 #{(i+1)*2}\n"
end


You are given a following process. There is a platform with $$$n$$$ columns. $$$1 \times 1$$$ squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column. When all of the $$$n$$$ columns have at least one square in them, the bottom row is being removed. You will receive $$$1$$$ point for this, and all the squares left will fall down one row. You task is to calculate the amount of points you will receive.

The first line of input contain 2 integer numbers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$) — the length of the platform and the number of the squares. The next line contain $$$m$$$ integer numbers $$$c_1, c_2, \dots, c_m$$$ ($$$1 \le c_i \le n$$$) — column in which $$$i$$$-th square will appear.

Print one integer — the amount of points you will receive.

NoteIn the sample case the answer will be equal to $$$2$$$ because after the appearing of $$$6$$$-th square will be removed one row (counts of the squares on the platform will look like $$$[2~ 3~ 1]$$$, and after removing one row will be $$$[1~ 2~ 0]$$$).After the appearing of $$$9$$$-th square counts will be $$$[2~ 3~ 1]$$$, and after removing one row it will look like $$$[1~ 2~ 0]$$$.So the answer will be equal to $$$2$$$.

#bismillahir rahmanir rahim

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

num = gets.split.map{ |x| x.to_i }

x=num.count(1)

for i in 2..n
    y = num.count(i)
    x=y if x>y
    #puts i,x,y
end

puts x

=begin
for i in 0...m
    puts num[i]
end
=end

n,m,*a=$<.read.split.map &:to_i
x=[0]*n
a.each{|e|x[e-1]+=1}
p x.min

n_and_m = gets.chomp
squares = gets.chomp

n_and_m = n_and_m.split(" ")

n = n_and_m[0].to_i
m = n_and_m[1].to_i

squares = squares.split(" ")
squares.map! {|s| s.to_i}

platform = Array.new(n, 0)

squares.each do |square|
  platform[square - 1] += 1
end

score = 0
total = 0
length = platform.length

while true
  platform.map {|s| total += 1 if !s.equal?(0) }
  break if !total.equal?(length)
  score += 1
  platform.map! {|s| s -= 1}
  total = 0
end

puts score

n, m = gets.split.map(&:to_i)
ar = gets.split.map(&:to_i)
counts = Array.new(n)
n.times{|i| counts[i] = ar.count{|a| a == i+1}}
puts counts.include?(nil) ? 0 : counts.min

n_and_m = gets.chomp
squares = gets.chomp

n_and_m = n_and_m.split(" ")
puts n_and_m.inspect
n = n_and_m[0].to_i
m = n_and_m[1].to_i

squares = squares.split(" ")
squares.map! {|s| s.to_i}

platform = Array.new(n, 0)

#puts squares.inspect
#puts "el tamaño del platform es : #{platform.length}"
squares.each do |square|
  platform[square - 1] += 1
end

score = 0
total = 0
length = platform.length

while true
  platform.map {|s| total += 1 if !s.equal?(0) }
  break if !total.equal?(length)
  score += 1
  platform.map! {|s| s -= 1}
  total = 0
end

puts score


In one little known, but very beautiful country called Waterland, lives a lovely shark Valerie. Like all the sharks, she has several rows of teeth, and feeds on crucians. One of Valerie's distinguishing features is that while eating one crucian she uses only one row of her teeth, the rest of the teeth are "relaxing".For a long time our heroine had been searching the sea for crucians, but a great misfortune happened. Her teeth started to ache, and she had to see the local dentist, lobster Ashot. As a professional, Ashot quickly relieved Valerie from her toothache. Moreover, he managed to determine the cause of Valerie's developing caries (for what he was later nicknamed Cap).It turned that Valerie eats too many crucians. To help Valerie avoid further reoccurrence of toothache, Ashot found for each Valerie's tooth its residual viability. Residual viability of a tooth is a value equal to the amount of crucians that Valerie can eat with this tooth. Every time Valerie eats a crucian, viability of all the teeth used for it will decrease by one. When the viability of at least one tooth becomes negative, the shark will have to see the dentist again. Unhappy, Valerie came back home, where a portion of crucians was waiting for her. For sure, the shark couldn't say no to her favourite meal, but she had no desire to go back to the dentist. That's why she decided to eat the maximum amount of crucians from the portion but so that the viability of no tooth becomes negative. As Valerie is not good at mathematics, she asked you to help her to find out the total amount of crucians that she can consume for dinner.We should remind you that while eating one crucian Valerie uses exactly one row of teeth and the viability of each tooth from this row decreases by one.

The first line contains three integers n, m, k (1 ≤ m ≤ n ≤ 1000, 0 ≤ k ≤ 106) — total amount of Valerie's teeth, amount of tooth rows and amount of crucians in Valerie's portion for dinner. Then follow n lines, each containing two integers: r (1 ≤ r ≤ m) — index of the row, where belongs the corresponding tooth, and c (0 ≤ c ≤ 106) — its residual viability. It's guaranteed that each tooth row has positive amount of teeth.

In the first line output the maximum amount of crucians that Valerie can consume for dinner.

s = gets.chomp
ns,ms,ks = s.split(/ /)
n = ns.to_i
m = ms.to_i
k = ks.to_i
h = Hash.new
for i in 1..n
	s2 = gets.chomp
	rs,cs = s2.split(/ /)
	r = rs.to_i
	c = cs.to_i

	if h.has_key?(r)
		h[r] = c if h[r] > c
	else
		h[r] = c
	end
end
sum = 0
h.each {|key,val|
	sum += val
}
ret = [sum,k].min
puts ret

n, m, k = gets.split.map(&:to_i)
a = [nil] * n
n.times do
	r, c = gets.split.map(&:to_i)
	r -= 1
	a[r] = a[r] ? [a[r], c].min : c
end
p [a.compact.inject(:+), k].min

n,m,k=gets.split.map(&:to_i)
a=Array.new(m)
n.times{r,c=gets.split.map(&:to_i)
r-=1
a[r]=a[r] ? [a[r],c].min : c}
b=a.inject:+
p b>k ? k : b

#=================================
# Better be sure than sorry.
#=================================
$stdin=File.open("./input.txt","r") if ENV["LOGNAME"]=="skydos"
require 'prime'
require 'mathn'
require 'matrix'
include Math
#=================================

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

hs=Hash.new(10**9)
n.times{
	r, c=gets.split.map(&:to_i)
	hs[r]=[c, hs[r]].min
}

puts [hs.values.inject(:+), k].min

s = gets.split(" ")
n = s[0].to_i
m = s[1].to_i
k = s[2].to_i

row = Array.new()
for i in 1..m
  row[i] = 9999999
end

for i in 1..n
  s = gets.split(" ")
  key = s[0].to_i
  value = s[1].to_i
  if (value < row[key])
    row[key] = value
  end
end

sum = 0
for i in 1..m
  sum += row[i]
end

puts sum < k ? sum : k


Fishingprince is playing with an array $$$[a_1,a_2,\dots,a_n]$$$. He also has a magic number $$$m$$$.He can do the following two operations on it:  Select $$$1\le i\le n$$$ such that $$$a_i$$$ is divisible by $$$m$$$ (that is, there exists an integer $$$t$$$ such that $$$m \cdot t = a_i$$$). Replace $$$a_i$$$ with $$$m$$$ copies of $$$\frac{a_i}{m}$$$. The order of the other elements doesn't change. For example, when $$$m=2$$$ and $$$a=[2,3]$$$ and $$$i=1$$$, $$$a$$$ changes into $$$[1,1,3]$$$.  Select $$$1\le i\le n-m+1$$$ such that $$$a_i=a_{i+1}=\dots=a_{i+m-1}$$$. Replace these $$$m$$$ elements with a single $$$m \cdot a_i$$$. The order of the other elements doesn't change. For example, when $$$m=2$$$ and $$$a=[3,2,2,3]$$$ and $$$i=2$$$, $$$a$$$ changes into $$$[3,4,3]$$$. Note that the array length might change during the process. The value of $$$n$$$ above is defined as the current length of the array (might differ from the $$$n$$$ in the input).Fishingprince has another array $$$[b_1,b_2,\dots,b_k]$$$. Please determine if he can turn $$$a$$$ into $$$b$$$ using any number (possibly zero) of operations.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1\le n\le 5\cdot 10^4$$$, $$$2\le m\le 10^9$$$). The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1\le a_i\le 10^9$$$). The third line of each test case contains one integer $$$k$$$ ($$$1\le k\le 5\cdot 10^4$$$). The fourth line of each test case contains $$$k$$$ integers $$$b_1,b_2,\ldots,b_k$$$ ($$$1\le b_i\le 10^9$$$). It is guaranteed that the sum of $$$n+k$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each testcase, print Yes if it is possible to turn $$$a$$$ into $$$b$$$, and No otherwise. You can print each letter in any case (upper or lower).

NoteIn the first test case of the sample, we can do the second operation with $$$i=2$$$: $$$[1,\color{red}{2,2},4,2]\to [1,\color{red}{4},4,2]$$$.In the second testcase of the sample, we can:  do the second operation with $$$i=2$$$: $$$[1,\color{red}{2,2},8,2,2]\to [1,\color{red}{4},8,2,2]$$$.  do the second operation with $$$i=4$$$: $$$[1,4,8,\color{red}{2,2}]\to [1,4,8,\color{red}{4}]$$$.  do the first operation with $$$i=3$$$: $$$[1,4,\color{red}{8},4]\to [1,4,\color{red}{4,4},4]$$$.  do the second operation with $$$i=2$$$: $$$[1,\color{red}{4,4},4,4]\to [1,\color{red}{8},4,4]$$$.  do the second operation with $$$i=3$$$: $$$[1,8,\color{red}{4,4}]\to [1,8,\color{red}{8}]$$$.  do the second operation with $$$i=2$$$: $$$[1,\color{red}{8,8}]\to [1,\color{red}{16}]$$$.

# gets.to_i
# gets.split.map(&:to_i)

def f(x, m)
  cnt = 1
  while x % m == 0
    x /= m
    cnt *= m
  end
  return [x, cnt]
end

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

  ac = []
  n.times do |i|
    num, cnt = f(a[i], m)
    if ac.empty?
      ac << [num, cnt]
    elsif ac[-1][0] == num
      ac[-1][1] += cnt
    else
      ac << [num, cnt]
    end
  end

  bc = []
  k.times do |i|
    num, cnt = f(b[i], m)
    if bc.empty?
      bc << [num, cnt]
    elsif bc[-1][0] == num
      bc[-1][1] += cnt
    else
      bc << [num, cnt]
    end
  end

  puts bc == ac ? "Yes" : "No"
end

split = ->xs, m {
  chunks = []
  xs.each do |x|
    xx = x
    xx /= m while xx % m == 0
    n, count = xx, x / xx
    if chunks.last && chunks.last[0] == n
      chunks.last[1] += count
    else
      chunks << [n, count]
    end
  end
  chunks
}

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

  ok = split[as, m] == split[bs, m]

  puts ok ? "YES" : "NO"
end

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

  powers = (0..30).map { |i| [m ** i, i] }.to_h

  split = []
  as.each do |a|
    aa = a
    aa /= m while aa % m == 0
    x, y = aa, a / aa
    if split.last && split.last[0] == x
      split.last[1] += y
    else
      split << [x, y]
    end
  end

  ok = true
  bs.each do |b|
    if split.empty?
      ok = false
      break
    end
    x, y = split[0]
    if b % x == 0 && p = powers[b / x]
      if y >= b / x
        split[0][1] -= b / x
      else
        ok = false
      end
    else
      ok = false
    end
    split.shift if split[0][1] == 0
  end

  ok &&= split.empty?

  puts ok ? "YES" : "NO"
end

# gets.to_i
# gets.split.map(&:to_i)

def f(x, m)
  cnt = 1
  while x % m == 0
    x /= m
    cnt *= m
  end
  return [x, cnt]
end

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

  ac = []
  n.times do |i|
    if a[i] % m == 0
      num, cnt = f(a[i], m)
      if ac.empty?
        ac << [num, cnt]
      elsif ac[-1][0] == num
        ac[-1][1] += cnt
      else
        ac << [num, cnt]
      end
    else
      ac << [a[i], 1]
    end
  end

  bc = []
  k.times do |i|
    if b[i] % m == 0
      num, cnt = f(b[i], m)
      if bc.empty?
        bc << [num, cnt]
      elsif bc[-1][0] == num
        bc[-1][1] += cnt
      else
        bc << [num, cnt]
      end
    else
      bc << [b[i], 1]
    end
  end

  puts bc == ac ? "Yes" : "No"
end

# gets.to_i
# gets.split.map(&:to_i)

def f(x, m)
  cnt = 1
  while x % m == 0
    x /= m
    cnt *= m
  end
  return [x, cnt]
end

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

  ac = []
  n.times do |i|
    if a[i] % m == 0
      ac << f(a[i], m)
    else
      ac << [a[i], 1]
    end
  end

  bc = []
  k.times do |i|
    if b[i] % m == 0
      bc << f(b[i], m)
    else
      bc << [b[i], 1]
    end
  end

  ans_a = []
  num, cnt = ac[0]
  (ac.size-1).times do |i|
    num1, cnt1 = ac[i+1]
    if num == num1
      cnt += cnt1
      if ac.size == i+2
        ans_a << [num, cnt]
      end
    else
      ans_a << [num, cnt]
      num = num1
      cnt = cnt1
    end
  end

  ans_b = []
  num, cnt = bc[0]
  (bc.size-1).times do |i|
    num1, cnt1 = bc[i+1]
    if num == num1
      cnt += cnt1
      if bc.size == i+2
        ans_b << [num, cnt]
      end
    else
      ans_b << [num, cnt]
      num = num1
      cnt = cnt1
    end
  end

  puts ans_a == ans_b ? "Yes" : "No"
end

# gets.to_i
# gets.split.map(&:to_i)

def f(x, m)
  cnt = 1
  while x % m == 0
    x /= m
    cnt *= m
  end
  return [x, cnt]
end

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

  ac = []
  n.times do |i|
    if a[i] % m == 0
      ac << f(a[i], m)
    else
      ac << [a[i], 1]
    end
  end

  bc = []
  k.times do |i|
    if b[i] % m == 0
      bc << f(b[i], m)
    else
      bc << [b[i], 1]
    end
  end

  ans_a = []
  num, cnt = ac[0]
  (ac.size-1).times do |i|
    num1, cnt1 = ac[i+1]
    if num == num1
      cnt += cnt1
      if ac.size == i+2
        ans_a << [num, cnt]
      end
    else
      ans_a << [num, cnt]
      num = num1
      cnt = cnt1
    end
  end

  ans_b = []
  num, cnt = bc[0]
  (bc.size-1).times do |i|
    num1, cnt1 = bc[i+1]
    if num == num1
      cnt += cnt1
      if bc.size == i+2
        ans_b << [num, cnt]
      end
    else
      ans_b << [num, cnt]
      num = num1
      cnt = cnt1
    end
  end

    ok = true
    ans_a.size.times do |i|
      num1, cnt1 = ans_a[i]
      num2, cnt2 = ans_b[i]

      break ok = false if num1 != num2 || cnt1 != cnt2
    end

  puts ok ? "Yes" : "No"
end

# gets.to_i
# gets.split.map(&:to_i)

def f(x, m)
  cnt = 1
  while x % m == 0
    x /= m
    cnt *= m
  end
  return [x, cnt]
end

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

  ac = []
  n.times do |i|
    if a[i] % m == 0
      min, cnt = f(a[i], m)
      ac << [min, cnt]
    else
      ac << [a[i], 1]
    end
  end

  bc = []
  k.times do |i|
    if b[i] % m == 0
      min, cnt = f(b[i], m)
      bc << [min, cnt]
    else
      bc << [b[i], 1]
    end
  end

  ans_a = []
  num, cnt = ac[0]
  (ac.size-1).times do |i|
    num1, cnt1 = ac[i+1]
    if num == num1
      cnt += cnt1
      if ac.size == i+2
        ans_a << [num, cnt]
      end
    else
      ans_a << [num, cnt]
      num = num1
      cnt = cnt1
    end
  end

  ans_b = []
  num, cnt = bc[0]
  (bc.size-1).times do |i|
    num1, cnt1 = bc[i+1]
    if num == num1
      cnt += cnt1
      if bc.size == i+2
        ans_b << [num, cnt]
      end
    else
      ans_b << [num, cnt]
      num = num1
      cnt = cnt1
    end
  end

  ok = false

  if ans_a.size == ans_b.size
    ok = true
    ans_a.size.times do |i|
      next if ans_a[i] == ans_b[i]
      num1, cnt1 = ans_a[i]
      num2, cnt2 = ans_b[i]

      break ok = false if num1 != num2 || cnt1 != cnt2
    end
  end

  puts ok ? "Yes" : "No"
end

# gets.to_i
# gets.split.map(&:to_i)

def f(x, m)
  while x % m == 0
    x /= m
  end
  return x
end

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

  ac = []
  n.times do |i|
    if a[i] % m == 0
      min = f(a[i], m)
      ac << min
    else
      ac << a[i]
    end
  end

  bc = []
  k.times do |i|
    if b[i] % m == 0
      min = f(b[i], m)
      bc << min
    else
      bc << b[i]
    end
  end

  ans_a = ac.slice_when{|i,j| i != j}.map{|e| e[0]}
  ans_b = bc.slice_when{|i,j| i != j}.map{|e| e[0]}

  puts ans_a == ans_b ? "Yes" : "No"
end

# gets.to_i
# gets.split.map(&:to_i)

def f(x, m)
  while x % m == 0
    x /= m
  end
  return x
end

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

  ac = []
  n.times do |i|
    if a[i] % m == 0
      min = f(a[i], m)
      ac << min
    else
      ac << a[i]
    end
  end

  bc = []
  k.times do |i|
    if b[i] % m == 0
      min = f(b[i], m)
      bc << min
    else
      bc << b[i]
    end
  end

  ans_a = ac.slice_when{|i,j| i != j}.map{|e| e[0]}
  ans_b = bc.slice_when{|i,j| i != j}.map{|e| e[0]}

  ok = false
  if ans_a.size == ans_b.size
    ok = true
    ans_a.size.times do |i|
      num1 = ans_a[i]
      num2 = ans_b[i]

      break ok = false if num1 != num2
    end
  end

  puts ok ? "Yes" : "No"
end

# gets.to_i
# gets.split.map(&:to_i)

def f(x, m)
  cnt = 1
  while x % m == 0
    x /= m
    cnt *= m
  end
  return [x, cnt]
end

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

  ac = []
  n.times do |i|
    if a[i] % m == 0
      min, cnt = f(a[i], m)
      ac << [min, cnt]
    else
      ac << [a[i], 1]
    end
  end

  bc = []
  k.times do |i|
    if b[i] % m == 0
      min, cnt = f(b[i], m)
      bc << [min, cnt]
    else
      bc << [b[i], 1]
    end
  end

  ans_a = []
  num, cnt = ac[0]
  (ac.size-1).times do |i|
    num1, cnt1 = ac[i+1]
    if num == num1
      cnt += cnt1
      if ac.size == i+2
        ans_a << [num, cnt]
      end
    else
      ans_a << [num, cnt]
      num = num1
      cnt = cnt1
    end
  end

  ans_b = []
  num, cnt = bc[0]
  (bc.size-1).times do |i|
    num1, cnt1 = bc[i+1]
    if num == num1
      cnt += cnt1
      if bc.size == i+2
        ans_b << [num, cnt]
      end
    else
      ans_b << [num, cnt]
      num = num1
      cnt = cnt1
    end
  end

  ok = false
  if ans_a.size == ans_b.size
    ok = true
    ans_a.size.times do |i|
      num1, cnt1 = ans_a[i]
      num2, cnt2 = ans_b[i]

      break ok = false if num1 != num2
    end
  end

  puts ok ? "Yes" : "No"
end

# gets.to_i
# gets.split.map(&:to_i)

def f(x, m)
  cnt = 0
  while x % m == 0
    x /= m
    cnt += 1
  end
  return [x, cnt]
end

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

  ac = []
  n.times do |i|
    if a[i] % m == 0
      min, cnt = f(a[i], m)
      ac << [min, 1 << cnt]
    else
      ac << [a[i], 1]
    end
  end

  bc = []
  k.times do |i|
    if b[i] % m == 0
      min, cnt = f(b[i], m)
      bc << [min, 1 << cnt]
    else
      bc << [b[i], 1]
    end
  end

  ans_a = []
  num, cnt = ac[0]
  (ac.size-1).times do |i|
    num1, cnt1 = ac[i+1]
    if num == num1
      cnt += cnt1
      if ac.size == i+2
        ans_a << [num, cnt]
      end
    else
      ans_a << [num, cnt]
      num = num1
      cnt = cnt1
    end
  end

  ans_b = []
  num, cnt = bc[0]
  (bc.size-1).times do |i|
    num1, cnt1 = bc[i+1]
    if num == num1
      cnt += cnt1
      if bc.size == i+2
        ans_b << [num, cnt]
      end
    else
      ans_b << [num, cnt]
      num = num1
      cnt = cnt1
    end
  end

  ok = false

  if ans_a.size == ans_b.size
    ok = true
    ans_a.size.times do |i|
      next if ans_a[i] == ans_b[i]

      num1, cnt1 = ans_a[i]
      num2, cnt2 = ans_b[i]

      break ok = false if num1 != num2
    end
  end

  puts ok ? "Yes" : "No"
end

# gets.to_i
# gets.split.map(&:to_i)

def f(x, m)
  cnt = 0
  while x % m == 0
    x /= m
    cnt += 1
  end
  return [x, cnt]
end

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

  ac = []
  n.times do |i|
    if a[i] % m == 0
      min, cnt = f(a[i], m)
      ac << [min, 1 << cnt]
    else
      ac << [a[i], 1]
    end
  end

  bc = []
  k.times do |i|
    if b[i] % m == 0
      min, cnt = f(b[i], m)
      bc << [min, 1 << cnt]
    else
      bc << [b[i], 1]
    end
  end

  ans_a = []
  num, cnt = ac[0]
  (ac.size-1).times do |i|
    num1, cnt1 = ac[i+1]
    if num == num1
      cnt += cnt1
      if ac.size == i+2
        ans_a << [num, cnt]
      end
    else
      ans_a << [num, cnt]
      num = num1
      cnt = cnt1
    end
  end

  ans_b = []
  num, cnt = bc[0]
  (bc.size-1).times do |i|
    num1, cnt1 = bc[i+1]
    if num == num1
      cnt += cnt1
      if bc.size == i+2
        ans_b << [num, cnt]
      end
    else
      ans_b << [num, cnt]
      num = num1
      cnt = cnt1
    end
  end

  ok = false

  if ans_a.size == ans_b.size
    ok = true
    ans_a.size.times do |i|
      next if ans_a[i] == ans_b[i]
      num1, cnt1 = ans_a[i]
      num2, cnt2 = ans_b[i]

      break ok = false if num1 != num2

      if cnt1 != cnt2
        s = m-2
        break ok = false if s == 0
        break ok = false if (cnt1 < m && cnt2 < m) || (cnt2 - cnt1).abs % s != 0
      end
    end
  end

  puts ok ? "Yes" : "No"
end

# gets.to_i
# gets.split.map(&:to_i)

def f(x, m)
  cnt = 0
  while x % m == 0
    x /= m
    cnt += 1
  end
  return [x, cnt]
end

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

  ac = []
  n.times do |i|
    if a[i] % m == 0
      min, cnt = f(a[i], m)
      ac << [min, 1 << cnt]
    else
      ac << [a[i], 1]
    end
  end

  bc = []
  k.times do |i|
    if b[i] % m == 0
      min, cnt = f(b[i], m)
      bc << [min, 1 << cnt]
    else
      bc << [b[i], 1]
    end
  end

  ans_a = []
  num, cnt = ac[0]
  (ac.size-1).times do |i|
    num1, cnt1 = ac[i+1]
    if num == num1
      cnt += cnt1
      if ac.size == i+2
        ans_a << [num, cnt]
      end
    else
      ans_a << [num, cnt]
      num = num1
      cnt = cnt1
    end
  end

  ans_b = []
  num, cnt = bc[0]
  (bc.size-1).times do |i|
    num1, cnt1 = bc[i+1]
    if num == num1
      cnt += cnt1
      if bc.size == i+2
        ans_b << [num, cnt]
      end
    else
      ans_b << [num, cnt]
      num = num1
      cnt = cnt1
    end
  end

  ok = false
  if ans_a.size == ans_b.size

    ok = true
    ans_a.size.times do |i|
      next if ans_a[i] == ans_b[i]
      num1, cnt1 = ans_a[i]
      num2, cnt2 = ans_b[i]
      break ok = false if num1 != num2

      if cnt1 != cnt2
        break ok = false if cnt1 < m && cnt2 < m
        s = m-2
        if cnt1 < cnt2
          break ok = false if (cnt2 - cnt1) % s != 0
        else
          break ok = false if (cnt1 - cnt2) % s != 0
        end
      end
    end
  end

  puts ok ? "Yes" : "No"
end


You are given a number $$$n$$$ and an array $$$b_1, b_2, \ldots, b_{n+2}$$$, obtained according to the following algorithm:   some array $$$a_1, a_2, \ldots, a_n$$$ was guessed;  array $$$a$$$ was written to array $$$b$$$, i.e. $$$b_i = a_i$$$ ($$$1 \le i \le n$$$);  The $$$(n+1)$$$-th element of the array $$$b$$$ is the sum of the numbers in the array $$$a$$$, i.e. $$$b_{n+1} = a_1+a_2+\ldots+a_n$$$;  The $$$(n+2)$$$-th element of the array $$$b$$$ was written some number $$$x$$$ ($$$1 \le x \le 10^9$$$), i.e. $$$b_{n+2} = x$$$; The  array $$$b$$$ was shuffled. For example, the array $$$b=[2, 3, 7, 12 ,2]$$$ it could be obtained in the following ways:   $$$a=[2, 2, 3]$$$ and $$$x=12$$$;  $$$a=[3, 2, 7]$$$ and $$$x=2$$$. For the given array $$$b$$$, find any array $$$a$$$ that could have been guessed initially.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). The second row of each test case contains $$$n+2$$$ integers $$$b_1, b_2, \ldots, b_{n+2}$$$ ($$$1 \le b_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output:    "-1", if the array $$$b$$$ could not be obtained from any array $$$a$$$;  $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$, otherwise.  If there are several arrays of $$$a$$$, you can output any.

t = gets.to_s.to_i

def solve_case1(a)
  orig_sum = a[-1]
  tmp = a.reduce(0) {|acc, x| acc + x } - orig_sum
  x_idx = nil
  0.upto(a.size - 2) do |i|
    if tmp - a[i] == orig_sum
      x_idx = i
    end
  end
  return nil if !x_idx
  a.select.with_index {|x, i| (i != x_idx) && (i != a.size - 1)}
end

def solve_case2(a)
  tmp = a.reduce(0) {|acc, x| acc + x } - a[-1] - a[-2]
  if tmp == a[-2]
    return a[0 .. -3]
  end
  return nil
end

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

  # case 1 (the sum is the largest number)
  x = solve_case1(a)
  if x
    printf("%s\n", x.join(" "))
    next
  end

  # case 2
  x = solve_case2(a)
  if x
    printf("%s\n", x.join(" "))
    next
  end

  printf("-1\n")
end

t = gets.to_i
t.times do
	n = gets.to_i
	a = gets.split.map(&:to_i).sort
	s = a.sum - a[n+1]

	idx = -1
	for i in 0..n
		if s - a[i] == a[n+1]
			idx = i
			break
		end
	end

	if idx == -1
		if s == 2*a[n]
			idx = n
		else
			puts -1
			next
		end
	end

	for i in 0..n
		next if i == idx
		print a[i], " "
	end
	puts ""
end

t = gets.to_s.to_i

def solve_case1(a)
  orig_sum = a[-1]
  tmp = a.reduce(0) {|acc, x| acc + x } - orig_sum
  x_idx = nil
  0.upto(a.size - 2) do |i|
    if tmp - a[i] == orig_sum
      x_idx = i
    end
  end
  return nil if !x_idx
  a.select.with_index {|x, i| (i != x_idx) && (i != a.size - 1)}
end

def solve_case2(a)
  a[-1] = a[-2]
  return solve_case1(a.sort)
end

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

  # case 1 (the sum is the largest number)
  x = solve_case1(a)
  if x
    printf("%s\n", x.join(" "))
    next
  end

  # case 2
  x = solve_case2(a)
  if x
    printf("%s\n", x.join(" "))
    next
  end

  printf("-1\n")
end

t = gets.to_s.to_i

def solve_case1(a)
  orig_sum = a[-1]
  tmp = a.reduce(0) {|acc, x| acc + x } - orig_sum
  0.upto(a.size - 2) do |i|
    if tmp - a[i] == orig_sum
      if i == 0
        return a[i + 1 .. -2]
      elsif i == a.size - 2
        return a[0 .. i - 1]
      else
        return a[0 .. i - 1] + a[i + 1 .. -2]
      end
    end
  end
  return nil
end

def solve_case2(a)
  a[-1] = a[-2]
  return solve_case1(a.sort)
end

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

  # case 1 (the sum is the largest number)
  x = solve_case1(a)
  if x
    printf("%s\n", x.join(" "))
    next
  end

  # case 2
  x = solve_case2(a)
  if x
    printf("%s\n", x.join(" "))
    next
  end

  printf("-1\n")
end

t = gets.to_s.to_i

def solve_case1(a)
  orig_sum = a[-1]
  tmp = a.reduce(0) {|acc, x| acc + x } - orig_sum
  0.upto(a.size - 3) do |i|
    if tmp - a[i] == orig_sum
      if i == 0
        return a[i + 1 .. -2]
      elsif i == a.size - 3
        return a[0 .. i - 1]
      else
        return a[0 .. i - 1] + a[i + 1 .. -2]
      end
    end
  end
  return nil
end

def solve_case2(a)
  a[-1] = a[-2]
  return solve_case1(a.sort)
end

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

  # case 1 (the sum is the largest number)
  x = solve_case1(a)
  if x
    printf("%s\n", x.join(" "))
    next
  end

  # case 2
  x = solve_case2(a)
  if x
    printf("%s\n", x.join(" "))
    next
  end

  printf("-1\n")
end

t = gets.to_s.to_i

def solve_case1(a)
  orig_sum = a[-1]
  tmp = a.reduce(0) {|acc, x| acc + x } - orig_sum
  0.upto(a.size - 2) do |i|
    if tmp - a[i] == orig_sum
      if i == 0
        return a[i + 1 .. -2]
      elsif i == a.size - 3
        return a[0 .. i - 1]
      else
        return a[0 .. i - 1] + a[i + 1 .. -2]
      end
    end
  end
  return nil
end

def solve_case2(a)
  a[-1] = a[-2]
  return solve_case1(a.sort)
end

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

  # case 1 (the sum is the largest number)
  x = solve_case1(a)
  if x
    printf("%s\n", x.join(" "))
    next
  end

  # case 2
  x = solve_case2(a)
  if x
    printf("%s\n", x.join(" "))
    next
  end

  printf("-1\n")
end

t = gets.to_s.to_i

def solve_case1(a)
  orig_sum = a[-1]
  tmp = a.reduce(0) {|acc, x| acc + x } - orig_sum
  0.upto(a.size - 2) do |i|
    if tmp - a[i] == orig_sum
      if i == 0
        return a[i + 1 .. -2]
      elsif i == a.size - 3
        return a[0 .. i - 1]
      else
        return a[0 .. i - 1] + a[i + 1 .. -2]
      end
    end
  end
  return nil
end

def solve_case2(a)
  x = a[-1]
  orig_sum = a[-2]
  tmp = a.reduce(0) {|acc, x| acc + x } - x - orig_sum
  if tmp == orig_sum
    return a[0 .. -3]
  end
  return nil
end

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

  # case 1 (the sum is the largest number)
  x = solve_case1(a)
  if x
    printf("%s\n", x.join(" "))
    next
  end

  # case 2 (the X
  x = solve_case2(a)
  if x
    printf("%s\n", x.join(" "))
    next
  end

  printf("-1\n")
end

t = gets.to_i
t.times do
	n = gets.to_i
	a = gets.split.map(&:to_i).sort
	s = a.sum - a[n+1]

	idx = -1
	for i in 0..n
		if s - a[i] == a[n+1]
			idx = i
			break
		end
	end

	if idx == -1
		unless s == 2*a[n]
			puts -1
			next
		end
	end

	for i in 0..n
		next if i == idx
		print a[i], " "
	end
	puts ""
end

t = gets.to_i
t.times do
	n = gets.to_i
	a = gets.split.map(&:to_i).sort
	s = a.sum - a[n+1]

	idx = -1
	for i in 0..n
		if s - a[i] == a[n+1]
			idx = i
			break
		end
	end

	if idx == -1
		puts -1
		next
	end

	for i in 0..n
		next if i == idx
		print a[i], " "
	end
	puts ""
end


The hero of the Cut the Rope game is a little monster named Om Nom. He loves candies. And what a coincidence! He also is the hero of today's problem.  One day, Om Nom visited his friend Evan. Evan has n candies of two types (fruit drops and caramel drops), the i-th candy hangs at the height of hi centimeters above the floor of the house, its mass is mi. Om Nom wants to eat as many candies as possible. At the beginning Om Nom can make at most x centimeter high jumps. When Om Nom eats a candy of mass y, he gets stronger and the height of his jump increases by y centimeters.What maximum number of candies can Om Nom eat if he never eats two candies of the same type in a row (Om Nom finds it too boring)?

The first line contains two integers, n and x (1 ≤ n, x ≤ 2000) — the number of sweets Evan has and the initial height of Om Nom's jump.  Each of the following n lines contains three integers ti, hi, mi (0 ≤ ti ≤ 1; 1 ≤ hi, mi ≤ 2000) — the type, height and the mass of the i-th candy. If number ti equals 0, then the current candy is a caramel drop, otherwise it is a fruit drop.

Print a single integer — the maximum number of candies Om Nom can eat.

NoteOne of the possible ways to eat 4 candies is to eat them in the order: 1, 5, 3, 2. Let's assume the following scenario:  Initially, the height of Om Nom's jump equals 3. He can reach candies 1 and 2. Let's assume that he eats candy 1. As the mass of this candy equals 4, the height of his jump will rise to 3 + 4 = 7.  Now Om Nom can reach candies 2 and 5. Let's assume that he eats candy 5. Then the height of his jump will be 7 + 5 = 12.  At this moment, Om Nom can reach two candies, 2 and 3. He won't eat candy 2 as its type matches the type of the previously eaten candy. Om Nom eats candy 3, the height of his jump is 12 + 3 = 15.  Om Nom eats candy 2, the height of his jump is 15 + 1 = 16. He cannot reach candy 4.

$candies_amount, initial_jump_height = gets.split.map(&:to_i)
$candies = []

$candies_amount.times do
  candy = {}
  candy[:type], candy[:height], candy[:weight] = gets.split.map(&:to_i)
  $candies << candy
end

$candies.sort_by! {|t| -t[:weight]}

$max_ate = 0
# $tries = {0 => [], 1 => []}
$ate = Array.new($candies_amount, false)

def find_max(eaten, last_eaten_type, current_jump_height)
  # if ($tries[last_eaten_type][eaten.size] || -1 ) >= current_jump_height
  #   return
  # end

  # $tries[last_eaten_type][eaten.size] = current_jump_height

  to_eat_index = nil
  to_eat = nil
  $candies.each_with_index do |candy, i|
    if !$ate[i] && candy[:type] != last_eaten_type && candy[:height] <= current_jump_height
      to_eat_index = i
      to_eat = candy
      break
    end
  end

  if to_eat_index
    $ate[to_eat_index] = true
    find_max(eaten + [to_eat_index], to_eat[:type], current_jump_height + to_eat[:weight])
    $ate[to_eat_index] = false
  else
    $max_ate = eaten.size if eaten.size > $max_ate
  end
end

find_max([], 0, initial_jump_height)
# puts
# puts
find_max([], 1, initial_jump_height)
puts $max_ate

$candies_amount, initial_jump_height = gets.split.map(&:to_i)
$candies = []

$candies_amount.times do
  candy = {}
  candy[:type], candy[:height], candy[:weight] = gets.split.map(&:to_i)
  $candies << candy
end

$candies.sort_by! {|t| -t[:weight]}

$max_ate = 0
$tries = {0 => [], 1 => []}
$ate = Array.new($candies_amount, false)

def find_max(eaten, last_eaten_type, current_jump_height)
  if ($tries[last_eaten_type][eaten.size] || -1 ) >= current_jump_height
    return
  end

  $tries[last_eaten_type][eaten.size] = current_jump_height

  to_eat_index = nil
  to_eat = nil
  $candies.each_with_index do |candy, i|
    if !$ate[i] && candy[:type] != last_eaten_type && candy[:height] <= current_jump_height
      to_eat_index = i
      to_eat = candy
      break
    end
  end

  if to_eat_index
    $ate[to_eat_index] = true
    find_max(eaten + [to_eat_index], to_eat[:type], current_jump_height + to_eat[:weight])
    $ate[to_eat_index] = false
  else
    $max_ate = eaten.size if eaten.size > $max_ate
  end
end

find_max([], 0, initial_jump_height)
# puts
# puts
find_max([], 1, initial_jump_height)
puts $max_ate

$candies_amount, initial_jump_height = gets.split.map(&:to_i)
$candies = []

$candies_amount.times do
  candy = {}
  candy[:type], candy[:height], candy[:weight] = gets.split.map(&:to_i)
  $candies << candy
end

$candies.sort_by! {|t| -t[:weight]}

$max_ate = 0
$tries = {0 => [], 1 => []}

def find_max(eaten, last_eaten_type, current_jump_height)
  if ($tries[last_eaten_type][eaten.size] || -1 ) >= current_jump_height
    return
  end

  $tries[last_eaten_type][eaten.size] = current_jump_height

  available = (0..$candies_amount-1).to_a - eaten
  available_of_type = available.keep_if {|i| $candies[i][:type] != last_eaten_type }
  available_of_height = available_of_type.keep_if {|i| $candies[i][:height] <= current_jump_height}

  if available_of_height.length > 0
    # puts available_of_height.join(', ')
    max_weighted = $candies[available_of_height.first]
    find_max(eaten + [available_of_height.first], max_weighted[:type], current_jump_height + max_weighted[:weight])
  else
    $max_ate = eaten.size if eaten.size > $max_ate
  end
end

find_max([], 0, initial_jump_height)
# puts
# puts
find_max([], 1, initial_jump_height)
puts $max_ate

n,x = readline.strip.split.map(&:to_i)

candies = [[],[]]
n.times{
  t,h,m = readline.strip.split.map(&:to_i)
  candies[t] << [h,m]
}

# all_candies.each{|candies| candies.sort_by!{|h,m| -h } }

def count_max_num(candies_group_now, candies_group_next_turn, height, count)
  # puts "(#{candies_group_now};  #{candies_group_next_turn};  #{height};  #{count})"
  target_candies = candies_group_now.select{|h,m| h <= height }
  # puts "  target:#{target_candies}"

  if target_candies.empty?
    # puts "count:#{count}"
    return count
  end

  h,m = target_candies.max_by{|h,m| m}
  idx = candies_group_now.index([h,m])

  count_max_num(candies_group_next_turn, candies_group_now.dup.tap{|cnd| cnd.delete_at(idx) }, height + m, count + 1)
end

puts [count_max_num(candies[0], candies[1], x, 0), count_max_num(candies[1], candies[0], x, 0)].max

require 'ostruct'

$candies_amount, initial_jump_height = gets.split.map(&:to_i)
$candies = []

$candies_amount.times do
  candy = OpenStruct.new
  candy.type, candy.height, candy.weight = gets.split.map(&:to_i)
  $candies << candy
end

$max_ate = 0

$tries = {nil => [], 0 => [], 1 => []}

def find_max(index, ate, last_eaten_type, jump_height)
  if index == $candies_amount
    $max_ate = ate if ate > $max_ate
    return
  end

  tries = $tries[last_eaten_type][index]
  if tries && tries.detect {|t| t[:height] > jump_height && t[:ate] > ate}
    return
  end

  $tries[last_eaten_type][index] ||= []
  $tries[last_eaten_type][index] << {height: jump_height, ate: ate}

  current_candy = $candies[index]

  if last_eaten_type != current_candy.type && jump_height >= current_candy.height
    find_max(index+1, ate+1, current_candy.type, jump_height + current_candy.weight )
  end

  find_max(index+1, ate, last_eaten_type, jump_height)
end

find_max(0, 0, nil, initial_jump_height)
puts $max_ate

require 'ostruct'

$candies_amount, initial_jump_height = gets.split.map(&:to_i)
$candies = []

$candies_amount.times do
  candy = OpenStruct.new
  candy.type, candy.height, candy.weight = gets.split.map(&:to_i)
  $candies << candy
end

$max_ate = 0

$tries = {nil => [], 0 => [], 1 => []}

def find_max(index, ate, last_eaten_type, jump_height)
  if index == $candies_amount
    $max_ate = ate if ate > $max_ate
    return
  end

  # tries = $tries[last_eaten_type][index]
  # if tries && tries.detect {|t| t[:height] >= jump_height && t[:ate] >= ate}
  #   return
  # end

  # $tries[last_eaten_type][index] ||= []
  # $tries[last_eaten_type][index] << {height: jump_height, ate: ate}

  current_candy = $candies[index]

  if last_eaten_type != current_candy.type && jump_height >= current_candy.height
    find_max(index+1, ate+1, current_candy.type, jump_height + current_candy.weight )
  end

  find_max(index+1, ate, last_eaten_type, jump_height)
end

find_max(0, 0, nil, initial_jump_height)
puts $max_ate

require 'ostruct'

$candies_amount, initial_jump_height = gets.split.map(&:to_i)
$candies = []

$candies_amount.times do
  candy = OpenStruct.new
  candy.type, candy.height, candy.weight = gets.split.map(&:to_i)
  $candies << candy
end

$max_ate = 0

$tries = {nil => [], 0 => [], 1 => []}

def find_max(index, ate, last_eaten_type, jump_height)
  if index == $candies_amount
    $max_ate = ate if ate > $max_ate
    return
  end

  tries = $tries[last_eaten_type][index]
  if tries && tries.detect {|t| t[:height] >= jump_height && t[:ate] >= ate}
    return
  end

  $tries[last_eaten_type][index] ||= []
  $tries[last_eaten_type][index] << {height: jump_height, ate: ate}

  current_candy = $candies[index]

  if last_eaten_type != current_candy.type && jump_height >= current_candy.height
    find_max(index+1, ate+1, current_candy.type, jump_height + current_candy.weight )
  end

  find_max(index+1, ate, last_eaten_type, jump_height)
end

find_max(0, 0, 1, initial_jump_height)
find_max(0, 0, 0, initial_jump_height)
puts $max_ate

$candies_amount, initial_jump_height = gets.split.map(&:to_i)
$candies = []

$candies_amount.times do
  candy = {}
  candy[:type], candy[:height], candy[:weight] = gets.split.map(&:to_i)
  $candies << candy
end

$max_ate = 0

$tries = {nil => [], 0 => [], 1 => []}

def find_max(index, ate, last_eaten_type, jump_height)
  if index == $candies_amount
    $max_ate = ate if ate > $max_ate
    return
  end

  tries = $tries[last_eaten_type][index]
  if tries && tries.detect {|t| t[:height] >= jump_height && t[:ate] >= ate}
    return
  end

  $tries[last_eaten_type][index] ||= []
  $tries[last_eaten_type][index] << {height: jump_height, ate: ate}

  if last_eaten_type != $candies[index][:type] && jump_height >= $candies[index][:height]
    find_max(index+1, ate+1, $candies[index][:type], jump_height + $candies[index][:weight] )
  end

  find_max(index+1, ate, last_eaten_type, jump_height)
end

find_max(0, 0, nil, initial_jump_height)
puts $max_ate


There are n piles of pebbles on the table, the i-th pile contains ai pebbles. Your task is to paint each pebble using one of the k given colors so that for each color c and any two piles i and j the difference between the number of pebbles of color c in pile i and number of pebbles of color c in pile j is at most one.In other words, let's say that bi, c is the number of pebbles of color c in the i-th pile. Then for any 1 ≤ c ≤ k, 1 ≤ i, j ≤ n the following condition must be satisfied |bi, c - bj, c| ≤ 1. It isn't necessary to use all k colors: if color c hasn't been used in pile i, then bi, c is considered to be zero.

The first line of the input contains positive integers n and k (1 ≤ n, k ≤ 100), separated by a space — the number of piles and the number of colors respectively. The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 100) denoting number of pebbles in each of the piles.

If there is no way to paint the pebbles satisfying the given condition, output "NO" (without quotes) . Otherwise in the first line output "YES" (without quotes). Then n lines should follow, the i-th of them should contain ai space-separated integers. j-th (1 ≤ j ≤ ai) of these integers should be equal to the color of the j-th pebble in the i-th pile. If there are several possible answers, you may output any of them.

#!/usr/bin/env ruby
n,k=gets.split.map(&:to_i)
a=gets.split.map(&:to_i)
b=a.map{|e|
	h=Hash.new(0)
	z=e.times.map{|i|
		n=i%k+1
		h[n]+=1
		n
	}
	[z,h]
}
if b.combination(2).all?{|x,y|
	(1..k).all?{|e|(x[1][e]-y[1][e]).abs<=1}
}
	puts :YES
	puts b.map{|e|e[0]*' '}
else
	puts :NO
end

n,k=gets.chomp.split.map(&:to_i)
a=gets.chomp.split.map(&:to_i)
max,min=a.max,a.min
if max-min>k
	puts "NO"
else
	puts "YES"
	n.times do |i|
		j=0
		while j<a[i]
			print "#{(j%k)+1} "
			j+=1
		end
		puts
	end
end

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

colors = []
n.times { colors << [] }

min = 0
k.times do |i|
  if i == 0
    min = a.min + 1
  else
    min = 1
  end

  n.times do |j|
    min.times do |k|
      if a[j] != 0
        colors[j] << i + 1
        a[j] -= 1
      end
    end
  end
end

if a.max == 0
  puts "YES"
  n.times do |i|
    puts colors[i].join(" ")
  end
else
  puts "NO"
end

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

class PileData
  attr_accessor :data
  def initialize(x)
    @data = x.split.map(&:to_i)
  end
end
n, k = gets.split.map(&:to_i)
t = (1..k).map {|i| i}

w = PileData.new(gets)
if w.data.max - w.data.min > k
  puts 'NO'
else
  puts 'YES'
  n.times {|i|
    puts (t * (w.data[i] / k) + t[0, w.data[i] % k]).join(' ')
  }
end

#!/usr/bin/ruby

#read data
input_line = gets
params = input_line.split(' ')
n = params[0].to_i
k = params[1].to_i

a = gets.split(" ").map {|i| i.to_i}

#find max(a) and min(a)

if ((a.max - a.min)>k)
    puts 'NO'
else
    puts 'YES'
    a.each do |a_i|
        res = ''
        (0...a_i).each do |a_i_j|
          res += ((a_i_j % k)+1).to_s + ' '
        end
        puts res.strip
    end
end

n,k = gets.split(" ").map(&:to_i)
arr = gets.split(" ").map(&:to_i)
# col = arr.map{|a| a/k}
a,b = arr.minmax
# puts "#{col.minmax}"
ans = true
ans = false if b  - a > k
col_arr = (1..k).to_a

x = (100 / k.to_f).ceil
col_arr *= x
# puts "#{col_arr.length}"
if ans
	puts "YES"
	arr.each do |a|
		puts col_arr[0..(a-1)].join(" ")
	end
else
	puts "NO"
end
#

inp = gets.split(' ')
n = inp[0].to_i
m = inp[1].to_i

pebbles = gets.split(' ')
colors = Array.new() { Array.new() }
count = Array.new(n) { Array.new(m, 0) }

for i in 0..(n - 1)
	pebbles[i] = pebbles[i].to_i
	colors << Array.new(pebbles[i], 0)
end

for i in 0..(n - 1)
	color = 0
	for j in 0..(pebbles[i] - 1)
		colors[i][j] = color
		count[i][color] += 1
		color += 1
		if color >= m
			color = 0
		end
	end
	for j in 0..(i - 1)
		for k in 0..(m - 1)
			if (count[j][k] - count[i][k]).abs > 1
				puts "NO"
				exit
			end
		end
	end
end

puts "YES"
colors.each { |arr|
	arr.each { |el|
		print "#{el + 1} "
	}
	puts
}

pa = Array.new
pb = Array.new
data = Array.new

str = gets.to_s
stt = gets.to_s
pa = str.split
pb = stt.split
n = pa[0].to_i
k = pa[1].to_i

for i in 0..n-1
  data[i]=Array.new
  r = pb[i].to_i / k
  t = pb[i].to_i % k
  for j in 1..k
    if j <= t
      data[i][j] = r + 1
    else
      data[i][j] = r
    end
  end
end

flag = 0
for j in 1..k
   min = max = data[0][j]
   for i in 1..n-1
     if min > data[i][j]
       min = data[i][j]
     end
     if max < data[i][j]
       max = data[i][j]
     end
   end
   if max - min > 1
     flag = 1
     break
   end
end

if flag == 1
  puts "NO"
else
  puts "YES"
  for i in 0..n-1
    flag = 0
    for j in 1..k
      for r in 1..data[i][j]
        if flag == 0
          print j
          flag = 1
        else
          print " "
          print j
        end
      end
    end
    puts
  end
end

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

colors = []
n.times { colors << [] }

min = 0
k.times do |i|
  min = (a.select { |x| x != 0}).min

  n.times do |j|
    min.times do |k|
      colors[j] << i + 1 if a[j] != 0
    end
  end

  break if min == 0

  a = a.map { |x| x == 0 ? 0 : x - min }
end

if a.max == 0
  puts "YES"
  n.times do |i|
    puts colors[i].join(" ")
  end
else
  puts "NO"
end

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

colors = []
n.times { colors << [] }

min = 0
k.times do |i|
  if i == 0
    min = a.min
  else
    min = 1
  end

  n.times do |j|
    min.times do |k|
      colors[j] << i + 1 if a[j] != 0
    end
  end

  a = a.map { |x| x == 0 ? 0 : x - min }
end

if a.max == 0
  puts "YES"
  n.times do |i|
    puts colors[i].join(" ")
  end
else
  puts "NO"
end

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

class PileData
  attr_accessor :data
  def initialize(x)
    @data = x.split.map(&:to_i)
  end
end
n, k = gets.split.map(&:to_i)
t = (1..k).map {|i| i}

w = PileData.new(gets)
if w.data.max - w.data.min > k
  p 'NO'
else
  n.times {|i|
    puts (t * (w.data[i] / k) + t[0, w.data[i] % k]).join(' ')
  }
end

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

class PileData
  attr_accessor :data
  def initialize(x)
    @data = x.split.map(&:to_i)
  end
end
n, k = gets.split.map(&:to_i)
t = (1..k).map {|i| i}

w = PileData.new(gets)
if w.data.max - w.data.min > k
  p 'NO'
else
  p 'YES'
  n.times {|i|
    puts (t * (w.data[i] / k) + t[0, w.data[i] % k]).join(' ')
  }
end

#!/usr/bin/ruby

#read data
input_line = gets
params = input_line.split(' ')
n = params[0].to_i
k = params[1].to_i

a = gets.split(" ").map {|i| i.to_i}

#find max(a) and min(a)

if ((a.max - a.min)>k)
    puts 'NO'
else
    puts 'YES'
    res = ''
    a.each do |a_i|
        res += ((a_i % k)+1).to_s + ' '
        puts res.strip
    end
end

n,k = gets.split(" ").map(&:to_i)
arr = gets.split(" ").map(&:to_i)
# col = arr.map{|a| a/k}
a,b = arr.minmax
# puts "#{col.minmax}"
ans = true
ans = false if b  - a > k
col_arr = (1..k).to_a

x = (100 / k.to_f).ceil
col_arr *= x
puts "#{col_arr.length}"
if ans
	puts "YES"
	arr.each do |a|
		puts col_arr[0..(a-1)].join(" ")
	end
else
	puts "NO"
end

n,k = gets.split(" ").map(&:to_i)
arr = gets.split(" ").map(&:to_i)
col = arr.map{|a| a/k}
a,b = col.minmax
ans = true
ans = false if b  - a > 1
col_arr = (1..k).to_a

x = (100 / k.to_f).ceil
col_arr *= x
# puts "#{col_arr.length}"
if ans
	puts "YES"
	arr.each do |a|
		puts col_arr[0..(a-1)].join(" ")
	end
else
	puts "NO"
end

#!/usr/bin/ruby

n = gets.to_i
m = gets.to_i

pebbles = Array.new(n)
colors = Array.new() { Array.new() }
count = Array.new(n) { Array.new(m, 0) }

for i in 0..(n - 1)
	pebbles[i] = gets.to_i
	colors << Array.new(pebbles[i], 0)
end

for i in 0..(n - 1)
	color = 0
	for j in 0..(pebbles[i] - 1)
		colors[i][j] = color
		count[i][color] += 1
		color += 1
		if color >= m
			color = 0
		end
	end
	for j in 0..(i - 1)
		for k in 0..(m - 1)
			if (count[j][k] - count[i][k]).abs > 1
				puts "NO"
				exit
			end
		end
	end
end

puts "YES"
colors.each { |arr|
	arr.each { |el|
		print "#{el + 1} "
	}
	puts
}

#!/usr/bin/ruby

if __FILE__ == $0

	n = ARGV[0].to_i
	m = ARGV[1].to_i

	pebbles = Array.new(n)
	colors = Array.new() { Array.new() }
	count = Array.new(n) { Array.new(m, 0) }

	for i in 2..(n + 1)
		pebbles[i - 2] = ARGV[i].to_i
		colors << Array.new(pebbles[i - 2], 0)
	end

	for i in 0..(n - 1)
		color = 0
		for j in 0..(pebbles[i] - 1)
			colors[i][j] = color
			count[i][color] += 1
			color += 1
			if color >= m
				color = 0
			end
		end
		for j in 0..(i - 1)
			for k in 0..(m - 1)
				if (count[j][k] - count[i][k]).abs > 1
					puts "NO"
					exit
				end
			end
		end
	end

	puts "YES"
	colors.each { |arr|
		arr.each { |el|
			print "#{el + 1} "
		}
		puts
	}

end


You are given a string $$$s=s_1s_2\dots s_n$$$ of length $$$n$$$, which only contains digits $$$1$$$, $$$2$$$, ..., $$$9$$$.A substring $$$s[l \dots r]$$$ of $$$s$$$ is a string $$$s_l s_{l + 1} s_{l + 2} \ldots s_r$$$. A substring $$$s[l \dots r]$$$ of $$$s$$$ is called even if the number represented by it is even. Find the number of even substrings of $$$s$$$. Note, that even if some substrings are equal as strings, but have different $$$l$$$ and $$$r$$$, they are counted as different substrings.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 65000$$$) — the length of the string $$$s$$$. The second line contains a string $$$s$$$ of length $$$n$$$. The string $$$s$$$ consists only of digits $$$1$$$, $$$2$$$, ..., $$$9$$$.

Print the number of even substrings of $$$s$$$.

NoteIn the first example, the $$$[l, r]$$$ pairs corresponding to even substrings are:   $$$s[1 \dots 2]$$$ $$$s[2 \dots 2]$$$ $$$s[1 \dots 4]$$$ $$$s[2 \dots 4]$$$ $$$s[3 \dots 4]$$$ $$$s[4 \dots 4]$$$ In the second example, all $$$10$$$ substrings of $$$s$$$ are even substrings. Note, that while substrings $$$s[1 \dots 1]$$$ and $$$s[2 \dots 2]$$$ both define the substring "2", they are still counted as different substrings.

n = gets.to_i
s = gets.chomp.chars.map(&:to_i)
ans = 0
(0..n-1).each do |i|
  if s[i].even?
    ans += i + 1
  end
end
puts ans

n = gets.to_i
s = gets
ans = 0
n.times do |i|
  if /[02468]/ =~ s[i]
    ans += i+1
  end
end
puts ans

ans = 0
gets
gets.split('').each_with_index{|x, i|
    ans += i + 1 if ['0', '2', '4', '6', '8'].include? x
}
puts ans

require 'enumerator'
gets
s = gets;
puts s.enum_for(:scan, /[2468]/)
      .map { Regexp.last_match.begin(0) + 1 }
      .inject(0) {|r, p| r + p}


Eshag has an array $$$a$$$ consisting of $$$n$$$ integers.Eshag can perform the following operation any number of times: choose some subsequence of $$$a$$$ and delete every element from it which is strictly larger than $$$AVG$$$, where $$$AVG$$$ is the average of the numbers in the chosen subsequence.For example, if $$$a = [1 , 4 , 3 , 2 , 4]$$$ and Eshag applies the operation to the subsequence containing $$$a_1$$$, $$$a_2$$$, $$$a_4$$$ and $$$a_5$$$, then he will delete those of these $$$4$$$ elements which are larger than $$$\frac{a_1+a_2+a_4+a_5}{4} = \frac{11}{4}$$$, so after the operation, the array $$$a$$$ will become $$$a = [1 , 3 , 2]$$$.Your task is to find the maximum number of elements Eshag can delete from the array $$$a$$$ by applying the operation described above some number (maybe, zero) times.A sequence $$$b$$$ is a subsequence of an array $$$c$$$ if $$$b$$$ can be obtained from $$$c$$$ by deletion of several (possibly, zero or all) elements.

The first line contains an integer $$$t$$$ $$$(1\le t\le 100)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1\le n\le 100)$$$ — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1\le a_i \le 100)$$$ — the elements of the array $$$a$$$.

For each test case print a single integer — the maximum number of elements Eshag can delete from the array $$$a$$$.

NoteConsider the first test case.Initially $$$a = [1, 1, 1, 2, 2, 3]$$$.In the first operation, Eshag can choose the subsequence containing $$$a_1$$$, $$$a_5$$$ and $$$a_6$$$, their average is equal to $$$\frac{a_1 + a_5 + a_6}{3} = \frac{6}{3} = 2$$$. So $$$a_6$$$ will be deleted.After this $$$a = [1, 1, 1, 2, 2]$$$.In the second operation, Eshag can choose the subsequence containing the whole array $$$a$$$, the average of all its elements is equal to $$$\frac{7}{5}$$$. So $$$a_4$$$ and $$$a_5$$$ will be deleted.After this $$$a = [1, 1, 1]$$$.In the second test case, Eshag can't delete any element.

def solve
  n = gets.to_i
  a = gets.split.map(&:to_i)
  m = a.min
  puts a.count { |x| x > m }
end

t = gets.to_i
t.times do
  solve
end

t = gets.chomp.to_i

t.times do
  n = gets.chomp.to_i
  arr = gets.chomp.split(" ").map(&:to_i)
  arr.delete(arr.min)
  puts arr.size
end

def solution(n, arr)
	average = arr.sum / n

	removed = true
	result = 0

	while removed
		i = 0
		removed = false

		while i < n
			if arr[i] > average
				arr.delete_at(i)
				n -= 1
				result += 1
				removed = true

				average = arr.sum / n
			end

			i += 1
		end
	end

	result
end

test_cases = gets.to_i

test_cases.times do
  n = gets.to_i
  arr = gets.chomp.split(' ').map(&:to_i)
  puts solution(n, arr)
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  a = gets.to_s.split.map {|x| x.to_i }.sort
  i = 0
  i += 1 while a[i] == a[0]
  printf("%d\n", a.size - i)
end


You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.Let's define a substring as a contiguous subsegment of a string. For example, "acab" is a substring of "abacaba" (it starts in position $$$3$$$ and ends in position $$$6$$$), but "aa" or "d" aren't substrings of this string. So the substring of the string $$$s$$$ from position $$$l$$$ to position $$$r$$$ is $$$s[l; r] = s_l s_{l + 1} \dots s_r$$$.You have to choose exactly one of the substrings of the given string and reverse it (i. e. make $$$s[l; r] = s_r s_{r - 1} \dots s_l$$$) to obtain a string that is less lexicographically. Note that it is not necessary to obtain the minimum possible string.If it is impossible to reverse some substring of the given string to obtain a string that is less, print "NO". Otherwise print "YES" and any suitable substring.String $$$x$$$ is lexicographically less than string $$$y$$$, if either $$$x$$$ is a prefix of $$$y$$$ (and $$$x \ne y$$$), or there exists such $$$i$$$ ($$$1 \le i \le min(|x|, |y|)$$$), that $$$x_i < y_i$$$, and for any $$$j$$$ ($$$1 \le j < i$$$) $$$x_j = y_j$$$. Here $$$|a|$$$ denotes the length of the string $$$a$$$. The lexicographic comparison of strings is implemented by operator < in modern programming languages.

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

If it is impossible to reverse some substring of the given string to obtain a string which is lexicographically less, print "NO". Otherwise print "YES" and two indices $$$l$$$ and $$$r$$$ ($$$1 \le l < r \le n$$$) denoting the substring you have to reverse. If there are multiple answers, you can print any.

NoteIn the first testcase the resulting string is "aacabba".

n = gets.chomp.to_i

str = gets.chomp

small = str[0]
curr = 0
low = -1
high = -1

(n-1).times.with_index do |x|
	if str[x+1] < small
		low = curr+1
		high = x+2
		break
	else
		curr = x+1
		small = str[x+1]
	end
end
if low != -1
	puts "YES"
	puts "#{low} #{high}"
else
	puts "NO"
end

n   = gets.to_i
str = gets.chomp.chars

if str == str.sort
  puts :NO
else
  (n - 1).times do |i|
    if str[i] > str[i + 1]
      right = i + 1
      left = i
      while str[left] <= str[right]
        left -= 1
      end
      puts :YES, [left + 1, right + 1].join(' ')
    break
    end
  end
end

n = gets.chomp.to_i

str = gets.chomp

small = str[0]
curr = 1
low = -1
high = -1

(n-1).times.with_index do |x|
	if str[x+1] < small
		low = curr+1
		high = x+2
		break
	else
		curr = x+1
		small = str[x+1]
	end
end
if low != -1
	puts "YES"
	puts "#{low} #{high}"
else
	puts "NO"
end

n = gets.chomp.to_i

str = gets.chomp

small = str[0]
curr = 1
low = -1
high = -1

(n-1).times.with_index do |x|
	if str[x+1] < small
		low = curr+1
		high = x+2
		break
	else
		curr = x+1
		small = str[x+1]
	end
end
if low != "-1"
	p "YES"
	p "#{low} #{high}"
else
	p "NO"
end


Businessman Divan loves chocolate! Today he came to a store to buy some chocolate. Like all businessmen, Divan knows the value of money, so he will not buy too expensive chocolate. At the same time, too cheap chocolate tastes bad, so he will not buy it as well.The store he came to has $$$n$$$ different chocolate bars, and the price of the $$$i$$$-th chocolate bar is $$$a_i$$$ dollars. Divan considers a chocolate bar too expensive if it costs strictly more than $$$r$$$ dollars. Similarly, he considers a bar of chocolate to be too cheap if it costs strictly less than $$$l$$$ dollars. Divan will not buy too cheap or too expensive bars.Divan is not going to spend all his money on chocolate bars, so he will spend at most $$$k$$$ dollars on chocolates.Please determine the maximum number of chocolate bars Divan can buy.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The description of each test case consists of two lines. The first line contains integers $$$n$$$, $$$l$$$, $$$r$$$, $$$k$$$ ($$$1 \le n \le 100$$$, $$$1 \le l \le r \le 10^9$$$, $$$1 \le k \le 10^9$$$) — the lowest acceptable price of a chocolate, the highest acceptable price of a chocolate and Divan's total budget, respectively. The second line contains a sequence $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) integers — the prices of chocolate bars in the store.

For each test case print a single integer — the maximum number of chocolate bars Divan can buy.

NoteIn the first example Divan can buy chocolate bars $$$1$$$ and $$$3$$$ and spend $$$100$$$ dollars on them.In the second example Divan can buy chocolate bars $$$3$$$ and $$$4$$$ and spend $$$7$$$ dollars on them.In the third example Divan can buy chocolate bars $$$3$$$, $$$4$$$, and $$$5$$$ for $$$12$$$ dollars.In the fourth example Divan cannot buy any chocolate bar because each of them is either too cheap or too expensive.In the fifth example Divan cannot buy any chocolate bar because he considers the first bar too cheap, and has no budget for the second or third.In the sixth example Divan can buy all the chocolate bars in the shop.

gets.to_i.times do
  n, l, r, k = gets.split.map(&:to_i)
  as = gets.split.map(&:to_i)
  p as.sort.select { |a| a >= l && a <= r }.take_while { |a| k -= a; k >= 0 }.size
end

t = gets

t = t.to_i

(1..t).each do |e|
    inp = gets
    inp = inp.split(' ').map(&:to_i)
    a = gets
    a = a.split(' ').map(&:to_i)
    a.sort!
    #puts "{a: #{a}"
    cur = 0
    res = 0
    a.each do |x|
        if (cur+x) <= inp[3]
            if x >= inp[1] && x <= inp[2]
                cur += x
                res += 1
            end
        else
            break
        end
    end

    puts res
end


Let's say string $$$s$$$ has period $$$k$$$ if $$$s_i = s_{i + k}$$$ for all $$$i$$$ from $$$1$$$ to $$$|s| - k$$$ ($$$|s|$$$ means length of string $$$s$$$) and $$$k$$$ is the minimum positive integer with this property.Some examples of a period: for $$$s$$$="0101" the period is $$$k=2$$$, for $$$s$$$="0000" the period is $$$k=1$$$, for $$$s$$$="010" the period is $$$k=2$$$, for $$$s$$$="0011" the period is $$$k=4$$$.You are given string $$$t$$$ consisting only of 0's and 1's and you need to find such string $$$s$$$ that:  String $$$s$$$ consists only of 0's and 1's;  The length of $$$s$$$ doesn't exceed $$$2 \cdot |t|$$$;  String $$$t$$$ is a subsequence of string $$$s$$$;  String $$$s$$$ has smallest possible period among all strings that meet conditions 1—3. Let us recall that $$$t$$$ is a subsequence of $$$s$$$ if $$$t$$$ can be derived from $$$s$$$ by deleting zero or more elements (any) without changing the order of the remaining elements. For example, $$$t$$$="011" is a subsequence of $$$s$$$="10101".

The first line contains single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. Each line contains string $$$t$$$ ($$$1 \le |t| \le 100$$$) consisting only of 0's and 1's.

Print one string for each test case — string $$$s$$$ you needed to find. If there are multiple solutions print any one of them.

NoteIn the first and second test cases, $$$s = t$$$ since it's already one of the optimal solutions. Answers have periods equal to $$$1$$$ and $$$2$$$, respectively.In the third test case, there are shorter optimal solutions, but it's okay since we don't need to minimize the string $$$s$$$. String $$$s$$$ has period equal to $$$1$$$.

gets.to_i.times {
    t=gets.chomp.chars
    if t.uniq.size==1
        s=t*''
    else
        s=t.shift
        t.each{|c|
            s+=(c==?0 ? ?1 : ?0) if s[-1]==c
            s+=c
        }
    end
    puts s
}

1.upto(gets.chomp.to_i) do
  t = gets.chomp
  at = t.split(//)
  if at.uniq.size == 1
    puts t
  else
    puts "01"*t.size
  end
end

tttt = gets.chomp.to_i

# 周期性
def chkPeriod(str)
	(1..str.length/2).each do |i|
		ngo = str.chars.each_slice(i).to_a
		return i if ngo.uniq.length == 1
	end
	return -1
end

#sがtのサブシーケンスか
def chkSubsequence(s, t)
	si = 0
	ti = 0
	while si < s.length || ti < t.length
		return false if si >= s.length
		return true if ti >= t.length
		if s[si] == t[ti] then
			ti += 1
		end
		si += 1
	end
end

tttt.times do
	t = gets.chomp
	if t.chars.uniq.length == 1 then
		puts t
		next
	end

	# 次にどの文字をぶちこむか(true→1 false→0)
	str = ""
	i = 0
	while i < t.length
		if t[i+1] != t[i] && i < t.length - 1 then
			str += t[i]
			i += 1
			next
		end
		str += t[i]
		str += t[i] == "0" ? "1" : "0"
		i += 1
	end
	#puts str
	str = str[0] != str[-1] ? str : str.slice(0,str.length - 1)
	puts str
end

1.upto(gets.to_i) do
  s = gets.chomp

  same = s.chars.all? { |c| s[0] == c }

  while !same
    ll = s.length
    s.gsub!('00', '010')
    s.gsub!('11', '101')

    break if ll == s.length
  end

  puts s
end

def solution
  s = gets.chop!
  chars = s.chars
  zeros = chars.count("0")
  ones = chars.count("1")

  return s if zeros == 0 || ones == 0

  i = 0
  while i < s.size
    if s[i] == s[i + 1]
      s.insert(i + 1, s[i] == '0' ? '1' : '0')
    end
    i += 1
  end

  s
end

t = gets.to_i
t.times do
  print "#{solution}\n"
end

def solution
  s = gets.chop!
  chars = s.chars
  zeros = chars.count("0")
  ones = chars.count("1")

  return s if zeros == 0 || ones == 0

  (0..s.size).to_a.each do |i|
    if s[i] != s[i + 2] && s[i + 2]
      s.insert(i + 1, s[i] == '0' ? '1' : '0')
    end
  end

  s
end

t = gets.to_i
t.times do
  print "#{solution}\n"
end

def solution
  s = gets.chop!
  "10" * (s.size / 2)
end

t = gets.to_i
t.times do
  print "#{solution}\n"
end

def solution
  s = gets.chop!
  chars = s.chars
  zeros = chars.count("0")
  ones = chars.count("1")

  return s if zeros == 0 || ones == 0

  chars.size.times do |i|
    if s[i] == s[i + 1]
      s.insert(i + 1, s[i] == '0' ? '1' : '0')
    end
  end

  s
end

t = gets.to_i
t.times do
  print "#{solution}\n"
end

def solution
  s = gets.chop!
  chars = s.chars
  zeros = chars.count("0")
  ones = chars.count("1")

  return s if zeros == 0 || ones == 0

  chars.size.times do |i|
    next if i == 0
    if s[i] == s[i-1]
      s.insert(i, s[i] == '0' ? '1' : '0')
    end
  end

  s
end

t = gets.to_i
t.times do
  print "#{solution}\n"
end

def solution
  s = gets.chop!
  chars = s.chars
  zeros = chars.count("0")
  ones = chars.count("1")

  return s if zeros == 0 || ones == 0

  (0..chars.size).to_a.each do |i|
    if s[i] != s[i + 2] && s[i + 2]
      s.insert(i + 1, s[i] == '0' ? '1' : '0')
    end
  end

  s
end

t = gets.to_i
t.times do
  print "#{solution}\n"
end


High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?

The first line of the input contains two integers n and k (1 ≤ n ≤ 100 000, 0 ≤ k ≤ n) — the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.

Print the only integer — the maximum beauty of the string Vasya can achieve by changing no more than k characters.

NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".

N, K = gets.chomp.split.map &:to_i

str = gets.chomp

def calcu str, base_chr, k
    count = 0
    pos = 0
    ret = 0
    for i in 0...str.length
        while pos < str.length && count <= k
            if str[pos] == base_chr
                count += 1
            end
            pos += 1
        end
        len = pos - i
        if str[pos-1] == base_chr && count > k
            len -= 1
        end

        if ret < len
            ret = len
        end

        if str[i] == base_chr
            count -= 1
        end
    end

    ret
end

ans = [(calcu str, "a", K), (calcu str, "b", K)].max
puts ans

x , k = gets.strip.split(' ').map(&:to_i);
n = gets.chomp
c = 0
l = 0
best = 0
for i in 0 ... x
  if (n[i] != 'a')
    c+=1
  end
  while(c > k)
    if (n[l] == 'b')
      c-=1
    end
    l+=1
  end
  best = [best , i - l + 1].max
end
c = 0
l = 0
for i in 0 ... x
  if (n[i] != 'b')
    c+=1
  end

  while(c > k)
    if (n[l] == 'a')
      c-=1
    end
    l+=1
  end
  best = [best , i - l + 1].max
end
puts best

N, K = gets.chomp.split.map &:to_i

str = gets.chomp

def calcu str, base_chr, k
    count = 0
    pos = 0
    ret = 0
    for i in 0...str.length
        while pos < str.length && count <= k
            if str[pos] == base_chr
                count += 1
            end
            pos += 1
        end
        len = pos - i
        if str[pos-1] == base_chr && count > k
            len -= 1
        end

        if ret < len
            ret = len
        end

        if str[pos] == base_chr
            count -= 1
        end
    end

    ret
end

ans = [(calcu str, "a", K), (calcu str, "b", K)].max
puts ans

N, K = gets.chomp.split.map &:to_i

str = gets.chomp

def calcu str, base_chr, k
    count = 0
    pos = 0
    ret = 0
    for i in 0...str.length
        while pos < str.length && count <= k
            if str[pos] == base_chr
                count += 1
            end
            pos += 1
        end
        len = pos - i
        if str[pos-1] == base_chr && count == k
            len -= 1
        end

        if ret < len
            ret = len
        end

        if str[pos] == base_chr
            count -= 1
        end
    end

    ret
end

ans = [(calcu str, "a", K), (calcu str, "b", K)].max
puts ans


You have two positive integers $$$a$$$ and $$$b$$$.You can perform two kinds of operations:  $$$a = \lfloor \frac{a}{b} \rfloor$$$ (replace $$$a$$$ with the integer part of the division between $$$a$$$ and $$$b$$$)  $$$b=b+1$$$ (increase $$$b$$$ by $$$1$$$) Find the minimum number of operations required to make $$$a=0$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The only line of the description of each test case contains two integers $$$a$$$, $$$b$$$ ($$$1 \le a,b \le 10^9$$$).

For each test case, print a single integer: the minimum number of operations required to make $$$a=0$$$.

NoteIn the first test case, one of the optimal solutions is:  Divide $$$a$$$ by $$$b$$$. After this operation $$$a = 4$$$ and $$$b = 2$$$.  Divide $$$a$$$ by $$$b$$$. After this operation $$$a = 2$$$ and $$$b = 2$$$.  Increase $$$b$$$. After this operation $$$a = 2$$$ and $$$b = 3$$$.  Divide $$$a$$$ by $$$b$$$. After this operation $$$a = 0$$$ and $$$b = 3$$$.

gets.to_i.times do
    a, b = gets.split.map &:to_i
    if a == 0
        puts 0
        next
    end
    res, i = a + 3, b < 2 ? 2 - b : 0
    while i < res do
        ca, cur = a, i
        while ca > 0 do
            ca /= b + i
            cur += 1
        end
        res = [res, cur].min
        i += 1
    end
    puts res
end

def method(a, b)
  if b == 1
    return 100
  end
  res = 0
  while a != 0
    a /= b
    res += 1
  end
  res
end

t = gets.to_i
t.times do
  a, b = gets.split.map { |x| x.to_i }
  puts (0..30).map { |x| method(a, b + x) + x }.min
end

gets.to_i.times do
  a,b=gets.split.map(&:to_i)
  c=0
  if b==1
    b+=1
    c+=1
  end
  cmin=1/0.0
  cc=c
  bb=b
  aa=a
  while true
    a=aa
    b=bb
    c=cc
    while a>b
      a=a/b
      c+=1
    end
    c+=1 if a==b
    if c+1<=cmin
      cmin=c+1
    else
      puts cmin
      break
    end
    bb+=1
    cc+=1
  end
end


Today, Yasser and Adel are at the shop buying cupcakes. There are $$$n$$$ cupcake types, arranged from $$$1$$$ to $$$n$$$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $$$i$$$ is an integer $$$a_i$$$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment $$$[l, r]$$$ $$$(1 \le l \le r \le n)$$$ that does not include all of cupcakes (he can't choose $$$[l, r] = [1, n]$$$) and buy exactly one cupcake of each of types $$$l, l + 1, \dots, r$$$.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be $$$[7, 4, -1]$$$. Yasser will buy all of them, the total tastiness will be $$$7 + 4 - 1 = 10$$$. Adel can choose segments $$$[7], [4], [-1], [7, 4]$$$ or $$$[4, -1]$$$, their total tastinesses are $$$7, 4, -1, 11$$$ and $$$3$$$, respectively. Adel can choose segment with tastiness $$$11$$$, and as $$$10$$$ is not strictly greater than $$$11$$$, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$), where $$$a_i$$$ represents the tastiness of the $$$i$$$-th type of cupcake. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".

NoteIn the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example, Adel will choose the segment $$$[1, 2]$$$ with total tastiness $$$11$$$, which is not less than the total tastiness of all cupcakes, which is $$$10$$$.In the third example, Adel can choose the segment $$$[3, 3]$$$ with total tastiness of $$$5$$$. Note that Yasser's cupcakes' total tastiness is also $$$5$$$, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes.

T = gets.to_i

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

  var = -Float::INFINITY
  cur = 0
  len = 0

  a.each do |v|
    if cur < 0
      len = 1
      cur = v
    else
      len += 1
      cur += v
    end

    if var < cur && len < n
      var = cur
    end
  end

  cur = 0
  len = 0

  a.reverse_each do |v|
    if cur < 0
      len = 1
      cur = v
    else
      len += 1
      cur += v
    end

    if var < cur && len < n
      var = cur
    end
  end

  sum = a.inject(:+)

  if var >= sum
    puts 'NO'
  else
    puts 'YES'
  end
end

# frozen_string_literal: true

def one_test
  gets.to_i
  vec = gets.strip.split.map(&:to_i)
#  puts vec.to_s
  puts(test(vec) || test(vec.reverse) ? 'NO' : 'YES')
end

def test(vector)
  vector = vector.clone
  vector.pop
#  puts vector.to_s
  sum = 0
  vector.each do |a|
    sum += a
   #  puts sum.to_s + "   " + a.to_s
    return true unless sum > 0
  end
  false
end

n = gets
n.to_i.times { one_test }

T = gets.to_i

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

  var = -Float::INFINITY
  cur = 0
  len = 0
  max_len = 0

  a.each do |v|
    if cur < 0
      len = 1
      cur = v
    else
      len += 1
      cur += v
    end

    if var < cur
      max_len = len
      var = cur
    end
  end

  sum = a.inject(:+)

  if max_len < n && var >= sum
    puts 'NO'
  else
    puts 'YES'
  end
end

T = gets.to_i

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

  var = -Float::INFINITY
  cur = 0
  len = 0

  a.each do |v|
    if cur < 0
      len = 1
      cur = v
    else
      len += 1
      cur += v
    end

    if var < cur && len < n
      var = cur
    end
  end

  sum = a.inject(:+)

  if var >= sum
    puts 'NO'
  else
    puts 'YES'
  end
end

# frozen_string_literal: true

def one_test
  gets.to_i
  vec = gets.strip.split.map(&:to_i)
  puts vec.to_s
  puts(test(vec) || test(vec.reverse) ? 'NO' : 'YES')
end

def test(vector)
  vector = vector.clone
  vector.pop
  puts vector.to_s
  sum = 0
  vector.each do |a|
    sum += a
    if a <= 0
      return true
    end
  end
  false
end

n = gets
n.to_i.times { one_test }

# frozen_string_literal: true

def one_test
  gets.to_i
  vec = gets.strip.split.map(&:to_i)
#  puts vec.to_s
  puts(test(vec) || test(vec.reverse) ? 'NO' : 'YES')
end

def test(vector)
  vector = vector.clone
  vector.pop
#  puts vector.to_s
  sum = 0
  vector.each do |a|
    sum += a
    if a <= 0
      return true
    end
  end
  false
end

n = gets
n.to_i.times { one_test }


Inflation has occurred in Berlandia, so the store needs to change the price of goods.The current price of good $$$n$$$ is given. It is allowed to increase the price of the good by $$$k$$$ times, with $$$1 \le k \le m$$$, k is an integer. Output the roundest possible new price of the good. That is, the one that has the maximum number of zeros at the end.For example, the number 481000 is more round than the number 1000010 (three zeros at the end of 481000 and only one at the end of 1000010).If there are several possible variants, output the one in which the new price is maximal.If it is impossible to get a rounder price, output $$$n \cdot m$$$ (that is, the maximum possible price).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases in the test. Each test case consists of one line. This line contains two integers: $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^9$$$). Where $$$n$$$ is the old price of the good, and the number $$$m$$$ means that you can increase the price $$$n$$$ no more than $$$m$$$ times.

For each test case, output on a separate line the roundest integer of the form $$$n \cdot k$$$ ($$$1 \le k \le m$$$, $$$k$$$ — an integer). If there are several possible variants, output the one in which the new price (value $$$n \cdot k$$$) is maximal. If it is impossible to get a more rounded price, output $$$n \cdot m$$$ (that is, the maximum possible price).

NoteIn the first case $$$n = 6$$$, $$$m = 11$$$. We cannot get a number with two zeros or more at the end, because we need to increase the price $$$50$$$ times, but $$$50 > m = 11$$$. The maximum price multiple of $$$10$$$ would be $$$6 \cdot 10 = 60$$$.In the second case $$$n = 5$$$, $$$m = 43$$$. The maximum price multiple of $$$100$$$ would be $$$5 \cdot 40 = 200$$$.In the third case, $$$n = 13$$$, $$$m = 5$$$. All possible new prices will not end in $$$0$$$, then you should output $$$n \cdot m = 65$$$.In the fourth case, you should increase the price $$$15$$$ times.In the fifth case, increase the price $$$12000$$$ times.

zeros = ->n {
  count = 0
  while n % 10 == 0
    count += 1
    n /= 10
  end
  count
}

gets.to_i.times do
  n, m = gets.split.map(&:to_i)
  o = 1
  o *= 2 while o * 2 < m && zeros[n * o * 2] > zeros[n * o]
  o *= 5 while o * 5 < m && zeros[n * o * 5] > zeros[n * o]
  o *= 10 while o * 10 < m && zeros[n * o * 10] > zeros[n * o]
  o *= m / o
  p n * o
end

zeros = ->n { n.to_s.reverse.chars.take_while { |c| c == "0" }.size }

gets.to_i.times do
  n, m = gets.split.map(&:to_i)
  o = 1
  o *= 2 while o * 2 < m && zeros[n * o * 2] > zeros[n * o]
  o *= 5 while o * 5 < m && zeros[n * o * 5] > zeros[n * o]
  o *= 10 while o * 10 < m && zeros[n * o * 10] > zeros[n * o]
  o *= m / o
  p n * o
end

gets.to_i.times do
    n,m=gets.chomp.split(' ').map(&:to_i)
    factor=1
    t=n
    while t%10==0 do
        t/=10
    end
    while t%2==0 && factor*5 <= m do
        t/=2
        factor*=5
    end
    while t%5==0 && factor*2 <= m do
        t/=5
        factor *=2
    end
    while factor*10<=m
        factor*=10
    end
    puts n*(m-m%factor)
end


Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times:   A  BC  B  AC  C  AB  AAA  empty string Note that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source.

The first line contains a string S (1 ≤ |S| ≤ 105). The second line contains a string T (1 ≤ |T| ≤ 105), each of these strings consists only of uppercase English letters 'A', 'B' and 'C'. The third line contains the number of queries Q (1 ≤ Q ≤ 105). The following Q lines describe queries. The i-th of these lines contains four space separated integers ai, bi, ci, di. These represent the i-th query: is it possible to create T[ci..di] from S[ai..bi] by applying the above transitions finite amount of times? Here, U[x..y] is a substring of U that begins at index x (indexed from 1) and ends at index y. In particular, U[1..|U|] is the whole string U. It is guaranteed that 1 ≤ a ≤ b ≤ |S| and 1 ≤ c ≤ d ≤ |T|.

Print a string of Q characters, where the i-th character is '1' if the answer to the i-th query is positive, and '0' otherwise.

NoteIn the first query we can achieve the result, for instance, by using transitions .The third query asks for changing AAB to A — but in this case we are not able to get rid of the character 'B'.

$numAs=Array.new(1, 0)
$numBs=Array.new(1, 0)
$numAs1=Array.new(1, 0)
$numBs1=Array.new(1, 0)

def f(a, b, c, d)
    nA=[b-a+1, $numAs[b]].min
    nB=$numBs[b]-$numBs[a-1]
    nA1=[d-c+1, $numAs1[d]].min
    nB1=$numBs1[d]-$numBs1[c-1]
#    print nA, nB, nA1, nB1, "\n"
    if (nB==nB1)
        if (nA>=nA1 && (nA%3)==(nA1%3))
            print 1
        else
            print 0
        end
    elsif (nB<nB1 && (nB%2)==(nB1%2))
        if (nB==0)
            nA-=1
        end
        if (nA>=nA1)
            print 1
        else
            print 0
        end
    else
        print 0
    end
end

s=gets
s1=gets
n=gets.to_i
(0..s.length-1).each{|x| $numBs.push($numBs[x]+(s[x]=="B" || s[x]=="C" ? 1 : 0 ))}
(0..s1.length-1).each{|x| $numBs1.push($numBs1[x]+(s1[x]=="B" || s1[x]=="C" ? 1 : 0 ))}
(0..s.length-1).each{|x| $numAs.push(s[x]=='A' ? $numAs[x]+1 : 0)}
(0..s1.length-1).each{|x| $numAs1.push(s1[x]=='A' ? $numAs1[x]+1 : 0)}
t=Array.new
for i in 0...n
  t=gets.split(' ').collect{|x| x.to_i}
  f(t[0], t[1], t[2], t[3])
end

$numAs=Array.new(1, 0)
$numBs=Array.new(1, 0)
$numAs1=Array.new(1, 0)
$numBs1=Array.new(1, 0)

def f(a, b, c, d)
    nA=[b-a+1, $numAs[b]].min
    nB=$numBs[b]-$numBs[a-1]
    nA1=[d-c+1, $numAs1[d]].min
    nB1=$numBs1[d]-$numBs1[c-1]
#    print nA, nB, nA1, nB1, "\n"
    if (nB==nB1)
        if (nA>=nA1 && (nA%3)==(nA1%3))
            print 1
        else
            print 0
        end
    elsif (nB<nB1)
        if (nB==0)
            nA-=1
        end
        if (nA>nA1)
            print 1
        else
            print 0
        end
    else
        print 0
    end
end

s=gets
s1=gets
n=gets.to_i
(0..s.length-1).each{|x| $numBs.push($numBs[x]+(s[x]=="B" || s[x]=="C" ? 1 : 0 ))}
(0..s1.length-1).each{|x| $numBs1.push($numBs1[x]+(s1[x]=="B" || s1[x]=="C" ? 1 : 0 ))}
(0..s.length-1).each{|x| $numAs.push(s[x]=='A' ? $numAs[x]+1 : 0)}
(0..s1.length-1).each{|x| $numAs1.push(s1[x]=='A' ? $numAs1[x]+1 : 0)}
t=Array.new
for i in 0...n
  t=gets.split(' ').collect{|x| x.to_i}
  f(t[0], t[1], t[2], t[3])
end

$numAs=Array.new(1, 0)
$numBs=Array.new(1, 0)
$numAs1=Array.new(1, 0)
$numBs1=Array.new(1, 0)

def f(a, b, c, d)
    nA=[b-a+1, $numAs[b]].min
    nB=$numBs[b]-$numBs[a-1]
    nA1=[d-c+1, $numAs1[d]].min
    nB1=$numBs1[d]-$numBs1[c-1]
#    print nA, nB, nA1, nB1, "\n"
    if (nB==nB1)
        if (nA>=nA1 && (nA%3)==(nA1%3))
            print 1
        else
            print 0
        end
    elsif (nB<nB1)
        if (nB==0)
            nA-=1
        end
        if (nA>=nA1)
            print 1
        else
            print 0
        end
    else
        print 0
    end
end

s=gets
s1=gets
n=gets.to_i
(0..s.length-1).each{|x| $numBs.push($numBs[x]+(s[x]=="B" || s[x]=="C" ? 1 : 0 ))}
(0..s1.length-1).each{|x| $numBs1.push($numBs1[x]+(s1[x]=="B" || s1[x]=="C" ? 1 : 0 ))}
(0..s.length-1).each{|x| $numAs.push(s[x]=='A' ? $numAs[x]+1 : 0)}
(0..s1.length-1).each{|x| $numAs1.push(s1[x]=='A' ? $numAs1[x]+1 : 0)}
t=Array.new
for i in 0...n
  t=gets.split(' ').collect{|x| x.to_i}
  f(t[0], t[1], t[2], t[3])
end


Authors guessed an array $$$a$$$ consisting of $$$n$$$ integers; each integer is not less than $$$2$$$ and not greater than $$$2 \cdot 10^5$$$. You don't know the array $$$a$$$, but you know the array $$$b$$$ which is formed from it with the following sequence of operations:  Firstly, let the array $$$b$$$ be equal to the array $$$a$$$;  Secondly, for each $$$i$$$ from $$$1$$$ to $$$n$$$:   if $$$a_i$$$ is a prime number, then one integer $$$p_{a_i}$$$ is appended to array $$$b$$$, where $$$p$$$ is an infinite sequence of prime numbers ($$$2, 3, 5, \dots$$$);  otherwise (if $$$a_i$$$ is not a prime number), the greatest divisor of $$$a_i$$$ which is not equal to $$$a_i$$$ is appended to $$$b$$$;   Then the obtained array of length $$$2n$$$ is shuffled and given to you in the input. Here $$$p_{a_i}$$$ means the $$$a_i$$$-th prime number. The first prime $$$p_1 = 2$$$, the second one is $$$p_2 = 3$$$, and so on.Your task is to recover any suitable array $$$a$$$ that forms the given array $$$b$$$. It is guaranteed that the answer exists (so the array $$$b$$$ is obtained from some suitable array $$$a$$$). If there are multiple answers, you can print any.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$2n$$$ integers $$$b_1, b_2, \dots, b_{2n}$$$ ($$$2 \le b_i \le 2750131$$$), where $$$b_i$$$ is the $$$i$$$-th element of $$$b$$$. $$$2750131$$$ is the $$$199999$$$-th prime number.

In the only line of the output print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$2 \le a_i \le 2 \cdot 10^5$$$) in any order — the array $$$a$$$ from which the array $$$b$$$ can be obtained using the sequence of moves given in the problem statement. If there are multiple answers, you can print any.

MAX = 2750159
$primes = (0..MAX).to_a
def generate_primes
  $primes[0] = $primes[1] = nil
  counter = 0
  $primes.each do |p|
    next unless p
    break if p*p > MAX
    counter += 1
    (p*p).step(MAX,p) { |m| $primes[m] = nil }
  end
  $primes = $primes.compact
end

def bs(a, e)
  l, r = 0, a.size - 1
  while l <= r
    m = (l + r) / 2
    if a[m] < e
      l = m + 1
    elsif a[m] > e
      r = m - 1
    else
      return m
    end
  end
  -1
end

def prime?(n)
  bs($primes, n) != -1
end

def gd(n)
  return n / 2 if n % 2 == 0
  sq = Math.sqrt(n).to_i
  idx = 0
  while $primes[idx] <= sq
    return n / $primes[idx] if n % $primes[idx] == 0
    idx += 1
  end
end

def solve(a)
  h = a.inject({}) { |m, e| m[e] = (m[e] || 0) + 1; m }
  rev = a.reverse
  res = []
  rev.each_with_index do |n, i|
    next if h[n].zero?

    if prime?(n)
      p_idx = bs($primes, n)
      res << p_idx + 1
      h[p_idx + 1] -= 1
      h[n] -= 1
    else
      div = gd(n)
      res << n
      h[div] -= 1
      h[n] -= 1
    end
  end
  res.join(' ')
end

generate_primes()
n = gets.strip.to_i
a = gets.strip.split(' ').map(&:to_i).sort
puts solve(a)