Sho has an array $$$a$$$ consisting of $$$n$$$ integers. An operation consists of choosing two distinct indices $$$i$$$ and $$$j$$$ and removing $$$a_i$$$ and $$$a_j$$$ from the array.For example, for the array $$$[2, 3, 4, 2, 5]$$$, Sho can choose to remove indices $$$1$$$ and $$$3$$$. After this operation, the array becomes $$$[3, 2, 5]$$$. Note that after any operation, the length of the array is reduced by two.After he made some operations, Sho has an array that has only distinct elements. In addition, he made operations such that the resulting array is the longest possible. More formally, the array after Sho has made his operations respects these criteria:   No pairs such that ($$$i < j$$$) and $$$a_i = a_j$$$ exist.  The length of $$$a$$$ is maximized. Output the length of the final array.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 50$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_i$$$ ($$$1 \leq a_i \leq 10^4$$$) — the elements of the array.

For each test case, output a single integer — the length of the final array. Remember that in the final array, all elements are different, and its length is maximum.

NoteFor the first test case Sho can perform operations as follows:   Choose indices $$$1$$$ and $$$5$$$ to remove. The array becomes $$$[2, 2, 2, 3, 3, 3] \rightarrow [2, 2, 3, 3]$$$.  Choose indices $$$1$$$ and $$$4$$$ to remove. The array becomes $$$[2, 2, 3, 3] \rightarrow [2, 3]$$$.  The final array has a length of $$$2$$$, so the answer is $$$2$$$. It can be proven that Sho cannot obtain an array with a longer length.For the second test case Sho can perform operations as follows:   Choose indices $$$3$$$ and $$$4$$$ to remove. The array becomes $$$[9, 1, 9, 9, 1] \rightarrow [9, 1, 1]$$$.  Choose indices $$$1$$$ and $$$3$$$ to remove. The array becomes $$$[9, 1, 1] \rightarrow [1]$$$.  The final array has a length of $$$1$$$, so the answer is $$$1$$$. It can be proven that Sho cannot obtain an array with a longer length.

n = gets.to_i

n.times do
  m = gets.to_i

  hashmap = Hash.new(0)
  initial_size = 0
  gets.split(" ").each do |chunk|
    initial_size += 1
    hashmap[chunk] += 1
  end

  result = 0
  hashmap.each_value do |value|
    result += value - 1 if value > 1
  end

  result += 1 if result % 2 == 1

  p (initial_size - result)
end

t = gets.to_i
t.times do
    n=gets.to_i
    d=gets.split.map &:to_i
    uniques = d.uniq.size
    if uniques%2==n%2
        puts uniques
    else
        puts uniques - 1
    end
end

$cnt = []

def solve
    n = gets.to_i
    a = gets.split.map(&:to_i)
    a.each do |x|
        $cnt[x] = $cnt[x] + 1
    end
    ans = 0
    even = 0
    a.each do |x|
        if $cnt[x] % 2 == 1
            ans = ans + 1
        elsif $cnt[x] > 0
            even = even + 1
        end
        $cnt[x] = 0
        if even == 2
            ans = ans + 2
            even = 0
        end
    end
    puts ans
end

maxn = 10005
maxn.times do
    $cnt.append(0)
end
gets.to_i.times do
    solve
end

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  at = a.tally
  e = a.uniq.size
  if n.even?
    if e.even?
      puts e
    else
      puts e-1
    end
  else
    if e.odd?
      puts e
    else
      puts e-1
    end
  end
end

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map(&:to_i).tally
  puts a.size - (n - a.size) % 2
end

