The School №0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti:  ti = 1, if the i-th child is good at programming,  ti = 2, if the i-th child is good at maths,  ti = 3, if the i-th child is good at PE Each child happens to be good at exactly one of these three subjects.The Team Scientific Decathlon Olympias requires teams of three students. The school teachers decided that the teams will be composed of three children that are good at different subjects. That is, each team must have one mathematician, one programmer and one sportsman. Of course, each child can be a member of no more than one team.What is the maximum number of teams that the school will be able to present at the Olympiad? How should the teams be formed for that?

The first line contains integer n (1 ≤ n ≤ 5000) — the number of children in the school. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 3), where ti describes the skill of the i-th child.

In the first line output integer w — the largest possible number of teams.  Then print w lines, containing three numbers in each line. Each triple represents the indexes of the children forming the team. You can print both the teams, and the numbers in the triplets in any order. The children are numbered from 1 to n in the order of their appearance in the input. Each child must participate in no more than one team. If there are several solutions, print any of them. If no teams can be compiled, print the only line with value w equal to 0.

n = gets.to_i
a = gets.split(" ").map(&:to_i)
print [a.count(1), a.count(2), a.count(3)].min
print "\n"
[a.count(1), a.count(2), a.count(3)].min.times {
  p = a.index(1)
  print p+1
  a[p] = 0
  print ' '
  p = a.index(2)
  print p+1
  a[p]= 0
  print ' '
  p = a.index(3)
  print p+1
  a[p] = 0
  print ' '
  print "\n"
}

#! /usr/bin/env ruby
# coding: utf-8

n = gets.to_i
s = gets.split.map(&:to_i)
i = 1
a = []
s.each do |g|
  a << [i, g]
  i += 1
end

one   = a.select { |i| i[1] == 1 }
two   = a.select { |i| i[1] == 2 }
three = a.select { |i| i[1] == 3 }

if one.length == 0 or two.length == 0 or three.length == 0
  puts 0
  exit 0
end

ans = []
until one.length == 0 or two.length == 0 or three.length == 0
  o = one.shift
  tw = two.shift
  th = three.shift

  ans << "#{o[0]} #{tw[0]} #{th[0]}"
end

puts "#{ans.length}"
ans.each do |an|
  puts an
end

n = gets.to_i

ps = []
ms = []
pes = []

gets.split.map(&:to_i).each_with_index do |t, i|
  if t == 1
    ps << i + 1
  elsif t == 2
    ms << i + 1
  else
    pes <<i + 1
  end
end

ans = 0
list = []
while !ps.empty? && !ms.empty? && !pes.empty? do
  ans += 1
  list << [ps.shift, ms.shift, pes.shift].join(" ")
end
puts ans
puts list

gets
l=gets.split.map(&:to_i)
m=(1..3).map{|i|(0..l.size).select{|j|i==l[j]}}
p n=m.map(&:size).min
n.times{|i|puts m.map{|a|a[i]+1}*" "}

gets.chomp.to_i
students = gets.chomp.split(/ /).map(&:to_i)
has_teams = true
teams = []
while has_teams
    temp = []
    (1..3).each do |skill|
        index = students.index( skill )
        if index.nil?
            has_teams = false
            break
        end
        temp << index + 1
        students[index] = -1
    end
    teams << temp if temp.length == 3
end
puts teams.length
teams.each do |team|
    puts team.join(" ")
end

n = gets.to_i
a = gets.split.map(&:to_i)
pr = []
m = []
s = []
for i in 0...a.size
	if a[i] == 1
		pr << i + 1
	elsif a[i] == 2
		m << i + 1
	else
		s << i + 1
	end
end
w = [pr.size, m.size,s.size].min
puts w
0.upto(w - 1) do |i|
	print pr[i],' ',m[i],' ',s[i],"\n"
end

n = gets.to_i
students = gets.split(" ").map(&:to_i)
gift = {1 => [], 2 => [] , 3 => []}
students.each_with_index do |s,i|
gift[s] << i + 1
end
# puts "#{gift}"
arr = []
gift.each { |k,v|
 arr << v.count
}
min_teams = arr.min
puts min_teams
(0..min_teams - 1).each { |i|
  puts "#{gift[1][i]} #{gift[2][i]} #{gift[3][i]}"
}

n = gets.to_i
a = [nil] + gets.split.map(&:to_i)
b = [nil] + Array.new(3, 0)
for i in 1..n
  b[a[i]] += 1
end
w = b[1..3].min
puts w
if w != 0
  x = 0
  y = 0
  z = 0
  ans = Array.new(w){Array.new(3)}
  for i in 1..n
    if a[i] == 1 && x < w
      ans[x][0] = i
      x += 1
      a[i] = 0
    elsif a[i] == 2 && y < w
      ans[y][1] = i
      y += 1
      a[i] = 0
    elsif a[i] == 3 && z < w
      ans[z][2] = i
      z += 1
      a[i] = 0
    end
  end
  w.times do |i|
    puts "#{ans[i][0]} #{ans[i][1]} #{ans[i][2]}"
  end
end

n = gets.to_i
a = gets.split.map{|x| x.to_i - 1}
ans = [[], [], []]
a.each.with_index(1){|x, i| ans[x] << i}
w = ans.map(&:size).min
puts w
puts ans.map{|x| x.take(w)}.transpose.map{|x| x.join(' ')}

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

result = {
  1 => [],
  2 => [],
  3 => []
}

a.each_with_index { |v, i| result[v] << i+1 }

result = result[1].zip(result[2]).zip(result[3]).map(&:flatten).select { |w| w.none?(&:nil?) }

puts result.size
result.each { |w| puts w.join(' ') }

Person = Struct.new(:index, :subj) do
  def <=> (other)
    self.subj <=> other.subj
  end
end

n = gets.to_i
arr = gets.split(" ").each_with_index.map { |x, i| Person.new(i + 1, x.to_i) }.group_by { |p| p.subj }.values

if arr.length != 3
  puts 0
else
  len = arr.min_by { |x| x.length }.length

  puts len
  for i in 0...len
    puts "#{arr[0][i].index} #{arr[1][i].index} #{arr[2][i].index} "
  end
end

a=Array.new
b=Array.new
c=Array.new
d=Array.new
i=j=k=0
n=gets.to_i
str=gets.to_s
d=str.split
for r in 0..n-1
    h=d[r].to_i
#    print h
    if h==1
      a[i]=r+1
      i+=1
    elsif h==2
      b[j]=r+1
      j+=1
    elsif h==3
      c[k]=r+1
      k+=1
    end
end
#puts i
#puts j
#puts k
if i<=j and i<=k
  h=i
elsif j<=i and j<=k
  h=j
elsif k<=i and k<=j
  h=k
end
puts h
for r in 0..h-1
  print a[r]
  print " "
  print b[r]
  print " "
  puts c[r]
end

# 490A

gets.to_i
g = [[], [], []]
gets.chomp.split.each_with_index do |x, i|
  g[x.to_i - 1] << i + 1
end
m = g.map { |a| a.size }.min
puts m
m.times { |i| puts "#{g[0][i]} #{g[1][i]} #{g[2][i]}" }

n, t = 2.times.map{gets.split.map(&:to_i)}
m = 3.times.map{|x| t.each_index.select{|i| t[i]==x+1}}
puts s = m.map(&:size).min
s.times.each{|i| puts 3.times.map{|j| (m[j][i] + 1).to_s}.join(" ")}

n = gets.to_i
t = gets.split.map(&:to_i)
m = (1..3).to_a.map{ |x|
            t.each_index.select{ |i|
                            t[i] == x
                                    }
                                        }
                                        s = m.map(&:size).min
                                        puts s
                                        s.times.each{ |i|
                                                puts 3.times.map{ |j|
                                                            "#{m[j][i] + 1}"
                                                                }.join(" ")
                                        }

n = Integer gets
arry = gets
arry = arry.split(" ")
for i in 0..n-1
  arry[i] = Integer arry[i]
end

a=[[],[],[]]

for i in 1..n
  a[arry[i-1]-1] << i
end

size = a[0].size()
if a[1].size()<size
  size = a[1].size()
end

if a[2].size()<size
  size = a[2].size()
end

puts size
for i in 0..size-1
  printf("#{a[0][i]} #{a[1][i]} #{a[2][i]}\n")
end

n = gets.to_i
children_skills = gets.split.map &:to_i

children_by_skill = Array.new(3) {Array.new}

children_skills.each_index do |i|
  children_by_skill[children_skills[i] - 1] << (i + 1)
end

max_number_teams = [children_by_skill[0].length, children_by_skill[1].length, children_by_skill[2].length].min
puts max_number_teams
max_number_teams.times do
  puts "#{children_by_skill[0].shift} #{children_by_skill[1].shift} #{children_by_skill[2].shift}"
end

#!/usr/bin/ruby
gets
h=gets.split.map(&:to_i).each_with_index.group_by{|e,i|e}
h.default=[]
a=(1..3).map{|e|h[e].map{|_|_.last+1}}
siz=a.map(&:size).min
p siz
siz.times{|i|puts a.map{|e|e[i]}*' '}

n=gets.to_i
s=gets.chomp.split.map(&:to_i)
x=0;y=0;z=0;a=[];b=[];c=[]
s.each_index do |i|
	#puts i
	if s[i]==1
		a[x]=i+1
		x+=1
	elsif s[i]==2
		b[y]=i+1
		y+=1
	else
		c[z]=i+1
		z+=1
	end
end
m=x
if y<m
	m=y
end
if z<m
	m=z
end
puts m
m.times do |i|
	print a[i].to_s+' '+b[i].to_s+' '+c[i].to_s
	puts
end

def run
  n = $stdin.gets
  t = $stdin.gets.split.map(&:to_i)

  a = []
  t.each_with_index do |x, i|
    a << [x, i]
  end

  b = a.group_by { |x| x[0] }
  if b.length != 3
    puts "0"
    return
  end

  r = []
  b[1].zip(b[2], b[3]).each do |v|
    if v[0] != nil and v[1] != nil and v[2] != nil
      r << v.map {|x| x[1] + 1 }.join(" ")
    else
      break
    end
  end

  puts r.length
  puts r.join("\n")
end

run if $0 == __FILE__

n = gets.chomp.to_i
a = [[] , [] , []]           #list of lists
arr= gets.split.map(&:to_i)
arr.each_with_index do |val,ind|
  a[val-1] << ind + 1
end
size = a.map{|i| i.size}.min
puts size
size.times { |i|

  puts "#{a[0][i]} #{a[1][i]} #{a[2][i]}"
}

n = gets.split.map(&:to_i)
arr = gets.split.map(&:to_i)
num = [[],[],[]]
arr.size.times do |i|
  num[arr[i]-1].push(i+1)
end
small = [num[0].size , num[1].size , num[2].size].min
puts small

