Polycarp is very careful. He even types numeric sequences carefully, unlike his classmates. If he sees a sequence without a space after the comma, with two spaces in a row, or when something else does not look neat, he rushes to correct it. For example, number sequence written like "1,2 ,3,...,   10" will be corrected to "1, 2, 3, ..., 10".In this task you are given a string s, which is composed by a concatination of terms, each of which may be:   a positive integer of an arbitrary length (leading zeroes are not allowed),  a "comma" symbol (","),  a "space" symbol (" "),  "three dots" ("...", that is, exactly three points written one after another, also known as suspension points). Polycarp wants to add and remove spaces in the string s to ensure the following:   each comma is followed by exactly one space (if the comma is the last character in the string, this rule does not apply to it),  each "three dots" term is preceded by exactly one space (if the dots are at the beginning of the string, this rule does not apply to the term),  if two consecutive numbers were separated by spaces only (one or more), then exactly one of them should be left,  there should not be other spaces. Automate Polycarp's work and write a program that will process the given string s.

The input data contains a single string s. Its length is from 1 to 255 characters. The string s does not begin and end with a space. Its content matches the description given above.

Print the string s after it is processed. Your program's output should be exactly the same as the expected answer. It is permissible to end output line with a line-break character, and without it.

NUMBER_REGEX = /(\d+)/

tokens = gets.strip.gsub(',', ' , ').gsub('...', ' ... ').split

tokens.each_with_index do |token, index|
  if index.zero?
    print token
  else
    print ' ' if tokens[index - 1] == ',' or token == '...'
    print ' ' if tokens[index - 1] =~ NUMBER_REGEX and token =~ NUMBER_REGEX
    print token
  end
end

puts

line = gets.chomp
line.gsub!(/ *, */, ', ')
line.gsub!(/ *\.\.\. */, ' ...')
line.gsub!(/ +/, ' ')
line.strip!
puts line

input = STDIN.readline.gsub(',', ' , ').gsub('...', ' ... ').strip.split(' ').map do |s| s.strip end

spaceIns = true
ishead = true
isPrevNum = false
input.each do |s|
  print ' ' if !ishead && spaceIns
  ishead = false
  case s
  when ','
    print ','
    spaceIns = true
    isPrevNum = false
  when '...'
    print((spaceIns ? '' : ' ') + '...')
    spaceIns = false
    isPrevNum = false
  else
    print((isPrevNum ? ' ' : '') + s)
    spaceIns = false
    isPrevNum = true
  end
end
puts ''

class String
  def is_integer?
    self.to_i.to_s == self
  end
end

def parse(line)
  return line.scan(Regexp.union(/,/, /\.../, /\d*/)).map{ |t| t.strip }.select{ |t| t != '' }
end

def format(tokens)
  acc = ""
  tokens.each_with_index { |val, index|
    if val == ","
      acc << ", "
    elsif val == "..." and acc[-1, 1] == " "
      acc << val
    elsif val == "..."
      acc << " ..."
    elsif val.is_integer? and index > 0 and tokens[index - 1].is_integer?
      acc << " " << val
    else
      acc << val
    end
    }
  return acc.strip
end

def process_line(line)
  tokens = parse(line)
  return format(tokens)
end

input = STDIN.read
lines = input.chomp.split("\n")
lines.map! { |l| puts process_line(l) }

line = gets.chomp
line.gsub!(/, */, ', ')
line.gsub!(/ *\.\.\./, ' ...')
line.gsub!(/ +/, ' ')
line.strip!
puts line

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

s = gets
elems = s.split(/,/)
elems.map!{|x|
  xx = x.strip
  if xx != "..." && xx =~ /\.\.\./
    xx = xx.gsub(/\.\.\./, " ...")
  end
  xx
}
puts elems.join(', ')

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

s = gets
elems = s.split(/,/)
elems.map!{|x|
  xx = x.strip
  if xx != "..." && xx =~ /\.\.\./
    xx = xx.gsub(/\.\.\./, " ...").lstrip
  end
  xx
}
puts elems.join(', ').strip

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

s = gets
s.gsub!(/\s{1,}/, ' ')
elems = s.split(/,/)
elems.map!{|x|
  xx = x.strip
  if xx != "..." && xx =~ /\.\.\./
    xx = xx.gsub(/\.\.\./, " ...").lstrip
  end
  xx
}
puts elems.join(', ').strip

class String
  def is_integer?
    self.to_i.to_s == self
  end
end

def parse(line)
  return line.scan(Regexp.union(/,/, /\.../, /\d*/)).map{ |t| t.strip }.select{ |t| t != '' }
end

def format(tokens)
  acc = ""
  tokens.each_with_index { |val, index|
    if val == ","
      acc << ", "
    elsif val == "..." and acc[-1, 1] == " "
      acc << val
    elsif val == "..."
      acc << " ..."
    elsif val.is_integer? and index > 1 and tokens[index - 1].is_integer?
      acc << " " << val
    else
      acc << val
    end
    }
  return acc
end

def process_line(line)
  tokens = parse(line)
  return format(tokens)
end

input = STDIN.read
lines = input.chomp.split("\n")
lines.map! { |l| puts process_line(l) }

class String
  def is_integer?
    self.to_i.to_s == self
  end
end

def parse(line)
  return line.scan(Regexp.union(/,/, /\.../, /\d*/)).map{ |t| t.strip }.select{ |t| t != '' }
end

def format(tokens)
#  puts tokens
  acc = ""
  tokens.each_with_index { |val, index|
    if val == ","
      acc << ", "
    elsif val == "..." and acc[-1, 1] == " "
      acc << val
    elsif val == "..."
      acc << " ..."
    elsif val.is_integer? and index > 1 and tokens[index - 1].is_integer?
      acc << " " << val
    else
      acc << val
    end
    }
  puts acc
  return tokens.join("~")
end

def process_line(line)
  puts line
  tokens = parse(line)
  return format(tokens)
end

input = STDIN.read
lines = input.chomp.split("\n")
lines.map! { |l| puts process_line(l) }

class String
  def is_integer?
    self.to_i.to_s == self
  end
end

def parse(line)
  return line.scan(Regexp.union(/,/, /\.../, /\d*/)).map{ |t| t.strip }.select{ |t| t != '' }
end

def format(tokens)
  acc = ""
  tokens.each_with_index { |val, index|
    if val == ","
      acc << ", "
    elsif val == "..." and acc[-1, 1] == " "
      acc << val
    elsif val == "..."
      acc << " ..."
    elsif val.is_integer? and index > 1 and tokens[index - 1].is_integer?
      acc << " " << val
    else
      acc << val
    end
    }
  return acc.strip
end

def process_line(line)
  tokens = parse(line)
  return format(tokens)
end

input = STDIN.read
lines = input.chomp.split("\n")
lines.map! { |l| puts process_line(l) }


The Cereal Guy's friend Serial Guy likes to watch soap operas. An episode is about to start, and he hasn't washed his plate yet. But he decided to at least put in under the tap to be filled with water. The plate can be represented by a parallelepiped k × n × m, that is, it has k layers (the first layer is the upper one), each of which is a rectangle n × m with empty squares ('.') and obstacles ('#'). The water can only be present in the empty squares. The tap is positioned above the square (x, y) of the first layer, it is guaranteed that this square is empty. Every minute a cubical unit of water falls into the plate. Find out in how many minutes the Serial Guy should unglue himself from the soap opera and turn the water off for it not to overfill the plate. That is, you should find the moment of time when the plate is absolutely full and is going to be overfilled in the next moment.Note: the water fills all the area within reach (see sample 4). Water flows in each of the 6 directions, through faces of 1 × 1 × 1 cubes.

The first line contains three numbers k, n, m (1 ≤ k, n, m ≤ 10) which are the sizes of the plate. Then follow k rectangles consisting of n lines each containing m characters '.' or '#', which represents the "layers" of the plate in the order from the top to the bottom. The rectangles are separated by empty lines (see the samples). The last line contains x and y (1 ≤ x ≤ n, 1 ≤ y ≤ m) which are the tap's coordinates. x is the number of the line and y is the number of the column. Lines of each layer are numbered from left to right by the integers from 1 to n, columns of each layer are numbered from top to bottom by the integers from 1 to m.

The answer should contain a single number, showing in how many minutes the plate will be filled.

#!/usr/bin/env ruby

$k, $n, $m = gets.split.map(&:to_i)
$t = []

def fs(z, x, y)
  stack = [[z, x, y]]
  $t[z][x][y] = '#'
  #puts "dfs #{z} #{x} #{y}"
  result = 1
  while not stack.empty?
    z, x, y = stack.pop
    (-1..1).each do |i|
      (-1..1).each do |j|
        (-1..1).each do |k|
          if [i, j, k].select { |x| x == 0 }.count == 2
            nz, nx, ny = z + i, x + j, y + k
            #puts [i, j, k, nz, nx, ny] * " " + [0 <= nz, nz < t.size, 0 <= nx, nx < t[0].size, ny <= 0, ny < t[0][0].size] * " "
            if 0 <= nz && nz < $k && 0 <= nx && nx < $n && 0 <= ny && ny < $m
              #puts "ok"
              if $t[nz][nx][ny] == '.'
                $t[nz][nx][ny] = '#'
                stack.push([nz, nx, ny])
                result += 1
              end
            end
          end
        end
      end
    end
  end

  return result
end

$k.times do
  gets
  $t << []
  $n.times do
    $t[-1] << gets.chomp
  end
end
gets
x, y = gets.split.map(&:to_i)

#p t, x, y, t.size, t[0].size, t[0][0].size

puts fs(0, x - 1, y - 1)

K, N, M = gets.chomp.split.map{|e| e.to_i}

map = Array.new(K + 1) { Array.new(N + 1) {[]}}

1.upto(K) {|i|
  gets
  1.upto(N) {|j|
    map[i][j].push 0
    tmp = gets.chomp.split('').each {|e|
      map[i][j].push e
    }
  }
}

gets
X, Y = gets.chomp.split.map{|e| e.to_i}

