You are given an array $$$a$$$ consisting of $$$n$$$ integers.Your task is to determine if $$$a$$$ has some subsequence of length at least $$$3$$$ that is a palindrome.Recall that an array $$$b$$$ is called a subsequence of the array $$$a$$$ if $$$b$$$ can be obtained by removing some (possibly, zero) elements from $$$a$$$ (not necessarily consecutive) without changing the order of remaining elements. For example, $$$[2]$$$, $$$[1, 2, 1, 3]$$$ and $$$[2, 3]$$$ are subsequences of $$$[1, 2, 1, 3]$$$, but $$$[1, 1, 2]$$$ and $$$[4]$$$ are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array $$$a$$$ of length $$$n$$$ is the palindrome if $$$a_i = a_{n - i - 1}$$$ for all $$$i$$$ from $$$1$$$ to $$$n$$$. For example, arrays $$$[1234]$$$, $$$[1, 2, 1]$$$, $$$[1, 3, 2, 2, 3, 1]$$$ and $$$[10, 100, 10]$$$ are palindromes, but arrays $$$[1, 2]$$$ and $$$[1, 2, 3, 1]$$$ are not.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 5000$$$) — the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5000$$$ ($$$\sum n \le 5000$$$).

For each test case, print the answer — "YES" (without quotes) if $$$a$$$ has some subsequence of length at least $$$3$$$ that is a palindrome and "NO" otherwise.

NoteIn the first test case of the example, the array $$$a$$$ has a subsequence $$$[1, 2, 1]$$$ which is a palindrome.In the second test case of the example, the array $$$a$$$ has two subsequences of length $$$3$$$ which are palindromes: $$$[2, 3, 2]$$$ and $$$[2, 2, 2]$$$.In the third test case of the example, the array $$$a$$$ has no subsequences of length at least $$$3$$$ which are palindromes.In the fourth test case of the example, the array $$$a$$$ has one subsequence of length $$$4$$$ which is a palindrome: $$$[1, 2, 2, 1]$$$ (and has two subsequences of length $$$3$$$ which are palindromes: both are $$$[1, 2, 1]$$$).In the fifth test case of the example, the array $$$a$$$ has no subsequences of length at least $$$3$$$ which are palindromes.

# coding: utf-8

# if __FILE__ == $0
# end

t = gets.to_i
t.times {
    n = gets.to_i
    mc = {}
    gets.chomp.split.each_with_index { |value, index|
        i = value.to_i
        mc[i] ||= []
        mc[i] << index
    }
    # p mc
    found = false
    catch :found do
        for k, v in mc
            if v.length >= 2
                if v.last - v.first > 1 # 모든 간격을 검사할 필요는 없지. at least니까.
                    found = true
                    throw :found
                end
            end
        end
    end

    if found == true
        puts "YES"
    else
        puts "NO"
    end

}

tc = gets.to_i

tc.times do
    n = gets.to_i
    arr = gets.split().map{|x| x.to_i}
    mark = Array.new(5001) {0}
    mark1 = Array.new(5001) {-1}
    ans = false
    (0...n).each do |x|
        cur = arr[x]
        if(mark[cur] == 0)
            mark1[cur] = x
        end
        mark[cur] += 1
        if(mark[cur] > 1)
            if(mark1[cur]+1 < x)
                ans = true
                break
            end
        end
    end
    # print(mark[1])
    if(ans)
        puts ("YES")
    else
        puts ("NO")
    end
end

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  ok = false
  for i in 0...(n-2) do
    for j in (i+2)...n do
      ok = true if a[i] == a[j]
    end
  end
  puts ok ? "YES" : "NO"
end

t = gets.chomp.to_i
(0...t).each do |_|
  n = gets.chomp.to_i
  l = gets.chomp.split.map(&:to_i)
  seq_palidrom_exists = false
  (0...n).each{|i| seq_palidrom_exists = true if (l.rindex(l[i]) - i) > 1}
  puts seq_palidrom_exists ? "YES" : "NO"
end

# coding: utf-8

# if __FILE__ == $0
# end

t = gets.to_i
t.times {
    n = gets.to_i
    mc = {}
    gets.chomp.split.each_with_index { |value, index|
        i = value.to_i
        mc[i] ||= []
        mc[i] << index
    }
    # p mc
    found = false
    catch :found do
        for k, v in mc
            if v.length >= 2
                for i in 0...(v.length - 1)
                    if v[i+1] - v[i] > 1
                        found = true
                        throw :found
                    end
                end
            end
        end
    end

    if found == true
        puts "YES"
    else
        puts "NO"
    end

}

tc = gets.to_i

tc.times do
    n = gets.to_i
    arr = gets.split().map{|x| x.to_i}
    mark = Array.new(5001) {0}
    ans = false
    (0...n).each do |x|
        mark[arr[x]] += 1
        if(mark[arr[x]] > 1)
            if(arr[x] != arr[x-1])
                ans = true
                break
            end
        end
    end
    if(ans)
        puts ("YES")
    else
        puts ("NO")
    end
end

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  ok = false
  for i in 0...(n-2) do
    ok = true if a[i] == a[i+2]
  end
  for i in 0...(n-3) do
    ok = true if a[i] == a[i+3] && a[i+1] == a[i+2]
  end
  puts ok ? "YES" : "NO"
end


Recently, Tokitsukaze found an interesting game. Tokitsukaze had $$$n$$$ items at the beginning of this game. However, she thought there were too many items, so now she wants to discard $$$m$$$ ($$$1 \le m \le n$$$) special items of them.These $$$n$$$ items are marked with indices from $$$1$$$ to $$$n$$$. In the beginning, the item with index $$$i$$$ is placed on the $$$i$$$-th position. Items are divided into several pages orderly, such that each page contains exactly $$$k$$$ positions and the last positions on the last page may be left empty.Tokitsukaze would do the following operation: focus on the first special page that contains at least one special item, and at one time, Tokitsukaze would discard all special items on this page. After an item is discarded or moved, its old position would be empty, and then the item below it, if exists, would move up to this empty position. The movement may bring many items forward and even into previous pages, so Tokitsukaze would keep waiting until all the items stop moving, and then do the operation (i.e. check the special page and discard the special items) repeatedly until there is no item need to be discarded.    Consider the first example from the statement: $$$n=10$$$, $$$m=4$$$, $$$k=5$$$, $$$p=[3, 5, 7, 10]$$$. The are two pages. Initially, the first page is special (since it is the first page containing a special item). So Tokitsukaze discards the special items with indices $$$3$$$ and $$$5$$$. After, the first page remains to be special. It contains $$$[1, 2, 4, 6, 7]$$$, Tokitsukaze discards the special item with index $$$7$$$. After, the second page is special (since it is the first page containing a special item). It contains $$$[9, 10]$$$, Tokitsukaze discards the special item with index $$$10$$$. Tokitsukaze wants to know the number of operations she would do in total.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 10^{18}$$$, $$$1 \le m \le 10^5$$$, $$$1 \le m, k \le n$$$) — the number of items, the number of special items to be discarded and the number of positions in each page. The second line contains $$$m$$$ distinct integers $$$p_1, p_2, \ldots, p_m$$$ ($$$1 \le p_1 < p_2 < \ldots < p_m \le n$$$) — the indices of special items which should be discarded.

Print a single integer — the number of operations that Tokitsukaze would do in total.

NoteFor the first example:  In the first operation, Tokitsukaze would focus on the first page $$$[1, 2, 3, 4, 5]$$$ and discard items with indices $$$3$$$ and $$$5$$$;  In the second operation, Tokitsukaze would focus on the first page $$$[1, 2, 4, 6, 7]$$$ and discard item with index $$$7$$$;  In the third operation, Tokitsukaze would focus on the second page $$$[9, 10]$$$ and discard item with index $$$10$$$. For the second example, Tokitsukaze would focus on the second page $$$[6, 7, 8, 9, 10]$$$ and discard all special items at once.

n,m,k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
ans = 0
i = 0
while i < m
  #p i
  l = (a[i]-i-1) % k + 1
  r = a[i] + k- l
  while i < m && a[i] <= r
     i += 1
  end
  #p [l,r]
  ans += 1
end
p ans

N, M, K = gets.split.map(&:to_i)
P = gets.split.map(&:to_i)

l, r = 1, K
count, answer = 0, 0
m = 0
while m < M
	count = m
	while P[m] && P[m] <= r
		m += 1
	end
	count = m - count
	if count > 0
		answer += 1
		r += count
	elsif P[m]
		pages = ( (P[m] - r) / K.to_r ).ceil
		r += pages * K
#		l += pages * K
	end
#	puts count
end
puts answer

N, M, K = gets.split.map(&:to_i)
P = gets.split.map(&:to_i)

count, answer = 0, 0
m = 0
while m < M
	r = ( (P[m] - m) / K.to_r ).ceil * K
	count = m
	while P[m] && (P[m] - count) <= r
		m += 1
	end
	count = m - count
	if count > 0
		answer += 1
	end
#	puts count
end
puts answer

N, M, K = gets.split.map(&:to_i)
P = gets.split.map(&:to_i)

l, r = 1, K
count, answer = 0, 0
m = 0
while m < M
	count = m
	while P[m] && P[m] <= r
		m += 1
	end
	count = m - count
	if count > 0
		answer += 1
		r += count
	elsif P[m]
		pages = ( (P[m] - r) / K.to_r ).ceil
		r += pages * K
		l += pages * K
	end
#	puts count
end
puts answer

N, M, K = gets.split.map(&:to_i)
P = gets.split.map(&:to_i)

count, answer = 0, 0
m = 0
while m < M
	r = ( (P[m] - count) / K.to_r ).ceil * K
	while P[m] && (P[m] - count) <= r
		m += 1
	end
	count = m
	answer += 1
#	puts count
end
puts answer


Suppose you have two points $$$p = (x_p, y_p)$$$ and $$$q = (x_q, y_q)$$$. Let's denote the Manhattan distance between them as $$$d(p, q) = |x_p - x_q| + |y_p - y_q|$$$.Let's say that three points $$$p$$$, $$$q$$$, $$$r$$$ form a bad triple if $$$d(p, r) = d(p, q) + d(q, r)$$$.Let's say that an array $$$b_1, b_2, \dots, b_m$$$ is good if it is impossible to choose three distinct indices $$$i$$$, $$$j$$$, $$$k$$$ such that the points $$$(b_i, i)$$$, $$$(b_j, j)$$$ and $$$(b_k, k)$$$ form a bad triple.You are given an array $$$a_1, a_2, \dots, a_n$$$. Calculate the number of good subarrays of $$$a$$$. A subarray of the array $$$a$$$ is the array $$$a_l, a_{l + 1}, \dots, a_r$$$ for some $$$1 \le l \le r \le n$$$.Note that, according to the definition, subarrays of length $$$1$$$ and $$$2$$$ are good.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print the number of good subarrays of array $$$a$$$.

def ok?(arr)
  for j in 1...(arr.size) do
    for k in (j+1)...(arr.size) do
      return false if (arr[0] -arr[j]) *  (arr[j] - arr[k]) >= 0
    end
  end
  true
end

t = gets.chomp.to_i

t.times do
  n = gets.chomp.to_i
  arr = gets.chomp.split(' ').map(&:to_i)
  d = Array.new(n+1) { 0 }

  for i in 1..n do
    d[i] = d[i-1]
    ptr = 0
    while i - ptr > 0 do
      if ok?(arr[(i-ptr-1)...i])
        d[i] += 1
        ptr += 1
      else
        break
      end
    end
  end

  puts "#{d[n]}\n"
end

def ok?(arr)
  for j in 1...(arr.size) do
    for k in (j+1)...(arr.size) do
      return false if (arr[0] -arr[j]) *  (arr[j] - arr[k]) >= 0
    end
  end
  true
end

t = gets.chomp.to_i