while !num[0].empty? and !num[1].empty? and !num[2].empty?
  puts "#{num[0][0]} #{num[1][0]} #{num[2][0]}"
  num[0].shift; num[1].shift; num[2].shift
end

n = gets.to_i
a = gets.split(" ").map(&:to_i)
print [a.count(1), a.count(2), a.count(3)].min
print "\n"
[a.count(1), a.count(2), a.count(3)].min.times {
  print a.index(1)+1
  a[a.index(1)] = 0
  print ' '
  print a.index(2)+1
  a[a.index(2)] = 0
  print ' '
  print a.index(3)+1
  a[a.index(3)] = 0
  print "\n"
}
print "\n"
print a

n = gets.to_i
a = gets.split(" ").map(&:to_i)
print [a.count(1), a.count(2), a.count(3)].min
print "\n"
[a.count(1), a.count(2), a.count(3)].min.times {
  p = a.index(1)+1
  print p
  p = 0
  print ' '
  p = a.index(2)+1
  print p
  p = 0
  print ' '
  p = a.index(3)+1
  print p
  p = 0
  print ' '
  print "\n"
}

n = gets.to_i
a = [nil] + gets.split.map(&:to_i)
b = [nil] + Array.new(3, 0)
for i in 1..n
  b[a[i]] += 1
end
w = b[1..3].min
puts w
if w != 0
  x = 0
  y = 0
  z = 0
  ans = Array.new(w){Array.new(3)}
  for i in 1..n
    if a[i] == 1 && x < w
      ans[x][0] = i
      x += 1
      a[i] = 0
    elsif a[i] == 2 && y < w
      ans[y][1] = i
      y += 1
      a[i] = 0
    elsif a[i] == 3 && y < w
      ans[z][2] = i
      z += 1
      a[i] = 0
    end
  end
  w.times do |i|
    puts "#{ans[i][0]} #{ans[i][1]} #{ans[i][2]}"
  end
end

Person = Struct.new(:index, :subj) do
  def <=> (other)
    self.subj <=> other.subj
  end
end

n = gets.to_i
arr = gets.split(" ").each_with_index.map { |x, i| Person.new(i, x.to_i) }

arr = arr.group_by { |x| x.subj }

one = arr[1].map { |x| x.index }
scn = arr[2].map { |x| x.index }
thr = arr[3].map { |x| x.index }

stop = [one.length, scn.length, thr.length].min

puts stop
for i in 0...stop
  puts "#{one[i]} #{scn[i]} #{thr[i]}"
end


A tree is a connected undirected graph consisting of n vertices and n  -  1 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:  The tree had exactly n vertices.  The tree had diameter d. In other words, d was the biggest distance between two vertices.  Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".

The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.

If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes). Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.

NoteBelow you can see trees printed to the output in the first sample and the third sample.

n, d, h = gets.split(" ").map(&:to_i)
d += 1
h += 1

if n < d
    p -1
    exit
end

if d >= 2*h
    p -1
    exit
end

if d == h && h >= 3
    (h-1).times do |i|
        puts "#{i+1} #{i+2}"
    end

    (n-h).times do |i|
        b = h
        puts "2 #{b+i+1}"
    end

    exit
end

if d == h && h < 3
    if n != d
        p -1
        exit
    end

    (h-1).times do |i|
        puts "#{i+1} #{i+2}"
    end

    exit
end

(h-1).times do |i|
    puts "#{i+1} #{i+2}"
end
#puts "."
puts "1 #{h+1}"
(d-h-1).times do |i|
    b = h
    puts "#{b+i+1} #{b+i+2}"
end
#puts "."

(n-d).times do |i|
    b = d
    puts "1 #{b+i+1}"
end

buf=gets.split(" ")
n, d, h=buf[0].to_i, buf[1].to_i, buf[2].to_i
if n<=d || d>h*2 || n>2 && d==1
	puts -1
else
	for i in 2..h+1
		puts "#{i-1} #{i}"
	end
	last=1
	for i in 1..d-h
		puts "#{last} #{i+h+1}"
		last=i+h+1
	end
	for i in 1..n-d-1
		puts "#{h} #{i+d+1}"
	end
end

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

if n < d
    p -1
    exit
end

if d >= 2*h
    p -1
    exit
end

if d == h && h >= 3
    (h-1).times do |i|
        puts "#{i+1} #{i+2}"
    end

    (n-h).times do |i|
        b = h
        puts "2 #{b+i+1}"
    end

    exit
end

if d == h && h < 3
    if n != d
        p -1
        exit
    end

    (h-1).times do |i|
        puts "#{i+1} #{i+2}"
    end

    exit
end

(h-1).times do |i|
    puts "#{i+1} #{i+2}"
end
puts "1 #{h+1}"
(d-h-1).times do |i|
    b = h+1
    puts "#{b+i+1} #{b+i+2}"
end

(n-d).times do |i|
    b = d+1
    puts "1 #{b+i+1}"
end

buf=gets.split(" ")
n, d, h=buf[0].to_i, buf[1].to_i, buf[2].to_i
if n<=d || d>h*2
	puts -1
else
	for i in 2..h+1
		puts "#{i-1} #{i}"
	end
	last=1
	for i in 1..d-h
		puts "#{last} #{i+h+1}"
		last=i+h+1
	end
	for i in 1..n-d-1
		puts "#{h} #{i+d+1}"
	end
end


Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.

The first line contains a single integer $$$t$$$ — the number of test cases ($$$1 \le t \le 1000$$$). The next $$$t$$$ lines describe the test cases. Each line contains three integers $$$a$$$, $$$b$$$, and $$$c$$$ — the lengths of the three fence segments ($$$1 \le a, b, c \le 10^9$$$).

For each test case print a single integer $$$d$$$ — the length of the fourth fence segment that is suitable for building the fence. If there are multiple answers, print any. We can show that an answer always exists.

NoteWe can build a quadrilateral with sides $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$.We can build a quadrilateral with sides $$$12$$$, $$$34$$$, $$$56$$$, $$$42$$$.

gets.chomp.to_i.times do |_i|
  a, b, c = gets.split.map(&:to_i)
  puts a + b + c - 1
end

T = gets.to_i

T.times do
  a, b, c = gets.split.map(&:to_i).sort

  puts Math.sqrt(b ** 2 + (c - a) ** 2).ceil
end


You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. $$$n$$$ is even.For each position $$$i$$$ ($$$1 \le i \le n$$$) in string $$$s$$$ you are required to change the letter on this position either to the previous letter in alphabetic order or to the next one (letters 'a' and 'z' have only one of these options). Letter in every position must be changed exactly once.For example, letter 'p' should be changed either to 'o' or to 'q', letter 'a' should be changed to 'b' and letter 'z' should be changed to 'y'.That way string "codeforces", for example, can be changed to "dpedepqbft" ('c' $$$\rightarrow$$$ 'd', 'o' $$$\rightarrow$$$ 'p', 'd' $$$\rightarrow$$$ 'e', 'e' $$$\rightarrow$$$ 'd', 'f' $$$\rightarrow$$$ 'e', 'o' $$$\rightarrow$$$ 'p', 'r' $$$\rightarrow$$$ 'q', 'c' $$$\rightarrow$$$ 'b', 'e' $$$\rightarrow$$$ 'f', 's' $$$\rightarrow$$$ 't').String $$$s$$$ is called a palindrome if it reads the same from left to right and from right to left. For example, strings "abba" and "zz" are palindromes and strings "abca" and "zy" are not.Your goal is to check if it's possible to make string $$$s$$$ a palindrome by applying the aforementioned changes to every position. Print "YES" if string $$$s$$$ can be transformed to a palindrome and "NO" otherwise.Each testcase contains several strings, for each of them you are required to solve the problem separately.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 50$$$) — the number of strings in a testcase. Then $$$2T$$$ lines follow — lines $$$(2i - 1)$$$ and $$$2i$$$ of them describe the $$$i$$$-th string. The first line of the pair contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$, $$$n$$$ is even) — the length of the corresponding string. The second line of the pair contains a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters.

Print $$$T$$$ lines. The $$$i$$$-th line should contain the answer to the $$$i$$$-th string of the input. Print "YES" if it's possible to make the $$$i$$$-th string a palindrome by applying the aforementioned changes to every position. Print "NO" otherwise.

NoteThe first string of the example can be changed to "bcbbcb", two leftmost letters and two rightmost letters got changed to the next letters, two middle letters got changed to the previous letters.The second string can be changed to "be", "bg", "de", "dg", but none of these resulting strings are palindromes.The third string can be changed to "beeb" which is a palindrome.The fifth string can be changed to "lk", "lm", "nk", "nm", but none of these resulting strings are palindromes. Also note that no letter can remain the same, so you can't obtain strings "ll" or "mm".

gets.to_i.times{gets;s=gets.chomp
	puts [s.bytes,s.bytes.reverse].transpose.all?{|x,y|[-2,0,2].include?(x-y)} ? :YES : :NO
}

T = gets.to_i
T.times do |i|
    n = gets.to_i
    str = gets.chomp
    result = true
    (n/2).times do |i|
        diff = str[i].ord - str[n-i-1].ord
        unless [0, 2, -2].include?(diff)
            result = false
            break
        end
    end
    puts result ? 'YES' : 'NO'
end

t=gets.to_i

chars = ('a'..'z').to_a
hsh = {}
0.upto(25).each do |pi|
  hsh[chars[pi]] = []
  hsh[chars[pi]] << chars[pi-1] if pi>0
  hsh[chars[pi]] << chars[pi+1] if pi<25
end

t.times do
  n=gets.to_i
  str=gets.strip
  hn=n/2
  possible = true
  0.upto(hn-1).each do |i|
    break unless possible
    j = n-1 - i
    # puts hsh[str[i]].inspect
    # puts hsh[str[j]].inspect
    possible = possible && (hsh[str[i]] & hsh[str[j]]).any?
  end
  puts (possible ? "YES" : "NO")
end

A = 'a'.ord
Z = 'z'.ord

def g(c)
  c > -1 ? c.chr : c
end

def f
  n = gets.chomp.to_i
  s = gets.chomp

  (0..(n/2)).each do |i|
    j = -1 - i
    a = s[i].ord
    b = s[j].ord

    amin = (a - 1) < A ? -1 : a - 1
    amax = (a + 1) > Z ? -1 : a + 1
    bmin = (b - 1) < A ? -1 : b - 1
    bmax = (b + 1) > Z ? -1 : b + 1
    # puts [i, j, s[i], s[j], a, b].inspect
    # puts [g(amin), g(amax), g(bmin), g(bmax)].inspect
    aminbmax = bmax != -1 && amin != -1 && bmax == amin
    amaxbmax = bmax != -1 && amax != -1 && bmax == amax
    aminbmin = bmin != -1 && amin != -1 && bmin == amin
    amaxbmin = bmin != -1 && amax != -1 && bmin == amax

    # puts [aminbmax, amaxbmax, aminbmin, amaxbmin].inspect

    if aminbmax || amaxbmax || aminbmin || amaxbmin
    else
      puts 'NO'
      return
    end
  end

  puts 'YES'