def dfs(map, k, n, m)
  return 0 if (k < 1 || k > K || n < 1 || n > N || m < 1 || m > M)
  return 0 if (map[k][n][m] != ".")

  count = 1
  map[k][n][m] = "0"
  directions = [[0, 0, 1], [0, 0, -1], [0, 1, 0], [0, -1, 0], [1, 0, 0], [-1, 0, 0]]

  directions.each {|e|
    count += dfs(map, k + e[0], n + e[1], m + e[2])
  }

  return count
end

puts dfs(map, 1, X, Y)

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

data = []
k.times do
  gets
  o = []
  n.times do
    o << gets.chomp
  end
  data << o
end

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

lim = [k, n, m]
q = [[1, x, y]]
used = {}
n = 0
until q.empty?
  pos = q.shift

  next if used[pos]
  next if pos.min < 1 || pos.zip(lim).find{|a,b| a>b}
  next if data[pos[0]-1][pos[1]-1][pos[2]-1] != '.'

  used[pos] = true

  n += 1
  q << [pos[0], pos[1], pos[2]+1]
  q << [pos[0], pos[1], pos[2]-1]
  q << [pos[0], pos[1]+1, pos[2]]
  q << [pos[0], pos[1]-1, pos[2]]
  q << [pos[0]+1, pos[1], pos[2]]
  q << [pos[0]-1, pos[1], pos[2]]

end

p n


This problem is same as the previous one, but has larger constraints.Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.For each of the $$$n$$$ days since the day Shiro moved to the new house, there will be exactly one cat coming to the Shiro's house. The cat coming in the $$$i$$$-th day has a ribbon with color $$$u_i$$$. Shiro wants to know the largest number $$$x$$$, such that if we consider the streak of the first $$$x$$$ days, it is possible to remove exactly one day from this streak so that every ribbon color that has appeared among the remaining $$$x - 1$$$ will have the same number of occurrences.For example, consider the following sequence of $$$u_i$$$: $$$[2, 2, 1, 1, 5, 4, 4, 5]$$$. Then $$$x = 7$$$ makes a streak, since if we remove the leftmost $$$u_i = 5$$$, each ribbon color will appear exactly twice in the prefix of $$$x - 1$$$ days. Note that $$$x = 8$$$ doesn't form a streak, since you must remove exactly one day. Since Shiro is just a cat, she is not very good at counting and needs your help finding the longest streak.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the total number of days. The second line contains $$$n$$$ integers $$$u_1, u_2, \ldots, u_n$$$ ($$$1 \leq u_i \leq 10^5$$$) — the colors of the ribbons the cats wear.

Print a single integer $$$x$$$ — the largest possible streak of days.

NoteIn the first example, we can choose the longest streak of $$$13$$$ days, since upon removing the last day out of the streak, all of the remaining colors $$$1$$$, $$$2$$$, $$$3$$$, and $$$4$$$ will have the same number of occurrences of $$$3$$$. Note that the streak can also be $$$10$$$ days (by removing the $$$10$$$-th day from this streak) but we are interested in the longest streak.In the fourth example, if we take the streak of the first $$$6$$$ days, we can remove the third day from this streak then all of the remaining colors $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$ and $$$5$$$ will occur exactly once.

n = readline.to_i
u = readline.split.map(&:to_i)

C = 100000

cs = [0] * C
csr = {0 => n}
csr.default = 0
max_x = 1
(0...n).each do |i|
  ui = u[i] - 1
  c = cs[ui]
  csr[c] -= 1
  csr.delete(c) if csr[c] == 0
  c += 1
  cs[ui] = c
  csr[c] += 1
  if csr.length <= 3 then
    ks = csr.keys
    ks.delete_if { |x| x == 0 }
    if ks.length == 1 and (ks[0] == 1 or csr[ks[0]] == 1)
      max_x = i + 1
    elsif ks.length == 2
      ks = ks.sort
      if (ks[1] == ks[0] + 1 and csr[ks[1]] == 1) or (ks[0] == 1 and csr[ks[0]] == 1)
        max_x = i + 1
      end
    end
  end
end
p max_x

N = gets.to_i
arr = gets.split.map(&:to_i)
nums = Hash.new(0)
counts = Hash.new(0)
answer = 0
for k in 0...N
	x = arr[k]
	nums[x] += 1
	cnt = nums[x]
	if cnt == 1
		counts[1] += 1
	else
		counts[cnt-1] -= 1
		counts[cnt] += 1
	end
	counts.delete_if { |key, value| value == 0 }
#	STDERR.puts "#{nums}"
#	STDERR.puts "#{counts}"
#	STDERR.puts counts.size
	if counts.size == 1
		answer = k if counts.key?(1) or counts.value?(1)
	elsif counts.size == 2
		if counts.value?(1)
			answer = k if counts[1] == 1
			a, b = counts.keys
			if (a - b).abs == 1
				max = a > b ? a : b
				answer = k if counts[max] == 1
			end
		end
	end
end
puts answer + 1

N = gets.to_i
arr = gets.split.map(&:to_i)
nums = Hash.new(0)
counts = Hash.new(0)
answer = 0
for k in 0...N
	cnt = ( nums[ arr[k] ] += 1 )
	if cnt == 1
		counts[1] += 1
	else
		counts[cnt-1] -= 1
		counts.delete cnt-1 if counts[cnt-1] == 0
		counts[cnt] += 1
	end
#	STDERR.puts "#{nums}"
#	STDERR.puts "#{counts}"
#	STDERR.puts counts.size
	if counts.size == 1
		answer = k if counts.key?(1) or counts.value?(1)
	elsif counts.size == 2
		if counts.value?(1)
			if counts[1] == 1
				answer = k
			else
				a, b = counts.keys
				answer = k if (a - b).abs == 1 && counts[a > b ? a : b] == 1
			end
		end
	end
end
puts answer + 1

N = gets.to_i
arr = gets.split.map(&:to_i)
nums = Hash.new(0)
counts = Hash.new(0)
answer = 0
for k in 0...arr.size
	x = arr[k]
	nums[x] += 1
	cnt = nums[x]
	if cnt == 1
		counts[1] += 1
	else
		counts[cnt-1] -= 1
		counts[cnt] += 1
	end
	counts.delete_if { |key, value| value == 0 }
#	STDERR.puts "#{nums}"
#	STDERR.puts "#{counts}"
#	STDERR.puts counts.size
	if counts.size == 1
		answer = k if counts.key?(1) or counts.value?(1)
	elsif counts.size == 2
		if counts.value?(1)
			answer = k if counts[1] == 1
			a, b = counts.keys
			answer = k if (a - b).abs == 1
		end
	end
end
puts answer + 1

N = gets.to_i
arr = gets.split.map(&:to_i)
nums = Hash.new(0)
counts = Hash.new(0)
answer = 0
for k in 0...arr.size
	x = arr[k]
	nums[x] += 1
	cnt = nums[x]
	if cnt == 1
		counts[1] += 1
	else
		counts[cnt-1] -= 1
		counts[cnt] += 1
	end
	counts.delete_if { |key, value| value == 0 }
	STDERR.puts "#{nums}"
	STDERR.puts "#{counts}"
	STDERR.puts counts.size
	if counts.size == 1
		answer = k if counts.key?(1) or counts.value?(1)
	elsif counts.size == 2
		if counts.value?(1)
			a, b = counts.keys
			answer = k if (a - b).abs == 1
		end
	end
end
puts answer + 1

N = gets.to_i
arr = gets.split.map(&:to_i)
nums = Hash.new(0)
counts = Hash.new(0)
answer = 0
for k in 0...N
	cnt = ( nums[ arr[k] ] += 1 )
	if cnt == 1
		counts[1] += 1
	else
		counts[cnt-1] -= 1
		counts.delete cnt-1 if counts[cnt-1] == 0
		counts[cnt] += 1
	end
#	STDERR.puts "#{nums}"
#	STDERR.puts "#{counts}"
#	STDERR.puts counts.size
	if counts.size == 1
		answer = k if counts.key?(1) or counts.value?(1)
	elsif counts.size == 2
		if counts.value?(1)
			if counts[1] == 1
				answer = k
			else
				a, b = counts.keys
				answer = k if (a - b).abs == 1 || counts[a > b ? a : b] == 1
			end
		end
	end
end
puts answer + 1

N = gets.to_i
arr = gets.split.map(&:to_i)
nums = Hash.new(0)
counts = Hash.new(0)
answer = 0
for k in 0...arr.size
	x = arr[k]
	nums[x] += 1
	cnt = nums[x]
	if cnt == 1
		counts[1] += 1
	else
		counts[cnt-1] -= 1
		counts[cnt] += 1
	end
	counts.delete_if { |key, value| value == 0 }
	STDERR.puts "#{nums}"
	STDERR.puts "#{counts}"
	STDERR.puts counts.size
	if counts.size == 1
		answer = k if counts.key?(1) or counts.value?(1)
	elsif counts.size == 2
		if counts.value?(1)
			answer = k if counts.key?(1)
			a, b = counts.keys
			answer = k if (a - b).abs == 1
		end
	end
end
puts answer + 1

N = gets.to_i
arr = gets.split.map(&:to_i)
nums = Hash.new(0)
counts = Hash.new(0)
answer = 0
for k in 0...N
	x = arr[k]
	nums[x] += 1
	cnt = nums[x]
	if cnt == 1
		counts[1] += 1
	else
		counts[cnt-1] -= 1
		counts[cnt] += 1
	end
	counts.delete_if { |key, value| value == 0 }
#	STDERR.puts "#{nums}"
#	STDERR.puts "#{counts}"
#	STDERR.puts counts.size
	if counts.size == 1
		answer = k if counts.key?(1) or counts.value?(1)
	elsif counts.size == 2
		if counts.value?(1)
			answer = k if counts[1] == 1
			a, b = counts.keys
			a, b = b, a if counts[a] == 1
			answer = k if b - a == 1
		end
	end
end
puts answer + 1


You are given a string A. Find a string B, where B is a palindrome and A is a subsequence of B.A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, "cotst" is a subsequence of "contest".A palindrome is a string that reads the same forward or backward.The length of string B should be at most 104. It is guaranteed that there always exists such string.You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 104.