main = -> {
  t = int
  t.times do
      n = int
      a = ints

      double_count = 0
      a.tally.each_value do |c|
          double_count += c - 1
      end

      puts n - double_count.div_ceil(2) * 2
  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[]

gets.to_i.times do
  gets
  xs = gets.split.map(&:to_i)
  ys = xs.uniq
  diff = xs.size - ys.size
  p ys.size - (diff & 1)
end


The average miner Vaganych took refresher courses. As soon as a miner completes the courses, he should take exams. The hardest one is a computer test called "Testing Pants for Sadness".The test consists of n questions; the questions are to be answered strictly in the order in which they are given, from question 1 to question n. Question i contains ai answer variants, exactly one of them is correct. A click is regarded as selecting any answer in any question. The goal is to select the correct answer for each of the n questions. If Vaganych selects a wrong answer for some question, then all selected answers become unselected and the test starts from the very beginning, from question 1 again. But Vaganych remembers everything. The order of answers for each question and the order of questions remain unchanged, as well as the question and answers themselves.Vaganych is very smart and his memory is superb, yet he is unbelievably unlucky and knows nothing whatsoever about the test's theme. How many clicks will he have to perform in the worst case?

The first line contains a positive integer n (1 ≤ n ≤ 100). It is the number of questions in the test. The second line contains space-separated n positive integers ai (1 ≤ ai ≤ 109), the number of answer variants to question i.

Print a single number — the minimal number of clicks needed to pass the test it the worst-case scenario.  Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.

NoteNote to the second sample. In the worst-case scenario you will need five clicks:   the first click selects the first variant to the first question, this answer turns out to be wrong.  the second click selects the second variant to the first question, it proves correct and we move on to the second question;  the third click selects the first variant to the second question, it is wrong and we go back to question 1;  the fourth click selects the second variant to the first question, it proves as correct as it was and we move on to the second question;  the fifth click selects the second variant to the second question, it proves correct, the test is finished.

gets
s = 0
gets.split.map(&:to_i).each_with_index do |a, i|
	s += (a - 1) * (i + 1) + 1
end
puts s

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

ans=0
n.times{|i|
        ans+=a[i]*(1+i)
        ans-=i
}
p ans

n = gets.to_i
arr = gets.split(' ').map(&:to_i)
ans = 0
n.times do |i|
    ans += (arr[i] - 1) * (1 + i)
end
ans += n
print (ans)

n = gets.to_i
arr = gets.split(' ').map(&:to_i)
ans = 0
n.times do |i|
    ans += (arr[i] - 1) * (1 + i)
end
ans += n
print ans

n = gets.to_i
a = gets.split(' ').map(&:to_i)
ans = 0
n.times do |i|
  ans += a[i] * (1+i)
  ans -= i
end
puts ans

n = gets.to_i
arr = gets.split(" ").map(&:to_i)
dp = [1]
ans = 0
arr.reverse_each do |e|
	dp << e + dp[-1] - 1
	ans += dp[-1]
end
puts ans

n = gets.to_i
a = gets.split.collect{|i| i.to_i}
ans = 0
n.times do |i|
    ans += (i+1)*(a[i]-1)+1
end
puts ans

n = gets.chomp.to_i
a = gets.chomp.split(/ /).map!{|x| x.to_i}
sum = 0
for i in 0..n-1
  sum += a[i]
  sum += (i * (a[i]-1))
end
puts sum

#!/usr/bin/ruby
noq = gets.chop.to_i
qp = gets.chop.split(' ');
clicks = 0
for i in 0..qp.count-1
        clicks += qp[i].to_i*(i+1) - i;
end
puts clicks.to_s

#!/usr/bin/ruby
noq = gets.chop.to_i
qp = gets.chop.split(' ');
clicks = 0
for i in 0..qp.count-1
	clicks += qp[i].to_i
	clicks += qp[i].to_i*i - i;
end
puts clicks.to_s

n=gets.to_i
res,x=0,0
gets.split.map(&:to_i).reverse.each {|a|
    res+=a+x
    x+=a-1
}
p res

#!/usr/bin/env ruby
#

def solve ai
  ret = ai[0]
  (1..ai.length-1).each do |i|
    ret += i*(ai[i]-1)
    ret += ai[i]
  end
  ret
end

n=STDIN.gets.to_i
arr = STDIN.gets.split(" ").map {|i| i.to_i}
p solve(arr)

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

ans=0
n.times{|i|
        ans+=a[i]*(1+i)
        ans-=1
}
p ans+1

#!/usr/bin/ruby
noq = gets.chop.to_i
qp = gets.chop.split(' ');
clicks = 0
for i in 0..qp.count-1
        clicks += qp[i].to_i*i;
end
puts clicks.to_s

#!/usr/bin/ruby
noq = gets.chop.to_i
qp = gets.chop.split(' ');
clicks = 0
for i in 0..qp.count-1
	clicks += qp[i].to_i
end
if qp.count > 1
	for i in 1..qp.count-1
		clicks+= qp[i].to_i
	end
end
clicks -= noq-1
puts clicks.to_s

n=gets.to_i
res=0
gets.split.map(&:to_i).each {|a|
    n-=1
    res+=a
    res+=n if a>1
}
p res

#!/usr/bin/env ruby
#

def solve ai
  ret = ai[0]
  (1..ai.length-1).each do |i|
    ret += i #if ai[i] > 1
    ret += ai[i]
  end
  ret
end

n=STDIN.gets.to_i
arr = STDIN.gets.split(" ").map {|i| i.to_i}
p solve(arr)

#!/usr/bin/env ruby
#

def solve ai
  ret = ai[0]
  (1..ai.length-1).each do |i|
    ret += i if ai[i] > 1
    ret += ai[i]
  end
  ret
end

n=STDIN.gets.to_i
arr = STDIN.gets.split(" ").map {|i| i.to_i}
p solve(arr)

#!/usr/bin/env ruby
#

def solve ai
  ret = ai[0]
  (1..ai.length-1).each do |i|
    ret *= ai[i]-1
    ret += ai[i]
  end
  ret
end

n=STDIN.gets.to_i
arr = STDIN.gets.split(" ").map {|i| i.to_i}
p solve(arr)


$$$n$$$ students attended the first meeting of the Berland SU programming course ($$$n$$$ is even). All students will be divided into two groups. Each group will be attending exactly one lesson each week during one of the five working days (Monday, Tuesday, Wednesday, Thursday and Friday), and the days chosen for the groups must be different. Furthermore, both groups should contain the same number of students.Each student has filled a survey in which they told which days of the week are convenient for them to attend a lesson, and which are not. Your task is to determine if it is possible to choose two different week days to schedule the lessons for the group (the first group will attend the lesson on the first chosen day, the second group will attend the lesson on the second chosen day), and divide the students into two groups, so the groups have equal sizes, and for each student, the chosen lesson day for their group is convenient.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of students. The $$$i$$$-th of the next $$$n$$$ lines contains $$$5$$$ integers, each of them is $$$0$$$ or $$$1$$$. If the $$$j$$$-th integer is $$$1$$$, then the $$$i$$$-th student can attend the lessons on the $$$j$$$-th day of the week. If the $$$j$$$-th integer is $$$0$$$, then the $$$i$$$-th student cannot attend the lessons on the $$$j$$$-th day of the week.  Additional constraints on the input: for each student, at least one of the days of the week is convenient, the total number of students over all testcases doesn't exceed $$$10^5$$$.

For each testcase print an answer. If it's possible to divide the students into two groups of equal sizes and choose different days for the groups so each student can attend the lesson in the chosen day of their group, print "YES" (without quotes). Otherwise, print "NO" (without quotes).

NoteIn the first testcase, there is a way to meet all the constraints. For example, the first group can consist of the first and the third students, they will attend the lessons on Thursday (the fourth day); the second group can consist of the second and the fourth students, and they will attend the lessons on Tuesday (the second day).In the second testcase, it is impossible to divide the students into groups so they attend the lessons on different days.

# 2
# 4
# 1 0 0 1 0
# 0 1 0 0 1
# 0 0 0 1 0
# 0 1 0 1 0
# 2
# 0 0 0 1 0
# 0 0 0 1 0

require 'set'

n = gets.to_i

def result
  n = gets.to_i
  arrs = n.times.map { gets.split.map(&:to_i) }
  counts = Array.new(5) { Set.new }
  arrs.each.with_index do |arr, j|
    5.times do |i|
      counts[i].add(j) if arr[i] == 1
    end
  end

  counts = counts.select { |c| c.size >= n / 2 }
  counts.size.times do |i|
    first_group = counts[i]
    (i + 1).upto(counts.size - 1) do |j|
      second_group = counts[j]
      big_group, small_group = if second_group.size < first_group.size
                                 [first_group,
                                  second_group]
                               else
                                 [second_group, first_group]
                               end
      f = 0
      s = 0
      b = 0
      big_group.each do |stu|
        if small_group === stu
          b += 1
        else
          f += 1
        end
      end
      small_group.each do |stu|
        next if big_group === stu

        s += 1
      end
      return 'YES' if n / 2 - f >= 0 && n / 2 - s >= 0 && b == n - f - s
    end
  end
  'NO'
end

n.times do
  puts result
end

t = gets.chomp.to_i

t.times do
  n = gets.chomp.to_i

  week = Array.new(5) { [] }

  n.times do
    v = gets.chomp.split.map(&:to_i)

    week[0] << v[0]
    week[1] << v[1]
    week[2] << v[2]
    week[3] << v[3]
    week[4] << v[4]
  end

  good = false

  5.times do |i|
    for j in i+1..4
      l, r, no = 0, 0, 0

      [week[i], week[j]].transpose.each do |a,b|
        if a == 1
          l += 1
        end

        if b == 1
          r += 1
        end

        if a == 0 and b == 0
          no += 1
        end
      end

      if l >= n / 2 and r >= n / 2 and no == 0
        good = true
        break
      else
        next
      end
    end
  end

  if good
    puts "YES"
  else
    puts "NO"
  end
end

days = [*0..4]

gets.to_i.times do
  n = gets.to_i
  xxs = n.times.map { gets.split.map(&:to_i) }
  ok = days.any? do |i|
    (days - [i]).any? do |j|
      ii = xxs.count { |xs| xs[i] == 1 && xs[j] == 0 }
      jj = xxs.count { |xs| xs[j] == 1 && xs[i] == 0 }
      ij = xxs.count { |xs| xs[i] == 1 && xs[j] == 1 }
      ni = [0, n / 2 - ii].max
      nj = [0, n / 2 - jj].max
      ni + nj <= ij
    end
  end
  puts ok ? "YES" : "NO"
end

gets.to_i.times do
  n=gets.to_i
  n2=n/2
  l=[]
  5.times do
    l << [0]*5
  end
  n.times do
    s=gets.split.map(&:to_i)
    5.times do |i|
      5.times do |j|
        if s[i]+s[j]==2
          l[i][j]+=1
        end
      end
    end
  end
  f=false
  5.times do |j|
    j.times do |i|
      if l[i][i]+l[j][j]-l[i][j]==n&&l[i][i]>=n2&&l[j][j]>=n2
        f=true
        break
      end
    end
    break if f
  end
  if f
    puts "YES"
  else
    puts "NO"
  end

end

# 2
# 4
# 1 0 0 1 0
# 0 1 0 0 1
# 0 0 0 1 0
# 0 1 0 1 0
# 2
# 0 0 0 1 0
# 0 0 0 1 0

require 'set'

n = gets.to_i

def result
  n = gets.to_i
  arrs = n.times.map { gets.split.map(&:to_i) }
  counts = Array.new(5) { Set.new }
  arrs.each.with_index do |arr, j|
    5.times do |i|
      counts[i].add(j) if arr[i] == 1
    end
  end

  counts = counts.select { |c| c.size >= n / 2 }
  counts.size.times do |i|
    first_group = counts[i]
    (i + 1).upto(counts.size - 1) do |j|
      second_group = counts[j]
      big_group, small_group = if second_group.size < first_group.size
                                 [first_group,
                                  second_group]
                               else
                                 [second_group, first_group]
                               end
      changed = 0
      big_group.each do |stu|
        changed += 1 if small_group === stu
      end
      if n / 2 - big_group.size + changed >= 0 && n / 2 - small_group.size + changed >= 0 && 0 == n - big_group.size + small_group.size - (3 * changed)
        return 'YES'
      end
    end
  end
  'NO'
end

n.times do
  puts result
end

# 2
# 4
# 1 0 0 1 0
# 0 1 0 0 1
# 0 0 0 1 0
# 0 1 0 1 0
# 2
# 0 0 0 1 0
# 0 0 0 1 0

require 'set'

n = gets.to_i

def result
  n = gets.to_i
  arrs = n.times.map { gets.split.map(&:to_i) }
  counts = Array.new(5) { Set.new }
  arrs.each.with_index do |arr, j|
    5.times do |i|
      counts[i].add(j) if arr[i] == 1
    end
  end

  counts = counts.select { |c| c.size >= n / 2 }
  counts.size.times do |i|
    first_group = counts[i]
    (i + 1).upto(counts.size - 1) do |j|
      second_group = counts[j]
      big_group, small_group = if second_group.size < first_group.size
                                 [first_group,
                                  second_group]
                               else
                                 [second_group, first_group]
                               end
      changed = 0
      big_group.each do |stu|
        changed += 1 if small_group === stu
      end
      if n / 2 - big_group.size + changed >= 0 && n / 2 - small_group.size + changed >= 0 && 0 == n - big_group.size + small_group.size - changed
        return 'YES'
      end
    end
  end
  'NO'
end

n.times do
  puts result
end

# 2
# 4
# 1 0 0 1 0
# 0 1 0 0 1
# 0 0 0 1 0
# 0 1 0 1 0
# 2
# 0 0 0 1 0
# 0 0 0 1 0

require 'set'

n = gets.to_i

def result
  n = gets.to_i
  arrs = n.times.map { gets.split.map(&:to_i) }
  counts = Array.new(5) { Set.new }
  arrs.each.with_index do |arr, j|
    5.times do |i|
      counts[i].add(j) if arr[i] == 1
    end
  end

  counts = counts.select { |c| c.size >= n / 2 }
  counts.size.times do |i|
    first_group = counts[i]
    (i + 1).upto(counts.size - 1) do |j|
      second_group = counts[j]
      big_group, small_group = if second_group.size < first_group.size
                                 [first_group,
                                  second_group]
                               else
                                 [second_group, first_group]
                               end
      changed = 0
      big_group.each do |stu|
        changed += 1 if small_group === stu
      end
      0.upto(changed) do |z|
        return 'YES' if z + small_group.size == n / 2 && big_group.size - changed + z == n / 2
      end
    end
  end
  'NO'
end

n.times do
  puts result
end

# 2
# 4
# 1 0 0 1 0
# 0 1 0 0 1
# 0 0 0 1 0
# 0 1 0 1 0
# 2
# 0 0 0 1 0
# 0 0 0 1 0

require 'set'

n = gets.to_i

def result
  n = gets.to_i
  arrs = n.times.map { gets.split.map(&:to_i) }
  counts = Array.new(5) { Set.new }
  arrs.each.with_index do |arr, j|
    5.times do |i|
      counts[i].add(j) if arr[i] == 1
    end
  end

  counts = counts.select { |c| c.size >= n / 2 }
  result = true
  counts.size.times do |i|
    first_group = counts[i]
    (i + 1).upto(counts.size - 1) do |j|
      second_group = counts[j]
      big_group, small_group = if second_group.size < first_group.size
                                 [first_group,
                                  second_group]
                               else
                                 [second_group, first_group]
                               end
      changed = 0
      big_group.each do |stu|
        changed += 1 if small_group === stu
      end
      result = false if small_group.size + big_group.size - changed == n || big_group.size + small_group.size == n
    end
  end
  !result ? 'YES' : 'NO'
end

n.times do
  puts result
end

# 2
# 4
# 1 0 0 1 0
# 0 1 0 0 1
# 0 0 0 1 0
# 0 1 0 1 0
# 2
# 0 0 0 1 0
# 0 0 0 1 0

require 'set'

n = gets.to_i

def result
  n = gets.to_i
  arrs = n.times.map { gets.split.map(&:to_i) }
  counts = Array.new(5) { Set.new }
  arrs.each.with_index do |arr, j|
    5.times do |i|
      counts[i].add(j) if arr[i] == 1
    end
  end

  counts = counts.select { |c| c.size >= n / 2 }
  result = true
  counts.size.times do |i|
    first_group = counts[i]
    (i + 1).upto(counts.size - 1) do |j|
      second_group = counts[j]
      big_group, small_group = if second_group.size < first_group.size
                                 [first_group,
                                  second_group]
                               else
                                 [second_group, first_group]
                               end
      changed = 0
      big_group.each do |stu|
        changed += 1 if small_group === stu
      end
      if (changed + small_group.size >= n / 2 && small_group.size - (n / 2) <= changed && big_group.size - small_group.size + changed / 2 >= n / 2) || big_group.size - changed + small_group.size == n
        result = false
      end
    end
  end
  !result ? 'YES' : 'NO'
end

n.times do
  puts result
end

# 2
# 4
# 1 0 0 1 0
# 0 1 0 0 1
# 0 0 0 1 0
# 0 1 0 1 0
# 2
# 0 0 0 1 0
# 0 0 0 1 0

require 'set'

n = gets.to_i

def result
  n = gets.to_i
  arrs = n.times.map { gets.split.map(&:to_i) }
  counts = Array.new(5) { Set.new }
  arrs.each.with_index do |arr, j|
    5.times do |i|
      counts[i].add(j) if arr[i] == 1
    end
  end

  result = true
  counts.size.times do |i|
    first_group = counts[i]
    (i + 1).upto(4) do |j|
      second_group = counts[j]
      big_group, small_group = if second_group.size < first_group.size
                                 [first_group,
                                  second_group]
                               else
                                 [second_group, first_group]
                               end
      changed = 0
      big_group.each do |stu|
        changed += 1 if small_group === stu
      end
      if (changed + small_group.size >= n / 2 && small_group.size - (n / 2) <= changed && big_group.size - small_group.size + changed / 2 >= n / 2) || big_group.size - changed + small_group.size == n
        result = false
      end
    end
  end
  !result ? 'YES' : 'NO'
end

n.times do
  puts result
end

# 2
# 4
# 1 0 0 1 0
# 0 1 0 0 1
# 0 0 0 1 0
# 0 1 0 1 0
# 2
# 0 0 0 1 0
# 0 0 0 1 0

require 'set'

n = gets.to_i

def result
  n = gets.to_i
  arrs = n.times.map { gets.split.map(&:to_i) }
  counts = Array.new(5) { Set.new }
  arrs.each.with_index do |arr, j|
    5.times do |i|
      counts[i].add(j) if arr[i] == 1
    end
  end

  result = true
  counts.size.times do |i|
    first_group = counts[i]
    (i + 1).upto(4) do |j|
      second_group = counts[j]
      big_group, small_group = if second_group.size < first_group.size
                                 [first_group,
                                  second_group]
                               else
                                 [second_group, first_group]
                               end
      changed = 0
      big_group.each do |stu|
        changed += 1 if small_group === stu
      end
      if changed + small_group.size >= n / 2 && small_group.size - (n / 2) <= changed && big_group.size - small_group.size + changed / 2 >= n / 2
        result = false
      end
    end
  end
  !result ? 'YES' : 'NO'
end

n.times do
  puts result
end

# 2
# 4
# 1 0 0 1 0
# 0 1 0 0 1
# 0 0 0 1 0
# 0 1 0 1 0
# 2
# 0 0 0 1 0
# 0 0 0 1 0

require 'set'

n = gets.to_i

def result
  n = gets.to_i
  arrs = n.times.map { gets.split.map(&:to_i) }
  counts = Array.new(5) { Set.new }
  arrs.each.with_index do |arr, j|
    5.times do |i|
      counts[i].add(j) if arr[i] == 1
    end
  end

  data = counts.select do |count|
    count.size >= n / 2
  end

  result = true
  data.size.times do |i|
    first_group = data[i]
    (i + 1).upto(data.size - 1) do |j|
      second_group = data[j]
      big_group, small_group = if second_group.size < first_group.size
                                 [first_group,
                                  second_group]
                               else
                                 [second_group, first_group]
                               end
      changed = 0
      big_group.each do |stu|
        changed += 1 if small_group === stu
      end
      if (small_group.size + changed) >= n / 2 && big_group.size - changed + (small_group.size + changed - n / 2)
        result = false
      end
    end
  end
  !result ? 'YES' : 'NO'
end

n.times do
  puts result
end

# 2
# 4
# 1 0 0 1 0
# 0 1 0 0 1
# 0 0 0 1 0
# 0 1 0 1 0
# 2
# 0 0 0 1 0
# 0 0 0 1 0

require 'set'

n = gets.to_i

def result
  n = gets.to_i
  arrs = n.times.map { gets.split.map(&:to_i) }
  counts = Array.new(5) { Set.new }
  arrs.each.with_index do |arr, j|
    5.times do |i|
      counts[i].add(j) if arr[i] == 1
    end
  end

  data = counts.select do |count|
    count.size >= n / 2
  end

  result = true
  data.size.times do |i|
    first_group = data[i]
    (i + 1).upto(data.size - 1) do |j|
      second_group = data[j]
      big_group, small_group = if second_group.size < first_group.size
                                 [first_group,
                                  second_group]
                               else
                                 [second_group, first_group]
                               end
      changed = 0
      big_group.each do |stu|
        changed += 1 if small_group === stu
      end
      result = false if (small_group.size + changed) >= n / 2
    end
  end
  !result ? 'YES' : 'NO'
end

n.times do
  puts result
end

t = gets.chomp.to_i

t.times do
  n = gets.chomp.to_i

  week = Array.new(5) { [] }

  n.times do
    v = gets.chomp.split.map(&:to_i)

    week[0] << v[0]
    week[1] << v[1]
    week[2] << v[2]
    week[3] << v[3]
    week[4] << v[4]
  end

  good = false

  5.times do |i|
    for j in (i+1)..4
      l, r = 0, 0

      [week[i], week[j]].transpose.each do |a,b|
        if a == 1 and b == 1
          l += 1
        end

        if a == 1
          l += 1
        end

        if b == 1
          r += 1
        end
      end

      if l+r == n and l != 0 and r != 0
        good = true
        break
      else
        next
      end
    end
  end

  if good
    puts "YES"
  else
    puts "NO"
  end
end

t = gets.chomp.to_i

t.times do
  n = gets.chomp.to_i

  week = Array.new(5) { [] }

  n.times do
    v = gets.chomp.split.map(&:to_i)

    week[0] << v[0]
    week[1] << v[1]
    week[2] << v[2]
    week[3] << v[3]
    week[4] << v[4]
  end

  good = false

  5.times do |i|
    for j in i+1..4
      ok = true

      [week[i], week[j]].transpose.each do |a,b|
        if a == 0 and b == 0
          ok = false
          break
        end
      end

      if ok
        good = true
        break
      else
        next
      end
    end
  end

  if good
    puts "YES"
  else
    puts "NO"
  end
end

t = gets.chomp.to_i

t.times do
  n = gets.chomp.to_i

  week = Array.new(5) { [] }

  n.times do
    v = gets.chomp.split.map(&:to_i)

    week[0] << v[0]
    week[1] << v[1]
    week[2] << v[2]
    week[3] << v[3]
    week[4] << v[4]
  end

  good = false

  n.times do |i|
    for j in i..n
      ok = true

      [week[i], week[j]].transpose.each do |a, b|
        if a == 0 and b == 0
          ok = false
          break
        end
      end

      if ok
        good = true
        break
      else
        next
      end
    end
  end

  if good
    puts("YES")
  else
    puts "NO"
  end
end

t = gets.chomp.to_i

t.times do
  n = gets.chomp.to_i

  week = Array.new(5) { [] }

  n.times do
    v = gets.chomp.split.map(&:to_i)

    week[0] << v[0]
    week[1] << v[1]
    week[2] << v[2]
    week[3] << v[3]
    week[4] << v[4]
  end

  good = false

  n.times do |i|
    for j in i..n
      ok = true

      [week[i], week[j]].transpose.each do |a, b|
        if a == 0 and b == 0
          ok = false
          break
        end
      end

      if ok
        good = true
        break
      else
        next
      end
    end
  end

  if good
    p "YES"
  else
    p "NO"
  end
end


This problem is same as the previous one, but has larger constraints.It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system consisting of many chimneys, electric poles, and wires. Since they are cats, they found those things gigantic.At the entrance of the station, there is a map describing the complicated wiring system. Selena is the best at math among three friends. He decided to draw the map on the Cartesian plane. Each pole is now a point at some coordinates $$$(x_i, y_i)$$$. Since every pole is different, all of the points representing these poles are distinct. Also, every two poles are connected with each other by wires. A wire is a straight line on the plane infinite in both directions. If there are more than two poles lying on the same line, they are connected by a single common wire.Selena thinks, that whenever two different electric wires intersect, they may interfere with each other and cause damage. So he wonders, how many pairs are intersecting? Could you help him with this problem?

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — the number of electric poles. Each of the following $$$n$$$ lines contains two integers $$$x_i$$$, $$$y_i$$$ ($$$-10^4 \le x_i, y_i \le 10^4$$$) — the coordinates of the poles. It is guaranteed that all of these $$$n$$$ points are distinct.

Print a single integer — the number of pairs of wires that are intersecting.

NoteIn the first example:  In the second example:  Note that the three poles $$$(0, 0)$$$, $$$(0, 2)$$$ and $$$(0, 4)$$$ are connected by a single wire.In the third example:

# coding: utf-8
n = readline.to_i
poles = (0...n).map { |_| readline.split.map(&:to_i) }

def c2(n)
  n * (n-1) / 2
end

lines = {}
lines.default = 0
parallels = {}
parallels.default = 0
for i in 0...n do
  x1, y1 = poles[i]
  for j in i+1...n do
    x2, y2 = poles[j]
    a = y1 - y2
    b = x2 - x1
    if a < 0 or (a == 0 and b < 0)
      a = -a
      b = -b
    end
    d = a.gcd b
    a /= d
    b /= d
    c = a*x1 + b*y1
    line = [a, b, c]
    lines[line] += 1
    parallels[[a, b]] += 1 if lines[line] == 1
  end
end

r = c2(lines.length)
parallels.values.each { |x| r -= c2(x) }
p r

n = readline.to_i
poles = (0...n).map { |_| readline.split.map(&:to_i) }

def line_x(x1, y1, x2, y2)
  if y1 == y2
    [nil, nil]
  else
    slope = Rational((x1-x2)/(y1-y2))
    [slope, x1 - slope * y1]
  end
end

def c2(n)
  n * (n-1) / 2
end

lines = {}
lines.default = 0
parallels = {}
parallels.default = 0
for i in 0...n do
  x1, y1 = poles[i]
  for j in i+1...n do
    x2, y2 = poles[j]
    sx, lx = line_x(x1, y1, x2, y2)
    sy, ly = line_x(y1, x1, y2, x2)
    line = [sx, sy, lx, ly]
    lines[line] += 1
    parallels[[sx, sy]] += 1 if lines[line] == 1
  end
end

r = c2(lines.length)
parallels.values.each { |x| r -= c2(x) }
p r

n = readline.to_i
poles = (0...n).map { |_| readline.split.map(&:to_i) }

def line_x(x1, y1, x2, y2)
  if y1 == y2
    [nil, nil]
  else
    slope = Float(x1-x2) / (y1-y2)
    [slope, x1 - slope * y1]
  end
end

def c2(n)
  n * (n-1) / 2
end

lines = {}
lines.default = 0
parallels = {}
parallels.default = 0
for i in 0...n do
  x1, y1 = poles[i]
  for j in i+1...n do
    x2, y2 = poles[j]
    sx, lx = line_x(x1, y1, x2, y2)
    sy, ly = line_x(y1, x1, y2, x2)
    line = [sx, lx, ly]
    lines[line] += 1
    parallels[sx] += 1 if lines[line] == 1
  end
end

r = c2(lines.length)
parallels.values.each { |x| r -= c2(x) }
p r

n = readline.to_i
poles = (0...n).map { |_| readline.split.map(&:to_i) }

def c2(n)
  n * (n-1) / 2
end

lines = {}
lines.default = 0
parallels = {}
parallels.default = 0
for i in 0...n do
  x1, y1 = poles[i]
  for j in i+1...n do
    x2, y2 = poles[j]
    a = y1 - y2
    b = x2 - x1
    d = a.gcd b
    a /= d
    b /= d
    c = a*x1 + b*y1
    line = [a, b, c]
    lines[line] += 1
    parallels[[a, b]] += 1 if lines[line] == 1
  end
end

r = c2(lines.length)
parallels.values.each { |x| r -= c2(x) }
p r


You are given a huge integer $$$a$$$ consisting of $$$n$$$ digits ($$$n$$$ is between $$$1$$$ and $$$3 \cdot 10^5$$$, inclusive). It may contain leading zeros.You can swap two digits on adjacent (neighboring) positions if the swapping digits are of different parity (that is, they have different remainders when divided by $$$2$$$). For example, if $$$a = 032867235$$$ you can get the following integers in a single operation:   $$$302867235$$$ if you swap the first and the second digits;  $$$023867235$$$ if you swap the second and the third digits;  $$$032876235$$$ if you swap the fifth and the sixth digits;  $$$032862735$$$ if you swap the sixth and the seventh digits;  $$$032867325$$$ if you swap the seventh and the eighth digits. Note, that you can't swap digits on positions $$$2$$$ and $$$4$$$ because the positions are not adjacent. Also, you can't swap digits on positions $$$3$$$ and $$$4$$$ because the digits have the same parity.You can perform any number (possibly, zero) of such operations.Find the minimum integer you can obtain.Note that the resulting integer also may contain leading zeros.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. The only line of each test case contains the integer $$$a$$$, its length $$$n$$$ is between $$$1$$$ and $$$3 \cdot 10^5$$$, inclusive. It is guaranteed that the sum of all values $$$n$$$ does not exceed $$$3 \cdot 10^5$$$.

For each test case print line — the minimum integer you can obtain.

NoteIn the first test case, you can perform the following sequence of operations (the pair of swapped digits is highlighted): $$$0 \underline{\textbf{70}} 9 \rightarrow 0079$$$.In the second test case, the initial integer is optimal. In the third test case you can perform the following sequence of operations: $$$246 \underline{\textbf{43}} 2 \rightarrow 24 \underline{\textbf{63}}42 \rightarrow 2 \underline{\textbf{43}} 642 \rightarrow 234642$$$.

readline.to_i.times do
  e,o = readline.chomp.chars.partition { |x| x.to_i.odd? }
  i = j = 0
  im = e.length
  jm = o.length
  r = []
  while i < im or j < jm do
    if j == jm or (i < im and e[i] < o[j]) then
      r << e[i]
      i += 1
    else
      r << o[j]
      j += 1
    end
  end
  print r.join(), "\n"
end


There are $$$n$$$ programmers that you want to split into several non-empty teams. The skill of the $$$i$$$-th programmer is $$$a_i$$$. You want to assemble the maximum number of teams from them. There is a restriction for each team: the number of programmers in the team multiplied by the minimum skill among all programmers in the team must be at least $$$x$$$.Each programmer should belong to at most one team. Some programmers may be left without a team.Calculate the maximum number of teams that you can assemble.

The first line contains the integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5; 1 \le x \le 10^9$$$) — the number of programmers and the restriction of team skill respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the skill of the $$$i$$$-th programmer. The sum of $$$n$$$ over all inputs does not exceed $$$10^5$$$.