t.times do
  n = gets.chomp.to_i
  arr = gets.chomp.split(' ').map(&:to_i)
  d = Array.new(n+1) { 0 }

  for i in 1..n do
    d[i] = d[i-1]
    ptr = 0
    while i - ptr > 0 do
      d[i] += 1 if ok?(arr[(i-ptr-1)...i])
      ptr += 1
    end
  end

  puts "#{d[n]}\n"
end


YouKn0wWho has an integer sequence $$$a_1, a_2, \ldots a_n$$$. Now he will split the sequence $$$a$$$ into one or more consecutive subarrays so that each element of $$$a$$$ belongs to exactly one subarray. Let $$$k$$$ be the number of resulting subarrays, and $$$h_1, h_2, \ldots, h_k$$$ be the lengths of the longest increasing subsequences of corresponding subarrays.For example, if we split $$$[2, 5, 3, 1, 4, 3, 2, 2, 5, 1]$$$ into $$$[2, 5, 3, 1, 4]$$$, $$$[3, 2, 2, 5]$$$, $$$[1]$$$, then $$$h = [3, 2, 1]$$$.YouKn0wWho wonders if it is possible to split the sequence $$$a$$$ in such a way that the bitwise XOR of $$$h_1, h_2, \ldots, h_k$$$ is equal to $$$0$$$. You have to tell whether it is possible.The longest increasing subsequence (LIS) of a sequence $$$b_1, b_2, \ldots, b_m$$$ is the longest sequence of valid indices $$$i_1, i_2, \ldots, i_k$$$ such that $$$i_1 \lt i_2 \lt \ldots \lt i_k$$$ and $$$b_{i_1} \lt b_{i_2} \lt \ldots \lt b_{i_k}$$$. For example, the LIS of $$$[2, 5, 3, 3, 5]$$$ is $$$[2, 3, 5]$$$, which has length $$$3$$$.An array $$$c$$$ is a subarray of an array $$$b$$$ if $$$c$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$)  — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 \cdot 10^5$$$.

For each test case, print "YES" (without quotes) if it is possible to split into subarrays in the desired way, print "NO" (without quotes) otherwise. You can print each letter in any register (upper or lower).

NoteIn the first test case, YouKn0wWho can split the sequence in the following way: $$$[1, 3, 4]$$$, $$$[2, 2]$$$, $$$[1, 5]$$$. This way, the LIS lengths are $$$h = [3, 1, 2]$$$, and the bitwise XOR of the LIS lengths is $$$3 \oplus 1 \oplus 2 = 0$$$.In the second test case, it can be shown that it is impossible to split the sequence into subarrays that will satisfy the condition.

gets.to_i.times do
  gets
  xs = gets.split.map(&:to_i)
  puts xs.size.even? || xs.each_cons(2).any? { |a, b| a >= b } ? "YES" : "NO"
end


A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from $$$1$$$ to $$$9$$$ (inclusive) are round.For example, the following numbers are round: $$$4000$$$, $$$1$$$, $$$9$$$, $$$800$$$, $$$90$$$. The following numbers are not round: $$$110$$$, $$$707$$$, $$$222$$$, $$$1001$$$.You are given a positive integer $$$n$$$ ($$$1 \le n \le 10^4$$$). Represent the number $$$n$$$ as a sum of round numbers using the minimum number of summands (addends). In other words, you need to represent the given number $$$n$$$ as a sum of the least number of terms, each of which is a round number.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is a line containing an integer $$$n$$$ ($$$1 \le n \le 10^4$$$).

Print $$$t$$$ answers to the test cases. Each answer must begin with an integer $$$k$$$ — the minimum number of summands. Next, $$$k$$$ terms must follow, each of which is a round number, and their sum is $$$n$$$. The terms can be printed in any order. If there are several answers, print any of them.

t = gets.to_i
t.times do
  n = gets.to_i
  res = []
  [10_000, 1_000, 100, 10, 1].each do |d|
    if (i = n / d) != 0
      res << i * d
      n -= res.last
    end
  end
  puts res.size
  puts res.join(' ')
end

t = gets.to_i
t.times do
  n = gets.chomp
  ans = []
  m = n.size
  m.times do |i|
    if n[i] != "0"
      ans << n[i].to_i * 10 ** (m-i-1)
    end
  end
  p ans.size
  puts ans.join(" ")
end

t = gets.to_i
(1).upto(t) do
  x = gets
  x = x.strip.split('')
  arr = []
  i = x.length-1
  x.each do |c|
    if(c!='0')
      arr.push([c,i])
    end
    i-=1
  end
  puts arr.length
  arr.each do |v|
    print v[0]
    (1..v[1]).each do
      print 0
    end
    print ' '
  end
  puts
end

# Approach
# mod = 10
#
# r = n % mod
# n = n - r
t = gets.to_i
for i in 1..t do
  n = gets.to_i
  mod = 10
  rnds = []
  while n*10 >= mod
    r = n % mod
    if r != 0
      rnds << r
      n = n - r
    end
    mod = mod * 10
  end
  puts rnds.size
  puts rnds.join(' ')
end

t = gets.to_i

1.upto t do
  count = 0
  mul = 1
  val = []
  k = gets.chomp
  array = k.each_char.map {|num| num.to_i}
  for i in array.reverse
    if i != 0
      val.push(i * mul)
    else
      mul *= 10
      next
    end
    mul *= 10
    count += 1
  end
  puts count
  puts val.join(" ")
end

gets.to_i.times{
    s=gets.chomp
    n=s.size
    res=[]
    n.downto(1){|i|
        if s[i-1]!=?0
            res<<s[i-1..-1]
            s[i-1]=?0
        end
    }
    puts [res.size, res.reverse*' ']
}

def is_round(n)
  length = n.to_s.size

  if length == 1
    puts '1'
    puts n
    return
  end

  k = 0
  summands = []

  while length > 1
    term = (10 ** (length - 1))
    m = n / term
    summands << (m * term)

    n = n % term
    length = n.to_s.size
    k += 1
  end

  if n > 0
    summands << n
    k += 1
  end

  puts k
  puts summands.join(' ')
end

if ENV['LOCAL_PROJECT']
  input = File.exist?('in.in') ? File.new('in.in','r') : STDIN
else
  input = STDIN
end

t = input.gets.chomp.to_i

t.times do
  n = input.gets.chomp.to_i
  is_round(n)
end

class Fixnum
  def digits
    d = []
    t = self
    while t > 0
      d << t%10
      t /= 10
    end
    d
  end
end

module Enumerable
  alias filter select
end

gets.to_i.times do
  n = gets.to_i
  puts n.digits.filter{|x| x > 0}.size
  n.digits.each_with_index{|x, i| print x*10**i, ' ' if x > 0}
  puts
end

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

  res = s.reverse.chars.each_with_object([]).with_index do |(char, result), idx|
    result << char + '0' * idx unless char == '0'
  end

  puts res.size
  puts res.join(' ')
end

n = gets.chomp.to_i

nums = []

n.times do
  nums.push(gets.chomp.to_i)
end

nums.each_with_index do |num|
  nums_to_send = []
  num.to_s.reverse!.each_char.with_index do |digit, index|
    nums_to_send.push(digit.to_i * 10 ** index)
  end
  filtered_arr = nums_to_send.filter {|e| e != 0 }
  p filtered_arr.length
  puts filtered_arr.join(' ')
end

# Approach
# mod = 10
#
# r = n % mod
# n = n - r
t = gets.to_i
for i in 1..t do
  n = gets.to_i
  mod = 10
  rnds = []
  while n >= mod
    r = n % mod
    rnds << r
    n = n - r
    mod = mod * 10
  end
  puts rnds.size
  puts rnds.join(' ')
end


Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk).Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them.

The first line contains integer n (1 ≤ n ≤ 2·109) — the number of the game's rounds. The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 ≤ m, k ≤ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper.

Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have.

NoteIn the first sample the game went like this:  R - R. Draw.  P - S. Nikephoros loses.  S - P. Polycarpus loses.  R - P. Nikephoros loses.  P - R. Polycarpus loses.  S - S. Draw.  R - P. Nikephoros loses. Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2.

def gcd(a, b)
  return a if b == 0
  return gcd(b, a%b)
end

def lcm(a, b)
  return (a/gcd(a, b))*b
end

n = gets.to_i
a = gets.strip
b = gets.strip
m = a.length
k = b.length
x = lcm(m, k)

a *= x/m
b *= x/k

dota = Array.new
dotb = Array.new

dota[0] = 0
dotb[0] = 0

for i in 1..x
  case a[i-1]
    when "R"; c=1
    when "P"; c=2
    when "S"; c=3
  end
  case b[i-1]
    when "R"; c-=1
    when "P"; c-=2
    when "S"; c-=3
  end
  dota[i] = dota[i-1]
  dotb[i] = dotb[i-1]
  case c
    when 1; dotb[i] += 1
    when 2; dota[i] += 1
    when -1; dota[i] += 1
    when -2; dotb[i] += 1
  end
end

print dota[x]*(n/x) + dota[n%x], " ", dotb[x]*(n/x) + dotb[n%x]

def gcd(a, b)
  until b == 0
    temp = a%b
    a = b
    b = temp
  end
  return a
end

def lcm(a, b)
  return (a/gcd(a, b))*b
end

n = gets.to_i
a = gets.strip
b = gets.strip
m = a.length
k = b.length
x = lcm(m, k)

a *= x/m
b *= x/k

dota = Array.new
dotb = Array.new

dota[0] = 0
dotb[0] = 0

for i in 1..x
  case a[i-1]
    when "R"; c=1
    when "P"; c=2
    when "S"; c=3
  end
  case b[i-1]
    when "R"; c-=1
    when "P"; c-=2
    when "S"; c-=3
  end
  dota[i] = dota[i-1]
  dotb[i] = dotb[i-1]
  case c
    when 1; dotb[i] += 1
    when 2; dota[i] += 1
    when -1; dota[i] += 1
    when -2; dotb[i] += 1
  end
end

print dota[x]*(n/x) + dota[n%x], " ", dotb[x]*(n/x) + dotb[n%x]

n = gets.to_i
s1 = gets.chomp
s2 = gets.chomp
n1 = s1.size
n2 = s2.size
T = n1*n2
D = n%T
N = n/T
sum1 = 0
sum2 = 0
sumd1 = 0
sumd2 = 0
#Символ «R» (от английского rock) означает знак камня, символ «S» (scissors) — ножниц, «P» (paper) — бумаги.
0.upto(T-1) do |i|
  c1 = s1[i%n1]
  c2 = s2[i%n2]
  if c1 == 'R' && c2 == 'S' || c1 == 'S' && c2 == 'P' || c1 == 'P' && c2 == 'R'
    sum1 += 1
    sumd1 += 1 if i < D
  end
  c1,c2=c2,c1
  if c1 == 'R' && c2 == 'S' || c1 == 'S' && c2 == 'P' || c1 == 'P' && c2 == 'R'
    sum2 += 1
    sumd2 += 1 if i < D
  end
end
sum1 = sum1 * N + sumd1
sum2 = sum2 * N + sumd2
printf("#{sum2} #{sum1}")

n=gets.to_i
R,P,S=82,80,83
a,b=2.times.map{gets.chomp.each_byte.to_a}
as=bs=ar=br=0
lcm=a.size.lcm b.size
q,r=n.divmod lcm
lcm.times{|i|
	ar,br=as,bs if i==r
	_a=a[i%a.size]
	_b=b[i%b.size]
	next if _a==_b
	as+=1 if (_a==R&&_b==P)||(_a==P&&_b==S)||(_a==S&&_b==R)
	bs+=1 if (_b==R&&_a==P)||(_b==P&&_a==S)||(_b==S&&_a==R)
}
puts"%d %d"%[as*q+ar,bs*q+br]


