There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.

If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.

NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).

# coding: utf-8

# if __FILE__ == $0
# end

n = gets.to_i
seq = gets.split(//)[0...-1].map { |c| c == 'B' ? 0 : 1 }
stand = seq[0]

i = 0
flipIdx = []
maximumTries = seq.length * 3
maximumIdx = seq.length - 1 - 1
while flipIdx.length <= maximumTries
    if seq[i] != stand
        seq[i] ^= 1
        seq[i+1] ^= 1
        flipIdx << i+1 # 1-based index
    end

    if i == maximumIdx
        if seq.count(stand) != seq.length
            stand ^= 1
            i = 0
        else
            break
        end
    else
        i += 1
    end
end

if flipIdx.length > maximumTries || seq.count(stand) != seq.length
    # puts flipIdx.length
    # puts flipIdx.join ' '
    # p seq
    puts -1
else
    puts flipIdx.length

    if flipIdx.length > 0
        puts flipIdx.join ' '
    end
end

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

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

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

def puts_yesno(can) puts(can ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def debug(k,v) puts "#{k}:#{v}" end
########### ( ˘ω˘ )ｽﾔｧ… ###########
n=gi
s=gs

putsend(0) if s.count('W')==n||s.count('B')==n

ans=[]
# Wにする
(n-1).times do |i|
  if s[i]!='W'
    s[i]='W'
    ans<<i+1
    #反転
    if s[i+1]=='W'
      s[i+1]='B'
    else
      s[i+1]='W'
    end
  end
end
if s[n-1]==s[n-2]
  puts ans.size
  putsend(ans.join(" "))
end

# Bにする
(n-1).times do |i|
  if s[i]!='B'
    s[i]='B'
    ans<<i+1
    #反転
    if s[i+1]=='W'
      s[i+1]='B'
    else
      s[i+1]='W'
    end
  end
end
if s[n-1]==s[n-2]
  puts ans.size
  putsend(ans.join(" "))
end
puts -1

# coding: utf-8

# if __FILE__ == $0
# end

n = gets.to_i
seq = gets.split(//)[0...-1].map { |c| c == 'B' ? 0 : 1 }

if seq.count(0) == seq.length || seq.count(1) == seq.length
    puts 0
else
    i = 0
    flipIdx = []
    stand = seq[0] ^ 1 # first flipping always occurs
    maximumTries = seq.length * 3
    while i < seq.length-1 && flipIdx.length <= maximumTries
        if seq[i] != stand
            seq[i] ^= 1
            seq[i+1] ^= 1
            flipIdx << i+1 # 1-based index
        end

        if seq[i] == seq[i+1]
            i += 2
        else
            i += 1
        end
    end

    if flipIdx.length > maximumTries || seq.count(stand) != seq.length
        puts -1
    else
        puts flipIdx.length
        puts flipIdx.join ' '
    end
end


Carol is currently curling.She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100.She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed.

The first line will contain two integers n and r (1 ≤ n, r ≤ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≤ xi ≤ 1 000) — the x-coordinates of the disks.

Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if  for all coordinates.

NoteThe final positions of the disks will look as follows:  In particular, note the position of the last disk.

x = gets.chomp.split(' ')
n = x[0].to_i
r = x[1].to_i
arr = gets.chomp.split(' ')
ans = []
for i in (0...n)
  ans.push(r)
  arr[i] = arr[i].to_i
  for j in (0...i)
    if (arr[i] - arr[j]).abs <= 2 * r
      x = ans[j] + (4 * r * r - (arr[i] - arr[j]) ** 2) ** 0.5
      if(x > ans[i])
        ans[i] = x
      end
    end
  end
  printf("%.12f ", ans[i])
end

def puta ary

  n = ary.size
  # p n
  n.times do |i|
    print ary[i]
    print i == n - 1 ? "\n" : " "
  end
end

n, r = gets.split.map(&:to_i)
x = gets.split.map(&:to_i)

y = Array.new(n, r)

n.times do |i|

  tmp = r
  (0...i).each do |j|

    dx = ( x[i] - x[j] ).abs
    next if dx > 2 * r
    tmp = y[j] +  ( (2*r)**2 - dx**2 ) ** 0.5

    y[i] = tmp if y[i] < tmp
    # p [j, tmp] if i == 25
  end
end

puta y

def puta ary

  n = ary.size
  n.times do |i|
    print ary[i]
    print i == n - 1 ? "\n" : " "
  end
end

n, r = gets.split.map(&:to_i)
x = gets.split.map(&:to_i)

y = Array.new(n, r)

n.times do |i|

  tmp = r
  (0...i).each do |j|

    dx = ( x[i] - x[j] ).abs
    next if dx > 2 * r
    tmp = y[j] +  ( (2*r)**2 - dx**2 ) ** 0.5

  end

  y[i] = [ y[i], tmp ].max

end

puta y


Piegirl got bored with binary, decimal and other integer based counting systems. Recently she discovered some interesting properties about number , in particular that q2 = q + 1, and she thinks it would make a good base for her new unique system. She called it "golden system". In golden system the number is a non-empty string containing 0's and 1's as digits. The decimal value of expression a0a1...an equals to .Soon Piegirl found out that this system doesn't have same properties that integer base systems do and some operations can not be performed on it. She wasn't able to come up with a fast way of comparing two numbers. She is asking for your help.Given two numbers written in golden system notation, determine which of them has larger decimal value.

Input consists of two lines — one for each number. Each line contains non-empty string consisting of '0' and '1' characters. The length of each string does not exceed 100000.

Print ">" if the first number is larger, "<" if it is smaller and "=" if they are equal.

NoteIn the first example first number equals to , while second number is approximately 1.6180339882 + 1.618033988 + 1 ≈ 5.236, which is clearly a bigger number.In the second example numbers are equal. Each of them is  ≈ 2.618.


The process of mammoth's genome decoding in Berland comes to its end!One of the few remaining tasks is to restore unrecognized nucleotides in a found chain s. Each nucleotide is coded with a capital letter of English alphabet: 'A', 'C', 'G' or 'T'. Unrecognized nucleotides are coded by a question mark '?'. Thus, s is a string consisting of letters 'A', 'C', 'G', 'T' and characters '?'.It is known that the number of nucleotides of each of the four types in the decoded genome of mammoth in Berland should be equal.Your task is to decode the genome and replace each unrecognized nucleotide with one of the four types so that the number of nucleotides of each of the four types becomes equal.

The first line contains the integer n (4 ≤ n ≤ 255) — the length of the genome. The second line contains the string s of length n — the coded genome. It consists of characters 'A', 'C', 'G', 'T' and '?'.

If it is possible to decode the genome, print it. If there are multiple answer, print any of them. If it is not possible, print three equals signs in a row: "===" (without quotes).

NoteIn the first example you can replace the first question mark with the letter 'A', the second question mark with the letter 'G', the third question mark with the letter 'T', then each nucleotide in the genome would be presented twice.In the second example the genome is already decoded correctly and each nucleotide is exactly once in it.In the third and the fourth examples it is impossible to decode the genom.

n=gets.to_i
s=gets.chomp
h=Hash.new 0
g=Hash.new n/4
s.each_char{|c|h[c]+=1 if c!='?'}
if n%4>0||h.any?{|k,v|g[k]-=v;v>n/4}
puts '==='
exit
end
s.each_char{|c|
if c!='?'
print c
else
x='ATGC'.chars.find{|x|g[x]>0}
g[x]-=1
print x
end
}
puts

n = gets.to_i
s = gets.chomp.split('')
if n % 4 != 0
  puts '==='
  exit
end
h = {}
['A', 'G', 'C', 'T'].each { |x| h[x] = 0 }
s.each do |x|
  h[x] += 1 if x != '?'
end
if h.values.any? { |m| m > n / 4 }
  puts '==='
  exit
end
ss = s.map do |x|
  if x != '?'
    x
  else
    y = h.keys.find { |z| h[z] < n / 4 }
    h[y] += 1
    y
  end
end
puts ss.join('')

n = gets
s = gets

if n.to_i() % 4 > 0
  puts("===")
else
  a = s.count("A")
  t = s.count("T")
  c = s.count("C")
  g = s.count("G")

  if a.to_i() > n.to_i() / 4 || t.to_i() > n.to_i() / 4 || c.to_i() > n.to_i() / 4 || g.to_i() > n.to_i() / 4
    puts("===")
  else
    while a < n.to_i() / 4
      s[s.index('?')] = 'A'
      a += 1
    end

    while t < n.to_i() / 4
      s[s.index('?')] = 'T'
      t += 1
    end

    while c < n.to_i() / 4
      s[s.index('?')] = 'C'
      c += 1
    end

    while g < n.to_i() / 4
      s[s.index('?')] = 'G'
      g += 1
    end

    puts(s)
  end
end

CODES = ['A', 'G', 'C', 'T']

def count(code)
  result = {'A'=> 0, 'G'=> 0, 'C'=> 0, 'T'=> 0, '?'=> 0}
  code.each_char{|c| result[c]+=1}
  return result
end

def eval(code)
  max = code.length/4
  count(code).all? { |ch, cnt|
    ch == '?' || cnt <= max
  }
end

def find(code)
  return nil if !eval(code)
  i = code.index('?')
  if i.nil?
    return code
  else
    for ch in CODES
      copy = code.dup
      copy[i] = ch
      result = find(copy)
      return result if result
    end
    return nil
  end
end

def solve(n, code)
  return "===" if n < 4 || n%4 != 0
  find(code) || "==="
end

puts solve(STDIN.readline.to_i, STDIN.readline.chomp)

a2 = gets.to_i
str = gets.to_s
count_a = count_g = count_c = count_t = 0
for i in 0..a2-1
  e = str[i]
  a = e.ord
  if (a==65)
    count_a = count_a + 1
  end
  if (a==67)
    count_c = count_c + 1
  end
  if (a==71)
    count_g = count_g + 1
  end
  if (a==84)
    count_t = count_t + 1
  end
end
count_q = a2 - (count_a + count_c + count_g + count_t)
no = a2 / 4

if (a2%4 !=0)||(count_a > no) || (count_c > no) || (count_g > no) || (count_t > no) || ((count_a + count_c + count_g + count_t) > a2)
  print("===")
  flag = 1
elsif count_q == 0
  print str
  flag = 1
end

if (flag != 1)
  count_a = -count_a + no
  count_g = -count_g + no
  count_c = -count_c + no
  count_t = -count_t + no

  stack = Array.new
  for i in 1..count_a
    stack.push("A")
  end
  for i in 1..count_g
    stack.push("G")
  end
  for i in 1..count_c
    stack.push("C")
  end
  for i in 1..count_t
    stack.push("T")
  end
  k =0
  for i in 0..a2-1
    a= str[i].ord
    if (a==63)
      str[i]=stack[k]
      k = k+1
    end
  end
  puts str
end

n=gets.to_i
s=gets.chomp

c=[0]*128
s.bytes{|e|c[e]+=1}

for i in 0..n-1
    if s[i]==??
        "AGCT".bytes{|e|
            if c[e]<n/4
                s[i]=e.chr
                c[e]+=1
                break
            end
        }
    end
end

c=[0]*128
s.bytes{|e|c[e]+=1}
puts ((n%4>0 or c.uniq!=[0,n/4]) ? "===" : s)

class Genome
  attr_reader(:gen)
  def initialize(gen)
    @gen = gen.split("")
    @memo = Hash[
      "A" => 0,
      "C" => 0,
      "G" => 0,
      "T" => 0
    ]
  end

  def length
    @length ||= gen.length
  end

  def gcount
    length / 4
  end

  def _gen_count
    gen.each do |i|
      if(i != "?")
        @memo[i] += 1
      end
    end
    @memo
  end

  def gen_count
    @gen_count ||= _gen_count
  end

  def max_gen_count
    @max_gen_count ||= gen_count.map{|k, v| v}.max
  end

  def possible?
    return false if gen.length % 4 != 0
    @possible ||= max_gen_count <= gcount
  end

  def _solver
    @_solver = []
    gen_count.each do |k, v|
      if(v < gcount)
        (1..(gcount - v)).each{ @_solver << (k) }
      end
    end
    return @_solver
  end

  def solver
    @solver ||= _solver
  end

  def solutions
    return "===" unless possible?
    @solutions = []
    i = 0
    gen.each do |g|
      if(g == "?")
        @solutions << solver[i];
        i += 1
      else
        @solutions << g
      end
    end
    @solutions.join("")
  end

end

gets
puts Genome.new(gets.strip).solutions

def miss
  puts "==="
  exit 0
end

n=gets.to_i
s=gets.chomp
if n % 4 != 0
  miss
end
inv_t={'A'=>0,'G'=>1,'C'=>2,'T'=>3,'?'=>4}
t='AGCT?'.split('')
freq=Array.new(5, 0)
s.split('').each {|c|
  freq[inv_t[c]] += 1
}
(0 .. 3).each {|i|
  if freq[i] > n / 4
    miss
  end
}
(0 ... n).each {|i|
  if s[i] == '?'
    for j in 0 .. 3
      if freq[j] < n / 4
        s[i] = t[j]
        freq[j] += 1
        break
      end
    end
  end
}
puts s

CODES = ['A', 'G', 'C', 'T']

def count(code)
  result = {'A'=> 0, 'G'=> 0, 'C'=> 0, 'T'=> 0, '?'=> 0}
  code.each_char{|c| result[c]+=1}
  return result
end

def eval(code)
  max = code.length/4
  count(code).all? { |ch, cnt|
    ch == '?' || cnt <= max
  }
end

def find(code)
  return nil if !eval(code)
  i = code.index('?')
  if i.nil?
    return code
  else
    for ch in CODES
      copy = code.dup
      copy[i] = ch
      result = find(copy)
      return result if result
    end
    return nil
  end
end

def solve(n, code)
  return "===" if n < 4 || n%4 != 0
  find(code)
end

puts solve(STDIN.readline.to_i, STDIN.readline.chomp)

n=gets.to_i
s=gets.chomp

c=[0]*128
s.bytes{|e|c[e]+=1}

for i in 0..n-1
    if s[i]==??
        "AGCT".bytes{|e|
            if c[e]<n/4
                s[i]=e.chr
                c[e]+=1
                break
            end
        }
    end
end

c=[0]*128
s.bytes{|e|c[e]+=1}
puts (n%4>0 or c.uniq!=[0,n/4] ? "===" : s)

n=gets.to_i
s=gets.chomp

c=[0]*128
s.bytes{|e|c[e]+=1}

for i in 0..n-1
    if s[i]==??
        "AGCT".bytes{|e|
            if c[e]<n/4
                s[i]=e.chr
                c[e]+=1
                break
            end
        }
    end
end

c=[0]*128
s.bytes{|e|c[e]+=1}
puts (c.uniq.size>2 ? "===" : s)

n=gets.to_i
c=[0]*128
s=gets.chomp
s.bytes{|e|c[e]+=1}
m=0
"AGCT".bytes{|e|m=c[e] if m<c[e]}
d=0
"AGCT".bytes{|e|d+=m-c[e]}

if c[??.ord]!=d
    puts "==="
else
    for i in 0..n-1
        if s[i]==??
            "AGCT".bytes{|e|
                if c[e]<m
                    s[i]=e.chr
                    c[e]+=1
                    break
                end
            }
        end
    end
    puts s
end

n=gets.to_i
c=[0]*128
s=gets.chomp
s.bytes{|e|c[e]+=1}
m=0
"AGCT".bytes{|e|m=c[e] if m<c[e]}
d=0
"AGCT".bytes{|e|d+=m-c[e]}

if n%4>0 or (m>0 and c[??.ord]!=d)
    puts "==="
else
    m=n/4 if m==0
    for i in 0..n-1
        if s[i]==??
            "AGCT".bytes{|e|
                if c[e]<m
                    s[i]=e.chr
                    c[e]+=1
                    break
                end
            }
        end
    end
    puts s
end

n=gets.to_i
s=gets.chomp

c=[0]*128
s.bytes{|e|c[e]+=1}

for i in 0..n-1
    if s[i]==??
        "AGCT".bytes{|e|
            if c[e]<n/4
                s[i]=e.chr
                c[e]+=1
                break
            end
        }
    end
end

c=[0]*128
s.bytes{|e|c[e]+=1}
puts (c.uniq!=[0,n/4] ? "===" : s)

class Genome
  attr_reader(:gen)
  def initialize(gen)
    @gen = gen.split("")
    @memo = Hash[
      "A" => 0,
      "C" => 0,
      "G" => 0,
      "T" => 0
    ]
  end

  def length
    @length ||= gen.length
  end

  def gcount
    length / 4
  end

  def _gen_count
    gen.each do |i|
      if(i != "?")
        @memo[i] += 1
      end
    end
    @memo
  end

  def gen_count
    @gen_count ||= _gen_count
  end

  def max_gen_count
    @max_gen_count ||= gen_count.map{|k, v| v}.max
  end

  def possible?
    @possible ||= max_gen_count <= gcount
  end

  def _solver
    @_solver = []
    gen_count.each do |k, v|
      if(v < gcount)
        (1..(gcount - v)).each{ @_solver << (k) }
      end
    end
    return @_solver
  end

  def solver
    @solver ||= _solver
  end

  def solutions
    return "===" unless possible?
    @solutions = []
    i = 0
    gen.each do |g|
      if(g == "?")
        @solutions << solver[i];
        i += 1
      else
        @solutions << g
      end
    end
    @solutions.join("")
  end

end

gets
puts Genome.new(gets.strip).solutions


Some number of people (this number is even) have stood in a circle. The people stand in the circle evenly. They are numbered clockwise starting from a person with the number $$$1$$$. Each person is looking through the circle's center at the opposite person.    A sample of a circle of $$$6$$$ persons. The orange arrows indicate who is looking at whom. You don't know the exact number of people standing in the circle (but this number is even, no doubt). It is known that the person with the number $$$a$$$ is looking at the person with the number $$$b$$$ (and vice versa, of course). What is the number associated with a person being looked at by the person with the number $$$c$$$? If, for the specified $$$a$$$, $$$b$$$, and $$$c$$$, no such circle exists, output -1.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing three distinct integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \le a,b,c \le 10^8$$$).

For each test case output in a separate line a single integer $$$d$$$ — the number of the person being looked at by the person with the number $$$c$$$ in a circle such that the person with the number $$$a$$$ is looking at the person with the number $$$b$$$. If there are multiple solutions, print any of them. Output $$$-1$$$ if there's no circle meeting the given conditions.

NoteIn the first test case, there's a desired circle of $$$8$$$ people. The person with the number $$$6$$$ will look at the person with the number $$$2$$$ and the person with the number $$$8$$$ will look at the person with the number $$$4$$$.In the second test case, there's no circle meeting the conditions. If the person with the number $$$2$$$ is looking at the person with the number $$$3$$$, the circle consists of $$$2$$$ people because these persons are neighbors. But, in this case, they must have the numbers $$$1$$$ and $$$2$$$, but it doesn't meet the problem's conditions.In the third test case, the only circle with the persons with the numbers $$$2$$$ and $$$4$$$ looking at each other consists of $$$4$$$ people. Therefore, the person with the number $$$10$$$ doesn't occur in the circle.

def solve(a, b, c)
  n = (a - b).abs
  return -1 if [a, b, c].max > 2 * n
  a -= 1
  b -= 1
  c -= 1
  (c+n) % (2*n) + 1
end

t = gets.chomp.to_i

t.times do
  a, b, c = gets.chomp.split(' ').map(&:to_i)
  puts "#{solve(a, b, c)}\n"
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

gets.to_i.times do
  a, b, c = gli
  n = 2 * (a - b).abs
  if n < [a, b, c].max
    puts "-1"
  else
    if c > n / 2
      puts c - n / 2
    else
      puts n / 2+c
    end
  end
end


Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed x in the absolute value.Natasha doesn't like when Vanya spends a long time playing, so she hid all of his cards. Vanya became sad and started looking for the cards but he only found n of them. Vanya loves the balance, so he wants the sum of all numbers on found cards equal to zero. On the other hand, he got very tired of looking for cards. Help the boy and say what is the minimum number of cards does he need to find to make the sum equal to zero?You can assume that initially Vanya had infinitely many cards with each integer number from  - x to x.

The first line contains two integers: n (1 ≤ n ≤ 1000) — the number of found cards and x (1 ≤ x ≤ 1000) — the maximum absolute value of the number on a card. The second line contains n space-separated integers — the numbers on found cards. It is guaranteed that the numbers do not exceed x in their absolute value.

Print a single number — the answer to the problem.

NoteIn the first sample, Vanya needs to find a single card with number -2.In the second sample, Vanya needs to find two cards with number 2. He can't find a single card with the required number as the numbers on the lost cards do not exceed 3 in their absolute value.

card = gets.split(" ").map { |e| e.to_i }
mas = gets.split(" ").map { |e| e.to_i }
sum = 0
mas.map { |e| sum += e }
sum = sum.abs
puts (sum.abs + card[1] - 1) / card[1]

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

result = (cards.inject(:+).abs.to_f / m).ceil
puts result

first_line = (gets()).split()
second_line = (gets()).split()

found_num = (first_line.shift).to_i
max_abs = (first_line.shift).to_i
num_ary = 0

second_line.each do |c|
	num_ary += c.to_i
end
result = (num_ary).abs / max_abs
if ((num_ary % max_abs) != 0)
	result += 1
end
p result

a=gets.chomp.split(" ")
ans=0.0
b=gets.chomp.split(" ").each {|i|  ans+=i.to_i  }
ans=ans.abs
ans=(ans/a[1].to_i).ceil
puts "#{ans}"

n, x = gets.split.map &:to_i
a = gets.split.map &:to_i
s = a.inject(0){|s, x| s + x}
p (s.abs + x - 1)/x

def solve(max, cards)
  sum = cards.inject(:+).abs
  div = sum / max
  rem = sum % max
  div += 1 if rem > 0
  div
end

def read_next_line
  gets.chomp.split.map(&:to_i)
end

if __FILE__ == $0
  puts solve(read_next_line[1], read_next_line)
end

n, x = gets.split.map(&:to_i)
given = gets.split.map(&:to_i)
sum = 0

given.each do |i|
    sum += i
end
ans = sum.abs / Float(x)
ans = ans.ceil
p Integer(ans)

#f = File.open('test1.txt', 'r')
f = STDIN
n, x = f.gets.chomp.split.map &:to_i
sum = f.gets.chomp.split.map(&:to_i).reduce(&:+).abs
puts (sum / x + (sum % x != 0 ? 1 : 0))

ri=->{gets.split.map(&:to_i)}
n,x=ri[]
p (ri[].inject(:+).abs+x-1)/x

n, x = gets.split.map { |x| x.to_i }
sum = gets.split.map { |x| x.to_i }.reduce(:+).abs
puts (sum + x - 1) / x

n, x = gets.split(' ').map(&:to_i)
s = gets.split(' ').map(&:to_i).inject(:+).abs
puts s/x + ( s%x == 0 ? 0 : 1 )

n,x = gets.chomp.split

g = gets.chomp.split

n = n.to_i
x = x.to_i
s = 0

for i in 0...n
  s += g[i].to_i
end

s = s.abs

s = s/x.to_f

s = s.ceil

puts s.to_i

#!/usr/bin/ruby
n,x=gets.split.map(&:to_i)
s=gets.split.map(&:to_i).reduce(:+).abs
p (s+x-1)/x

n, x = gets.chomp.split(" ").map{ |e| e.to_i }
cards = gets.chomp.split(" ").map{ |e| e.to_i }

sum = cards.inject{ |s, i| s += i }.abs
puts (sum.to_f / x.to_f).ceil

def run
  n, x = $stdin.gets.split.map(&:to_i)
  c = $stdin.gets.split.map(&:to_i)
  s = c.reduce(&:+)
  puts (s.abs.to_f / x).ceil
end

run if $0 == __FILE__

n, x = gets.split.map &:to_i
sum = gets.split.map { |x| x.to_i }.inject(:+)
puts (sum.abs/x.to_f).ceil

class A
  def initialize
    n, x = gets.chomp.split(' ').map(&:to_i)

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

    sum = num_list.inject(:+)

    puts (sum.abs/x.to_f).ceil
  end
end

A.new

(n , x) = gets.split.map(&:to_i)
arr = gets.split.map(&:to_i)
(sum , res) = 0,0
n.times do |i|
  sum += arr[i]
end

sum = sum.abs
if sum != 0
  res += (sum/x) + (sum%x==0?0:1)
end
puts res

n, x = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
sum = a.reduce(:+).abs
p (sum + x - 1) / x

class ProblemA
  def initialize
    @dats = STDIN.read.split("\n")
    @cards_num, @max_abs = @dats[0].split(" ").map{|x| x.to_i}
    @cards = @dats[1].split(" ").map{|x| x.to_i}
  end

  def solve
    sum = @cards.inject(:+).abs
    return 1 if sum != 0 && sum <= @max_abs-1
    return 0 if @max_abs == 0

    count_ret = 0
    (@max_abs).downto(1) do |elem|
      if sum >= elem
        d = sum / elem
        sum -= elem * d
        count_ret += d
      elsif sum == 0
        return count_ret
      end
    end
    return count_ret
  end
end

solver = ProblemA.new
p solver.solve

n, x = gets.split.map(&:to_i)
as = gets.split.map(&:to_f)

puts (as.inject(:+)/x).abs.ceil

a = readline.split().map {|x| x.to_i}
s = 0
readline.split().map {|i| s += i.to_i}
puts (s.abs + a[1] - 1) / a[1]

n, x = readline.split().map {|i| i.to_i}
s = 0
readline.split().map {|i| s += i.to_i}
puts (s.abs + x - 1) / x

n,x = gets.chomp!.split.map { |e|  e.to_i}

sum = gets.split.collect{|x| x.to_i}.inject{|y, x| y += x}

sum = sum.abs

k = (sum + x -1)/x

p k

n,x = gets.chomp!.split.map { |e|  e.to_i}
sum = gets.split.collect{|x| x.to_i}.inject{|y, x| y += x}
p (sum.abs + x -1)/x

input = gets.chomp
num = input.split
n = Integer(num[0])
x = Integer(num[1])
input2 = gets.chomp
nums= input2.split
card = Array.new
for i in 0...n
    card[i] = Integer(nums[i])
end

sum = 0
for i in 0...n
    sum += card[i]
end
if sum == 0
    puts 0
else
    if sum.abs <= x
        puts 1
    else
        if sum.abs % x == 0
            puts sum.abs / x
        else
            puts sum.abs / x + 1
        end
    end
end

input = gets.chomp
num = input.split
n = Integer(num[0])
x = Integer(num[1])
input2 = gets.chomp
nums= input2.split
card = Array.new
for i in 0...n
    card[i] = Integer(nums[i])
end

sum = 0
for i in 0...n
    sum += card[i]
end
if sum.abs <= x
    puts 1
else
    if sum.abs % x == 0
        puts sum.abs / x
    else
        puts sum.abs / x + 1
    end
end

card = gets.split(" ").map { |e| e.to_i }
mas = gets.split(" ").map { |e| e.to_i }
sum = 0
mas.map { |e| sum += e }
if sum % 2 != 0 then
    sum = sum / 2 + 1
else
    sum = sum / 2
end
puts sum.abs

card = gets.split(" ").map { |e| e.to_i }
mas = gets.split(" ").map { |e| e.to_i }
sum = 0
mas.map { |e| sum += e }
if sum % card[1] != 0 then
    sum = sum / card[1] + 1
else
    sum = sum / card[1]
end
puts sum.abs

def check_pair (pos_ary,neg_ary,surplus_cards)
	if (pos_ary.first and neg_ary.first)
		num = pos_ary.first
		overlap = neg_ary.index(num)
		if overlap
			pos_ary.shift
			neg_ary.delete_at(overlap)
			return check_pair(pos_ary,neg_ary,surplus_cards)
		else
			pos_ary.shift
			surplus_cards += 1
			return check_pair(pos_ary,neg_ary,surplus_cards)
		end
	else
		surplus_cards = pos_ary.length + neg_ary.length
		return surplus_cards
	end
end

first_line = (gets()).split()
second_line = (gets()).split()
pos_cards = []
neg_cards = []

found_num = (first_line.shift).to_i
mux_abs = (first_line.shift).to_i

second_line.each do |c|
	num = c.to_i
	if num > 0
		pos_cards << num
	elsif num < 0
		neg_cards << num
	end
end

p check_pair(pos_cards,neg_cards,0)

n, x = gets.split.map(&:to_i)
given = gets.split.map(&:to_i)
sum = 0

given.each do |i|
    sum += i
end
sum += x - 1
p sum / x

n, x = gets.split.map(&:to_i)
given = gets.split.map(&:to_i)
sum = 0

given.each do |i|
    sum += i
end
p (sum / x).abs.ceil

#f = File.open('test1.txt', 'r')
f = STDIN
n, x = f.gets.chomp.split.map &:to_i
sum = f.gets.chomp.split.map(&:to_i).reduce(&:+).abs
puts (sum / x + sum % x)

#!/usr/bin/ruby
n,x=gets.split.map(&:to_i)
s=gets.split.map(&:to_i).reduce(:+).abs
p (x+s-1)/s

n, x = gets.split.map &:to_i
sum = gets.split.map { |x| x.to_i }.inject(:+)
puts (sum/x).ceil.abs

n, x = gets.split.map &:to_i
sum = gets.split.map { |x| x.to_i }.inject(:+)
puts (sum/x.to_f).ceil.abs

(n , x) = gets.split.map(&:to_i)
arr = gets.split.map(&:to_i)
print arr
sum = 0
res = 0
n.times do |i|
  sum += arr[i]
end

sum = sum.abs
if sum != 0
  res += (sum/x)+1
end
puts res

(n , x) = gets.split.map(&:to_i)
arr = gets.split.map(&:to_i)
(sum , res) = 0,0
n.times do |i|
  sum += arr[i]
end

sum = sum.abs
if sum != 0
  res += (sum/x)+1
end
puts res

(n , x) = gets.split.map(&:to_i)
arr = gets.split.map(&:to_i)
sum = 0
res = 0
n.times do |i|
  sum += arr[i]
end

sum = sum.abs
if sum != 0
  res += (sum%x)+1
end
puts res

class ProblemA
  def initialize
    @dats = STDIN.read.split("\n")
    @cards_num, @max_abs = @dats[0].split(" ").map{|x| x.to_i}
    @cards = @dats[1].split(" ").map{|x| x.to_i}
  end

  def solve
    sum = @cards.inject(:+).abs
    return 1 if sum <= @max_abs-1
    return 0 if @max_abs == 0

    count_ret = 0
    (@max_abs).downto(1) do |elem|
      if sum >= elem
        d = sum / elem
        sum -= elem * d
        count_ret += d
      elsif sum == 0
        return count_ret
      end
    end
    return count_ret
  end
end

solver = ProblemA.new
p solver.solve

class ProblemA
  def initialize
    @dats = STDIN.read.split("\n")
    @cards_num, @max_abs = @dats[0].split(" ").map{|x| x.to_i}
    @cards = @dats[1].split(" ").map{|x| x.to_i}
  end

  def solve
    sum = @cards.inject(:+).abs
    return 1 if sum <= @max_abs
    return 0 if @max_abs == 0

    count_ret = 0
    (@max_abs-1).downto(1) do |elem|
      if sum > elem
        count_ret += 1
        sum -= elem
      elsif sum == 1
        return count_ret+1
      end
    end
    return count_ret
  end
end

solver = ProblemA.new
p solver.solve

class ProblemA
  def initialize
    @dats = STDIN.read.split("\n")
    @cards_num, @max_abs = @dats[0].split(" ").map{|x| x.to_i}
    @cards = @dats[1].split(" ").map{|x| x.to_i}
  end

  def solve
    sum = @cards.inject(:+).abs
    return 1 if sum <= @max_abs
    return 0 if @max_abs == 0

    count_ret = 0
    (@max_abs-1).downto(1) do |elem|
      if sum >= elem
        count_ret += 1
        sum -= elem
      elsif sum == 1
        return count_ret+1
      elsif sum == 0
        return count_ret
      end
    end
    return count_ret
  end
end

solver = ProblemA.new
p solver.solve

class ProblemA
  def initialize
    @dats = STDIN.read.split("\n")
    @cards_num, @max_abs = @dats[0].split(" ").map{|x| x.to_i}
    @cards = @dats[1].split(" ").map{|x| x.to_i}
  end

  def solve
    sum = @cards.inject(:+).abs
    return 1 if sum <= @max_abs
    return 0 if @max_abs == 0

    count_ret = 0
    (@max_abs-1).downto(1) do |elem|
      if sum >= elem
        count_ret += 1
        sum -= elem
      elsif sum == 0
        return count_ret
      end
    end
    return count_ret
  end
end

solver = ProblemA.new
p solver.solve

class ProblemA
  def initialize
    @dats = STDIN.read.split("\n")
    @cards_num, @max_abs = @dats[0].split(" ").map{|x| x.to_i}
    @cards = @dats[1].split(" ").map{|x| x.to_i}
  end

  def solve
    sum = @cards.inject(:+).abs
    return 1 if sum <= @max_abs-1
    return 0 if @max_abs == 0

    count_ret = 0
    (@max_abs-1).downto(1) do |elem|
      if sum >= elem
        d = sum / elem
        sum -= elem * d
        count_ret += d
      elsif sum == 0
        return count_ret
      end
    end
    return count_ret
  end
end

solver = ProblemA.new
p solver.solve

class ProblemA
  def initialize
    @dats = STDIN.read.split("\n")
    @cards_num, @max_abs = @dats[0].split(" ").map{|x| x.to_i}
    @cards = @dats[1].split(" ").map{|x| x.to_i}
  end

  def solve
    sum = @cards.inject(:+).abs
    return 1 if sum <= @max_abs
    return 0 if @max_abs == 0

    count_ret = 0
    @max_abs.downto(1) do |elem|
      if sum > elem
        count_ret += 1
        sum -= elem
      elsif sum == 1
        return count_ret+1
      end
    end
    return count_ret
  end
end

solver = ProblemA.new
p solver.solve

class ProblemA
  def initialize
    @dats = STDIN.read.split("\n")
    @cards_num, @max_abs = @dats[0].split(" ").map{|x| x.to_i}
    @cards = @dats[1].split(" ").map{|x| x.to_i}
  end

  def solve
    sum = @cards.inject(:+).abs
    return 1 if sum <= @max_abs-1
    return 0 if @max_abs == 0

    count_ret = 0
    (@max_abs-1).downto(1) do |elem|
      if sum >= elem
        count_ret += 1
        sum -= elem
      elsif sum == 0
        return count_ret
      end
    end
    return count_ret
  end
end

solver = ProblemA.new
p solver.solve


Bob has a rectangular chocolate bar of the size W × H. He introduced a cartesian coordinate system so that the point (0, 0) corresponds to the lower-left corner of the bar, and the point (W, H) corresponds to the upper-right corner. Bob decided to split the bar into pieces by breaking it. Each break is a segment parallel to one of the coordinate axes, which connects the edges of the bar. More formally, each break goes along the line x = xc or y = yc, where xc and yc are integers. It should divide one part of the bar into two non-empty parts. After Bob breaks some part into two parts, he breaks the resulting parts separately and independently from each other. Also he doesn't move the parts of the bar. Bob made n breaks and wrote them down in his notebook in arbitrary order. At the end he got n + 1 parts. Now he wants to calculate their areas. Bob is lazy, so he asks you to do this task.

The first line contains 3 integers W, H and n (1 ≤ W, H, n ≤ 100) — width of the bar, height of the bar and amount of breaks. Each of the following n lines contains four integers xi, 1, yi, 1, xi, 2, yi, 2 — coordinates of the endpoints of the i-th break (0 ≤ xi, 1 ≤ xi, 2 ≤ W, 0 ≤ yi, 1 ≤ yi, 2 ≤ H, or xi, 1 = xi, 2, or yi, 1 = yi, 2). Breaks are given in arbitrary order. It is guaranteed that the set of breaks is correct, i.e. there is some order of the given breaks that each next break divides exactly one part of the bar into two non-empty parts.

Output n + 1 numbers — areas of the resulting parts in the increasing order.

class Rectnode
	def initialize(isrect, x1,y1,x2,y2)
		@isrect = isrect
		@x1 = x1
		@x2 = x2
		@y1 = y1
		@y2 = y2
		@div1 = nil
		@div2 = nil
	end

	def rdiv(x1,y1,x2,y2)
		if @isrect
			if intersects(x1,y1,x2,y2)
				@div1 = Rectnode.new(true, @x1,@y1,x2,y2)
				@div2 = Rectnode.new(true, x1,y1,@x2,@y2)
				@isrect = false
				return true
			else
				return false
			end
		else
			if @div1.intersects(x1,y1,x2,y2)
				return @div1.rdiv(x1,y1,x2,y2)
			else
				return @div2.rdiv(x1,y1,x2,y2)
			end
		end
	end

	def intersects(x1,y1,x2,y2)
		return false if (@x2 <= x1) || (@x1 >= x2 )
		return false if (@y2 <= y1) || (@y1 >= y2 )

		if @isrect
			if x1 == x2
				return false if (@y1 != y1) || (@y2 != y2)
			else
				return false if (@x1 != x1) || (@x2 != x2)
			end
		end

		return true
	end

	def area
		(@x2-@x1)*(@y2-@y1)
	end

	def allarea( ar )
		if @isrect
			ar.push(area())
		else
			@div1.allarea(ar)
			@div2.allarea(ar)
		end
	end
end

def splitspaceint(s)
	aaa = s.split(/ /)
	bbb = []
	for i in 0..aaa.length-1
		bbb.push(aaa[i].to_i)
	end
	return bbb
end

w,h,n = splitspaceint(gets)
rootnode = Rectnode.new(true, 0,0,w,h)
divs = []
for i in 1..n
	divs.push( splitspaceint(gets) )
end

while divs.length > 0
	for i in 0..divs.length
		xy = divs[i]
		if rootnode.rdiv(xy[0],xy[1],xy[2],xy[3])
			divs.delete_at(i)
			break
		end
	end
end

ar = []
rootnode.allarea(ar)
ar.sort!
first = true
ar.each{|a|
	print " " if not first
	print a
	first = false
}
puts ""

class Rectnode
	def initialize(isrect, x1,y1,x2,y2)
		@isrect = isrect
		@x1 = x1
		@x2 = x2
		@y1 = y1
		@y2 = y2
		@div1 = nil
		@div2 = nil
	end

	def rdiv(x1,y1,x2,y2)
		if @isrect
			@div1 = Rectnode.new(true, @x1,@y1,x2,y2)
			@div2 = Rectnode.new(true, x1,y1,@x2,@y2)
			@isrect = false
		else
			if @div1.intersects(x1,y1,x2,y2)
				@div1.rdiv(x1,y1,x2,y2)
			else
				@div2.rdiv(x1,y1,x2,y2)
			end
		end
	end

	def intersects(x1,y1,x2,y2)
		return false if (@x2 <= x1) || (@x1 >= x2 )
		return false if (@y2 <= y1) || (@y1 >= y2 )
		return true
	end

	def area
		(@x2-@x1)*(@y2-@y1)
	end

	def allarea( ar )
		if @isrect
			ar.push(area())
		else
			@div1.allarea(ar)
			@div2.allarea(ar)
		end
	end
end

def splitspaceint(s)
	aaa = s.split(/ /)
	bbb = []
	for i in 0..aaa.length-1
		bbb.push(aaa[i].to_i)
	end
	return bbb
end

w,h,n = splitspaceint(gets)
rootnode = Rectnode.new(true, 0,0,w,h)
for i in 1..n
	x1,y1,x2,y2 = splitspaceint(gets)
	rootnode.rdiv(x1,y1,x2,y2)
end
ar = []
rootnode.allarea(ar)
ar.sort!
first = true
ar.each{|a|
	print " " if not first
	print a
	first = false
}
puts ""


You have a Petri dish with bacteria and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them.You know that you have $$$n$$$ bacteria in the Petri dish and size of the $$$i$$$-th bacteria is $$$a_i$$$. Also you know intergalactic positive integer constant $$$K$$$.The $$$i$$$-th bacteria can swallow the $$$j$$$-th bacteria if and only if $$$a_i > a_j$$$ and $$$a_i \le a_j + K$$$. The $$$j$$$-th bacteria disappear, but the $$$i$$$-th bacteria doesn't change its size. The bacteria can perform multiple swallows. On each swallow operation any bacteria $$$i$$$ can swallow any bacteria $$$j$$$ if $$$a_i > a_j$$$ and $$$a_i \le a_j + K$$$. The swallow operations go one after another.For example, the sequence of bacteria sizes $$$a=[101, 53, 42, 102, 101, 55, 54]$$$ and $$$K=1$$$. The one of possible sequences of swallows is: $$$[101, 53, 42, 102, \underline{101}, 55, 54]$$$ $$$\to$$$ $$$[101, \underline{53}, 42, 102, 55, 54]$$$ $$$\to$$$ $$$[\underline{101}, 42, 102, 55, 54]$$$ $$$\to$$$ $$$[42, 102, 55, \underline{54}]$$$ $$$\to$$$ $$$[42, 102, 55]$$$. In total there are $$$3$$$ bacteria remained in the Petri dish.Since you don't have a microscope, you can only guess, what the minimal possible number of bacteria can remain in your Petri dish when you finally will find any microscope.

The first line contains two space separated positive integers $$$n$$$ and $$$K$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le K \le 10^6$$$) — number of bacteria and intergalactic constant $$$K$$$. The second line contains $$$n$$$ space separated integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — sizes of bacteria you have.

Print the only integer — minimal possible number of bacteria can remain.

NoteThe first example is clarified in the problem statement.In the second example an optimal possible sequence of swallows is: $$$[20, 15, 10, 15, \underline{20}, 25]$$$ $$$\to$$$ $$$[20, 15, 10, \underline{15}, 25]$$$ $$$\to$$$ $$$[20, 15, \underline{10}, 25]$$$ $$$\to$$$ $$$[20, \underline{15}, 25]$$$ $$$\to$$$ $$$[\underline{20}, 25]$$$ $$$\to$$$ $$$[25]$$$.In the third example no bacteria can swallow any other bacteria.

n, k = gets.strip.split.map(&:to_i)
ary = gets.strip.split.map(&:to_i)
hsh = {}
ary.each {|x| hsh[x] = (hsh[x] || 0) + 1 }
ary.sort!
ary.uniq!
remaining_ary = []
un = ary.size
0.upto(un-2).each do |j|
  i =  j + 1
  next if ary[j] < ary[i] && ary[i] <= (ary[j]+k)
  remaining_ary << ary[j]
end
remaining_ary << ary.last
puts remaining_ary.map{|x| hsh[x] }.inject(:+)

def read_line
  gets.split.map{|e| e.to_i }
end

n, k = read_line
a = read_line.sort

count = 0

nearest_bigger = []
nearest_bigger[a.count - 1] = a[a.count -1]

(0...n-1).reverse_each do |index|
  cur = a[index]
  next_val = a[index+1]
  if cur == next_val
    nearest_bigger[index] = nearest_bigger[index+1]
  else
    nearest_bigger[index] = next_val
  end
end

a[0...-1].to_enum.with_index.each do |val, index|
  next_val = nearest_bigger[index]
  if val < next_val && (val + k) >= next_val
    count += 1
  end
end

puts n-count

# http://codeforces.com/problemset/problem/990/B

def count
  n, k = gets.split.map(&:to_i)
  a = gets.split.map(&:to_i)
  a.sort!
  # puts a.inspect

  return n if a.first == a.last || n == 1

  s = 0
  c = 0
  1.upto(n - 1) do |i|
    next if a[i] - a[i-1] <= k

    c += skip_count(a, i-1, s)
    s = i
  end

  c += skip_count(a, n-1, s)

  return n - c
end

def skip_count(a, startIdx, endIdx)
  c = 0
  startIdx.downto(endIdx) do |i|
    if a[i] == a[startIdx]
      next
    end

    c = (i - endIdx + 1)
    break
  end

  c
end

puts count

_, k = gets.split.map(&:to_i)
b = gets.split.map(&:to_i)

b.sort!

n = 0
prev = b.first
prev_cnt = 0
b.each do |i|
  if i > prev
    if i > prev + k
      n += prev_cnt
    end
    prev = i
    prev_cnt = 1
  else
    prev_cnt +=1
  end
end
n += prev_cnt
puts n

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

c = 1
s = 1
unique = true
1.upto(n - 1) do |i|
  unique = false if (a[i] != a[i - 1]) && unique
  next if a[i] - a[i-1] <= k

  (i - 1).downto(s) do |j|
    if a[j] == a[i - 1]
      c += 1
      next
    end

    c += 1
    break
  end

  s = i
end

if unique
  puts n
else
  puts c
end


A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ of length $$$n$$$ containing each number exactly once. For example, $$$[1]$$$, $$$[4, 3, 5, 1, 2]$$$, $$$[3, 2, 1]$$$ are permutations, and $$$[1, 1]$$$, $$$[0, 1]$$$, $$$[2, 2, 1, 4]$$$ are not.There was a permutation $$$p[1 \dots n]$$$. It was merged with itself. In other words, let's take two instances of $$$p$$$ and insert elements of the second $$$p$$$ into the first maintaining relative order of elements. The result is a sequence of the length $$$2n$$$.For example, if $$$p=[3, 1, 2]$$$ some possible results are: $$$[3, 1, 2, 3, 1, 2]$$$, $$$[3, 3, 1, 1, 2, 2]$$$, $$$[3, 1, 3, 1, 2, 2]$$$. The following sequences are not possible results of a merging: $$$[1, 3, 2, 1, 2, 3$$$], [$$$3, 1, 2, 3, 2, 1]$$$, $$$[3, 3, 1, 2, 2, 1]$$$.For example, if $$$p=[2, 1]$$$ the possible results are: $$$[2, 2, 1, 1]$$$, $$$[2, 1, 2, 1]$$$. The following sequences are not possible results of a merging: $$$[1, 1, 2, 2$$$], [$$$2, 1, 1, 2]$$$, $$$[1, 2, 2, 1]$$$.Your task is to restore the permutation $$$p$$$ by the given resulting sequence $$$a$$$. It is guaranteed that the answer exists and is unique.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 400$$$) — 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 50$$$) — the length of permutation. The second line of the test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the array $$$a$$$ represents the result of merging of some permutation $$$p$$$ with the same permutation $$$p$$$.

For each test case, print the answer: $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$), representing the initial permutation. It is guaranteed that the answer exists and is unique.

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i)
	flag = [false] * (n + 1)
	puts a.reduce([]) { |acc, i|
			if !flag[i]
				acc << i
				flag[i] = true
			end
			acc
	     }.join(' ')