For each test case print one integer — the maximum number of teams that you can assemble.

tc  = gets.to_i
tc.times do
	n,y = gets.split().map{|x| x.to_i}
	arr = gets.split().map{|x| x.to_i}
	arr.sort_by!{|x| -x}
	cur = ans =  0
	arr.each do |x|
		cur += 1
		if(cur*x >= y)
			ans += 1
			cur = 0
		end
	end
	puts ans
end


Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length $$$k$$$ is vowelly if there are positive integers $$$n$$$ and $$$m$$$ such that $$$n\cdot m = k$$$ and when the word is written by using $$$n$$$ rows and $$$m$$$ columns (the first row is filled first, then the second and so on, with each row filled from left to right), every vowel of the English alphabet appears at least once in every row and every column.You are given an integer $$$k$$$ and you must either print a vowelly word of length $$$k$$$ or print $$$-1$$$ if no such word exists.In this problem the vowels of the English alphabet are 'a', 'e', 'i', 'o' ,'u'.

Input consists of a single line containing the integer $$$k$$$ ($$$1\leq k \leq 10^4$$$) — the required length.

The output must consist of a single line, consisting of a vowelly word of length $$$k$$$ consisting of lowercase English letters if it exists or $$$-1$$$ if it does not. If there are multiple possible words, you may output any of them.