Team Red and Team Blue competed in a competitive FPS. Their match was streamed around the world. They played a series of $$$n$$$ matches.In the end, it turned out Team Red won $$$r$$$ times and Team Blue won $$$b$$$ times. Team Blue was less skilled than Team Red, so $$$b$$$ was strictly less than $$$r$$$.You missed the stream since you overslept, but you think that the match must have been neck and neck since so many people watched it. So you imagine a string of length $$$n$$$ where the $$$i$$$-th character denotes who won the $$$i$$$-th match  — it is R if Team Red won or B if Team Blue won. You imagine the string was such that the maximum number of times a team won in a row was as small as possible. For example, in the series of matches RBBRRRB, Team Red won $$$3$$$ times in a row, which is the maximum.You must find a string satisfying the above conditions. If there are multiple answers, print any.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$)  — the number of test cases. Each test case has a single line containing three integers $$$n$$$, $$$r$$$, and $$$b$$$ ($$$3 \leq n \leq 100$$$; $$$1 \leq b < r \leq n$$$, $$$r+b=n$$$).

For each test case, output a single line containing a string satisfying the given conditions. If there are multiple answers, print any.

RBR
RRBRBRBRBR
RBRBRBRBRBR
RRRRRBRRRR
RRRBRRRBRR
RRRBRRRBRRR

NoteThe first test case of the first example gives the optimal answer for the example in the statement. The maximum number of times a team wins in a row in RBRBRBR is $$$1$$$. We cannot minimize it any further.The answer for the second test case of the second example is RRBRBRBRBR. The maximum number of times a team wins in a row is $$$2$$$, given by RR at the beginning. We cannot minimize the answer any further.

def solve(n, r, b)
  # b is strictly less than r, which means we can divide n into b + 1 sections
  # extra rs go into r % (b + 1)
  num_sections = b + 1
  len_r = r / num_sections
  extra = r % num_sections
  ans = 'R' * len_r
  b.times do
    ans.concat('B').concat('R' * len_r)
    if extra > 0
      ans.concat('R')
      extra -= 1
    end
  end
  ans
end

tests = gets.to_i
tests.times do
  n, r, b = gets.chomp.split(' ').map(&:to_i)
  puts solve(n, r, b)
end

def solve(n, r, b)
  # b is strictly less than r, which means we can divide n into b + 1 sections
  # extra rs go into r % (b + 1)
  num_sections = b + 1
  len_r = r / num_sections
  extra = r % num_sections
  ans = ''
  b.times do
    ans.concat('R' * len_r).concat('B')
    if extra > 0
      ans.concat('R')
      extra -= 1
    end
  end
  ans
end

tests = gets.to_i
tests.times do
  n, r, b = gets.chomp.split(' ').map(&:to_i)
  puts solve(n, r, b)
end


Permutation p is an ordered set of integers p1,   p2,   ...,   pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,   p2,   ...,   pn.Your task is to find such permutation p of length n, that the group of numbers |p1 - p2|, |p2 - p3|, ..., |pn - 1 - pn| has exactly k distinct elements.

The single line of the input contains two space-separated positive integers n, k (1 ≤ k < n ≤ 105).

Print n integers forming the permutation. If there are multiple answers, print any of them.

NoteBy |x| we denote the absolute value of number x.

n, k = gets.split.map { |i| i.to_i }
ans = []
if k == n - 1
  for i in 0...n
    print i % 2 == 0 ? i / 2 + 1 : n - i / 2
    print ' '
  end
  exit(0)
end
for i in 0...k / 2
  ans.push i, n - i - 1
end
for i in k / 2...n - k / 2
  ans.push i
end
if k % 2 == 0
  ans[0], ans[1] = ans[1], ans[0]
end
for x in ans
  print (x + 1).to_s + ' '
end

n, k = gets.split.map &:to_i

sw = 0
h  = n
l  = 1

(k - 1).times do
    if sw == 0
        print "#{h} "
        h -= 1
    else
        print "#{l} "
        l += 1
    end
    sw = 1 - sw
end

if sw == 1
    l.upto(h) { |i| print "#{i} " }
else
    h.downto(l) { |i| print "#{i} " }
end

puts


One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.