First line contains a string A (1 ≤ |A| ≤ 103) consisting of lowercase Latin letters, where |A| is a length of A.

Output single line containing B consisting of only lowercase Latin letters. You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 104. If there are many possible B, print any of them.

NoteIn the first example, "aba" is a subsequence of "aba" which is a palindrome.In the second example, "ab" is a subsequence of "aabaa" which is a palindrome.

a = gets.chomp
a.downcase!
puts a + a.reverse

def Pal(s)
  s == s.reverse
end

s = gets.chomp
puts Pal(s)? s : s + s[0..-2].reverse

s = gets.chomp
puts s + s.reverse[0..-1]

s=gets.chomp
print s
for i in (s.size-1).downto(0)
  print s[i]

end


Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number n. How many times can Gerald put a spell on it until the number becomes one-digit?

The first line contains the only integer n (0 ≤ n ≤ 10100000). It is guaranteed that n doesn't contain any leading zeroes.

Print the number of times a number can be replaced by the sum of its digits until it only contains one digit.

NoteIn the first sample the number already is one-digit — Herald can't cast a spell.The second test contains number 10. After one casting of a spell it becomes 1, and here the process is completed. Thus, Gerald can only cast the spell once.The third test contains number 991. As one casts a spell the following transformations take place: 991 → 19 → 10 → 1. After three transformations the number becomes one-digit.