NoteIn the second example, the word "agoeuioaeiruuimaeoieauoweouoiaouimae" can be arranged into the following $$$6 \times 6$$$ grid:  It is easy to verify that every row and every column contain all the vowels.

def tempfun(k)
	temp = ['a','e','i','o','u']
	n = k - 5
	n.to_i.times do
		temp << 'g'
	end
	ans = []
	for b in 0...temp.length
		ans << temp.rotate(b)
	end
	return ans
end
mark = false
i = gets.chomp.to_i
k = Math.sqrt(i)
ans = Array.new
if(k >= 5)
	t = k.to_i
	for z in 5..t
		if(i % z == 0 )
			mark  = true
			m = (i - z*z)
			ans = tempfun(z)
			#print(ans)
			for i in 0...z
				for j in 0... (m/z)
					ans[i] << ans[i][j]
				end
			end
			break
		end
	end
	if(mark)
		for i in ans
			for m in i
				print(m)
			end
			#puts()
		end
	else
		print(-1)
	end
else
	print(-1)
end

n = gets.to_i
val = nil
5.upto(n**0.5) do |i|
  if n % i == 0
    val = i
    break
  end
end
vow = "aeiou"
if val == nil
  p -1
  exit
else
  row = vow * (val*2/5 + 1)
  (n/val).times do |i|
    print row[i%val,val]
  end
  print "\n"
end

n = gets.to_i
val = nil
5.upto(n**0.5) do |i|
  if n % i == 0
    val = i
    break
  end
end
vow = "aeiou"
if val == nil
  p -1
  exit
else
  row = vow * (val/5) + vow[0,val%5]
  row *= 2
  (n/val).times do |i|
    print row[i%val,val]
  end
  print "\n"
end

n = gets.to_i
f = false
u = v = 0
for i in 5..n
    if n%i == 0 && n/i >= 5
        f = true
        u = i
        v = n/i
        break
    end
end
if !f
    puts "-1"
    exit
end
s = "aiueo"*(u/5+2)
ans = ""
v.times do |i|
    ans += s[i%5,u]
end
puts ans

def tempfun(k)
	temp = ['a','e','i','o','u']
	n = k - 5
	n.to_i.times do
		temp << 'g'
	end
	ans = []
	for b in 0...temp.length
		ans << temp.rotate(b)
	end
	return ans
end

i = gets.chomp.to_i
k = Math.sqrt(i)
ans = Array.new
if(k >= 5)
	t = k.to_i
	if((i - t*t) % t == 0 )
		m = (i - t*t)
		ans = tempfun(t)
		#print(ans)
		for i in 0...t
			for j in 0... (m/t)
				ans[i] << ans[i][j]
			end
		end
	else
		print(-1)
		exit
	end
	for i in ans
		for m in i
			print(m)
		end
		puts()
	end
else
	print(-1)
	exit
end

def tempfun(k)
	temp = ['a','e','i','o','u']
	n = k - 5
	n.to_i.times do
		temp << 'g'
	end
	ans = []
	for b in 0...temp.length
		ans << temp.rotate(b)
	end
	return ans
end

i = gets.chomp.to_i
k = Math.sqrt(i)
ans = Array.new
if(k >= 5)
	t = k.to_i
	if((i - t*t) % t == 0 )
		m = (i - t*t)
		ans = tempfun(t)
		#print(ans)
		for i in 0...t
			for j in 0... (m/t)
				ans[i] << ans[i][j]
			end
		end
	else
		print(-1)
		exit
	end
	for i in ans
		for m in i
			print(m)
		end

	end
else
	print(-1)
	exit
end

n = gets.to_i
val = nil
5.upto(n**0.5) do |i|
  if n % i == 0
    val = i
    break
  end
end
if val == nil
  p -1
  exit
else
  row = "aeiou" * (val/5) + "x" * (val % 5)
  (n/val).times do
    print row
  end
  print "\n"
end

n = gets.to_i
f = false
u = v = 0
for i in 5..n
    if n%i == 0 && n/i >= 5
        f = true
        u = i
        v = n/i
        break
    end
end
if !f
    puts "-1"
    exit
end
s = "aiueo"*(u/5+1)
ans = ""
v.times do |i|
    ans += s[i%5,u]
end
puts ans


The flag of Berland is such rectangular field n × m that satisfies following conditions:  Flag consists of three colors which correspond to letters 'R', 'G' and 'B'.  Flag consists of three equal in width and height stripes, parralel to each other and to sides of the flag. Each stripe has exactly one color.  Each color should be used in exactly one stripe. You are given a field n × m, consisting of characters 'R', 'G' and 'B'. Output "YES" (without quotes) if this field corresponds to correct flag of Berland. Otherwise, print "NO" (without quotes).

The first line contains two integer numbers n and m (1 ≤ n, m ≤ 100) — the sizes of the field. Each of the following n lines consisting of m characters 'R', 'G' and 'B' — the description of the field.

Print "YES" (without quotes) if the given field corresponds to correct flag of Berland . Otherwise, print "NO" (without quotes).

6 7
RRRGGGG
RRRGGGG
RRRGGGG
RRRBBBB
RRRBBBB
RRRBBBB

NoteThe field in the third example doesn't have three parralel stripes.Rows of the field in the fourth example are parralel to each other and to borders. But they have different heights — 2, 1 and 1.

def build(n, m)
  'RGB'.chars.permutation.map do |cs|
    cs.flat_map{|c| n.times.map{(c * m).chars}}
  end
end

n, m = gets.split.map(&:to_i)
s = n.times.map{gets.strip.chars}
ts = build(n / 3, m) + build(m / 3, n).map(&:transpose)

if ts.include?(s)
  puts 'YES'
else
  puts 'NO'
end

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

a = []
n.times do
  a.push << (gets.strip.split(''))
end

rc = true
temp = []
n.times do |i|
  first = nil
  bool = true
  m.times do |j|
    if j == 0
      first = a[i][j]
      temp.push(a[i][j])
      next
    end
    if first != a[i][j]
      bool = false
      break
    end
  end
  if !bool
    rc = false
    break
  end
end

if rc
    if temp.count('R') == temp.count('G') && temp.count('G')  == temp.count('B')
        cnt = temp.count('R')
        if ((temp.rindex('R') - temp.index('R') + 1) == cnt) && ((temp.rindex('G') - temp.index('G') + 1) == cnt) && ((temp.rindex('B') - temp.index('B') + 1) == cnt)
            rc = true
        else
            rc = false
        end
    else
        rc = false
    end
end

rc1 = true
temp = []
m.times do |i|
  first = nil
  bool = true
  n.times do |j|
    if j == 0
      first = a[j][i]
      temp.push(a[j][i])
      next
    end
    if first != a[j][i]
      bool = false
      break
    end
  end
  if !bool
    rc1 = false
    break
  end
end

if rc1
    if temp.count('R') == temp.count('G') && temp.count('G')  == temp.count('B')
        cnt = temp.count('R')
        if ((temp.rindex('R') - temp.index('R') + 1) == cnt) && ((temp.rindex('G') - temp.index('G') + 1) == cnt) && ((temp.rindex('B') - temp.index('B') + 1) == cnt)
            rc1 = true
        else
            rc1 = false
        end
    else
        rc1 = false
    end
end

if rc || rc1
  puts 'YES'
else
  puts 'NO'
end

n, m = gets.split.map(&:to_i)
a, res = [], "NO"
n.times {a << gets.chomp.chars}
c = [a[0][0], a[n / 2][m / 2], a[n - 1][m - 1]].uniq
if c.size == 3
  n = n * m / 3
  s = [c[0] * n, c[1] * n, c[2] * n].join
  [a, a.transpose].each {|b| res = "YES" if b.flatten.join == s}
end
puts res

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

a = []
n.times do
  a.push << (gets.strip.split(''))
end

rc = true
temp = []
n.times do |i|
  first = nil
  bool = true
  m.times do |j|
    if j == 0
      first = a[i][j]
      temp.push(a[i][j])
      next
    end
    if first != a[i][j]
      bool = false
      break
    end
  end
  if !bool
    rc = false
    break
  end
end

if rc
    if temp.count('R') == temp.count('G') && temp.count('G')  == temp.count('B')
        rc = true
    else
        rc = false
    end
end

rc1 = true
temp = []
m.times do |i|
  first = nil
  bool = true
  n.times do |j|
    if j == 0
      first = a[j][i]
      temp.push(a[j][i])
      next
    end
    if first != a[j][i]
      bool = false
      break
    end
  end
  if !bool
    rc1 = false
    break
  end
end

if rc1
    if temp.count('R') == temp.count('G') && temp.count('G')  == temp.count('B')
        rc1 = true
    else
        rc1 = false
    end
end

if rc || rc1
  puts 'YES'
else
  puts 'NO'
end


n soldiers stand in a circle. For each soldier his height ai is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |ai - aj| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance unit.

The first line contains integer n (2 ≤ n ≤ 100) — amount of soldiers. Then follow the heights of the soldiers in their order in the circle — n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 1000). The soldier heights are given in clockwise or counterclockwise direction.

Output two integers — indexes of neighbouring soldiers, who should form a reconnaissance unit. If there are many optimum solutions, output any of them. Remember, that the soldiers stand in a circle.

n = gets.to_i

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

min = (solds[0] - solds[-1]).abs
q = n
w = 1
i = 1
while i < n do
    if min > (solds[i-1] - solds[i]).abs then
        min = (solds[i-1] - solds[i]).abs
        q = i
        w = i + 1
    end
    i += 1
end

puts [q,w].join(" ")

n = gets.chomp.to_i
s = gets.chomp
sa = s.split(/ /)
sa.map!{|x| x.to_i}

mindiff = (sa[1]-sa[0]).abs
minidx1 = 1
minidx2 = 2

for i in 1..n-1
	j = i+1
	j = 0 if j >= n
	wk = (sa[i]-sa[j]).abs
	if wk < mindiff
		mindiff = wk
		minidx1 = i+1
		minidx2 = j+1
	end
end

puts minidx1.to_s + " " + minidx2.to_s

n=gets.to_i
v=gets.split.map{|i|i.to_i}
v<<v[0]
m,r=1e9,0
(1..n).each{|i|
	t=(v[i]-v[i-1]).abs
	if m>t then
		m=t
		r=i
	end
}
print r," ",r%n+1

#!/usr/bin/ruby
gets;a=gets.split.map(&:to_i)
r=a.size.times.map{|i|[(a[i]-a[(i+1)%a.size]).abs,i]}.min.pop
puts "#{r+1} #{(r+1)%a.size+1}"

num_soldiers = gets.to_i
soldiers = gets.split.collect {|i| i.to_i}
best = (soldiers[0] - soldiers[-1]).abs
best_index = [1,num_soldiers]
for i in 0...num_soldiers-1
	temp = (soldiers[i+1] - soldiers[i]).abs
	if temp < best
		best = temp
		best_index = [i+1,i+2]
	end
end
puts best_index[0].to_s + " " + best_index[1].to_s

n=gets.to_i
a=gets.chomp.split.map(&:to_i)
x,y=1,1
z=[(a[0]-a[n-1]).abs]
for i in 0..n-2
	z.push((a[i]-a[i+1]).abs)
end
for i in 0..z.length-1
	if z[i]==z.min
		if i==0
			puts "#{n} 1"
			exit
		else
			puts "#{i} #{i+1}"
			exit
		end
	end
end

n = gets.chomp.to_i
a = gets.chomp.split(/ /).map(&:to_i)
neighbor = {}
i = j = 0
n1 = n2 = 0
diff = 0
while true
    n1 = a[i]
    if i + 1 == n
        j = 0
    else
        j = i + 1
    end
    n2 = a[j]
    diff = (n1 - n2).abs
    pair = [i + 1, j + 1]
    if !neighbor.has_key? pair
        neighbor.store pair, diff
    else
        neighbor[pair] = diff
    end
    i += 1
    break if j == 0
end
min_h = neighbor.values.min
recon = neighbor.select { |k, v| v == min_h }.to_a[0][0]
puts recon.join(" ")

n=gets.to_i
data=gets.split.map(&:to_i)
data << data[0]