The first input line contains two integers n and k (1 ≤ k ≤ n ≤ 103) — the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1 ≤ ci ≤ 109) is an integer denoting the price of the i-th item, ti (1 ≤ ti ≤ 2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.

In the first line print a single real number with exactly one  decimal place — the minimum total price of the items, including the discounts. In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1, b2, ..., bt (1 ≤ bj ≤ n) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.

NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2·0.5 + (3 + 3·0.5) = 1 + 4.5 = 5.5.

n,k = gets.split.map(&:to_i)
stool = []
pencil = []
sum = 0
n.times do |i|
  c,t=gets.split.map(&:to_i)
  sum += c
  if t==1
    stool.push([c,i,0])
  else
    pencil.push([c,i,1])
  end
end
stool.sort!
stool.reverse!
cart = Array.new(k){Array.new()}
cnt = [stool.length, k-1].min

cnt.times do |i|
  cart[i] = Array.new
  cart[i].push(stool[i])
end
# 残りを余りに詰める
now = cnt
while cnt < stool.size()
  cart[now].push(stool[cnt])
  cnt += 1
  now += 1
  if now >= cart.size()
    now = cart.size()-1
  end
end
cnt = 0
while cnt < pencil.size()
  cart[now].push(pencil[cnt])
  cnt += 1
  now += 1
  if now >= cart.size()
    now = cart.size()-1
  end
end

sum = 0
k.times{|i|
  cart[i].sort!
  has_stool = false
  cart[i].each{|t|
    sum += t[0]*2
    has_stool = true if t[2] == 0
  }
  if has_stool
    sum -= cart[i][0][0]
  end
}
print sum/2
print "."
if sum%2 == 1
  puts "5"
else
  puts "0"
end

k.times{|i|
  print cart[i].size()
  cart[i].each{|t|
    print " "
    print t[1]+1
  }
  puts
}

n, k = gets.split.collect{|i| i.to_i}
carts = Array.new(k) {[]}
items = Array.new(n) {gets.split.collect{|i| i.to_i}}
items.each_index{|i|
  items[i] = [i+1, items[i][0], items[i][1]]
}

items = items.sort{|a,b| b[1] <=> a[1]}
stools  = items.select{|x| x[2] == 1}
pencils = items.select{|x| x[2] == 2}

curr_k = 0
price = 0
stools.each{|s|
   carts[curr_k] << s
   curr_k += 1 if curr_k < k - 1
}

pencils.each{|p|
  carts[curr_k] << p
  curr_k += 1 if curr_k < k - 1
}

carts.each{|c|
  has_stool = c[0][2] == 1
  cart_items = c.sort{|a,b| a[1] <=> b[1]}
  cart_items.each{|item|
     price += item[1]
  }
  price -= cart_items[0][1] * 0.5 if has_stool
}

puts "%.1f" % price
carts.each{|c|
  c = c.flatten
  idxs = 0.step(c.size - 1, 3).map{|i| c[i]}
  puts [idxs.size, idxs].join(" ")
}

n, k = gets.split.collect{|i| i.to_i}
carts = Array.new(k) {[]}
items = Array.new(n) {gets.split.collect{|i| i.to_i}}
items.each_index{|i|
  items[i] = [i+1, items[i][0], items[i][1]]
}

items.sort{|a,b| a[1] <=> b[1]}
stools  = items.select{|x| x[2] == 1}
pencils = items.select{|x| x[2] == 2}

curr_k = 0
price = 0
stools.each{|s|
   carts[curr_k] << s
   curr_k += 1 if curr_k < k - 1
}

pencils.each{|p|
  carts[curr_k] << p
  curr_k += 1 if curr_k < k - 1
}

carts.each{|c|
  has_stool = c[0][2] == 1
  cart_items = c.sort{|a,b| a[1] <=> b[1]}
  cart_items.each{|item|
     price += item[1]
  }
  price -= cart_items[-1][1] * 0.5 if has_stool
}

puts "%.1f" % price
carts.each{|c|
  c = c.flatten
  idxs = 0.step(c.size - 1, 3).map{|i| c[i]}
  puts [idxs.size, idxs].join(" ")
}

n, k = gets.split.collect{|i| i.to_i}
carts = Array.new(k) {[]}
items = Array.new(n) {gets.split.collect{|i| i.to_i}}
items.each_index{|i|
  items[i] = [i+1, items[i][0], items[i][1]]
}

items.sort{|a,b| a[1] <=> b[1]}
stools  = items.select{|x| x[2] == 1}
pencils = items.select{|x| x[2] == 2}

curr_k = 0
price = 0
stools.each{|s|
   carts[curr_k] << s
   curr_k += 1 if curr_k < k - 1
}

pencils.each{|p|
  carts[curr_k] << p
  curr_k += 1 if curr_k < k - 1
}

carts.each{|c|
  has_stool = c[0][2] == 1
  cart_items = c.sort{|a,b| a[1] <=> b[1]}
  cart_items.each{|item|
     price += item[1]
  }
  price -= cart_items[0][1] * 0.5 if has_stool
}

puts "%.1f" % price
carts.each{|c|
  c = c.flatten
  idxs = 0.step(c.size - 1, 3).map{|i| c[i]}
  puts [idxs.size, idxs].join(" ")
}


In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills. Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration. Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life. As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the k coefficient (if the skill level was equal to x, then after transmigration it becomes equal to [kx], where [y] is the integral part of y). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0. Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible. You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be?

The first line contains three numbers n, m and k — the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; n and m are integers, and k is a real number with exactly two digits after decimal point (1 ≤ n, m ≤ 20, 0.01 ≤ k ≤ 0.99). Then follow n lines, each of which describes a character's skill in the form "name exp" — the skill's name and the character's skill level: name is a string and exp is an integer in range from 0 to 9999, inclusive.  Then follow m lines each of which contains names of skills specific for the class, into which the character transmigrates.  All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names.

Print on the first line number z — the number of skills the character will have after the transmigration. Then print z lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order.

5 4 0.75
axe 350
impaler 300
ionize 80
megafire 120
magicboost 220
heal
megafire
shield
magicboost

6
axe 262
heal 0
impaler 225
magicboost 165
megafire 0
shield 0

input=gets.split
n,m=input[0..1].map(&:to_i)
k=(input[2].to_f*100+1e-8).to_i
res={}
res.default=0
n.times{
        input=gets.split
        input[1]=(input[1].to_i*k/100).to_i
        if input[1]>=100 then
                res.store(input[0],input[1])
        end
}
m.times{
        input=gets.split[0]
        res[input]+=0
}
puts res.length
res.sort.each do|k, v|
        puts "#{k} #{v}"
end

params = gets.split(" ").collect {|v| v.to_f}
old_skill = Hash::new
params[0].to_i.times do
    old_list = gets.split(" ")
    old_skill[old_list[0]] = old_list[1].to_i
end

new_skill  = Array::new
params[1].to_i.times do
    new_skill << gets.strip
end

skills = Hash::new
old_skill.each do |k,v|
    level = (v*params[2]+0.0001).to_i
    skills[k] = level unless level<100
end

new_skill.each do |v|
    skills[v] = 0 unless skills.key?(v)
end
skills = skills.to_a.sort

puts skills.size
skills.each do |v|
    print v[0], " ", v[1].to_i, "\n"
end

#!/usr/bin/ruby
# coding: utf-8
require 'scanf'
require 'bigdecimal'

n, m, k = gets.scanf '%d %d %s'
k = BigDecimal k

skills = {}
n.times do
  s, t = gets.scanf '%s %d'
  if t*k >= 100
    skills[s] = (t*k).to_i
  end
end

m.times do
  s = gets.chomp
  if not skills.has_key? s
    skills[s] = 0
  end
end

puts skills.size
puts skills.map { |k, v| "#{k} #{v}" }.sort

require 'scanf'
a = gets.scanf("%d %d %f")
n = a[0]
m = a[1]
k_100 = (a[2] * 100 + 0.5).to_i

h = Hash.new

n.times do
	a = gets.scanf("%s %d")
	if a[1] * k_100 >= 10000 then
		h[a[0]] = a[1] * k_100 / 100
	end
end

m.times do
	s = gets.chomp!
	if h[s].nil? then
		h[s] = 0
	end
end

ans = Array.new
h.each{|key, value|
	ans.push(sprintf("%s %d", key, value))
}

ans.sort!
puts ans.size
ans.each{|line|
	puts line
}

#!/usr/bin/env ruby

args = STDIN.gets.split(" ")
skill = []
args[0].to_i.times do
  skill << STDIN.gets.split(" ")
end

skillname = skill.map {|i| i[0]}

args[1].to_i.times do
  n = STDIN.gets.chomp
  if skillname.index(n)
    skill[skillname.index(n)][1] = "0" if (skill[skillname.index(n)][1].to_i*args[2].to_f*(1.0000001)).to_i < 100
  else
    skill << [n,"0"]
  end
end

skill.sort! {|a,b| a[0] <=> b[0]}
ret =[]
skill.each do |i|
  exp = (i[1].to_i*args[2].to_f*(1.0000001)).to_i
  ret << "#{i[0]} #{exp}" unless exp < 100 and i[1].to_i != 0
end

puts ret.size
ret.each do |s|
  puts s
end

input=gets.split
n,m=input[0..1].map(&:to_i)
k=(input[2].to_f*100).to_i
res={}
res.default=0
n.times{
        input=gets.split
        input[1]=(input[1].to_i*k/100).to_i
        if input[1]>=100 then
                res.store(input[0],input[1])
        end
}
m.times{
        input=gets.split[0]
        res[input]+=0
}
puts res.length
res.sort.each do|k, v|
        puts "#{k} #{v}"
end

input=gets.split
n,m=input[0..1].map(&:to_i)
k=input[2].to_f
res={}
res.default=0
n.times{
        input=gets.split
        input[1]=(input[1].to_i*k).to_i
        if input[1]>=100 then
                res.store(input[0],input[1])
        end
}
m.times{
        input=gets.split[0]
        res[input]+=0
}
res.sort.each do|k, v|
        puts "#{k} #{v}"
end

input=gets.split
n,m=input[0..1].map(&:to_i)
k=input[2].to_f
res={}
res.default=0
n.times{
        input=gets.split
        input[1]=(input[1].to_i*k).to_i
        if input[1]>=100 then
                res.store(input[0],input[1])
        end
}
m.times{
        input=gets.split[0]
        res[input]+=0
}
puts res.length
res.sort.each do|k, v|
        puts "#{k} #{v}"
end

params = gets.split(" ").collect {|v| v.to_f}
old_skill = Hash::new
params[0].to_i.times do
    old_list = gets.split(" ")
    old_skill[old_list[0]] = old_list[1].to_i
end

new_skill  = Array::new
params[1].to_i.times do
    new_skill << gets.strip
end

skills = Hash::new
old_skill.each do |k,v|
    level = (v*100*params[2]/100).to_s.to_i
    skills[k] = level unless level<100
end

new_skill.each do |v|
    skills[v] = 0 unless skills.key?(v)
end
skills = skills.to_a.sort

puts skills.size
skills.each do |v|
    print v[0], " ", v[1].to_i, "\n"
end

params = gets.split(" ").collect {|v| v.to_f}
old_skill = Hash::new
params[0].to_i.times do
    old_list = gets.split(" ")
    old_skill[old_list[0]] = old_list[1].to_i
end

new_skill  = Array::new
params[1].to_i.times do
    new_skill << gets.strip
end

skills = Hash::new
old_skill.each do |k,v|
    level = (v*100*params[2]/100).to_i
    skills[k] = level unless level<100
end

new_skill.each do |v|
    skills[v] = 0 unless skills.key?(v)
end
skills = skills.to_a.sort

puts skills.size
skills.each do |v|
    print v[0], " ", v[1].to_i, "\n"
end

params = gets.split(" ").collect {|v| v.to_f}
old_skill = Hash::new
params[0].to_i.times do
    old_list = gets.split(" ")
    old_skill[old_list[0]] = old_list[1].to_i
end

new_skill  = Array::new
params[1].to_i.times do
    new_skill << gets.strip
end

skills = Hash::new
old_skill.each do |k,v|
    level = (v*params[2]).to_i
    skills[k] = level unless level<100
end

new_skill.each do |v|
    skills[v] = 0 unless skills.key?(v)
end
skills = skills.to_a.sort

puts skills.size
skills.each do |v|
    print v[0], " ", v[1].to_i, "\n"
end

params = gets.split(" ").collect {|v| v.to_f}
old_skill = Hash::new
params[0].to_i.times do
    old_list = gets.split(" ")
    old_skill[old_list[0]] = old_list[1].to_i
end

new_skill  = Array::new
params[1].to_i.times do
    new_skill << gets.strip
end

skills = Hash::new
old_skill.each do |k,v|
    level = (v*params[2]).to_s.to_i
    skills[k] = level unless level<100
end

new_skill.each do |v|
    skills[v] = 0 unless skills.key?(v)
end
skills = skills.to_a.sort

puts skills.size
skills.each do |v|
    print v[0], " ", v[1].to_i, "\n"
end

params = gets.split(" ").collect {|v| v.to_f}
old_skill = Hash::new
params[0].to_i.times do
    old_list = gets.split(" ")
    old_skill[old_list[0]] = old_list[1].to_i
end

new_skill  = Array::new
params[1].to_i.times do
    new_skill << gets.strip
end

skills = Hash::new
old_skill.each do |k,v|
    skills[k] = v*params[2] unless v*params[2]<100
end

new_skill.each do |v|
    skills[v] = 0 unless skills.key?(v)
end
skills = skills.to_a.sort

puts skills.size
skills.each do |v|
    print v[0], " ", v[1].to_i, "\n"
end

params = gets.split(" ").collect {|v| v.to_f}
old_skill = Hash::new
params[0].to_i.times do
    old_list = gets.split(" ")
    old_skill[old_list[0]] = old_list[1].to_i
end

new_skill  = Array::new
params[1].to_i.times do
    new_skill << gets.strip
end

skills = Hash::new
old_skill.each do |k,v|
    level = (v*params[2]).to_s.to_f.to_i
    skills[k] = level unless level<100
end

new_skill.each do |v|
    skills[v] = 0 unless skills.key?(v)
end
skills = skills.to_a.sort

puts skills.size
skills.each do |v|
    print v[0], " ", v[1].to_i, "\n"
end

#!/usr/bin/env ruby

args = STDIN.gets.split(" ")
skill = []
args[0].to_i.times do
  skill << STDIN.gets.split(" ")
end

skillname = skill.map {|i| i[0]}

args[1].to_i.times do
  n = STDIN.gets.chomp
  if skillname.index(n)
    skill[skillname.index(n)][1] = "0" if skill[skillname.index(n)][1].to_i*args[2].to_f < 100
  else
    skill << [n,"0"]
  end
end

skill.sort! {|a,b| a[0] <=> b[0]}
ret =[]
skill.each do |i|
  exp = (i[1].to_i*args[2].to_f).to_i
  ret << "#{i[0]} #{exp}" unless exp < 100 and i[1].to_i != 0
end

puts ret.size
ret.each do |s|
  puts s
end


Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted — that is, one call connects exactly two people.

The first line contains integer n (1 ≤ n ≤ 103) — the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id1, id2, ..., idn (0 ≤ idi ≤ 109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise. Consider the secretaries indexed from 1 to n in some way.

Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.

NoteIn the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.In the second test sample the described situation is impossible as conferences aren't allowed.

hs = Hash.new 0
n = gets.to_i
gets.split(' ').map(&:to_i).map{|x| hs[x]+=1}
hs.delete(0)
hs.delete_if{|k,v| v<2}
if hs.any?{|k,v| v>2}
  puts -1
else
  puts hs.length
end

n = gets.to_i
arr = gets.split(" ").map(&:to_i)
kv = {}
arr.each do |e|
    if kv[e].nil? then
        kv[e] = 1
    else
        kv[e] = kv[e] + 1
    end
end
if kv.any? { |k,v| k>0 and v>2 } then
    puts -1
else
    puts kv.select { |k,v| k>0 and v==2 }.length
end

gets; res = 0; h = Hash.new(0)

gets.split.map.each{|i|
	next if (i == '0')

	if (h[i] == 2) then
		res = -1;
		break;
	end

	res += 1 if (h[i] == 1)
	h[i] += 1
}

p res

n = gets.to_i

t = true
wk = gets.split.map{|i| i.to_i}
asmas = {}
res = 0

n.times do |i|
    if wk[i] != 0
        if asmas[wk[i]] then
            asmas[wk[i]] += 1
            if asmas[wk[i]] == 2 then
                res +=1
            elsif asmas[wk[i]] > 2 then
                t = false
            end
        else
            asmas[wk[i]] = 1
        end
    end
end

if t then
    puts res
else
    puts "-1"
end

ids = Hash.new{0}
$stdin.each_line.to_a[1].split(" ").map(&:to_i).each do |id|
  next if id == 0
  ids[id] += 1
end

answer = 0

ids.each do |id, count|
  if count > 2
    answer = -1
    break
  end

  if count == 2
    answer += 1
  end
end

puts answer

num_calls = gets
calls = gets.split.collect {|i| i.to_i}
numbers = Hash.new(0)
calls.each do |call|
	numbers[call] += 1 unless call == 0
	if numbers[call] > 2
		puts "-1"
		exit
	end
end
puts numbers.values.count(2)

n = gets.chomp.to_i
h = {}
gets.chomp.split(' ').map {|x| if x.to_i!=0; h[x].nil? ? h[x] = 1 : h[x]+=1; end;}

v = h.values
if v.any? {|x| x > 2}
  puts -1
else
  puts v.count(2)
end

def main
  num = gets.chomp.to_i
  lines = gets.chomp.split(' ').map(&:to_i)
  return if num != lines.count

  line_count = {}

  lines.each do |line|
    next if line == 0

    if line_count.include?(line)
      line_count[line] += 1
      if line_count[line] >= 3
        puts '-1'
        return
      end
    else
      line_count[line] = 1
    end
  end

  total = 0
  line_count.each { |k,v| total += 1 if v == 2 }

  puts total
end

main

n = gets.to_i
a = gets.split.map{|x|x.to_i}
c = {}
c.default = 0
a.each do |x|
  c[x] += 1 if x != 0
end
err = false
ans = 0
c.values.each do |x|
  err = true if x > 2
  ans += 1   if x == 2
end
if err
  puts -1
else
  puts ans
end

class A
  def initialize
    n = $stdin.gets.chomp.to_i
    list = $stdin.gets.chomp.split(' ').map(&:to_i)
    @list = Hash.new(0)
    count = 0

    list.each do |num|
      @list[num] += 1 if num != 0
    end

    @list.each do |key, value|
      case value
      when 1
      when 2
        count += 1
      else
        puts -1
        exit
      end
    end

    puts count
  end
end

a = A.new

require 'set'
require 'rational'
require 'mathn'
include Math
$stdin = File.open("./input.txt", "r") if ENV["USER"] == "new"
# ====================================

gets
data = gets.split.map(&:to_i)
hash = Hash.new( 0 )

data.each do |value|
  hash[value]+=1
end

ans = 0
hash.to_a.each do |key, value|
  if value > 2 and key != 0 then
    ans = -1
    break
  end

  if value == 2 and key != 0 then
    ans+=1
  end
end

puts ans

length = $stdin.readline.to_i
ids = $stdin.readline.split(" ").map{|i| i.to_i}
raise "Input data error" if length != ids.size

counter = Hash.new(0)
ids.each{|id| counter[id]+=1}
counter.delete(0)
if counter.values.find_all{|v| v>2}.any?
	puts "-1"
else
	puts counter.values.find_all{|v| v==2}.size
end

n = gets.to_i
ids = gets.split.map(&:to_i).sort.take(n)

m = ids.reduce [-1, 0, 0] do |memo, id|
  next memo if id == 0
  if memo[0] == id
    if memo[1] > 1
      puts -1
      exit
    else
      [id, 2, memo[2] + 1]
    end
  else
    [id, 1, memo[2]]
  end
end

puts m[2]

number=Integer(gets.chomp)
str=gets.chomp
policarp=0;
flag=0;
list = Array.new
str=str.split
str.each do |c_hop|
    next if c_hop=='0'
    break if flag==1
    if list.find_all{|elem| elem==c_hop}.size == 1
        policarp=policarp+1
    elsif list.find_all{|elem| elem==c_hop}.size > 1
        flag=1;
    end
    list=list << c_hop;
 end
if flag==0
    puts policarp
else
    puts "-1"
end

begin
  ids = []
  conversations = {}
  count = 0

  n = gets.chomp

  ids = gets.chomp

  ids = ids.split(' ').map(&:to_i)

  if ids.size != n.to_i
    puts -1
    abort
  end

  ids.delete(0)

  ids.each { |id| conversations[id] ||= 0; conversations[id] += 1 }

  conversations.each { |key, value| if value > 2; puts -1; abort; end; count +=1 if value == 2  }

  puts count
rescue Exception

end

lines = ARGF.readlines

a = lines.last.split ' '
b = a.map(&:to_i).delete_if {|x| 0.eql?(x) }
b = b.uniq.map{|x| b.count(x)}
b << 0
puts (b.max > 2) ? -1 : b.count(2)

n = gets.to_i
a = gets.split(' ').map(&:to_i).reject(&:zero?).sort
b = a.uniq

if b.any? { |n| a.count(n) > 2 }
  puts -1
  exit 0
end

x = b.count do |n|
  a.count(n) == 2
end

puts x

gets.chomp # Skip the first line
id_counts = (gets.chomp.split.map { |x| x.to_i } - [0]).inject(Hash.new(0)) { |h, e| h[e] += 1; h }.values
puts(id_counts.any? { |c| c > 2 } ? -1 : id_counts.select { |c| c > 1 }.size)

at_exit do
  n = get_numbers_from_line[0]
  ids = get_numbers_from_line[0...n]
  count = 0
  ids.select{|x| x != 0}.group_by{|x| x}.each do |_, group|
    if group.length == 2
      count += 1
    elsif group.length > 2
      count = -1
      break
    end
  end
  puts count
end

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

hs = Hash.new 0
n = gets.to_i
gets.split(' ').map(&:to_i).map{|x| hs[x]+=1}
hs.delete_if{|k,v| v<2}
if hs.any?{|k,v| v>2}
  puts -1
else
  puts hs.length
end

n = gets.to_i
arr = gets.split(" ")
kv = {}
arr.each do |e|
    if kv[:"#{e}"].nil? then
        kv[:"#{e}"] = 1
    else
        kv[:"#{e}"] = kv[:"#{e}"] + 1
    end
end

if kv.any? { |k,v| v>2 } or kv.values.inject(&:+)>n then
    puts -1
else
    puts kv.select { |k,v| v==2 }.length
end

n = gets.to_i
arr = gets.split(" ").map(&:to_i)
kv = {}
arr.each do |e|
    if kv[e].nil? then
        kv[e] = 1
    else
        kv[e] = kv[e] + 1
    end
end
puts kv.inspect
if kv.any? { |k,v| k>0 and v>2 } then
    puts -1
else
    puts kv.select { |k,v| k>0 and v==2 }.length
end

n = gets
arr = gets.split(" ")
kv = {}
arr.each do |e|
    if kv[:"#{e}"].nil? then
        kv[:"#{e}"] = 1
    else
        kv[:"#{e}"] = kv[:"#{e}"] + 1
    end
end
if kv.any? { |k,v| v>2 } then
    puts -1
else
    puts kv.select { |k,v| v==2 }.length
end

n = gets.to_i

t = true
wk = gets.split.map{|i| i.to_i}
asmas = {}
res = 0

n.times do |i|
    if asmas[wk[i]] then
        asmas[wk[i]] += 1
        if asmas[wk[i]] == 2 then
            res +=1
        elsif asmas[wk[i]] > 2 then
            t = false
        end
    else
        asmas[wk[i]] = 1
    end
end

if t then
    puts res
else
    puts "-1"
end

ids = Hash.new{0}
$stdin.each_line.to_a[1].split(" ").map(&:to_i).each do |id|
  ids[id] += 1
end

answer = 0

ids.each do |id, count|
  if count > 2
    answer = -1
    break
  end

  if count == 2
    answer += 1
  end
end

puts answer

num_calls = gets
calls = gets.split.collect {|i| i.to_i}
numbers = Hash.new(0)
calls.each do |call|
	numbers[call] += 1
	if numbers[call] > 2
		puts "-1"
		exit
	end
end
puts numbers.values.count(2)

n = gets.chomp.to_i
h = {}
gets.chomp.split(' ').map {|x| x.to_i; h[x].nil? ? h[x] = 1 : h[x]+=1}

v = h.values
if v.any? {|x| x > 2}
  puts -1
else
  puts v.count(2)
end

n = gets.chomp.to_i
h = {}
gets.chomp.split(' ').map {|x| h[x].nil? ? h[x] = 1 : h[x]+=1}

v = h.values
if v.any? {|x| x > 2}
  puts -1
else
  puts v.count(2)
end

def main
  num = gets.chomp.to_i
  lines = gets.chomp.split(' ')
  return if num != lines.count

  line_count = {}

  lines.each do |line|
    next if line == 0

    if line_count.include?(line)
      line_count[line] += 1
      if line_count[line] >= 3
        puts '-1'
        return
      end
    else
      line_count[line] = 1
    end
  end

  total = 0
  line_count.each { |k,v| total += 1 if v == 2 }

  puts total
end

main

n = gets.to_i
a = gets.split.map{|x|x.to_i}
c = {}
c.default = 0
a.each do |x|
  c[x] += 1
end
err = false
ans = 0
c.values.each do |x|
  err = true if x > 2
  ans += 1   if x == 2
end
if err
  puts -1
else
  puts ans
end

class A
  def initialize
    n = $stdin.gets.chomp.to_i
    list = $stdin.gets.chomp.split(' ').map(&:to_i)
    @list = Hash.new(0)
    count = 0

    list.each do |num|
      @list[num] += 1
    end

    @list.each do |key, value|
      case value
      when 1
      when 2
        count += 1
      else
        puts -1
        exit
      end
    end

    puts count
  end
end

a = A.new

require 'set'
require 'rational'
require 'mathn'
include Math
$stdin = File.open("./input.txt", "r") if ENV["USER"] == "new"
# ====================================

gets
data = gets.split.map(&:to_i)
hash = Hash.new( 0 )

data.each do |value|
  hash[value]+=1
end

ans = 0
hash.to_a.each do |key, value|
  if value == 2 and key != 0 then
    ans+=1
  end
end

puts ans

require 'set'
require 'rational'
require 'mathn'
include Math
$stdin = File.open("./input.txt", "r") if ENV["USER"] == "new"
# ====================================

gets
data = gets.split.map(&:to_i)
hash = Hash.new( 0 )

data.each do |value|
  hash[value]+=1
end

ans = 0
hash.to_a.each do |key, value|
  next if value == 1 or key == 0

  if value%2 != 0 then
    ans = -1
    break
  end

  ans+=1
end

puts ans

require 'set'
require 'rational'
require 'mathn'
include Math
$stdin = File.open("./input.txt", "r") if ENV["USER"] == "new"
# ====================================

gets
data = gets.split.map(&:to_i)
hash = Hash.new( 0 )

data.each do |value|
  hash[value]+=1
end

ans = 0
hash.to_a.each do |key, value|
  next if value == 1

  if value%2 != 0 then
    ans = -1
    break
  end

  ans+=1
end

puts ans

length = $stdin.readline.to_i
ids = $stdin.readline.split(" ").map{|i| i.to_i}
raise "Input data error" if length != ids.size

counter = Hash.new(0)
ids.each{|id| counter[id]+=1}
if counter.values.find_all{|v| v>2}.any?
	puts "-1"
else
	puts counter.values.find_all{|v| v==2}.size
end

n = gets.to_i
ids = gets.split.map(&:to_i).sort

m = ids.reduce [-1, 0, 0] do |memo, id|
  if memo[0] == id
    if memo[1] > 1
      puts -1
      exit
    else
      [id, 2, memo[2] + 1]
    end
  else
    [id, 1, memo[2]]
  end
end

puts m[2]

number=Integer(gets.chomp)
str=gets.chomp
policarp=0;
flag=0;
list = Array.new
str=str.split
str.each do |c_hop|
	next if c_hop==0;
	if list.find_all{|elem| elem==c_hop}.size == 1
	    policarp=policarp+1
	elsif list.find_all{|elem| elem==c_hop}.size > 1
	    flag=1;
		break;
	end
	list=list << c_hop;
 end
if flag==0
    puts policarp
else
    puts "-1"
end

ids = []
conversations = {}
count = 0

n = gets.chomp

ids = gets.chomp

ids = ids.split(' ').map(&:to_i)

ids.delete(0)

ids.each { |id| conversations[id] ||= 0; conversations[id] += 1 }

conversations.each { |key, value| if value > 2; puts -1; abort; end; count +=1 if value > 0  }

puts count

gets.chomp # Skip the first line
id_counts = gets.chomp.split.map { |x| x.to_i }.inject(Hash.new(0)) { |h, e| h[e] += 1; h }.values
puts(id_counts.any? { |c| c > 2 } ? -1 : id_counts.select { |c| c > 1 }.size)


Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question.Suppose you are given a positive integer $$$a$$$. You want to choose some integer $$$b$$$ from $$$1$$$ to $$$a - 1$$$ inclusive in such a way that the greatest common divisor (GCD) of integers $$$a \oplus b$$$ and $$$a \> \& \> b$$$ is as large as possible. In other words, you'd like to compute the following function:$$$$$$f(a) = \max_{0 < b < a}{gcd(a \oplus b, a \> \& \> b)}.$$$$$$Here $$$\oplus$$$ denotes the bitwise XOR operation, and $$$\&$$$ denotes the bitwise AND operation.The greatest common divisor of two integers $$$x$$$ and $$$y$$$ is the largest integer $$$g$$$ such that both $$$x$$$ and $$$y$$$ are divided by $$$g$$$ without remainder.You are given $$$q$$$ integers $$$a_1, a_2, \ldots, a_q$$$. For each of these integers compute the largest possible value of the greatest common divisor (when $$$b$$$ is chosen optimally).

The first line contains an integer $$$q$$$ ($$$1 \le q \le 10^3$$$) — the number of integers you need to compute the answer for. After that $$$q$$$ integers are given, one per line: $$$a_1, a_2, \ldots, a_q$$$ ($$$2 \le a_i \le 2^{25} - 1$$$) — the integers you need to compute the answer for.

For each integer, print the answer in the same order as the integers are given in input.

NoteFor the first integer the optimal choice is $$$b = 1$$$, then $$$a \oplus b = 3$$$, $$$a \> \& \> b = 0$$$, and the greatest common divisor of $$$3$$$ and $$$0$$$ is $$$3$$$.For the second integer one optimal choice is $$$b = 2$$$, then $$$a \oplus b = 1$$$, $$$a \> \& \> b = 2$$$, and the greatest common divisor of $$$1$$$ and $$$2$$$ is $$$1$$$.For the third integer the optimal choice is $$$b = 2$$$, then $$$a \oplus b = 7$$$, $$$a \> \& \> b = 0$$$, and the greatest common divisor of $$$7$$$ and $$$0$$$ is $$$7$$$.


Vasya has a grid with $$$2$$$ rows and $$$n$$$ columns. He colours each cell red, green, or blue.Vasya is colourblind and can't distinguish green from blue. Determine if Vasya will consider the two rows of the grid to be coloured the same.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 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 \leq n \leq 100$$$) — the number of columns of the grid. The following two lines each contain a string consisting of $$$n$$$ characters, each of which is either R, G, or B, representing a red, green, or blue cell, respectively — the description of the grid.

For each test case, output "YES" if Vasya considers the grid's two rows to be identical, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

6

2

RG

RB

4

GRBG

GBGB

5

GGGGG

BBBBB

7

BBBBBBB

RRRRRRR

8

RGBRRGBR

RGGRRBGR

1

G

G

NoteIn the first test case, Vasya sees the second cell of each row as the same because the second cell of the first row is green and the second cell of the second row is blue, so he can't distinguish these two cells. The rest of the rows are equal in colour. Therefore, Vasya will say that the two rows are coloured the same, even though they aren't.In the second test case, Vasya can see that the two rows are different.In the third test case, every cell is green or blue, so Vasya will think they are the same.

gets.to_i.times do
  gets
  a = gets.chomp.gsub('G', 'B')
  b = gets.chomp.gsub('G', 'B')
  puts a == b ? :YES : :NO
end


Peter decided to wish happy birthday to his friend from Australia and send him a card. To make his present more mysterious, he decided to make a chain. Chain here is such a sequence of envelopes A = {a1,  a2,  ...,  an}, where the width and the height of the i-th envelope is strictly higher than the width and the height of the (i  -  1)-th envelope respectively. Chain size is the number of envelopes in the chain. Peter wants to make the chain of the maximum size from the envelopes he has, the chain should be such, that he'll be able to put a card into it. The card fits into the chain if its width and height is lower than the width and the height of the smallest envelope in the chain respectively. It's forbidden to turn the card and the envelopes. Peter has very many envelopes and very little time, this hard task is entrusted to you.

The first line contains integers n, w, h (1  ≤ n ≤ 5000, 1 ≤ w,  h  ≤ 106) — amount of envelopes Peter has, the card width and height respectively. Then there follow n lines, each of them contains two integer numbers wi and hi — width and height of the i-th envelope (1 ≤ wi,  hi ≤ 106).

In the first line print the maximum chain size. In the second line print the numbers of the envelopes (separated by space), forming the required chain, starting with the number of the smallest envelope. Remember, please, that the card should fit into the smallest envelope. If the chain of maximum size is not unique, print any of the answers. If the card does not fit into any of the envelopes, print number 0 in the single line.

n,w,h = gets.split(' ').map(&:to_i)
arr = []
n.times do |i|
    a,b = gets.split(' ').map(&:to_i)
    if a > w and b > h then
        arr.push([a,b,i])
    end
end

arr.sort! {|a,b| if a[0] != b[0] then a[0] <=> b[0] else b[1] <=> a[1] end}

best = []
cur = []
from = []

arr.each_with_index do |v,i|
    lst = v[0]
    l,r = -1, best.length
    while r - l > 1 do
        e = ((l + r) >> 1)
        if best[e] >= v[1] then r = e
        else l = e end
    end
    if l == -1 then
        best[0] = v[1]
        cur[0] = i
        from.push(-1)
    else
        if l == best.length - 1 then
            best.push(v[1])
            cur.push(i)
            from.push(cur[l])
        else
            best[l + 1] = v[1]
            from.push(cur[l])
            cur[l + 1] = i
        end
    end
end

puts best.length
c = cur.length > 0 ? cur.last : -1
ans = []
while c != -1 do
    ans.push(arr[c][2])
    c = from[c]
end

ans.reverse!

puts ans.map{|i| i + 1}.join(' ')

n,w,h = gets.split(' ').map(&:to_i)
arr = []
n.times do |i|
    a,b = gets.split(' ').map(&:to_i)
    if a > w and b > h then
        arr.push([a,b,i])
    end
end

arr.sort! {|a,b| a[0] <=> b[0]}

best = []
cur = []
from = []

arr.each_with_index do |v,i|
    l,r = -1, best.length
    while r - l > 1 do
        e = ((l + r) >> 1)
        if best[e] >= v[1] then r = e
        else l = e end
    end
    if l == -1 then
        best[0] = v[1]
        cur[0] = i
        from.push(-1)
    else
        if l == best.length - 1 then
            best.push(v[1])
            cur.push(i)
            from.push(cur[l])
        else
            best[l + 1] = v[1]
            from.push(cur[l])
            cur[l + 1] = i
        end
    end
end

puts best.length
c = cur.length > 0 ? cur.last : -1
ans = []
while c != -1 do
    ans.push(arr[c][2])
    c = from[c]
end

ans.reverse!

puts ans.map{|i| i + 1}.join(' ')

n,w,h = gets.split(' ').map(&:to_i)
arr = []
n.times do |i|
    a,b = gets.split(' ').map(&:to_i)
    if a > w and b > h then
        arr.push([a,b,i])
    end
end

arr.sort! {|a,b| a[0] <=> b[0]}

best = []
cur = []
from = []

lst = -1
arr.each_with_index do |v,i|
    if v[0] == lst then
        from.push(-1)
        next
    end
    lst = v[0]
    l,r = -1, best.length
    while r - l > 1 do
        e = ((l + r) >> 1)
        if best[e] >= v[1] then r = e
        else l = e end
    end
    if l == -1 then
        best[0] = v[1]
        cur[0] = i
        from.push(-1)
    else
        if l == best.length - 1 then
            best.push(v[1])
            cur.push(i)
            from.push(cur[l])
        else
            best[l + 1] = v[1]
            from.push(cur[l])
            cur[l + 1] = i
        end
    end
end

puts best.length
c = cur.length > 0 ? cur.last : -1
ans = []
while c != -1 do
    ans.push(arr[c][2])
    c = from[c]
end

ans.reverse!

puts ans.map{|i| i + 1}.join(' ')


Sereja loves integer sequences very much. He especially likes stairs.Sequence a1, a2, ..., a|a| (|a| is the length of the sequence) is stairs if there is such index i (1 ≤ i ≤ |a|), that the following condition is met: a1 < a2 < ... < ai - 1 < ai > ai + 1 > ... > a|a| - 1 > a|a|.For example, sequences [1, 2, 3, 2] and [4, 2] are stairs and sequence [3, 1, 2] isn't.Sereja has m cards with numbers. He wants to put some cards on the table in a row to get a stair sequence. What maximum number of cards can he put on the table?

The first line contains integer m (1 ≤ m ≤ 105) — the number of Sereja's cards. The second line contains m integers bi (1 ≤ bi ≤ 5000) — the numbers on the Sereja's cards.

In the first line print the number of cards you can put on the table. In the second line print the resulting stairs.

#!/usr/bin/ruby

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

grouped = a.group_by {|x| x }.to_a.sort.reverse
tail = [grouped.shift[0]]
head = []
grouped.each do |val,seq|
  if seq.size >= 2
    tail << val
    head << val
  else
    tail << val
  end
end

r = head.reverse + tail
puts r.size
puts r.join(" ")

STDIN.gets
cards = STDIN.gets.strip.split.map {|x| x.to_i}
cards.sort!

stairs = []
leftovers = []
prev = 0

cards.each do |x|
  if x == prev
    leftovers << x
  else
    stairs << x
  end
  prev = x
end

leftovers.reverse.each do |x|
  stairs << x unless x == prev
  prev = x
end

STDOUT.puts stairs.size
STDOUT.puts stairs.reverse.join(" ")

m = $stdin.gets.to_i
cards = $stdin.gets.chomp.split(' ').map{|e| e.to_i}

cards.sort! {|a, b| b <=> a}
ladder = [cards.shift]
cards.each do |e|
    if e < ladder.last
        ladder.push e
    elsif e < ladder.first
        ladder.unshift e
    end
end

puts ladder.size
puts ladder.join(" ")

m=gets.to_i
b=gets.split.map(&:to_i)
b.sort!.reverse!
a=[b.shift]
c=0
while b.size>0
  d=b.shift
  if c%2==0
    a.unshift d if a[0]>d
  else
    a<<d if a[-1]>d
  end
  c+=1
end
puts a.size,a*' '

i = gets.to_i
cards = gets.split.map(&:to_i)

if cards.uniq.length == i
  puts i
  puts cards.sort.reverse.join ' '
else
  card_grps = cards.group_by(&:to_i).to_a.sort_by(&:first).map(&:last)
  result = []
  card_grps.each { |cs| result.push cs.pop }
  rev = card_grps.reverse
  rev.shift
  rev.each { |cs| result.push cs.pop unless cs.empty? }
  # p card_grps
  # p rev
  # p result
  puts result.count
  puts result.join ' '
end

cardNum = gets.chomp.to_i
cards = gets.chomp.split(' ').map {|i| i.to_i}
old = -1

if cards.uniq.length == cards.length
	puts "#{cards.length}"
	cards.reverse_each do |item|
		print "#{item} "
	end
else
	frontList = []
	backList = []
	cards.sort!

	cards.each do |item|
		frontList << item if old != item
		backList << item if old == item
		old = item
	end

#	print "#{frontList}"
#	print "#{backList}"

	backList.uniq!
	backList.delete_at(backList.length - 1) if frontList[frontList.length - 1] == backList[backList.length - 1]
	puts "#{frontList.length + backList.length}"

	frontList.each do |item|
		print "#{item} "
	end

	backList.reverse_each do |item|
		print "#{item} "
	end
end

STDIN.gets
cards = STDIN.gets.strip.split.map {|x| x.to_i}
cards.sort!

stairs = []
leftovers = []
prev = 0

cards.each do |x|
  if x == prev
    leftovers << x
  else
    stairs << x
  end
  prev = x
end

leftovers.reverse.each do |x|
  stairs << x unless x == prev
end

STDOUT.puts stairs.size
STDOUT.puts stairs.reverse.join(" ")

STDIN.gets
cards = STDIN.gets.strip.split.map {|x| x.to_i}
cards.sort!

stairs = []
leftovers = []
prev = 0

cards.each do |x|
  if x == prev
    leftovers << x
  else
    stairs << x
  end
  prev = x
end

leftovers.reverse.each do |x|
  stairs << x unless x == prev
  x = prev
end

STDOUT.puts stairs.size
STDOUT.puts stairs.reverse.join(" ")

STDIN.gets
cards = STDIN.gets.strip.split.map {|x| x.to_i}
cards.sort!

stairs = []
leftovers = []
prev = 0

cards.each do |x|
  if x == prev
    leftovers << x
  else
    stairs << x
  end
  prev = x
end

leftovers.reverse.each do |x|
  stairs << x unless x == prev
end

p stairs.size
p stairs.join(" ")

cardNum = gets.chomp.to_i
cards = gets.chomp.split(' ').map {|i| i.to_i}
old = -1

if cards.uniq.length == cards.length
	puts "#{cards.length}"
	cards.reverse_each do |item|
		print "#{item} "
	end
else
	frontList = []
	backList = []
	cards.sort!

	cards.each do |item|
		frontList << item if old != item
		backList << item if old == item
		old = item
	end

#	print "#{frontList}"
#	print "#{backList}"

	backList.delete_at(backList.length - 1) if frontList[frontList.length - 1] == backList[backList.length - 1]
	puts "#{frontList.length + backList.length}"

	frontList.each do |item|
		print "#{item} "
	end

	backList.reverse_each do |item|
		print "#{item} "
	end
end

cardNum = gets.chomp.to_i
cards = gets.chomp.split(' ').map {|i| i.to_i}

if cards.uniq.length == cards.length
	puts "#{cards.length}"
	cards.reverse_each do |item|
		print "#{item} "
	end
else
	tempCards = cards.uniq
	tempCards.sort!

	list = []

	tempCards.each do |item|
		#print "#{item} "
		list << item
		cards.delete_at(cards.index(item))
	end

	if list[list.length - 1] == cards[cards.length - 1]
		cards.delete_at(cards.length - 1)
	end

	cards.reverse_each do |item|
		list << item
	end

	puts "#{list.length}"
	list.each do |item|
		print "#{item} "
	end
end


The Fair Nut found a string $$$s$$$. The string consists of lowercase Latin letters. The Nut is a curious guy, so he wants to find the number of strictly increasing sequences $$$p_1, p_2, \ldots, p_k$$$, such that:   For each $$$i$$$ ($$$1 \leq i \leq k$$$), $$$s_{p_i} =$$$ 'a'.  For each $$$i$$$ ($$$1 \leq i < k$$$), there is such $$$j$$$ that $$$p_i < j < p_{i + 1}$$$ and $$$s_j =$$$ 'b'. The Nut is upset because he doesn't know how to find the number. Help him.This number should be calculated modulo $$$10^9 + 7$$$.

The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 10^5$$$) consisting of lowercase Latin letters.

In a single line print the answer to the problem — the number of such sequences $$$p_1, p_2, \ldots, p_k$$$ modulo $$$10^9 + 7$$$.

MOD = 10**9 + 7
ss = STDIN.gets.strip
chunks = ss.split(/b+/).map do |s|
  cnt = 0
  for i in 0..(s.length-1)
    cnt += 1 if s[i] == 'a'
  end
  cnt
end
ans = 1
chunks.each do |n|
  ans *= n+1
  ans %= MOD
end
puts (ans-1) % MOD


Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost.Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network.Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.

The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1 ≤ ti ≤ 2; xi, yi ≥ 0; xi + yi = 10). If ti = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost. It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.

