You are given a string $$$s$$$ such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of $$$s$$$ such that it contains each of these three characters at least once.A contiguous substring of string $$$s$$$ is a string that can be obtained from $$$s$$$ by removing some (possibly zero) characters from the beginning of $$$s$$$ and some (possibly zero) characters from the end of $$$s$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 20000$$$) — the number of test cases. Each test case consists of one line containing the string $$$s$$$ ($$$1 \le |s| \le 200000$$$). It is guaranteed that each character of $$$s$$$ is either 1, 2, or 3. The sum of lengths of all strings in all test cases does not exceed $$$200000$$$.

For each test case, print one integer — the length of the shortest contiguous substring of $$$s$$$ containing all three types of characters at least once. If there is no such substring, print $$$0$$$ instead.

NoteConsider the example test:In the first test case, the substring 123 can be used.In the second test case, the substring 213 can be used.In the third test case, the substring 1223 can be used.In the fourth test case, the substring 3221 can be used.In the fifth test case, there is no character 3 in $$$s$$$.In the sixth test case, there is no character 1 in $$$s$$$.In the seventh test case, the substring 3112 can be used.

def ternary_string(str)
  h = {"1"=>false, "2"=>false, "3"=>false}
  i = 0
  min_size = 0
  while i < str.length
    h[str[i]] = i
    if h.values.all?
      if min_size == 0
        min_size = h.values.max - h.values.min + 1
      else
        min_size = [min_size, h.values.max - h.values.min + 1].min
      end
    end
    i += 1
  end
  min_size
end

test_cases = gets.chomp.to_i
i = 0
while i < test_cases
  st = gets.chomp
  p ternary_string(st)
  i += 1
end

def ternary_string(str)
  s = []
  i = 0
  h = {"1"=>false, "2"=>false, "3"=>false}
  min_size = str.length + 1
  while i < str.length
    s << str[i]
    h[str[i]] = true
    fin = s.size - 1
    if s[0] == s[fin]
      while fin > 0
        if s[fin] == s[0]
          s.shift
        end
        fin -= 1
      end
    end
    if h.values.all?
      min_size = [min_size, s.size].min
    end
    i += 1
  end
  min_size > str.length ? 0 : min_size
end

test_cases = gets.chomp.to_i
i = 0
while i < test_cases
  st = gets.chomp
  p ternary_string(st)
  i += 1
end

def ternary_string(str)
  s = []
  i = 0
  h = {"1"=>false, "2"=>false, "3"=>false}
  min_size = str.length + 1
  while i < str.length
    s << str[i]
    h[str[i]] = true
    fin = s.size - 1
    if s[0] == s[fin]
      while fin > 0
        if s[fin] == s[0]
          s.shift
        end
        fin -= 1
      end
    end
    min_size = [min_size, s.size].min if h.values.all?
#    p s
    i += 1
  end
  min_size > str.length ? 0 : min_size
end

test_cases = gets.chomp.to_i
i = 0
while i < test_cases
  st = gets.chomp
  puts ternary_string(st)
  i += 1
end


One day mum asked Petya to sort his toys and get rid of some of them. Petya found a whole box of toy spiders. They were quite dear to him and the boy didn't want to throw them away. Petya conjured a cunning plan: he will glue all the spiders together and attach them to the ceiling. Besides, Petya knows that the lower the spiders will hang, the more mum is going to like it and then she won't throw his favourite toys away. Help Petya carry out the plan.A spider consists of k beads tied together by k - 1 threads. Each thread connects two different beads, at that any pair of beads that make up a spider is either directly connected by a thread, or is connected via some chain of threads and beads.Petya may glue spiders together directly gluing their beads. The length of each thread equals 1. The sizes of the beads can be neglected. That's why we can consider that gluing spiders happens by identifying some of the beads (see the picture). Besides, the construction resulting from the gluing process should also represent a spider, that is, it should have the given features. After Petya glues all spiders together, he measures the length of the resulting toy. The distance between a pair of beads is identified as the total length of the threads that connect these two beads. The length of the resulting construction is the largest distance between all pairs of beads. Petya wants to make the spider whose length is as much as possible.    The picture two shows two spiders from the second sample. We can glue to the bead number 2 of the first spider the bead number 1 of the second spider. The threads in the spiders that form the sequence of threads of maximum lengths are highlighted on the picture.

The first input file line contains one integer n (1 ≤ n ≤ 100) — the number of spiders. Next n lines contain the descriptions of each spider: integer ni (2 ≤ ni ≤ 100) — the number of beads, then ni - 1 pairs of numbers denoting the numbers of the beads connected by threads. The beads that make up each spider are numbered from 1 to ni.

Print a single number — the length of the required construction.

def rec(d, node, e, depth)
  depth[node] = d
  e[node].each do |n|
    unless depth[n]
      rec(d+1, n, e, depth)
    end
  end
end

def sub(node, e)
  depth = {}

  rec(0, node, e, depth)

  depth.max_by{|k,v| v}
end

def longest_length(g)
  e = {}
  g.each do |u,v|
    (e[u] ||= []) << v
    (e[v] ||= []) << u
  end

  node, len = sub(1, e)
  node, len = sub(node, e)

  len
end

n, gs = nil
File.open("input.txt") do |f|
  n = f.gets.to_i
  gs = []
  n.times do
    a = f.gets.split.map(&:to_i)
    gs << a[1..-1].each_slice(2).map
  end
end

len = gs.inject(0){|r,g| r + longest_length(g)}

File.open("output.txt", "w") do |f|
  f.puts len
end


"We've tried solitary confinement, waterboarding and listening to Just In Beaver, to no avail. We need something extreme.""Little Alena got an array as a birthday present..."The array b of length n is obtained from the array a of length n and two integers l and r (l ≤ r) using the following procedure:b1 = b2 = b3 = b4 = 0.For all 5 ≤ i ≤ n:   bi = 0 if ai, ai - 1, ai - 2, ai - 3, ai - 4 > r and bi - 1 = bi - 2 = bi - 3 = bi - 4 = 1  bi = 1 if ai, ai - 1, ai - 2, ai - 3, ai - 4 < l and bi - 1 = bi - 2 = bi - 3 = bi - 4 = 0  bi = bi - 1 otherwise You are given arrays a and b' of the same length. Find two integers l and r (l ≤ r), such that applying the algorithm described above will yield an array b equal to b'.It's guaranteed that the answer exists.

The first line of input contains a single integer n (5 ≤ n ≤ 105) — the length of a and b'. The second line of input contains n space separated integers a1, ..., an ( - 109 ≤ ai ≤ 109) — the elements of a. The third line of input contains a string of n characters, consisting of 0 and 1 — the elements of b'. Note that they are not separated by spaces.

Output two integers l and r ( - 109 ≤ l ≤ r ≤ 109), conforming to the requirements described above. If there are multiple solutions, output any of them. It's guaranteed that the answer exists.

NoteIn the first test case any pair of l and r pair is valid, if 6 ≤ l ≤ r ≤ 109, in that case b5 = 1, because a1, ..., a5 < l.

n = gets.to_i
a = gets.split.map(&:to_i)
b = gets.chomp.reverse.to_i(2)
r_max = l_max = 10 ** 9
r_min = l_min = - 10 ** 9

4.upto(n-1) do |i|
  if b & 15 == 15
    if b & 16 == 0
      t = a[i-4,5].min - 1
      r_max = t if t < r_max
    else
      t = a[i-4,5].min
      r_min = t if t > r_min
    end
  elsif b & 15 == 0
    if b & 16 == 16
      t = a[i-4,5].max + 1
      l_min = t if t > l_min
    else
      t = a[i-4,5].max
      l_max = t if t < l_max
    end
  end
  b = b >> 1
  #p b.to_s(2)
end
print "#{l_min} #{r_max}"
#print "\nl is from #{l_min} to #{l_max}, r is from #{r_min} to #{r_max}"

n = gets.to_i
a = gets.split.map(&:to_i)
b = gets.chomp.reverse.to_i(2)
r_max = l_max = 10 ** 9
r_min = l_min = - 10 ** 9

4.upto(n-1) do |i|
  if b & 15 == 15
    if b & 16 == 0
      t = a[i-4,5].min - 1
      r_max = t if t < r_max
    #else
    #  t = a[i-4,5].min
    #  r_min = t if t > r_min
    end
  elsif b & 15 == 0
    if b & 16 == 16
      t = a[i-4,5].max + 1
      l_min = t if t > l_min
    #else
    #  t = a[i-4,5].max
    #  l_max = t if t < l_max
    end
  end
  b = b >> 1
  #p b.to_s(2)
end
print "#{l_min} #{r_max}"
#print "\nl is from #{l_min} to #{l_max}, r is from #{r_min} to #{r_max}"


Polycarp has just attempted to pass the driving test. He ran over the straight road with the signs of four types.  speed limit: this sign comes with a positive integer number — maximal speed of the car after the sign (cancel the action of the previous sign of this type);  overtake is allowed: this sign means that after some car meets it, it can overtake any other car;  no speed limit: this sign cancels speed limit if any (car can move with arbitrary speed after this sign);  no overtake allowed: some car can't overtake any other car after this sign. Polycarp goes past the signs consequentially, each new sign cancels the action of all the previous signs of it's kind (speed limit/overtake). It is possible that two or more "no overtake allowed" signs go one after another with zero "overtake is allowed" signs between them. It works with "no speed limit" and "overtake is allowed" signs as well.In the beginning of the ride overtake is allowed and there is no speed limit.You are given the sequence of events in chronological order — events which happened to Polycarp during the ride. There are events of following types:  Polycarp changes the speed of his car to specified (this event comes with a positive integer number);  Polycarp's car overtakes the other car;  Polycarp's car goes past the "speed limit" sign (this sign comes with a positive integer);  Polycarp's car goes past the "overtake is allowed" sign;  Polycarp's car goes past the "no speed limit";  Polycarp's car goes past the "no overtake allowed"; It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified).After the exam Polycarp can justify his rule violations by telling the driving instructor that he just didn't notice some of the signs. What is the minimal number of signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view?