end

# frozen_string_literal: true

lines = gets.to_i
lines.times do
  numbers = gets.to_i
  number_permutation = gets.split(' ').map(&:to_i)
  find_map = {}
  number_permutation.each do |i|
    next if find_map[i]

    find_map[i] = true
  end
  print find_map.keys.join(' '), "\n"
end

n = gets.chomp.to_i
n.times do
    b = gets.chomp.to_i
    atr = gets.chomp.split(" ")
    retsu = []
    until atr == []
        a = atr.shift
       # p retsu
        if !retsu.include?(a)
            retsu << a
        end
    end
    #p retsu
    retsu.delete(" ")
    puts retsu.join(" ")
end

tc = gets.to_i

tc.times do
    n = gets.to_i
    arr = gets.split().map{|i| i.to_i}
    dic = Hash.new(0)
    ans = []
    arr.each do |x|
        if(dic[x] == 0)
            ans << x
        end
        dic[x] += 1
    end
    puts ans.join(" ")
end

gets.to_i.times do
    n = gets.to_i
    a = gets.split.map(&:to_i)
    used = [false] * n
    res = []
    (0...2 * n).each do |i|
        if !used[a[i] - 1]
            used[a[i] - 1] = true
            res << a[i]
        end
    end
    puts res.join ' '