n = gets.chomp
count = 0
while n.size > 1
  n = n.split(//).inject(0) {|sum, e| sum + e.to_i}.to_s
  count += 1
end
puts count

n = gets.chomp
count = 0
while n.size != 1
  m = 0;
  n.each_byte{|c|
    m += c-48
  }
  n = m.to_s
  count += 1
end
puts count

#!/usr/local/bin/ruby19
ans=0
n=gets.split[0]
while n.length>1
        m=0
        n.each_byte{|c|
                m+=c-48
        }
        ans+=1
        n=m.to_s
end
puts ans

s = gets.chomp
res = 0
while s.length > 1 && res+=1
	s = s.each_char.inject(0){ |sum, i| sum += i.to_i }.to_s
end
puts res

n = gets.chomp.split(//)
i = 0
if n.size == 1
  puts i
  exit
else
  while n.size != 1 do
    n = n.inject(0){ |sum,x| x.to_i + sum }.to_s.split(//)
    i += 1
  end
end
puts i

s = gets.chomp
q = 0
ans = 1
0.upto(s.length - 1).each do |i|
    q += s[i].to_i
end
while q >= 10 do
    nq = 0
    while q != 0 do
        nq += q % 10
        q /= 10
    end
    q = nq
    ans += 1
end

if s.length == 1 then ans = 0 end

print ans

#=================================
if ARGV.include?("ONLINE_JUDGE")
	$stdin = File.open(ARGV[0], "r")
	ARGV.delete("ONLINE_JUDGE")
end
#=================================

n=gets.strip

if n.length==1
		puts 0
		exit
end

step=1
loop{
	n=n.split(//).map(&:to_i).inject(:+).to_s

	if n.length==1
		puts step
		exit
	end

	step+=1
}

n = STDIN.read.gsub("\n", "")

steps = 0
while (n.size != 1) do
    digits = n.split("")
    n = digits.inject(0) { |result, digit| result + digit.to_i }.to_s
    steps += 1
end

puts steps

n = gets.chomp
cnt = 0
while(n.length != 1)
   res = 0
   for i in 0...n.length
      res += Integer(n[i])
   end
   n = String(res)
   cnt += 1
end
puts cnt

sn = gets.chop

#n = sn.to_i

count = 0

while (sn.length > 1)
  sum = 0
  (0..sn.length-1).each { |i|
    sum += sn[i].to_i
  }
  sn = sum.to_s
  #puts sn
  count += 1
end

puts count

def sum_of_digits
  n = gets.strip

  count = 0
  while n.length > 1
    sum = n.chars.map{|i| i.to_i}.inject(0){|sum, j| sum+j }
    n = sum.to_s
    count += 1
  end

  p count
end

sum_of_digits

s = gets.chomp
c = 0
while s.size != 1
	s = s.split(//).map(&:to_i).reduce(:+).to_s
	c += 1
end
puts c

s = gets.chomp.split("").collect{|i| i.to_i}
ans = 0
while s.size > 1
    ans += 1
    s = s.inject{|sum,i| sum+=i}.to_s.split("").collect{|i| i.to_i}
end
puts ans

n = gets.chomp
asr = 0
bool = true
while bool do
  if(n.to_i <=9 && n.to_i >= 0)
    bool = false
  else
    begin
      asr += 1
      n = n.to_s.split('').inject(0){ |result, elem| result.to_i + elem.to_i }
    end
  end
end
puts asr

n, i = gets.strip, 0

(print 0; exit) if n.length == 1

loop do
  n = n.split(//).map(&:to_i).inject { |sum, e| sum += e  }.to_s
  (print i + 1; exit) if n.length == 1
  i += 1
end

n = gets.chomp
res = 0
for i in 0...n.length
   res += Integer(n[i])
end
puts res

s = gets
c = 0
while s.size != 1
	s = s.split(//).map(&:to_i).reduce(:+).to_s
	c += 1
end
puts c

n = gets.chomp
asr = 0
bool = true
while bool do
  if(n.to_i <=9 && n.to_i >= 0)
    bool = false
  else
    begin
      asr += 1
      n = n.to_s.split('').inject(0){ |result, elem| result.to_i + elem.to_i }
      puts n
    end
  end
end
puts asr

a=gets
($.+=1;a=(a.sum-48*a.size).to_s)while a.size>1
p$.

n, i = gets.strip, 0

(print 0; exit) if n == "0"

loop do
  n = n.split(//).map(&:to_i).inject { |sum, e| sum += e  }.to_s
  (print i + 1; exit) if n.length == 1
  i += 1
end


As you know, Bob's brother lives in Flatland. In Flatland there are n cities, connected by n - 1 two-way roads. The cities are numbered from 1 to n. You can get from one city to another moving along the roads.The «Two Paths» company, where Bob's brother works, has won a tender to repair two paths in Flatland. A path is a sequence of different cities, connected sequentially by roads. The company is allowed to choose by itself the paths to repair. The only condition they have to meet is that the two paths shouldn't cross (i.e. shouldn't have common cities).It is known that the profit, the «Two Paths» company will get, equals the product of the lengths of the two paths. Let's consider the length of each road equals 1, and the length of a path equals the amount of roads in it. Find the maximum possible profit for the company.

The first line contains an integer n (2 ≤ n ≤ 200), where n is the amount of cities in the country. The following n - 1 lines contain the information about the roads. Each line contains a pair of numbers of the cities, connected by the road ai, bi (1 ≤ ai, bi ≤ n).

n = gets.to_i
e = Array.new(n)
e.map!{[]}
ee = []

def gao(e, p, q)
	l = 0
	t = [0, 0]
	e[p].each do |i|
		next if i == q
		ll, dd = gao(e, i, p)
		l = [l, ll].max
		t <<= dd + 1
	end
	t.sort!{|a, b| b <=> a}
	l = [l, t[0] + t[1]].max
	return [l, t[0]]
end

(n - 1).times do
	a, b = gets.split.map{|i| i.to_i - 1}
	e[a] <<= b
	e[b] <<= a
	ee <<= [a, b]
end
ans = 0
ee.each do |p|
	ans = [ans, gao(e, p[0], p[1])[0] * gao(e, p[1], p[0])[0]].max
end
p ans

def gao(e, p, q)
	l, t = 0, [0, 0]
	e[p].each do |i|
		next if i == q
		ll, dd = gao(e, i, p)
		l = [l, ll].max
		t <<= dd + 1
	end
	t.sort!{|a, b| b <=> a}
	return [[l, t[0] + t[1]].max, t[0]]
end

n = gets.to_i
e = Array.new(n).map{[]}
ee = []
(n - 1).times do
	a, b = gets.split.map{|i| i.to_i - 1}
	e[a] <<= b
	e[b] <<= a
	ee <<= [a, b]
end
p ee.map{|p| gao(e, p[0], p[1])[0] * gao(e, p[1], p[0])[0]}.max


Initially Ildar has an empty array. He performs $$$n$$$ steps. On each step he takes a subset of integers already added to the array and appends the mex of this subset to the array. The mex of an multiset of integers is the smallest non-negative integer not presented in the multiset. For example, the mex of the multiset $$$[0, 2, 3]$$$ is $$$1$$$, while the mex of the multiset $$$[1, 2, 1]$$$ is $$$0$$$.More formally, on the step $$$m$$$, when Ildar already has an array $$$a_1, a_2, \ldots, a_{m-1}$$$, he chooses some subset of indices $$$1 \leq i_1 < i_2 < \ldots < i_k < m$$$ (possibly, empty), where $$$0 \leq k < m$$$, and appends the $$$mex(a_{i_1}, a_{i_2}, \ldots a_{i_k})$$$ to the end of the array.After performing all the steps Ildar thinks that he might have made a mistake somewhere. He asks you to determine for a given array $$$a_1, a_2, \ldots, a_n$$$ the minimum step $$$t$$$ such that he has definitely made a mistake on at least one of the steps $$$1, 2, \ldots, t$$$, or determine that he could have obtained this array without mistakes.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$) — the number of steps Ildar made. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$) — the array Ildar obtained.

If Ildar could have chosen the subsets on each step in such a way that the resulting array is $$$a_1, a_2, \ldots, a_n$$$, print $$$-1$$$. Otherwise print a single integer $$$t$$$ — the smallest index of a step such that a mistake was made on at least one step among steps $$$1, 2, \ldots, t$$$.

NoteIn the first example it is possible that Ildar made no mistakes. Here is the process he could have followed.  $$$1$$$-st step. The initial array is empty. He can choose an empty subset and obtain $$$0$$$, because the mex of an empty set is $$$0$$$. Appending this value to the end he gets the array $$$[0]$$$.  $$$2$$$-nd step. The current array is $$$[0]$$$. He can choose a subset $$$[0]$$$ and obtain an integer $$$1$$$, because $$$mex(0) = 1$$$. Appending this value to the end he gets the array $$$[0,1]$$$.  $$$3$$$-rd step. The current array is $$$[0,1]$$$. He can choose a subset $$$[0,1]$$$ and obtain an integer $$$2$$$, because $$$mex(0,1) = 2$$$. Appending this value to the end he gets the array $$$[0,1,2]$$$.  $$$4$$$-th step. The current array is $$$[0,1,2]$$$. He can choose a subset $$$[0]$$$ and obtain an integer $$$1$$$, because $$$mex(0) = 1$$$. Appending this value to the end he gets the array $$$[0,1,2,1]$$$. Thus, he can get the array without mistakes, so the answer is $$$-1$$$.In the second example he has definitely made a mistake on the very first step, because he could not have obtained anything different from $$$0$$$.In the third example he could have obtained $$$[0, 1, 2]$$$ without mistakes, but $$$239$$$ is definitely wrong.

def solution
  _ = read_int
  as = read_ints

  current_max = -1

  for i in (0...as.size)
    a = as[i]
    if a > current_max + 1
      puts (i+1)
      return
    end
    current_max = [current_max, a].max
  end

  puts (-1)

end

def read_int
  gets.to_i
end

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

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']

class B
  def self.run(n, m)
    prev_max = nil

    m.each_with_index do |el, idx|

      if valid_mexes(prev_max).include?(el)
        prev_max ||= el
        prev_max = prev_max < el ? el : prev_max
      else
        return idx+1
      end

    end

    return -1
  end

  def self.valid_mexes(prev_max)
    if !prev_max
      return [0]
    else
      (0..prev_max+1)
    end
  end
end

a = gets.chomp.to_i
b = gets.chomp.split.map(&:to_i)
puts B.run(a, b)

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

k = 0
arr.each_with_index do |z,i|
  if z>k
    puts i+1
    exit
  elsif z==k
    k+=1
  end
end

puts -1

def solution
  _ = read_int
  as = read_ints

  for i in (0...as.size)
    a = as[i]
    if a > i
      puts (i+1)
      return
    end
  end

  puts (-1)

end

def read_int
  gets.to_i
end

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

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']


Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.

6

logic

codeforces

bca

aaaaaaaaaaa

adbaadabad

to

NoteIn the first test case, the required path corresponds to the picture:  In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.

$stdin.readline

while !$stdin.eof do
    bytes = $stdin.readline.chomp.bytes
    cost = (bytes.first - bytes.last).abs

    bytes_i = bytes.each_with_index.select{ |x, _|
        (bytes.first..bytes.last).include?(x) || (bytes.last..bytes.first).include?(x)
    }

    jumps = bytes_i[1..-2].sort_by{|x| x[0]}
    jumps.reverse! if bytes.first > bytes.last
    jumps = [bytes_i[0]] + jumps + [bytes_i[-1]]
    indexes = jumps.map{|x| x[1] + 1}

    puts [cost, indexes.size].join(" ")
    puts indexes.join(" ")
end


After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero.

The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102).

Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .

NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles.

hour, minute = gets.split.map(&:to_f)
hunger, dec, bunCost, inc = gets.split.map(&:to_f)
buyNow = hunger/inc*bunCost
buyLater = (hunger + dec*(1200 - ((hour%24)*60+minute)))/inc*(bunCost-(bunCost*0.2))
puts [buyLater,buyNow].min.round(4)

hour, minute = gets.split.map(&:to_i)
hunger, dec, bunCost, inc = gets.split.map(&:to_f)
buyNow = (hunger/inc).ceil*bunCost
buyLater = ((hunger + dec*(1200 - ((hour%24)*60+minute)))/inc).ceil * bunCost
buyLater -= buyLater*0.2
puts hour != 20 ? [buyLater,buyNow].min : buyNow-(buyNow*0.2)

hour, minute = gets.split.map(&:to_i)
hunger, dec, bunCost, inc = gets.split.map(&:to_f)
buyNow = (hunger/inc).ceil*bunCost
buyLater = ((hunger + dec*(1200 - ((hour%24.0)*60+minute)))/inc).ceil * bunCost
buyLater -= buyLater*0.2
puts [buyLater,buyNow].min


You are given a positive integer $$$n$$$ greater or equal to $$$2$$$. For every pair of integers $$$a$$$ and $$$b$$$ ($$$2 \le |a|, |b| \le n$$$), you can transform $$$a$$$ into $$$b$$$ if and only if there exists an integer $$$x$$$ such that $$$1 < |x|$$$ and ($$$a \cdot x = b$$$ or $$$b \cdot x = a$$$), where $$$|x|$$$ denotes the absolute value of $$$x$$$.After such a transformation, your score increases by $$$|x|$$$ points and you are not allowed to transform $$$a$$$ into $$$b$$$ nor $$$b$$$ into $$$a$$$ anymore.Initially, you have a score of $$$0$$$. You can start at any integer and transform it as many times as you like. What is the maximum score you can achieve?

A single line contains a single integer $$$n$$$ ($$$2 \le n \le 100\,000$$$) — the given integer described above.

Print an only integer — the maximum score that can be achieved with the transformations. If it is not possible to perform even a single transformation for all possible starting integers, print $$$0$$$.

NoteIn the first example, the transformations are $$$2 \rightarrow 4 \rightarrow (-2) \rightarrow (-4) \rightarrow 2$$$.In the third example, it is impossible to perform even a single transformation.

n=gets.to_i
ans=0
for i in 2..n do
    j=2*i
    until j>n do
        ans+=j/i
        j+=i
    end
end
p ans*4


There is a $$$n \times m$$$ grid. You are standing at cell $$$(1, 1)$$$ and your goal is to finish at cell $$$(n, m)$$$.You can move to the neighboring cells to the right or down. In other words, suppose you are standing at cell $$$(x, y)$$$. You can:   move right to the cell $$$(x, y + 1)$$$ — it costs $$$x$$$ burles;  move down to the cell $$$(x + 1, y)$$$ — it costs $$$y$$$ burles. Can you reach cell $$$(n, m)$$$ spending exactly $$$k$$$ burles?

The first line contains the single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first and only line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \le n, m \le 100$$$; $$$0 \le k \le 10^4$$$) — the sizes of grid and the exact amount of money you need to spend.

For each test case, if you can reach cell $$$(n, m)$$$ spending exactly $$$k$$$ burles, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

NoteIn the first test case, you are already in the final cell, so you spend $$$0$$$ burles.In the second, third and fourth test cases, there are two paths from $$$(1, 1)$$$ to $$$(2, 2)$$$: $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(1, 2)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ or $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$. Both costs $$$1 + 2 = 3$$$ burles, so it's the only amount of money you can spend.In the fifth test case, there is the only way from $$$(1, 1)$$$ to $$$(1, 4)$$$ and it costs $$$1 + 1 + 1 = 3$$$ burles.

t = gets.to_s.to_i

def solve(maxx, maxy, k, cache)
  return k == 0 if maxx == 1 && maxy == 1
  return false if k <= 0 || maxx < 1 || maxy < 1
  maxx, maxy = maxy, maxx if maxx < maxy
  return cache[maxx * 128 + maxy] if cache.has_key?(maxx * 128 + maxy)

  result = solve(maxx - 1, maxy, k - maxy, cache) || solve(maxx, maxy - 1, k - maxx, cache)
  cache[maxx * 128 + maxy] = result
  return result
end

1.upto(t) do |casenum|
  maxx, maxy, k = gets.to_s.split.map {|x| x.to_i }
  printf("%s\n", solve(maxx, maxy, k, {}) ? "YES" : "NO")
end

test_cases = gets.chomp.to_i
for i in 1..test_cases do
    line = gets.chomp.split(" ")
    n = line[0].to_i
    m = line[1].to_i
    k = line[2].to_i
    puts (n - 1) + n * (m - 1) == k ? "Yes" : "No"
end


There is a grid with $$$n$$$ rows and $$$m$$$ columns, and three types of cells:   An empty cell, denoted with '.'.  A stone, denoted with '*'.  An obstacle, denoted with the lowercase Latin letter 'o'. All stones fall down until they meet the floor (the bottom row), an obstacle, or other stone which is already immovable. (In other words, all the stones just fall down as long as they can fall.)Simulate the process. What does the resulting grid look like?

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 50$$$) — the number of rows and the number of columns in the grid, respectively. Then $$$n$$$ lines follow, each containing $$$m$$$ characters. Each of these characters is either '.', '*', or 'o' — an empty cell, a stone, or an obstacle, respectively.

For each test case, output a grid with $$$n$$$ rows and $$$m$$$ columns, showing the result of the process. You don't need to output a new line after each test, it is in the samples just for clarity.

gets.to_i.times do
  n, m = gets.split.map(&:to_i)
  xxs = n.times.map { gets.chomp.chars }
  (n - 2).downto(0).each do |i|
    0.upto(m - 1).each do |j|
      if xxs[i][j] == "*"
        i2 = i
        while i2 + 1 < n && xxs[i2 + 1][j] == "."
          xxs[i2][j] = "."
          i2 += 1
        end
        xxs[i2][j] = "*"
      end
    end
  end
  puts xxs.map(&:join).join("\n")
end


This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.

The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres.

In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.

NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each.

N = gets.to_i
A = gets.split.map(&:to_i).sort
res = Array.new(N, 0)

1.step(N - 1, 2) do |x|
  res[x] = A.shift
end

0.step(N - 1, 2) do |x|
  res[x] = A.shift
end

ans = 0

1.upto(N - 2) do |i|
  ans += 1 if res[i - 1] > res[i] && res[i] < res[i + 1]
end

puts ans
puts res.join(' ')


Permutation p is an ordered set of integers p1,  p2,  ...,  pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1,  p2,  ...,  pn.You have a sequence of integers a1, a2, ..., an. In one move, you are allowed to decrease or increase any number by one. Count the minimum number of moves, needed to build a permutation from this sequence.

The first line contains integer n (1 ≤ n ≤ 3·105) — the size of the sought permutation. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109).

Print a single number — the minimum number of moves. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample you should decrease the first number by one and then increase the second number by one. The resulting permutation is (2, 1).In the second sample you need 6 moves to build permutation (1, 3, 2).

n=gets.to_i
a=gets.split.map(&:to_i).sort
puts n.times.inject(0){|s, i| s+(a[i]-i-1).abs}

n = gets.to_i; a = gets.split.map &:to_i; a.sort!
res = 0; 0.upto(n-1){|i|res += (a[i] - i - 1).abs}
puts res

#!/usr/bin/ruby1.9

n = STDIN.readline.to_i
a = STDIN.readline.split.collect {|s| s.to_i }

b = []
a.each do |x|
	#b.push([(1-x).abs, x])
	b.push(x)
end
b.sort!

#puts b.inspect

sum = 0
n.times do |i|
	#sum += (i+1-b[i][1]).abs
	sum += (i+1-b[i]).abs
end

puts sum

n = gets.to_i
t = gets.split.map(&:to_i).sort
result = 0
t.each_with_index do |x, i|
  result += (i + 1 - x).abs
end
puts result

require 'set'
require 'rational'
require 'mathn'
include Math
$stdin = File.open("./input.txt", "r") if ENV["USER"] == "new"
# ====================================

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

changes = 0
set = Set.new
index = 1
perm.each{|value|
  changes+=(index - value).abs
  index+=1
}

print changes

require 'set'
require 'rational'
require 'mathn'
include Math
$stdin = File.open("./input.txt", "r") if ENV["USER"] == "new"
# ====================================

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

changes = 0
index = 1
perm.each{|value|
  changes+=(index - value).abs
  index+=1
}

print changes

n = gets.chomp.to_i
a = gets.chomp.split(" ").map{|i| i.to_i}

less = []
middle = []
greater = []

n.times do |i|
  if a[i] < 1
    less << a[i]
  elsif a[i] > n
    greater << a[i]
  else
    middle << a[i]
  end
end
less.sort!
greater.sort!
middle.sort!

l = less.length
g = greater.length

move = 0

original = (1..n).to_a
missing = original - middle
length_missing = missing.length

same = []
old_x = 0
middle.each do |x|
  if x != old_x
    old_x = x
  else
    same << x
  end
end

sum_less = 0
sum_missing = 0
l.times do |i|
  sum_missing += missing[i]
  sum_less += less[i]
end
move += sum_missing - sum_less

sum_greater = 0
sum_missing = 0
g.times do |i|
  sum_missing += missing[length_missing - i - 1]
  sum_greater += greater[i]
end
move += sum_greater - sum_missing

missing[l...(length_missing - g)].each_with_index do |x,i|
  move += (x - same[i]).abs
end

puts move

n = gets.to_i
vec = (gets.split.map &:to_i).sort
total = 0
for i in (0...n)
    total+=(i+1-vec[i]).abs
end
puts total

n=gets.to_i
a=gets.split.map(&:to_i).sort
a.unshift(0)
res=0
1.upto(n) {|x| res+=(x-a[x]).abs}
puts res

# coding: utf-8

n = gets.to_i
a = gets.split.map(&:to_i)
delta_sum = 0
for tup in (1..n).zip(a.sort)
    # p tup
    delta_sum += (tup[0] - tup[1]).abs
end

puts delta_sum

n = Integer(gets)
a = Array.new
input = gets.chomp
nums = input.split
for i in 0...n
    a[i] = Integer(nums[i])
end

a = a.sort
c = 0
for i in 0...n
    c += (i + 1 - a[i]).abs
end
puts c

n = gets.to_i
v = gets.split.map &:to_i
v = v.sort
moves=0
for i in 0...n
    moves+=((i+1)-v[i]).abs
end
puts moves

n = gets.to_i
a = [nil] +gets.split.map(&:to_i).sort
ans = 0
1.upto(n) do |i|
  ans += (i - a[i]).abs
end
p ans

n = gets.to_i;
a = gets.split.map(& :to_i);
cur = 0;
b = a.sort;
p (1..n).inject(0){|acc, x| acc + (x - b[x-1]).abs}
#p a.sort.inject {|acc, x| cur += 1; acc + (cur - x).abs}

n = Integer(gets.chomp)
a = gets.chomp.split.map { |x| x.to_i }.sort
count = 0
for i in 1..n
  count += (a[i - 1] - i).abs
end
puts count

n = gets.chomp.to_i
a = gets.chomp.split(" ").map{|i| i.to_i}
a.sort!
  i = n - 1
  move = 0
  while i >= 0 do
    move += (a[i] - i - 1).abs
    i -= 1
  end

puts move

#!/usr/bin/env ruby

gets
tot = 0
gets.split.collect{ |i| i.to_i }.sort.each_with_index { |x, i| tot += (i + 1 - x).abs }
puts tot

n, _ = gets.strip.split.map(&:to_i)
as = gets.strip.split.map(&:to_i).sort

result = 0
(1..n).each do |i|
  result += (as[i-1] - i).abs
end

puts result

n = gets.chomp.to_i
a = gets.chomp.split(" ").map{|i| i.to_i}

less = []
middle = []
greater = []

n.times do |i|
  if a[i] < 1
    less << a[i]
  elsif a[i] > n
    greater << a[i]
  else
    middle << a[i]
  end
end
less.sort!
greater.sort!

move = 0
(1..n).each do |i|
  unless middle.include?(i)
    if less.any?
      move += i - less.shift
    elsif greater.any?
      move += greater.shift - i
    end
  end
end

puts move

# coding: utf-8

n = gets.to_i
a = gets.split.map(&:to_i)
delta_sum = 0
for tup in (1..n).zip(a)
    delta_sum += (tup[0] - tup[1]).abs
end

puts delta_sum

n = gets.chomp.to_i
a = gets.chomp.split(" ").map{|i| i.to_i}
a.sort!
  i = n - 1
  move = 0
  while i > 0 do
    move +=(a[i] - i - 1).abs
    i -= 1
  end

puts move

n = gets.to_i
g = gets.split(' ')
a = []
index = []
index1 = []
s = 0
giam = 0

(0..n-1).each do |i|
  a[i] = g[i].to_i
end

(1..n+1).each do |i|
  index[i] = 0
  index1[i] = 0
end

(0..n-1).each do |i|
  s += a[i]
  if a[i] >= n
    a[i] = n
    giam = a[i] - n
    index[n] +=1
  else
    index[a[i]] +=1 if a[i] > 0
  end
end

index1[n+1] = 0
i = n
while i > 0
  index1[i] = index1[i+1] + index[i]
  giam += index1[i] - (n+1-i) if index1[i] > (n+1-i)
  i -= 1
end

t = (n+1)*n/2
s1 = (s-t).abs + 2*giam

puts s1

n = gets.to_i
g = gets.split(' ')
a = []
index = []
index1 = []
s = 0
giam = 0
s1 = 0

(0..n-1).each do |i|
  a[i] = g[i].to_i
end

(1..n+1).each do |i|
  index[i] = 0
  index1[i] = 0
end

(0..n-1).each do |i|
  if a[i] > n
    s1 += a[i] - n
    index[n] +=1
    a[i] = n
  else
    index[a[i]] +=1 if a[i] > 0
  end
  s += a[i]
end

index1[n+1] = 0
i = n
while i > 0
  index1[i] = index1[i+1] + index[i]
  giam += index1[i] - (n+1-i) if index1[i] > (n+1-i)
  i -= 1
end

t = (n+1)*n/2
s1 += (s-t).abs + 2*giam

puts s
puts s1

n = gets.to_i
g = gets.split(' ')
a = []
index = []
index1 = []
s = 0
giam = 0
s1 = 0

(0..n-1).each do |i|
  a[i] = g[i].to_i
end

(1..n+1).each do |i|
  index[i] = 0
  index1[i] = 0
end

(0..n-1).each do |i|
  if a[i] > n
    s1 += a[i] - n
    index[n] +=1
    a[i] = n
  else
    index[a[i]] +=1 if a[i] > 0
  end
  s += a[i]
end

index1[n+1] = 0
i = n
while i > 0
  index1[i] = index1[i+1] + index[i]
  giam += index1[i] - (n+1-i) if index1[i] > (n+1-i)
  i -= 1
end

t = (n+1)*n/2
s1 += (s-t).abs + 2*giam

puts s1

n = gets.to_i
g = gets.split(' ')
a = []
index = []
index1 = []
s = 0
giam = 0
s1 = 0

(0..n-1).each do |i|
  a[i] = g[i].to_i
end

(1..n+1).each do |i|
  index[i] = 0
  index1[i] = 0
end

(0..n-1).each do |i|
  if a[i] > n
    s1 += a[i] - n
    index[n] +=1
    a[i] = n
  else
    index[a[i]] +=1 if a[i] > 1
  end
  s += a[i]
end

index1[n+1] = 0
i = n
while i > 0
  index1[i] = index1[i+1] + index[i]
  giam += index1[i] - (n+1-i) if index1[i] > (n+1-i)
  i -= 1
end

t = (n+1)*n/2
s1 += (s-t).abs + 2*giam

puts s1


You are given a string $$$s$$$, consisting of brackets of two types: '(', ')', '[' and ']'.A string is called a regular bracket sequence (RBS) if it's of one of the following types:   empty string;  '(' + RBS + ')';  '[' + RBS + ']';  RBS + RBS. where plus is a concatenation of two strings.In one move you can choose a non-empty subsequence of the string $$$s$$$ (not necessarily consecutive) that is an RBS, remove it from the string and concatenate the remaining parts without changing the order.What is the maximum number of moves you can perform?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Each of the next $$$t$$$ lines contains a non-empty string, consisting only of characters '(', ')', '[' and ']'. The total length of the strings over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase print a single integer — the maximum number of moves you can perform on a given string $$$s$$$.

NoteIn the first example you can just erase the whole string.In the second example you can first erase the brackets on positions $$$1$$$ and $$$2$$$: "[]()", then "()" is left. After that you can erase it whole. You could erase the whole string from the beginning but you would get one move instead of two.In the third example you can first erase the brackets on positions $$$1$$$ and $$$3$$$: "([)]". They form an RBS "()". Then "[]" is left, so you can erase it whole.In the fourth example there is no subsequence that is an RBS, so you can't perform a move at all.In the fifth example you can erase the brackets on positions $$$2$$$ and $$$4$$$: ")[(]" and get ")(" as a result. You can erase nothing from it.

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

def main
  t = int
  t.times do
    p1 = 0
    p2 = 0
    count = 0
    string.each_char do |c|
      case c
      when ?(
        p1 += 1
      when ?)
        count += 1 if p1 > 0
        p1 -= 1 if p1 > 0
      when ?[
        p2 += 1
      when ?]
        count += 1 if p2 > 0
        p2 -= 1 if p2 > 0
      end
    end

    puts count
  end
end

def int; gets.to_i; end
def ints; gets.split.map &:to_i; end
def float; gets.to_f; end
def floats; gets.split.map &:to_f; end
def array(&convert); gets.split.map(&convert); end
def string; gets.chomp; end
def rep(n, &b); Array.new(n, &b); end
def yes; puts YESNO[0]; end
def no; puts YESNO[1]; end
def yesno t; t ? yes : no; end
def zip(xs, *yss); Enumerator.new { |y| xs.zip(*yss) { |a| y.yield(*a) } }; end
def sorted_uniq(xs); x = nil; xs.filter! { |y| c = x === y; x = y; !c }; end
def max(*xs); xs.max; end
def min(*xs); xs.min; end
def minmax(*xs); xs.minmax; 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); if DEBUG; STDERR.puts (block_given? ? yield(x) : x).inspect; end; 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