The first line contains one integer number n (1 ≤ n ≤ 2·105) — number of events. Each of the next n lines starts with integer t (1 ≤ t ≤ 6) — the type of the event. An integer s (1 ≤ s ≤ 300) follows in the query of the first and the third type (if it is the query of first type, then it's new speed of Polycarp's car, if it is the query of third type, then it's new speed limit). It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified).

Print the minimal number of road signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view.

NoteIn the first example Polycarp should say he didn't notice the "speed limit" sign with the limit of 70 and the second "speed limit" sign with the limit of 120.In the second example Polycarp didn't make any rule violation.In the third example Polycarp should say he didn't notice both "no overtake allowed" that came after "overtake is allowed" sign.

n = gets.to_i
events = []
n.times do
  events.push(gets.split.map(&:to_i))
end

missed_indexes = []

speed = events[0][1]
events.each_with_index do | event, index |
  #p [event, index]
  case event[0]
  when 1
    speed = event[1]
  when 3
    if event[1] < speed
      missed_indexes.push(index)
    end
  end
end
#puts "missed slow downs"
#p missed_indexes

max_speed = 0
race = false
events.each_with_index.to_a.reverse.each do |event, index|
  #p [event, index]
  case event[0]
  # Поликарп изменил скорость машины на заданную
  when 1
    max_speed = [max_speed, event[1]].max

  # машина Поликарпа обогнала другую машину;
  when 2
    race = true

  # машина Поликарпа проехала знак «ограничение скорости»
  when 3
    if max_speed > event[1]
      missed_indexes.push(index)
    else
      max_speed = 0
    end

  # машина Поликарпа проехала знак «обгон разрешен»;
  when 4
    race = false

  # машина Поликарпа проехала знак «отмена ограничения скорости»;
  when 5
    max_speed = 0

  # машина Поликарпа проехала знак «обгон запрещен».
  when 6
    if race
      missed_indexes.push(index)
    end
  end
end
#puts "missed everything"
#p missed_indexes

puts missed_indexes.uniq.count


Given an array $$$a$$$ of length $$$n$$$ and an integer $$$k$$$, find the number of indices $$$1 \leq i \leq n - k$$$ such that the subarray $$$[a_i, \dots, a_{i+k}]$$$ with length $$$k+1$$$ (not with length $$$k$$$) has the following property:   If you multiply the first element by $$$2^0$$$, the second element by $$$2^1$$$, ..., and the ($$$k+1$$$)-st element by $$$2^k$$$, then this subarray is sorted in strictly increasing order.  More formally, count the number of indices $$$1 \leq i \leq n - k$$$ such that $$$$$$2^0 \cdot a_i < 2^1 \cdot a_{i+1} < 2^2 \cdot a_{i+2} < \dots < 2^k \cdot a_{i+k}.$$$$$$

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$3 \leq n \leq 2 \cdot 10^5$$$, $$$1 \leq k < n$$$) — the length of the array and the number of inequalities. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the elements of the array. The sum of $$$n$$$ across all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer — the number of indices satisfying the condition in the statement.

NoteIn the first test case, both subarrays satisfy the condition:   $$$i=1$$$: the subarray $$$[a_1,a_2,a_3] = [20,22,19]$$$, and $$$1 \cdot 20 < 2 \cdot 22 < 4 \cdot 19$$$.  $$$i=2$$$: the subarray $$$[a_2,a_3,a_4] = [22,19,84]$$$, and $$$1 \cdot 22 < 2 \cdot 19 < 4 \cdot 84$$$.  In the second test case, three subarrays satisfy the condition:   $$$i=1$$$: the subarray $$$[a_1,a_2] = [9,5]$$$, and $$$1 \cdot 9 < 2 \cdot 5$$$.  $$$i=2$$$: the subarray $$$[a_2,a_3] = [5,3]$$$, and $$$1 \cdot 5 < 2 \cdot 3$$$.  $$$i=3$$$: the subarray $$$[a_3,a_4] = [3,2]$$$, and $$$1 \cdot 3 < 2 \cdot 2$$$.  $$$i=4$$$: the subarray $$$[a_4,a_5] = [2,1]$$$, but $$$1 \cdot 2 = 2 \cdot 1$$$, so this subarray doesn't satisfy the condition.

def solve(a, k)
  b = []

  (0...a.size - 1).each do |i|
    if a[i] < a[i + 1] * 2
      b.push(1)
    else
      b.push(1)
      b.push(0)
    end
  end
  b.push(1)
  # p b

  (0...b.size).each do |i|
    b[i] = (i > 0 ? b[i] + b[i - 1] : b[0])
  end

  result = 0

  k += 1
  (b.size - k + 1).times do |l|
    v = (l > 0 ? b[l + k - 1] - b[l - 1] : b[l + k - 1])
    # p [b[l, k], v, l, l + k]
    if v == k
      result += 1
    end
  end

  result
end

n = gets.to_i

n.times do
  size, s = gets.split.map(&:to_i)
  array = Array.new(size)
  array = gets.split.map(&:to_i)

  p solve(array, s)
end

def solve
    q = gets.split.map(&:to_i)
    a = gets.split.map(&:to_i)
    n = q[0]
    k = q[1]
    pref = Array.new(n)
    pref[0] = 0
    i = 1
    while i < n
        pref[i] = pref[i - 1]
        if 2 * a[i] > a[i - 1]
            pref[i] = pref[i] + 1
        end
        i = i + 1
    end
    ans = 0
    i = 0
    while i + k < n
        curr = pref[i + k] - pref[i]
        if curr == k
            ans = ans + 1
        end
        i = i + 1
    end
    puts ans
end

gets.to_i.times do
    solve
end

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

  l = 0
  r = 1
  cnt = 0
  ans = 0
  flag = false
  while l < n-k
    while r < n && (r <= l || cnt < k)
      if a[r-1] >= 2*a[r]
        l = r
        cnt = 0
        flag = true
        r += 1
        break
      else
        cnt += 1
        r += 1
      end
    end
    next flag = false if flag
    ans += 1 if cnt == k
    cnt -= 1
    l += 1
  end

  puts ans
end

gets.to_i.times do
  n, k = gets.split.map(&:to_i)
  xs = gets.split.map(&:to_i)
  counts = [0]
  xs.each_cons(2) do |a, b|
    if a < 2 * b
      counts[-1] += 1
    else
      counts << 0
    end
  end
  p counts.filter_map { |c| c - k + 1 if c >= k }.sum
end

main = -> {
    t = int
    t.times do
        n, k = ints
        a = ints
        prefix_sum = [0]
        (n - 1).times do |i|
            x = (a[i] < a[i + 1] * 2) ? 1 : 0
            prefix_sum << (prefix_sum[-1] + x)
        end

        puts (0 ... n - k).count { |i| prefix_sum[i + k] - prefix_sum[i] == k }
    end
}

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

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 ? 1 : 0] end
def YesNo t; puts $YesNo[t ? 1 : 0] end
def YESNO t; puts $YESNO[t ? 1 : 0] 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[]


Little penguin Polo likes permutations. But most of all he likes permutations of integers from 0 to n, inclusive.For permutation p = p0, p1, ..., pn, Polo has defined its beauty — number .Expression  means applying the operation of bitwise excluding "OR" to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is represented as "^" and in Pascal — as "xor".Help him find among all permutations of integers from 0 to n the permutation with the maximum beauty.

The single line contains a positive integer n (1 ≤ n ≤ 106).

In the first line print integer m the maximum possible beauty. In the second line print any permutation of integers from 0 to n with the beauty equal to m. If there are several suitable permutations, you are allowed to print any of them.

h,n=[],gets.to_i+1
p n*(n-1)
now=2**(Math.log2(n-1).floor+1)-1
(0..n-1).reverse_each do |i|
  if i==now/2
    now/=2
  end
if(h[i])
  next
end
h[i]=now-i
h[now-i]=i
end
puts h.join ' '

h,n=[],gets.to_i+1
p n*(n-1)
now=2**(Math.log2(n-1).floor+1)-1
(0..n-1).reverse_each do |i|
  if i==now/2
    now/=2
  end
if(h[i])
  next
end
h[i]=now^i
h[now^i]=i
end
puts h.join ' '

def f n
  cur = 1
  while cur <= n
    cur = cur * 2
  end
  cur /= 2
  i = cur
  cur -= 1
  while i <= n && cur >= 0
    $a[cur] = i
    $a[i] = cur
    $ans += 2 * (cur ^ i)
    i += 1
    cur -= 1
  end
  if cur >= 1
    f cur
  end
end

n = gets.to_i
$ans = 0
$a = Array.new(n + 1, 0)
f n
p $ans
puts $a.join(' ')


Polycarp is a music editor at the radio station. He received a playlist for tomorrow, that can be represented as a sequence a1, a2, ..., an, where ai is a band, which performs the i-th song. Polycarp likes bands with the numbers from 1 to m, but he doesn't really like others. We define as bj the number of songs the group j is going to perform tomorrow. Polycarp wants to change the playlist in such a way that the minimum among the numbers b1, b2, ..., bm will be as large as possible.Find this maximum possible value of the minimum among the bj (1 ≤ j ≤ m), and the minimum number of changes in the playlist Polycarp needs to make to achieve it. One change in the playlist is a replacement of the performer of the i-th song with any other group.

The first line of the input contains two integers n and m (1 ≤ m ≤ n ≤ 2000). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the performer of the i-th song.

In the first line print two integers: the maximum possible value of the minimum among the bj (1 ≤ j ≤ m), where bj is the number of songs in the changed playlist performed by the j-th band, and the minimum number of changes in the playlist Polycarp needs to make. In the second line print the changed playlist. If there are multiple answers, print any of them.

NoteIn the first sample, after Polycarp's changes the first band performs two songs (b1 = 2), and the second band also performs two songs (b2 = 2). Thus, the minimum of these values equals to 2. It is impossible to achieve a higher minimum value by any changes in the playlist. In the second sample, after Polycarp's changes the first band performs two songs (b1 = 2), the second band performs three songs (b2 = 3), and the third band also performs two songs (b3 = 2). Thus, the best minimum value is 2.

n, m  = gets.split.map(&:to_i)
array = gets.split.map(&:to_i)
count = Array.new(m + 1, 0)
label = []
array.each_with_index do |x, i|
  if x <= m and count[x] < n / m
    count[x] += 1
  else
    label[i] = true
  end
end
changes = 0
(1..m).each do |i|
  while(count[i] < n / m) do
    j = label.index(true)
    array[j] = i
    label[j] = false
    count[i] += 1
    changes  += 1
  end
end
puts "#{n / m} #{changes}"
array.each { |x| print "#{x} " }
puts

n, m = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
goal = n / m
cnt = Array.new(m + 1, 0)
cgable = []
a.each_with_index do |x, i|
  if x <= m && cnt[x] < goal
    cnt[x] += 1
  else
    cgable << i
  end
end
ans = 0
(1..m).each do |i|
  while cnt[i] < goal
    a[cgable.shift] = i
    cnt[i] += 1
    ans += 1
  end
end
puts "#{goal} #{ans}"
puts a.join(' ')

n, m  = gets.split.map(&:to_i)
array = gets.split.map(&:to_i)
count, replace = Array.new(m + 1, 0), []
array.each_with_index do |x, i|
  if x <= m and count[x] < n / m
    count[x] += 1
  else
    replace[i] = true
  end
end
changes = 0
(1..m).each do |i|
  if(count[i] < n / m)
    array[j = replace.index(true)] = i
    replace[j] = false
    count[i] += 1
    changes  += 1
  end
end

puts "#{n / m} #{changes}"
array.each { |x| print "#{x} " }


Given an array $$$a$$$ of $$$n$$$ elements, print any value that appears at least three times or print -1 if there is no such value.

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

For each test case, print any value that appears at least three times or print -1 if there is no such value.

NoteIn the first test case there is just a single element, so it can't occur at least three times and the answer is -1.In the second test case, all three elements of the array are equal to $$$2$$$, so $$$2$$$ occurs three times, and so the answer is $$$2$$$.For the third test case, $$$2$$$ occurs four times, so the answer is $$$2$$$.For the fourth test case, $$$4$$$ occurs three times, so the answer is $$$4$$$.For the fifth test case, $$$1$$$, $$$2$$$ and $$$3$$$ all occur at least three times, so they are all valid outputs.For the sixth test case, all elements are distinct, so none of them occurs at least three times and the answer is -1.