end

def solve
  n = gets.strip.to_i
  a = gets.strip.split(' ').map(&:to_i)
  v = []
  (1..n).each { |e| v[e] = true }
  a.each { |e|
    break if n.zero?
    if v[e] == true
      print "#{e} "
      v[e] = false
    end
  }
  puts
end

gets.strip.to_i.times { solve }

gets.to_i.times do
  gets
  puts gets.split.map(&:to_i).uniq.join(' ')
end

gets.to_i.times do
  gets
  puts gets.split(' ').map(&:to_i).uniq.join(' ')
end

n = gets.chomp.to_i
n.times do
    b = gets.chomp.to_i
    atr = gets.chomp.split("")
    retsu = []
    until atr == []
        a = atr.shift
        if !retsu.include?(a)
            retsu << a
        end
    end
    retsu.delete(" ")
    puts retsu.join(" ")
end


Do you know a story about the three musketeers? Anyway, you will learn about its origins now.Richelimakieu is a cardinal in the city of Bearis. He is tired of dealing with crime by himself. He needs three brave warriors to help him to fight against bad guys.There are n warriors. Richelimakieu wants to choose three of them to become musketeers but it's not that easy. The most important condition is that musketeers must know each other to cooperate efficiently. And they shouldn't be too well known because they could be betrayed by old friends. For each musketeer his recognition is the number of warriors he knows, excluding other two musketeers.Help Richelimakieu! Find if it is possible to choose three musketeers knowing each other, and what is minimum possible sum of their recognitions.