In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes). In the second line print the state of server b in the similar format.

NoteConsider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.

n = gets.to_i
a = [[], []] # a b
n.times do
  s = gets.split.map(&:to_i)
  (s[0] == 1 ? a[0] : a[1]).push [s[1], s[2]]
end
puts (a[0].transpose[0].inject(:+) >= a[0].transpose[1].inject(:+) ? :LIVE : :DEAD)
puts (a[1].transpose[0].inject(:+) >= a[1].transpose[1].inject(:+) ? :LIVE : :DEAD)

n = gets.to_i
at = 0
ab = 0
bt = 0
bb = 0
n.times do
  t, x, y = gets.split.map(&:to_f)
  if t == 1.0
    at += x
    ab += x + y
  else
    bt += x
    bb += x + y
  end
end

if at / ab >= 0.5
  puts 'LIVE'
else
  puts 'DEAD'
end

if bt / bb >= 0.5
  puts 'LIVE'
else
  puts 'DEAD'
end

n=gets.to_i
a=[0,0]
c=[0,0]
n.times {
    t,s,f=gets.split.map(&:to_i)
    a[t-1]+=s
    c[t-1]+=1
}
for i in 0..1 do
    puts a[i]>=5*c[i] ? "LIVE" : "DEAD"
end

#! /usr/bin/ruby
$n = gets.to_i
$k, $p = [0,0,0], [0,0,0]
(1..$n).each do
  k, x, y = gets.split(' ').map(&:to_i)
  $k[k] += x
  $p[k] += 10