t = gets.chomp().to_i

while t > 0
    n = gets.chomp().to_i
    a = Array.new(n + 1, 0)
    ind = gets.chomp.split(' ').map!{ |num| num.to_i}

    ans = -1

    ind.each do |i|
        a[i] +=  1
        if a[i] == 3
            ans = i
        end
    end

    puts ans
    t -= 1

end

t = gets.chomp().to_i

while t > 0
    n = gets.chomp().to_i
    a = Array.new(n + 1, 0)
    ind = gets.chomp.split(' ').map!{ |num| num.to_i}

    ans = -1

    ind.each do |i|
        a[i] +=  1
        if a[i] == 3
            ans = i
        end
    end

    puts ans
    a = nil
    t -= 1
end

def triple(element)
  len = element[0]
  arr = element[1]
  map = {}
  arr.each do |i|
    map.key?(i) ? map[i] += 1 : map[i] = 1
  end
  map.each do |k, v|
    if v >= 3
      return k
    end
  end
  return -1
end

t = gets.chomp.to_i

inputs = []
(0..t-1).each do |i|
  len = gets.chomp.to_i
  input = gets.chomp
  input = input.split(" ").map(&:to_i)
  inputs.push([len, input])
end

inputs.each do |element|
  p triple(element)
end

gets.to_i.times do
  gets
  xs = gets.split.map(&:to_i)
  x = xs.tally.find { |x, count| count >= 3 }
  p x ? x[0] : -1
end

gets.to_i.times do
  gets
  a = gets.split.map(&:to_i).tally.sort_by { |_k, v| -v }
  if a[0][1] < 3
    puts(-1)
  else
    puts a[0][0]
  end
end


You've got an array a, consisting of n integers. The array elements are indexed from 1 to n. Let's determine a two step operation like that:  First we build by the array a an array s of partial sums, consisting of n elements. Element number i (1 ≤ i ≤ n) of array s equals . The operation x mod y means that we take the remainder of the division of number x by number y.  Then we write the contents of the array s to the array a. Element number i (1 ≤ i ≤ n) of the array s becomes the i-th element of the array a (ai = si). You task is to find array a after exactly k described operations are applied.

The first line contains two space-separated integers n and k (1 ≤ n ≤ 2000, 0 ≤ k ≤ 109). The next line contains n space-separated integers a1, a2, ..., an — elements of the array a (0 ≤ ai ≤ 109).

Print n integers  — elements of the array a after the operations are applied to it. Print the elements in the order of increasing of their indexes in the array a. Separate the printed numbers by spaces.

Mod = 1000000007
Pow = "111011100110101100101000000101"
Len = 30

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

def inverse(n)
  c = 1
  for i in 0...Len
    c = (c*c)%Mod
    if Pow[i] == '1'
      c = (c*n)%Mod
    end
  end
  return c
end

com = Array.new
com[0] = 1
s = Array.new
s[0] = a[0]
for i in 1...n
  com[i] = (com[i-1]*(k+i-1)*inverse(i))%Mod
  s[i] = 0
  for j in 0..i
    s[i] = (s[i]+a[i-j]*com[j])%Mod
  end
end

s.each {|x| print x, " "}

buf = gets.split(" ")
n = buf[0].to_i
k = buf[1].to_i
a = [0]
mod = 1000000007
for i in gets.split(" ")
    a << i.to_i
end
if k == 0 then
    1.upto(n) { |i|
        print a[i], " "
    }
else
    k -= 1
    now = 1
    sum = 0
    list = []
    1.upto(n) { |i|
        list << now % mod
        now *= i + k
        now /= i
    }
    1.upto(n) { |i|
        sum = 0
        i.downto(1) { |j|
            sum = sum + list[i - j] * a[j];
            sum %= mod
        }
        print sum, " "
    }
end

def modinv(num)
  a = num
  x = 0; nx = 1; b = 1000000007
  while(a>0) do
    q = b/a
    x -= q*nx
    x,nx = nx, x
    b -= q*a
    a,b = b,a
  end
  return x
end

n,k = gets.chomp.split.map(&:to_i)
array = gets.chomp.split.map(&:to_i)
mul = [1]
a = k
b = 1
1.upto(array.size - 1) do |i|
    mul[i] = (mul[i-1] * a * modinv(b)) % 1000000007
    a = a + 1
    b = b + 1
end
0.upto(array.size-1) do |i|
    ans = 0
    0.upto(i) do |j|
        ans += mul[i-j]*array[j]
    end
    print "#{ans%1000000007} "
end
puts

Mod = 1000000007
Pow = "111011100110101100101000000101"
Len = 30

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

def inverse(n)
  c = 1
  for i in 0...Len
    c = (c*c)%Mod
    if Pow[i] == '1'
      c = (c*n)%Mod
    end
  end
  return c
end

com = Array.new
com[0] = 1
s = Array.new
s[0] = a[0]
for i in 1...n
  com[i] = (com[i-1]*(k+i-1)*inverse(i))%Mod
  s[i] = 0
  for j in 0..i
    s[i] += a[i-j]*com[j]
  end
end

s.each {|x| print x, " "}

buf = gets.split(" ")
n = buf[0].to_i
k = buf[1].to_i
a = [0]
mod = 1000000007
for i in gets.split(" ")
    a << i.to_i
end
#p a
if k == 0 then
    1.upto(n) { |i|
        print a[i], " "
    }
else
    k -= 1
    now = 1
    sum = 0
    list = []
    1.upto(n) { |i|
        list << now % mod
        now /= i
        now *= i + k
    }
    1.upto(n) { |i|
        sum = 0
        i.downto(1) { |j|
            sum = sum + list[i - j] * a[j];
            sum %= mod
        }
        print sum, " "
    }
end

def modinv(num)
  a = num
  x = 0; nx = 1; b = 1000000007
  while(a>0) do
    q = b/a
    x -= q*nx
    x,nx = nx, x
    b -= q*a
    a,b = b,a
  end
  return x
end

n,k = gets.chomp.split.map(&:to_i)
array = gets.chomp.split.map(&:to_i)
mul = [1]
a = k
b = 1
1.upto(array.size - 1) do |i|
    mul[i] = (mul[i-1] * a * modinv(b)) % 1000000007
    a = a + 1
    b = b + 1
end
0.upto(array.size-1) do |i|
    ans = 0
    0.upto(i) do |j|
        ans += mul[i-j]*array[j]
    end
    print "#{ans} "
end
puts


Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya loves long lucky numbers very much. He is interested in the minimum lucky number d that meets some condition. Let cnt(x) be the number of occurrences of number x in number d as a substring. For example, if d = 747747, then cnt(4) = 2, cnt(7) = 4, cnt(47) = 2, cnt(74) = 2. Petya wants the following condition to fulfil simultaneously: cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. Petya is not interested in the occurrences of other numbers. Help him cope with this task.

The single line contains four integers a1, a2, a3 and a4 (1 ≤ a1, a2, a3, a4 ≤ 106).

On the single line print without leading zeroes the answer to the problem — the minimum lucky number d such, that cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. If such number does not exist, print the single number "-1" (without the quotes).

a1,a2,a3,a4=gets.split.map(&:to_i)
if a3==a4+1 then
	# 47が多い
	# 47を作っていく
	a1-=a3
	a2-=a3
	if a1<0 || a2<0 then #生成不能
		p -1
		exit
	end
	print "4"*a1
	print "47"*a3
	print "7"*a2
elsif a4==a3+1
	# 47が多い
	# 47を作っていく
	a1-=a4
	a2-=a4
	if a1<0 || a2<0 then #生成不能
		p -1
		exit
	end
	print 7
	print "4"*a1
	print "47"*a3
	print "7"*a2
	print 4
elsif a3==a4
	#47優先解法
	a1-=a3+1
	a2-=a3
	if a1<0||a2<0 then
		a1+=a3+1
		a2+=a3

		a1-=a3
		a2-=a3+1
		if a1<0||a2<0 then
			p -1
			exit
		end
		#74優先解法
		print 7
		print "4"*(a1+1)
		print "74"*(a3-1)
		print "7"*(a2+1)
		exit
	end
	print "4"*a1
	print 4
	print "74"*(a3-1)
	print "7"*(a2+1)
	print 4
else
	puts "-1"
end

a1,a2,a3,a4=gets.split.map(&:to_i)
if a3==a4+1 then
	# 47が多い
	# 47を作っていく
	a1-=a3
	a2-=a3
	if a1<0 || a2<0 then #生成不能
		p -1
		exit
	end
	a1.times{print 4}
	a3.times{print 47}
	a2.times{print 7}
elsif a4==a3+1
	# 47が多い
	# 47を作っていく
	a1-=a4
	a2-=a4
	if a1<0 || a2<0 then #生成不能
		p -1
		exit
	end
	print 7
	a1.times{print 4}
	a3.times{print 47}
	a2.times{print 7}
	print 4
elsif a3==a4
	#47優先解法
	a1-=a3+1
	a2-=a3
	if a1<0||a2<0 then
		a1+=a3+1
		a2+=a3

		a1-=a3
		a2-=a3+1
		#74優先解法
		print 7
		(a1+1).times{print 4}
		(a3-1).times{print 74}
		(a2+1).times{print 7}
		exit
	end
	a1.times{print 4}
	print 4
	(a3-1).times{print 74}
	(a2+1).times{ print 7 }
	print 4
else
	puts "-1"
end


During the "Russian Code Cup" programming competition, the testing system stores all sent solutions for each participant. We know that many participants use random numbers in their programs and are often sent several solutions with the same source code to check.Each participant is identified by some unique positive integer k, and each sent solution A is characterized by two numbers: x — the number of different solutions that are sent before the first solution identical to A, and k — the number of the participant, who is the author of the solution. Consequently, all identical solutions have the same x.It is known that the data in the testing system are stored in the chronological order, that is, if the testing system has a solution with number x (x > 0) of the participant with number k, then the testing system has a solution with number x - 1 of the same participant stored somewhere before.During the competition the checking system crashed, but then the data of the submissions of all participants have been restored. Now the jury wants to verify that the recovered data is in chronological order. Help the jury to do so.

The first line of the input contains an integer n (1 ≤ n ≤ 105) — the number of solutions. Each of the following n lines contains two integers separated by space x and k (0 ≤ x ≤ 105; 1 ≤ k ≤ 105) — the number of previous unique solutions and the identifier of the participant.

A single line of the output should contain «YES» if the data is in chronological order, and «NO» otherwise.

#$stdin.reopen('/home/chen/Desktop/input.txt', 'r')

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

if k*(n/2)>=n
	puts -1
else
	puts n*k
	(1..n).each do |ind|
		(1..k).each do |ind2|
			puts "#{ind} #{(ind+ind2-1)%n+1}"
		end
	end
end

=end

array = [-1]* (10**5+1)

n=gets.to_i
i=0