The first line contains two space-separated integers, n and m (3 ≤ n ≤ 4000, 0 ≤ m ≤ 4000) — respectively number of warriors and number of pairs of warriors knowing each other. i-th of the following m lines contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Warriors ai and bi know each other. Each pair of warriors will be listed at most once.

If Richelimakieu can choose three musketeers, print the minimum possible sum of their recognitions. Otherwise, print "-1" (without the quotes).

NoteIn the first sample Richelimakieu should choose a triple 1, 2, 3. The first musketeer doesn't know anyone except other two musketeers so his recognition is 0. The second musketeer has recognition 1 because he knows warrior number 4. The third musketeer also has recognition 1 because he knows warrior 4. Sum of recognitions is 0 + 1 + 1 = 2.The other possible triple is 2, 3, 4 but it has greater sum of recognitions, equal to 1 + 1 + 1 = 3.In the second sample there is no triple of warriors knowing each other.

=begin
      ____________
     /            \
    /  /\      /\  \
   /  /  \    /  \  \
   \                /
    \     \___/    /
     \____________/
=end

class Solve
  def run()
    str = gets.split
    n , m = Integer(str[0]), Integer(str[1])
    graph = Array.new(n) {Array.new(n,false)}
    graph2 = Array.new(n) {Array.new}
    degree = Array.new(n,0)
    for i in 1..m
      str = gets.split
      u , v = Integer(str[0]),Integer(str[1])
      if v < u
        u, v = v , u
      end
      u -= 1
      v -= 1
      graph[u][v] = graph[v][u] = true
      graph2[u].push(v)
      degree[u] += 1
      degree[v] += 1
    end
    mn = 4000 * 4000 * 4000 * 2
    for i in 0..n-1
      for j in 0..graph2[i].length-2
        for k in j+1..graph2[i].length-1
          if graph[graph2[i][j]][graph2[i][k]] == true and degree[i] + degree[graph2[i][j]] + degree[graph2[i][k]] < mn
            mn = degree[i] + degree[graph2[i][j]] + degree[graph2[i][k]]
          end
        end
      end
    end
    if mn == 4000 * 4000 * 4000 * 2
      puts -1
    else
      puts (mn - 6)
    end
  end