def div_ceil(x, y); (x + y - 1) / y; end
def gcd(*xs); xs.inject(0) { |y, x| y.gcd(x) }; end
def factorial(n, mod); (2..n).inject(1) { |f, x| f * x % mod }; end
def cumsum(xs); ys = [0]; xs.each { |x| ys << x + ys[-1] }; ys; end
def cumdiff(ys); xs = []; xs.inject { |x, y| xs << (d = y - x); d }; end
def cumfold(ys, range); r = range.end; r -= 1 if range.exclusive_end?; ys[r] - ys[range.begin-1]; end
def mod_inv(x, mod); x.pow(mod-2, mod); end
def mod_div(x, y, mod); x * mod_inv(y, mod) % mod; end
def bitbrute(size, &block); (1<<size).times(&block); end

class UnionFind
  def initialize(size); @p, @r = size.times.to_a, [1] * size; end
  def merge(i, j); k, l = leader(i), leader(j); return if k == l; k, l = l, k if @r[k] < @r[l]; @p[l] = k; @r[k] += @r[l]; end
  def size(i); @r[leader(i)]; end
  def same?(i, j); leader(i) == leader(j); end
  def leader(i); j = i; until i == @p[i]; j, i = i, @p[j] = @p[i]; end; i; end
end

main

t = gets.chomp.to_i
t.times do
    a = gets.chomp.split("")
    count = 0
    co = 0
    lo = 0
    a.each do |i|
        if i == "("
            co += 1
        elsif i == ")" && co >= 1
            co -= 1
            count += 1
        elsif i == "["
            lo += 1
        elsif i == "]" && lo >= 1
            lo -= 1
            count += 1
        end
    end
    puts count