while i<n
	x,k=gets.split.map(&:to_i)
	if x==array[k]+1
		array[k] = x
		i+=1
		next
	end

	if x>array[k]+1
		puts 'NO'
		exit 0
	end
	i+=1
end

puts 'YES'

prevmax = Hash.new -1
n = gets.to_i
n.times do
  x,k = gets.split.map &:to_i
  d = x - prevmax[k]
  if d == 1
    prevmax[k] += 1
  elsif d > 1
    puts "NO"
    exit
  end
end

puts "YES"

parties = Array.new(10**5+1, nil)

n = gets.to_i

data = Array.new(n) { gets.chomp.split(' ').map(&:to_i) }

ans = 'YES'
data.each do |x, k|
    t = parties[k]
    if t
        if x > t + 1
            ans = 'NO'
            break
        elsif x == t + 1
            parties[k] = x
        end
    else
        if x == 0
            parties[k] = 0
        else
            ans = 'NO'
            break
        end
    end
end

puts ans

require 'set'
n = Integer gets
a = Array.new(10 ** 5)
cnt = Array.new(10 ** 5, 0)
for i in 0...10**5
  a[i] = [].to_set
end
for i in 0...n
  x, k = gets.split.map {|x| Integer x}
  k -= 1
  if !a[k].include?(x) && x != cnt[k]
    puts 'NO'
    exit
  end
  unless a[k].include?(x)
    a[k].add(cnt[k])
    cnt[k] += 1
  end
end
puts 'YES'

require 'set'
n = Integer gets
a = Array.new(10 ** 5, [].to_set)
cnt = 0
for i in 0...n
  x, k = gets.split.map {|x| Integer x}
  k -= 1
  if !a[k].include?(x) && x != cnt
    puts 'NO'
    exit
  end
  unless a[k].include?(x)
    a[k].add(cnt)
    cnt += 1
  end
end
puts 'YES'

require 'set'
n = Integer gets
a = Array.new(10 ** 5, [].to_set)
cnt = Array.new(10 ** 5, 0)
for i in 0...n
  x, k = gets.split.map {|x| Integer x}
  k -= 1
  if !a[k].include?(x) && x != cnt[k]
    puts 'NO'
    exit
  end
  unless a[k].include?(x)
    a[k].add(cnt[k])
    cnt[k] += 1
  end
end
puts 'YES'

require 'set'
n = Integer gets
a = Array.new(10 ** 5, [].to_set)
cnt = Array.new(10 ** 5, 0)
for i in 0...n
  x, k = gets.split.map {|x| Integer x}
  k -= 1
  if !a[k].include?(x) && x != cnt[k]
    puts 'NO'
    exit
  end
  unless a[k].include?(x)
    a[k].add(cnt[k])
  end
  cnt[k] += 1
end
puts 'YES'


Pasha loves his phone and also putting his hair up... But the hair is now irrelevant.Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of n row with m pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose any pixel and color it black. In particular, he can choose the pixel that is already black, then after the boy's move the pixel does not change, that is, it remains black. Pasha loses the game when a 2 × 2 square consisting of black pixels is formed. Pasha has made a plan of k moves, according to which he will paint pixels. Each turn in his plan is represented as a pair of numbers i and j, denoting respectively the row and the column of the pixel to be colored on the current move.Determine whether Pasha loses if he acts in accordance with his plan, and if he does, on what move the 2 × 2 square consisting of black pixels is formed.

The first line of the input contains three integers n, m, k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 105) — the number of rows, the number of columns and the number of moves that Pasha is going to perform.  The next k lines contain Pasha's moves in the order he makes them. Each line contains two integers i and j (1 ≤ i ≤ n, 1 ≤ j ≤ m), representing the row number and column number of the pixel that was painted during a move.

If Pasha loses, print the number of the move when the 2 × 2 square consisting of black pixels is formed. If Pasha doesn't lose, that is, no 2 × 2 square consisting of black pixels is formed during the given k moves, print 0.

h, w, k = gets.split.map( &:to_i )

board = Array.new( h + 2 ) { |idx| Array.new( w + 2, 0 ) }

k.times do | t |
	y, x = gets.split.map( &:to_i )
	board[y][x] = 1

	2.times do | i |
		2.times do | j |
			f = true
			2.times do | k |
				2.times do | l |
					f &= board[ y - 1 + i + k ][ x - 1 + j + l ] == 1
				end
			end

			if f
				puts t + 1
				exit 0
			end
		end
	end
end

puts 0

# http://codeforces.com/contest/508/problem/A
n, m, k = gets.chomp.split.map(&:to_i)
f = []
(n + 2).times { f << Array.new(m + 2) }

ans = nil
k.times do |i|
  y, x = gets.chomp.split.map(&:to_i)
  f[y][x] = 1

  points = [
    [f[y][x], f[y][x + 1], f[y + 1][x], f[y + 1][x + 1]],
    [f[y][x], f[y][x - 1], f[y + 1][x], f[y + 1][x - 1]],
    [f[y][x], f[y][x + 1], f[y - 1][x], f[y - 1][x + 1]],
    [f[y][x], f[y][x - 1], f[y - 1][x], f[y - 1][x - 1]]
  ]

  if points.find { |arr| arr.map(&:to_i).inject(0, :+) == 4 }
    ans = i + 1 if ans.nil?
  end
end

puts ans.nil? ? 0 : ans

DEBUG = false

class Board
  DELTA = [
    [ [-1, 0], [-1, 1],  [0, 1] ],
    [ [0, 1], [1, 1], [1, 0] ],
    [ [1, 0], [1, -1], [0, -1] ],
    [ [0, -1], [-1, -1], [-1, 0] ]
  ]
  attr_accessor :boards, :height, :width

  def initialize(height, width)
    self.boards = {}
    self.height = height
    self.width = width
  end

  def go(row, col)
    return false if row <= 0 || col <= 0 || row > self.height || col > self.width
    self.boards[[row, col]] = true
    return true if self.end_game?(row, col)
    return false
  end

  def end_game?(row, col)
    if DEBUG
      puts "----- Check step -----"
      puts "row = #{row}, col = #{col}"
    end

    Board::DELTA.any? do |delta_set|

      if DEBUG
        puts "----- Check data set -----"
      end

      delta_set.all? do |delta_row, delta_col|
        if DEBUG
          puts "#{row + delta_row} #{col + delta_col}"
        end

        (row + delta_row > 0) &&
        (col + delta_col > 0) &&
        (row  + delta_row <= self.height) &&
        (col + delta_col <= self.width) &&
        (self.boards[[row + delta_row, col + delta_col]] == true)
      end
    end
  end
end

height, width, steps = gets.strip.split(' ').map &:to_i

board = Board.new(height, width)

end_game_at = 0
1.upto(steps).each do |index|
  step_row, step_col = gets.strip.split(' ').map &:to_i
  end_game = board.go(step_row, step_col)
  if end_game
    end_game_at = index
    break
  end
end

puts end_game_at

DEBUG = false

class Board
  DELTA = [
    [ [-1, 0], [-1, 1],  [0, 1] ],
    [ [0, 1], [1, 1], [1, 0] ],
    [ [1, 0], [1, -1], [0, -1] ],
    [ [0, -1], [-1, -1], [-1, 0] ]
  ]
  attr_accessor :boards, :height, :width

  def initialize(height, width)
    self.boards = {}
    self.height = height
    self.width = width
  end

  def go(row, col)
    return false if row <= 0 || col <= 0 || row > self.height || col > self.width
    self.boards["#{row}_#{col}"] = true
    return true if self.end_game?(row, col)
    return false
  end

  def end_game?(row, col)
    if DEBUG
      puts "----- Check step -----"
      puts "row = #{row}, col = #{col}"
    end

    Board::DELTA.any? do |delta_set|

      if DEBUG
        puts "----- Check data set -----"
      end

      delta_set.all? do |delta_row, delta_col|
        if DEBUG
          puts "#{row + delta_row} #{col + delta_col}"
        end

        (row + delta_row > 0) &&
        (col + delta_col > 0) &&
        (row  + delta_row <= self.height) &&
        (col + delta_col <= self.width) &&
        (self.boards["#{row + delta_row}_#{col + delta_col}"] == true)
      end
    end
  end
end

height, width, steps = gets.strip.split(' ').map &:to_i

board = Board.new(height, width)

end_game_at = 0
1.upto(steps).each do |index|
  step_row, step_col = gets.strip.split(' ').map &:to_i
  end_game = board.go(step_row, step_col)
  if end_game
    end_game_at = index
    break
  end
end

puts end_game_at

class Board
  DELTA = [
    [ [-1, 0], [-1, 1],  [0, 1] ],
    [ [0, 1], [1, 1], [1, 0] ],
    [ [1, 0], [1, -1], [0, -1] ],
    [ [0, -1], [-1, -1], [-1, 0] ]
  ]
  attr_accessor :boards, :height, :width

  def initialize(height, width)
    self.boards = {}
    self.height = height
    self.width = width
  end

  def go(row, col)
    return false if row <= 0 || col <= 0 || row > self.height || col > self.width
    self.boards[row] ||= []
    self.boards[row][col] = true
    return true if self.end_game?(row, col)
    return false
  end

  def end_game?(row, col)
    Board::DELTA.any? do |delta_set|
      delta_set.all? do |delta_row, delta_col|
        (row + delta_row > 0) &&
        (col + delta_col > 0) &&
        (row  + delta_row <= self.height) &&
        (col + delta_col <= self.width) &&
        (!self.boards[row + delta_row].nil? && self.boards[row + delta_row][col + delta_col] == true)
      end
    end
  end
end

height, width, steps = gets.strip.split(' ').map &:to_i

board = Board.new(height, width)

end_game_at = 0
1.upto(steps).each do |index|
  step_row, step_col = gets.strip.split(' ').map &:to_i
  end_game = board.go(step_row, step_col)
  if end_game
    end_game_at = index
    break
  end
end

puts end_game_at

DEBUG = false

class Board
  DELTA = [
    [ [-1, 0], [-1, 1],  [0, 1] ],
    [ [0, 1], [1, 1], [1, 0] ],
    [ [1, 0], [1, -1], [0, -1] ],
    [ [0, -1], [-1, -1], [-1, 0] ]
  ]
  attr_accessor :boards, :height, :width

  def initialize(height, width)
    self.boards = {}
    self.height = height
    self.width = width
  end

  def go(row, col)
    return false if row <= 0 || col <= 0 || row > self.height || col > self.width
    self.boards["#{row}_#{col}".to_sym] = true
    return true if self.end_game?(row, col)
    return false
  end

  def end_game?(row, col)
    if DEBUG
      puts "----- Check step -----"
      puts "row = #{row}, col = #{col}"
    end

    Board::DELTA.any? do |delta_set|

      if DEBUG
        puts "----- Check data set -----"
      end

      delta_set.all? do |delta_row, delta_col|
        if DEBUG
          puts "#{row + delta_row} #{col + delta_col}"
        end

        (row + delta_row > 0) &&
        (col + delta_col > 0) &&
        (row  + delta_row <= self.height) &&
        (col + delta_col <= self.width) &&
        (self.boards["#{row + delta_row}_#{col + delta_col}".to_sym] == true)
      end
    end
  end