dif=999999
a=b=0
for i in 0..data.size-2
	tmp=(data[i]-data[i+1]).abs
	if dif>tmp
		a,b=i,((i+1)%n==0? 1 : i+2)
		dif=tmp
	end
end

puts "#{a+1} #{b}"

n = gets.to_i
arr = gets.split(" ").map(&:to_i)
diff_arr = []
(1..n-1).each do |i|
	diff_arr << (arr[i] - arr[i-1]).abs
end
diff_arr << (arr[0]-arr[-1]).abs
min,min_ind = diff_arr.each_with_index.min

if min_ind == n -1
	a,b = n,1
else
	a,b = min_ind+1,min_ind + 2
end
puts "#{a} #{b}"

tot, min, min_index, input = gets.to_i, 20000, -1, gets.split(' ').map{|n| n.to_i}
input.each_cons(2).to_a.each_with_index { |(a, b), index| min, min_index = (a - b).abs, index if (((a - b).abs) < min) }
min_index = tot - 1 if (min > (input[0] - input[input.length - 1]).abs)
max_index = (min_index == tot - 1) ? 0 : min_index + 1
print (min_index + 1).to_s + ' ' + (max_index + 1).to_s

n = gets.to_i
a = gets.split.collect{|i| i.to_i}
ans = 0
(1...n-1).each{|i| ans = i if (a[i]-a[i+1]).abs < (a[ans]-a[ans+1]).abs}
if (a[0]-a[n-1]).abs < (a[ans]-a[ans+1]).abs
    print n, " ", 1, "\n"
else
    print ans+1, " ", ans+2, "\n"
end

n = gets.to_i
a = gets.split.collect{|i| i.to_i}
ans = 0
for i in 1...n-1
    ans = i if (a[i]-a[i+1]).abs < (a[ans]-a[ans+1]).abs
end
if (a[0]-a[n-1]).abs < (a[ans]-a[ans+1]).abs
    print n, " ", 1, "\n"
else
    print ans+1, " ", ans+2, "\n"
end

gets # ignore n

soldiers = gets.chomp.split.map(&:to_i)

soldiers << soldiers[0]
diff, pos = 1_001, 0

soldiers[0..-2].each_with_index do |s, i|
  tmp_diff = (s - soldiers[i + 1]).abs
  if tmp_diff < diff
    diff = tmp_diff
    pos = i
  end
end

puts pos + 1, (pos + 2 > soldiers.size - 1 ? 1 : pos + 2)

gets
h = gets.split(" ").map{|s| s.to_i}
n = h.length
h << h[0]
best = 0
(0...n).each do |i|
  if (h[i] - h[i+1]).abs < (h[best] - h[best+1]).abs
    best = i
  end
end

print (best%n)+1, " ", ((best+1)%n) + 1

n = gets.to_i
a = gets.split.map { |x| x.to_i }

min = 1_000
min_ind = nil
for i in 1...n
  diff = (a[i] - a[i - 1]).abs
  if diff < min
    min = diff
    min_ind = i
  end
end

if (a.last - a.first).abs < min
  min_ind = n
  next_min_ind = 1
else
  next_min_ind = min_ind + 1
end
puts "#{min_ind} #{next_min_ind}"

n, s, min, idx = gets.to_i, gets.strip.split.map(&:to_i), 0, idx

(print [1, n].join " "; exit) if s[0] == s[-1]
min, idx = (s[0] - s[-1]).abs, [1, n]

(0...n - 1).each do |i|
  a, b = i, i + 1
  (print [a + 1, b + 1].join " "; exit) if s[a] == s[b]
  m = (s[a] - s[b]).abs
  if m < min
    min = m
    idx = [a + 1, b + 1]
  end
end

print idx.join " "

tot, min, min_index, input = gets.to_i, 20000, -1, gets.split(' ').map{|n| n.to_i}
input.each_cons(2).to_a.each_with_index { |(a, b), index| min, min_index = (a - b).abs, index if (((a - b).abs) < min) }
min_index = tot - 1 if (min > (input[0] - input[input.length - 1]).abs)
max_index = (min_index == tot - 1) ? 0 : min_index + 1
p (min_index + 1).to_s + ' ' + (max_index + 1).to_s


You are given an array $$$a$$$ of length $$$n$$$.You are also given a set of distinct positions $$$p_1, p_2, \dots, p_m$$$, where $$$1 \le p_i < n$$$. The position $$$p_i$$$ means that you can swap elements $$$a[p_i]$$$ and $$$a[p_i + 1]$$$. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order ($$$a_1 \le a_2 \le \dots \le a_n$$$) using only allowed swaps.For example, if $$$a = [3, 2, 1]$$$ and $$$p = [1, 2]$$$, then we can first swap elements $$$a[2]$$$ and $$$a[3]$$$ (because position $$$2$$$ is contained in the given set $$$p$$$). We get the array $$$a = [3, 1, 2]$$$. Then we swap $$$a[1]$$$ and $$$a[2]$$$ (position $$$1$$$ is also contained in $$$p$$$). We get the array $$$a = [1, 3, 2]$$$. Finally, we swap $$$a[2]$$$ and $$$a[3]$$$ again and get the array $$$a = [1, 2, 3]$$$, sorted in non-decreasing order.You can see that if $$$a = [4, 1, 2, 3]$$$ and $$$p = [3, 2]$$$ then you cannot sort the array.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. Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m < n \le 100$$$) — the number of elements in $$$a$$$ and the number of elements in $$$p$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$). The third line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i < n$$$, all $$$p_i$$$ are distinct) — the set of positions described in the problem statement.

For each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order ($$$a_1 \le a_2 \le \dots \le a_n$$$) using only allowed swaps. Otherwise, print "NO".

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

# [1,2], [3,4], (2,3)

gets.strip.to_i.times do
  _ = read_array(:to_i)
  a = read_array(:to_i)
  p = read_array(:to_i).map { |e| e - 1 }.sort
  ranges = []
  p.each_with_index do |e, i|
    if ranges.all? { |r| (r & [e,e+1]).empty? }
      ranges << [e,e+1]
    else
      ranges = ranges.select { |r| (r & [e,e+1]).empty? } +
        [  [[e,e+1], ranges.select { |r| !(r & [e,e+1]).empty? }].flatten.uniq.sort ]
    end
  end
  ranges.each do |r|
    a[r[0]..r[-1]] = a[r[0]..r[-1]].sort
  end
  puts a == a.sort ? "YES" : "NO"
end

n=gets.to_i
array = sets = []
(1..n).each do |x|
  a,b=gets.chomp.split(" ")
  array=gets.chomp.split(" ").map(&:to_i)
  sets=gets.chomp.split(" ").map(&:to_i)
  sets = sets.sort
  s = e = sets[0]
  sets.each do |set|
    if e != set
      array[s-1..e-1] = array[s-1..e-1].sort!
      s = set
    end
    e = set + 1
  end
  array[s-1..e-1] = array[s-1..e-1].sort!
  c = array[0]
  check = false
  array.each do |arr|
    if arr >= c
      c = arr
    else
      print("NO\n")
      check = true
      break
    end
  end
  print("YES\n") unless check
end

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

gets.strip.to_i.times do
  _ = read_array(:to_i)
  a = read_array(:to_i)
  p = read_array(:to_i).map { |e| e - 1 }
  ranges = []
  p.each do |e|
    found = false
    ranges.map! do |r|
      unless (r & [e, e + 1]).empty?
        found = true
        r = (r + [e, e + 1]).uniq.sort
      else
        r
      end
    end
    unless found
      ranges << [e, e+1]
    end
  end
  ranges.each do |r|
    a[r[0]..r[-1]] = a[r[0]..r[-1]].sort
  end
  puts a == a.sort ? "YES" : "NO"
end


There are n integers b1, b2, ..., bn written in a row. For all i from 1 to n, values ai are defined by the crows performing the following procedure:  The crow sets ai initially 0.  The crow then adds bi to ai, subtracts bi + 1, adds the bi + 2 number, and so on until the n'th number. Thus, ai = bi - bi + 1 + bi + 2 - bi + 3.... Memory gives you the values a1, a2, ..., an, and he now wants you to find the initial numbers b1, b2, ..., bn written in the row? Can you do it?

The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of integers written in the row. The next line contains n, the i'th of which is ai ( - 109 ≤ ai ≤ 109) — the value of the i'th number.

Print n integers corresponding to the sequence b1, b2, ..., bn. It's guaranteed that the answer is unique and fits in 32-bit integer type.

NoteIn the first sample test, the crows report the numbers 6, - 4, 8, - 2, and 3 when he starts at indices 1, 2, 3, 4 and 5 respectively. It is easy to check that the sequence 2 4 6 1 3 satisfies the reports. For example, 6 = 2 - 4 + 6 - 1 + 3, and  - 4 = 4 - 6 + 1 - 3.In the second sample test, the sequence 1,  - 3, 4, 11, 6 satisfies the reports. For example, 5 = 11 - 6 and 6 = 6.

n = gets.to_i
a = gets.split.map(&:to_i)
b = []
sum = 0
a.reverse_each do |val|
	b.unshift val + sum
	sum = b[0] - sum
end

puts b * " "

n = gets.chomp.to_i
arr = gets.chomp.split.map(&:to_i)
puts (arr.each_cons(2).map { |i, j| i + j } << arr.last).join(' ')

n=gets.to_i
x=gets.split.map{|e| e.to_i}
bt=0
ans=[]
x.reverse.each{|e|
	bi=e+bt
	ans<<bi
	bt=bi-bt
}
puts ans.reverse*" "

n = gets.strip.to_i
arr = gets.strip.split(" ").map(&:to_i)
ans = []
for i in 0..(arr.length-2) do
  ans << arr[i] + arr[i+1]
end
ans << arr.last
for i in 0..(ans.length-2) do
  print ans[i].to_s + " "
end
print ans.last

n=gets.to_i
a=gets.split.map &:to_i
a<<0
for i in 1..n
    print "#{a[i]+a[i-1]} "
end

#!/usr/local/rvm/rubies/ruby-2.3.0/bin/ruby

class Task1
  attr_accessor :crows, :n, :result

  def initialize()
    @n = 0
    @crows = []
    @result = []
  end

  def getData()
    tmp = []
    $stdin.each { |x| (x!="\n") ? tmp.push(x.chomp.split.map { |y| y.to_i }) : nil }
    @n = tmp[0][0]
    @crows = tmp[1]
  end

  def getResult()
    (0..@n-1).each do |x|
      if x == @n-1
        @result.push(@crows[x])
      else
        @result.push(@crows[x]+@crows[x+1])
      end
    end
  end

  def printResult()
    puts @result.join(' ')
  end

  def run()
    getData
    getResult
    printResult
  end

end
if __FILE__ == $0
  pc = Task1.new
  pc.run
end

def read_line
  gets.chomp.split.map &:to_i
end

n = read_line
a = read_line
b = []
y = 0

a.reverse_each do |x|
  b << x+y
  y = x
end

puts b.reverse

n = gets.to_i
a = gets.split.map(&:to_i)
puts n.times.map{|i| i == n - 1 ? a[i] : a[i] + a[i + 1]}.join(' ')

n=readline.to_i
a=readline.split.map(&:to_i)
a << 0
b = []
(0...n).each do |i|
  b << a[i]+a[i+1]
end
puts b.join(" ")

totalNumber = gets.chomp.to_i
numbers = gets.chomp.split(' ').map(&:to_i)

ans = [numbers[totalNumber - 1]]

(totalNumber - 2).downto(0).each do |i|
    ans << (numbers[i] + numbers[i + 1])
end

ans.reverse_each do |a|
    print "#{a} "
end


Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.

The first input line contains 3 space-separated integer numbers n, m, v (3 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ v ≤ n), n — amount of servers, m — amount of direct connections, v — index of the server that fails and leads to the failure of the whole system.

If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each — description of all the direct connections in the system. Each direct connection is described by two numbers — indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.

def solve(n, m, v)
    if m < n-1
        puts -1
        return
    end
    if m > (n-1)*(n-2)/2 + 1
        puts -1
        return
    end
    other = v % n + 1
    a = (1..n).to_a - [v, other]
    a = [v] + a + [other]
    puts "#{v} #{other}"
    m -= 1
    0.upto(n-2) do |i|
        break if m == 0
        (i+1).upto(n-2) do |j|
            break if m == 0
            puts "#{a[i]} #{a[j]}"
            m -= 1
        end
    end