end

t = gets.chomp.to_i
t.times do
  f
end

def palindrome(x)
  return x==x.reverse
end

t = gets.to_i

larr = []
arr = []

t.times do
  larr.push gets.to_i
  arr.push gets.to_s
end

t.times do |i|
  num = larr[i]
  string = arr[i]

#  if palindrome(string)
#    puts "YES"
#    next
#  end
  f = false

  (0..num/2-1).each do |c|
    asdf = (string[c].ord-string[num-c-1].ord).abs
    if !(asdf == 0 or asdf == 2)
#      puts (string[c].ord-string[num-c-1].ord).abs
      puts "NO"
      f = true
      break
    end
  end

  next if f

  puts "YES"
end

i = gets.to_i

def checkpal(sa,sb)
    for i in 0..sa.length-1 do
        if sa[i].ord == sb[i].ord || (sa[i].ord-sb[i].ord).abs == 2
            next
        else
            return puts 'NO'
        end
    end
    return puts 'YES'
end

i.times do
    k = gets.to_i
    s = gets.chomp
    sa = s[0..(k/2)-1]
    sb = s[k/2..k].reverse
    checkpal(sa,sb)
end

gets.to_i.times{gets;s=gets.chomp
	puts [s.bytes,s.bytes.reverse].transpose.all?{|x,y|[-2,0,2].include?(x-y)} ? :Yes : :No
}

T = gets.to_i
T.times do |i|
    n = gets.to_i
    str = gets.chomp
    result = true
    (n/2).times do |i|
        diff = (str[i].ord - str[n-i-1].ord) % 26
        unless [0, 2, 24].include?(diff)
            result = false
            break
        end
    end
    puts result ? 'YES' : 'NO'
end


And where the are the phone numbers?You are given a string s consisting of lowercase English letters and an integer k. Find the lexicographically smallest string t of length k, such that its set of letters is a subset of the set of letters of s and s is lexicographically smaller than t.It's guaranteed that the answer exists.Note that the set of letters is a set, not a multiset. For example, the set of letters of abadaba is {a, b, d}.String p is lexicographically smaller than string q, if p is a prefix of q, is not equal to q or there exists i, such that pi < qi and for all j < i it is satisfied that pj = qj. For example, abc is lexicographically smaller than abcd , abd is lexicographically smaller than abec, afa is not lexicographically smaller than ab and a is not lexicographically smaller than a.

The first line of input contains two space separated integers n and k (1 ≤ n, k ≤ 100 000) — the length of s and the required length of t. The second line of input contains the string s consisting of n lowercase English letters.

Output the string t conforming to the requirements above. It's guaranteed that the answer exists.

NoteIn the first example the list of strings t of length 3, such that the set of letters of t is a subset of letters of s is as follows: aaa, aab, aac, aba, abb, abc, aca, acb, .... Among them, those are lexicographically greater than abc: aca, acb, .... Out of those the lexicographically smallest is aca.

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

min = max = s[0]
n.times do |i|
  min = s[i] if min > s[i]
  max = s[i] if max < s[i]
end

if n < k
  ans = s + min * (k-n)
else
  i = k-1
  until s[i] < max
    i -= 1
  end
  t = s[i]
  t_min = max
  n.times do |i|
    t_min = s[i] if s[i] > t && s[i] < t_min
  end
  ans = s[0,i] + t_min + min * (k-i-1)
end
puts ans

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

if n < k
  ans = s + s[0] * (k-n)
elsif n == k
  i = 0
  while s[i] > s[i+1] && i < s.length-1
    i += 1
  end
  t = s[i]
  s[i] = s[i+1]
  s[i+1] = t
  ans = s
else
  m = s[0]
  s.length.times do |i|
    m = s[i] if m < s[i]
  end
  ans = m * k
end
puts ans


You have an array a with length n, you can perform operations. Each operation is like this: choose two adjacent elements from a, say x and y, and replace one of them with gcd(x, y), where gcd denotes the greatest common divisor.What is the minimum number of operations you need to make all of the elements equal to 1?

The first line of the input contains one integer n (1 ≤ n ≤ 2000) — the number of elements in the array. The second line contains n space separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the array.

Print -1, if it is impossible to turn all numbers to 1. Otherwise, print the minimum number of operations needed to make all numbers equal to 1.

NoteIn the first sample you can turn all numbers to 1 using the following 5 moves:  [2, 2, 3, 4, 6].  [2, 1, 3, 4, 6]  [2, 1, 3, 1, 6]  [2, 1, 1, 1, 6]  [1, 1, 1, 1, 6]  [1, 1, 1, 1, 1] We can prove that in this case it is not possible to make all numbers one using less than 5 moves.

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

k = a.dup
flag = false
count = 0
while(a.size > 0)
	if a.count(1) != 0
		flag = true
		break
	end
	b = []
	for i in 0..(a.size-2)
		b << (a[i].gcd a[i+1])
	end
	a = b
	count += 1
end
if flag
	if k.count(1) > 1
		print(n - k.count(1) + count)
	else
		print(n - 1 + count)
	end
else
	print('-1')
end

n = gets.chomp.to_i
a = gets.chomp.split.map(&:to_i)
cnt = 0
a.each do |x|
  cnt += (x != 1) ? 1 : 0
end
if (cnt < n)
  print cnt
  exit
end
g = a[0]
a[1..-1].each do |x|
  g = g.gcd(x)
end
if (g > 1)
  print -1
  exit
end
ans = n
(0..n - 1).each do |i|
  g = a[i]
  (i..n - 1).each do |j|
    g = g.gcd(a[j])
    if (g == 1)
      ans = [ans, j - i + 1].min
      break
    end
  end
end
print ans - 1 + n - 1

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

k = a.dup
flag = false
count = 0
while(a.size > 0)
	if a.count(1) != 0
		flag = true
		break
	end
	b = []
	for i in 0..(a.size-2)
		b << (a[i].gcd a[i+1])
	end
	a = b
	count += 1
end
if flag
	print(n - a.count(1) + count)
else
	print('-1')
end


In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury. Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in ai burles (burle is the currency in Berland).You are the royal treasurer, which needs to count the minimum charges of the kingdom on the king's present. The king can only give money, he hasn't a power to take away them.

The first line contains the integer n (1 ≤ n ≤ 100) — the number of citizens in the kingdom. The second line contains n integers a1, a2, ..., an, where ai (0 ≤ ai ≤ 106) — the welfare of the i-th citizen.

In the only line print the integer S — the minimum number of burles which are had to spend.

NoteIn the first example if we add to the first citizen 4 burles, to the second 3, to the third 2 and to the fourth 1, then the welfare of all citizens will equal 4.In the second example it is enough to give one burle to the third citizen. In the third example it is necessary to give two burles to the first and the third citizens to make the welfare of citizens equal 3.In the fourth example it is possible to give nothing to everyone because all citizens have 12 burles.

n = gets.chomp.to_i
container = gets.chomp.split().map { |e| e.to_i }
maxEle = container.max
answer = 0
for i in container
    answer += maxEle - i
end

puts answer

require 'mathn'

n = gets.to_i
sum = 0

aaa = Array.new(n)
aab = Array.new(n)
aaa = gets.chomp.split

max = aaa[0].to_i

for i in 0...n
  aab[i] = aaa[i].to_i
  sum += aab[i]
  max = aab[i] if max < aab[i]
end

# puts sum

sum = max*n - sum

puts sum

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

max = arr.max
puts arr.map { |a| max - a }.inject(0, :+)

n = gets.to_i
a = []
a = gets.split.map &:to_i
sum = 0
(0...n).each do |i|
    sum += a[i]
end
puts a.max * n - sum

n = gets.to_i
a = gets.split.map(&:to_i)
a.sort!
t = 0
for i in 0...n
	t += a[-1] - a[i]
end
puts t

n = gets.to_i
as = gets.split.map(&:to_i)
puts as.map { |a| as.max - a }.inject(:+)

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

gets
x=gets.split.map{|e| e.to_i}
m=x.max
ans=0
x.each{|e|
	ans+=m-e
}
puts ans

t = gets.chomp.to_i
arr = gets.chomp.split.map(&:to_i)
mx = arr.max
co = 0
t.times.each do |i|
  # p [mx,arr[i]]
  co += (mx-arr[i])
end
puts co

gets
a=gets.split.map &:to_i
res=0
a.each{|e| res+=a.max-e}
puts res

gets;a=gets.split.map &:to_i;p a.max*a.size-(a.inject :+)

# coding: utf-8

# if __FILE__ == $0
# end

n = gets.to_i
a = gets.split.map(&:to_i)
top = a.max
fullfill = 0
for i in a
    fullfill += top - i
end
puts fullfill

class A
  attr_reader(:arr)
  def initialize(arr)
    @arr = arr
  end

  def max
    arr.max
  end

  def diffs
    m = max
    arr.map{|a| m - a}
  end

  def out
    diffs.inject(:+)
  end
end

_ = gets
xs = gets.split(" ").map(&:to_i)
puts A.new(xs).out

citizens = gets.chomp.to_i
w = gets.chomp
welfare = w.split

count = 0
for x in (0..citizens-1)
	for i in (0..citizens-1)
		if x != i
			if welfare[x].to_i < welfare[i].to_i
				count += (welfare[i].to_i - welfare[x].to_i)
				welfare[x] = welfare[i]
			end
		end
	end
end

print count

gets
arr = gets.split().map &:to_i
sum = 0
arr.each {|i| sum+= (arr.max - i)}
puts sum

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

max = pieces.max
p pieces.reduce(0) {|acc, n| n < max ? acc + max - n : acc }

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

puts a.map { |x| a.max - x }.inject(&:+)

n, *pieces = gets.chomp.split.map(&:to_i)

max = pieces.max
p pieces.reduce(0) {|acc, n| n < max ? acc + max - n : acc }


Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:  Include a person to the chat ('Add' command).  Remove a person from the chat ('Remove' command).  Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command). Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.As Polycarp has no time, he is asking for your help in solving this problem.

Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:   +<name> for 'Add' command.  -<name> for 'Remove' command.  <sender_name>:<message_text> for 'Send' command.  <name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line. It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc. All names are case-sensitive.

Print a single number — answer to the problem.

+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate

+Mike
-Mike
+Mike
Mike:Hi   I am here
-Mike
+Kate
-Kate

command = []
i = 0
traffic = 0
members = 0

while line = gets do
    command[i] = line.chomp
    i += 1
end

command.size.times do |i|
    if command[i].start_with? "+" then
        members += 1
    elsif command[i].start_with? "-" then
        members -= 1
    else
        k = command[i].index(":")
        traffic += (command[i][k+1..-1].size * members)
    end
end

puts traffic