end

height, width, steps = gets.strip.split(' ').map &:to_i

board = Board.new(height, width)

end_game_at = 0
1.upto(steps).each do |index|
  step_row, step_col = gets.strip.split(' ').map &:to_i
  end_game = board.go(step_row, step_col)
  if end_game
    end_game_at = index
    break
  end
end

puts end_game_at

DELTA = [
  [ [-1, 0], [-1, 1],  [0, 1] ],
  [ [0, 1], [1, 1], [1, 0] ],
  [ [1, 0], [1, -1], [0, -1] ],
  [ [0, -1], [-1, -1], [-1, 0] ]
]
def go(boards, row, col, height, width)
  return if row <= 0 || col <= 0 || row > height || col > width
  boards[row] ||= []
  boards[row][col] = true
end

def end_game?(boards, row, col, height, width)
  DELTA.any? do |delta_set|
    delta_set.all? do |delta_row, delta_col|
      (row + delta_row > 0) &&
      (col + delta_col > 0) &&
      (row  + delta_row <= height) &&
      (col + delta_col <= width) &&
      (!boards[row + delta_row].nil? && boards[row + delta_row][col + delta_col] == true)
    end
  end
end

height, width, steps = gets.strip.split(' ').map &:to_i
boards = []
end_game_at = 0
1.upto(steps).each do |index|
  step_row, step_col = gets.strip.split(' ').map &:to_i
  go(boards, step_row, step_col, height, width)
  if end_game?(boards, step_row, step_col, height, width)
    end_game_at = index
    break
  end
end

puts end_game_at

DEBUG = false

class Board
  DELTA = [
    [ [-1, 0], [-1, 1],  [0, 1] ],
    [ [0, 1], [1, 1], [1, 0] ],
    [ [1, 0], [1, -1], [0, -1] ],
    [ [0, -1], [-1, -1], [-1, 0] ]
  ]
  attr_accessor :boards, :height, :width

  def initialize(height, width)
    self.boards = []
    self.height = height
    self.width = width
  end

  def go(row, col)
    return false if row <= 0 || col <= 0 || row > self.height || col > self.width
    self.boards[row] ||= []
    self.boards[row][col] = true
    return true if self.end_game?(row, col)
    return false
  end

  def end_game?(row, col)
    if DEBUG
      puts "----- Check step -----"
      puts "row = #{row}, col = #{col}"
    end

    Board::DELTA.any? do |delta_set|

      if DEBUG
        puts "----- Check data set -----"
      end

      delta_set.all? do |delta_row, delta_col|
        if DEBUG
          puts "#{row + delta_row} #{col + delta_col}"
        end

        (row + delta_row > 0) &&
        (col + delta_col > 0) &&
        (row  + delta_row <= self.height) &&
        (col + delta_col <= self.width) &&
        (!self.boards[row + delta_row].nil? && self.boards[row + delta_row][col + delta_col] == true)
      end
    end
  end
end

height, width, steps = gets.strip.split(' ').map &:to_i

board = Board.new(height, width)

end_game_at = 0
1.upto(steps).each do |index|
  step_row, step_col = gets.strip.split(' ').map &:to_i
  end_game = board.go(step_row, step_col)
  if end_game
    end_game_at = index
    break
  end
end

puts end_game_at

# File.open("5.txt","r") do |file|
	a=Array.new
	b=Array.new(1005)
	for i in 0..1004
		b[i]=Array.new(1005,0)
	end
	# str=file.gets.to_s
	str=gets.to_s
	a=str.split
	n=a[0].to_i
	m=a[1].to_i
	k=a[2].to_i
	h=0
	for r in 0..k
		# str=file.gets.to_s
		str=gets.to_s
		a=str.split
		i=a[0].to_i
		j=a[1].to_i
		b[i][j]=1
		if b[i-1][j-1]==1 and b[i-1][j]==1 and b[i][j-1]==1 and h==0
			h=r+1
		elsif b[i-1][j+1]==1 and b[i-1][j]==1 and b[i][j+1]==1 and h==0
			h=r+1
		elsif b[i+1][j-1]==1 and b[i+1][j]==1 and b[i][j-1]==1 and h==0
			h=r+1
		elsif b[i+1][j+1]==1 and b[i+1][j]==1 and b[i][j+1]==1 and h==0
			h=r+1
		end
	end
	if h==0
		puts 0
	else
		puts h
	end
# end

def checksquare(array,i,j)
	if array[i][j+1]==1 && array[i+1][j]==1 && array[i+1][j+1]==1
		return true
	end
	if array[i][j-1]==1 && array[i+1][j-1]==1 && array[i+1][j]==1
		return true
	end
	if array[i-1][j-1]==1 && array[i-1][j]==1 && array[i][j-1]==1
		return true
	end
	if array[i-1][j]==1 && array[i-1][j+1]==1 && array[i][j+1]==1
		return true
	end
	return false
end
n,m,k=gets.split().map{|i| Integer(i)}
pos=0
flag=1
array=Array.new
for i in 0..n
	array[i]=Array.new
	for j in 0..m
		array[i][j]=0
	end
end
start=1
while start<=k
	start+=1
	i,j=gets.split().map{|h| Integer(h)}
	array[i-1][j-1]=1
	if flag==1 && checksquare(array,i-1,j-1)==true
		pos=start-1
		flag=0
	end
end
puts pos

DEBUG = false

class Board
  DELTA = [
    [ [-1, 0], [-1, 1],  [0, 1] ],
    [ [0, 1], [1, 1], [1, 0] ],
    [ [1, 0], [1, -1], [0, -1] ],
    [ [0, -1], [-1, -1], [-1, 0] ]
  ]
  attr_accessor :boards, :height, :width

  def initialize(height, width)
    self.boards = {}
    self.height = height
    self.width = width
  end

  def go(row, col)
    return false if row <= 0 || col <= 0 || row > self.height || col > self.width
    self.boards["#{row}_#{col}"] = true
    if self.end_game?(row, col)
      return true
    end
    return false
  end

  def end_game?(row, col)
    if DEBUG
      puts "----- Check step -----"
      puts "row = #{row}, col = #{col}"
    end

    Board::DELTA.any? do |delta_set|

      if DEBUG
        puts "----- Check data set -----"
      end

      delta_set.all? do |delta_row, delta_col|
        if DEBUG
          puts "#{row + delta_row} #{col + delta_col}"
        end

        (row + delta_row > 0) &&
        (col + delta_col > 0) &&
        (row  + delta_row <= self.height) &&
        (row + delta_col <= self.width) &&
        (self.boards["#{row + delta_row}_#{col + delta_col}"] == true)
      end
    end
  end
end

height, width, steps = gets.strip.split(' ').map &:to_i

board = Board.new(height, width)

end_game_at = 0
1.upto(steps).each do |index|
  step_row, step_col = gets.strip.split(' ').map &:to_i
  end_game = board.go(step_row, step_col)
  if end_game
    end_game_at = index
    break
  end
end

puts end_game_at

# File.open("5.txt","r") do |file|
	a=Array.new
	b=Array.new(1005)
	for i in 0..1004
		b[i]=Array.new(1005,0)
	end
	# str=file.gets.to_s
	str=gets.to_s
	a=str.split
	n=a[0].to_i
	m=a[1].to_i
	k=a[2].to_i
	h=0
	for r in 0..k
		# str=file.gets.to_s
		str=gets.to_s
		a=str.split
		i=a[0].to_i
		j=a[1].to_i
		b[i][j]=1
		if b[i-1][j-1]==1 and b[i-1][j]==1 and b[i][j-1]==1
			h=r+1
		elsif b[i-1][j+1]==1 and b[i-1][j]==1 and b[i][j+1]==1
			h=r+1
		elsif b[i+1][j-1]==1 and b[i+1][j]==1 and b[i][j-1]==1
			h=r+1
		elsif b[i+1][j+1]==1 and b[i+1][j]==1 and b[i][j+1]==1
			h=r+1
		end
	end
	if h==0
		puts 0
	else
		puts h
	end
# end


Today the kindergarten has a new group of $$$n$$$ kids who need to be seated at the dinner table. The chairs at the table are numbered from $$$1$$$ to $$$4n$$$. Two kids can't sit on the same chair. It is known that two kids who sit on chairs with numbers $$$a$$$ and $$$b$$$ ($$$a \neq b$$$) will indulge if:   $$$gcd(a, b) = 1$$$ or,  $$$a$$$ divides $$$b$$$ or $$$b$$$ divides $$$a$$$. $$$gcd(a, b)$$$ — the maximum number $$$x$$$ such that $$$a$$$ is divisible by $$$x$$$ and $$$b$$$ is divisible by $$$x$$$.For example, if $$$n=3$$$ and the kids sit on chairs with numbers $$$2$$$, $$$3$$$, $$$4$$$, then they will indulge since $$$4$$$ is divided by $$$2$$$ and $$$gcd(2, 3) = 1$$$. If kids sit on chairs with numbers $$$4$$$, $$$6$$$, $$$10$$$, then they will not indulge.The teacher really doesn't want the mess at the table, so she wants to seat the kids so there are no $$$2$$$ of the kid that can indulge. More formally, she wants no pair of chairs $$$a$$$ and $$$b$$$ that the kids occupy to fulfill the condition above.Since the teacher is very busy with the entertainment of the kids, she asked you to solve this problem.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing an integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the number of kids.

Output $$$t$$$ lines, which contain $$$n$$$ distinct integers from $$$1$$$ to $$$4n$$$ — the numbers of chairs that the kids should occupy in the corresponding test case. If there are multiple answers, print any of them. You can print $$$n$$$ numbers in any order.

# frozen_string_literal: true

gets.chomp.to_i.times do |_m|
  n = gets.chomp.to_i
  (2 * n + 2).step(4 * n, 2) { |i| print i.to_s + ' ' }
  puts
end

t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  res = [4 * n]
  while res.size < n
    cur = res[-1]
    if cur <= 1
      break
    end
    while not(res.all? {|el| el.gcd(cur) > 1} &&
        res.all? {|el| el % cur > 0 && cur % el > 0})
      cur -= 1
    end
    res << cur
  end
  puts res.join(' ')
end

$\ = " "
gets.to_i.times do
  n = gets.to_i
  cur = 2 * n + 2
  while cur <= 4 * n do
    print cur
    cur += 2
  end
  puts
end


You are given $$$n$$$ sticks with positive integral length $$$a_1, a_2, \ldots, a_n$$$.You can perform the following operation any number of times (possibly zero):   choose one stick, then either increase or decrease its length by $$$1$$$. After each operation, all sticks should have positive lengths. What is the minimum number of operations that you have to perform such that it is possible to select three of the $$$n$$$ sticks and use them without breaking to form an equilateral triangle?An equilateral triangle is a triangle where all of its three sides have the same length.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 300$$$) — the number of sticks. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the lengths of the sticks. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$300$$$.

For each test case, print one integer on a single line — the minimum number of operations to be made.