end

Solve.new.run

q = Hash.new([])
n, m = gets.split.map(&:to_i)
glory = 0
out = -1

m.times do
  a, b = gets.split.map(&:to_i)
  q[a] += [b]
  q[b] += [a]
end

q.delete_if{ |key, value| value.size < 2 }

q.each do |key, value|

  for i in 0...value.size-1 do
    next unless q.key?(value[i])

    for j in i+1..value.size-1 do
      next unless q.key?(value[j])
      next unless q[value[j]].include?(value[i])

      glory = -6
      glory += q[value[i]].size
      glory += q[value[j]].size
      glory += q[key].size
      out = glory if out > glory || out == -1

    end
  end
end

puts out

require 'set'

n, m = gets.split.map &:to_i
neighbour = (1..n).map{0}
degree = (1..n).map{0}

edges = []
m.times {
	i, j = gets.split.map(&:to_i)
	i -= 1
	j -= 1
	neighbour[i] |= (1 << j)
	neighbour[j] |= (1 << i)
	degree[i] += 1
	degree[j] += 1
	edges << [i, j]
}

min = Float::INFINITY

edges.each{|i, j|
	d0 = degree[i] + degree[j]
	x = neighbour[i] & neighbour[j]
	(0..n-1).each{|k|
		if x[k] == 1
			d = d0 + degree[k]
			min = d if d < min
		end
	}
}

#(0..n-1).sort_by{|i| degree[i]}.each{|i|
#	d1 = degree[i]
#	break if d1 * 3 >= min
#
#	edges.reject!{|j, k|
#		if j == i || k == i
#			true
#		else
#			if neighbour[i].include?(j) && neighbour[i].include?(k)
#				d2, d3 = degree[j], degree[k]
#				d = d1 + d2 + d3
#				min = d if d < min
#			end
#			false
#		end
#	}
#}
#

p min == Float::INFINITY ? -1 : min - 6

n, m = STDIN.gets.split(' ').map{|x| x.to_i}
a = []

m.times do |i|
  a.push(STDIN.gets.split(' ').map{|y| y.to_i - 1});
end

=begin
n, m = 5, 6
a = ['1 2',
'1 3',
'2 3',
'2 4',
'3 4',
'4 5'].map{|x| x.split(' ').map{|y| y.to_i - 1}}
=end
musketeers = Array.new(n){|x| {'known'=>{}, 'knowncount'=> 0}}
a.map do |elem|
  musketeers[elem[0]]['knowncount'] +=1;
  musketeers[elem[0]]['known'][elem[1]]=true;
  musketeers[elem[1]]['knowncount'] +=1;
  musketeers[elem[1]]['known'][elem[0]]=true;
end

# получить тройки знающих
troikas = [];
a.map do |x|
  unite = musketeers[x[0]]['known'].keys & musketeers[x[1]]['known'].keys

  unite.map{|y| troikas.push([y, x[0],x[1] ].sort) }

end

troikas.uniq!

res = troikas.map{|x|  -6 + x.inject(0){|result, y| result+= musketeers[y]['knowncount']}}.min
res = -1 if res == nil
puts res

n, m = gets.chomp.split(' ').map(&:to_i)
as = []
bs = []
m.times do
  a, b = gets.chomp.split(' ').map(&:to_i)
  as << a
  bs << b
end

rs = [[]]
n.times do
  rs << []
end

hs = Hash.new(0)
for i in 0..m-1
  hs[as[i]] += 1
  hs[bs[i]] += 1
  rs[as[i]] << bs[i]
  rs[bs[i]] << as[i]
end

rtn = -1
for m1 in 1..n-2
  r = rs[m1]
  if 1 < r.size
    for j in 0..r.size-2
      m2 = r[j]
      for k in j+1..r.size-1
        m3 = r[k]
        if rs[m2].include?(m3)
          if rtn < 0 || hs[m1] + hs[m2] + hs[m3] - 6 < rtn
            rtn = hs[m1] + hs[m2] + hs[m3] - 6
          end
        end
      end
    end
  end
end

puts rtn

=begin
      ____________
     /            \
    /  /\      /\  \
   /  /  \    /  \  \
   \                /
    \     \___/    /
     \____________/
=end

class Solve
  def run()
    str = gets.split
    n , m = Integer(str[0]), Integer(str[1])
    graph = Array.new(n) {Array.new(n,false)}
    graph2 = Array.new(n) {Array.new}
    degree = Array.new(n,0)
    for i in 1..m
      str = gets.split
      u , v = Integer(str[0]),Integer(str[1])
      if v < u
        u, v = v , u
      end
      u -= 1
      v -= 1
      graph[u][v] = graph[v][u] = true
      graph2[u].push(v)
      degree[u] += 1
      degree[v] += 1
    end
    mn = 4000 * 4000 * 4000 * 2
    for i in 0..n-1
      for j in 0..graph2[i].length-2
        for k in j+1..graph2[i].length-1
          if graph[graph2[i][j]][graph2[i][k]] == true and degree[i] + degree[graph2[i][j]] + degree[graph2[i][k]] < mn
            mn = degree[i] + degree[graph2[i][j]] + degree[graph2[i][k]]
          end
        end
      end
    end
    puts (mn - 6)
  end
end

Solve.new.run

q = Hash.new([])
n, m = gets.split.map(&:to_i)
glory = 0
out = -1

m.times do
  a, b = gets.split.map(&:to_i)
  q[a] += [b]
  q[b] += [a]
end

q.delete_if{ |key, value| value.size < 2 }

q.each do |key, value|
  for i in 0...value.size-1 do
    unless q.key?(value[i])
      glory = 0
      break
    end
    for j in i+1..value.size-1 do
      if q.key?(value[j])

        if q[value[j]].include?(value[i])
          glory += q[value[i]].size
          glory += q[value[j]].size
          glory += q[key].size
          glory -= 6
          out = glory if out > glory || out == -1
        else
          glory = 0
          break
        end
      else
        glory = 0
        break
      end

    end
  end