end
(1..2).each{ |i| if $k[i] * 2 >= $p[i] then puts "LIVE" else puts "DEAD" end }

n = gets.to_i
k = 0
x = 0.0
y = 0.0
n.times do
  a = []
  gets.split(" ").each do |st|
    a << st.to_i
  end
  if a[0] == 1 then
    x += a[1]/10.0
    k += 1
  else
    y += a[1]/10.0
  end
end
if (x/k >= 0.5) then
  puts "LIVE"
else
  puts "DEAD"
end

if (y/(n-k) >= 0.5) then
  puts "LIVE"
else
  puts "DEAD"
end

n = gets.to_i
a, c = [0,0], [0,0]
n.times do
  t,x,y = gets.split(' ').map(&:to_i)
  a[t-1] += x
  c[t-1] += 1
end
for i in 0..1 do
  puts a[i]>=5*c[i] ? "LIVE" : "DEAD"
end

n = gets.to_i
xx = Array.new(2,0)
yy = Array.new(2,0)
(1..n).each do
    t, x, y = gets.split.collect{|i| i.to_i}
    xx[t-1] += x
    yy[t-1] += y
end
(0..1).each do |i|
    if xx[i] >= yy[i]
        puts 'LIVE'
    else
        puts 'DEAD'
    end
end