end

n, m, v = *gets.split(' ').map { |s| s.to_i }
solve(n, m, v)


A chess tournament will be held soon, where $$$n$$$ chess players will take part. Every participant will play one game against every other participant. Each game ends in either a win for one player and a loss for another player, or a draw for both players.Each of the players has their own expectations about the tournament, they can be one of two types:  a player wants not to lose any game (i. e. finish the tournament with zero losses);  a player wants to win at least one game. You have to determine if there exists an outcome for all the matches such that all the players meet their expectations. If there are several possible outcomes, print any of them. If there are none, report that it's impossible.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$2 \le n \le 50$$$) — the number of chess players. The second line contains the string $$$s$$$ ($$$|s| = n$$$; $$$s_i \in \{1, 2\}$$$). If $$$s_i = 1$$$, then the $$$i$$$-th player has expectations of the first type, otherwise of the second type.

For each test case, print the answer in the following format: In the first line, print NO if it is impossible to meet the expectations of all players. Otherwise, print YES, and the matrix of size $$$n \times n$$$ in the next $$$n$$$ lines. The matrix element in the $$$i$$$-th row and $$$j$$$-th column should be equal to:   +, if the $$$i$$$-th player won in a game against the $$$j$$$-th player;  -, if the $$$i$$$-th player lost in a game against the $$$j$$$-th player;  =, if the $$$i$$$-th and $$$j$$$-th players' game resulted in a draw;  X, if $$$i = j$$$.

gets.to_i.times do

n = gets.to_i
s = gets.chomp.chars.map!(&:to_i)

n1 = s.count(1)
n2 = n - n1

if n2 == 1 || n2 == 2
  puts "NO"
  next
end

puts "YES"

mtx = s.each_with_index.map do |si, i|
  next Array.new(n, '=') if si == 1

  Array.new(n) do |j|
    next '=' if s[j] == 1
    i < j ? '+' : '-'
  end
end

if n2 > 0
  i1 = s.index(2)
  i2 = s.rindex(2)
  mtx[i1][i2] = '-'
  mtx[i2][i1] = '+'
end

mtx.each_with_index { |row, i| row[i] = 'X' }
mtx.each { |row| puts row.join }

end


The King of Berland Polycarp LXXXIV has $$$n$$$ daughters. To establish his power to the neighbouring kingdoms he wants to marry his daughters to the princes of these kingdoms. As a lucky coincidence there are $$$n$$$ other kingdoms as well.So Polycarp LXXXIV has enumerated his daughters from $$$1$$$ to $$$n$$$ and the kingdoms from $$$1$$$ to $$$n$$$. For each daughter he has compiled a list of kingdoms princes of which she wanted to marry.Polycarp LXXXIV is very busy, so he finds a couple for his daughters greedily one after another.For the first daughter he takes the kingdom with the lowest number from her list and marries the daughter to their prince. For the second daughter he takes the kingdom with the lowest number from her list, prince of which hasn't been taken already. If there are no free princes in the list then the daughter marries nobody and Polycarp LXXXIV proceeds to the next daughter. The process ends after the $$$n$$$-th daughter.For example, let there be $$$4$$$ daughters and kingdoms, the lists daughters have are $$$[2, 3]$$$, $$$[1, 2]$$$, $$$[3, 4]$$$, $$$[3]$$$, respectively.  In that case daughter $$$1$$$ marries the prince of kingdom $$$2$$$, daughter $$$2$$$ marries the prince of kingdom $$$1$$$, daughter $$$3$$$ marries the prince of kingdom $$$3$$$, leaving daughter $$$4$$$ nobody to marry to.Actually, before starting the marriage process Polycarp LXXXIV has the time to convince one of his daughters that some prince is also worth marrying to. Effectively, that means that he can add exactly one kingdom to exactly one of his daughter's list. Note that this kingdom should not be present in the daughter's list.Polycarp LXXXIV wants to increase the number of married couples.Unfortunately, what he doesn't have the time for is determining what entry to add. If there is no way to increase the total number of married couples then output that the marriages are already optimal. Otherwise, find such an entry that the total number of married couples increases if Polycarp LXXXIV adds it.If there are multiple ways to add an entry so that the total number of married couples increases then print any of them.For your and our convenience you are asked to answer $$$t$$$ independent test cases.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of daughters and the number of kingdoms. Each of the next $$$n$$$ lines contains the description of each daughter's list. The first integer $$$k$$$ ($$$0 \le k \le n$$$) is the number of entries in the $$$i$$$-th daughter's list. After that $$$k$$$ distinct integers follow $$$g_i[1], g_i[2], \dots, g_i[k]$$$ ($$$1 \le g_i[j] \le n$$$) — the indices of the kingdoms in the list in the increasing order ($$$g_i[1] < g_i[2] < \dots < g_i[k]$$$). It's guaranteed that the total number of daughters over all test cases does not exceed $$$10^5$$$. It's also guaranteed that the total number of kingdoms in lists over all test cases does not exceed $$$10^5$$$.

For each test case print the answer to it. Print "IMPROVE" in the first line if Polycarp LXXXIV can add some kingdom to some of his daughter's list so that the total number of married couples increases. The second line then should contain two integers — the index of the daughter and the index of the kingdom Polycarp LXXXIV should add to that daughter's list. If there are multiple ways to add an entry so that the total number of married couples increases then print any of them. Otherwise the only line should contain one word "OPTIMAL".

IMPROVE
4 4
IMPROVE
1 1
OPTIMAL
OPTIMAL
OPTIMAL

NoteThe first test case is depicted in the statement. Adding the fourth kingdom to the list of the fourth daughter makes her marry the prince of the fourth kingdom.In the second test case any new entry will increase the number of marriages from $$$0$$$ to $$$1$$$.In the third and the fourth test cases there is no way to add an entry.In the fifth test case there is no way to change the marriages by adding any entry.

#!usr/bin/env ruby

# https://codeforces.com/problemset/problem/1327/B

require 'set'

t = gets.to_i

t.times do
  n = gets.to_i

  options = []

  n.times do
    options << gets.split(' ').map(&:to_i).drop(1)
  end

  choices = Set.new
  first_untaken_princess = nil

  options.each_with_index do |op, num|
    first_untaken_princess ||= num + 1 if op.size == 0

    op.each_with_index do |prince, n|
      unless choices.include? prince
        choices << prince
        break
      end
      if n + 1 == op.size
        first_untaken_princess ||= num + 1
      end
    end
  end

  if first_untaken_princess
    first_untaken_prince = 1

    while true do
      if choices.include? first_untaken_prince
        first_untaken_prince += 1
      else
        break
      end
    end
    puts "IMPROVE\n#{first_untaken_princess} #{first_untaken_prince}"
  else
    puts "OPTIMAL"
  end
end

t = gets.to_i
t.times do
  n = gets.to_i
  k = []
  g = []
  da = Array.new(n, nil)
  pr = Array.new(n, nil)
  married = 0
  n.times do |i|
    k[i], *g[i] = gets.split.map(&:to_i)
    ok = false
    for j in 0...k[i] do
      if pr[g[i][j] - 1].nil?
        da[i] = g[i][j]
        pr[g[i][j] - 1] = i + 1
        ok = true
        break
      end
    end
    married += 1 if ok
  end
  if married < n
    puts "IMPROVE"
    puts "#{da.index(nil) + 1} #{pr.index(nil) + 1}"
  else
    puts "OPTIMAL"
  end
end


"The zombies are lurking outside. Waiting. Moaning. And when they come...""When they come?""I hope the Wall is high enough."Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.

The first line of the input consists of two space-separated integers R and C, 1 ≤ R, C ≤ 100. The next R lines provide a description of the columns as follows:    each of the R lines contains a string of length C,  the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise.  B

The number of wall segments in the input configuration.

NoteIn the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.

rows, cols = gets.split(' ').map(&:to_i)
(rows-1).times { gets }

parts = 0
part = false
gets.chomp.each_char do |ch|
  if ch == 'B'
    part = true if !part
  else
    parts += 1 if part
    part = false
  end
end

parts += 1 if part

puts parts

n , m = gets.split.map(&:to_i)
s = ""
n.times do
    s = gets.strip
end
arr = s.split(".")

ans = 0
for i in arr
    if i.include? "B"
        ans +=1
    end
end
puts ans

n , m = gets.split.map(&:to_i)
s = ""
n.times do
    s = gets.strip
end
arr = s.split(".")
puts arr
ans = 0
for i in arr
    if i.include? "B"
        ans +=1
    end
end
puts ans


You've got table a, consisting of n rows, numbered from 1 to n. The i-th line of table a contains ci cells, at that for all i (1 < i ≤ n) holds ci ≤ ci - 1. Let's denote s as the total number of cells of table a, that is, . We know that each cell of the table contains a single integer from 1 to s, at that all written integers are distinct. Let's assume that the cells of the i-th row of table a are numbered from 1 to ci, then let's denote the number written in the j-th cell of the i-th row as ai, j. Your task is to perform several swap operations to rearrange the numbers in the table so as to fulfill the following conditions:  for all i, j (1 < i ≤ n; 1 ≤ j ≤ ci) holds ai, j > ai - 1, j;  for all i, j (1 ≤ i ≤ n; 1 < j ≤ ci) holds ai, j > ai, j - 1. In one swap operation you are allowed to choose two different cells of the table and swap the recorded there numbers, that is the number that was recorded in the first of the selected cells before the swap, is written in the second cell after it. Similarly, the number that was recorded in the second of the selected cells, is written in the first cell after the swap.Rearrange the numbers in the required manner. Note that you are allowed to perform any number of operations, but not more than s. You do not have to minimize the number of operations.

The first line contains a single integer n (1 ≤ n ≤ 50) that shows the number of rows in the table. The second line contains n space-separated integers ci (1 ≤ ci ≤ 50; ci ≤ ci - 1) — the numbers of cells on the corresponding rows. Next n lines contain table а. The i-th of them contains ci space-separated integers: the j-th integer in this line represents ai, j. It is guaranteed that all the given numbers ai, j are positive and do not exceed s. It is guaranteed that all ai, j are distinct.

In the first line print a single integer m (0 ≤ m ≤ s), representing the number of performed swaps. In the next m lines print the description of these swap operations. In the i-th line print four space-separated integers xi, yi, pi, qi (1 ≤ xi, pi ≤ n; 1 ≤ yi ≤ cxi; 1 ≤ qi ≤ cpi). The printed numbers denote swapping the contents of cells axi, yi and api, qi. Note that a swap operation can change the contents of distinct table cells. Print the swaps in the order, in which they should be executed.

n = gets.to_i
gets

a = Array.new(n) {
  gets.split.map{|x| x.to_i - 1}
}

b = []
n.times {|i|
  a[i].each_index {|j|
    b << [i, j]
  }
}

c = []
50.times {
  n.times {|i|
  a[i].each_index {|j|
    t = a[i][j]
    next if b[t] == [i, j]
    x, y = *b[t]
    a[i][j], a[x][y] = a[x][y], a[i][j]
    c << [i, j, x, y].map(&:succ)
  }
}
}
p c.size
puts c.map{|i| i * ' '}

n = gets.chomp.to_i
c = gets.chomp.split(" ").map{|e| e.to_i}
tables = []
map = {}
1.upto(n) do |y|
  col = gets.chomp.split(" ").map{|e| e.to_i}
  tables << col

  col.each_with_index do |num, x|
    map[num] = [y, x + 1]
  end
end
ans = []
k = 0
idx = 1
for i in 1 .. n do
  for j in 1 .. c[i - 1] do
    k += 1
    next if tables[i - 1][j - 1] == k

    y = map[k].first
    x = map[k].last

    ans << [i, j, y, x]

    # swap
    tmp = tables[i - 1][j - 1]
    tables[i - 1][j - 1] = k
    tables[y - 1][x - 1] = tmp

    map[k] = [i, j]
    map[tmp] = [y, x]
  end
end

puts ans.length
ans.each do |line|
  puts line.join(" ")
end

#!/usr/bin/env ruby
n = gets.to_i
gets
t = []
n.times do
  t << gets.split.map(&:to_i)