#!/usr/bin/ruby
h=Hash.new
n=0
while s=gets do
  s.chomp!
  if s[0,1]=="+" then h[s[1..-1]]=true
  elsif s[0,1]=="-" then h.delete(s[1..-1])
  else
    x=s.split(":")[1]
    if x then n+=x.length*h.size end
  end
end
puts n

hash = Hash.new
bytes = 0
while line = gets
	line.chomp!
	hash.store(line, 0) if line.start_with?('+')
	if line.start_with?('-')
		line[0] = '+'
		hash.delete(line)
	end
	if line.include?(':')
		msg = line.split(':')
		if msg.size == 1
			len = 0
		else
			len = msg[1].length
		end
		bytes += len * hash.size
	end
end
puts bytes

bytes=0
names={}
while line=STDIN.gets do
	line=line.chomp
	if line[0,1]=="+" then names[line[1,line.length-1]]=1
	elsif line[0,1]=="-" then names.delete(line[1,line.length-1])
	else
		name,message=line.split(":")
		if message!=nil then bytes+=message.length*names.length end
	end
end
print(bytes,"\n")

member=0
byte=0
while line = gets
  line.strip!
  if line[0..0]=="+"
    member+=1
  elsif line[0..0]=="-"
    member-=1
  else
    pos=line.index ":"
    byte+=(line.size-pos-1)*member
  end
end
puts byte

traffic = num = 0
while input = gets
    input.strip!
    if input[0] == "+"
        num = num + 1
    elsif input[0] == "-"
        num = num - 1
    else
        traffic = traffic + (input.split(':', 2)[1].length) * num
    end
end
puts traffic

nl=Hash.new
sum=0
while line=gets
  line.chomp!
  if line[0] == "+"
    nl[line[1..(line.length-1)]]=true
  elsif line[0] == "-"
    nl.delete(line[1..(line.length-1)])
  else
    tmp=line.split(":")
    if tmp.length!=1
      sum+=tmp[1].length*nl.length
    end
  end
end
puts sum

ans=0
active=0

while a=gets do
a=a.chomp
if a[0]=="+"
active+=1
elsif a[0]=="-"
active-=1
else
l=a.length-a.index(":")-1
ans+=l*active
end
end

puts"#{ans}"

res = 0
sankasha=0
while line=gets do
  if line =~ /^\+/
    sankasha += 1
  elsif line =~ /^\-/
    sankasha -= 1
  else
    line.chomp =~ /:(.*)\z/
    res += ($1.size)*sankasha
  end
end
puts res

users = 0
bytes = 0

while line = gets do
  if line[0,1] == "+" then
    users += 1
  elsif line[0,1] == "-" then
    users -= 1
  else
    line = /[:](.*)/.match(line)
    if line then bytes += line[1].to_s.length * users end
  end
end

p bytes

count = 0
traffic = 0
while (command = gets)
	command.strip!
	case command[0]
	when "+"
	 count += 1
	when "-"
		count -= 1
	else
		message = command.split(":", 2)[1]
		traffic += message.length * count
	end
end

puts traffic

#!/usr/bin/env ruby

$users = Array.new
$bytes_sent = 0

def handle_input(chat_command)

	if chat_command.start_with? '+'
		chat_command.slice!(0)
		$users << chat_command
	elsif chat_command.start_with? '-'
		chat_command.slice!(0)
		$users.delete chat_command
	else
		message = chat_command.split(':')[1].to_s.strip
		$bytes_sent += $users.count * message.length
	end
end

ARGF.each do |line|
	handle_input(line)
end

puts $bytes_sent

num=0
sum=0
while STDIN.gets != nil ;
	s = $_
	if s[0] == ?+ ;
		num += 1
	elsif s[0] == ?- ;
		num -= 1
	else
		# print s.split(?:)
		sum += num*(s.split(?:)[1].size-1)
		# print "#{num}, #{sum}\n"
	end
end
print sum

#!/usr/bin/env ruby
count = 0
traffic = 0
while l = gets
  l.strip!
  case l[0]
  when ?+
    count += 1
  when ?-
    count -= 1
  else
    traffic += count * l.split(':', 2)[1].length
  end
end

puts traffic

traffic = count = 0

while l = gets
  l.strip!
  case l[0]
  when "+"
    count += 1
  when "-"
    count -= 1
  else
    traffic += count * l.split(':', 2)[1].length
  end
end

puts traffic

require 'set'
lines = gets(nil)
user = Set.new
ans = 0
lines.split("\n").each do |line|
    if line[0] == "+"
        user.add(line[1,line.size-1])
    elsif line[0] == "-"
        user.delete(line[1,line.size-1])
    else
        ans += user.size * line.split(":")[1].size if line.split(":")[1]
    end
end
puts ans

cnt = 0
res = 0
while s = gets do
  next if s.empty?
  s.strip!
  cnt += 1 if s[0, 1] == '+'
  cnt -= 1 if s[0, 1] == '-'
  pos = s.index(':')
  next if pos.nil?
  res += cnt * s[pos + 1, s.length].length
end
puts res

peoples, traffic = 0, 0
while line = gets do
  case line.strip
    when /\+\w+/ then peoples += 1
    when /\-\w+/ then peoples -= 1
    when /\w+:(.+)/ then traffic += peoples * $1.size
  end
end
puts traffic

require 'set'

ret = 0
persons = Set.new
while line = gets
  line.chomp!
  if line[0] == '+'
    persons.add(line[1..line.size])
  elsif line[0] == '-'
    persons.delete(line[1..line.size])
  else
    name, text = line.split(":")
    if text
      ret += text.size * persons.size
    end
  end
end

puts ret

input, names, traffic = STDIN.read.split("\n"), [], 0

input.each do |i|
	if i[0] == '+'
		names.push i[1..-1]
	elsif i[0] == '-'
		names.delete i[1..-1]
	else
		msg = i.split(':')
		traffic += names.length * msg[1].length unless msg[1].nil?
	end
end

p traffic

#!/usr/bin/ruby
h=Hash.new
n=0
while s=gets do
  s.chomp!
  if s[0,1]=="+" then h[s[1,-1]]=true
  elsif s[0,1]=="-" then h.delete(s[1,-1])
  else n+=s.split(":")[1].length*h.size end
end
puts n

member=0
byte=0
while line = gets
  line.strip!
  if line[0..0]=="+"
    member+=1
  elsif line[0..0]=="-"
    member-=1
  else
    pos=line.index ":"
    byte+=line.size-pos-1
  end
end
puts byte

member=0
byte=0
while line = gets
  if line[0..0]=="+"
    member+=1
  elsif line[0..0]=="-"
    member-=1
  else
    pos=line.index ":"
    byte+=line.size-pos-1
  end
end
puts byte

ans=0
active=0

while a=gets do

if a[0]=="+"
active+=1
elsif a[0]=="-"
active-=1
else
l=a.length-a.index(":")-1
ans+=l*active
end
end

puts"#{ans}"

res = 0
while line=gets do
  if line =~ /^\+/
  elsif line =~ /^\-/
  else
    res += line.split(':')[1].size
  end
end
puts res

res = 0
while line=gets do
  if line =~ /^\+/
  elsif line =~ /^\-/
  else
    res += line.chomp.split(':')[1].size
  end
end
puts res

users = 0
bytes = 0
loop {
  line = gets().chomp!

  if line[0,1] == "+" then
    users += 1
  elsif line[0,1] == "-" then
    users -= 1
  else
    line = /[:](.*)/.match(line)
    bytes += line[1].to_s.length * users
  end

  if users <= 1 then break end
}
p bytes

cnt = 0
res = 0
100.times do
  s = gets
  next if s.nil? || s.empty?
  s.chomp!
  cnt += 1 if s[0] == '+'
  cnt -= 1 if s[0] == '-'
  pos = s.index(':')
  i = 0
  while i <= s.length && s[i] != ':' do
    i += 1
  end
#  if i != pos then
#    while true do
#      i += 1
#    end
#  end
  res += cnt * (s.length - i - 1)
end
puts res

cnt = 0
res = 0
while s = gets do
  next if s.empty?
  cnt += 1 if s[0] == '+'
  cnt -= 1 if s[0] == '-'
  pos = s.index(':')
  next if pos.nil?
  res += cnt * s[pos + 1, s.length].chomp.length
end
puts res

cnt = 0
res = 0
100.times do
  s = gets
  next if s.nil? || s.empty?
  cnt += 1 if s[0] == '+'
  cnt -= 1 if s[0] == '-'
  pos = s.index(':')
  next if pos.nil?
  res += cnt * s[pos + 1, s.length].chomp.length
end
puts res

cnt = 0
res = 0
while s = gets do
  cnt += 1 if s[0] == '+'
  cnt -= 1 if s[0] == '-'
  pos = s.index(':')
  next if pos.nil?
  res += cnt * s[pos + 1, s.length].chomp.length
end
puts res

cnt = 0
res = 0
while true do
  s = gets
  break if s.nil?
  cnt += 1 if s[0] == '+'
  cnt -= 1 if s[0] == '-'
  pos = s.index(':')
  next if pos.nil?
  res += cnt * s[pos + 1, s.length].chomp.length
end
puts res

cnt = 0
res = 0
while s = gets do
  next if s.empty?
  s.strip!
  cnt += 1 if s[0] == '+'
  cnt -= 1 if s[0] == '-'
  pos = s.index(':')
  next if pos.nil?
  res += cnt * s[pos + 1, s.length].length
end
puts res

cnt = 0
res = 0
100.times do
  s = gets
  next if s.nil? || s.empty?
  s.chomp!
  cnt += 1 if s[0] == '+'
  cnt -= 1 if s[0] == '-'
  pos = s.index(':')
  next if pos.nil?
  i = 0
  while i <= s.length && s[i] != ':' do
    i += 1
  end
#  if i != pos then
#    while true do
#      i += 1
#    end
#  end
  res += cnt * (s.length - i - 1)
end
puts res


Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold:   The product of all numbers in the first set is less than zero ( < 0).  The product of all numbers in the second set is greater than zero ( > 0).  The product of all numbers in the third set is equal to zero.  Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array.

The first line of the input contains integer n (3 ≤ n ≤ 100). The second line contains n space-separated distinct integers a1, a2, ..., an (|ai| ≤ 103) — the array elements.

In the first line print integer n1 (n1 > 0) — the number of elements in the first set. Then print n1 numbers — the elements that got to the first set. In the next line print integer n2 (n2 > 0) — the number of elements in the second set. Then print n2 numbers — the elements that got to the second set. In the next line print integer n3 (n3 > 0) — the number of elements in the third set. Then print n3 numbers — the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them.