n = gets.to_i

a = [0,0]
b = [0,0]

n.times do
  t,x,y = *(gets.split.map &:to_i)
  if t==1
    a[0] += x
    a[1] += x+y
  else
    b[0] += x
    b[1] += x+y
  end
end

puts a[0]>=a[1]/2 ? 'LIVE' : 'DEAD'
puts b[0]>=b[1]/2 ? 'LIVE' : 'DEAD'

n = gets.to_i
s = []
good1 = 0
good2 = 0
bad1 = 0
bad2 = 0
n.times do |i|
    s[i] = gets.split
    s[i] = s[i].collect {|j| j = j.to_i}
    if s[i][0] == 1 then
        good1 += s[i][1]
        bad1 += s[i][2]
    else
        good2 += s[i][1]
        bad2 += s[i][2]
    end
end
if good1 >= bad1 then
    puts "LIVE"
else
    puts "DEAD"
end
if good2 >= bad2 then
    puts "LIVE"
else
    puts "DEAD"
end

num_pings = gets.to_i
num = {1 => 0, 2 => 0}
successful = {1 => 0, 2 => 0}
for i in 0...num_pings
	temp = gets.split.collect {|i| i.to_i}
	num[temp[0]] += 10
	successful[temp[0]] += temp[1]
end
(1..2).each do |n|
	if num[n]/2 <= successful[n]
		puts "LIVE"
	else
		puts "DEAD"
	end
end

n = gets.to_i
s = [[0, 0], [0, 0]]
n.times do
  t, x, y = gets.split.map(&:to_i)
  s[t-1][0] += x
  s[t-1][1] += 10
end
s.each {|a| if a[0] >= a[1]/2 then puts "LIVE" else puts "DEAD" end}

n = gets.to_i
s = ["LIVE", "LIVE"]
n.times do
  t, x, y = gets.split.map(&:to_i)
  if x >= 5 then
    s[t-1] = "LIVE"
  else
    s[t-1] = "DEAD"
  end
end
s.each {|x| puts x}

n = gets.to_i
at = 0
ab = 0
bt = 0
bb = 0
n.times do
  c, t, b = gets.split.map(&:to_f)
  if c == 1.0
    at += t
    ab += b
  else
    bt += t
    bb += b
  end
end

if at / ab >= 0.5
  puts 'LIVE'
else
  puts 'DEAD'
end

if bt / bb >= 0.5
  puts 'LIVE'
else
  puts 'DEAD'
end

n = gets.to_i
s = ["DEAD", "DEAD"]
n.times do
  t, x, y = gets.split.map(&:to_i)
  if x >= 5 then
    s[t-1] = "LIVE"
  else
    s[t-1] = "DEAD"
  end
end
s.each {|x| puts x}


Ivan decided to prepare for the test on solving integer equations. He noticed that all tasks in the test have the following form:  You are given two positive integers $$$u$$$ and $$$v$$$, find any pair of integers (not necessarily positive) $$$x$$$, $$$y$$$, such that: $$$$$$\frac{x}{u} + \frac{y}{v} = \frac{x + y}{u + v}.$$$$$$  The solution $$$x = 0$$$, $$$y = 0$$$ is forbidden, so you should find any solution with $$$(x, y) \neq (0, 0)$$$. Please help Ivan to solve some equations of this form.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of test cases. The next lines contain descriptions of test cases. The only line of each test case contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq 10^9$$$) — the parameters of the equation.

For each test case print two integers $$$x$$$, $$$y$$$ — a possible solution to the equation. It should be satisfied that $$$-10^{18} \leq x, y \leq 10^{18}$$$ and $$$(x, y) \neq (0, 0)$$$. We can show that an answer always exists. If there are multiple possible solutions you can print any.

za=gets.chomp.to_i
za.times do
	a,b=gets.split.map(&:to_i)
	print -a*a," ",b*b
	puts ""
end


One day, Vogons wanted to build a new hyperspace highway through a distant system with $$$n$$$ planets. The $$$i$$$-th planet is on the orbit $$$a_i$$$, there could be multiple planets on the same orbit. It's a pity that all the planets are on the way and need to be destructed.Vogons have two machines to do that.  The first machine in one operation can destroy any planet at cost of $$$1$$$ Triganic Pu.  The second machine in one operation can destroy all planets on a single orbit in this system at the cost of $$$c$$$ Triganic Pus. Vogons can use each machine as many times as they want.Vogons are very greedy, so they want to destroy all planets with minimum amount of money spent. Can you help them to know the minimum cost of this project?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow. Each test case consists of two lines. The first line contains two integers $$$n$$$ and $$$c$$$ ($$$1 \le n, c \le 100$$$) — the number of planets and the cost of the second machine usage. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the orbit of the $$$i$$$-th planet.

For each test case print a single integer — the minimum cost of destroying all planets.

NoteIn the first test case, the cost of using both machines is the same, so you can always use the second one and destroy all planets in orbit $$$1$$$, all planets in orbit $$$2$$$, all planets in orbit $$$4$$$, all planets in orbit $$$5$$$.In the second test case, it is advantageous to use the second machine for $$$2$$$ Triganic Pus to destroy all the planets in orbit $$$2$$$, then destroy the remaining two planets using the first machine.In the third test case, you can use the first machine twice or the second machine once.In the fourth test case, it is advantageous to use the first machine twice.

def main
  t = inp.to_i
  t.times do
    n, c = mapint(inarr)
    orb = Array.new(101, 0)
    mapint(inarr).each { |e|
      orb[e - 1]+=1
    }
    cst = 0
    orb.each { |e|
      cst += [c, e].min
    }
    puts cst
  end

end

# lib
def inp
  gets.chomp
end

def inarr
  gets.chomp.split
end

def mapint(lst)
  lst.map(&:to_i)
end

main


You are given $$$n$$$ words of equal length $$$m$$$, consisting of lowercase Latin alphabet letters. The $$$i$$$-th word is denoted $$$s_i$$$.In one move you can choose any position in any single word and change the letter at that position to the previous or next letter in alphabetical order. For example:  you can change 'e' to 'd' or to 'f';  'a' can only be changed to 'b';  'z' can only be changed to 'y'. The difference between two words is the minimum number of moves required to make them equal. For example, the difference between "best" and "cost" is $$$1 + 10 + 0 + 0 = 11$$$.Find the minimum difference of $$$s_i$$$ and $$$s_j$$$ such that $$$(i < j)$$$. In other words, find the minimum difference over all possible pairs of the $$$n$$$ words.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains $$$2$$$ integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 50$$$, $$$1 \leq m \leq 8$$$) — the number of strings and their length respectively. Then follows $$$n$$$ lines, the $$$i$$$-th of which containing a single string $$$s_i$$$ of length $$$m$$$, consisting of lowercase Latin letters.

For each test case, print a single integer — the minimum difference over all possible pairs of the given strings.

6

2 4

best

cost

6 3

abb

zba

bef

cdu

ooo

zzz

2 7

aaabbbc

bbaezfe

3 2

ab

ab

ab

2 8

aaaaaaaa

zzzzzzzz

3 1

a

u

y

NoteFor the second test case, one can show that the best pair is ("abb","bef"), which has difference equal to $$$8$$$, which can be obtained in the following way: change the first character of the first string to 'b' in one move, change the second character of the second string to 'b' in $$$3$$$ moves and change the third character of the second string to 'b' in $$$4$$$ moves, thus making in total $$$1 + 3 + 4 = 8$$$ moves.For the third test case, there is only one possible pair and it can be shown that the minimum amount of moves necessary to make the strings equal is $$$35$$$.For the fourth test case, there is a pair of strings which is already equal, so the answer is $$$0$$$.

gets.to_i.times do
  n, m = gets.split.map(&:to_i)
  ss = n.times.map { gets.chomp.bytes.map { |c| c - 97 } }
  answer = ss.flat_map.with_index do |s1, i|
    ss[i + 1..].map do |s2|
      m.times.map do |i|
        (s1[i] - s2[i]).abs
      end.sum
    end
  end.min
  p answer
end

def chardist(a, b)
  xs = [a.ord, b.ord].sort
  xs[1] - xs[0]
end

def dist(a, b)
  fail unless a.length == b.length
  m = a.length
  (0...m).map { |i| chardist(a[i], b[i]) }.sum
end

