You are given an integer $$$x$$$ and an array of integers $$$a_1, a_2, \ldots, a_n$$$. You have to determine if the number $$$a_1! + a_2! + \ldots + a_n!$$$ is divisible by $$$x!$$$.Here $$$k!$$$ is a factorial of $$$k$$$ — the product of all positive integers less than or equal to $$$k$$$. For example, $$$3! = 1 \cdot 2 \cdot 3 = 6$$$, and $$$5! = 1 \cdot 2 \cdot 3 \cdot 4 \cdot 5 = 120$$$.

The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 500\,000$$$, $$$1 \le x \le 500\,000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le x$$$) — elements of given array.

In the only line print "Yes" (without quotes) if $$$a_1! + a_2! + \ldots + a_n!$$$ is divisible by $$$x!$$$, and "No" (without quotes) otherwise.

# This solution relies on the fact that y! is divisible by x! if the value of y >= x
# So for multiple numbers: m! + n! + o! would be divisible by x! if m, n, and o are less than or equal to x

# Now the above fails if there are factorials of the same number like:
# (4! + 4! + 4! + 4! + 4!) which is divisible by 5! even though 4 is less than 5
# In these cases we can try to combine lower order factorials into higher order factorials
# i.e. (4! + 4! + 4! + 4! + 4!) can be represented as 5(4!) which is 5! thus its clearly divisible by 5!

# If the lower order factorials cannot be combined and are less than divisor factorial then it is not divisible

# I'm applying the above method using by storing the frequency of each number in a hash (called count)
def factorial_divisibility?(divisor, num_array)
  # tally method creates a hash by frequency Eg: [1, 1, 2, 3, 3, 3, 3, 3] becomes {1=>2, 2=>1, 3=>5}
  count = num_array.tally
  count.default = 0

  # iterate up till the value of divisor any more is not needed
  divisor.times do |i|
    # if possible try to combine factorials and add to next order factorial
    if count[i] > i
      count[i + 1] += count[i] / (i + 1)
      count[i] %= (i + 1)
    end
    return false if count[i].positive? # return false if some factorial that cannot be combined still exists
  end
  true
end

# code for tests:

divisor = gets.chomp.split.last.to_i
num_arr = gets.chomp.split.map(&:to_i)

factorial_divisibility?(divisor, num_arr) ? (puts 'Yes') : (puts 'No')

# This solution relies on the fact that y! is divisible by x! if the value of y >= x
# So for multiple numbers: m! + n! + o! would be divisible by x! if m, n, and o are less than or equal to x

# Now the above fails if there are factorials of the same number like:
# (4! + 4! + 4! + 4! + 4!) which is divisible by 5! even though 4 is less than 5
# In these cases we can try to combine lower order factorials into higher order factorials
# i.e. (4! + 4! + 4! + 4! + 4!) can be represented as 5(4!) which is 5! thus its clearly divisible by 5!

# If the lower order factorials cannot be combined and are less than divisor factorial then it is not divisible

# I'm applying the above method using by storing the frequency of each number in a hash (called count)
def factorial_divisibility?(divisor, num_array)
  # tally method creates a hash by frequency Eg: [1, 1, 2, 3, 3, 3, 3, 3] becomes {1=>2, 2=>1, 3=>5}
  count = num_array.tally
  count.default = 0

  # iterate up till the value of divisor any more is not needed
  divisor.times do |i|
    # if possible try to combine factorials and add to next order factorial
    if count[i] > i
      count[i + 1] += count[i] / (i + 1)
      count[i] %= (i + 1)
    end
    return false if count[i].positive? # return false if some factorial that cannot be combined still exists
  end
  true
end

# code for tests:

divisor = gets.chomp[-1].to_i
num_arr = gets.chomp.split.map(&:to_i)

factorial_divisibility?(divisor, num_arr) ? (puts 'Yes') : (puts 'No')


Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy.

The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000).

On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1.

NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana".

#!/usr/bin/ruby
h=Hash.new(0)
gets.chomp.chars{|c|h[c]+=1}
n=gets.to_i
if h.size>n
	p -1
	exit
end
a=h.sort_by{|e|-e[1]}
x=[1]*a.size
z=n-a.size
while z>0
	b=a.each_with_index.max_by{|e,i|e.last*1.0/(x[i])}
	x[b.last]+=1
	z-=1
end
p a.each_with_index.map{|e,i|(e.last+x[i]-1)/x[i]}.max
puts a.each_with_index.map{|e,i|e.first*x[i]}*''

#!/usr/bin/ruby
h=Hash.new(0)
gets.chomp.chars{|c|h[c]+=1}
n=gets.to_i
if h.size>n
	p -1
	exit
end
a=h.sort_by{|e|-e[1]}
x=[1]*a.size
(n-a.size).times{x[a.each_with_index.max_by{|e,i|e.last*1.0/x[i]}.last]+=1}
p a.each_with_index.map{|e,i|(e.last+x[i]-1)/x[i]}.max
puts a.each_with_index.map{|e,i|e.first*x[i]}*''

s=gets.chomp
n=gets.to_i
h=Hash[s.each_char.group_by{|x|x}.map{|k,v|[k,v.size]}]
if h.size>n
  p -1
  exit
end
r=Hash.new(0)
while n>0
  m=h.max_by{|k,v|r.key?(k)?v.to_f/r[k]:2000}
  r[m[0]]+=1
  n-=1
end
p h.map{|k,v|(v+r[k]-1)/r[k]}.max
r.each{|k,v|print(k*v)}

s = gets.chomp.scan(/./)
n = gets.to_i
a = [0] * 26
for x in s
  a[x.ord - 'a'.ord] += 1
end
l, r = 0, s.length
while r - l > 1
  m = (r + l) / 2
  cnt = n
  for i in 0...26
    if a[i] != 0
      cnt -= (m + a[i] - 1) / m
    end
  end
  if cnt >= 0
    r = m
  else
    l = m
  end
end
ans = ''
for i in 0...26
  if a[i] != 0
    ans += (i + 'a'.ord).chr * ((a[i] + r - 1) / r)
  end
end
if n >= ans.length
  ans += 'a' * (n - ans.length)
else
  puts -1
  exit
end
puts r
puts ans

#!/usr/bin/ruby
h=Hash.new(0)
gets.chomp.chars{|c|h[c]+=1}
n=gets.to_i
if h.size>n
	p -1
	exit
end
a=h.sort_by{|e|-e[1]}
x=[1]*a.size
z=n-a.size
while z>0
	b=a.each_with_index.max_by{|e,i|e.last*1.0/(x[i]+1)}
	x[b.last]+=1
	z-=1
end
p a.each_with_index.map{|e,i|(e.last*1.0/x[i]).ceil}.max
puts a.each_with_index.map{|e,i|e.first*x[i]}*''

#!/usr/bin/ruby
h=Hash.new(0)
gets.chomp.chars{|c|h[c]+=1}
n=gets.to_i
if h.size>n
	p -1
	exit
end
a=h.sort_by{|e|-e[1]}
x=[1]*a.size
z=n-a.size
while z>0
	b=a.each_with_index.max_by{|e,i|e.last*1.0/(x[i]+1)}
	x[b.last]+=1
	z-=1
end
p a.each_with_index.map{|e,i|(e.last+x[i]-1)/x[i]}.max
puts a.each_with_index.map{|e,i|e.first*x[i]}*''

s=gets.chomp
n=gets.to_i
h=Hash[s.each_char.group_by{|x|x}.map{|k,v|[k,v.size]}]
if h.size>n
  p -1
  exit
end
r=Hash.new(0)
while n>0
  m=h.max_by{|k,v|r.key?(k)?v/r[k]:2000}
  r[m[0]]+=1
  n-=1
end
p h.map{|k,v|(v+r[k]-1)/r[k]}.max
r.each{|k,v|print(k*v)}


Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the side equals n squares (n is an odd number) and each unit square contains some small letter of the English alphabet.Valera needs to know if the letters written on the square piece of paper form letter "X". Valera's teacher thinks that the letters on the piece of paper form an "X", if:  on both diagonals of the square paper all letters are the same;  all other squares of the paper (they are not on the diagonals) contain the same letter that is different from the letters on the diagonals. Help Valera, write the program that completes the described task for him.

The first line contains integer n (3 ≤ n < 300; n is odd). Each of the next n lines contains n small English letters — the description of Valera's paper.

Print string "YES", if the letters on the paper form letter "X". Otherwise, print string "NO". Print the strings without quotes.

n=gets.chomp.to_i
a=[]
n.times do
	a.push(gets.chomp.strip)
end
x=a[0][0]
s=a[0][1]
if x==s
	puts 'NO'
	exit
end
puts((0...n).all? { |i| str = s * n; str[i] = str[n - 1 - i] = x; a[i] == str } ? 'YES' : 'NO')

n = gets.to_i
m = []