class A
  def initialize
    list1 = []
    list2 = []
    list3 = []
    zero_list = []
    m_list = []
    p_list = []
    n = gets.chomp.to_i

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

    list.each do |num|
      if num < 0
        m_list << num
      elsif num > 0
        p_list << num
      else
        zero_list << num
      end
    end
    m_count = list.count{|n| n < 0}
    p_count = list.count{|n| n > 0}
    z_count = list.count{|n| n == 0}

    if m_count > 2
      if(m_count.odd?)
        list1 << m_list.pop
        list2 += m_list
      else
        list1 << m_list.pop
        list2 << m_list.pop
        list2 << m_list.pop
        list3 += m_list
      end
      m_list = []
    else
      list1 << m_list.pop
      list3 += m_list
    end

    list2 += p_list
    list3 += [0]*z_count

    puts "#{list1.size} " + list1.join(' ')
    puts "#{list2.size} " + list2.join(' ')
    puts "#{list3.size} " + list3.join(' ')
  end
end

a = A.new

gets
a=gets.split.map(&:to_i).sort
[[a.shift],a.last==0?a.shift(2):[a.pop],a].each{|c|puts"#{c.size} #{c.join' '}"}

gets.chomp.to_i
arrs = gets.chomp.split(/ /).map(&:to_i)
arr_1 = []
arr_2 = []
arr_3 = []
arrs.each do |a|
    arr_1 << a if a < 0
    arr_2 << a if a > 0
    arr_3 << a if a == 0
end
arr_3 << arr_1.shift if arr_1.length.even?
if arr_2.length == 0 && arr_1.length > 2
    arr_2 << arr_1.delete_at(0)
    arr_2 << arr_1.delete_at(0)
end
puts "#{arr_1.length} #{arr_1.sort.join(" ")}"
puts "#{arr_2.length} #{arr_2.sort.join(" ")}"
puts "#{arr_3.length} #{arr_3.sort.join(" ")}"

def g1(xs)
	print xs.size
	while xs.empty? ==false
		print " ",xs.shift
	end
	print "\n"
end
def f()
n=gets.to_i
xs=gets.split.map{|e| e.to_i}
xsU=xs.select{|e|
	e>0
}
xsD=xs.select{|e|
	e<0
}
xs0=xs.select{|e|
	e==0
}
if xsU.size==0
	xsU<<xsD.shift
	xsU<<xsD.shift
end
if xsD.size%2==0 then
	xs0<<xsD.shift
end
g1(xsD)
g1(xsU)
g1(xs0)
end
f()

n=gets.to_i
a=gets.split.map(&:to_i)
x=[];y=[];z=[]
a.each {|v|
    x<<v if v<0
    y<<v if v>0
    z<<v if v==0
}
if y.empty? then
    y<<x.pop
    y<<x.pop
end
if x.size.even? then
    z<<x.pop
end
puts "#{x.size} #{x*' '}"
puts "#{y.size} #{y*' '}"
puts "#{z.size} #{z*' '}"

n = Integer(gets)
input = gets.chomp
nums = input.split
a = Array.new
for i in 0...n
    a[i] = Integer(nums[i])
end
num1 = -1
for i in 0...n
    if a[i] < 0
        num1 = i
        break
    end
end
positive = Array.new
for i in 0...n
    if a[i] > 0
        positive.push(a[i])
    end
end
class2 = Array.new
if positive.length == 0
    for i in 0...n
        if a[i] < 0 && i != num1
            class2.push(a[i])
        end
        if class2.length == 2
            break
        end
    end
end

if positive.length != 0
    b = a.reject{|x| x == a[num1] || x == positive[0]}
    print 1," ", a[num1]
    puts
    print 1, " ", positive[0]
    puts
    print (n-2)," ",b.join(" ")
else
    b = a.reject{|x| x == a[num1] || x == class2[0] || x == class2[1]}
    print 1," ", a[num1]
    puts
    print 2," ", class2.join(" ")
    puts
    print (n-3)," ",b.join(" ")
end

n = gets.to_i

arr = gets.split(" ").map(&:to_i)

zero_array = arr.select{|i| i == 0}
zero_count = zero_array.length

pos_array = arr.select{|i| i > 0}
pos_count = pos_array.length

neg_count = n - zero_count - pos_count

neg_array = arr - pos_array - zero_array

if pos_count == 0
	pos_array << neg_array.pop
	pos_array << neg_array.pop
	neg_count -= 2
	pos_count += 2
end

if neg_count.even?
	zero_array << neg_array.pop
	zero_count += 1
	neg_count -= 1
end

puts "#{neg_count} #{neg_array.join(' ')}"
puts "#{pos_count} #{pos_array.join(' ')}"
puts "#{zero_count} #{zero_array.join(' ')}"

gets
l = gets.split.map(&:to_i)
n = l.find { |x| x < 0 }
l.delete(n)
p = l.find { |x| x > 0 }
if !p
	t1 = l.find { |x| x < 0 }
	l.delete(t1)
	t2 = l.find { |x| x < 0 }
	l.delete(t2)

	p = "2 #{t1} #{t2}"
else
	l.delete(p)
	p = "1 #{p}"
end
puts "1 #{ n }"
puts "#{ p }"
puts "#{ l.size } #{ l.join(" ") }"

gets
a=gets.split.map(&:to_i).sort
b=[[a.shift]]
a.last==0?b<<a.shift(2):b<<[a.pop]
b<<a
b.each{|c|puts"#{c.size} #{c.join' '}"}

gets
a=gets.split.map(&:to_i).sort
puts"1 #{a.shift}"
a.last==0?(puts"2 #{a.shift(2).join' '}"):(puts"1 #{a.pop}")
puts"#{a.size} #{a.join' '}"

gets
a=gets.split.map(&:to_i).sort
puts"1 #{a.shift}"
if a.last==0 then puts"2 #{a.shift(2).join' '}" else puts"1 #{a.pop}" end
puts"#{a.size} #{a.join' '}"

gets.chomp # Skip the first line
seq = gets.chomp.split.map { |x| x.to_i }
neg = seq.select { |x| x < 0 }
pos = seq.select { |x| x > 0 }
zeros = [0]
if pos.empty?
  pos.concat(neg[-2..-1])
  neg = neg[0..-3]
end
first_neg, *rest_neg = *neg
(neg.size.even? ? zeros : pos).concat(rest_neg) unless rest_neg.first.nil?
puts "1 #{first_neg}"
puts "#{pos.size} #{pos.join(' ')}"
puts "#{zeros.size} #{zeros.join(' ')}"

n = gets[0..-2].to_i
arr = gets[0..-2].split(' ')
a = Array.new(arr.size) { |index| arr[index].to_i }
a.sort!
puts "1 #{a[0]}"
nPositive = a.count { |obj| obj > 0 }
if nPositive == 0#There is no positive numbers
  puts "2 #{a[1]} #{a[2]}"
  print "#{n - 3} "
  3.upto(n - 1) { |i| print "#{a[i]} " }
else #There is atleast one positive numbers
  puts "1 #{a[n-1]}"
  print "#{n - 2} "
  1.upto(n - 2) { |i| print "#{a[i]} " }
end

#!/usr/bin/env ruby

n = gets.to_i
x = gets.split.collect{|i| i.to_i}
a, b, c = [], [], []
x.each do |i|
	if i < 0 && a.size == 0
		a << i
	elsif i > 0 && b.size == 0
		b << i
	else
		c << i
	end
end

if b.size == 0
	2.times do
		c.each do |i|
			if b.size < 2 && i < 0
				b << i
				c.delete(i)
				break
			end
		end
	end
end

puts "#{a.size} #{a.join(" ")}"
puts "#{b.size} #{b.join(" ")}"
puts "#{c.size} #{c.join(" ")}"

n=gets.to_i
a=gets.chomp.split.map(&:to_i).sort!
puts "1 #{a[0]}"
if a[2]<0 && a[1]<0
	puts "2 #{a[1]} #{a[2]}"
	print "#{n-3}"
	for i in 3..n-1
		print " #{a[i]}"
	end
else
	puts "1 #{a[n-1]}"
	print n-2
	for i in 1..n-2
		print " #{a[i]}"
	end
end
puts

n = gets.to_i
a = gets.split(' ').map { |i| i.to_i }
b = a.select { |i|  i > 0}
c = a.select { |i|  i < 0}
d = a.select { |i|  i == 0 }
if c.size % 2 == 0
    d.push c.pop
end
if b.size == 0
    2.times { b.push c.pop }
end

puts "#{c.size} " + c.join(' ')
puts "#{b.size} " + b.join(' ')
puts "#{d.size} " + d.join(' ')

n = gets.to_i
a = gets.split(' ').map { |i| i.to_i }.sort
c = [a.shift]
b = a[-1] > 0 ? [a.pop()] : a.shift(2)
[c, b, a].each do |arr| puts "#{arr.size} " + arr.join(' ') end

n = gets.to_i
a = gets.split(' ').map { |i| i.to_i }
b = a.select { |i|  i > 0}
c = a.select { |i|  i < 0}
d = a.select { |i|  i == 0 }
if c.size % 2 == 0
    d.push c.pop
end
if b.size == 0
    2.times { b.push c.pop }
end
[c, b, d].each do |arr|
    puts "#{arr.size} " + arr.join(' ')
end

def pick_minus(a)
  a.delete(a.find {|x| x < 0})
end

def pick_plus(a)
  a.delete(a.find {|x| x > 0})
end

def str(n)
  if n.is_a?(Array)
    "#{n.length} #{n.join(" ")}\n"
  else
    "1 #{n}\n"
  end
end

def run
  n = $stdin.gets.to_i
  a = $stdin.gets.split.map(&:to_i)

  n1 = pick_minus(a)
  unless n2 = pick_plus(a)
    n2 = [pick_minus(a), pick_minus(a)]
  end

  puts str(n1) , str(n2) , str(a)
end

run if $0 == __FILE__

n = gets

a= gets.split.map(&:to_i).sort
b= [[a.shift]]            # there's atleast one negative element
a.last == 0 ? b<< a.shift(2) : b<< [a.pop]  # there's no positive so combine two neg
b<< a
b.each do |val|
    puts "#{val.size()} #{val.join(' ')}"
end

# cook your code here

def solve(arr)
    first = []
    second= []
    third= []
    arr.each do |val|
        if val ==0
            third.push(0)
        elsif val >0
            second << val
        else
            first << val
        end
    end

    if second.size == 0
        second<< first.pop
        second << first.pop
    end
    if first.size % 2 ==0
        third<< first.pop
    end
    return first,second,third

end

n = gets.to_i
a = gets.split(" ").map(&:to_i)
ans = solve(a)
print "#{ans[0].size} "
ans[0].each do |val|
    print "#{val} "
end
puts
print "#{ans[1].size} "
ans[1].each do |val|
    print "#{val} "
end
puts
print"#{ans[2].size} "
ans[2].each do |val|
    print "#{val} "
end