NoteIn the first test case, you can increase the length of the first stick by $$$1$$$, then decrease the length of the third stick by $$$1$$$. In total, you perform $$$2$$$ operations, such that the three sticks form an equilateral triangle of side length $$$2$$$.In the fourth test case, you can decrease the length of the seventh stick by $$$1$$$. An equilateral triangle of side length $$$1$$$ can be selected and formed by the second, fourth, and seventh sticks.

def main
  t = inp.to_i
  t.times do
    n = inp.to_i
    a = mapint(inarr).sort!
    ans = 1 << 32
    0.upto(n - 1) do|i|
      (i + 1).upto(n - 1) do|j|
        (j + 1).upto(n - 1) do|k|
          dif = a[j] - a[i] + a[k] - a[j]
          ans = [ans, dif].min
        end
      end

    end
    puts ans

  end

end

# lib
def inp
  gets.chomp
end

def inarr
  gets.chomp.split
end

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

main

gets.to_i.times do
  n=gets.to_i
  a=gets.split.map(&:to_i).sort
  ans=Float::INFINITY
  a.each_cons(3) do |i,j,k|
    ans=[ans,j-i+k-j].min
  end
  puts ans
end


You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled:   All pixels in each column are of the same color.  The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y.

The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#".

In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists.

NoteIn the first test sample the picture after changing some colors can looks as follows:  .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows:  .#.#..#.#.

n, m, x, y = gets.split.map(&:to_i)
a = Array.new(n){gets.chomp.chars.to_a}
a = a.transpose.map{|_| _.count('#')}
w = [0] + [n * m] * m
b = [0] + [n * m] * m
x.upto(m) do |i|
    c = 0
    (i - 1).downto([i - y, 0].max) do |j|
        c += a[j]
        if i - j >= x
            w[i] = [w[i], b[j] + c].min
            b[i] = [b[i], w[j] + (i - j) * n - c].min
        end
    end
end
p [w.last, b.last].min


There was a big bank robbery in Tablecity. In order to catch the thief, the President called none other than Albert – Tablecity’s Chief of Police. Albert does not know where the thief is located, but he does know how he moves.Tablecity can be represented as 1000 × 2 grid, where every cell represents one district. Each district has its own unique name “(X, Y)”, where X and Y are the coordinates of the district in the grid. The thief’s movement is as Every hour the thief will leave the district (X, Y) he is currently hiding in, and move to one of the districts: (X - 1, Y), (X + 1, Y), (X - 1, Y - 1), (X - 1, Y + 1), (X + 1, Y - 1), (X + 1, Y + 1) as long as it exists in Tablecity. Below is an example of thief’s possible movements if he is located in district (7,1):Albert has enough people so that every hour he can pick any two districts in Tablecity and fully investigate them, making sure that if the thief is located in one of them, he will get caught. Albert promised the President that the thief will be caught in no more than 2015 hours and needs your help in order to achieve that.

The first line of output contains integer N – duration of police search in hours. Each of the following N lines contains exactly 4 integers Xi1, Yi1, Xi2, Yi2 separated by spaces, that represent 2 districts (Xi1, Yi1), (Xi2, Yi2) which got investigated during i-th hour. Output is given in chronological order (i-th line contains districts investigated during i-th hour) and should guarantee that the thief is caught in no more than 2015 hours, regardless of thief’s initial position and movement.   N ≤ 2015  1 ≤ X ≤ 1000  1 ≤ Y ≤ 2

В этой задаче нет примеров ввода-вывода.
This problem doesn't have sample input and output.

Смотрите замечание ниже.
See the note below.

NoteLet's consider the following output:25 1 50 28 1 80 2This output is not guaranteed to catch the thief and is not correct. It is given to you only to show the expected output format. There exists a combination of an initial position and a movement strategy such that the police will not catch the thief.Consider the following initial position and thief’s movement:In the first hour, the thief is located in district (1,1). Police officers will search districts (5,1) and (50,2) and will not find him.At the start of the second hour, the thief moves to district (2,2). Police officers will search districts (8,1) and (80,2) and will not find him.Since there is no further investigation by the police, the thief escaped!


Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva.You are given an encoding s of some word, your task is to decode it.

The first line contains a positive integer n (1 ≤ n ≤ 2000) — the length of the encoded word. The second line contains the string s of length n consisting of lowercase English letters — the encoding.

NoteIn the first example Polycarp encoded the word volga. At first, he wrote down the letter l from the position 3, after that his word looked like voga. After that Polycarp wrote down the letter o from the position 2, his word became vga. Then Polycarp wrote down the letter g which was at the second position, the word became va. Then he wrote down the letter v, then the letter a. Thus, the encoding looked like logva.In the second example Polycarp encoded the word no. He wrote down the letter n, the word became o, and he wrote down the letter o. Thus, in this example, the word and its encoding are the same.In the third example Polycarp encoded the word baba. At first, he wrote down the letter a, which was at the position 2, after that the word looked like bba. Then he wrote down the letter b, which was at the position 2, his word looked like ba. After that he wrote down the letter b, which was at the position 1, the word looked like a, and he wrote down that letter a. Thus, the encoding is abba.

n = gets.chomp.to_i
word = gets.chomp
empty = " "*n
middle = n%2 == 0 ? (n/2) - 1: n / 2
left = middle - 1
right = middle + 1
empty[ middle ] = word[0]

if n % 2 == 1
    for i in 1 ... n
        if i % 2 == 1
            empty[ left ] = word[i]
            left -= 1
        else
            empty[ right ] = word[i]
            right += 1
        end
    end
else
    for i in 1 ... n
        if i % 2 == 0
            empty[ left ] = word[i]
            left -= 1
        else
            empty[ right ] = word[i]
            right += 1
        end
    end
end

puts empty

n = gets.to_i
s = gets.chomp.reverse
x, y = "", ""
s.chars.each_with_index do |c, i|
  if i % 2 == 0
    x << c
  else
    y << c
  end
end
puts y + x.reverse

gets
s = gets.chomp

a = []
i = 0
if s.length % 2 != 0
  a.push(s[i])
  i += 1
end

while i < s.length
  a.unshift(s[i])
  a.push(s[i + 1])
  i += 2
end

puts a.join

n = gets.to_i
s = gets.chomp.chars

i = n
ans = ''
while !s.empty? do
  ss = s.shift
  if i.odd?
    ans += ss
  else
    ans = ss + ans
  end
  i += 1
end

puts ans

def g(ps)
	if ps.empty? == true then
		return []
	else
		p=ps.pop
		return (f(ps).unshift(p))
	end
end

def f(ps)
	if ps.empty? == true then
		return []
	else
		p=ps.pop
		return (g(ps).push(p))
	end
end

n=gets.to_i
s=gets.chomp

ps=(0..(n-1)).map{|i| i}
ps2=f(ps)
ps2.each{|i|
	print s[i]
}
print "\n"

n = gets.to_i
str = gets.chomp
res = Array.new
if n%2 != 0
  k = i =1
  ctr =1
  res[n/2] = str[0]
  while(k <= n/2)
      if (i == 1)
        res[n/2-k] = str[ctr]
        i = -1
      else
        res[n/2+k] = str[ctr]
        i=1
      end
      ctr +=1
      if(ctr%2 != 0)
        k = k+1
      end
  end
else
  k=1
  i=1
  ctr = 0
  while(k <= n/2)
      if (i == 1)
        res[n/2-k] = str[ctr]
        i = -1
      else
        res[n/2+k-1] = str[ctr]
        i=1
      end
      ctr +=1
      if(ctr%2 == 0)
        k = k+1
      end
  end
end

print res.join("")

n=gets.to_i
s=gets
r=''
for i in 0...n
    c=s[i]
    if (n+i).odd?
        r<<c
    else
        r=c+r
    end
end
puts r

n = gets.to_i
s = gets
a = []
i, d, sgn = (n - 1)/2, 0, n%2 == 0 ? -1 : 1
(0...n).each do |j|
  a[i] = s[j]
  d += 1
  sgn *= -1
  i += sgn*d
end
puts a.join

n=gets.to_i
s=gets
r=''
for i in 0...n
    c=s[i]
    if i.odd?
        r=c+r
    else
        r<<c
    end
end
puts r

n = gets.to_i
s = gets
a = []
i, d, sgn = (n - 1)/2, 0, 1
(0...n).each do |j|
  a[i] = s[j]
  d += 1
  sgn *= -1
  i += sgn*d
end
puts a.join

n = gets.to_i
s = gets
a = [nil]*n
i, d, sgn = (n - 1)/2, 0, 1
(0...n).each do |j|
  a[i] = s[j]
  d += 1
  sgn *= -1
  i += sgn*d
end
puts a.join

n = gets.to_i
s = gets.strip
a = [nil]*n
i, d, sgn = (n - 1)/2, 0, 1
(0...n).each do |j|
  a[i] = s[j]
  d += 1
  sgn *= -1
  i += sgn*d
end
puts a.join


Let's define a string <x> as an opening tag, where x is any small letter of the Latin alphabet. Each opening tag matches a closing tag of the type </x>, where x is the same letter.Tegs can be nested into each other: in this case one opening and closing tag pair is located inside another pair.Let's define the notion of a XML-text:   an empty string is a XML-text  if s is a XML-text, then s'=<a>+s+</a> also is a XML-text, where a is any small Latin letter  if s1, s2 are XML-texts, then s1+s2 also is a XML-text You are given a XML-text (it is guaranteed that the text is valid), your task is to print in the following form:   each tag (opening and closing) is located on a single line  print before the tag 2 * h spaces, where h is the level of the tag's nestedness.

The input data consists on the only non-empty string — the XML-text, its length does not exceed 1000 characters. It is guaranteed that the text is valid. The text contains no spaces.

Print the given XML-text according to the above-given rules.

str=gets
input=str[1..str.length-3].split("><")
depth=0
input.each{|a|
        if a[0]=="/" then
                depth-=1
                print "  "*depth
        else
                print "  "*depth
                depth+=1
        end
        print "<"+a+">\n"
}

line = STDIN.gets()

def rec(arr)
  def _rec(_arr, ret, depth)
    if _arr.empty?
      return ret
    end

    e = _arr.shift.shift

    if e.start_with?('/') then
      depth -= 1
      ret << (['  '] * depth).join('') + '<' + e + '>'
      return _rec(_arr,ret,depth)
    else
      ret << (['  '] * depth).join('') + '<' + e + '>'
      return _rec(_arr,ret,depth+1)
    end

  end

  return _rec(arr, [], 0)
end

rec(line.scan(/<([a-z\/]+)>/)).each do |l|
  puts l
end

xml = gets.strip!

de = []
while xml.size > 0
  r = xml.index ">"
  if xml[1] == "/"
    puts " " * (de.size - 1) * 2 + xml[0..r]
    de.pop
  else
    puts " " * (de.size) * 2 + xml[0..r]
    de << 1
  end
  xml = xml[r + 1..-1]
end

str = gets.chomp
h = []

while str.size > 0
  res = str.index ">"
  if str[1] == "/"
    puts " " * (h.size - 1) *2 + str[0..res]
    h.pop
  else
    puts " " * (h.size) *2 + str[0..res]
    h << 1
  end
  str = str[res + 1..-1]
end