end

def make_score(arr)
  score = 0
  ph_s = 0
  arr.each do |b|
    if b
      ph_s += 1
    else
      if ph_s.positive?
        score += 1
        ph_s -= 1
      end
    end
  end
  score
end

testcases = gets.to_i
testcases.times do
  str = gets.chars
  small = []
  large = []
  str.each do |c|
    case c
    when '('
      small << true
    when ')'
      small << false
    when '['
      large << true
    when ']'
      large << false
    end
  end
  p make_score(small) + make_score(large)
end

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

def main
  t = int
  t.times do
    p1 = 0
    p2 = 0
    count = 0
    string.each_char do |c|
      case c
      when ?(
        p1 += 1
      when ?)
        count += 1 if p1 > 0
        p1 -= 1
      when ?[
        p2 += 1
      when ?]
        count += 1 if p2 > 0
        p2 -= 1
      end
    end

    puts count
  end
end

def int; gets.to_i; end
def ints; gets.split.map &:to_i; end
def float; gets.to_f; end
def floats; gets.split.map &:to_f; end
def array(&convert); gets.split.map(&convert); end
def string; gets.chomp; end
def rep(n, &b); Array.new(n, &b); end
def yes; puts YESNO[0]; end
def no; puts YESNO[1]; end
def yesno t; t ? yes : no; end
def zip(xs, *yss); Enumerator.new { |y| xs.zip(*yss) { |a| y.yield(*a) } }; end
def sorted_uniq(xs); x = nil; xs.filter! { |y| c = x === y; x = y; !c }; end
def max(*xs); xs.max; end
def min(*xs); xs.min; end
def minmax(*xs); xs.minmax; 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); if DEBUG; STDERR.puts (block_given? ? yield(x) : x).inspect; end; 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

def div_ceil(x, y); (x + y - 1) / y; end
def gcd(*xs); xs.inject(0) { |y, x| y.gcd(x) }; end
def factorial(n, mod); (2..n).inject(1) { |f, x| f * x % mod }; end
def cumsum(xs); ys = [0]; xs.each { |x| ys << x + ys[-1] }; ys; end
def cumdiff(ys); xs = []; xs.inject { |x, y| xs << (d = y - x); d }; end
def cumfold(ys, range); r = range.end; r -= 1 if range.exclusive_end?; ys[r] - ys[range.begin-1]; end
def mod_inv(x, mod); x.pow(mod-2, mod); end
def mod_div(x, y, mod); x * mod_inv(y, mod) % mod; end
def bitbrute(size, &block); (1<<size).times(&block); end

class UnionFind
  def initialize(size); @p, @r = size.times.to_a, [1] * size; end
  def merge(i, j); k, l = leader(i), leader(j); return if k == l; k, l = l, k if @r[k] < @r[l]; @p[l] = k; @r[k] += @r[l]; end
  def size(i); @r[leader(i)]; end
  def same?(i, j); leader(i) == leader(j); end
  def leader(i); j = i; until i == @p[i]; j, i = i, @p[j] = @p[i]; end; i; end
end

main

t = gets.chomp.to_i
t.times do
  s = gets.chomp.split('')
  b1, b2 = 0, 0
  mx1, mx2 = 0, 0
  s.each do |el|
    b1 += 1 if el == '('
    b1 = [b1 - 1, 0].max if el == ')'
    b2 += 1 if el == '['
    b2 = [b2 - 1, 0].max if el == ']'
    mx1 = [mx1, b1].max
    mx2 = [mx2, b2].max
  end
  puts mx1 + mx2
end

t = gets.chomp.to_i
t.times do
  s = gets.chomp.split('')
  b1, b2 = 0, 0
  mx1, mx2 = 0, 0
  s.each do |el|
    b1 += 1 if el == '('
    b1 -= 1 if el == ')'
    b2 += 1 if el == '['
    b2 -= 1 if el == ']'
    mx1 = [mx1, b1].max
    mx2 = [mx2, b2].max
  end
  puts mx1 + mx2
end


Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties:  In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to zero.  When all elements of the array become equal to zero, the array explodes. Nastya is always busy, so she wants to explode the array as fast as possible. Compute the minimum time in which the array can be exploded.

The first line contains a single integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains n integers a1, a2, ..., an ( - 105 ≤ ai ≤ 105) — the elements of the array.

Print a single integer — the minimum number of seconds needed to make all elements of the array equal to zero.

NoteIn the first example you can add  - 1 to all non-zero elements in one second and make them equal to zero.In the second example you can add  - 2 on the first second, then the array becomes equal to [0, 0,  - 3]. On the second second you can add 3 to the third (the only non-zero) element.

n = gets.to_i

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

puts array.select { |a| a != 0 }.uniq.count

n = gets.strip.to_i
seq = gets.strip.split.map(&:to_i)
puts seq.select { |n| !n.zero? }.uniq.size

N = gets.to_i
as = gets.split.map(&:to_i)
hash = {}
as.each do |a|
    hash[a] = true if a != 0
end
puts hash.length

n = gets.strip.to_i
ary = gets.strip.split.map(&:to_i)
puts ary.uniq.select{|x| x!=0}.size

x = gets.chomp.to_i
stairways =  gets.strip.split.map(&:to_i)
res = 0
Frq = Hash.new(0)

for i in 0 ... x
  if stairways[i] != 0
    Frq[stairways[i]]+=1
  end
end
for i in 0 ... x
  Frq[stairways[i]]-=1
  res += 1 if Frq[stairways[i]] == 0
end
puts res

x = gets.chomp.to_i
stairways =  gets.strip.split.map(&:to_i)
res = 0
Frq = Hash.new(0)

for i in 0 ... x
  Frq[stairways[i]]+=1
end
for i in 0 ... x
  Frq[stairways[i]]-=1
  res += 1 if Frq[stairways[i]] == 0
end
puts res


Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second.The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse.Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight.

The first line of the input contains a single integer l (1 ≤ l ≤ 1 000) — the length of the corridor where the fight takes place. The second line contains integer p, the third line contains integer q (1 ≤ p, q ≤ 500) — the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively.

Print a single real number — the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 4.  Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if .

NoteIn the first sample the speeds of the impulses are equal, so both of their meetings occur exactly in the middle of the corridor.

l = gets.to_i
p = gets.to_i
q = gets.to_i

q = q.to_f
p = p.to_f
l = l.to_f

l = l * p / (p+q)

puts l

l, p, q, = $stdin.read.split.map &:to_f
puts l * p / (p + q)

# http://codeforces.com/contest/591/problem/A
# A. Wizards' Duel
l = gets.chomp.to_f
p = gets.chomp.to_f
q = gets.chomp.to_f