class A
  def initialize
    list1 = []
    list2 = []
    list3 = [1]
    zero_list = []
    m_list = []
    p_list = []
    n = gets.chomp.to_i

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

    list.each do |num|
      if num < 0
        m_list << num
      elsif num > 0
        p_list << num
      else
        zero_list << num
      end
    end
    m_count = list.count{|n| n < 0}

    m_c = (m_count/2.0).ceil
    if m_c.even?
      list1 << -1
    else
      list1 << 1
    end

    if (m_count-m_c).even?
      list2 << 1
    else
      list2 << -1
    end

    m_c.times do
      list1 << m_list.pop
    end

    list2 += m_list + p_list
    list3 += zero_list

    puts list1.join(' ')
    puts list2.join(' ')
    puts list3.join(' ')
  end
end

a = A.new

class A
  def initialize
    list1 = []
    list2 = []
    list3 = []
    zero_list = []
    m_list = []
    p_list = []
    n = gets.chomp.to_i

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

    0.upto(n-2) do |i|
      1.upto(n-1) do |j|
        list1 = list[0..i]
        list2 = list[i+1..j]
        list3 = list[j+1..n-1]

        if list1.inject(:*) < 0 && list2.inject(:*) > 0 && list3.include?(0)
          puts "#{list1.size} " + list1.join(' ')
          puts "#{list2.size} " + list2.join(' ')
          puts "#{list3.size} " + list3.join(' ')
          exit
        end
      end
    end

  end
end

a = A.new

class A
  def initialize
    list1 = []
    list2 = []
    list3 = [1]
    zero_list = []
    m_list = []
    p_list = []
    n = gets.chomp.to_i

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

    0.upto(97) do |i|
      1.upto(98) do |j|
        list1 = list[0..i]
        list2 = list[i+1..j]
        list3 = list[j+1..n-1]

        if list1.inject(:*) < 0 && list2.inject(:*) > 0 && list3.include?(0)
          puts "#{list1.max.abs} " + list1.join(' ')
          puts "#{list2.max.abs} " + list2.join(' ')
          puts "#{[list3.max.abs,1].max} " + list3.join(' ')
          exit
        end
      end
    end

  end
end

a = A.new

class A
  def initialize
    list1 = []
    list2 = []
    list3 = [1]
    zero_list = []
    m_list = []
    p_list = []
    n = gets.chomp.to_i

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

    0.upto(97) do |i|
      1.upto(98) do |j|
        list1 = list[0..i]
        list2 = list[i+1..j]
        list3 = list[j+1..n-1]

        if list1.inject(:*) < 0 && list2.inject(:*) > 0 && list3.include?(0)
          puts list1.join(' ')
          puts list2.join(' ')
          puts list3.join(' ')
          exit
        end
      end
    end

  end
end

a = A.new

class A
  def initialize
    list1 = []
    list2 = []
    list3 = []
    zero_list = []
    m_list = []
    p_list = []
    n = gets.chomp.to_i

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

    list.each do |num|
      if num < 0
        m_list << num
      elsif num > 0
        p_list << num
      else
        zero_list << num
      end
    end
    m_count = list.count{|n| n < 0}
    p_count = list.count{|n| n > 0}
    z_count = list.count{|n| n == 0}

    if p_count == 0
      list2 << m_list.pop
      list2 << m_list.pop
      list1 += m_list
    else
      list1 << m_list.pop
      list2 += m_list
    end

    list2 += p_list
    list3 += [0]*z_count + m_list

    puts "#{list1.size} " + list1.join(' ')
    puts "#{list2.size} " + list2.join(' ')
    puts "#{list3.size} " + list3.join(' ')
  end
end

a = A.new

class A
  def initialize
    list1 = []
    list2 = []
    list3 = []
    zero_list = []
    m_list = []
    p_list = []
    n = gets.chomp.to_i

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

    list.each do |num|
      if num < 0
        m_list << num
      elsif num > 0
        p_list << num
      else
        zero_list << num
      end
    end
    m_count = list.count{|n| n < 0}
    p_count = list.count{|n| n > 0}
    z_count = list.count{|n| n == 0}

    if m_count > 2
      if(m_count.odd?)
        list2 << m_list.pop
        list2 << m_list.pop
        list1 += m_list
      else
        list1 << m_list.pop
        list2 += m_list
      end
      m_list = []
    else
      list1 << m_list.pop
    end

    list2 += p_list
    list3 += [0]*z_count + m_list

    puts "#{list1.size} " + list1.join(' ')
    puts "#{list2.size} " + list2.join(' ')
    puts "#{list3.size} " + list3.join(' ')
  end
end

a = A.new

gets.chomp.to_i
arrs = gets.chomp.split(/ /).map(&:to_i)
arr_1 = []
arr_2 = []
arr_3 = []
arrs.each do |a|
    arr_1 << a if a < 0
    arr_2 << a if a > 0
    arr_3 << a if a == 0
end
arr_2 << arr_1.shift if arr_1.length.even?
if arr_2.length == 0 && arr_1.length > 2
    arr_2 << arr_1.delete_at(0)
    arr_2 << arr_1.delete_at(0)
end
puts "#{arr_1.length} #{arr_1.sort.join(" ")}"
puts "#{arr_2.length} #{arr_2.sort.join(" ")}"
puts "#{arr_3.length} #{arr_3.sort.join(" ")}"

def g1(xs)
	print xs.size
	while xs.empty? ==false
		print " ",xs.shift
	end
	print "\n"
end
def f()
n=gets.to_i
xs=gets.split.map{|e| e.to_i}
xsU=xs.select{|e|
	e>0
}
xsD=xs.select{|e|
	e<0
}
xs0=xs.select{|e|
	e==0
}
if xsU.size==0
	xsU<<xsD.shift
	xsU<<xsD.shift
end
g1(xsU)
g1(xsD)
g1(xs0)
end
f()

def g1(xs)
	print xs.size
	while xs.empty? ==false
		print " ",xs.shift
	end
	print "\n"
end
def f()

n=gets.to_i
xs=gets.split.map{|e| e.to_i}
(1..n).each{|i|
	xs1=xs.take(i)
	xa=xs.drop(i)
	(1..(xa.size)).each{|j|
		xs2=xa.take(j)
		xs3=xa.drop(j)
		if xs2.empty? ==true || xs3.empty? == true
			next
		end
		n1=xs1.reduce(:*)
		n2=xs2.reduce(:*)
		n3=xs3.reduce(:*)
		if n1<0 && n2>0 && n3==0 then
			g1(xs1)
			g1(xs2)
			g1(xs3)
			return
		end
	}
}
end
f()

n = Integer(gets)
input = gets.chomp
nums = input.split
a = Array.new
for i in 0...n
    a[i] = Integer(nums[i])
end
num1 = -1
for i in 0...n
    if a[i] < 0
        num1 = i
        break
    end
end
positive = Array.new
for i in 0...n
    if a[i] > 0
        positive.push(a[i])
    end
end
class2 = Array.new
if positive.length == 0
    for i in 0...n
        if a[i] < 0 && i != num1
            class2.push(a[i])
        end
        if class2.length == 2
            break
        end
    end
end

if positive.length != 0
    b = a.reject{|x| x == a[num1] || x == positive[0]}
    print 1," ", a[num1]
    puts
    print 1, " ", positive[0]
    puts
    print (n-2)," ",b.join(" ")
else
    b = a.reject{|x| x == a[num1] || x == class2[0] || x == class2[1]}
    print 1," ", a[num1]
    puts
    print 1," ", class2.join(" ")
    puts
    print (n-3)," ",b.join(" ")
end

gets
a=gets.split.map(&:to_i)
puts "1 #{a.min}","1 #{a.max}","#{a.size-2} #{(a-[a.min,a.max]).join' '}"

gets.chomp # Skip the first line
seq = gets.chomp.split.map { |x| x.to_i }
neg = seq.select { |x| x < 0 }
pos = seq.select { |x| x > 0 }
zeros = [0]
first_neg, *rest_neg = *neg
(neg.size.even? ? zeros : pos) << rest_neg
puts "1 #{first_neg}"
puts "#{pos.size} #{pos.join(' ')}"
puts "#{zeros.size} #{zeros.join(' ')}"

gets.chomp # Skip the first line
seq = gets.chomp.split.map { |x| x.to_i }
first_neg = seq.find { |x| x < 0 }
pos = seq.select { |x| x > 0 || (x < 0 && x != first_neg) }
puts "1 #{first_neg}"
puts "#{pos.size} #{pos.join(' ')}"
puts '1 0'

gets.chomp # Skip the first line
seq = gets.chomp.split.map { |x| x.to_i }
neg = seq.select { |x| x < 0 }
pos = seq.select { |x| x > 0 }
zeros = [0]
first_neg, *rest_neg = *neg
(neg.size.even? ? zeros : pos).concat(rest_neg) unless rest_neg.first.nil?
puts "1 #{first_neg}"
puts "#{pos.size} #{pos.join(' ')}"
puts "#{zeros.size} #{zeros.join(' ')}"

n = gets[0..-2].to_i
arr = gets[0..-2].split(' ')
a = Array.new(arr.size) { |index| arr[index].to_i }
a.sort!
puts "1 #{a[0]}"
nPositive = a.count { |obj| obj > 0 }
if nPositive == 0#There is no positive numbers
  puts "2 #{a[1]} #{a[2]}"
  print "#{n - 3} "
  3.upto(n - 1) { |i| print "#{a[i] }" }
else #There is atleast one positive numbers
  puts "1 #{a[n-1]}"
  print "#{n - 2} "
  1.upto(n - 2) { |i| print "#{a[i]} " }
end

n = gets[0..-2].to_i
arr = gets[0..-2].split(' ')
a = Array.new(arr.size) { |index| arr[index].to_i }
a.sort!
puts("1 " + a[0].to_s)
print n - 2
1.upto(n - 2) { |i| print " ", a[i]}
puts
print 1, " ", a[-1]

n = gets.to_i
a = gets.split(' ').map { |i| i.to_i }
for i in 1...n-1
    for j in i+1...n
        array = [a[0, i], a[i, j - 1], a[j, n - j]]
        m1 = a[0, i].inject { |val, temp| val *= temp}
        m2 = a[i, j - i].inject { |val, temp| val *= temp}
        m3 = a[j, n - j].inject { |val, temp| val *= temp}
        if m1 < 0 && m2 > 0 && m3 == 0
            puts "#{array[0].size} " + array[0].join(' ')
            puts "#{array[1].size} " + array[1].join(' ')
            puts "#{array[2].size} " + array[2].join(' ')
        end
    end
end

n = gets.to_i
a = gets.split(' ').map { |i| i.to_i }.sort
c = [a.shift]
b = a[-1] > 0 ? [a.pop()] : [a.shift(2)]
[c, b, a].each do |a| puts "#{a.size} " + a.join(' ') end

n = gets.to_i
a = gets.split(' ').map { |i| i.to_i }.sort
c = [a.shift]
b = a[-1] > 0 ? [a.pop()] : [a.shift(2)]
[c, b, a].each do |arr| puts "#{arr.size} " + arr.join(' ') end