s = gets.strip
depth = 0
s.scan(/<(\/)?.*?>/) do
  depth -= 1 if $1
  puts " "*(2*depth)+$&
  depth += 1 unless $1
end

xml = gets.strip!

de = []
while xml.size > 0
  r = xml.index ">"
  if xml[1] == "/"
    puts " " * (de.size - 1) * 2 + xml[0..r]
    de.pop
  else
    puts " " * (de.size) * 2 + xml[0..r]
    de << 1
  end
  xml = xml[r + 1..-1]
  puts xml
  puts xml.size
end


Not to be confused with chessboard.

The first line of input contains a single integer N (1 ≤ N ≤ 100) — the number of cheeses you have. The next N lines describe the cheeses you have. Each line contains two space-separated strings: the name of the cheese and its type. The name is a string of lowercase English letters between 1 and 10 characters long. The type is either "soft" or "hard. All cheese names are distinct.

9
brie soft
camembert soft
feta soft
goat soft
muenster soft
asiago hard
cheddar hard
gouda hard
swiss hard

6
parmesan hard
emmental hard
edam hard
colby hard
gruyere hard
asiago hard

n = gets.to_i
w = (0...n).map { gets.split[-1] } .group_by(&:itself).values.map(&:size).sort
w.unshift(0) until w.size == 2
p (1..1000).find { |i| [i*i / 2 - w[0], (i*i + 1 >> 1) - w[1]].all? { |v| v >= 0 } }


You are given two integers $$$n$$$ and $$$k$$$. Your task is to find if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers or not.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^7$$$).

For each test case, print the answer — "YES" (without quotes) if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers and "NO" otherwise.

NoteIn the first test case, you can represent $$$3$$$ as $$$3$$$.In the second test case, the only way to represent $$$4$$$ is $$$1+3$$$.In the third test case, you cannot represent $$$10$$$ as the sum of three distinct positive odd integers.In the fourth test case, you can represent $$$10$$$ as $$$3+7$$$, for example.In the fifth test case, you can represent $$$16$$$ as $$$1+3+5+7$$$.In the sixth test case, you cannot represent $$$16$$$ as the sum of five distinct positive odd integers.

def main
  t = gets.chomp.to_i
  t.times { solve }
end

def solve
  # n = gets.chomp.to_i
  n, k = gets.chomp.split.map(&:to_i)
  # S = gets.chomp.chars

  if (k == 1)
    # Here, we should check the oddness of n
    if (n%2 == 1)
      print "YES\n"
      return
    else
      print "NO\n"
      return
    end
  end

  # Here, k >= 2
  # minimum k-1 sum is k_sum. [0, k-2]
  k_sum = (k-1)*(k-1)
  remain = n - k_sum
  if (remain % 2 == 1 && remain > (2*k - 3))
    print "YES\n"
  else
    print "NO\n"
  end
end

main

t = gets.to_i
t.times do
  n, k = gets.split.map(&:to_i)
  puts (n >= k * k && (n - k) % 2 == 0) ? "YES" : "NO"
end

lines = []
for i in 0...gets.to_i
	lines << gets
end
def summable(n, k)
	return false if n - (k ** 2) < 0
	if n % 2 != k % 2
		return false
	end
	return true
end
def problem1(lines)
	for i in lines
		i = i.split(" ")
		summable(i[0].to_i, i[1].to_i) ? (puts "YES") : (puts "NO")
	end
end
problem1(lines)

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

  puts (n.modulo(2) == k.modulo(2) && n >= k ** 2) ? 'YES' : 'NO'
end

t = gets.to_i
t.times do
  n, k = gets.split.map(&:to_i)
  puts (n >= k && (n - k) % 2 == 0) ? "YES" : "NO"
end

lines = []
for i in 0...gets.to_i
	lines << gets
end
def summable(n, k)
	firstKSum = k ** 2
	if (n - k) % 2 == 1
		return false
	end
	return true
end
def problem1(lines)
	for i in lines
		i = i.split(" ")
		summable(i[0].to_i, i[1].to_i) ? (puts "YES") : (puts "NO")
	end
end
problem1(lines)

lines = []
for i in 0...gets.to_i
	lines << gets
end
def summable(n, k)
	if k == 1
		if n % 2 == 0
			return false
		end
		return true
	end
	for i in 2..k
		return true if n % i == k % i
	end
	return false
end
def problem1(lines)
	for i in lines
		i = i.split(" ")
		summable(i[0].to_i, i[1].to_i) ? (puts "YES") : (puts "NO")
	end
end
problem1(lines)

lines = []
for i in 0...gets.to_i
	lines << gets
end
def summable(n, k)
	if n % 2 != k % 2
		return false
	end
	return true
end
def problem1(lines)
	for i in lines
		i = i.split(" ")
		summable(i[0].to_i, i[1].to_i) ? (puts "YES") : (puts "NO")
	end
end
problem1(lines)


Every year a race takes place on the motorway between cities A and B. This year Vanya decided to take part in the race and drive his own car that has been around and bears its own noble name — The Huff-puffer.So, Vasya leaves city A on the Huff-puffer, besides, at the very beginning he fills the petrol tank with α liters of petrol (α ≥ 10 is Vanya's favorite number, it is not necessarily integer). Petrol stations are located on the motorway at an interval of 100 kilometers, i.e. the first station is located 100 kilometers away from the city A, the second one is 200 kilometers away from the city A, the third one is 300 kilometers away from the city A and so on. The Huff-puffer spends 10 liters of petrol every 100 kilometers. Vanya checks the petrol tank every time he passes by a petrol station. If the petrol left in the tank is not enough to get to the next station, Vanya fills the tank with α liters of petrol. Otherwise, he doesn't stop at the station and drives on. For example, if α = 43.21, then the car will be fuelled up for the first time at the station number 4, when there'll be 3.21 petrol liters left. After the fuelling up the car will have 46.42 liters. Then Vanya stops at the station number 8 and ends up with 6.42 + 43.21 = 49.63 liters. The next stop is at the station number 12, 9.63 + 43.21 = 52.84. The next stop is at the station number 17 and so on. You won't believe this but the Huff-puffer has been leading in the race! Perhaps it is due to unexpected snow. Perhaps it is due to video cameras that have been installed along the motorway which register speed limit breaking. Perhaps it is due to the fact that Vanya threatened to junk the Huff-puffer unless the car wins. Whatever the reason is, the Huff-puffer is leading, and jealous people together with other contestants wrack their brains trying to think of a way to stop that outrage.One way to do this is to mine the next petrol station where Vanya will stop. Your task is to calculate at which station this will happen and warn Vanya. You don't know the α number, however, you are given the succession of the numbers of the stations where Vanya has stopped. Find the number of the station where the next stop will be.

The first line contains an integer n (1 ≤ n ≤ 1000) which represents the number of petrol stations where Vanya has stopped. The next line has n space-separated integers which represent the numbers of the stations. The numbers are positive and do not exceed 106, they are given in the increasing order. No two numbers in the succession match. It is guaranteed that there exists at least one number α ≥ 10, to which such a succession of stops corresponds.

Print in the first line "unique" (without quotes) if the answer can be determined uniquely. In the second line print the number of the station where the next stop will take place. If the answer is not unique, print in the first line "not unique".

NoteIn the second example the answer is not unique. For example, if α = 10, we'll have such a sequence as 1, 2, 3, and if α = 14, the sequence will be 1, 2, 4.

gets
x = gets.split.map &:to_i
mina = []
maxa = []
x.map.with_index do |o,i|
    mina << Float(o)/(i+1)
    maxa << Float(o+1)/(i+1)-0.00000001
end
a = ([mina.max,1].max*(x.size+1)).floor
b = (maxa.min*(x.size+1)).floor
puts a == b ? "unique\n#{a}" : "not unique"


Polycarp wants to train before another programming competition. During the first day of his training he should solve exactly $$$1$$$ problem, during the second day — exactly $$$2$$$ problems, during the third day — exactly $$$3$$$ problems, and so on. During the $$$k$$$-th day he should solve $$$k$$$ problems.Polycarp has a list of $$$n$$$ contests, the $$$i$$$-th contest consists of $$$a_i$$$ problems. During each day Polycarp has to choose exactly one of the contests he didn't solve yet and solve it. He solves exactly $$$k$$$ problems from this contest. Other problems are discarded from it. If there are no contests consisting of at least $$$k$$$ problems that Polycarp didn't solve yet during the $$$k$$$-th day, then Polycarp stops his training.How many days Polycarp can train if he chooses the contests optimally?

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of contests. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$) — the number of problems in the $$$i$$$-th contest.

Print one integer — the maximum number of days Polycarp can train if he chooses the contests optimally.

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

now = 1
a.each { |i| now += 1 if i >= now }
puts now - 1

len = gets.to_i
arr = gets.split(' ').map(&:to_i).sort()
for x in 1..len
    n = x
    while n > 0 && arr.length > 0
        n -= arr[0]
        arr.shift()
    end
    while arr.length > 0 && arr[0] <= x
        arr.shift()
    end
    if arr.length == 0
        puts "#{x}"
        break
    end
end
if arr.length > 0
    puts "#{len}"
end


Monocarp plays a computer game (yet again!). This game has a unique trading mechanics.To trade with a character, Monocarp has to choose one of the items he possesses and trade it for some item the other character possesses. Each item has an integer price. If Monocarp's chosen item has price $$$x$$$, then he can trade it for any item (exactly one item) with price not greater than $$$x+k$$$.Monocarp initially has $$$n$$$ items, the price of the $$$i$$$-th item he has is $$$a_i$$$. The character Monocarp is trading with has $$$m$$$ items, the price of the $$$i$$$-th item they have is $$$b_i$$$. Monocarp can trade with this character as many times as he wants (possibly even zero times), each time exchanging one of his items with one of the other character's items according to the aforementioned constraints. Note that if Monocarp gets some item during an exchange, he can trade it for another item (since now the item belongs to him), and vice versa: if Monocarp trades one of his items for another item, he can get his item back by trading something for it.You have to answer $$$q$$$ queries. Each query consists of one integer, which is the value of $$$k$$$, and asks you to calculate the maximum possible total cost of items Monocarp can have after some sequence of trades, assuming that he can trade an item of cost $$$x$$$ for an item of cost not greater than $$$x+k$$$ during each trade. Note that the queries are independent: the trades do not actually occur, Monocarp only wants to calculate the maximum total cost he can get.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the prices of the items Monocarp has. The third line contains $$$m$$$ integers $$$b_1, b_2, \dots, b_m$$$ ($$$1 \le b_i \le 10^9$$$) — the prices of the items the other character has. The fourth line contains $$$q$$$ integers, where the $$$i$$$-th integer is the value of $$$k$$$ for the $$$i$$$-th query ($$$0 \le k \le 10^9$$$).

For each query, print one integer — the maximum possible total cost of items Monocarp can have after some sequence of trades, given the value of $$$k$$$ from the query.