first = l / (p + q)
puts first * p

len = gets.chomp.to_f;
a = gets.chomp.to_f;
b = gets.chomp.to_f;
puts len*(a/(a+b));

a=gets.chomp.to_f
v=gets.chomp.to_i
b=gets.chomp.to_i
c=a/(v+b)
puts "#{v*c}"

l=gets.chomp.to_f
p=gets.chomp.to_f
q=gets.chomp.to_f

answer=l*p/(p+q)
puts answer

a=gets.to_f
b=gets.to_f
c=gets.to_f
puts a/(b+c)*b

l = gets.chomp.to_f
p = gets.chomp.to_f
q = gets.chomp.to_f

puts l * p / (p + q)

#!/usr/bin/env ruby

c, p, q = $stdin.read.split.map { |i| i.to_f }

$stderr.puts "c=#{c}, p=#{p}, q=#{q}"

puts c * p / (p + q)

l = gets.to_i
p = gets.to_i
q = gets.to_i

puts l * ( p * 1.0 / (p + q) )

l = gets.to_i
p = gets.to_i
q = gets.to_i
print l - l * 1.0 / (p + q) * q, "\n"

l, p, q = STDIN.read.split.map &:to_i
p p*l/(p + q + 0.0)

a = gets.chomp.to_f
b = gets.chomp.to_f
c = gets.chomp.to_f
print (a * b) / (c + b)

class Solver
	def main
		l = gets.to_i
		p = gets.to_i
		q = gets.to_i

		t = 1.0 * l / (p + q)
		dis = t * p

		puts dis
	end
end

Solver.new.main

a=gets.chomp.to_f
v=gets.chomp.to_i
b=gets.chomp.to_i
c=a/(v+b)
if v>b
puts "#{v*c}"
else
puts "#{b*c}"
end


$$$ \def\myred#1{\color{red}{\underline{\bf{#1}}}} \def\myblue#1{\color{blue}{\overline{\bf{#1}}}} $$$ $$$\def\RED{\myred{Red}} \def\BLUE{\myblue{Blue}}$$$You are given a sequence of $$$n$$$ non-negative integers $$$a_1, a_2, \ldots, a_n$$$. Initially, all the elements of the sequence are unpainted. You can paint each number $$$\RED$$$ or $$$\BLUE$$$ (but not both), or leave it unpainted. For a color $$$c$$$, $$$\text{Count}(c)$$$ is the number of elements in the sequence painted with that color and $$$\text{Sum}(c)$$$ is the sum of the elements in the sequence painted with that color.For example, if the given sequence is $$$[2, 8, 6, 3, 1]$$$ and it is painted this way: $$$[\myblue{2}, 8, \myred{6}, \myblue{3}, 1]$$$ (where $$$6$$$ is painted red, $$$2$$$ and $$$3$$$ are painted blue, $$$1$$$ and $$$8$$$ are unpainted) then $$$\text{Sum}(\RED)=6$$$, $$$\text{Sum}(\BLUE)=2+3=5$$$, $$$\text{Count}(\RED)=1$$$, and $$$\text{Count}(\BLUE)=2$$$.Determine if it is possible to paint the sequence so that $$$\text{Sum}(\RED) > \text{Sum}(\BLUE)$$$ and $$$\text{Count}(\RED) < \text{Count}(\BLUE)$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$3\le n\le 2\cdot 10^5$$$) — the length of the given sequence.  The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$0\le a_i\le 10^9$$$) — the given sequence. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each test case, print YES if it is possible to paint the given sequence satisfying the above requirements, and NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).

NoteIn the first test case, there is no possible way to paint the sequence. For example, if you paint the sequence this way: $$$[\myblue{1},\myblue{2},\myred{3}]$$$ (where $$$3$$$ is painted red, $$$1$$$ and $$$2$$$ are painted blue) then $$$\text{Count}(\RED)=1 < \text{Count}(\BLUE)=2$$$, but $$$\text{Sum}(\RED)=3 \ngtr \text{Sum}(\BLUE)=3$$$. So, this is not a possible way to paint the sequence.In the second test case, a possible way to paint the sequence is described in the statement. We can see that $$$\text{Sum}(\RED)=6 > \text{Sum}(\BLUE)=5$$$ and $$$\text{Count}(\RED)=1 < \text{Count}(\BLUE)=2$$$.In the third test case, there is no possible way to paint the sequence. For example, if you paint the sequence this way: $$$[\myred{3},\myred{5},\myblue{4}, \myblue{2}]$$$ (where $$$3$$$ and $$$5$$$ are painted red, $$$4$$$ and $$$2$$$ are painted blue) then $$$\text{Sum}(\RED) = 8 > \text{Sum}(\BLUE) = 6$$$ but $$$\text{Count}(\RED) = 2 \nless \text{Count}(\BLUE) = 2$$$. So, this is not a possible way to paint the sequence.In the fourth test case, it can be proven that there is no possible way to paint the sequence satisfying sum and count constraints.

gets.chomp.to_i.times do
    n = gets.chomp.to_i
    str = gets.chomp.split.map{|el| el.to_i}.sort

    smallSum = str[0]
    bigSum =0
    boolFound=false

    for i in 0..str.length-1
        smallSum +=str[i].to_i
        bigSum +=str[-i].to_i
        if(bigSum>smallSum)
            puts "YES"
            boolFound = true
        end
        break if(boolFound)
    end

    if(boolFound==false)
        puts "NO"
    end

end

t=gets.chomp.to_i

t.times do
    n = gets.chomp.to_i
    str = gets.chomp.split
    arr = str.sort_by{|el| el.to_i}
   # for i in 0..str.length-1
   #     arr[i]=str[i].to_i
   # end
    #arr =  str.sort

   # puts arr
    smallSum = arr[0].to_i
    bigSum =0
    boolFound=false
    for i in 0..str.length-1
        smallSum +=arr[i].to_i
        bigSum +=arr[-i].to_i

        #puts " smallSum = #{smallSum} bigSum = #{bigSum}"
        if(bigSum>smallSum)
            puts "YES"
            boolFound = true

        #    puts " if #{boolFound}"

        end
        break if(boolFound)
        #puts " breal if #{boolFound}"

    end
    if(boolFound==false)
        puts "NO"
    end
   # puts " breal if #{boolFound}"

end

t=gets.chomp.to_i

t.times do
    n = gets.chomp.to_i
    str = gets.chomp.split.sort
    smallSum = str[0].to_i
    bigSum =0
    boolFound=false
    for i in 0..str.length-1
        smallSum +=str[i].to_i
        bigSum +=str[-i].to_i
        if(bigSum>smallSum)
            puts "YES"
            boolFound = true
        end
        break if(boolFound)
    end
    if(boolFound==false)
        puts "NO"
    end
end


Little Dormi received a histogram with $$$n$$$ bars of height $$$a_1, a_2, \ldots, a_n$$$ for Christmas. However, the more he played with his new histogram, the more he realized its imperfections, so today he wanted to modify it to his liking.To modify the histogram, Little Dormi is able to perform the following operation an arbitrary number of times: Select an index $$$i$$$ ($$$1 \le i \le n$$$) where $$$a_i>0$$$, and assign $$$a_i := a_i-1$$$.Little Dormi defines the ugliness score of his histogram (after performing some number of operations) as the sum of the vertical length of its outline and the number of operations he performed on it. And to make the histogram as perfect as possible, he would like to minimize the ugliness score after modifying it with some number of operations.However, as his histogram is very large, Little Dormi is having trouble minimizing the ugliness score, so as Little Dormi's older brother, help him find the minimal ugliness.Consider the following example where the histogram has $$$4$$$ columns of heights $$$4,8,9,6$$$:  The blue region represents the histogram, and the red lines represent the vertical portion of the outline. Currently, the vertical length of the outline is $$$4+4+1+3+6 = 18$$$, so if Little Dormi does not modify the histogram at all, the ugliness would be $$$18$$$.However, Little Dormi can apply the operation once on column $$$2$$$ and twice on column $$$3$$$, resulting in a histogram with heights $$$4,7,7,6$$$:  Now, as the total vertical length of the outline (red lines) is $$$4+3+1+6=14$$$, the ugliness is $$$14+3=17$$$ dollars. It can be proven that this is optimal.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 4 \cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$4 \cdot 10^5$$$.

For each test case output one integer, the minimal ugliness Little Dormi can achieve with the histogram in that test case.

NoteExample $$$1$$$ is the example described in the statement.The initial histogram for example $$$2$$$ is given below:  The ugliness is currently $$$2+1+6+3+4=16$$$.By applying the operation once on column $$$1$$$, six times on column $$$3$$$, and three times on column $$$4$$$, we can end up with a histogram with heights $$$1,1,1,1,0,0$$$:  The vertical length of the outline is now $$$1+1=2$$$ and Little Dormi made $$$1+6+3=10$$$ operations, so the final ugliness is $$$2+10=12$$$, which can be proven to be optimal.

gets.to_i.times do
  gets
  as = [0] + gets.split.map(&:to_i) + [0]
  cost = 1.upto(as.size - 1).filter_map do |i|
    a, b, c = as[i - 1], as[i], as[i + 1]
    if a < b && c < b
      as[i] = [a, c].max
      (b - as[i]).abs
    end
  end.sum
  p cost + as.each_cons(2).map { |a, b| (a - b).abs }.sum
end


Mr. Scrooge, a very busy man, decided to count the time he wastes on all sorts of useless stuff to evaluate the lost profit. He has already counted the time he wastes sleeping and eating. And now Mr. Scrooge wants to count the time he has wasted signing papers.Mr. Scrooge's signature can be represented as a polyline A1A2... An. Scrooge signs like that: first it places a pen at the point A1, then draws a segment from point A1 to point A2, then he draws a segment from point A2 to point A3 and so on to point An, where he stops signing and takes the pen off the paper. At that the resulting line can intersect with itself and partially repeat itself but Scrooge pays no attention to it and never changes his signing style. As Scrooge makes the signature, he never takes the pen off the paper and his writing speed is constant — 50 millimeters per second.Scrooge signed exactly k papers throughout his life and all those signatures look the same.Find the total time Scrooge wasted signing the papers.