class A
  def initialize
    list1 = []
    list2 = []
    list3 = []
    zero_list = []
    m_list = []
    p_list = []
    n = gets.chomp.to_i

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

    list.each do |num|
      if num < 0
        m_list << num
      elsif num > 0
        p_list << num
      else
        zero_list << num
      end
    end
    m_count = list.count{|n| n < 0}
    p_count = list.count{|n| n > 0}
    z_count = list.count{|n| n == 0}

    if m_count > 2
      if(m_count.odd?)
        list1 << m_list.pop
        list2 += m_list
      else
        list1 << m_list.pop
        list2 << m_list.pop
        list2 << m_list.pop
      end
      m_list = []
    else
      list1 << m_list.pop
    end

    list2 += p_list
    list3 += [0]*z_count + m_list

    puts "#{list1.size} " + list1.join(' ')
    puts "#{list2.size} " + list2.join(' ')
    puts "#{list3.size} " + list3.join(' ')
  end
end

a = A.new

class A
  def initialize
    list1 = []
    list2 = []
    list3 = []
    zero_list = []
    m_list = []
    p_list = []
    n = gets.chomp.to_i

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

    list.each do |num|
      if num < 0
        m_list << num
      elsif num > 0
        p_list << num
      else
        zero_list << num
      end
    end
    m_count = list.count{|n| n < 0}
    p_count = list.count{|n| n > 0}
    z_count = list.count{|n| n == 0}

    if m_count > 2
      if(m_count.odd?)
        list1 << m_list.pop
        list2 += m_list
      else
        list1 << m_list.pop
        list1 << m_list.pop
        list2 += m_list
      end
      m_list = []
    else
      list1 << m_list.pop
    end

    list2 += p_list
    list3 += [0]*z_count + m_list

    puts "#{list1.size} " + list1.join(' ')
    puts "#{list2.size} " + list2.join(' ')
    puts "#{list3.size} " + list3.join(' ')
  end
end

a = A.new

class A
  def initialize
    list1 = []
    list2 = []
    list3 = [1]
    zero_list = []
    m_list = []
    p_list = []
    n = gets.chomp.to_i

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

    0.upto(97) do |i|
      1.upto(98) do |j|
        list1 = list[0..i]
        list2 = list[i+1..j]
        list3 = list[j+1..n-1]

        if list1.inject(:*) < 0 && list2.inject(:*) > 0 && list3.include?(0)
          puts "1 " + list1.join(' ')
          puts "1 " + list2.join(' ')
          puts "1 " + list3.join(' ')
          exit
        end
      end
    end

  end
end

a = A.new

class A
  def initialize
    list1 = []
    list2 = []
    list3 = [1]
    zero_list = []
    m_list = []
    p_list = []
    n = gets.chomp.to_i

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

    0.upto(97) do |i|
      1.upto(98) do |j|
        list1 = list[0..i]
        list2 = list[i+1..j]
        list3 = list[j+1..n-1]

        if list1.inject(:*) < 0 && list2.inject(:*) > 0 && list3.include?(0)
          puts "#{list1.size} " + list1.join(' ')
          puts "#{list2.size} " + list2.join(' ')
          puts "#{list3.size} " + list3.join(' ')
          exit
        end
      end
    end

  end
end

a = A.new

class A
  def initialize
    list1 = []
    list2 = []
    list3 = []

    n = gets.chomp.to_i

    list = gets.chomp.split(' ').map(&:to_i)
    z_c = list.count(0)
    list.delete(0)
    list.sort!

    list += [0]*z_c

    0.upto(n-3) do |i|
      1.upto(n-2) do |j|
        list1 = list[0..i]
        list2 = list[i+1..j]
        list3 = list[j+1..n-1]

        if list1.inject(:*) < 0 && list2.inject(:*) > 0 && list3.include?(0)
          puts "#{list1.size} " + list1.join(' ')
          puts "#{list2.size} " + list2.join(' ')
          puts "#{list3.size} " + list3.join(' ')
          exit
        end
      end
    end

  end
end

a = A.new

class A
  def initialize
    list1 = []
    list2 = []
    list3 = []

    n = gets.chomp.to_i

    list = gets.chomp.split(' ').map(&:to_i)
    z_c = list.count(0)
    list.delete(0)
    list.sort!

    list += [0]*z_c

    0.upto(n-2) do |i|
      1.upto(n-1) do |j|
        list1 = list[0..i]
        list2 = list[i+1..j]
        list3 = list[j+1..n-1]

        if list1.inject(:*) < 0 && list2.inject(:*) > 0 && list3.include?(0)
          puts "#{list1.size} " + list1.join(' ')
          puts "#{list2.size} " + list2.join(' ')
          puts "#{list3.size} " + list3.join(' ')
          exit
        end
      end
    end

  end
end

a = A.new

class A
  def initialize
    list1 = []
    list2 = []
    list3 = []
    zero_list = []
    m_list = []
    p_list = []
    n = gets.chomp.to_i

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

    list.each do |num|
      if num < 0
        m_list << num
      elsif num > 0
        p_list << num
      else
        zero_list << num
      end
    end
    m_count = list.count{|n| n < 0}
    p_count = list.count{|n| n > 0}
    z_count = list.count{|n| n == 0}

    if m_count > 2
      if(m_count.odd?)
        list2 << m_list.pop
        list2 << m_list.pop
        list1 += m_list
      else
        list1 << m_list.pop
        list2 += m_list
      end
    else
      list1 << m_list.pop
    end

    list2 += p_list
    list3 += [0]*z_count + m_list

    puts "#{list1.size} " + list1.join(' ')
    puts "#{list2.size} " + list2.join(' ')
    puts "#{list3.size} " + list3.join(' ')
  end
end

a = A.new

class A
  def initialize
    list1 = []
    list2 = []
    list3 = []

    n = gets.chomp.to_i

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

    list.sort!

    0.upto(n-2) do |i|
      1.upto(n-1) do |j|
        list1 = list[0..i]
        list2 = list[i+1..j]
        list3 = list[j+1..n-1]

        if list1.inject(:*) < 0 && list2.inject(:*) > 0 && list3.include?(0)
          puts "#{list1.size} " + list1.join(' ')
          puts "#{list2.size} " + list2.join(' ')
          puts "#{list3.size} " + list3.join(' ')
          exit
        end
      end
    end

  end
end

a = A.new


The Smart Beaver from ABBYY loves puzzles. One of his favorite puzzles is the magic square. He has recently had an idea to automate the solution of this puzzle. The Beaver decided to offer this challenge to the ABBYY Cup contestants.The magic square is a matrix of size n × n. The elements of this matrix are integers. The sum of numbers in each row of the matrix is equal to some number s. The sum of numbers in each column of the matrix is also equal to s. In addition, the sum of the elements on the main diagonal is equal to s and the sum of elements on the secondary diagonal is equal to s. Examples of magic squares are given in the following figure:   Magic squares  You are given a set of n2 integers ai. It is required to place these numbers into a square matrix of size n × n so that they form a magic square. Note that each number must occur in the matrix exactly the same number of times as it occurs in the original set.It is guaranteed that a solution exists!

The first input line contains a single integer n. The next line contains n2 integers ai ( - 108 ≤ ai ≤ 108), separated by single spaces. The input limitations for getting 20 points are:    1 ≤ n ≤ 3  The input limitations for getting 50 points are:    1 ≤ n ≤ 4  It is guaranteed that there are no more than 9 distinct numbers among ai.  The input limitations for getting 100 points are:    1 ≤ n ≤ 4

The first line of the output should contain a single integer s. In each of the following n lines print n integers, separated by spaces and describing the resulting magic square. In the resulting magic square the sums in the rows, columns and diagonals must be equal to s. If there are multiple solutions, you are allowed to print any of them.

# f = File.open("test1", "r")

n = gets.to_i
nums = gets.split(" ").map(&:to_i)

if n == 1
    puts nums[0]
    puts nums[0]
    exit
end

if n == 2
    if nums[0] == nums[1] && nums[1] == nums[2] && nums[2] == nums[3]
        puts nums[1] * 2
        puts "#{nums[0]} #{nums[0]}\n#{nums[0]} #{nums[0]}"
    end
    exit
end

sum = nums.inject(:+)
lsum = sum / n

if n == 3
    tsum = lsum / 3
    9.times do |j|
        9.times do |i|
            9.times do |q|
                9.times do |w|
                    if nums[i] + nums[j] + tsum == lsum && nums[q] + nums[w] + tsum == lsum
                        t = lsum - nums[i] - nums[w]
                        y = lsum - nums[q] - nums[j]
                        e = lsum - nums[i] - nums[q]
                        r = lsum - nums[j] - nums[w]

                        if [nums[i], nums[j], nums[q], nums[w], t, y, e, r, tsum].uniq.size == nums.uniq.size
                            if nums.include?(t) && nums.include?(y) && nums.include?(e) && nums.include?(r)
                                puts lsum
                                puts "#{nums[i]} #{t} #{nums[w]}"
                                puts "#{e} #{tsum} #{r}"
                                puts "#{nums[q]} #{y} #{nums[j]}\n"
                                exit
                            end

                        end
                    end
                end
            end
        end
    end
    exit
end

if n == 4

    exit
end

# f = File.open("test1", "r")

n = gets.to_i
nums = gets.split(" ").map(&:to_i)

if n == 1
    puts nums[0]
    puts nums[0]
    exit
end

if n == 2
    if nums[0] == nums[1] && nums[1] == nums[2] && nums[2] == nums[3]
        puts nums[1] * 2
        puts "#{nums[0]} #{nums[0]}\n#{nums[0]} #{nums[0]}"
    end
    exit
end

sum = nums.inject(:+)
lsum = sum / n

if n == 3
    tsum = lsum / 3
    9.times do |j|
        9.times do |i|
            9.times do |q|
                9.times do |w|
                    if nums[i] + nums[j] + tsum == lsum && nums[q] + nums[w] + tsum == lsum
                        t = lsum - nums[i] - nums[w]
                        y = lsum - nums[q] - nums[j]
                        e = lsum - nums[i] - nums[q]
                        r = lsum - nums[j] - nums[w]

                        if [nums[i], nums[j], nums[q], nums[w], t, y, e, r].uniq.size == 8
                            if nums.include?(t) && nums.include?(y) && nums.include?(e) && nums.include?(r)
                                puts lsum
                                puts "#{nums[i]} #{t} #{nums[w]}"
                                puts "#{e} #{tsum} #{r}"
                                puts "#{nums[q]} #{y} #{nums[j]}\n"
                                exit
                            end

                        end
                    end
                end
            end
        end
    end
    exit
end

if n == 4

    exit
end

# f = File.open("test1", "r")

n = gets.to_i
nums = gets.split(" ").map(&:to_i)

if n == 1
    puts nums[0]
    puts nums[0]
    exit