end
results = []
n.times do |i|
  t[i].length.times do |j|
    mi, mj = i, j
    (i..(n - 1)).each do |ni|
      (j..(t[ni].length - 1)).each do |nj|
        if t[ni][nj] < t[mi][mj]
          mi, mj = ni, nj
        end
      end
    end
    if mi != i || mj != j
      results.push([i, j, mi, mj])
      t[i][j], t[mi][mj] = t[mi][mj], t[i][j]
    end
  end
end
puts results.length
results.each do |r|
  puts r.map { |x| x + 1 }.join(" ")
end

n = gets.to_i
c = gets.chomp.split.map(&:to_i)
s = c.inject(&:+)
a = []
l = []
o = []
n.times do |i|
    a[i] = gets.chomp.split.map(&:to_i)
    0.upto(c[i]-1) do |j|
        l[a[i][j]] = [i,j]
        o[i+j] = [] if o[i+j].nil?
        o[i+j].push([i,j])
    end
end

c = 0
moves = []
curr = 0
1.upto(s) do |i|
    curr = curr + 1 if o[curr].empty?
    tr, tc = o[curr].pop
    fr, fc = l[i]
    unless tr == fr && tc == fc
        moves.push([tr+1,tc+1,fr+1,fc+1])
        l[a[fr][fc]] = [tr,tc]
        l[a[tr][tc]] = [fr,fc]
        a[fr][fc], a[tr][tc] = a[tr][tc], a[fr][fc]
        c += 1
    end
end
puts c
c.times do |i|
    puts moves[i].join(" ")
end

n = gets.to_i
gets

a = Array.new(n) {
  gets.split.map{|x| x.to_i - 1}
}

b = []
n.times {|i|
  a[i].each_index {|j|
    b << [i, j]
  }
}

c = []
n.times {|i|
  a[i].each_index {|j|
    t = a[i][j]
    next if b[t] == [i, j]
    x, y = *b[t]
    a[i][j], a[x][y] = a[x][y], a[i][j]
    c << [i, j, x, y].map(&:succ)
  }
}
p c.size
puts c.map{|i| i * ' '}

n = gets.chomp.to_i
c = gets.chomp.split(" ").map{|e| e.to_i}
tables = []
map = {}
1.upto(n) do |y|
  col = gets.chomp.split(" ").map{|e| e.to_i}
  tables << col

  col.each_with_index do |num, x|
    map[num] = [y, x + 1]
  end
end
ans = []
p map
k = 0
idx = 1
for i in 1 .. n do
  for j in 1 .. c[i - 1] do
    k += 1
    next if tables[i - 1][j - 1] == k

    y = map[k].first
    x = map[k].last

    ans << [i, j, y, x]

    # swap
    tmp = tables[i - 1][j - 1]
    tables[i - 1][j - 1] = k
    tables[y - 1][x - 1] = tmp

    map[k] = [i, j]
    map[tmp] = [y, x]
  end
end

puts ans.length
ans.each do |line|
  puts line.join(" ")
end


It is the easy version of the problem. The only difference is that in this version $$$n = 1$$$.In the cinema seats can be represented as the table with $$$n$$$ rows and $$$m$$$ columns. The rows are numbered with integers from $$$1$$$ to $$$n$$$. The seats in each row are numbered with consecutive integers from left to right: in the $$$k$$$-th row from $$$m (k - 1) + 1$$$ to $$$m k$$$ for all rows $$$1 \le k \le n$$$. $$$1$$$$$$2$$$$$$\cdots$$$$$$m - 1$$$$$$m$$$$$$m + 1$$$$$$m + 2$$$$$$\cdots$$$$$$2 m - 1$$$$$$2 m$$$$$$2m + 1$$$$$$2m + 2$$$$$$\cdots$$$$$$3 m - 1$$$$$$3 m$$$$$$\vdots$$$$$$\vdots$$$$$$\ddots$$$$$$\vdots$$$$$$\vdots$$$$$$m (n - 1) + 1$$$$$$m (n - 1) + 2$$$$$$\cdots$$$$$$n m - 1$$$$$$n m$$$ The table with seats indices There are $$$nm$$$ people who want to go to the cinema to watch a new film. They are numbered with integers from $$$1$$$ to $$$nm$$$. You should give exactly one seat to each person.It is known, that in this cinema as lower seat index you have as better you can see everything happening on the screen. $$$i$$$-th person has the level of sight $$$a_i$$$. Let's define $$$s_i$$$ as the seat index, that will be given to $$$i$$$-th person. You want to give better places for people with lower sight levels, so for any two people $$$i$$$, $$$j$$$ such that $$$a_i < a_j$$$ it should be satisfied that $$$s_i < s_j$$$.After you will give seats to all people they will start coming to their seats. In the order from $$$1$$$ to $$$nm$$$, each person will enter the hall and sit in their seat. To get to their place, the person will go to their seat's row and start moving from the first seat in this row to theirs from left to right. While moving some places will be free, some will be occupied with people already seated. The inconvenience of the person is equal to the number of occupied seats he or she will go through.Let's consider an example: $$$m = 5$$$, the person has the seat $$$4$$$ in the first row, the seats $$$1$$$, $$$3$$$, $$$5$$$ in the first row are already occupied, the seats $$$2$$$ and $$$4$$$ are free. The inconvenience of this person will be $$$2$$$, because he will go through occupied seats $$$1$$$ and $$$3$$$.Find the minimal total inconvenience (the sum of inconveniences of all people), that is possible to have by giving places for all people (all conditions should be satisfied).

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$n = 1$$$, $$$1 \le m \le 300$$$) — the number of rows and places in each row respectively. The second line of each test case contains $$$n \cdot m$$$ integers $$$a_1, a_2, \ldots, a_{n \cdot m}$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the sight level of $$$i$$$-th person. It's guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print a single integer — the minimal total inconvenience that can be achieved.

NoteIn the first test case, there is a single way to arrange people, because all sight levels are distinct. The first person will sit on the first seat, the second person will sit on the second place, the third person will sit on the third place. So inconvenience of the first person will be $$$0$$$, inconvenience of the second person will be $$$1$$$ and inconvenience of the third person will be $$$2$$$. The total inconvenience is $$$0 + 1 + 2 = 3$$$.In the second test case, people should sit as follows: $$$s_1 = 2$$$, $$$s_2 = 1$$$, $$$s_3 = 5$$$, $$$s_4 = 4$$$, $$$s_5 = 3$$$. The total inconvenience will be $$$6$$$.

module AtCoder
  class FenwickTree
    def initialize(n = 0)
      @n = n
      @data = Array.new(n, 0).unshift(nil)
    end

    def add(idx, x)
      idx += 1
      while idx <= @n
        @data[idx] += x
        idx += idx & -idx
      end
      self
    end

    def sum(l, r)
      __sum__(r) - __sum__(l)
    end

    private

    def __sum__(r)
      s = 0
      while r > 0
        s += @data[r]
        r ^= r & -r
      end
      s
    end
  end
end

t = gets.to_i
t.times do

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

order = a.each_with_index.sort_by { |ai, i| [ai, -i] }.map(&:last)

ft = AtCoder::FenwickTree.new(m)
score = 0
order.each do |i|
  score += ft.sum(0, i)
  ft.add(i, 1)
end

puts score

end


Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants.The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has $$$n$$$ hotels, where the $$$i$$$-th hotel is located in the city with coordinate $$$x_i$$$. Sonya is a smart girl, so she does not open two or more hotels in the same city.Sonya understands that her business needs to be expanded by opening new hotels, so she decides to build one more. She wants to make the minimum distance from this hotel to all others to be equal to $$$d$$$. The girl understands that there are many possible locations to construct such a hotel. Thus she wants to know the number of possible coordinates of the cities where she can build a new hotel. Because Sonya is lounging in a jacuzzi in one of her hotels, she is asking you to find the number of cities where she can build a new hotel so that the minimum distance from the original $$$n$$$ hotels to the new one is equal to $$$d$$$.

The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1\leq n\leq 100$$$, $$$1\leq d\leq 10^9$$$) — the number of Sonya's hotels and the needed minimum distance from a new hotel to all others. The second line contains $$$n$$$ different integers in strictly increasing order $$$x_1, x_2, \ldots, x_n$$$ ($$$-10^9\leq x_i\leq 10^9$$$) — coordinates of Sonya's hotels.

Print the number of cities where Sonya can build a new hotel so that the minimum distance from this hotel to all others is equal to $$$d$$$.

NoteIn the first example, there are $$$6$$$ possible cities where Sonya can build a hotel. These cities have coordinates $$$-6$$$, $$$5$$$, $$$6$$$, $$$12$$$, $$$13$$$, and $$$19$$$.In the second example, there are $$$5$$$ possible cities where Sonya can build a hotel. These cities have coordinates $$$2$$$, $$$6$$$, $$$13$$$, $$$16$$$, and $$$21$$$.

n,d = STDIN.readline.strip.split(/\s+/).map(&:to_i)
coordinates = STDIN.readline.strip.split(/\s+/).map(&:to_i)

count = 2
(0..coordinates.length - 2).each do |i|
  if coordinates[i] + d == coordinates[i+1] - d
    count += 1
  else
    if coordinates[i] + d < coordinates[i+1] - d
      count += 1
    end
    if coordinates[i+1] - d > coordinates[i] + d
      count += 1
    end
  end
end

puts count

n, d = gets.chomp.split.map(&:to_i)
x = gets.chomp.split.map(&:to_i)
a = {}
x.each do |i|
	a[i-d] =0; a[i+d] = 0;
end

ac = 0
a.keys.each do |i|
	flag = 1
	x.each do |j|
		flag = 0 if ((i-j).abs < d)
	end

	ac += flag
end

print ac

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

count = 2

cities.each_cons(2) do |city1, city2|

  if city1 + d < city2 - d
    count += 2
  elsif city1 + d == city2 - d
    count += 1
  end

end

puts count

require 'set'

def solution
  m, d = read_ints
  cs = read_ints

  cities = Set.new

  cs.each.with_index do |c, i|
    before = c - d
    after = c + d

    cities << before if i == 0 || before - cs[i-1] >= d
    cities << after if i == cs.size-1 || cs[i+1] - after >= d
  end

  puts cities.size

end

def read_int
  gets.to_i
end

def read_ints
  gets.split.map(&:to_i)
end

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']

N, D = gets.split.map(&:to_i)
xs = gets.split.map(&:to_i)

ans = 2
(N-1).times do |i|
    if xs[i] < xs[i+1] - 2*D
        ans += 2
    elsif xs[i] == xs[i+1] - 2*D
        ans += 1
    end
end
puts ans

n, d = gets.strip.split.map(&:to_i)
ary = gets.strip.split.map(&:to_i)
ary.sort!

possible_locations = []
ary.each do |c|
  possible_locations << (c+d)
  possible_locations << (c-d)
end
possible_locations.uniq!
ans = 0
possible_locations.each do |nc|
  # puts nc
  # puts ary.map{|oc| (nc-oc).abs >= d }.inspect
  if ary.map{|oc| (nc-oc).abs }.min == d
    # puts nc
    ans += 1
  end
end
puts ans

$n,$d=gets.split
$n,$d=$n.to_i,$d.to_i
a=gets.split
i,ans,len=0,0,a.length
def test(val,id)
	yield id,val+$d
	yield id,val-$d
end
a.each do |c|
	test(c.to_i,i){|id,pos|
			flag=1
			if id>0 and pos-a[id-1].to_i<$d
			flag=0
			end
			if id<len-1 and a[id+1].to_i-pos<=$d
			flag=0
			end
			if flag!=0
			ans=ans+1
			end
			}
	i=i+1
end
puts ans
#a.each do |c| if c%2==0 then print c-1
#	   else print c
#	   end
#	   print " "
#	end

n,d = STDIN.readline.strip.split(/\s+/).map(&:to_i)
coordinates = STDIN.readline.strip.split(/\s+/).map(&:to_i)

count = 2
(0..coordinates.length - 2).each do |i|
  if coordinates[i] + d == coordinates[i+1] - d
    count += 1
  else
    if coordinates[i] + d < coordinates[i+1]
      count += 1
    end
    if coordinates[i-1] - d > coordinates[i]
      count += 1
    end
  end
end

puts count

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