end

puts out

q = Hash.new([])
n, m = gets.split.map(&:to_i)
glory = 0
out = -1

m.times do
  a, b = gets.split.map(&:to_i)
  q[a] += [b]
  q[b] += [a]
end

q.delete_if{ |key, value| value.size < 2 }

q.each do |key, value|

  for i in 0...value.size-1 do
    break unless q.key?(value[i])

    for j in i+1..value.size-1 do
      break unless q.key?(value[j])
      break unless q[value[j]].include?(value[i])

      glory = -6
      glory += q[value[i]].size
      glory += q[value[j]].size
      glory += q[key].size
      out = glory if out > glory || out == -1

    end
  end
end

puts out


Anfisa the monkey learns to type. She is yet unfamiliar with the "space" key and can only type in lower-case Latin letters. Having typed for a fairly long line, Anfisa understood that it would be great to divide what she has written into k lines not shorter than a and not longer than b, for the text to resemble human speech more. Help Anfisa.

The first line contains three integers k, a and b (1 ≤ k ≤ 200, 1 ≤ a ≤ b ≤ 200). The second line contains a sequence of lowercase Latin letters — the text typed by Anfisa. It is guaranteed that the given line is not empty and its length does not exceed 200 symbols.

Print k lines, each of which contains no less than a and no more than b symbols — Anfisa's text divided into lines. It is not allowed to perform any changes in the text, such as: deleting or adding symbols, changing their order, etc. If the solution is not unique, print any of them. If there is no solution, print "No solution" (without quotes).

k,a,b = gets.chomp.split(/ /).map!{|x| x.to_i}
s = gets.chomp
if k*a > s.length || k*b < s.length
	puts "No solution"
else
	av = s.length/k
	dd = b - av
	remain = s.length - av*k
	idx = 0
	while idx < s.length
		svidx = idx
		idx += av
		if remain > 0
			wk = [dd, remain].min
			remain -= wk
			idx += wk
		end
		puts s[svidx..idx-1]
	end
end

k,a,b = gets.chomp.split(/ /).map!{|x| x.to_i}
s = gets.chomp
av = s.length/k
if av < a || av*b < s.length
	puts "No solution"
else
	dd = b - av
	remain = s.length - av*k
	idx = 0
	while idx < s.length-1
		svidx = idx
		idx += av
		if remain > 0
			wk = [dd, remain].min
			remain -= wk
			idx += wk
		end
		puts s[svidx..idx-1]
	end
end


You are given an integer $$$n$$$ and an array $$$a_1, a_2, \ldots, a_n$$$. You should reorder the elements of the array $$$a$$$ in such way that the sum of $$$\textbf{MEX}$$$ on prefixes ($$$i$$$-th prefix is $$$a_1, a_2, \ldots, a_i$$$) is maximized.Formally, you should find an array $$$b_1, b_2, \ldots, b_n$$$, such that the sets of elements of arrays $$$a$$$ and $$$b$$$ are equal (it is equivalent to array $$$b$$$ can be found as an array $$$a$$$ with some reordering of its elements) and $$$\sum\limits_{i=1}^{n} \textbf{MEX}(b_1, b_2, \ldots, b_i)$$$ is maximized.$$$\textbf{MEX}$$$ of a set of nonnegative integers is the minimal nonnegative integer such that it is not in the set.For example, $$$\textbf{MEX}(\{1, 2, 3\}) = 0$$$, $$$\textbf{MEX}(\{0, 1, 2, 4, 5\}) = 3$$$.

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

For each test case print an array $$$b_1, b_2, \ldots, b_n$$$  — the optimal reordering of $$$a_1, a_2, \ldots, a_n$$$, so the sum of $$$\textbf{MEX}$$$ on its prefixes is maximized. If there exist multiple optimal answers you can find any.

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map &:to_i
  a.sort!
  res = []
  (0...n).each do |i|
    res << a[i] if i == 0 || a[i] != a[i - 1]
  end
  (0...n).each do |i|
    res << a[i] if i > 0 && a[i] == a[i - 1]
  end
  puts res.join ' '
end

t = gets.chomp.to_i
for test in (1..t)
  n = gets.chomp.to_i
  a = gets.chomp.split(' ').map { |x| x.to_i }
  c = Array.new(101).fill(0)
  for i in a
    c[i] += 1
  end
  j = 0
  for i in (0..100)
    if c[i] > 0
      c[i] -= 1
      a[j] = i
      j += 1
    end
  end
  for i in (0..100)
    while c[i] > 0
      c[i] -= 1
      a[j] = i
      j += 1
    end
  end
  a.each do |x|
    print x, ' '
  end
  puts
end

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map &:to_i
  i = 0
  (0..100).each do |x|
    if j = a.index(x)
      a[i], a[j] = a[j], a[i]
    else
      break
    end
    i += 1
  end
  puts a.join ' '
end

gets.to_i.times {
  gets
  arr = gets.split(' ').map(&:to_i).sort
  res = []
  res_tail = []
  arr.each { |el|
    if el == res[-1]
      res_tail.push(el)
    else
      res.push(el)
    end
  }
  puts [*res, *res_tail].join(' ')
}

def solve(n, a)
    mex = 0
    b = []
    n.times {
        if (i = a.index(mex))
            b << a.delete_at(i)
            mex += 1
        else
            break
        end
    }
    b += a
    b
end

def main
    t = int
    t.times do
        n = int
        a = ints
        puts solve(n, a) * " "
    end
end

DEBUG = true
MOD = 10**9+7
YESNO = %w(No Yes)
INF = 10**9

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 rep(n, &b); Array.new(n, &b) end
def yes; puts YESNO[1] end
def no; puts YESNO[0] end
def yesno t; puts YESNO[t] end
def 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 * mod_inv(y, mod) % 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
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
  n = gets.to_i
  a = gets.split.map &:to_i
  res = []
  (0...n).each do |i|
    res << a[i] if i == 0 || a[i] != a[i - 1]
  end
  (0...n).each do |i|
    res << a[i] if i > 0 && a[i] == a[i - 1]
  end
  puts res.join ' '
end


You are given a square grid with $$$n$$$ rows and $$$n$$$ columns. Each cell contains either $$$0$$$ or $$$1$$$. In an operation, you can select a cell of the grid and flip it (from $$$0 \to 1$$$ or $$$1 \to 0$$$). Find the minimum number of operations you need to obtain a square that remains the same when rotated $$$0^{\circ}$$$, $$$90^{\circ}$$$, $$$180^{\circ}$$$ and $$$270^{\circ}$$$.The picture below shows an example of all rotations of a grid.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the size of the grid. Then $$$n$$$ lines follow, each with $$$n$$$ characters $$$a_{i,j}$$$ ($$$0 \leq a_{i,j} \leq 1$$$) — the number written in each cell.

For each test case output a single integer  — the minimum number of operations needed to make the square look the same rotated $$$0^{\circ}$$$, $$$90^{\circ}$$$, $$$180^{\circ}$$$ and $$$270^{\circ}$$$.

NoteIn the first test case, we can perform one operations to make the grid $$$\begin{matrix}0 & 1 & 0\\ 1 & 1 & \color{red}{1}\\ 0 & 1 & 0\end{matrix}$$$. Now, all rotations of the square are the same.In the second test case, all rotations of the square are already the same, so we don't need any flips.

def solve(grid, i, j, n, m)
  return 0 if n == 1
  ans = 0
  (n-1).times do
    ones = 0
    zeros = 0
    4.times do
      if grid[i][j] == '1'
        ones += 1
      else
        zeros += 1
      end
      i, j = j, m-1-i
    end
    ans += [ones, zeros].min
    j += 1
  end
  ans
end

t = gets.to_i

t.times do
  n = gets.to_i
  a = Array.new(n) { gets.chomp }
  ans = 0
  ((n+1)/2).times do |i|
    ans += solve(a, i, i, n-2*i, n)
  end
  puts ans
end


Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.

The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.

If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.

abc
ab
6
a b 4
a b 7
b a 8
c b 11
c a 3
a c 0

def min(a,b)
    if a>b then
        return b
    else
        return a
    end
end
a=gets
b=gets
if a.length!=b.length then
    puts -1
    exit
end

a=a.bytes.to_a
b=b.bytes.to_a

INF=999999999
d=Array.new(128){Array.new(128,INF)}
r1=Array.new(128){Array.new(128,INF)}
r2=Array.new(128){Array.new(128,INF)}

0.upto(127){|i|
    d[i][i]=0
}
n=gets.to_i
0.upto(n-1){|i|
    input=gets.split
    for j in 0..1
        input[j]=input[j].bytes.to_a
    end

    if d[input[0][0]][input[1][0]]>input[2].to_i then
        d[input[0][0]][input[1][0]]=input[2].to_i
    end
}
97.upto(122){|k|
    97.upto(122){|i|
        97.upto(122){|j|
            if d[i][j]>d[i][k]+d[k][j] then
                d[i][j]=d[i][k]+d[k][j]
            end
        }
    }
}
for j in 97..122
    for i in 97..122
        tres=INF
        for k in 97..122
            tres=min(tres,d[i][k]+d[j][k])
        end
        r1[i][j]=tres
        for k in 97..122
            if tres==d[i][k]+d[j][k] then
                r2[i][j]=k.chr
                break
            end
        end

    end
end
res=0
str=""
q=a.length-2
0.upto(q){|i|
    res=res+r1[a[i]][b[i]]
}
if res>INF then
    puts -1
    exit
end
puts res
0.upto(q){|i|
    print r2[a[i]][b[i]]
}
puts

def min(a,b)
    if a>b then
        return b
    else
        return a
    end
end
a=gets
b=gets
if a.length!=b.length then
    puts -1
    exit
end

a=a.bytes.to_a
b=b.bytes.to_a

INF=999999999
d=Array.new(128){Array.new(128,INF)}
r1=Array.new(128){Array.new(128,INF)}
r2=Array.new(128){Array.new(128,INF)}

0.upto(127){|i|
    d[i][i]=0
}
n=gets.to_i
0.upto(n-1){|i|
    input=gets.split
    for j in 0..1
        input[j]=input[j].bytes.to_a
    end

    if d[input[0][0]][input[1][0]]>input[2].to_i then
        d[input[0][0]][input[1][0]]=input[2].to_i
    end
}
97.upto(122){|k|
    97.upto(122){|i|
        97.upto(122){|j|
            if d[i][j]>d[i][k]+d[k][j] then
                d[i][j]=d[i][k]+d[k][j]
            end
        }
    }
}
for j in 97..122
    for i in 97..122
        tres=INF
        for k in 97..122
            tres=min(tres,d[i][k]+d[j][k])
        end
        r1[i][j]=tres
        for k in 97..122
            if tres==d[i][k]+d[j][k] then
                r2[i][j]=k.chr
                break
            end
        end

    end
end
res=0
str=""
q=a.length-2
0.upto(q){|i|
    res+=r1[a[i]][b[i]]
    str+=r2[a[i]][b[i]]
}
puts res
puts str


Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.Each digit is allowed to occur in the number the same number of times it occurs in the set.

A single line contains a single integer n (1 ≤ n ≤ 100000) — the number of digits in the set. The second line contains n digits, the digits are separated by a single space.

On a single line print the answer to the problem. If such number does not exist, then you should print -1.

NoteIn the first sample there is only one number you can make — 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number.