end

if n == 2
    if nums[0] == nums[1] && nums[1] == nums[2] && nums[2] == nums[3]
        puts nums[1] * 2
        puts "#{nums[0]} #{nums[0]}\n#{nums[0]} #{nums[0]}"
    end
    exit
end

sum = nums.inject(:+)
lsum = sum / n

if n == 3
    tsum = lsum / 3
    9.times do |j|
        9.times do |i|
            9.times do |q|
                9.times do |w|
                    if nums[i] + nums[j] + tsum == lsum && nums[q] + nums[w] + tsum == lsum
                        t = lsum - nums[i] - nums[w]
                        y = lsum - nums[q] - nums[j]
                        e = lsum - nums[i] - nums[q]
                        r = lsum - nums[j] - nums[w]

                        if [nums[i], nums[j], nums[q], nums[w], t, y, e, r].uniq.size == 8
                            if nums.include?(t) && nums.include?(y) && nums.include?(e) && nums.include?(r)
                                puts lsum
                                puts "#{nums[i]} #{t} #{nums[w]}"
                                puts "#{e} #{tsum} #{r}"
                                puts "#{nums[q]} #{y} #{nums[j]}"
                                exit
                            end

                        end
                    end
                end
            end
        end
    end
    exit
end

if n == 4

    exit
end


Since Sonya is interested in robotics too, she decided to construct robots that will read and recognize numbers.Sonya has drawn $$$n$$$ numbers in a row, $$$a_i$$$ is located in the $$$i$$$-th position. She also has put a robot at each end of the row (to the left of the first number and to the right of the last number). Sonya will give a number to each robot (they can be either same or different) and run them. When a robot is running, it is moving toward to another robot, reading numbers in the row. When a robot is reading a number that is equal to the number that was given to that robot, it will turn off and stay in the same position.Sonya does not want robots to break, so she will give such numbers that robots will stop before they meet. That is, the girl wants them to stop at different positions so that the first robot is to the left of the second one.For example, if the numbers $$$[1, 5, 4, 1, 3]$$$ are written, and Sonya gives the number $$$1$$$ to the first robot and the number $$$4$$$ to the second one, the first robot will stop in the $$$1$$$-st position while the second one in the $$$3$$$-rd position. In that case, robots will not meet each other. As a result, robots will not be broken. But if Sonya gives the number $$$4$$$ to the first robot and the number $$$5$$$ to the second one, they will meet since the first robot will stop in the $$$3$$$-rd position while the second one is in the $$$2$$$-nd position.Sonya understands that it does not make sense to give a number that is not written in the row because a robot will not find this number and will meet the other robot.Sonya is now interested in finding the number of different pairs that she can give to robots so that they will not meet. In other words, she wants to know the number of pairs ($$$p$$$, $$$q$$$), where she will give $$$p$$$ to the first robot and $$$q$$$ to the second one. Pairs ($$$p_i$$$, $$$q_i$$$) and ($$$p_j$$$, $$$q_j$$$) are different if $$$p_i\neq p_j$$$ or $$$q_i\neq q_j$$$.Unfortunately, Sonya is busy fixing robots that broke after a failed launch. That is why she is asking you to find the number of pairs that she can give to robots so that they will not meet.

The first line contains a single integer $$$n$$$ ($$$1\leq n\leq 10^5$$$) — the number of numbers in a row. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1\leq a_i\leq 10^5$$$) — the numbers in a row.

Print one number — the number of possible pairs that Sonya can give to robots so that they will not meet.

require 'set'

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

# robot 2
n_rev = numbers.reverse
r2_seen = Set.new
n_seen = 0
seen_map = {}
seen_map[n] = 0
n_rev.each_with_index do |x2, i|
  if !r2_seen.include? x2
    r2_seen << x2
    n_seen += 1
  end
  seen_map[n - i - 1] = n_seen
end

# robot 1
count = 0
seen = Set.new
numbers.each_with_index do |x1, i|
  if !seen.include?(x1)
    count += seen_map[i + 1]
    seen << x1
  end
end

puts count

require 'set'

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

n = input[0]
a = input

s = Set.new
ns = 0
s_map = {}
s_map[n] = 0
a.reverse.each_with_index do |x, i|
	unless s.include?(x)
		s << x
		ns += 1
	end
	s_map[n-i-1] = ns
end

# p s_map
s = Set.new
ac = 0
a.each_with_index do |x, i|
	unless s.include?(x)
		s << x
		ac += s_map[i+1]
	end
end

print ac

N = gets.to_i
as = gets.split.map(&:to_i)

lhash = {}
rhash = Hash.new(0)

N.times do |i|
    rhash[as[i]] += 1
end
rsum = rhash.keys.length

ans = 0
N.times do |i|
    rhash[as[i]] -= 1
    rsum -= 1 if rhash[as[i]] == 0
    next if lhash[as[i]]
    lhash[as[i]] = true
    ans += rsum
end
puts ans

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

n = input[0]
a = input

store = {}
next_round = 0
ac = 0
a << -1 if a[-1] == a[-2]
a.each_with_index do |x, i|

	ac += next_round
	# puts "#{x}, #{next_round}, #{store[x]}"
	if store[x]
		next_round = -1 * store[x]
		store[x] = i
	else
		next_round = n - i - 1
		store[x] = i
	end
	# p ac
end

print ac

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

n = input[0]
a = input

store = {}
next_round = 0
ac = 0
a.each_with_index do |x, i|

	ac += next_round
	# puts "#{x}, #{next_round}, #{store[x]}"
	if store[x]
		next_round = -1 * store[x]
		store[x] = i
	else
		next_round = n - i - 1
		store[x] = i
	end
	# p ac
end

print ac


Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions:  Walk up or down one unit on a tree.  Eat a nut on the top of the current tree.  Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1 ≤ i ≤ n - 1), she jumps to height h of the tree i + 1. This action can't be performed if h > hi + 1. Compute the minimal time (in seconds) required to eat all nuts.

The first line contains an integer n (1  ≤  n ≤ 105) — the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1 ≤ hi ≤ 104) — the height of the tree with the number i.

Print a single integer — the minimal time required to eat all nuts in seconds.

def time_spent_on_tree(pre_height, height, nxt_height)
  (height - pre_height) + (height - nxt_height) + 1#cost of eating nuts
end

n = gets.to_i

tree_heights = [0]
n.times do
  tree_heights << gets.to_i
end

total_time = 0

(1 .. tree_heights.length - 2).each do |i|
  height = tree_heights[i]
  pre_height = [tree_heights[i - 1], height].min
  nxt_height = [height, tree_heights[i + 1]].min

  total_time += time_spent_on_tree pre_height, height, nxt_height
  total_time += 1 #cost of jumping between trees
end
last_tree_height = tree_heights[-1]
total_time += time_spent_on_tree tree_heights[-2 .. -1].min, last_tree_height, last_tree_height

puts total_time

n = gets.to_i
prev = gets.to_i
res = prev
for i in 0...n-1
	curr = gets.to_i
	res += (prev-curr).abs
	res += 2
	prev = curr
end
puts (res+1).to_s

t,ans=0,-1
gets.to_i.times do
	a=gets.to_i
	ans+=(a - t).abs+2
	t=a
end
puts ans

EAT = 1; JUMP = 1

def run
  n = ARGF.readline.to_i
  trees = ARGF.readlines.map(&:to_i)

  sec = 0
  height = 0
  cur_tree = 0

  trees.length.times do |i|
    if i > 0
      sec += JUMP

      diff = trees[i] - trees[i - 1]
      if diff < 0
        sec += -diff
        height = trees[i]
      end
    end

    sec += trees[i] - height + EAT
    height = trees[i]
  end

  puts sec
end

run if $0 == __FILE__

n,ac = gets.to_i,0
tot = 2*n-1
for i in (0...n)
    t = gets.to_i
    tot+=(t-ac).abs
    ac = t
end
puts tot

n=gets.to_i-1
l=r=gets.to_i
n.times{
    t=gets.to_i
    r+=(l-t).abs+2
    l=t
}
puts r+1

n=gets.to_i
h = []
n.times do |i|
	h[i] = gets.to_i
end

t = h[0] + n

(n-1).times do |i|
	if h[i+1] > h[i]
		t += h[i+1] - h[i] + 1
	else
		t += h[i] - h[i+1] + 1
	end
end

puts t

n = gets.chomp.to_i
h1,s = 0,n
for i in 0...n
    h2 = gets.chomp.to_i
    s+=(h2-h1).abs
    h1=h2
end
s+=n-1
puts s

n = gets.to_i
arr = []
n.times do
	arr << gets.to_i
end
time = arr[0]
prev_height = arr[0]
time += 1 # To eat
(1..n-1).each do |i|
	if arr[i] < prev_height
		#puts "He gets down to #{arr[i]}"#
		time += prev_height - arr[i]
		#puts "He jumps"
		time += 1
	else

		#puts "He jumps"
		time += 1 # Time to jump
		#puts "He Climbs to top in #{arr[i] - prev_height}"
		time += arr[i] - prev_height
	end
	#puts "He eats"
	time += 1

	#puts "Current time #{time}"
	prev_height = arr[i]
end

puts time

n = gets.chomp.to_i
a = 0
p = 0
(1..n).each { |k|
	b = gets.chomp.to_i
	p += (b-a).abs
	a = b
}

puts (p+2*n-1)

n=gets.to_i

sum=gets.to_i
last=sum

(n-1).times{
  t=gets.to_i
  sum+=2+(last-t).abs
  last=t
}

puts sum+1

#!/usr/bin/env ruby

n, x, tot = gets.to_i, [], 0
n.times { x << gets.to_i }
x.each_index { |i| tot = tot + (x[i] - x[i+1]).abs if i + 1 < n }
puts tot + n + n - 1 + x[0]

BEGIN{
	def gint()
		return gets.split.map(&:to_i)
	end
	def main()
		n = gint[0]
		a = []
		n.times do |i|
			a << gint[0]
		end
		ans = n + a[0]
		a.each_with_index do |item, i|
			break if i == a.length - 1
			if item > a[i + 1] then
				ans += item - a[i + 1] + 1
			elsif
				ans += 1 + a[i + 1] - item
			end
		end
		puts ans
	end
	Test_case = 1
	Test_case.times do
		main()
	end
}

n = gets.to_i
r = 0
h = 0

first = true

n.times do |i|
	if not first
		r += 1
	end
	first = false
	t = gets.to_i
	r += (t-h).abs + 1
	h = t
end

puts r

n = gets.to_i
arr = []
n.times do
	arr << gets.to_i
end
time = arr[0]
prev_height = arr[0]
time += 1 # To eat
(1..n-1).each do |i|
	if arr[i] < prev_height
		time += prev_height
		time += arr[i]
	else
		time += arr[i] - prev_height
		time += 1 # Time to jump
	end
	time += 1
	prev_height = arr[i]
end

puts time