count = 2

cities.each_cons(3) do |city1, city2, city3|

  if city2 - d > city1 + d
    count += 1
  end
  if city2 - d == city1 + d
    count += 1
  end
  if city2 + d < city3 - d
    count += 1
  end

end

if cities.count == 1
  puts '2'
else
  if cities[0] + d < cities[1] - d
    count += 1
  end
  if cities[n - 2] + d < cities[n - 1] - d
    count += 1
  end

  puts count
end


Little girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from $$$1$$$ to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains $$$3$$$ steps, and the second contains $$$4$$$ steps, she will pronounce the numbers $$$1, 2, 3, 1, 2, 3, 4$$$.You are given all the numbers pronounced by Tanya. How many stairways did she climb? Also, output the number of steps in each stairway.The given sequence will be a valid sequence that Tanya could have pronounced when climbing one or more stairways.

The first line contains $$$n$$$ ($$$1 \le n \le 1000$$$) — the total number of numbers pronounced by Tanya. The second line contains integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 1000$$$) — all the numbers Tanya pronounced while climbing the stairs, in order from the first to the last pronounced number. Passing a stairway with $$$x$$$ steps, she will pronounce the numbers $$$1, 2, \dots, x$$$ in that order. The given sequence will be a valid sequence that Tanya could have pronounced when climbing one or more stairways.

In the first line, output $$$t$$$ — the number of stairways that Tanya climbed. In the second line, output $$$t$$$ numbers — the number of steps in each stairway she climbed. Write the numbers in the correct order of passage of the stairways.

n = STDIN.readline.to_i
numbers = STDIN.readline.strip.split(/\s+/).map(&:to_i)

indices = []
(0..numbers.length - 1).each do |i|
  indices << i if numbers[i] == 1
end
indices << numbers.length

outputs = []
(0..indices.length - 2).each do |i|
  outputs << indices[i + 1] - indices[i]
end

puts outputs.length
puts outputs.join(' ')

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

z = 0
count = 0
ac = []
a.each_with_index do |x, i|
	if x == z + 1
		z += 1
		next
	else
		ac << z
		count +=1
		z = x
	end
end

ac << z
puts count + 1
puts ac.join(" ")

n = gets.to_i
a = gets.split.map(&:to_i)
ans = a.chunk_while { _1 < _2 }.map(&:size)
puts ans.size, ans.join(" ")

gets;a=(gets.split.map(&:to_i)+[1]).each_cons(2).select{|x,y|x>=y}.map{|x,y|x};p a.size;puts a*' '

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

stair_sizes = []
crt = 0

numbers.each do |n|
if n == crt + 1
  crt += 1
else
  stair_sizes.push crt
  crt = 1
end
end
stair_sizes.push crt

p stair_sizes.size
puts stair_sizes.join ' '

N = gets.to_i
as = gets.split.map(&:to_i)
ans = []
as.each do |a|
    if a == 1
        ans.push(a)
    else
        ans[-1] = a
    end
end
puts ans.length
puts ans.join(' ')

t = gets.to_i
ary = gets.strip.split.map(&:to_i)

if t==1
  puts "1\n1"
else
  steps = []
  0.upto(t-2).each do |x|
    steps << ary[x] if ary[x+1]==1
  end
  steps << ary[-1]
  puts steps.size
  puts steps.join(" ")
end

number_of_elems = gets.strip.to_i
array = gets.strip.split.to_a.collect { |val| val.to_i }
answer = []
(1...array.size).each do |i|
  answer << array[i-1] if array[i] <= array[i-1]
end
answer << array[-1]
puts answer.size
puts answer.join(' ')

n = gets.to_i
steps = gets.split.map(&:to_i)
stepss = []
t = []
steps.each do |step|
  if step == 1
    stepss << t unless t.empty?
    t = [1]
  else
    t << step
  end
end
stepss << t
puts stepss.count
puts stepss.map { |a| a.max }.join(" ")

x = gets.chomp.to_i
stairways =  gets.strip.split.map(&:to_i)
res = 1
arr = Array.new
for i in 1 ... x
 if stairways[i] > stairways[i-1]
   res +=1
 else if !(stairways[i] > stairways[i-1])
        arr.push(res)
        res=1
      end
 end
end
arr.push(res)
puts arr.size
puts arr.join(' ')

number = gets().to_i
list = gets().chomp.split.map(&:to_i)

ans = []
count = 0
for i in 0...list.length

  if(list[i+1] == 1 || i == list.length-1)
    ans.push(list[i])
  end
  if(list[i] == 1)
    count = count+1
  end
end

puts count
for i in 0...ans.length
  print ans[i]
  print " "
end

gets
t = []
t << gets.split.map{|x| x.to_i}.inject(0) do |s, x|
    t << s if x == 1 && s > 0
    x
end
puts(t.size, t.join(' '))

n = gets
input = gets

#TEST INPUTS
# input = "1 2 3 1 2 3 4"
#2
#3 4

# input = "1 1 1 1"
# 4
# 1 1 1 1

# input = "1 2 3 4 5"
# 1
# 5

# input = "1 2 1 2 1"
# 3
# 2 2 1

counts = input.split(" ").map(&:to_i)

last = 0
output = []
counts.each.with_index do |a_count, index|
	if a_count <= last
		#a new max step is added
		output << counts[index - 1]
	end
	last = a_count
end

output << counts.last

puts output.count
puts output.join(" ")

t = gets.to_i
stairs = gets.chomp.split(" ").map(&:to_i)

no = 1
arr = []
prev = 0

stairs.each do |x|
  if x<=prev
    no+=1
    arr.push prev
  end

  prev = x
end

arr.push stairs[-1]
puts no
print arr*" "
puts

gets
n = gets.split.map { |x| x.to_i }
k = []
c = 0
n[1, n.size-1].each_with_index do |x,i|
  if x == 1
    k << n[i]
    c += 1
  end
end
k.push(n.last)
c += 1
puts c
puts(k.join ' ')

N = gets.to_i
as = gets.split.map(&:to_i)
ans = []
as.each do |a|
    if a == 1
        ans.push(a)
    else
        ans[-1] = a
    end
end
puts ans.join(' ')


There are $$$n$$$ block towers in a row, where tower $$$i$$$ has a height of $$$a_i$$$. You're part of a building crew, and you want to make the buildings look as nice as possible. In a single day, you can perform the following operation:  Choose two indices $$$i$$$ and $$$j$$$ ($$$1 \leq i, j \leq n$$$; $$$i \neq j$$$), and move a block from tower $$$i$$$ to tower $$$j$$$. This essentially decreases $$$a_i$$$ by $$$1$$$ and increases $$$a_j$$$ by $$$1$$$. You think the ugliness of the buildings is the height difference between the tallest and shortest buildings. Formally, the ugliness is defined as $$$\max(a)-\min(a)$$$. What's the minimum possible ugliness you can achieve, after any number of days?

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the number of buildings. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^7$$$) — the heights of the buildings.

For each test case, output a single integer — the minimum possible ugliness of the buildings.

NoteIn the first test case, the ugliness is already $$$0$$$.In the second test case, you should do one operation, with $$$i = 1$$$ and $$$j = 3$$$. The new heights will now be $$$[2, 2, 2, 2]$$$, with an ugliness of $$$0$$$.In the third test case, you may do three operations:   with $$$i = 3$$$ and $$$j = 1$$$. The new array will now be $$$[2, 2, 2, 1, 5]$$$,  with $$$i = 5$$$ and $$$j = 4$$$. The new array will now be $$$[2, 2, 2, 2, 4]$$$,  with $$$i = 5$$$ and $$$j = 3$$$. The new array will now be $$$[2, 2, 3, 2, 3]$$$.  The resulting ugliness is $$$1$$$. It can be proven that this is the minimum possible ugliness for this test.

def find_ugliness(heights, building_num)
  sum = heights.sum
  remainder = sum.modulo(building_num)

  # move makes no effect when difference is 0 or 1
  if remainder == 0
    return 0
  else
    return 1
  end

end

test_case_num = gets.chomp.to_i

ugliness_array = []

test_case_num.times do |idx|
  # read input
  building_num = gets.chomp.to_i
  heights = gets.chomp.strip.split(" ").map!(&:to_i)

  ugliness_array.append(find_ugliness(heights, building_num))

end

ugliness_array.each do |ugliness_single|
  puts ugliness_single
end

t = gets.chomp
for i in 0..t.to_i-1
    n = gets.chomp.to_i
    arr = gets.chomp.split(" ")
    arr = arr.map{|n| n.to_i}
    if arr.sum % n == 0
        puts 0
    else
        puts 1
    end
end


You are given $$$n$$$ segments on a number line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide.The intersection of a sequence of segments is such a maximal set of points (not necesserily having integer coordinates) that each point lies within every segment from the sequence. If the resulting set isn't empty, then it always forms some continuous segment. The length of the intersection is the length of the resulting segment or $$$0$$$ in case the intersection is an empty set.For example, the intersection of segments $$$[1;5]$$$ and $$$[3;10]$$$ is $$$[3;5]$$$ (length $$$2$$$), the intersection of segments $$$[1;5]$$$ and $$$[5;7]$$$ is $$$[5;5]$$$ (length $$$0$$$) and the intersection of segments $$$[1;5]$$$ and $$$[6;6]$$$ is an empty set (length $$$0$$$).Your task is to remove exactly one segment from the given sequence in such a way that the intersection of the remaining $$$(n - 1)$$$ segments has the maximal possible length.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the number of segments in the sequence. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \le l_i \le r_i \le 10^9$$$) — the description of the $$$i$$$-th segment.

Print a single integer — the maximal possible length of the intersection of $$$(n - 1)$$$ remaining segments after you remove exactly one segment from the sequence.

NoteIn the first example you should remove the segment $$$[3;3]$$$, the intersection will become $$$[2;3]$$$ (length $$$1$$$). Removing any other segment will result in the intersection $$$[3;3]$$$ (length $$$0$$$).In the second example you should remove the segment $$$[1;3]$$$ or segment $$$[2;6]$$$, the intersection will become $$$[2;4]$$$ (length $$$2$$$) or $$$[1;3]$$$ (length $$$2$$$), respectively. Removing any other segment will result in the intersection $$$[2;3]$$$ (length $$$1$$$).In the third example the intersection will become an empty set no matter the segment you remove.In the fourth example you will get the intersection $$$[3;10]$$$ (length $$$7$$$) if you remove the segment $$$[1;5]$$$ or the intersection $$$[1;5]$$$ (length $$$4$$$) if you remove the segment $$$[3;10]$$$.

#idea_copied_From_ToErr_Vaia
#but_not_sorted
def call(ind,a)
	r = 30**9
	l = -2
	for i in 0...a.size
		if(i != ind)
			r = [r,a[i].r].min
			l = [l,a[i].l].max
		end
	end
	return r-l
end

pair = Struct.new(:l,:r)
a = []
n = STDIN.readline.to_i
for i in 1..n
	p = STDIN.readline.split(" ")
	s = pair.new(p[0].to_i,p[1].to_i)
	a << s
end
# a.sort! {|z,b| z.r <=> b.r}

r = 30**9
l = -1
for i in 0...n
	if a[i].r < r
		r = a[i].r
		ri = i
	end
	if a[i].l > l
		l = a[i].l
		li = i
	end
end

ans = 0
ans = [ans,call(li,a)].max
ans = [ans,call(ri,a)].max

print ans

#idea_copied_From_ToErr_Vaia

def call(ind,a)
	r = 30**9
	l = -2
	for i in 0...a.size
		if(i != ind)
			r = [r,a[i].r].min
			l = [l,a[i].l].max
		end
	end
	return r-l
end

pair = Struct.new(:l,:r)
a = []
n = STDIN.readline.to_i
for i in 1..n
	p = STDIN.readline.split(" ")
	s = pair.new(p[0].to_i,p[1].to_i)
	a << s
end
a.sort! {|z,b| z.r <=> b.r}

r = 30**9
l = -1
for i in 0...n
	if a[i].r < r
		r = a[i].r
		ri = i
	end
	if a[i].l > l
		l = a[i].l
		li = i
	end
end

ans = 0
ans = [ans,call(li,a)].max
ans = [ans,call(ri,a)].max

print ans