n = gets.to_i
arr = gets.split(" ").map(&:to_i).sort.reverse
ans = nil
if arr.include?(0)
	sum = arr.inject(0,:+)
	if sum % 3 == 0
		ans = arr.join("")
	elsif sum % 3 == 1

		one = [1,4,7]
		two = [2,5,8]
		l = nil
		one.each do |o|
			l = arr.rindex(o)
			if l
				arr.delete_at(l)
				break
			end
		end

		unless l
			deleted = 0
			two.each do |t|
				l = arr.rindex(t)
				if l
					if deleted == 0
						l1 = arr.index(t)
						if l == l1
							arr.delete_at(l)
							deleted = 1
							next
						else
							arr.delete_at(l)
							arr.delete_at(l1)
							break
						end
					end

					if deleted == 1
						arr.delete_at(l)
					end

				end
			end
		end

		# j = arr.length - 1
		# while j >= 0
		# 	a = arr[j]

		# 	if a % 3 == 1 && one.length < 1
		# 		one << j
		# 		break
		# 	end

		# 	if a % 3 == 2  && two.length < 2
		# 		two << j
		# 	end
		# 	j -= 1
		# end
		# if one.empty?
		# 	arr.delete_at(two[0])
		# 	arr.delete_at(two[1])
		# else
		# 	arr.delete_at(one[0])
		# end

		# puts "here"
		# l = arr.rindex{|a| a % 3 == 1}
		# if l
		# 	arr.delete_at(l)
		# else
		# 	l = arr.rindex{|a| a % 3 == 2}
		# 	arr.delete_at(l)
		# 	l = arr.rindex{|a| a % 3 == 2}
		# 	arr.delete_at(l)
		# end
	else

		one = [1,4,7]
		two = [2,5,8]
		l = nil
		two.each do |o|
			l = arr.rindex(o)
			if l
				arr.delete_at(l)
				break
			end
		end

		unless l
			deleted = 0
			one.each do |t|
				l = arr.rindex(t)
				if l
					if deleted == 0
						l1 = arr.index(t)
						if l == l1
							arr.delete_at(l)
							deleted = 1
							next
						else
							arr.delete_at(l)
							arr.delete_at(l1)
							break
						end
					end

					if deleted == 1
						arr.delete_at(l)
					end

				end
			end
		end

		# one = [1,4,7]
		# two = [2,5,8]
		# j = arr.length - 1
		# while j >= 0
		# 	a = arr[j]

		# 	if a % 3 == 2 && two.length < 1
		# 		two << j
		# 		break
		# 	end

		# 	if a % 3 == 1  && one.length < 2
		# 		one << j
		# 	end
		# 	j -= 1
		# end
		# if two.empty?
		# 	arr.delete_at(one[0])
		# 	arr.delete_at(one[1])
		# else
		# 	arr.delete_at(two[0])
		# end

		# l = arr.rindex{|a| a % 3 == 2}
		# if l
		# 	arr.delete_at(l)
		# else
		# 	l = arr.rindex{|a| a % 3 == 1}
		# 	arr.delete_at(l)
		# 	l = arr.rindex{|a| a % 3 == 1}
		# 	arr.delete_at(l)
		# end
	end
	ans = arr.join("")
	unless /[^0]/ =~ ans
		puts "0"
	else
		puts ans
	end
else
	puts "-1"
end

n = gets.to_i
digits = gets.split.map(&:to_i).sort_by {|el| -el}

unless digits.last==0
  puts -1
  exit
end

sum = digits.inject{|sum,el| sum+=el}
ans = 0
size = digits.size

if sum%3 == 0
  ans =  digits.join unless digits[0] == 0
elsif sum%3 == 1
  (size-1).downto(0) do |i|
    if digits[i]%3==1
      digits.delete_at i
      break
    end
  end
  if digits.size == size
    (size-1).downto(0) do |i|
      if digits[i]%3==2 && ( size - digits.size < 2 )
        digits.delete_at i
      end
    end
  end
  ans =  digits.join unless digits[0] == 0
elsif sum%3 == 2
  (size-1).downto(0) do |i|
    if digits[i]%3==2
      digits.delete_at i
      break
    end
  end
  if digits.size == size
    (size-1).downto(0) do |i|
      if digits[i]%3==1 && ( size - digits.size < 2 )
        digits.delete_at i
      end
    end
  end
  ans =  digits.join unless digits[0] == 0
end

puts (ans[0] == '0' ? 0 : ans)

n = gets.to_i
arr = gets.split(" ").map(&:to_i).sort.reverse
ans = nil
if arr.include?(0)
	sum = arr.inject(0,:+)
	if sum % 3 == 0
		ans = arr.join("")
	elsif sum % 3 == 1

		one = [1,4,7]
		two = [2,5,8]
		l = nil
		one.each do |o|
			l = arr.rindex(o)
			if l
				arr.delete_at(l)
				break
			end
		end

		unless l
			deleted = 0
			two.each do |t|
				l = arr.rindex(t)
				if l
					if deleted == 0
						l1 = arr.index(t)
						if l == l1
							arr.delete_at(l)
							deleted = 1
							next
						else
							arr.delete_at(l)
							arr.delete_at(l1)
							break
						end
					end

					if deleted == 1
						arr.delete_at(l)
					end

				end
			end
		end

		# j = arr.length - 1
		# while j >= 0
		# 	a = arr[j]

		# 	if a % 3 == 1 && one.length < 1
		# 		one << j
		# 		break
		# 	end

		# 	if a % 3 == 2  && two.length < 2
		# 		two << j
		# 	end
		# 	j -= 1
		# end
		# if one.empty?
		# 	arr.delete_at(two[0])
		# 	arr.delete_at(two[1])
		# else
		# 	arr.delete_at(one[0])
		# end

		# puts "here"
		# l = arr.rindex{|a| a % 3 == 1}
		# if l
		# 	arr.delete_at(l)
		# else
		# 	l = arr.rindex{|a| a % 3 == 2}
		# 	arr.delete_at(l)
		# 	l = arr.rindex{|a| a % 3 == 2}
		# 	arr.delete_at(l)
		# end
	else

		one = [1,4,7]
		two = [2,5,8]
		l = nil
		two.each do |o|
			l = arr.rindex(o)
			if l
				arr.delete_at(l)
				break
			end
		end

		unless l
			deleted = 0
			one.each do |t|
				l = arr.rindex(t)
				if l
					if deleted == 0
						l1 = arr.index(t)
						if l == l1
							arr.delete_at(l)
							deleted = 1
							next
						else
							arr.delete_at(l)
							arr.delete_at(l1)
							break
						end
					end

					if deleted == 1
						arr.delete_at(l)
					end

				end
			end
		end

		# one = [1,4,7]
		# two = [2,5,8]
		# j = arr.length - 1
		# while j >= 0
		# 	a = arr[j]

		# 	if a % 3 == 2 && two.length < 1
		# 		two << j
		# 		break
		# 	end

		# 	if a % 3 == 1  && one.length < 2
		# 		one << j
		# 	end
		# 	j -= 1
		# end
		# if two.empty?
		# 	arr.delete_at(one[0])
		# 	arr.delete_at(one[1])
		# else
		# 	arr.delete_at(two[0])
		# end

		# l = arr.rindex{|a| a % 3 == 2}
		# if l
		# 	arr.delete_at(l)
		# else
		# 	l = arr.rindex{|a| a % 3 == 1}
		# 	arr.delete_at(l)
		# 	l = arr.rindex{|a| a % 3 == 1}
		# 	arr.delete_at(l)
		# end
	end
	ans = arr.join("")
	# if ans.to_i == 0
	# 	puts "0"
	# else
		puts ans
	# end
else
	puts "-1"
end


Little Petya likes arrays of integers a lot. Recently his mother has presented him one such array consisting of n elements. Petya is now wondering whether he can swap any two distinct integers in the array so that the array got unsorted. Please note that Petya can not swap equal integers even if they are in distinct positions in the array. Also note that Petya must swap some two integers even if the original array meets all requirements.Array a (the array elements are indexed from 1) consisting of n elements is called sorted if it meets at least one of the following two conditions:  a1 ≤ a2 ≤ ... ≤ an;  a1 ≥ a2 ≥ ... ≥ an. Help Petya find the two required positions to swap or else say that they do not exist.

The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n non-negative space-separated integers a1, a2, ..., an — the elements of the array that Petya's mother presented him. All integers in the input do not exceed 109.

If there is a pair of positions that make the array unsorted if swapped, then print the numbers of these positions separated by a space. If there are several pairs of positions, print any of them. If such pair does not exist, print -1. The positions in the array are numbered with integers from 1 to n.

NoteIn the first two samples the required pairs obviously don't exist.In the third sample you can swap the first two elements. After that the array will look like this: 2 1 3 4. This array is unsorted.

n = gets.to_i
a = gets.split(' ').map(&:to_i)
if n < 3
  puts "-1"
  exit
end

incr = a.sort
decr = a.sort{|x,y| y <=> x}

i = 0
finish = false

1.upto(a.size-1) do |i|
  if a[i] != a[i-1]
    a[i],a[i-1] = a[i-1],a[i]

    finish = (a != incr) && (a != decr)
    if finish
      puts "#{i} #{i+1}"
      break
    end
    a[i],a[i-1] = a[i-1],a[i]
  end
end

if !finish
  puts "-1"
end

n = gets.to_i
a = gets.split(' ').map(&:to_i)
if n < 3
  puts "-1"
  exit
end

incr = a.sort
decr = a.sort{|x,y| y <=> x}

i = 0
finish = false

1.upto(a.size-1) do |i|
  if a[i] != a[i-1]
    a[i],a[i-1] = a[i-1],a[i]

    finish = (a != incr) && (a != decr)
    if finish
      puts "#{i} #{i+1}"
      break
    end
    a[i],a[i-1] = a[i-1],a[i]
  end
end

if !finish
  puts "-1 "
end

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

if n == 2
	puts "-1"
	exit 0
end

mn = x.min
k = x.index(mn)
lmx = x[0..k-1].max
rmx = x[k+1..-1].max
if 0 < k && k + 1 < n && lmx > mn && rmx > mn
	if lmx != rmx
		puts "#{x[0..k-1].index(lmx)+1} #{x[k+1..-1].index(rmx)+k+2}"
	else
		1.upto(k-1) do |i|
			if x[i] != mn
				puts "#{i+1} #{k+1}"
				exit 0
			end
		end
		(k+1).upto(n-2) do |i|
			if x[i] != mn
				puts "#{k+1} #{i+1}"
				exit 0
			end
		end
		if n == 3
			puts -1
			exit 0
		end
		puts "1 2"
	end
	exit 0
end

mx = x.max
k = x.index(mx)
lmn = x[0..k-1].min
rmn = x[k+1..-1].min
if 0 < k && k + 1 < n && lmn < mx && rmn < mx
	if lmn != rmn
		puts "#{x[0..k-1].index(lmn)+1} #{x[k+1..-1].index(rmn)+k+2}"
	else
		1.upto(k-1) do |i|
			if x[i] != mx
				puts "#{i+1} #{k+1}"
				exit 0
			end
		end
		(k+1).upto(n-2) do |i|
			if x[i] != mx
				puts "#{k+1} #{i+1}"
				exit 0
			end
		end
		if n == 3
			puts -1
			exit 0
		end
		puts "1 2"
	end
	exit 0
end

if mn == mx
	puts -1
	exit 0
end

x[1..-2].each_with_index do |v, i|
	if v != x[0]
		puts "1 #{i+2}"
		exit 0
	end
	if v != x[-1]
		puts "#{i+2} #{n}"
		exit 0
	end
end

puts -1

t = gets.to_i

a = gets.split.collect{|x| x.to_i}

up = a.sort
dn = a.sort{|x,y| y <=> x}