n.times do
	m << gets.chop.split(//)
end

def method matr, n
	d = matr[0][0]
	o = matr[0][1]

	return 'NO' if o == d

	for i in 0...n
		for j in 0...n
			if i == j or i == n - j - 1
				if d != matr[i][j]
					return 'NO'
				end
			else
				if o != matr[i][j]
					return "NO"
				end
			end
		end
	end

	return 'YES'
end

puts method(m, n)

class ProblemA
  def initialize
    @dats = STDIN.read.split("\n")
    @size = @dats[0].to_i
  end

  def solve
    return false if @size % 2 != 1 || @size >= 300 || @size < 3
    mtx = []
    (1..@size).each do |idx|
      mtx << @dats[idx]
    end
    mtx.flatten!
    mtx = mtx.join("").split(//)
    diag_char = nil
    not_diag_char = nil

    mtx.each_with_index do |char,idx|
      row = idx / @size
      row_mod = row % @size

      if idx == row*@size + row_mod || idx == (row+1)*@size - row_mod - 1
        if diag_char.nil?
          diag_char = char
        else
          if diag_char != char
            return false
          end
        end
      else
        if not_diag_char.nil?
          not_diag_char = char
          return false if not_diag_char == diag_char
        else
          if not_diag_char != char
            return false
          end
        end
      end
    end
    return true
  end
end

solver = ProblemA.new
print solver.solve ? "YES" : "NO"

n = gets.chomp.to_i
paper = []
uniq = []
valid = true
n.times do
    line = gets.chomp.split("")
    uniq << line.uniq if !uniq.include? line.uniq
    paper << line
    if uniq.length > 2
        valid = false
        break
    end
end
pos = []
x = 0
y = n - 1
ui = uj = di = dj = 0
while x < n && y >= 0 && valid
    ui = x
    uj = x
    di = y
    dj = x
    pos << [ui, uj] if !pos.include? [ui, uj]
    pos << [di, dj] if !pos.include? [di, dj]
    x += 1
    y -= 1
end
x = paper[0][0]
y = paper[0][1]
pos.sort!
center = (pos.length - 1) / 2
valid = x != y if valid
start = 0
fin = start + 1
(0...n).each do |i|
    break if !valid
    line = paper[i].clone
    d_index = 0
    pos.values_at(start..fin).each do |p|
        b = p[1]
        if x != paper[i][b]
            valid = false
            break
        elsif x == paper[i][b]
            line.delete_at( b - d_index )
            d_index += 1
        end
    end
    line.uniq!
    if line.length > 1
        valid = false
        break
    else
        if y != line[0]
            valid = false
            break
        end
    end
    start = fin + 1
    if start == center
        fin = start
    else
        fin = start + 1
    end
end
if valid
    puts "YES"
else
    puts "NO"
end

n=gets.to_i
s=STDIN.read.split.map{|e| e.chars.to_a}
ok="YES"
x=s[0][0]
if n>1 then
	y=s[0][1]
	ok="NO" if y==x
	n.times{|i|
		ok="NO" if s[i][i]!=x || s[i][n-i-1]!=x
		s[i].delete_at([n-i-1,i].max)
		if i!=n-i-1 then
			s[i].delete_at([i,n-i-1].min)
		end

		s[i].delete(y)
		ok="NO" if s[i].size>0
	}
end
puts ok

n=gets.to_i
m=[]

n.times do
    m<<gets.chop.split(//)
end

def method matr,n
    d=matr[0][0]
    o=matr[0][1]

    return 'NO' if d==o
    for i in 0...n
        for j in 0...n
            if i==j or i == n-j-1
                if d!=matr[i][j]
                    return 'NO'
                end
            else
                if o!=matr[i][j]
                        return 'NO'
                end
            end
        end
    end

    return 'YES'
end

puts method(m,n)

n = gets.chomp!.to_i
a = Array.new(n)

n.times{|i|
    a[i] = gets.chomp!
}

if n==1
    puts "YES"
    exit
end

x = a[0][0]
b = a[0][1]

if x == b
    puts "NO"
    exit
end
n.times { |i|
    n.times { |j|
        if i==j || (i+j==n-1)
            if a[i][j] != x
                puts "NO"
                exit
            end
        else
             if a[i][j] != b
                puts "NO"
                exit
            end
        end
    }
}

puts "YES"

n = Integer(gets)
a = Array.new
for i in 0...n
    a[i] = Array.new
    input = gets.chomp
    for j in 0...n
        a[i][j] = input[j]
    end
end
e = 0
if a[0][1] != a[0][0]
    e = 1
end
c = 1
for i in 0...n
    if a[i][i] != a[i][n-1-i] || a[0][0] != a[n/2][n/2]
        c = 0
        break
    end
end

b = Array.new
    for i in 0...n
        b[i] = Array.new
        a[i][i] = a[i][n - 1 - i] = a [0][1]
        for j in 0...n
        b[i][j] = a[0][1]
        end
    end

d = 1
for i in 0...n
    for j in 0...n
        if a[i][j] != b[i][j]
            d = 0
            break
        end
    end
end

if e == 1 && c == 1 && d == 1
    puts "YES"
else
    puts "NO"
end

n = gets.chomp.to_i
mat = Array.new(n)

n.times do |i|
    mat[i] = gets.chomp
end

ok = true
x = mat[0][0]
o = mat[0][1]

if x == o
    puts "NO"
    exit
end

n.times do |i|
    n.times do |j|
        if i == j || i + j == n - 1
            if mat[i][j] != x
                ok = false
                break
            end
        else
            if mat[i][j] != o
                ok = false
                break
            end
        end
    end

    break if ok == false
end

puts ok == true ? "YES" : "NO"

n = STDIN.readline.to_i
f = []
n.times do
	f << STDIN.readline.delete(?\n)
end
# print f

ans = true
n.times do |i|
	ans = false if f[i][i]    != f[0][0]
	ans = false if f[i][-i-1] != f[0][0]
end

s = f.join
s.delete! s[0]
unless s.length == (n-1)**2 && s.delete(s[0]).length == 0 ;
	ans = false
end

if ans == true ;
	print "YES\n"
else
	print "NO\n"
end

def diagonal?(i,j,n)
  (i == j) || (j == n - i )
end

matrix = []
n = gets.to_i

n.times do
matrix << gets.split('')

end

diagonal_letter = matrix[0][0]
other_letter = matrix[0][1]
forms_x = true
(0...n).each do |i|
  (0...n).each do |j|
    # puts "#{i} #{j} #{matrix[i][j]}"
  if diagonal?(i,j,n-1)
    if diagonal_letter != matrix[i][j]
     # puts "#{i} #{j} #{forms_x} mat #{matrix[i][j]} diag letter #{diagonal_letter} in diag"
     forms_x = false
     break
    end
  elsif other_letter != matrix[i][j]
    # puts "#{i} #{j} #{forms_x}"
    forms_x = false
    break
  end
  end
  break if forms_x == false
end

forms_x = diagonal_letter != other_letter if forms_x
puts forms_x ? "YES" : "NO"

n = gets.to_i
l = nil; o = nil; ret = ""

n.times do |i|
    r = gets.chomp
    if i==0
        l = r[i]; o = r[i+1]
        ret = "NO" if l==o
    end

    n.times do |j|
        if j==i or j==n-i-1
            ret = "NO" if r[j]!=l
        else
            ret = "NO" if r[j]!=o
        end
    end
    break if ret == "NO"
end

if ret=="NO"
    puts "NO"
else
    puts "YES"
end

n = gets.to_i
l = nil; o = nil;

n.times do |i|
    r = gets.chomp
    if i==0
        l = r[i]; o = r[i+1]
        if l==o
            puts "NO"
            exit
        end
    end

    n.times do |j|
        if j==i or j==n-i-1
            if r[j]!=l
                puts "NO"
                exit
            end
        else
            if r[j]!=o
                puts "NO"
                exit
            end
        end
    end
end

puts "YES"

n = gets.to_i
a = n.times.map{gets.chomp}
c = Hash.new(0)
a.each{|x| x.each_char{|y| c[y] += 1}}
ans = n.times.all?{|i| a[i][i] == a[0][0] && a[i][n - 1 - i] == a[0][0]}
ans &&= c[a[0][1]] == (n - 2) * n + 1

puts ans ? 'YES' : 'NO'

n = gets.to_i
a = n.times.map{gets.chomp.chars}
c = Array.new(123, 0)
a.each{|x| x.each{|y| c[y.ord] += 1}}
b = c.each.with_index.sort.reverse

ans = true
n.times do |i|
  ans = false if a[i][i] != a[i][n - 1 - i] || a[i][i] != a[0][0]
  ans = false if c[a[0][0].ord] != 2 * n - 1 || c[a[0][1].ord] != (n - 2) * n + 1
#  p c[a[0][0].ord], c[a[0][1].ord]
end

puts ans ? "YES" : "NO"

n = gets.to_i
a = n.times.map{gets.chomp.chars}
c = Array.new(123, 0)
a.each{|x| x.each{|y| c[y.ord] += 1}}

ans = true
n.times do |i|
  ans = false if a[i][i] != a[i][n - 1 - i] || a[i][i] != a[0][0]
  ans = false if c[a[0][0].ord] != 2 * n - 1 || c[a[0][1].ord] != (n - 2) * n + 1
end

puts ans ? "YES" : "NO"

def run(l)
  c1 = l[0][0]

  hv = l.size/2
  c2 = l[hv][0]

  return "NO" if c1 == c2

  (0...l.size).each do |i|
    (0...l.size).each do |j|
      if i == j
        return "NO" if l[i][j] != c1
      elsif i == l.size-1-j
        return "NO" if l[i][j] != c1
      else
        return "NO" if l[i][j] != c2
      end
    end
  end

  return "YES"
end

n = gets
while n != nil
  l = []
  n.to_i.times do
    t = gets.split(//)[0...-1]
    l << t
  end
  puts run(l)
  n = gets
end

def check_letter (line_num, board)
	diagonals_letters = []
	other_letters = []
	board.each_with_index do |letter_line, index|
		if (index == (line_num/2))
			diagonals_letters << letter_line[index]
			letter_line.delete_at(index)
			letter_line.each { |c| other_letters << c }
		elsif (index > (line_num/2))
			diagonals_letters << letter_line[index]
			diagonals_letters << letter_line[-(index+1)]
			letter_line.delete_at(index)
			letter_line.delete_at(-index)
			letter_line.each { |c| other_letters << c }
		else
			diagonals_letters << letter_line[index]
			diagonals_letters << letter_line[-(index+1)]
			letter_line.delete_at(index)
			letter_line.delete_at(-(index+1))
			letter_line.each { |c| other_letters << c }
		end
	end

	if ((diagonals_letters.uniq).length == 1) and ((other_letters.uniq).length == 1) and (diagonals_letters[0] != other_letters[0])
		return "YES"
	else
		return "NO"
	end
end

line_num = ((gets()).split().shift()).to_i

letter_board = []

for i in 0..(line_num-1)
	row = []
	row = (gets()).split(//)
	row.delete("\n")
	letter_board << row
end

result = check_letter(line_num, letter_board)
puts result

n = gets.to_i
a = (0...n).map { gets.chomp }
x = a[0][0]
s = a[0][1]
if x == s
 puts 'NO'
 exit
end
puts((0...n).all? { |i| str = s * n; str[i] = str[n - 1 - i] = x; a[i] == str } ? 'YES' : 'NO')

#!/usr/bin/ruby
n=gets.to_i
s=$<.map(&:chomp)
a=s[0][0,1]
b=s[0][1,1]
t=n.times.map{|i|
	z=b*n
	z[i,1]=a
	z[n-i-1,1]=a
	z
}
puts s==t ? 'YES' : 'NO'

n = gets.to_i
m = []

n.times do
	m << gets.chop.split(//)
end

def method matr, n
	d = matr[0][0]
	o = matr[0][1]

	for i in 0...n
		for j in 0...n
			if i == j or i == n - j - 1
				if d != matr[i][j]
					return 'NO'
				end
			else
				if o != matr[i][j]
					return "NO"
				end
			end
		end
	end

	return 'YES'
end

puts method(m, n)

class ProblemA
  def initialize
    @dats = STDIN.read.split("\n")
    @size = @dats[0].to_i
  end

  def solve
    mtx = []
    (1..@size).each do |idx|
      mtx << @dats[idx]
    end
    mtx.flatten!
    mtx = mtx.join("").split(//)
    diag_char = nil
    not_diag_char = nil

    mtx.each_with_index do |char,idx|
      row = idx / @size
      row_mod = row % @size

      if idx == row*@size + row_mod || idx == (row+1)*@size - row_mod - 1
        if diag_char.nil?
          diag_char = char
        else
          if diag_char != char
            return false
          end
        end
      else
        if not_diag_char.nil?
          not_diag_char = char
        else
          if not_diag_char != char
            return false
          end
        end
      end
    end
    return true
  end
end

solver = ProblemA.new
p solver.solve ? "YES" : "NO"

class ProblemA
  def initialize
    @dats = STDIN.read.split("\n")
    @size = @dats[0].to_i
  end

  def solve
    mtx = []
    (1..@size).each do |idx|
      mtx << @dats[idx]
    end
    mtx.flatten!
    mtx = mtx.join("").split(//)
    diag_char = nil
    not_diag_char = nil

    mtx.each_with_index do |char,idx|
      row = idx / @size
      row_mod = row % @size

      if idx == row*@size + row_mod || idx == (row+1)*@size - row_mod - 1
        if diag_char.nil?
          diag_char = char
        else
          if diag_char != char
            return false
          end
        end
      else
        if not_diag_char.nil?
          not_diag_char = char
        else
          if not_diag_char != char
            return false
          end
        end
      end
    end
    return true
  end
end

solver = ProblemA.new
print solver.solve ? "YES" : "NO"

class ProblemA
  def initialize
    @dats = STDIN.read.split("\n")
    @size = @dats[0].to_i
  end

  def solve
    return false if @size % 2 != 1 || @size >= 300 || @size < 3
    mtx = []
    (1..@size).each do |idx|
      mtx << @dats[idx]
    end
    mtx.flatten!
    mtx = mtx.join("").split(//)
    diag_char = nil
    not_diag_char = nil

    mtx.each_with_index do |char,idx|
      row = idx / @size
      row_mod = row % @size

      if idx == row*@size + row_mod || idx == (row+1)*@size - row_mod - 1
        if diag_char.nil?
          diag_char = char
        else
          if diag_char != char
            return false
          end
        end
      else
        if not_diag_char.nil?
          not_diag_char = char
        else
          if not_diag_char != char
            return false
          end
        end
      end
    end
    return true
  end
end

solver = ProblemA.new
print solver.solve ? "YES" : "NO"

n = gets.chomp.to_i
paper = []
uniq = []
valid = true
n.times do
    line = gets.chomp.split("")
    uniq << line.uniq if !uniq.include? line.uniq
    paper << line
    if uniq.length > 2
        valid = false
        break
    end
end
pos = []
x = 0
y = n - 1
ui = uj = di = dj = 0
while x < n && y >= 0 && valid
    ui = x
    uj = x
    di = y
    dj = x
    pos << [ui, uj] if !pos.include? [ui, uj]
    pos << [di, dj] if !pos.include? [di, dj]
    x += 1
    y -= 1
end
x = paper[0][0]
y = paper[0][1]
pos.sort!
center = (pos.length - 1) / 2
valid = x != y if valid
start = 0
fin = start + 1
(0...n).each do |i|
    break if !valid
    line = paper[i].clone
    d_index = 0
    puts pos.inspect
    pos.values_at(start..fin).each do |p|
        b = p[1]
        if x != paper[i][b]
            valid = false
            break
        elsif x == paper[i][b]
            line.delete_at( b - d_index )
            d_index += 1
        end
    end
    line.uniq!
    valid = false if line.length > 1
    start = fin + 1
    if start == center
        fin = start
    else
        fin = start + 1
    end
end
if valid
    puts "YES"
else
    puts "NO"
end

n = gets.chomp.to_i
paper = []
n.times do
    paper << gets.chomp.split("")
end
pos = []
x = 0
y = n - 1
ui = uj = di = dj = 0
while x < n && y >= 0
    ui = x
    uj = x
    di = y
    dj = x
    pos << [ui, uj] if !pos.include? [ui, uj]
    pos << [di, dj] if !pos.include? [di, dj]
    x += 1
    y -= 1
end
valid = true
x = paper[0][0]
y = paper[0][1]
(0...n).each do |i|
    break if !valid
    (0...n).each do |j|
        break if !valid
        if pos.include? [i, j]
            if x != paper[i][j]
                valid = false
            end
        else
            if y != paper[i][j]
                valid = false
            end
        end
    end
end
if valid
    puts "YES"
else
    puts "NO"
end

n = gets.chomp.to_i
paper = []
uniq = []
valid = true
n.times do
    line = gets.chomp.split("")
    uniq << line.uniq if !uniq.include? line.uniq
    paper << line
    if uniq.length > 2
        valid = false
        break
    end
end
if valid
    pos = []
    x = 0
    y = n - 1
    ui = uj = di = dj = 0
    while x < n && y >= 0
        ui = x
        uj = x
        di = y
        dj = x
        pos << [ui, uj] if !pos.include? [ui, uj]
        pos << [di, dj] if !pos.include? [di, dj]
        x += 1
        y -= 1
    end
    x = paper[0][0]
    y = paper[0][1]
    valid = x != y
    pos.each do |p|
        break if !valid
        i = p[0]
        j = p[1]
        if x != paper[i][j]
            valid = false
        end
    end
end
if valid
    puts "YES"
else
    puts "NO"
end

n = gets.chomp.to_i
paper = []
uniq = []
valid = true
n.times do
    line = gets.chomp.split("")
    uniq << line.uniq if !uniq.include? line.uniq
    paper << line
    if uniq.length > 2
        valid = false
        break
    end
end
pos = []
x = 0
y = n - 1
ui = uj = di = dj = 0
while x < n && y >= 0 && valid
    ui = x
    uj = x
    di = y
    dj = x
    pos << [ui, uj] if !pos.include? [ui, uj]
    pos << [di, dj] if !pos.include? [di, dj]
    x += 1
    y -= 1
end
x = paper[0][0]
y = paper[0][1]
pos.sort!
center = (pos.length - 1) / 2
valid = x != y if valid
start = 0
fin = start + 1
(0...n).each do |i|
    break if !valid
    line = paper[i].clone
    d_index = 0
    pos.values_at(start..fin).each do |p|
        b = p[1]
        if x != paper[i][b]
            valid = false
            break
        elsif x == paper[i][b]
            line.delete_at( b - d_index )
            d_index += 1
        end
    end
    line.uniq!
    valid = false if line.length > 1
    start = fin + 1
    if start == center
        fin = start
    else
        fin = start + 1
    end
end
if valid
    puts "YES"
else
    puts "NO"
end

n=gets.to_i
s=STDIN.read.split.map{|e| e.chars.to_a}
ok="YES"
x=s[0][0]
if n>1 then
	n.times{|i|
		ok="NO" if s[i][i]!=x || s[i][n-i-1]!=x
		s[i].delete_at([n-i-1,i].max)
		if i!=n-i-1 then
			s[i].delete_at([i,n-i-1].min)
		end
		ok="NO" if s[i][0]==x
		s[i].delete(s[i][0])
		ok="NO" if s[i].size>0
	}
end
puts ok

n=gets.to_i
m=[]

n.times do
    m<<gets.chop.split(//)
end

def method matr,n
    d=matr[0][0]
    o=matr[0][1]

    return 'NO' if d==o
    for i in 0...n
        for j in 0...n
            if i==j or i = n-j-1
                if d!=matr[i][j]
                    return 'NO'
                end
            else
                if o!=matr[i][j]
                        return 'NO'
                end
            end
        end
    end
    return 'YES'
end

puts method(m,n)

n = gets.chomp!.to_i
a = Array.new(n)

n.times{|i|
    a[i] = gets.chomp!
}

if n==1
    puts "YES"
    exit
end

x = a[0][0]
b = a[0][1]
n.times { |i|
    n.times { |j|
        if i==j || (i+j==n-1)
            if a[i][j] != x
                puts "NO"
                exit
            end
        else
             if a[i][j] != b
                puts "NO"
                exit
            end
        end
    }
}

puts "YES"

n = Integer(gets)
a = Array.new
for i in 0...n
	a[i] = Array.new
	input = gets.chomp
	for j in 0...n
		a[i][j] = input[j]
	end
end
e = 0
if a[0][1] != a[0][0]
	e = 1
end
c = 1
for i in 0...n
	if a[i][i] != a[i][n-1-i] || a[0][0] != a[(n-1)/2][(n-1/2)]
		c = 0
		break
	end
end

b = Array.new
	for i in 0...n
		b[i] = Array.new
		a[i][i] = a[i][n - 1 - i] = a [0][1]
		for j in 0...n
		b[i][j] = a[0][1]
		end
	end

d = 1
for i in 0...n
	for j in 0...n
		if a[i][j] != b[i][j]
			d = 0
			break
		end
	end
end

if e == 1 && c == 1 && d == 1
	puts "YES"
else
	puts "NO"
end

n = Integer(gets)
a = Array.new
for i in 0...n
	a[i] = Array.new
	input = gets.chomp
	for j in 0...n
		a[i][j] = input[j]
	end
end
c = 1
for i in 0...n
	if a[i][i] != a[i][n-1-i]
		c = 0
		break
	end
end
puts c

b = Array.new
	for i in 0...n
		b[i] = Array.new
		a[i][i] = a[i][n - 1 - i] = a [0][1]
		for j in 0...n
		b[i][j] = a[0][1]
		end
	end

d = 1
for i in 0...n
	for j in 0...n
		if a[i][j] != b[i][j]
			d = 0
			break
		end
	end
end
puts d

if c == 1 && d == 1
	puts "YES"
else
	puts "NO"
end

n = Integer(gets)
a = Array.new
for i in 0...n
	a[i] = Array.new
	input = gets.chomp
	for j in 0...n
		a[i][j] = input[j]
	end
end
e = 0
if a[0][1] != a[0][0]
	e = 1
end
c = 1
for i in 0...n
	if a[i][i] != a[i][n-1-i] || a[0][0] != a[n/2][n/2]
		c = 0
		break
	end
end
puts c

b = Array.new
	for i in 0...n
		b[i] = Array.new
		a[i][i] = a[i][n - 1 - i] = a [0][1]
		for j in 0...n
		b[i][j] = a[0][1]
		end
	end

d = 1
for i in 0...n
	for j in 0...n
		if a[i][j] != b[i][j]
			d = 0
			break
		end
	end
end

if e == 1 && c == 1 && d == 1
	puts "YES"
else
	puts "NO"
end

n = Integer(gets)
a = Array.new
for i in 0...n
	a[i] = Array.new
	input = gets.chomp
	for j in 0...n
		a[i][j] = input[j]
	end
end
c = 1
for i in 0...n
	if a[i][i] != a[i][n-1-i]
		c = 0
		break
	end
end

b = Array.new
	for i in 0...n
		b[i] = Array.new
		a[i][i] = a[i][n - 1 - i] = a [0][1]
		for j in 0...n
		b[i][j] = a[0][1]
		end
	end

d = 1
for i in 0...n
	for j in 0...n
		if a[i][j] != b[i][j]
			d = 0
			break
		end
	end
end

if c == 1 && d == 1
	puts "YES"
else
	puts "NO"
end

n = Integer(gets)
a = Array.new
for i in 0...n
    a[i] = Array.new
    input = gets.chomp
    for j in 0...n
        a[i][j] = input[j]
    end
end
c = 1
for i in 0...n
    if a[i][i] != a[i][n-1-i]
        c = 0
        break
    end
end

b = Array.new
    for i in 0...n
        b[i] = Array.new
        a[i][i] = a[i][n - 1 - i] = a [0][1]
        for j in 0...n
        b[i][j] = a[0][1]
        end
    end

d = 1
for i in 0...n
    for j in 0...n
        if a[i][j] != b[i][j]
            d = 0
            break
        end
    end
end

if a[0][0].ord != a[0][1].ord && c == 1 && d == 1
    puts "YES"
else
    puts "NO"
end

n = Integer(gets)
a = Array.new
for i in 0...n
    a[i] = Array.new
    input = gets.chomp
    for j in 0...n
        a[i][j] = input[j]
    end
end
e = 0
if a[0][1] != a[0][0]
    e = 1
end
c = 1
for i in 0...n
    if a[i][i] != a[i][n-1-i]
        c = 0
        break
    end
end

b = Array.new
    for i in 0...n
        b[i] = Array.new
        a[i][i] = a[i][n - 1 - i] = a [0][1]
        for j in 0...n
        b[i][j] = a[0][1]
        end
    end

d = 1
for i in 0...n
    for j in 0...n
        if a[i][j] != b[i][j]
            d = 0
            break
        end
    end
end

if e == 1 && c == 1 && d == 1
    puts "YES"
else
    puts "NO"
end

n = gets.chomp.to_i
mat = Array.new(n)

n.times do |i|
    mat[i] = gets.chomp
end

ok = true
x = mat[0][0]
o = mat[0][1]

n.times do |i|
    n.times do |j|
        if i == j || i + j == n - 1
            if mat[i][j] != x
                ok = false
                break
            end
        else
            if mat[i][j] != o
                ok = false
                break
            end
        end
    end

    break if ok == false
end

puts ok == true ? "YES" : "NO"

n = gets.chomp.to_i
mat = Array.new(n)

n.times do |i|
	mat[i] = gets.chomp
end

ok = true

n.times do |i|
	n.times do |j|
		if i == j || i + j == n - 1
			if mat[i][j] != mat[0][0]
				ok = false
				break
			end
		else
			if mat[i][j] == mat[0][0]
				ok = false
				break
			end
		end
	end

	break if ok == false
end

puts ok == true ? "YES" : "NO"

def diagonal?(i,j,n)
  (i == j) || (j == n - i )
end

matrix = []
n = gets.to_i

n.times do
matrix << gets.split('')

end

diagonal_letter = matrix[0][0]
other_letter = matrix[0][1]
forms_x = true
(0...n).each do |i|
  (0...n).each do |j|
    # puts "#{i} #{j} #{matrix[i][j]}"
  if diagonal?(i,j,n-1)
    if diagonal_letter != matrix[i][j]
     # puts "#{i} #{j} #{forms_x} mat #{matrix[i][j]} diag letter #{diagonal_letter} in diag"
     forms_x = false
     break
    end
  elsif other_letter != matrix[i][j]
    # puts "#{i} #{j} #{forms_x}"
    forms_x = false
    break
  end
  end
  break if forms_x == false
end

# forms_x = diagonal_letter != other_letter if forms_x
puts forms_x ? "YES" : "NO"

n = gets.to_i
l = nil; o = nil; ret = ""

n.times do |i|
    r = gets.chomp
    if i==0
        l = r[i]; o = r[i+1]
        if l==o
            puts "NO"
            exit
        end
    end

    n.times do |j|
        if j==i or j==n-i-1
            if r[j]!=l
                puts "NO"
                exit
            end
        else
            if r[j]!=o
                puts = "NO"
                exit
            end
        end
    end
end

puts "YES"

n = gets.to_i
l = nil; o = nil; ret = ""

n.times do |i|
    r = gets.chomp
    if i==0
        l = r[i]
        o = r[i+1]
    end

    n.times do |j|
        if j==i or j==n-i-1
            ret = "NO" if r[j]!=l
        else
            ret = "NO" if r[j]!=o
        end
    end
    break if ret == "NO"
end

if ret=="NO"
    puts "NO"
else
    puts "YES"
end

n = gets.to_i
a = n.times.map{gets.chomp.chars}
c = Array.new(123, 0)
a.each{|x| x.each{|y| c[y.ord] += 1}}
b = c.each.with_index.sort.reverse.map{|x, y| y.chr}
t = [b[0], b[1]]

def x?(n, a)
  n.times do |i|
    return false if a[i][i] != a[i][n - 1 - i]
  end
  return true
end

puts c[t[0].ord] + c[t[1].ord] == n * n && c[b[0].ord] != n * n && x?(n, a) ? "YES" : "NO"

n = gets.to_i
a = n.times.map{gets.chomp.chars}
c = Array.new(123, 0)
a.each{|x| x.each{|y| c[y.ord] += 1}}
b = c.each.with_index.sort.reverse.map{|x, y| y.chr}

def x?(n, a, b)
  n.times do |i|
    return false if a[i][i] != a[i][n - 1 - i]
    x = a[i].count(b[0])
    y = a[i].count(b[1])
    return false if x == n || y == n || x + y != n
  end
  return true
end

puts x?(n, a, b) ? "YES" : "NO"

n = gets.to_i
a = n.times.map{gets.chomp.chars}
c = Array.new(123, 0)
a.each{|x| x.each{|y| c[y.ord] += 1}}
b = c.each.with_index.sort.reverse.map{|x, y| y.chr}
t = [b[0], b[1]]

def x?(n, a)
  n.times do |i|
    return false if a[i][i] != a[i][n - 1 - i]
  end
  return true
end

puts c[t[0].ord] + c[t[1].ord] == n * n && x?(n, a) ? "YES" : "NO"

n = gets.to_i
a = n.times.map{gets.chomp.chars}
c = Array.new(123, 0)
a.each{|x| x.each{|y| c[y.ord] += 1}}
b = c.each.with_index.sort.reverse

ans = true
n.times do |i|
  ans = false if a[i][i] != a[i][n - 1 - i]
  ans = false if c[a[0][0].ord] != 2 * n - 1 || c[a[0][1].ord] != (n - 2) * n + 1
#  p c[a[0][0].ord], c[a[0][1].ord]
end

puts ans ? "YES" : "NO"

def run(l)
  c1 = l[0][0]

  hv = l.size/2
  c2 = l[hv][0]

  return "NO" if c1 == c2

  #diagonals
  (0...l.size).each do |i|
    return "NO" if l[i][i] != c1
    return "NO" if l[l.size-1-i][l.size-1-i] != c1
  end

  #cross
  (0...l.size).each do |i|
    return "NO" if l[hv][i] != c2 and i != hv
    return "NO" if l[i][hv] != c2 and i != hv
  end

  return "YES"
end

n = gets
while n != nil
  l = []
  n.to_i.times do
    t = gets.split(//)[0...-1]
    l << t
  end
  puts run(l)
  n = gets
end

def check_letter (line_num, board)
	diagonals_letters = []
	other_letters = []
	board.each_with_index do |letter_line, index|
		if (index == (line_num/2))
			diagonals_letters << letter_line[index]
			letter_line.delete_at(index)
			letter_line.each { |c| other_letters << c }
		elsif (index > (line_num/2))
			diagonals_letters << letter_line[index]
			diagonals_letters << letter_line[-(index+1)]
			letter_line.delete_at(index)
			letter_line.delete_at(-index)
			letter_line.each { |c| other_letters << c }
		else
			diagonals_letters << letter_line[index]
			diagonals_letters << letter_line[-(index+1)]
			letter_line.delete_at(index)
			letter_line.delete_at(-(index+1))
			letter_line.each { |c| other_letters << c }
		end
	end

	if ((diagonals_letters.uniq).length == 1) and ((other_letters.uniq).length == 1)
		return "YES"
	else
		return "NO"
	end
end

line_num = ((gets()).split().shift()).to_i

letter_board = []

for i in 0..(line_num-1)
	row = []
	row = (gets()).split(//)
	row.delete("\n")
	letter_board << row
end

result = check_letter(line_num, letter_board)
puts result

def check_letter (line_num, board)
	diagonals_letters = []
	other_letters = []
	board.each_with_index do |letter_line, index|
		if (index == (line_num/2))
			diagonals_letters << letter_line[index]
			letter_line.delete_at(index)
			letter_line.each { |c| other_letters << c }
		elsif (index > (line_num/2))
			diagonals_letters << letter_line[index]
			diagonals_letters << letter_line[-(index+1)]
			letter_line.delete_at(index)
			letter_line.delete_at(-index)
			letter_line.each { |c| other_letters << c }
		else
			diagonals_letters << letter_line[index]
			diagonals_letters << letter_line[-(index+1)]
			letter_line.delete_at(index)
			letter_line.delete_at(-(index+1))
			letter_line.each { |c| other_letters << c }
		end
	end

	p diagonals_letters
	p other_letters

	if ((diagonals_letters.uniq).length == 1) and ((other_letters.uniq).length == 1)
		return "YES"
	else
		return "NO"
	end
end

line_num = ((gets()).split().shift()).to_i

letter_board = []

for i in 0..(line_num-1)
	row = []
	row = (gets()).split(//)
	row.delete("\n")
	letter_board << row
end

p check_letter(line_num, letter_board)


Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.

For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.

NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.

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

gets.strip.to_i.times do
  n, s, k = read_array(:to_i)
  closed = read_array(:to_i)
  c = closed.inject({}) { |h, x| h[x] = 1; h }
  steps = 0
  l, r = [s, s]
  until c[l].nil? or c[r].nil?
    l = [1, l - 1].max
    r = [r + 1, n].min
    steps += 1
  end

  puts steps
end


You have a garland consisting of $$$n$$$ lamps. Each lamp is colored red, green or blue. The color of the $$$i$$$-th lamp is $$$s_i$$$ ('R', 'G' and 'B' — colors of lamps in the garland).You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is nice.A garland is called nice if any two lamps of the same color have distance divisible by three between them. I.e. if the obtained garland is $$$t$$$, then for each $$$i, j$$$ such that $$$t_i = t_j$$$ should be satisfied $$$|i-j|~ mod~ 3 = 0$$$. The value $$$|x|$$$ means absolute value of $$$x$$$, the operation $$$x~ mod~ y$$$ means remainder of $$$x$$$ when divided by $$$y$$$.For example, the following garlands are nice: "RGBRGBRG", "GB", "R", "GRBGRBG", "BRGBRGB". The following garlands are not nice: "RR", "RGBG".Among all ways to recolor the initial garland to make it nice you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of lamps. The second line of the input contains the string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B' — colors of lamps in the garland.

In the first line of the output print one integer $$$r$$$ — the minimum number of recolors needed to obtain a nice garland from the given one. In the second line of the output print one string $$$t$$$ of length $$$n$$$ — a nice garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.

n = gets.to_i
s = gets.chomp.chars
puts %w[R G B].permutation.map { |rgb| (0...n).map { rgb[_1 % 3] } }.map { |t|
		[s.zip(t).count { _1 != _2 }, t.join]
     }.min

class Strand

  def initialize
    @counts = {
      'R' => 0,
      'G' => 0,
      'B' => 0,
    }
  end

  def increase(c)
    @counts[c] += 1
  end

  def moves_to_change_to(c)
    @counts.to_a.select{|k, _| k != c }.map{ |_, v| v }.reduce(0, :+)
  end

end

def solution
  read_int
  gs = read_string

  def color_index(c)
    return 0 if c == "R"
    return 1 if c == "G"
    return 2 if c == "B"
  end

  s = [
    Strand.new,
    Strand.new,
    Strand.new
  ]

  for i in (0...gs.size)
    crt = gs[i]
    j = i % 3
    s[j].increase(crt)
  end

  min_moves = gs.size
  best = nil
  for three_cols in ("RGB".chars.permutation)
    total_moves = (0...3).map{ |i| s[i].moves_to_change_to(three_cols[i])}.reduce(0, :+)
    if min_moves > total_moves
      min_moves = total_moves
      best = three_cols
    end
  end

  final = (0...gs.size).map { |i| best[i % 3] }.join

  puts min_moves
  puts final
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 = gets.to_i
time = Time.now
s = gets.chomp.split('')
cl = ['R', 'G', 'B']
mn = s.size
res = s
cl.permutation.each do |cur|
  t = 0
  str = s.dup
  str.each_with_index do |e, ind|
    if (e != cur[ind % 3])
      t += 1
      str[ind] = cur[ind % 3]
    end
  end
  if (t < mn)
    mn = t
    res = str
  end
end
puts mn
puts res.join('')
# puts Time.now - time

salts = %w(RGB RBG BRG BGR GRB GBR)

n = Integer(gets)
s = gets

def dif(s, t, n)
  d = 0
  n.times do |i|
    d = d + 1 if s[i] != t[i]
  end
  d
end

best = ""
best_dif  = s.size + 1

salts.each do |salt|
  t = (salt * (n / 3 + 2))[0..(n - 1)]
  d = dif(s, t, n)
  if d < best_dif
    best = t
    best_dif = d
  end
end

puts best_dif
puts best

n = gets.to_i
s = gets.chomp.chars
puts (0...3).map { |k| (0...n).map { 'RGB'[(k + _1) % 3] } }.map { |t|
		[s.zip(t).count { _1 != _2 }, t.join]
     }.min

n = gets.to_i
s = gets.chomp.split('')
arr = Array.new(3){{'R'=> 0, 'G'=> 0, 'B'=> 0}}
s.each_with_index do |e, ind|
  arr[ind % 3][e] += 1
end
# puts arr.to_s
res = Array.new(3){0}
3.times do |i|
  res[i] = arr[i].max_by{|e, ee| ee}[1]
end
3.times do |i|
  res[i] = arr[i].select{|e, ee| ee == res[i]}.keys
end
# puts res.to_s
brr = []
arr.each_with_index do |e, ind|
  e.each do |k, v|
    brr << {'K'=> k, 'V' => v, 'I'=> ind}
  end
end
brr = brr.sort_by{|e| e['V']}.reverse
# puts brr.to_s
ans = Array.new(3){'_'}
colors = ['R', 'G', 'B']
brr.each do |e|
  if (ans[e['I']] == '_' && colors.include?(e['K']))
    ans[e['I']] = e['K']
    colors.delete(e['K'])
  end
end

cur = 0
s.each_with_index do |e, ind|
  if (e != ans[ind % 3])
    cur += 1
    s[ind] = ans[ind % 3]
  end
end
puts cur
puts s.join('')

n = gets.to_i
s = gets.chomp.split('')
arr = Array.new(3){{'R'=> 0, 'G'=> 0, 'B'=> 0}}
s.each_with_index do |e, ind|
  arr[ind % 3][e] += 1
end
# puts arr.to_s
brr = []
arr.each_with_index do |e, ind|
  e.each do |k, v|
    brr << {'K'=> k, 'V' => v, 'I'=> ind}
  end
end
brr = brr.sort_by{|e| e['V']}.reverse
# puts brr
ans = Array.new(3){'_'}
colors = ['R', 'G', 'B']
brr.each do |e|
  if (ans[e['I']] == '_' && colors.include?(e['K']))
    ans[e['I']] = e['K']
    colors.delete(e['K'])
  end
end

cur = 0
s.each_with_index do |e, ind|
  if (s[ind] != ans[ind % 3])
    cur += 1
    s[ind] = ans[ind % 3]
  end
end
puts cur
puts s.join('')

salts = %w(RGB RBG BRG BGR GRB GBR)

n = Integer(gets)
s = gets

def dif(s, t, n)
  d = 0
  n.times do |i|
    d = d + 1 if s[i] != t[i]
  end
  d
end

best = ""
best_dif  = s.size + 1

salts.each do |salt|
  t = (salt * (n / 3 + 2))[0..(n - 1)]
  puts t
  d = dif(s, t, n)
  if d < best_dif
    best = t
    best_dif = d
  end
end

puts best_dif
puts best


Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.

The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.  The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world. The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi. It is guaranteed that the graph described by the input is stable.

Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.

NoteFor the first sample test, the graph looks like this:    Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.For the second sample test, the graph looks like this:    We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.

# TEMPLATE BEGIN
def read_vector
    gets.chomp.split(/\s+/)
end
def read_vector_int
    read_vector.map(&:to_i)
end
# TEMPLATE END

class SNM
    def initialize(n)
        @a = (0..n).to_a
    end

    def get(v)
        return v if @a[v] == v
        @a[v] = get(@a[v])
    end

    def join(u, v)
        pu = get(u)
        pv = get(v)
        @a[pu] = @a[pv] if pu != pv
    end
end

n, m, k = read_vector_int

capitals = read_vector_int

snm = SNM.new(n)
edges = m.times.map{ read_vector_int }

edges.each do |a|
    u, v = a
    snm.join(u, v)
end

vertices_in_comp = Array.new(n + 1) { [] }
(1..n).each do |id|
    comp_id = snm.get(id)
    vertices_in_comp[comp_id].push(id)
end

ans = -edges.size
max_comp = 0
capitals.each do |id|
    comp_id = snm.get(id)
    comp_size = vertices_in_comp[comp_id].size
    max_comp = [max_comp, comp_size].max
    ans += (comp_size * (comp_size - 1)) / 2

    vertices_in_comp[comp_id] = []
end

vertices_in_comp.each do |comp|
    next if comp.empty?

    ans += (comp.size * (comp.size - 1)) / 2
    ans += comp.size * max_comp
    max_comp += comp.size
end

puts ans


You are an experienced Codeforces user. Today you found out that during your activity on Codeforces you have made y submissions, out of which x have been successful. Thus, your current success rate on Codeforces is equal to x / y.Your favorite rational number in the [0;1] range is p / q. Now you wonder: what is the smallest number of submissions you have to make if you want your success rate to be p / q?

The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. Each of the next t lines contains four integers x, y, p and q (0 ≤ x ≤ y ≤ 109; 0 ≤ p ≤ q ≤ 109; y > 0; q > 0). It is guaranteed that p / q is an irreducible fraction. Hacks. For hacks, an additional constraint of t ≤ 5 must be met.

For each test case, output a single integer equal to the smallest number of submissions you have to make if you want your success rate to be equal to your favorite rational number, or -1 if this is impossible to achieve.

NoteIn the first example, you have to make 4 successful submissions. Your success rate will be equal to 7 / 14, or 1 / 2.In the second example, you have to make 2 successful and 8 unsuccessful submissions. Your success rate will be equal to 9 / 24, or 3 / 8.In the third example, there is no need to make any new submissions. Your success rate is already equal to 20 / 70, or 2 / 7.In the fourth example, the only unsuccessful submission breaks your hopes of having the success rate equal to 1.

n = gets.to_i
for _ in 0 ... n
  x, y, p, q = gets.split.map(&:to_i)
  y -= x
  q -= p
  if p == 0 || q == 0
    if (x == 0 && p == 0) || (y == 0 && q == 0)
      puts 0
    else
      puts(-1)
    end
    next
  end
  a1 = (x + p - 1) / p
  a2 = (y + q - 1) / q
  a = [a1, a2].max
  r1 = a * p - x
  r2 = a * q - y
  puts r1 + r2
end

gets.to_i.times do
    x, y, p, q=gets.split.map &:to_i

    if (x<y and p==q) or (x>0 and p==0)
        puts -1
    elsif x*q==y*p
        puts 0
    elsif x*q>y*p
        b=64
        n=(1<<b)-1
        a=1<<(b-1)
        while a>0
            v=(n-a)*q-y
            n-=a if v>0 and x*q<=(v+y)*p
            a>>=1
        end
        puts n*q-y
    else
        b=64
        n=(1<<b)-1
        a=1<<(b-1)
        while a>0
            v=(n-a)*q-y
            n-=a if v>0 and (v+x)*q>=(v+y)*p
            a>>=1
        end
        puts n*q-y
    end
end

def min(a,b)
  a < b ? a : b
end

gets.to_i.times do
  x, y, p, q = gets.split(/\s+/).map(&:to_i)

  if p == q
    ans = x == y ? 0 : -1
  elsif p == 0
    ans = x == 0 ? 0 : -1
  else
    d = p*y - q*x
    k = q - p
    if d == 0
      ans = 0
    elsif d > 0 && d % k == 0
      ans = d/k
    else
      k = ((y - x.to_f) / (q - p)).ceil
      if k*p < x
        k = x / p + min(x%p, 1)
      end

      if k * q - y < 0
        ans = -1
      else
        ans = q*k-y
      end
    end
  end

  puts ans
end

n = gets.to_i
for i in 0 ... n
  x, y, p, q = gets.split.map(&:to_i)
  y -= x
  q -= p
  if p == 0 || q == 0
    puts(-1)
    next
  end
  a1 = (x + p - 1) / p
  a2 = (y + q - 1) / q
  a = [a1, a2].max
  r1 = a * p - x
  r2 = a * q - y
  puts r1 + r2
end

gets.to_i.times do
    x, y, p, q=gets.split.map &:to_i

    if x<y and p==q
        puts -1
    elsif x*q==y*p
        puts 0
    elsif x*q>y*p
        n=(1<<60)-1
        a=1<<59
        while a>0
            v=(n-a)*q-y
            n-=a if v>0 and x*q<=(v+y)*p
            a>>=1
        end
        puts n*q-y
    else
        n=(1<<60)-1
        a=1<<59
        while a>0
            v=(n-a)*q-y
            n-=a if v>0 and (v+x)*q>=(v+y)*p
            a>>=1
        end
        puts n*q-y
    end
end

gets.to_i.times do
    x, y, p, q=gets.split.map &:to_i

    if x<y and p==q
        puts -1
    elsif x*q==y*p
        puts 0
    elsif x*q>y*p
        b=64
        n=(1<<b)-1
        a=1<<(b-1)
        while a>0
            v=(n-a)*q-y
            n-=a if v>0 and x*q<=(v+y)*p
            a>>=1
        end
        puts n*q-y
    else
        b=64
        n=(1<<b)-1
        a=1<<(b-1)
        while a>0
            v=(n-a)*q-y
            n-=a if v>0 and (v+x)*q>=(v+y)*p
            a>>=1
        end
        puts n*q-y
    end
end


You and your friend are playing the game Mortal Kombat XI. You are trying to pass a challenge tower. There are $$$n$$$ bosses in this tower, numbered from $$$1$$$ to $$$n$$$. The type of the $$$i$$$-th boss is $$$a_i$$$. If the $$$i$$$-th boss is easy then its type is $$$a_i = 0$$$, otherwise this boss is hard and its type is $$$a_i = 1$$$.During one session, either you or your friend can kill one or two bosses (neither you nor your friend can skip the session, so the minimum number of bosses killed during one session is at least one). After your friend session, your session begins, then again your friend session begins, your session begins, and so on. The first session is your friend's session.Your friend needs to get good because he can't actually kill hard bosses. To kill them, he uses skip points. One skip point can be used to kill one hard boss.Your task is to find the minimum number of skip points your friend needs to use so you and your friend kill all $$$n$$$ bosses in the given order.For example: suppose $$$n = 8$$$, $$$a = [1, 0, 1, 1, 0, 1, 1, 1]$$$. Then the best course of action is the following:  your friend kills two first bosses, using one skip point for the first boss;  you kill the third and the fourth bosses;  your friend kills the fifth boss;  you kill the sixth and the seventh bosses;  your friend kills the last boss, using one skip point, so the tower is completed using two skip points. You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of bosses. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the type of the $$$i$$$-th boss. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer: the minimum number of skip points your friend needs to use so you and your friend kill all $$$n$$$ bosses in the given order.

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map &:to_i
  i, res = 1, a[0]
  while i < n
    if a[i].zero?
      i += 1
      next
    end
    j = i
    j += 1 while j + 1 < n && a[j + 1] == 1
    res += (j - i + 1) / 3
    i = j + 1
  end
  puts res
end


There is a chessboard of size $$$n$$$ by $$$n$$$. The square in the $$$i$$$-th row from top and $$$j$$$-th column from the left is labelled $$$(i,j)$$$.Currently, Gregor has some pawns in the $$$n$$$-th row. There are also enemy pawns in the $$$1$$$-st row. On one turn, Gregor moves one of his pawns. A pawn can move one square up (from $$$(i,j)$$$ to $$$(i-1,j)$$$) if there is no pawn in the destination square. Additionally, a pawn can move one square diagonally up (from $$$(i,j)$$$ to either $$$(i-1,j-1)$$$ or $$$(i-1,j+1)$$$) if and only if there is an enemy pawn in that square. The enemy pawn is also removed.Gregor wants to know what is the maximum number of his pawns that can reach row $$$1$$$?Note that only Gregor takes turns in this game, and the enemy pawns never move. Also, when Gregor's pawn reaches row $$$1$$$, it is stuck and cannot make any further moves.

The first line of the input contains one integer $$$t$$$ ($$$1\le t\le 2\cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of three lines. The first line contains a single integer $$$n$$$ ($$$2\le n\le 2\cdot{10}^{5}$$$) — the size of the chessboard. The second line consists of a string of binary digits of length $$$n$$$, where a $$$1$$$ in the $$$i$$$-th position corresponds to an enemy pawn in the $$$i$$$-th cell from the left, and $$$0$$$ corresponds to an empty cell. The third line consists of a string of binary digits of length $$$n$$$, where a $$$1$$$ in the $$$i$$$-th position corresponds to a Gregor's pawn in the $$$i$$$-th cell from the left, and $$$0$$$ corresponds to an empty cell. It is guaranteed that the sum of $$$n$$$ across all test cases is less than $$$2\cdot{10}^{5}$$$.

For each test case, print one integer: the maximum number of Gregor's pawns which can reach the $$$1$$$-st row.

NoteIn the first example, Gregor can simply advance all $$$3$$$ of his pawns forward. Thus, the answer is $$$3$$$.In the second example, Gregor can guarantee that all $$$4$$$ of his pawns reach the enemy row, by following the colored paths as demonstrated in the diagram below. Remember, only Gregor takes turns in this "game"!  In the third example, Gregor's only pawn is stuck behind the enemy pawn, and cannot reach the end.In the fourth example, Gregor has no pawns, so the answer is clearly $$$0$$$.

for i in 0..gets.to_i-1
	n=gets.to_i
	a=gets[..-2]
	b=gets[..-2]
	k=0
	for i in 0..n-1 do
		if b[i]=='1'
			if a[i]=='0'
				k+=1
			elsif i-1>=0 and a[i-1]=='1'
				k+=1
				a[i-1]='0'
			elsif i+1<n and a[i+1]=='1'
				k+=1
				a[i+1]='0'
			end
		end
	end
	puts k
end

t = gets.to_i
t.times do
	n = gets.to_i
	enemies = gets.chomp.chars.map!(&:to_i) << 0
	allies = gets.chomp.chars.map!(&:to_i)

	cnt = 0
	allies.each_with_index do |ai, i|
		next if ai == 0
		if enemies[i] == 0
			cnt += 1
		elsif enemies[i-1] == 1
			cnt += 1
			enemies[i-1] = 0
		elsif enemies[i+1] == 1
			cnt += 1
			enemies[i+1] = 0
		end
	end

	p cnt
end

MOD = 10 ** 9 + 7
def gs; gets.chomp; end
def gi; gets.to_i; end
def gli; gets.split.map(&:to_i); end
def cyesno(x); puts x ? :Yes : :No; end
def uyesno(x); puts x ? :YES : :NO; end
def array_to_hash_by_count(c); Hash.new(0).tap { |x| c.each { |z| x[z] += 1 } }; end

def solve
  n = gi
  c = 0
  ep = gs.split('').map(&:to_i)
  ap = gs.split('').map(&:to_i)
  for i in (0..n-1)
    if ep[i] == 1 && ap[i - 1] == 1 && i > 0
      c += 1
      ap[i - 1] = 0
    elsif ep[i] == 1 && ap[i + 1] == 1 && i < n - 1
      c +=1
      ap[i + 1] = 0
    elsif ep[i] == 0 && ap[i] == 1
      c += 1
      ap[i] = 0
    end
  end
  puts c
end

def main
  gi.times { solve }
end

main

for i in 0..gets.to_i-1
    n=gets.to_i
    a=gets[..-2]
    b=gets[..-2]
    k=0
    for i in 0..n-1 do
    	if b[i]=='1'
    		if a[i]=='0'
    			k+=1
    		elsif i-1>=0 and a[i-1]=='1'
    			k+=1
    		elsif i+1<n and a[i+1]=='1'
    			k+=1
    		end
    	end
    end
    puts k
end


You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.

The first line of input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 109). The next line contains n integers p1, p2, ..., pn — the given permutation. All pi are different and in range from 1 to n. The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.   In subproblem G1 (3 points), the constraints 1 ≤ n ≤ 6, 1 ≤ k ≤ 4 will hold.  In subproblem G2 (5 points), the constraints 1 ≤ n ≤ 30, 1 ≤ k ≤ 200 will hold.  In subproblem G3 (16 points), the constraints 1 ≤ n ≤ 100, 1 ≤ k ≤ 109 will hold.

Output the answer with absolute or relative error no more than 1e - 9.

NoteConsider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability , the interval will consist of a single element and the permutation will not be altered. With probability  we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability  the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to .

@c1 = 0
@ans = 0
def printa
  cnt = 0
  for i in 0...@n
    for j in i + 1...@n
      if @a[j] < @a[i]
        cnt += 1
      end
    end
  end
  @ans += cnt
  @c1 += 1
end
def gena(x)
  if x == @k
    printa
    return
  end
  for i in 0...@n
    for j in i...@n
      @a[i..j] = @a[i..j].reverse
      gena x + 1
      @a[i..j] = @a[i..j].reverse
    end
  end
end
@n, @k = gets.split.map {|i| i.to_i}
@a = gets.split.map {|i| i.to_i}
gena 0
puts @ans * 1.0 / @c1


Phoenix has collected $$$n$$$ pieces of gold, and he wants to weigh them together so he can feel rich. The $$$i$$$-th piece of gold has weight $$$w_i$$$. All weights are distinct. He will put his $$$n$$$ pieces of gold on a weight scale, one piece at a time. The scale has an unusual defect: if the total weight on it is exactly $$$x$$$, it will explode. Can he put all $$$n$$$ gold pieces onto the scale in some order, without the scale exploding during the process? If so, help him find some possible order. Formally, rearrange the array $$$w$$$ so that for each $$$i$$$ $$$(1 \le i \le n)$$$, $$$\sum\limits_{j = 1}^{i}w_j \ne x$$$.

The input consists of multiple test cases. The first line contains an 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 100$$$; $$$1 \le x \le 10^4$$$) — the number of gold pieces that Phoenix has and the weight to avoid, respectively.  The second line of each test case contains $$$n$$$ space-separated integers $$$(1 \le w_i \le 100)$$$ — the weights of the gold pieces. It is guaranteed that the weights are pairwise distinct.

For each test case, if Phoenix cannot place all $$$n$$$ pieces without the scale exploding, print NO. Otherwise, print YES followed by the rearranged array $$$w$$$. If there are multiple solutions, print any.

NoteIn the first test case, Phoenix puts the gold piece with weight $$$3$$$ on the scale first, then the piece with weight $$$2$$$, and finally the piece with weight $$$1$$$. The total weight on the scale is $$$3$$$, then $$$5$$$, then $$$6$$$. The scale does not explode because the total weight on the scale is never $$$2$$$.In the second test case, the total weight on the scale is $$$8$$$, $$$9$$$, $$$11$$$, $$$14$$$, then $$$18$$$. It is never $$$3$$$.In the third test case, Phoenix must put the gold piece with weight $$$5$$$ on the scale, and the scale will always explode.

Integer(gets.chomp).times{
    n, x = gets.chomp.split.map{|c| Integer(c)}
    a = gets.chomp.split.map{|c| Integer(c)}.sort
    if(x == a.sum)
        puts "NO"
        next
    end

    pref = Array.new
    k = 0
    a.each{ |e|
        k += e
        pref.push(k)
    }
    if(pref.include?(x))
        a.append(a.shift)
    end
    puts "YES"
    a.each {|e| print "#{e} "}
    puts ""
}

def read
    gets.split.map &:to_i
end
gets.to_i.times do
    n, x = read
    w = read
    if w.sum == x
        puts "NO"
    else
        puts "YES"
        n.times do |i|
            w[i], w[i + 1] = w[i + 1], w[i] if w[i] == x
            print w[i], " "
            x -= w[i]
        end
        puts
    end
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n, x = gets.to_s.split.map {|x| x.to_i }
  a = gets.to_s.split.map {|x| x.to_i }.sort
  sum = 0
  bad = false
  bad_i = 0
  0.upto(n - 1) do |i|
    sum += a[i]
    if sum == x
      bad = true
      bad_i = i
    end
  end
  if !bad
    printf("YES\n%s\n", a.join(" "))
  elsif bad_i != n - 1
    a[bad_i], a[n - 1] = a[n - 1], a[bad_i]
    printf("YES\n%s\n", a.join(" "))
  else
    printf("NO\n")
  end
end

Integer(gets.chomp).times{
    n, x = gets.chomp.split.map{|c| Integer(c)}
    a = gets.chomp.split.map{|c| Integer(c)}.sort
    if(x == a.sum)
        puts "NO"
        next
    end

    pref = Array.new
    k = 0
    a.each{ |e|
        k += e
        pref.push(k)
    }
    if(pref.include?(x))
        a.shuffle!
    end
    puts "YES"
    a.each {|e| print "#{e} "}
    puts ""
}

Integer(gets.chomp).times{
    n, x = gets.chomp.split.map{|c| Integer(c)}
    a = gets.chomp.split.map{|c| Integer(c)}.sort
    if(x == a.sum)
        puts "NO"
        next
    end

    pref = Array.new
    k = 0
    a.each{ |e|
        k += e
        pref.push(e)
    }
    if(pref.include?(x))
        a.append(a.shift)
    end
    puts "YES"
    a.each {|e| print "#{e} "}
    puts ""
}

Integer(gets.chomp).times{
    n, x = gets.chomp.split.map{|c| Integer(c)}
    a = gets.chomp.split.map{|c| Integer(c)}.sort
    if(x == a.sum)
        puts "NO"
        next
    end

    pref = Array.new
    k = 0
    a.each{ |e|
        k += e
        pref.push(e)
    }
    if(pref.include?(x))
        a.reverse!
    end
    puts "YES"
    a.each {|e| print "#{e} "}
    puts ""
}


Martian scientists explore Ganymede, one of Jupiter's numerous moons. Recently, they have found ruins of an ancient civilization. The scientists brought to Mars some tablets with writings in a language unknown to science.They found out that the inhabitants of Ganymede used an alphabet consisting of two letters, and each word was exactly $$$\ell$$$ letters long. So, the scientists decided to write each word of this language as an integer from $$$0$$$ to $$$2^{\ell} - 1$$$ inclusively. The first letter of the alphabet corresponds to zero bit in this integer, and the second letter corresponds to one bit.The same word may have various forms in this language. Then, you need to restore the initial form. The process of doing it is described below.Denote the distance between two words as the amount of positions, in which these words differ. For example, the distance between $$$1001_2$$$ and $$$1100_2$$$ (in binary) is equal to two, as these words have different letters in the second and the fourth positions, counting from left to right. Further, denote the distance between words $$$x$$$ and $$$y$$$ as $$$d(x, y)$$$.Let the word have $$$n$$$ forms, the $$$i$$$-th of which is described with an integer $$$x_i$$$. All the $$$x_i$$$ are not necessarily different, as two various forms of the word can be written the same. Consider some word $$$y$$$. Then, closeness of the word $$$y$$$ is equal to the sum of distances to each of the word forms, i. e. the sum $$$d(x_i, y)$$$ over all $$$1 \le i \le n$$$.The initial form is the word $$$y$$$ with minimal possible nearness.You need to help the scientists and write the program which finds the initial form of the word given all its known forms. Note that the initial form is not necessarily equal to any of the $$$n$$$ given forms.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The following are descriptions of the test cases. The first line contains two integers $$$n$$$ and $$$\ell$$$ ($$$1 \le n \le 100$$$, $$$1 \le \ell \le 30$$$) — the amount of word forms, and the number of letters in one word. The second line contains $$$n$$$ integers $$$x_i$$$ ($$$0 \le x_i \le 2^\ell - 1$$$) — word forms. The integers are not necessarily different.

For each test, print a single integer, the initial form of the word, i. e. such $$$y$$$ ($$$0 \le y \le 2^\ell - 1$$$) that the sum $$$d(x_i, y)$$$ over all $$$1 \le i \le n$$$ is minimal possible. Note that $$$y$$$ can differ from all the integers $$$x_i$$$. If there are multiple ways to restore the initial form, print any.

NoteIn the first test case, the words can be written as $$$x_1 = 10010_2$$$, $$$x_2 = 01001_2$$$ and $$$x_3 = 10101_2$$$ in binary. Let $$$y = 10001_2$$$. Then, $$$d(x_1, y) = 2$$$ (the difference is in the fourth and the fifth positions), $$$d(x_2, y) = 2$$$ (the difference is in the first and the second positions), $$$d(x_3, y) = 1$$$ (the difference is in the third position). So, the closeness is $$$2 + 2 + 1 = 5$$$. It can be shown that you cannot achieve smaller closeness.In the second test case, all the forms are equal to $$$18$$$ ($$$10010_2$$$ in binary), so the initial form is also $$$18$$$. It's easy to see that closeness is equal to zero in this case.

t = readline.strip.to_i

def calc_min(l, x)
  result = 0
  l.times do |p|
    os = 0
    is = 0

    x.map! do |xi|
      os += xi % 2 == 0 ? 1 : 0
      is += xi % 2 == 0 ? 0 : 1
      xi /= 2
    end

    result += (os >= is ? 0 : 1) * (2**p)
  end

  result
end

t.times do
  n, l = readline.strip.split(/\s+/).map(&:to_i)
  x = readline.strip.split(/\s+/).map(&:to_i)
  puts calc_min(l,x)
end