gets.to_i.times do
  n, _ = gets.split.map(&:to_i)
  ss = Array.new(n) { gets.strip }

  ans = nil
  n.times do |r|
    r.times do |l|
      cur = dist(ss[l], ss[r])
      ans = cur if !ans || cur < ans
    end
  end

  p ans
end

def diff(s, t)
  r = 0
  s.chars.each_with_index do |c, i|
    r += (c.ord - t[i].ord).abs
  end

  r
end

def main
  gets.to_i.times do
    n, m = gli
    a = []
    ans = 100_100_100_100
    n.times { a << gets.chomp }

    (0...n).each do |i|
      (i + 1...n).each do |j|
        ans = [ans, diff(a[i], a[j])].min
      end
    end
    puts ans
  end
end

MOD = 10**9 + 7
def gs = gets.chomp
def gi = gets.to_i
def gli = gets.split.map(&:to_i)
def cyesno(x) = x ? :Yes : :No
def uyesno(x) = x ? :YES : :NO

main

main = -> {
  t = int
  t.times do
      n, m = ints
      s = rep(n) { string.each_byte.to_a }
      min = INF
      s.combination(2) do |(a, b)|
          m = a.zip(b).sum { |x, y| (x - y).abs }
          min = [m, min].min
      end
      puts min
  end
}

DEBUG = true
MOD = 10**9+7
$yesno = %w(No Yes)
YesNo = %w(No Yes)
YESNO = %w(NO YES)
INF = 10**18

require "set"
require "prime"

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

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

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

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

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

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

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

main[]


Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≤ li < ri ≤ n). The answer to the query li, ri is the number of such integers i (li ≤ i < ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.

The first line contains string s of length n (2 ≤ n ≤ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≤ li < ri ≤ n).

Print m integers — the answers to the queries in the order in which they are given in the input.

dp=[0]
pre=0
gets.chomp.each_byte{|b|
  dp<<dp.last+(pre==b ? 1 : 0)
  pre=b
}
gets.to_i.times{
  l,r=gets.split.map(&:to_i)
  puts dp[r]-dp[l]
}

s = gets
n = s.length
sum = Array.new n + 1, 0
(2..n).each do |i|
  sum[i] += sum[i - 1]
  if s[i - 1] == s[i - 2]
    sum[i] += 1
  end
end
m = gets.to_i
m.times do
  l, r = gets.split.map &:to_i
  puts sum[r] - sum[l]
end

#!/usr/bin/ruby1.9

text = STDIN.readline[0..-2]
counts = [0]
(1..text.length-1).each do |pos|
	count = counts[pos-1] + (text[pos] == text[pos-1] ? 1 : 0)
	counts.push(count)
end

query_num = STDIN.readline.to_i
query_num.times do
	start, finish = STDIN.readline.split.collect {|s| s.to_i }
	puts counts[finish-1]-counts[start-1]
end

s=gets.chomp.chars
ans=0

arr=[]
while s.size>1
	if s[0]==s[1] then
		ans=ans+1
	end
	arr<<ans
	s.shift
end
arr.unshift(0)
gets.to_i.times{
	a,b=gets.split.map{|e| e.to_i}
	puts arr[b-1]-arr[a-1]
}

string, _, *queries = STDIN.read.split("\n")

data = [0] * string.size
(1..string.size).each do |i|
  data[i] = data[i-1]
  data[i] += 1 if string[i-1] == string[i-2] && i > 1
end

queries.map! { |query| query.split.map(&:to_i) }.each do |query|
  i, j = query
  puts data[j] - data[i]
end

def main()
    st=gets.chomp
    ar=Array.new(st.length)
    for i in 0...(st.length)
        ar[i]=0
    end
    for i in 0...(st.length)
        if i>0
            ar[i]=ar[i-1]
        end
        if i+1<(st.length) && st[i].chr==st[i+1].chr
            ar[i]+=1
        end
    end
    tc=gets.chomp.to_i
    for i in 0...tc
        l,r=gets.chomp.split(" ").map{|i| i.to_i}
        l-=1
        r-=1
        if l-1==-1
            puts ar[r-1]
        else
            puts ar[r-1]-ar[l-1]
        end
    end
end
main()

def solution(s, list)
  acc = [0]
  prev = ""
  s.each_char do |char|
    acc << acc.last + (prev == char ? 1 : 0)
    prev = char
  end

  list.each do |item|
    puts acc[item[1]] - acc[item[0]]
  end
end

s = gets.strip
n = gets.strip.to_i

list = []

n.times do
  list << gets.split.map(&:to_i)
end

solution(s, list)

s = gets.split('')
a = [0]
(1..s.size - 1).each{|i| a << (s[i - 1] == s[i] ? a.last + 1 : a.last)}
m = gets.to_i
m.times do
    l, r = gets.split.map{|x| x.to_i}
    puts a[r - 1] - a[l - 1]
end

s = gets
m = gets.to_i

a = [0]
(1..s.length).each { |i| a[i] = s[i] == s[i-1] ? a[i-1] + 1 : a[i-1] }

m.times do
  l, r = gets.chomp.split(' ').map(&:to_i)
  puts a[r-1] - a[l-1]
end

s = gets.chomp
n = s.size
f = [0] * n
(1...n).each{|i|
  f[i] = ((s[i] == s[i-1])?1:0) + f[i-1]
}
gets.to_i.times {
  l, r = gets.split.map(&:to_i)
  puts f[r-1] - f[l-1]
}

s = ' ' + gets.chomp + ' '
a = Array.new(s.length+1, 0)

s.chars.each_with_index do |c, i|
  a[i] = 1 if s[i] == s[i+1]
  a[i] += a[i-1] unless i.zero?
end

1.upto(gets.to_i) do
  l, r = gets.split(' ').map(&:to_i)

  puts a[r] - a[l-1] - (a[r] - a[r-1])
end

a = gets.split('')
dem = []
dem[0] = 0
(1..a.length-1).each do |i|
    if a[i] == a[i-1]
        dem[i] = dem[i-1] + 1
    else
        dem[i] = dem[i-1]
    end
end
n = gets.to_i

(1..n).each do |k|
    b = gets.chomp.split(" ").map{|i| i.to_i}
    puts ( dem[b[1] -1] - dem[b[0]-1])
end

str = gets().chomp.split(//).unshift(' ').join
qnum = gets().to_i
qarr = []
qnum.times { qarr.push gets().chomp.split(/\ /).collect{|s| s.to_i} }
correct = []
1.upto(str.size - 2) { |i| correct[i] = true if str[i] == str[i+1] }
count = correct[1] ? [0,1] : [0,0]
2.upto(str.size - 1) { |i| count[i] = count[i-1] + (correct[i] ? 1 : 0) }
qarr.each { |arr| puts count[arr[1]-1] - count[arr[0]-1] }

str = gets()
str.chomp!
str = str.split(//).unshift(' ').join
qnum = gets().to_i
qarr = []
qnum.times do
  qarr.push gets().chomp.split(/\ /).collect{|s| s.to_i}
end
correct = []
1.upto(str.size - 2) do |i|
  correct[i] = true if str[i] == str[i+1]
end
if(correct[1])
  count = [0,1]
else
  count = [0,0]
end
2.upto(str.size - 1) do |i|
  count[i] = count[i-1] + (correct[i] ? 1 : 0)
end
qarr.each do |arr|
  puts count[arr[1]-1] - count[arr[0]-1]
end

s = gets.chomp
ps = Array.new(s.length + 1) { 0 }
s.length.times do |i|
  ps[i + 1] = ps[i] + (s[i] == s[i + 1] ? 1 : 0)
end
STDIN.readlines.drop(1).map(&:chomp).each do |str|
  q = str.split.map(&:to_i)
  p ps[q[1] - 1] - ps[q[0] - 1]
end

s = ' ' + gets.chomp + ' '
a = Array.new(s.length+1, 0)

s.chars.each_with_index do |c, i|
  a[i] = 1 if s[i] == s[i+1]
  a[i] += a[i-1] unless i.zero?
end

p a

1.upto(gets.to_i) do
  l, r = gets.split(' ').map(&:to_i)

  puts a[r] - a[l-1] - (a[r] - a[r-1])
end

s = gets()
s.chomp!
max = s.to_i
if s.size > 1 && s[0...s.size-1].to_i > max
  max = s[0...s.size-1].to_i
end
 if s.size > 2
  arr = s.split(//)
  arr.delete_at(-2)
  n = arr.join.to_i
  if n > max
    max = n
  end
end
puts max


You are given a board of size $$$n \times n$$$, where $$$n$$$ is odd (not divisible by $$$2$$$). Initially, each cell of the board contains one figure.In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $$$(i, j)$$$ you can move the figure to cells:   $$$(i - 1, j - 1)$$$;  $$$(i - 1, j)$$$;  $$$(i - 1, j + 1)$$$;  $$$(i, j - 1)$$$;  $$$(i, j + 1)$$$;  $$$(i + 1, j - 1)$$$;  $$$(i + 1, j)$$$;  $$$(i + 1, j + 1)$$$; Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $$$n^2-1$$$ cells should contain $$$0$$$ figures and one cell should contain $$$n^2$$$ figures).You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n < 5 \cdot 10^5$$$) — the size of the board. It is guaranteed that $$$n$$$ is odd (not divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$ ($$$\sum n \le 5 \cdot 10^5$$$).

For each test case print the answer — the minimum number of moves needed to get all the figures into one cell.

gets.to_i.times { puts (1..gets.to_i / 2).sum { |i| i * i * 8 } }

1.upto(gets.to_i) do
  n = gets.to_i
  puts (1..n.div(2)).inject(0) { |x, i| x + 8 * i**2 }
end


You are given an array $$$a$$$ consisting of $$$n$$$ integers. Each $$$a_i$$$ is one of the six following numbers: $$$4, 8, 15, 16, 23, 42$$$.Your task is to remove the minimum number of elements to make this array good.An array of length $$$k$$$ is called good if $$$k$$$ is divisible by $$$6$$$ and it is possible to split it into $$$\frac{k}{6}$$$ subsequences $$$4, 8, 15, 16, 23, 42$$$.Examples of good arrays:  $$$[4, 8, 15, 16, 23, 42]$$$ (the whole array is a required sequence);  $$$[4, 8, 4, 15, 16, 8, 23, 15, 16, 42, 23, 42]$$$ (the first sequence is formed from first, second, fourth, fifth, seventh and tenth elements and the second one is formed from remaining elements);  $$$[]$$$ (the empty array is good). Examples of bad arrays:   $$$[4, 8, 15, 16, 42, 23]$$$ (the order of elements should be exactly $$$4, 8, 15, 16, 23, 42$$$);  $$$[4, 8, 15, 16, 23, 42, 4]$$$ (the length of the array is not divisible by $$$6$$$);  $$$[4, 8, 15, 16, 23, 42, 4, 8, 15, 16, 23, 23]$$$ (the first sequence can be formed from first six elements but the remaining array cannot form the required sequence).

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ (each $$$a_i$$$ is one of the following numbers: $$$4, 8, 15, 16, 23, 42$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

Print one integer — the minimum number of elements you have to remove to obtain a good array.

GOOD = [4,8,15,16,23,42]

def solve(a)
  pos = {}
  GOOD.each { |g| pos[g] = [] }

  a.each_with_index do |e, i|
    pos[e].push(i)
  end
  # puts pos.inspect
  res = 0
  while true
    positions = []
    GOOD.each_with_index do |g, i|
      p = pos[g].shift
      while i > 0 && !p.nil? && !positions[i - 1].nil? && p < positions[i - 1]
        p = pos[g].shift
      end
      positions << p
    end
    break if positions.include?(nil)
    res += 1
  end
  a.size - (res * 6)
end

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

GOOD = [4,8,15,16,23,42]
def solve(a)
  h = {}
  GOOD.each { |g| h[g] = 0 }
  a.each do |e|
    if GOOD.include?(e)
      h[e] += 1
    end
  end
  mn = h.min_by { |k, v| v }
  return a.size if mn.nil?
  return a.size - (mn[1] * GOOD.size)
end

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