class Unionfind
  attr_accessor(:par, :size)

  def initialize(n)
    @par = Array.new(n+1)
    (n+1).times do |i|
      @par[i] = i
    end
    @size = Array.new(n+1,1)
  end

  def root(x)
    while @par[x] != x
      x = @par[@par[x]]
      @par[x] = @par[@par[x]]
    end
    x
  end

  def unite(x,y)
    rx = root(x)
    ry = root(y)
    if rx != ry
      @size[ry] += size(rx)
      @par[rx] = ry
    end
  end

  def same(x,y)
    return root(x)==root(y)
  end

  def size(x)
    if @par[x] == x
      @size[x]
    else
      size(root(par[x]))
    end
  end

end

n,m,Q = gets.split.map(&:to_i)
a = gets.split.map(&:to_i).sort
b = gets.split.map(&:to_i).sort
q = gets.split.map(&:to_i)
query = []
Q.times do |i|
  query << [q[i],i]
end
query.sort_by!{|q,i|q}
hash = Hash.new(-1)
dist = {}
dists = []
arr = (a + b).sort
len = n+m
len.times do |i|
  hash[arr[i]] = i if hash[arr[i]] == -1
  if i > 0
    d = arr[i] - arr[i-1]
    if dist[d] == nil
      dist[d] = []
      dists << d
    end
    dist[d] << i-1
  end
end
dists_len = dists.size
dists.sort!

uf = Unionfind.new(len)
have = Hash.new(0)
start = Hash.new(-1)
finish = Hash.new(-1)
a.each do |v|
  index = hash[v]
  have[index] += 1
  start[index] = index
  finish[index] = index
end
b.each do |v|
  index = hash[v]
  start[index] = index
  finish[index] = index
end
len.times do |i|
  if start[i] == -1
    start[i] = i
    finish[i] = i
  end
end

sum = a.sum
acm = [0]
len.times do |i|
  acm[i+1] = acm[i] + arr[i]
end

ans = []
i = 0
j = 0
while i < Q
  k = query[i][0]
  while j < dists_len && dists[j] <= k
    dist[dists[j]].each do |from|
      root_from = uf.root(from)
      root_to = uf.root(from+1)
      have1 = have[root_from]
      have2 = have[root_to]
      start1 = start[root_from]
      finish1 = finish[root_from]
      finish2 = finish[root_to]
      uf.unite(from,from+1)
      root = uf.root(from)
      have[root] = have1+have2
      start[root] = start1
      finish[root] = finish2
      if have1 > 0 && dists[j] != 0
        sum -= acm[finish1+1] - acm[finish1+1-have1]
        sum -= acm[finish2+1] - acm[finish2+1-have2]
        sum += acm[finish2+1] - acm[finish2+1-have1-have2]
      end
    end
    j += 1
  end
  ans[query[i][1]] = sum
  i += 1
end
puts ans

class Unionfind
  attr_accessor(:par, :size)

  def initialize(n)
    @par = Array.new(n+1)
    (n+1).times do |i|
      @par[i] = i
    end
    @size = Array.new(n+1,1)
  end

  def root(x)
    while @par[x] != x
      x = @par[@par[x]]
      @par[x] = @par[@par[x]]
    end
    x
  end

  def unite(x,y)
    rx = root(x)
    ry = root(y)
    if rx != ry
      @size[ry] += size(rx)
      @par[rx] = ry
    end
  end

  def same(x,y)
    return root(x)==root(y)
  end

  def size(x)
    if @par[x] == x
      @size[x]
    else
      size(root(par[x]))
    end
  end

end

n,m,Q = gets.split.map(&:to_i)
a = gets.split.map(&:to_i).sort
b = gets.split.map(&:to_i).sort
q = gets.split.map(&:to_i)
query = []
Q.times do |i|
  query << [q[i],i]
end
query.sort_by!{|q,i|q}
hash = Hash.new(-1)
dist = {}
dists = []
arr = (a + b).sort
len = n+m
len.times do |i|
  hash[arr[i]] = i if hash[arr[i]] == -1
  if i > 0
    d = arr[i] - arr[i-1]
    if dist[d] == nil
      dist[d] = []
      dists << d
    end
    dist[d] << i-1
  end
end
dists_len = dists.size
dists.sort!

uf = Unionfind.new(len)
have = Hash.new(0)
start = Hash.new(-1)
finish = Hash.new(-1)
a.each do |v|
  index = hash[v]
  have[index] += 1
  start[index] = index
  finish[index] = index
end
b.each do |v|
  index = hash[v]
  start[index] = index
  finish[index] = index
end

sum = a.sum
acm = [0]
len.times do |i|
  acm[i+1] = acm[i] + arr[i]
end

ans = []
i = 0
j = 0
while i < Q
  k = query[i][0]
  while j < dists_len && dists[j] <= k
    dist[dists[j]].each do |from|
      root_from = uf.root(from)
      root_to = uf.root(from+1)
      have1 = have[root_from]
      have2 = have[root_to]
      start1 = start[root_from]
      finish1 = finish[root_from]
      finish2 = finish[root_to]
      uf.unite(from,from+1)
      root = uf.root(from)
      have[root] = have1+have2
      start[root] = start1
      finish[root] = finish2
      if have1 > 0 && dists[j] != 0
        sum -= acm[finish1+1] - acm[finish1+1-have1]
        sum -= acm[finish2+1] - acm[finish2+1-have2]
        sum += acm[finish2+1] - acm[finish2+1-have1-have2]
      end
    end
    j += 1
  end
  ans[query[i][1]] = sum
  i += 1
end
puts ans


There is a square painted on a piece of paper, the square's side equals n meters. John Doe draws crosses on the square's perimeter. John paints the first cross in the lower left corner of the square. Then John moves along the square's perimeter in the clockwise direction (first upwards, then to the right, then downwards, then to the left and so on). Every time he walks (n + 1) meters, he draws a cross (see picture for clarifications).John Doe stops only when the lower left corner of the square has two crosses. How many crosses will John draw?   The figure shows the order in which John draws crosses for a square with side 4. The lower left square has two crosses. Overall John paints 17 crosses.

The first line contains integer t (1 ≤ t ≤ 104) — the number of test cases.  The second line contains t space-separated integers ni (1 ≤ ni ≤ 109) — the sides of the square for each test sample.

For each test sample print on a single line the answer to it, that is, the number of crosses John will draw as he will move along the square of the corresponding size. Print the answers to the samples in the order in which the samples are given in the input. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

n = gets.to_i
input = gets.split.map(&:to_i)

for i in input
  if i%2 == 0 then puts i*4+1
  else
    if i%4 == 1
      puts i*2+1
    else
      puts i+1
    end
  end
end

def NOD(x, y)
    if x!=0
        return NOD((y%x),x)
    else
        return y
    end
end

def NOK(x,y)
    return (x*y)/NOD(x,y)
end

total = gets.chomp.to_i
line= gets.chomp
numbers=line.split(" ", total)
numbers.each do |number|
    number=number.chomp.to_i
    number=number+1
    mod=4*number-4
    puts NOK(mod, number)/number+1
end

"""(c) gorlum0 [at] gmail.com"""

def solve(n)
  g = (4*n).gcd(n+1)
  4*n / g + 1
end

t = STDIN.gets.to_i
ns = STDIN.gets.split.map(&:to_i)
ns.each do |n|
  puts solve(n)
end

"""(c) gorlum0 [at] gmail.com"""

def solve(n)
  g = (4*n).gcd(n+1)
  4*n / g + 1
end

def main
t = gets.to_i
ns = gets.split.map(&:to_i)
ns.each do |n|
  puts solve(n)
end
end

main

"""(c) gorlum0 [at] gmail.com"""

def solve(n)
  g = (4*n).gcd(n+1)
  4*n / g + 1
end

def main
  t = gets.to_i
  ns = gets.split.map(&:to_i)
  ns.each do |n|
    puts solve(n)
  end
end

if __FILE__ == $0
  main
end

"""(c) gorlum0 [at] gmail.com"""

def solve(n)
  g = (4*n).gcd(n+1)
  4*n / g + 1
end

t = gets.to_i
ns = gets.split.map(&:to_i)
ns.each do |n|
  puts solve(n)
end

t = gets.to_i
a = gets.split(" ").map(&:to_i)
a.each do |i|
    j = (i+1).gcd(4*i)
    p (4*i/j)+1
end

t = gets.to_i
array = gets.split.map(&:to_i)
array.each do |n|
  if n % 4 == 3
    puts n+1
  elsif n % 4 == 1
    puts 2*n+1
  else
    puts 4*n+1
  end
end

#!/usr/bin/ruby

t = $stdin.gets.to_i
ns = $stdin.gets.split.map(&:to_i)
ns.each do |n|
  g = (n+1).gcd(4*n)
  puts (4*n/g)+1
end

gets;gets.split.map{ |v| v=v.to_i; if v.even?; 4*v+1; else if (v+1)%4>0; 2*v+2*v/(v+1); else; v+1; end; end; }.map{ |v| p v }

#!/usr/bin/ruby

def gcd(a, b)
	return (b != 0) ? gcd(b, a % b) : a
end

gets
gets.split.map(&:to_i).each do |n|
	puts (n * 4) / gcd(n * 4, n + 1) + 1
end

#!/usr/bin/ruby

def gcd(a, b)
	return (b != 0) ? gcd(b, a % b) : a
end

def solve(n)
	puts (n * 4) / gcd(n * 4, n + 1) + 1
end

gets
gets.split.map(&:to_i).map{ |n| solve(n) }

gets
gets.split.map { |x| x.to_i } . map { |x| x*4 / (x*4).gcd(x+1) } . each { |x| puts x+1}

n = gets.to_i
input = gets.split.map(&:to_i)

for i in input
  if i%2 == 0 then puts i*2+1
  else
    if i == 1
      puts 2
    elsif i%4 == 1
      puts i*2+1
    else
      puts i+1
    end
  end
end

n = gets.to_i
input = gets.split.map(&:to_i)

for i in input
  if i%2 == 0 then puts i*4+1
  else
    if i == 1
      puts 2
    elsif i%4 == 1
      puts i*2+1
    else
      puts i+1
    end
  end
end

t = gets.to_i
array = gets.split.map(&:to_i)
array.each do |n|
  a = 4 * n
  b = n + 1
  c = 0
  count = 0
  while c != 0
    c = a - b
    if c < 0
      c = a + c
    end
    count += 1
  end
  puts count
end

t = gets.to_i
array = gets.split.map(&:to_i)
array.each do |n|
  if n == 1
    puts 3
  elsif n == 3
    puts 4
  else
    puts n * 4 + 1
  end
end

t = gets.to_i
array = gets.split.map(&:to_i)
array.each do |n|
  puts n * 4 + 1
end

t = gets.to_i
array = gets.split.map(&:to_i)
array.each do |n|
  if n == 1
    puts 3
  else
    puts n * 4 + 1
  end
end

t = gets.to_i
array = gets.split.map(&:to_i)
array.each do |n|
  if n == 1
    puts 2
  else
    puts n * 4 + 1
  end
end

t = gets.to_i
array = gets.split.map(&:to_i)
a = 0
array.each do |n|
  a += 1
  print n * 4 + 1
  if a != t
    print "\n"
  end
end

gets
gets.split.map { |x| x.to_i } . map { |x| x*4 / x.gcd(x+1) } . each { |x| puts x+1}