i = 0
finish = false

1.upto(a.size-1) do |i|
	if a[i-1] != a[i]
		a[i], a[i-1] = a[i-1], a[i]

		finish = a != up && a != dn

		if finish
			print i,' ', i+1
			break
		end

		a[i], a[i-1] = a[i-1], a[i]
	end
end

if not finish or a == Array.new(a.size, a[0])
	print -1
end

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

if n == 2
	puts "-1"
	exit 0
end

mn = x.min
k = x.index(mn)
lmx = x[0..k-1].max
rmx = x[k+1..-1].max
if 0 < k && k + 1 < n && lmx > mn && rmx > mn
	puts "#{x[0..k-1].index(lmx)+1} #{x[k+1..-1].index(rmx)+1}"
	exit 0
end

mx = x.max
k = x.index(mx)
lmn = x[0..k-1].min
rmn = x[k+1..-1].min
if 0 < k && k + 1 < n && lmn < mx && rmn < mx
	puts "#{x[0..k-1].index(lmn)+1} #{x[k+1..-1].index(rmn)+1}"
	exit 0
end

if mn == mx
	puts -1
	exit 0
end

x[1..-2].each_with_index do |v, i|
	if v != x[0]
		puts "1 #{i+2}"
		exit 0
	end
	if v != x[-1]
		puts "#{i+2} #{n}"
		exit 0
	end
end

puts -1

def gao(x, y)
	return [-1] if x.size == 2
	a, b = [], []
	x.each_index { |i| x[i] == y[i] ? a << x[i] : b << x[i] }
	a.uniq!
	ub = b.uniq
	if a.size >= 2
		[x.index(a[0]) + 1, x.index(a[1]) + 1]
	else
		if ub.size >= 2 && b.size >= 3
			[x.index(ub[0]) + 1, x.index(ub[1]) + 1]
		else
			[-1]
		end
	end
end

n = gets.to_i
x = gets.split.map(&:to_i)
r = gao(x, x.sort)
puts r.size == 1 ? gao(x, x.sort.reverse) : r.join(" ")

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

if n == 2
	puts "-1"
	exit 0
end

mn = x.min
k = x.index(mn)
lmx = x[0..k-1].max
rmx = x[k+1..-1].max
if 0 < k && k + 1 < n && lmx > mn && rmx > mn
	if lmx != rmx
		puts "#{x[0..k-1].index(lmx)+1} #{x[k+1..-1].index(rmx)+k+2}"
	else
		1.upto(k-1) do |i|
			if x[i] != mn
				puts "#{i+1} #{k+1}"
				exit 0
			end
		end
		(k+1).upto(n-1) do |i|
			if x[i] != mn
				puts "#{k+1} #{i+1}"
				exit 0
			end
		end
		if n == 3
			puts -1
			exit 0
		end
		puts "1 2"
	end
	exit 0
end

mx = x.max
k = x.index(mx)
lmn = x[0..k-1].min
rmn = x[k+1..-1].min
if 0 < k && k + 1 < n && lmn < mx && rmn < mx
	if lmx != rmx
		puts "#{x[0..k-1].index(lmn)+1} #{x[k+1..-1].index(rmn)+k+2}"
	else
		1.upto(k-1) do |i|
			if x[i] != mx
				puts "#{i+1} #{k+1}"
				exit 0
			end
		end
		(k+1).upto(n-1) do |i|
			if x[i] != mx
				puts "#{k+1} #{i+1}"
				exit 0
			end
		end
		if n == 3
			puts -1
			exit 0
		end
		puts "1 2"
	end
	exit 0
end

if mn == mx
	puts -1
	exit 0
end

x[1..-2].each_with_index do |v, i|
	if v != x[0]
		puts "1 #{i+2}"
		exit 0
	end
	if v != x[-1]
		puts "#{i+2} #{n}"
		exit 0
	end
end

puts -1


Local authorities have heard a lot about combinatorial abilities of Ostap Bender so they decided to ask his help in the question of urbanization. There are n people who plan to move to the cities. The wealth of the i of them is equal to ai. Authorities plan to build two cities, first for n1 people and second for n2 people. Of course, each of n candidates can settle in only one of the cities. Thus, first some subset of candidates of size n1 settle in the first city and then some subset of size n2 is chosen among the remaining candidates and the move to the second city. All other candidates receive an official refuse and go back home.To make the statistic of local region look better in the eyes of their bosses, local authorities decided to pick subsets of candidates in such a way that the sum of arithmetic mean of wealth of people in each of the cities is as large as possible. Arithmetic mean of wealth in one city is the sum of wealth ai among all its residents divided by the number of them (n1 or n2 depending on the city). The division should be done in real numbers without any rounding.Please, help authorities find the optimal way to pick residents for two cities.

The first line of the input contains three integers n, n1 and n2 (1 ≤ n, n1, n2 ≤ 100 000, n1 + n2 ≤ n) — the number of candidates who want to move to the cities, the planned number of residents of the first city and the planned number of residents of the second city. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000), the i-th of them is equal to the wealth of the i-th candidate.

Print one real value — the maximum possible sum of arithmetic means of wealth of cities' residents. You answer will be considered correct if its absolute or relative error does not exceed 10 - 6.  Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

NoteIn the first sample, one of the optimal solutions is to move candidate 1 to the first city and candidate 2 to the second.In the second sample, the optimal solution is to pick candidates 3 and 4 for the first city, and candidate 2 for the second one. Thus we obtain (a3 + a4) / 2 + a2 = (3 + 2) / 2 + 4 = 6.5

# first steps

n, n1, n2 = gets.split(' ')
a = gets.split(' ')

n = n.to_i
i = 0
while i < n
	a[i] = a[i].to_i
	i += 1
end

n1 = n1.to_i
n2 = n2.to_i

a = a.sort {|x, y| x.to_i <=> y.to_i}
a = a.reverse

if n1 > n2
	temp = n2
	n2 = n1
	n1 = temp
end

cnt1, cnt2 = [0, 0]

i = 0
n1.times do
	cnt1 += a[i].to_i
	i += 1
end
i = n1
n2.times do
	cnt2 += a[i].to_i
	i += 1
end
#puts a.join(', ')
#puts cnt1.to_s + ' ' + cnt2.to_s
puts cnt1.to_f / n1.to_f + cnt2.to_f / n2.to_f

n, n1, n2 = gets.split.map(&:to_i)
data = gets.split.map(&:to_i)

data.sort! { |x, y| y <=> x }
n1, n2 = [n1,n2].minmax

ans = data[0,n1].reduce(0,:+).to_f / n1.to_f + data[n1,n2].reduce(0,:+).to_f / n2.to_f
p ans


Fillomino is a classic logic puzzle. (You do not need to know Fillomino in order to solve this problem.) In one classroom in Yunqi town, some volunteers are playing a board game variant of it:Consider an $$$n$$$ by $$$n$$$ chessboard. Its rows are numbered from $$$1$$$ to $$$n$$$ from the top to the bottom. Its columns are numbered from $$$1$$$ to $$$n$$$ from the left to the right. A cell on an intersection of $$$x$$$-th row and $$$y$$$-th column is denoted $$$(x, y)$$$. The main diagonal of the chessboard is cells $$$(x, x)$$$ for all $$$1 \le x \le n$$$.A permutation of $$$\{1, 2, 3, \dots, n\}$$$ is written on the main diagonal of the chessboard. There is exactly one number written on each of the cells. The problem is to partition the cells under and on the main diagonal (there are exactly $$$1+2+ \ldots +n$$$ such cells) into $$$n$$$ connected regions satisfying the following constraints:  Every region should be connected. That means that we can move from any cell of a region to any other cell of the same region visiting only cells of the same region and moving from a cell to an adjacent cell.  The $$$x$$$-th region should contain cell on the main diagonal with number $$$x$$$ for all $$$1\le x\le n$$$.  The number of cells that belong to the $$$x$$$-th region should be equal to $$$x$$$ for all $$$1\le x\le n$$$.  Each cell under and on the main diagonal should belong to exactly one region.

The first line contains a single integer $$$n$$$ ($$$1\le n \le 500$$$) denoting the size of the chessboard. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$. $$$p_i$$$ is the number written on cell $$$(i, i)$$$. It is guaranteed that each integer from $$$\{1, \ldots, n\}$$$ appears exactly once in $$$p_1$$$, ..., $$$p_n$$$.

If no solution exists, output $$$-1$$$. Otherwise, output $$$n$$$ lines. The $$$i$$$-th line should contain $$$i$$$ numbers. The $$$j$$$-th number on the $$$i$$$-th line should be $$$x$$$ if cell $$$(i, j)$$$ belongs to the the region with $$$x$$$ cells.

NoteThe solutions to the examples are illustrated in the following pictures:

def pa(a)
  0.upto(a.size - 1) do |i|
    puts a[i][0 .. i].join(" ")
  end
end

def fill(a, i, j, val, count)
  a[i][j] = val
  done = 1
  if done < count && j > 0 && a[i][j - 1] == 0
     done += fill(a, i, j - 1, val, count - 1)
  end
  if done < count && i < a.size - 1 && a[i + 1][j] == 0
     done += fill(a, i + 1, j, val, count - 1)
  end
  return done
end

n = gets.to_s.to_i
a = n.times.map {[0] * n}
d = gets.to_s.split.map {|x| x.to_i }
d.each.with_index {|x, i| fill(a, i, i, x, x) }

freq = {}
a.each {|row| row.each {|val| freq[val] = (freq[val] || 0) + 1 }}

bad = false
freq.each {|k, v| bad = true if k != 0 && k != v }

if bad
  printf("-1\n")
else
  pa(a)
end


Recently, Norge found a string $$$s = s_1 s_2 \ldots s_n$$$ consisting of $$$n$$$ lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string $$$s$$$. Yes, all $$$\frac{n (n + 1)}{2}$$$ of them!A substring of $$$s$$$ is a non-empty string $$$x = s[a \ldots b] = s_{a} s_{a + 1} \ldots s_{b}$$$ ($$$1 \leq a \leq b \leq n$$$). For example, "auto" and "ton" are substrings of "automaton".Shortly after the start of the exercise, Norge realized that his keyboard was broken, namely, he could use only $$$k$$$ Latin letters $$$c_1, c_2, \ldots, c_k$$$ out of $$$26$$$.After that, Norge became interested in how many substrings of the string $$$s$$$ he could still type using his broken keyboard. Help him to find this number.

The first line contains two space-separated integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$, $$$1 \leq k \leq 26$$$) — the length of the string $$$s$$$ and the number of Latin letters still available on the keyboard. The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains $$$k$$$ space-separated distinct lowercase Latin letters $$$c_1, c_2, \ldots, c_k$$$ — the letters still available on the keyboard.

Print a single number — the number of substrings of $$$s$$$ that can be typed using only available letters $$$c_1, c_2, \ldots, c_k$$$.

gets
s = gets.chomp
c = gets.split
p s.chars.chunk { c.include? _1 }.select { _1[0] }.sum {
		_2.size * (_2.size + 1) / 2
  }

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

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

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

def puts_yesno(can) puts(can ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def debug(k,v) puts "#{k}:#{v}" end
########### ( ˘ω˘ )ｽﾔｧ… ###########
n,k=gsmi
s=gs
c=gets.chomp.split

i=0
cnt=0
while i<n do
  if c.include?(s[i])
    cnt+=1
  else
    h[cnt]+=1
    cnt=0
  end
  i+=1
end
h[cnt]+=1

# substringなん文字が何個あるか
h.each do |key,val|
  cnt = key*(key+1)/2*val
  sum+=cnt
end
puts sum