The first line contains two integers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ 1000). Each of the following n lines contains the coordinates of the polyline's endpoints. The i-th one contains coordinates of the point Ai — integers xi and yi, separated by a space. All points Ai are different. The absolute value of all coordinates does not exceed 20. The coordinates are measured in millimeters.

Print one real number — the total time Scrooges wastes on signing the papers in seconds. The absolute or relative error should not exceed 10 - 6.

str = STDIN.gets.chomp.split(' ')
n = str[0].to_i
k = str[1].to_i
x = Array.new
y = Array.new
n.times do |i|
    str = STDIN.gets.chomp.split(' ')
    x[i] = str[0].to_f
    y[i] = str[1].to_f
end

dist = 0.0
1.upto(x.length - 1).each do |i|
    dist += (((x[i - 1] - x[i]) ** 2) + ((y[i - 1] - y[i]) ** 2)) ** 0.5
end
puts "%.9f" %[((dist * k) / 50).to_f]

n, k = gets.split.map &:to_i
p = n.times.map { |_| gets.split.map(&:to_i) }
p n.times.inject() { |s, i|
  a, b = p[i], p[i-1]
  s += Math.hypot(a[0]-b[0], a[1]-b[1])
} * k / 50

n, k = gets.split.map &:to_i
pt = STDIN.each.to_a
s = 0.upto(pt.length - 1).inject do |s, i|
  a = pt[i].split.map(&:to_i)
  b = pt[i - 1].split.map(&:to_i)
  s += Math.hypot(a[0] - b[0], a[1] - b[1])
end
p s * k / 50

n,k=gets.split.map(&:to_i)
point=[]
for i in 1..n
        point.push(gets.split.map(&:to_i))
end
res=0.0
for i in 1..n-1
        res+=Math::sqrt((point[i-1][0]-point[i][0])**2+(point[i-1][1]-point[i][1])**2)
end
p res/50*k

#!/usr/bin/env ruby

n, k = ($stdin.readline).split().collect { |x| x.to_i }

points = ($stdin.readlines).collect {|s| s.split().collect {|x| x.to_i} }

speed = 50

def dist(a, b)
	return Math.sqrt((a[0] - b[0])**2 + (a[1] - b[1])**2)
end

sum = 0.0

(n-1).times { |i|
	sum += dist(points[i], points[i+1])
	}

puts sum/speed*k

n,k = gets.split.map(&:to_i)
arr = (1..n).map{|e| gets.split.map(&:to_i)}
before = arr[0]
p arr.map{|e| ret = Math::sqrt((before[0] - e[0]) ** 2 + (before[1] - e[1]) ** 2); before = e ; ret}.reduce(:+) / 50 * k

n, k = gets.strip.split.map {|x| x.to_i}
def dis x1, y1, x2, y2
  Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2))
end
sum = 0.0
bef = gets.strip.split.map {|x| x.to_i}
n.pred.times do
  cur = gets.strip.split.map {|x| x.to_i}
  sum += dis *bef, *cur
  bef = cur
end
puts sum * k / 50.0

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

dots=[]
n.times{dots << gets.split.map(&:to_f)}

dist=0
for i in 0...(n-1)
	dist+=Math.sqrt((dots[i][0] - dots[i+1][0])**2 + (dots[i][1] - dots[i+1][1])**2)
end

printf "%.7f", (dist/50.0)*k

n,k = gets.split()
n = n.to_i
k = k.to_i
x = Array.new(n)
y = Array.new(n)
for i in 0...n do
  xx,yy = gets.split()
  x[i] = xx.to_f
  y[i] = yy.to_f
end
dist = 0.0
for i in 1...n do
  xd = x[i] - x[i-1]
  yd = y[i] - y[i-1]
  d = xd*xd + yd*yd;
  dist += (d ** 0.5);
end
  print dist / 50.0 * k, "\n";

input = gets.chomp
nums = input.split
n = Integer(nums[0])
k = Integer(nums[1])
coordinate = Array.new
for i in 0...n
	coordinate[i] = Array.new
	input2 = gets.chomp
	nums2 = input2.split
	for j in 0...2
		coordinate[i][j] = Integer(nums2[j])
	end
end
count = 0

for i in 0...n-1
	c = (coordinate[i][0] - coordinate[i+1][0]) ** 2 + (coordinate[i][1] - coordinate[i+1][1])** 2
	c = ((c** (0.5)) / 50) * k
	count += c
end

puts count = format("%.9f",count)

n,k = gets.split.map &:to_i
x2 = y2 = sum = 0
for i in (1..n)
  x1, y1 = gets.split.map &:to_i
  if i > 1
    sum +=Math.hypot(x2-x1,y2-y1)
  end
  x2, y2 = x1,y1
end
puts (sum*k)/50

n, k = gets.split(" ").map do |s| s.to_i end

px, py = gets.split(" ").map do |s| s.to_i end

time = 0
(n-1).times do
    x, y = gets.split(" ").map do |s| s.to_i end
    time += Math.sqrt((x-px)**2 + (y-py)**2) / 50
    px, py = x, y
end

puts time*k

def next_line
  gets.chomp.split.map { |x| x.to_i }
end

n, k = next_line
d = 0
p = next_line
for _ in 1...n
  c = next_line
  d += Math.sqrt((c[0] - p[0]).abs ** 2 + (c[1] - p[1]).abs ** 2)
  p = c
end
puts d.to_f * k / 50

def size(a1, a2)

  return Math.sqrt((a1[0] - a2[0])*(a1[0] - a2[0]) +
      (a1[1] - a2[1])*(a1[1] - a2[1]))
end

Speed = 50

n, k = gets().split.map { |elem| elem.to_i}

if n == 0
  puts 0
  return
end

a_i = gets().split.map { |elem| elem.to_i}
length = 0

for i in 2..n
  a = gets().split.map { |elem| elem.to_i}
  length += size(a_i, a)
  a_i = a
end

puts length / Speed * k

n, k = gets.split.map(&:to_i)
ans, x, y = 0, 0, 0
n.times{ |i|
 u, v = gets.split.map(&:to_i)
 ans+=Math.hypot(u-x,v-y) if i > 0
 x, y = u, v
}
printf("%.9f\n",ans*k/50)

def meh
  meh = gets.split.map(&:to_i)
  n = meh[0]
  k = meh[1]
  total = 0

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

  for i in 1..(n - 1) do
    current = gets.split.map(&:to_i)
    distance = Math.sqrt((current[0] - meh[0]) * (current[0] - meh[0]) + (current[1] - meh[1]) * (current[1] - meh[1]))

    total += distance
    meh = current
  end

  puts (total/50.0) * k
end

meh

n, k = gets.split.map &:to_i
points = STDIN.read.split("\n").map { |e| e.split.map! &:to_i }
distance = 0

(points.length - 1).times { |i| distance += Math.sqrt((points[i][0] - points[i + 1][0]) ** 2 + (points[i][1] - points[i + 1][1]) ** 2) }

print "%.9f" % (distance * k / 50.0)

#!/usr/bin/env ruby

n, k = ($stdin.readline).split().collect { |x| x.to_i }

points = ($stdin.readlines).collect {|s| s.split().collect {|x| x.to_i} }

speed = 50

def dist(a, b)
	return Math.sqrt((a[0] - b[0])**2 + (a[1] - b[1])**2)
end

sum = 0.0

(n-1).times { |i|
	sum += dist(points[i], points[i+1])
	puts "#{i} - #{sum}"
	}

puts sum/speed*k

require 'scanf'
input = scanf("%d %d")
n = input[0]
k = input[1]
x = Array.new(n)
y = Array.new(n)
for i in 0...n do
  input = scanf("%d %d")
  x[i] = input[0]
  y[i] = input[1]
end
dist = 0.0
for i in 1...n do
  xd = x[i] - x[i-1]
  yd = y[i] - y[i-1]
  dist += Math.sqrt(xd * xd + yd * yd);
end
print dist * k / 50.0, "\n";

require 'scanf'
input = scanf("%d %d")
n = input[0]
k = input[1]
x = Array.new(n)
y = Array.new(n)
for i in 0...n do
  input = scanf("%f %f")
  x[i] = input[0]
  y[i] = input[1]
end
dist = 0.0
for i in 1...n do
#  d = 1.0 + x[i]
  d = (x[i] - x[i-1]) * (x[i] - x[i-1]) + (y[i] - y[i-1]) * (y[i] - y[i-1])
  dist += Math.sqrt(d);
end
print dist * k / 50.0, "\n";

require 'scanf'
input = scanf("%d %d")
n = input[0]
k = input[1]
x = Array.new(n)
y = Array.new(n)
for i in 0...n do
  input = scanf("%d %d")
  x[i] = input[0]
  y[i] = input[1]
end
dist = 0.0
for i in 1...n do
  xd = x[i] - x[i-1]
  yd = y[i] - y[i-1]
  dist += Math.sqrt(xd * xd + yd * yd);
end
  print dist / 50.0 * k, "\n";

require 'scanf'
input = scanf("%d %d")
n = input[0]
k = input[1]
x = Array.new(n)
y = Array.new
for i in 0...n do
  input = scanf("%d %d")
  x[i] = input[0]
  y[i] = input[1]
end
dist = 0.0
for i in 1...n do
  xd = x[i] - x[i-1]
  yd = y[i] - y[i-1]
  d = xd*xd + yd*yd;
  dist += (d ** 0.5);
end
  print dist / 50.0 * k, "\n";

require 'scanf'
input = scanf("%d %d")
n = input[0]
k = input[1]
x = Array.new(n)
y = Array.new
for i in 0...n do
  input = scanf("%d %d")
  x[i] = input[0]
  y[i] = input[1]
end
dist = 0.0
for i in 1...n do
  xd = x[i] - x[i-1]
  yd = y[i] - y[i-1]
  dist += Math.sqrt(xd * xd + yd * yd);
end
  print dist / 50.0 , "\n";