After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards.Rules of this game are simple: each player bring his favourite n-digit credit card. Then both players name the digits written on their cards one by one. If two digits are not equal, then the player, whose digit is smaller gets a flick (knock in the forehead usually made with a forefinger) from the other player. For example, if n = 3, Sherlock's card is 123 and Moriarty's card has number 321, first Sherlock names 1 and Moriarty names 3 so Sherlock gets a flick. Then they both digit 2 so no one gets a flick. Finally, Sherlock names 3, while Moriarty names 1 and gets a flick.Of course, Sherlock will play honestly naming digits one by one in the order they are given, while Moriary, as a true villain, plans to cheat. He is going to name his digits in some other order (however, he is not going to change the overall number of occurences of each digit). For example, in case above Moriarty could name 1, 2, 3 and get no flicks at all, or he can name 2, 3 and 1 to give Sherlock two flicks.Your goal is to find out the minimum possible number of flicks Moriarty will get (no one likes flicks) and the maximum possible number of flicks Sherlock can get from Moriarty. Note, that these two goals are different and the optimal result may be obtained by using different strategies.

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of digits in the cards Sherlock and Moriarty are going to use. The second line contains n digits — Sherlock's credit card number. The third line contains n digits — Moriarty's credit card number.

First print the minimum possible number of flicks Moriarty will get. Then print the maximum possible number of flicks that Sherlock can get from Moriarty.

NoteFirst sample is elaborated in the problem statement. In the second sample, there is no way Moriarty can avoid getting two flicks.

n=gets.to_i
a,b=$<.map{|e|e.chomp.bytes.sort}
j=0
p n-b.count{|e|e>=a[j]&&j+=1}
j=0
p b.count{|e|e>a[j]&&j+=1}

#!/usr/bin/ruby
n=gets.to_i
a,b=$<.map{|e|e.split.map(&:to_i).sort}
j=0
p n-b.count{|e|e>=a[j]&&j+=1}
j=0
p b.count{|e|e>a[j]&&j+=1}


It's a very unfortunate day for Volodya today. He got bad mark in algebra and was therefore forced to do some work in the kitchen, namely to cook borscht (traditional Russian soup). This should also improve his algebra skills.According to the borscht recipe it consists of n ingredients that have to be mixed in proportion  litres (thus, there should be a1 ·x, ..., an ·x litres of corresponding ingredients mixed for some non-negative x). In the kitchen Volodya found out that he has b1, ..., bn litres of these ingredients at his disposal correspondingly. In order to correct his algebra mistakes he ought to cook as much soup as possible in a V litres volume pan (which means the amount of soup cooked can be between 0 and V litres). What is the volume of borscht Volodya will cook ultimately?

The first line of the input contains two space-separated integers n and V (1 ≤ n ≤ 20, 1 ≤ V ≤ 10000). The next line contains n space-separated integers ai (1 ≤ ai ≤ 100). Finally, the last line contains n space-separated integers bi (0 ≤ bi ≤ 100).

Your program should output just one real number — the volume of soup that Volodya will cook. Your answer must have a relative or absolute error less than 10 - 4.

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

class Array
  def sum
    self.inject { |r, v| r + v }
  end
end

n, volume = gets.split.map { |v| v.to_f }
a = gets.split.map { |v| v.to_f }
b = gets.split.map { |v| v.to_f }

multiplier = min(volume / a.sum, b.zip(a).map { |f, s| f / s }.min)

puts multiplier * a.sum

sum , i= 0,0
arr = gets.split(' ').map { |x| x.to_i }
n,v = arr[0],arr[1]
res = v
a = gets.split(' ').map { |x| x.to_i }
for c in a
  sum += c
end
b = gets.split(' ').map { |x| x.to_i }
for s in b
  if res > 1.00*s*sum/a[i] then
    res = 1.00*s*sum/a[i]
  end
  i += 1
end
puts res


On one quiet day all of sudden Mister B decided to draw angle a on his field. Aliens have already visited his field and left many different geometric figures on it. One of the figures is regular convex n-gon (regular convex polygon with n sides).That's why Mister B decided to use this polygon. Now Mister B must find three distinct vertices v1, v2, v3 such that the angle  (where v2 is the vertex of the angle, and v1 and v3 lie on its sides) is as close as possible to a. In other words, the value  should be minimum possible.If there are many optimal solutions, Mister B should be satisfied with any of them.

First and only line contains two space-separated integers n and a (3 ≤ n ≤ 105, 1 ≤ a ≤ 180) — the number of vertices in the polygon and the needed angle, in degrees.

Print three space-separated integers: the vertices v1, v2, v3, which form . If there are multiple optimal solutions, print any of them. The vertices are numbered from 1 to n in clockwise order.

NoteIn first sample test vertices of regular triangle can create only angle of 60 degrees, that's why every possible angle is correct.Vertices of square can create 45 or 90 degrees angles only. That's why in second sample test the angle of 45 degrees was chosen, since |45 - 67| < |90 - 67|. Other correct answers are: "3 1 2", "3 2 4", "4 2 3", "4 3 1", "1 3 4", "1 4 2", "2 4 1", "4 1 3", "3 1 4", "3 4 2", "2 4 3", "2 3 1", "1 3 2", "1 2 4", "4 2 1".In third sample test, on the contrary, the angle of 90 degrees was chosen, since |90 - 68| < |45 - 68|. Other correct answers are: "2 1 4", "3 2 1", "1 2 3", "4 3 2", "2 3 4", "1 4 3", "3 4 1".

n, a=gets.split.map &:to_i
x=180.0*(n-2)/n
minD=(x-a).abs
minX=2
(3...n).each do |i|
    b=(180.0*(i-2)-x*(i-2))/2
    d=(b-a).abs
    if d<minD
        minD=d
        minX=n+2-i
    end
end
puts "1 #{minX} #{minX+1}"

n,k=gets.split(" ").map(&:to_i)
ans=0
mn=180.1
(3..n).each{|i|
	tmp=(180.0/n*(i-2)-k).abs
	if tmp<mn
		mn=tmp
		ans=i
	end
}
puts "2 1 #{ans}"


You are given a positive integer $$$n$$$. You have to find $$$4$$$ positive integers $$$a, b, c, d$$$ such that  $$$a + b + c + d = n$$$, and $$$\gcd(a, b) = \operatorname{lcm}(c, d)$$$.If there are several possible answers you can output any of them. It is possible to show that the answer always exists.In this problem $$$\gcd(a, b)$$$ denotes the greatest common divisor of $$$a$$$ and $$$b$$$, and $$$\operatorname{lcm}(c, d)$$$ denotes the least common multiple of $$$c$$$ and $$$d$$$.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Description of the test cases follows. Each test case contains a single line with integer $$$n$$$ ($$$4 \le n \le 10^9$$$) — the sum of $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$.

For each test case output $$$4$$$ positive integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ such that $$$a + b + c + d = n$$$ and $$$\gcd(a, b) = \operatorname{lcm}(c, d)$$$.

gets.to_i.times do
  n = gets.to_i
  puts "#{n - 3} 1 1 1"
end

gets.to_i.times do
  n = gets.to_i
  a, b, c, d = case n % 4
    when 0 then [n / 4] * 4
    when 1, 3 then [n - 5, 2, 2, 1]
    when 2 then [n - 6, 2, 2, 2]
    end
  puts "#{a} #{b} #{c} #{d}"
end


The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:  Operation ++ increases the value of variable x by 1.  Operation -- decreases the value of variable x by 1. A statement in language Bit++ is a sequence, consisting of exactly one operation and one variable x. The statement is written without spaces, that is, it can only contain characters "+", "-", "X". Executing a statement means applying the operation it contains.A programme in Bit++ is a sequence of statements, each of them needs to be executed. Executing a programme means executing all the statements it contains.You're given a programme in language Bit++. The initial value of x is 0. Execute the programme and find its final value (the value of the variable when this programme is executed).

The first line contains a single integer n (1 ≤ n ≤ 150) — the number of statements in the programme. Next n lines contain a statement each. Each statement contains exactly one operation (++ or --) and exactly one variable x (denoted as letter «X»). Thus, there are no empty statements. The operation and the variable can be written in any order.

Print a single integer — the final value of x.

n = gets.chomp.to_i
x = 0
n.times do
	s = gets.chomp
	if s.include?("+")
		x += 1
	else
		x -= 1
	end
end
puts x

x=gets.to_i
z=0
v=0
while z<x
c=gets.chomp
if c=="++X" || c=="X++"
    v+=1
else v-=1
end
z+=1
end
puts v

number = gets.strip.to_i

x = 0
number.times do
  input = gets.strip
  if input.downcase == '++x' || input.downcase == 'x++'
    x += 1
  else
    x -= 1
  end
end

puts x

x = gets.to_i
i = 0

for j in 1..x do
	y = gets.chomp
	if y[1] == "+"
		i = i+1
	else
		i = i-1
	end
end
puts i

x=0
gets.to_i.times{
	s=gets.chomp
	x=x+(" ++X++".index(s)?1:-1)
}
puts x

a=gets.chomp.to_i
x=0
a.times do
b=gets.chomp
if b[0]=="+" || b[2] == "+"
x+=1
else
x-=1
end
end

puts "#{x}"

ret = 0
gets.to_i.times do
    if (gets =~ /-/) then ret -= 1 else ret += 1 end
end
puts ret

n, x = gets.to_i, 0
n.times {
  a = gets
  if ((a.count '+') > 0)
    x += 1
  else
    x -= 1
  end
}
puts x

def answers ()
  n = gets.to_i
  count = 0
  for i in 0...n
    ope = gets.chomp
    if ope.include? "+"
      count +=1
    else
      count -=1
    end
  end
  puts count
end

answers

a = gets.chomp.to_i
x = 0
while a>0
    a-=1
    if gets.chomp[1]=='+'
        x+=1
    else
        x-=1
    end
end
print x

x = 0
n = gets.chomp.to_i
i = 0
if n >= 1 && n <= 150
	while i < n
		statement = gets.chomp
		if statement == "++X" || statement == "++x" || statement == "x++" || statement == "X++"
			x += 1
		elsif statement == "--X" || statement == "--x" || statement == "x--" || statement == "X--"
			x -= 1
		end
		i += 1
	end
end

puts x

n=gets.chomp.to_i
x=0
n.times{
    s=gets.chomp.to_s
    if s.scan(/\+\+/) { |match|
        x+=1
    }
    end
    if s.scan(/--/) { |match|
        x-=1
    }
    end
}
puts (x)

n=Integer(gets.chomp)
x=0
until n==0
    if gets.chomp.index('+')!=nil
        x = 1 + x
    else
        x = x - 1
    end
    n -= 1
end
puts x

n = gets.chomp.to_i
ans = 0
n.times{
  line = gets.chomp
  ans += 1 if line.include? "+"
  ans -= 1 if line.include? "-"
}
puts ans

r = 0

gets.to_i.times do
  if gets[1] == '+'
    r += 1
  else
    r -= 1
  end
end

puts r

n = gets.to_i
puts n.times.map{gets['++'] ? +1 : -1}.inject(:+)

x=0
gets.to_i.times{
	if gets.include?("++")
		x+=1
	else
		x-=1
	end
}
puts x

x = 0
gets.chomp.to_i.times do
	s = gets.chomp
	if s =~ /(\+\+(x|X)|(x|X)\+\+)/
		x += 1
	else
		x -= 1
	end
end
puts x

n = gets.to_i
value = 0
n.times do |_|
    statement = gets
    statement.include?('++') ? value += 1 : value -= 1
end
puts value

n = gets.to_i
sum = 0

(1..n).each do |i|
  s = gets.chomp
  if s[1] == '+'
    sum += 1
  else
    sum -= 1
  end
end

puts sum

n = gets.to_i
o=0

for i in 1..n
  gets.chomp[1] == '+' ? o+=1 : o-=1
end

p o

input = ARGV ? $< : File(ARGV[0])

n = gets.to_i

count = 0
for i in input.each_line.take n
	if i[0] == '+' || i[-2] == '+'
		count += 1
	else
		count -= 1
	end
end

puts count

x=0
gets.to_i.times{
	s=gets.chomp
	x=x+(" ++X++".index(s)?1:-1)
}
puts x

n = gets.chomp.to_i
c = 0
n.times do
    str = gets
    if str.include? "+"
        c += 1
    else
        c -= 1
    end
end
puts c

n = gets.chomp.to_i

x = 0
1.upto(n) do |i|
    instruction = gets.chomp
    instruction.each_char do |char|
        if char == "+"
            x += 1
            break
        elsif char == "-"
            x -= 1
            break
        end
    end
end
puts x

total = 0
n = gets.to_i.times {
	gets[1] == '+' ? (total += 1):(total -=1)
}
puts total

x = 0
n = gets.chomp.to_i
n.times do
	value = gets.chomp
	x = x + 1 if value.scan("+").count == 2 unless value.scan("X").count == 0
	x = x - 1 if value.scan("-").count == 2 unless value.scan("X").count == 0
end
puts(x)

$stdin = File.open("./input.txt", "r") if ENV["USER"] == "new"
# ====================================

x=0
n = gets.to_i

n.times{
  cmd = gets.strip

  x+=1 if cmd.include? "+"
  x-=1 if cmd.include? "-"
}

puts x

n=gets.chomp.to_i
y=0
while n>0
b=gets.chomp

if(b=="++X" or b=="X++")
y+=1
end
if(b=="--X" or b=="X--")
y=y-1
end
n=n-1
end
print y

x = 0

gets.strip.to_i.times do
  statement = gets.strip
  x += 1 if statement.include?('++')
  x -= 1 if statement.include?('--')
end

puts x

ans = 0
gets.to_i.times do |i|
     if gets.include?("++")
         ans += 1
     else
         ans -= 1
     end
end
puts ans

require 'scanf'

n = $stdin.readline.to_i
x = 0

n.times do |i|
  line = $stdin.readline
  line = line.chomp('').downcase
  line = line[0, 3]
  if line == "++x" || line == "x++"
    x += 1
  elsif line == "--x" || line == "x--"
    x -= 1
  end
end

puts x

n = gets.to_i
ans = 0
n.times.map{gets}.map{|x| x.include?('++') ? ans += 1 : ans -= 1}
puts ans

n = gets.to_i
X = 0

n.times do

pokemon = gets.to_s

pokemon.delete! ("X")

b = pokemon.scan(/[+]/).length

if b >= 1
X += 1

else
X -= 1

end

end

p X

operations = []
gets.to_i.times { operations << gets }
puts operations.inject(0) { |x, operation| operation.include?("++") ? x + 1 : x - 1}

stateNum = gets.chomp.to_i
value = 0

for i in 0...stateNum
	statement = gets.chomp

	value += 1 if statement.include?('+')
	value -= 1 if statement.include?('-')
end

puts value

r = 0

gets.to_i.times do
  if gets[1] == '+'
    r += 1
  else
    r -= 1
  end
end

puts r

n = gets.chomp
n = n.to_i

res = 0

n.times do
  cmd = gets.chomp
  res += 1 if cmd == "++X" or cmd == "X++"
  res -= 1 if cmd == "--X" or cmd == "X--"
end

puts res

x = 0
gets.to_i.times {
  x += gets.include?("+") ? 1 : -1
}
puts x

ret = 0
gets.to_i.times do
    if (gets =~ /-/) then ret -= 1 else ret += 1 end
end
puts ret

x=0
gets.to_i.times{
	s=gets.chomp
	x=x+(" ++X++".index(s)?1:-1)
}
puts x

x = 0
i = gets.to_i

while i > 0 do
    if gets.index('--') != nil
        x = x - 1
    else
        x = x + 1
    end
    i = i - 1
end

print x

n = gets.to_i
nilai = 0
for i in 1..n
	kata = gets.chomp
	myarray =kata.split("")
	if (myarray[0] == "+" && myarray[1] == "+") || (myarray[1] == "+" && myarray[2] == "+")
		nilai += 1
	else
		nilai -= 1
	end
end

puts nilai

p gets.to_i.times.map{gets=~/\+/?1: -1}.inject &:+

n = gets.chomp.to_i

ans = 0
n.times {

  s = gets.chomp

  if s[1] == '+'
    ans += 1
  else
    ans -= 1
  end
}

puts ans

x = 0

#input
counter = gets.chomp.to_i
listing = []

while counter != 0
	s = gets.chomp
	if s.include?("++")
		x += 1
	elsif s.include?("--")
		x -= 1
	end

	counter -= 1
end

puts x

n = gets.to_i

x = 0
n.times do
  if gets.count('+') != 0
    x += 1
  else
    x -= 1
  end
end

puts x

result = 0
gets.chomp.to_i.times do
  case gets.chomp.gsub(/X/, '')
    when '++' then result += 1
    when '--' then result -= 1
  end
end
puts result

n = gets.to_i
s = Array.new(n)

counters,xounterz = 0,0
for i in 0..n-1
 s[i] = gets.to_s
  if s[i].include? "+"
       counters+=1
   else
       xounterz+=1
   end
end
puts counters-xounterz

n = gets.to_i
puts n.times.map{gets['++'] ? +1 : -1}.inject(:+)

x = 0
gets.to_i.times {
  x += gets.include?("+") ? 1 : -1
}
puts x

r = 0

gets.to_i.times do
  if gets[1] == '+'
    r += 1
  else
    r -= 1
  end
end

puts r

s = gets.split(" ")
n = s[0].to_i
rez = 0
for i in 1..n
  s = gets
  if(s[1] == "-")
    rez -= 1
  end
    if(s[1] == "+")
    rez += 1
  end
end
puts(rez)

n = gets.to_i
o=0

for i in 1..n
  gets.chomp[1] == '+' ? o+=1 : o-=1
end

p o

ret = 0
gets.to_i.times do
    if (gets =~ /-/) then ret -= 1 else ret += 1 end
end
puts ret

n = gets.to_i
x = 0

1.upto(n) do
  line = gets

  case
    when line =~ /\+\+/
      x += 1
    when line =~ /--/
      x -= 1
  end
end

puts x

n = gets.to_i
x = 0
for i in 0...n
  operation = gets.chomp.to_s
  case operation
    when "++X","X++"
      x+=1
    when "--X","X--"
      x-=1
  end
end
puts x

ans = 0
gets.to_i.times do |i|
     if gets.include?("++")
         ans += 1
     else
         ans -= 1
     end
end
puts ans

n =  gets.strip.to_i
arr = []
last = ""

n.times do |i|
 x = gets.strip.to_s
 x.include?("+") ? arr << 1 : arr << -1
 last = x if (n - i == 1)
end

puts  arr.reduce(0){|init,ele| init + ele}

n = Integer(gets)
operation = Array.new
for i in 0...n
    operation[i] = Array.new
    input = gets.chomp
    operation[i] = input
end
x = 0
for i in 0...n
    if operation[i] == "++X" || operation[i] =="X++"
        x += 1
    else
        x -= 1
    end
end
puts x

n = gets.strip.to_i
x = 0
var = "X"
n.times do
  str = gets.strip
  if str == "++#{var}" || str == "#{var}++" then
    x += 1
  elsif str == "--#{var}" || str == "#{var}--" then
    x -= 1
  end
end
puts x

value = gets.chomp

operation = []
value.to_i.times do |i|
	value = gets.chomp
	operation << value
end
 x = 0
operation.each do |line|
	if line.include?('++')
		x += 1
	elsif line.include?('--')
			x -= 1
	end

end

puts x

p gets.to_i.times.map{gets=~/\+/?1: -1}.inject &:+

n = gets.to_i
rt = n
n.times do
  rt-=2 if gets=~/-/
end
puts rt

result = 0
gets.chomp.to_i.times do
  case gets.chomp
    when 'X++' then result += 1
    when '--X' then result -= 1
  end
end
puts result

k=gets.to_i
l=[]
k.times{l << gets.chomp}
print l.count("++X")-l.count("--X")

x = 0
gets.chomp.to_i.times do
	s = gets.chomp
	if s =~ /(\+\+x|x\+\+)/
		x += 1
	else
		x -= 1
	end
end
puts x

n = gets.to_i
x = 0
n.times do
  if gets.chomp == "x++"
    x += 1
  else
    x -= 1
  end
end

puts x

sum = 0
gets.to_i.times{
  if gets[1]=="+"
    sum+=1
  else
    sum-=1
  end
}
sum

n =  gets.strip.to_i
arr = []
last = ""

n.times do |i|
 x = gets.strip.to_s
 x.include?("+") ? arr << 1 : arr << -1
 last = x if (n - i == 1)
end

if last[0] != "+" and  last[0] != "-"
  arr[arr.length  - 1]  =  0
end

puts  arr.reduce(0){|init,ele| init + ele}

i = gets.to_i
counter = 0
(1..i).each do |x|
  counter += gets.chomp === 'X++' ? 1 : -1
end
print counter

input_line_num = gets.chomp.to_i
n = 0
res = 0
while input_line_num > n
  input_peration = gets.chomp
  case input_peration.include?("+")
  when true
      res +=1
  when false
      if res < 0
        res = 0
      end
        res -=1
  end
  n +=1
end
p res

num = gets.chomp.to_i
lines = []
i = 0
x = 0
while (i < num)
	lines[i] = gets.chomp
	i = i + 1
end
j = 0
while (j < lines.length)
	if(lines[j] == "++x" || lines[j] == "x++")
		x = x +1
	else
	x = x -1
	end
	j = j +1
end
puts x.to_s

number = gets.strip.to_i

x = 0
number.times do
  input = gets.strip
  if input == '++x'
    x += 1
  else
    x -= 1
  end
end

puts x


You have a card deck of $$$n$$$ cards, numbered from top to bottom, i. e. the top card has index $$$1$$$ and bottom card — index $$$n$$$. Each card has its color: the $$$i$$$-th card has color $$$a_i$$$.You should process $$$q$$$ queries. The $$$j$$$-th query is described by integer $$$t_j$$$. For each query you should:   find the highest card in the deck with color $$$t_j$$$, i. e. the card with minimum index;  print the position of the card you found;  take the card and place it on top of the deck.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 3 \cdot 10^5$$$; $$$1 \le q \le 3 \cdot 10^5$$$) — the number of cards in the deck and the number of queries. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 50$$$) — the colors of cards. The third line contains $$$q$$$ integers $$$t_1, t_2, \dots, t_q$$$ ($$$1 \le t_j \le 50$$$) — the query colors. It's guaranteed that queries ask only colors that are present in the deck.

Print $$$q$$$ integers — the answers for each query.

NoteDescription of the sample:   the deck is $$$[2, 1, 1, 4, \underline{3}, 3, 1]$$$ and the first card with color $$$t_1 = 3$$$ has position $$$5$$$;  the deck is $$$[3, \underline{2}, 1, 1, 4, 3, 1]$$$ and the first card with color $$$t_2 = 2$$$ has position $$$2$$$;  the deck is $$$[2, 3, \underline{1}, 1, 4, 3, 1]$$$ and the first card with color $$$t_3 = 1$$$ has position $$$3$$$;  the deck is $$$[\underline{1}, 2, 3, 1, 4, 3, 1]$$$ and the first card with color $$$t_4 = 1$$$ has position $$$1$$$;  the deck is $$$[1, 2, 3, 1, \underline{4}, 3, 1]$$$ and the first card with color $$$t_5 = 4$$$ has position $$$5$$$.

n, q = gets.to_s.split.map {|x| x.to_i }
a = gets.to_s.split.map {|x| x.to_i }
t = gets.to_s.split.map {|x| x.to_i }

pos = [a.size] * 51

a.each.with_index {|color, idx| pos[color] = [idx + 1, pos[color]].min }

t.each do |color|
   idx = pos[color]
   printf("%d ", pos[color])
   pos.map! {|x| ((x < idx) ? x + 1 : x) }
   pos[color] = 1
end
printf("\n")


Scientists say a lot about the problems of global warming and cooling of the Earth. Indeed, such natural phenomena strongly influence all life on our planet.Our hero Vasya is quite concerned about the problems. He decided to try a little experiment and observe how outside daily temperature changes. He hung out a thermometer on the balcony every morning and recorded the temperature. He had been measuring the temperature for the last n days. Thus, he got a sequence of numbers t1, t2, ..., tn, where the i-th number is the temperature on the i-th day.Vasya analyzed the temperature statistics in other cities, and came to the conclusion that the city has no environmental problems, if first the temperature outside is negative for some non-zero number of days, and then the temperature is positive for some non-zero number of days. More formally, there must be a positive integer k (1 ≤ k ≤ n - 1) such that t1 < 0, t2 < 0, ..., tk < 0 and tk + 1 > 0, tk + 2 > 0, ..., tn > 0. In particular, the temperature should never be zero. If this condition is not met, Vasya decides that his city has environmental problems, and gets upset.You do not want to upset Vasya. Therefore, you want to select multiple values of temperature and modify them to satisfy Vasya's condition. You need to know what the least number of temperature values needs to be changed for that.

The first line contains a single integer n (2 ≤ n ≤ 105) — the number of days for which Vasya has been measuring the temperature.  The second line contains a sequence of n integers t1, t2, ..., tn (|ti| ≤ 109) — the sequence of temperature values. Numbers ti are separated by single spaces.

Print a single integer — the answer to the given task.

NoteNote to the first sample: there are two ways to change exactly one number so that the sequence met Vasya's condition. You can either replace the first number 1 by any negative number or replace the number -2 by any positive number.

# https://codeforces.com/problemset/problem/234/C

n = 0
arr = []

File.open("input.txt", "r") do |f|
 n = f.gets.to_i - 2
 arr = f.gets.split(' ').map(&:to_i)
end

s = (arr[0] >= 0 ? 1 : 0) + (arr[-1] <= 0 ? 1 : 0)

File.open("output.txt", "w") do |f|
 if n > 0
  arr = arr[1...-1]

  temp = Array.new(n, 0)

  correct_count = 0
  n.times do |i|
   correct_count += 1 if arr[i] < 0
   temp[i] += correct_count
  end

  correct_count = 0
  (n-1).downto(0) do |i|
   correct_count += 1 if arr[i] > 0
   temp[i] += correct_count
  end

  f.write("#{s + n - temp.max}\n")
 else
  f.write("#{s}\n")
 end
end

n = 0
arr = []
open("input.txt") {|f|
  n = f.gets.to_i
  arr = f.gets.to_s.chomp.split.map(&:to_i)
}
File.open("output.txt", "w"){|f|
  t1 = 0
  t2 = 0
  ar1 = []
  ar2 = []
  n.times do |i|
    t1 += 1 if arr[i] >= 0
    ar1.push(t1)
    t2 += 1 if arr[n-1-i] <= 0
    ar2.push(t2)
  end
  ar2.reverse!
  ar3 = []
  #ar3.push(ar1[n-1])
  #ar3.push(ar2[0])
  (n-1).times do |i|
    ar3.push(ar1[i]+ar2[i+1])
  end
  #p ar1
  #p ar2
  #p ar3
  f.write "#{ar3.min}\n"
}

n = 0
arr = []
open("input.txt") {|f|
  n = f.gets.to_i
  arr = f.gets.to_s.chomp.split.map(&:to_i)
}
File.open("output.txt", "w"){|f|
  t1 = 0
  t2 = 0
  ar1 = []
  ar2 = []
  n.times do |i|
    t1 += 1 if arr[i] >= 0
    ar1.push(t1)
    t2 += 1 if arr[n-1-i] <= 0
    ar2.unshift(t2)
  end
  ar3 = []
  ar3.push(ar1[n-1])
  ar3.push(ar2[0])
  (n-1).times do |i|
    ar3.push(ar1[i]+ar2[i+1])
  end
  #p ar1
  #p ar2
  #p ar3
  f.write "#{ar3.min}\n"
}


An array is beautiful if both of the following two conditions meet:  there are at least $$$l_1$$$ and at most $$$r_1$$$ elements in the array equal to its minimum;  there are at least $$$l_2$$$ and at most $$$r_2$$$ elements in the array equal to its maximum. For example, the array $$$[2, 3, 2, 4, 4, 3, 2]$$$ has $$$3$$$ elements equal to its minimum ($$$1$$$-st, $$$3$$$-rd and $$$7$$$-th) and $$$2$$$ elements equal to its maximum ($$$4$$$-th and $$$5$$$-th).Another example: the array $$$[42, 42, 42]$$$ has $$$3$$$ elements equal to its minimum and $$$3$$$ elements equal to its maximum.Your task is to calculate the minimum possible number of elements in a beautiful array.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Each test case consists of one line containing four integers $$$l_1$$$, $$$r_1$$$, $$$l_2$$$ and $$$r_2$$$ ($$$1 \le l_1 \le r_1 \le 50$$$; $$$1 \le l_2 \le r_2 \le 50$$$).

For each test case, print one integer — the minimum possible number of elements in a beautiful array.

gets.to_i.times do
  l1, r1, l2, r2 = gets.split.map(&:to_i)
  if l1 <= r2 && r1 >= l2
    p [l1, l2].max
  else
    p l1 + l2
  end
end

gets.to_i.times do
  l1,r1,l2,r2 = gets.chomp.split.map(&:to_i)
  if (l2 > r1) or (r2<l1) then
    puts l1 + l2
  else
    puts [l1,l2].max
  end
end


A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes $$$l$$$ nanoseconds, where $$$l$$$ is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take $$$2$$$ nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — the length of Dima's sequence. The second line contains string of length $$$n$$$, consisting of characters "(" and ")" only.

Print a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.

NoteIn the first example we can firstly reorder the segment from first to the fourth character, replacing it with "()()", the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character, replacing it with "()". In the end the sequence will be "()()()()", while the total time spent is $$$4 + 2 = 6$$$ nanoseconds.

N = gets.to_i
S = gets.chomp.chars

counter = Hash.new(0)

S.each do |s|
  counter[s] += 1
end

if counter['('] != counter[')']
  puts -1
  exit
end

stack = []

ans = 0
len = 0

S.each do |s|
  stack << s

  if stack[0] == ')'
    len += 1
  else
    ans += len
    len = 0
  end

  if stack[-2] == '(' && stack[-1] == ')'
    stack.pop(2)
  elsif stack[-2] == ')' && stack[-1] == '('
    stack.pop(2)
  end
end

ans += len

puts ans


Petya and Gena play a very interesting game "Put a Knight!" on a chessboard n × n in size. In this game they take turns to put chess pieces called "knights" on the board so that no two knights could threat each other. A knight located in square (r, c) can threat squares (r - 1, c + 2), (r - 1, c - 2), (r + 1, c + 2), (r + 1, c - 2), (r - 2, c + 1), (r - 2, c - 1), (r + 2, c + 1) and (r + 2, c - 1) (some of the squares may be located outside the chessboard). The player who can't put a new knight during his move loses. Determine which player wins considering that both players play optimally well and Petya starts.

The first line contains integer T (1 ≤ T ≤ 100) — the number of boards, for which you should determine the winning player. Next T lines contain T integers ni (1 ≤ ni ≤ 10000) — the sizes of the chessboards.

For each ni × ni board print on a single line "0" if Petya wins considering both players play optimally well. Otherwise, print "1".

t, a = nil
File.open("input.txt") do |f|
  t = f.gets.to_i
  a = []
  t.times{ a << f.gets.to_i}
end

File.open("output.txt", "w") do |f|
  a.each{|x| f.puts 1-x%2}
end

$stdin=File.open('input.txt')
$stdout=File.open('output.txt','w')
N=gets.to_i
for i in 0...N
    j=gets.to_i
    if j%2==0
        puts "1"
    else
        puts "0"
    end
end


You have an array of integers (initially empty).You have to perform $$$q$$$ queries. Each query is of one of two types:   "$$$1$$$ $$$x$$$" — add the element $$$x$$$ to the end of the array;  "$$$2$$$ $$$x$$$ $$$y$$$" — replace all occurrences of $$$x$$$ in the array with $$$y$$$. Find the resulting array after performing all the queries.

The first line contains a single integer $$$q$$$ ($$$1 \le q \le 5 \cdot 10^5$$$) — the number of queries. Next $$$q$$$ lines contain queries (one per line). Each query is of one of two types:    "$$$1$$$ $$$x$$$" ($$$1 \le x \le 5 \cdot 10^5$$$);  "$$$2$$$ $$$x$$$ $$$y$$$" ($$$1 \le x, y \le 5 \cdot 10^5$$$).  It's guaranteed that there is at least one query of the first type.

In a single line, print $$$k$$$ integers — the resulting array after performing all the queries, where $$$k$$$ is the number of queries of the first type.


You are given two arrays A and B, each of size n. The error, E, between these two arrays is defined . You have to perform exactly k1 operations on array A and exactly k2 operations on array B. In one operation, you have to choose one element of the array and increase or decrease it by 1.Output the minimum possible value of error after k1 operations on array A and k2 operations on array B have been performed.

The first line contains three space-separated integers n (1 ≤ n ≤ 103), k1 and k2 (0 ≤ k1 + k2 ≤ 103, k1 and k2 are non-negative) — size of arrays and number of operations to perform on A and B respectively. Second line contains n space separated integers a1, a2, ..., an ( - 106 ≤ ai ≤ 106) — array A. Third line contains n space separated integers b1, b2, ..., bn ( - 106 ≤ bi ≤ 106)— array B.

Output a single integer — the minimum possible value of  after doing exactly k1 operations on array A and exactly k2 operations on array B.

NoteIn the first sample case, we cannot perform any operations on A or B. Therefore the minimum possible error E = (1 - 2)2 + (2 - 3)2 = 2. In the second sample case, we are required to perform exactly one operation on A. In order to minimize error, we increment the first element of A by 1. Now, A = [2, 2]. The error is now E = (2 - 2)2 + (2 - 2)2 = 0. This is the minimum possible error obtainable.In the third sample case, we can increase the first element of A to 8, using the all of the 5 moves available to us. Also, the first element of B can be reduced to 8 using the 6 of the 7 available moves. Now A = [8, 4] and B = [8, 4]. The error is now E = (8 - 8)2 + (4 - 4)2 = 0, but we are still left with 1 move for array B. Increasing the second element of B to 5 using the left move, we get B = [8, 5] and E = (8 - 8)2 + (4 - 5)2 = 1.

n, k1, k2 = gets.chomp.split.map(&:to_i)

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

c = Array.new(n) { |i| (a[i] - b[i]).abs }.sort
i = n - 1

(k1 + k2).times do
  c[i] = (c[i] - 1).abs

  current_max = c.max
  if c[i] != current_max
    i_max = c.index(current_max)
    i = i_max
  end
end

min_error = 0
for num in c
  min_error += num * num
end

puts min_error

n, k1, k2 = gets.chomp.split.map(&:to_i)

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

c = Array.new(n) { |i| (a[i] - b[i]).abs }.sort
i = c.length - 1

min = 0
potential = k1 + k2

while i >= 0
  if c[i] == 0
    a = [potential, (k1 - k2).abs].min
    min += a * a
  else
    if c[i] >= potential
      c[i] -= potential
      potential = 0
      min += c[i] * c[i]
    else
      potential -= c[i]
      c[i] = 0
    end
  end
  i -= 1
end

puts min

n, k1, k2 = gets.chomp.split.map(&:to_i)

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

c = Array.new(n) { |i| (a[i] - b[i]).abs }.sort
i = c.length - 1
p c
min = 0
potential = k1 + k2

while i >= 0
  if c[i] == 0
    a = [potential, (k1 - k2).abs].min
    min += a * a
  else
    if c[i] >= potential
      c[i] -= potential
      potential = 0
      min += c[i] * c[i]
    else
      potential -= c[i]
      c[i] = 0
    end
  end
  i -= 1
end

puts min

n, k1, k2 = gets.chomp.split.map(&:to_i)

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

c = Array.new(n) { |i| (a[i] - b[i]).abs }.sort
i = c.length - 1

min = 0
potential = k1 + k2

while i >= 0
  if c[i] == 0
    min += potential * potential
  else
    if c[i] >= potential
      c[i] -= potential
      potential = 0
      min += c[i] * c[i]
    else
      potential -= c[i]
      c[i] = 0
    end
  end
  i -= 1
end

puts min


There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. n particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the distance in meters from the center of the collider, xi is the coordinate of the i-th particle and its position in the collider at the same time. All coordinates of particle positions are even integers.You know the direction of each particle movement — it will move to the right or to the left after the collider's launch start. All particles begin to move simultaneously at the time of the collider's launch start. Each particle will move straight to the left or straight to the right with the constant speed of 1 meter per microsecond. The collider is big enough so particles can not leave it in the foreseeable time.Write the program which finds the moment of the first collision of any two particles of the collider. In other words, find the number of microseconds before the first moment when any two particles are at the same point.

The first line contains the positive integer n (1 ≤ n ≤ 200 000) — the number of particles.  The second line contains n symbols "L" and "R". If the i-th symbol equals "L", then the i-th particle will move to the left, otherwise the i-th symbol equals "R" and the i-th particle will move to the right. The third line contains the sequence of pairwise distinct even integers x1, x2, ..., xn (0 ≤ xi ≤ 109) — the coordinates of particles in the order from the left to the right. It is guaranteed that the coordinates of particles are given in the increasing order.

In the first line print the only integer — the first moment (in microseconds) when two particles are at the same point and there will be an explosion.  Print the only integer -1, if the collision of particles doesn't happen.

NoteIn the first sample case the first explosion will happen in 1 microsecond because the particles number 1 and 2 will simultaneously be at the same point with the coordinate 3. In the second sample case there will be no explosion because there are no particles which will simultaneously be at the same point.

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

ans = 1234567890

(n-1).times do |i|
    if s[i]=='R' && s[i+1]=='L'
        ans = [ans, (a[i+1]-a[i])/2].min
    end
end

if ans==1234567890
    p -1
else
    p ans
end

gets
str = gets.chomp
mas = gets.split.map(&:to_i)

n = str.length

ans = 10000000000000
l = false
for i in 0..n-1 do
  if str[i]=='R' and str[i+1]=='L' then
      l = true
      out = (mas[i+1] - mas[i])/2
      ans = out if ans > out
  end
end

puts (l==true ? "#{ans}": "-1")

n = gets.chomp.to_i
syms = gets.chomp.chars
points = gets.chomp.split.map(&:to_i)

arr = syms.each_cons(2).with_index.select { |s, _| s.join == "RL" }.map do |_, idx|
  (points[idx + 1] - points[idx]) / 2
end

puts arr.empty? ? -1 : arr.min

#! ruby
# Try Codeforces
# author: Leonardone @ NEETSDKASU
############################################################
def gs() gets.chomp end
def gi() gets.to_i end
def gss() gs.split end
def gis() gss.map(&:to_i) end
def nmapf(n,f) n.times.map{ __send__ f } end
def ngs(n) nmapf n,:gs end
def ngi(n) nmapf n,:gi end
def ngss(n) nmapf n,:gss end
def ngis(n) nmapf n,:gis end
def arr2d(h,w,v=0) h.times.map{[v] * w} end
def for2p(hr,wr,&pr) hr.each{|i|wr.each{|j| yield(i,j)}} end
def nsum(n) n * (n + 1) / 2 end
def vcount(d,r=Hash.new(0)) d.inject(r){|m,e| m[e]+=1;m} end
############################################################

n = gi
s = gs
x = gis

l = nil
r = nil

ans = nil

n.times do |i|
    if s[i] == 'L'
        l = x[i]
    else
        r = x[i]
    end
    next if l.nil?
    next if r.nil?
    next if r > l
    k = (l - r) / 2
    if ans.nil?
        ans = k
    else
        ans = [ans, k].min
    end
end

if ans.nil?
    puts -1
else
    puts ans
end

def solve
	min = 10 ** 10
	for i in 0..$s.size - 2
		if $s[i] == 'R' and $s[i + 1] == 'L'
			t = ($a[i + 1] - $a[i]) / 2
			min = t if t < min
		end
	end
	return min == 10 ** 10 ? -1 : min;
end

$n = gets.to_i
$s = gets
$a = gets.split.map &:to_i
puts solve

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

ans=-1
(n-1).times{|i|
	if s[i]=="R" && s[i+1]=="L" then
		t1=(x[i+1]-x[i])/2
		if ans==-1 || ans>t1 then
			ans=t1
		end
	end
}
puts ans

n = gets.to_i
directions = gets
numbers = gets

numbers = numbers.split(' ')
pr = -1
min = 20000000000
flag = 0
pl = -1
numbers.each_with_index do |r,i|
    if (directions[i] == 'R')
        pr = i
    else
        if (pr != -1)
            pl = i
            #calc magic
            delta = numbers[pl].to_i - numbers[pr].to_i
            min = delta if delta < min
            flag = 1;
        end
    end
end

puts flag == 0 ? -1 : min/2

n = gets.chomp.to_i
ss = gets.chomp.split('')
xs = gets.chomp.split.map(&:to_i)

ls = []
rs = []
(0...n).to_a.each do |i|
  if ss[i] == 'L'
    ls << xs[i]
  else
    rs << xs[i]
  end
end

ls.sort!
ans = -1

rs.each do |r|
  l = ls.bsearch { |l| r < l }
  if !l.nil?
    t = (l - r) / 2
    if ans < 0 || t < ans
      ans = t
    end
  end
end

puts ans

n = gets.to_i
d = gets.chomp.chars
t = gets.split.map(&:to_i)
ans = 1e9
(n - 1).times do |i|
  if d[i] == 'R' && d[i + 1] == 'L'
    ans = [( t[i + 1] - t[i] ) / 2, ans].min
  end
end
puts ans == 1e9 ? -1 : ans

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

ans = nil
last = nil
n.times do |i|
  if d[i] == 'L'
    ans = x[i] - last if last && (ans.nil? || x[i] - last < ans)
  else
    last = x[i]
  end
end

puts ans ? ans / 2 : -1

particleNum = gets.chomp.to_i
directions = gets.chomp.split('')
particles  = gets.chomp.split(' ').map(&:to_i)

foundRight = false
posRight = 0

ans = -1
candAns = []

for i in 0...particleNum
	foundRight = true if directions[i] == 'R'
	posRight = i if directions[i] == 'R'

	if foundRight && directions[i] == 'L'
		candAns << particles[i] - ((particles[posRight] + particles[i]) / 2)
		foundRight = false
	end
end

if candAns.length > 0
	puts candAns.min
else
	puts -1
end

particleNum = gets.chomp.to_i
directions = gets.chomp.split('')
particles  = gets.chomp.split(' ').map(&:to_i)

foundRight = false
posRight = 0

ans = -1

for i in 0...particleNum
	foundRight = true if directions[i] == 'R'
	posRight = i if directions[i] == 'R'

	if foundRight && directions[i] == 'L'
		ans = particles[i] - ((particles[posRight] + particles[i]) / 2)
		break
	end
end

puts ans


After celebrating the midcourse the students of one of the faculties of the Berland State University decided to conduct a vote for the best photo. They published the photos in the social network and agreed on the rules to choose a winner: the photo which gets most likes wins. If multiple photoes get most likes, the winner is the photo that gets this number first.Help guys determine the winner photo by the records of likes.

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the total likes to the published photoes.  The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 1 000 000), where ai is the identifier of the photo which got the i-th like.

Print the identifier of the photo which won the elections.

NoteIn the first test sample the photo with id 1 got two likes (first and fifth), photo with id 2 got two likes (third and fourth), and photo with id 3 got one like (second). Thus, the winner is the photo with identifier 2, as it got:  more likes than the photo with id 3;  as many likes as the photo with id 1, but the photo with the identifier 2 got its second like earlier.

#!/usr/bin/ruby
gets;a=gets.split.map(&:to_i)
b=a.group_by{|e|e}.map{|k,v|[-v.size,k]}.sort
c=b.take_while{|s,k|s==b[0][0]}.map(&:last)
h={}
a.reverse.each_with_index{|e,i|h[e]||=i if c.include?(e)}
p h.max_by{|k,v|v}[0]

n = gets.to_i
a = gets.split.map{|x| x.to_i}
h = Hash.new(0)
x = 0
y = -1
for i in 0...n

	h[a[i]] += 1
	if h[a[i]] > x then
		x = h[a[i]]
		y = a[i]
	end

end

puts y

n=gets.to_i
a=gets.split(" ")
s=Array.new(1111111,0)
ans=id=0
a.each do |v|
	x=v.to_i
	y = (s[x]+=1)
	if ans<y
		ans=y
		id=x
	end
end
puts id


Polycarp has an array $$$a$$$ consisting of $$$n$$$ integers.He wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains $$$n-1$$$ elements). For each of the next moves he chooses any element with the only restriction: its parity should differ from the parity of the element deleted on the previous move. In other words, he alternates parities (even-odd-even-odd-... or odd-even-odd-even-...) of the removed elements. Polycarp stops if he can't make a move.Formally:   If it is the first move, he chooses any element and deletes it;  If it is the second or any next move:   if the last deleted element was odd, Polycarp chooses any even element and deletes it;  if the last deleted element was even, Polycarp chooses any odd element and deletes it.   If after some move Polycarp cannot make a move, the game ends. Polycarp's goal is to minimize the sum of non-deleted elements of the array after end of the game. If Polycarp can delete the whole array, then the sum of non-deleted elements is zero.Help Polycarp find this value.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) — the number of elements of $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^6$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

Print one integer — the minimum possible sum of non-deleted elements of the array after end of the game.

n = gets.to_i
a = gets.split.map(&:to_i).sort
x = [[],[]]
n.times do |i|
    x[a[i]%2] << a[i]
end
if (x[0].size-x[1].size).abs <= 1
    puts 0
else
    x[0],x[1] = x[1],x[0] if x[0].size > x[1].size
    m = x[0].size
    puts x[1][0..-m-2].inject(:+)
end

gets.chomp
a = gets.chomp.split(" ").map(&:to_i)
even = a.select(&:even?).sort
odd = a.select(&:odd?).sort

elements_sum = 0
even_size_diff = even.size - odd.size - 1
odd_size_diff = odd.size - even.size - 1

elements_sum = even[0..even_size_diff-1].reduce(0, :+) if even_size_diff > 0
elements_sum = odd[0..odd_size_diff-1].reduce(0,:+) if odd_size_diff > 0

puts elements_sum

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

odds = a.select(&:odd?)
evens = a.select(&:even?)

res = 0
diff_size = (odds.size - evens.size).abs
if diff_size <= 1
  res = 0
else
  arr = (odds.size > evens.size) ? odds : evens
  res = arr.sort[0..(diff_size-2)].reduce(&:+)
end

puts res


Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop.

The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell).

Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries.

H, W, Q = gets.split.map(&:to_i)
D = Array.new(H) { gets.chomp }

icons_to_move = 0
icon = Array.new(H) { [false] * W }

icons = []
H.times do |i|
    W.times do |j|
        if D[i][j] == ?*
            icons << (j * H + i)
            icon[i][j] = true
        end
    end
end

icons.each do |k|
    icons_to_move += 1 if k >= icons.size
end

n_icons = icons.size

Q.times do
    i, j = gets.split.map { _1.to_i - 1 }
    k = j * H + i

    if icon[i][j]
        icons_to_move -= 1 if k >= n_icons
        icon[i][j] = false
        n_icons -= 1
        icons_to_move += 1 if icon[n_icons % H][n_icons / H]
    else
        icons_to_move -= 1 if icon[n_icons % H][n_icons / H]
        icon[i][j] = true
        n_icons += 1
        icons_to_move += 1 if (j * H + i) >= n_icons
    end

    puts icons_to_move
end


A card pyramid of height $$$1$$$ is constructed by resting two cards against each other. For $$$h>1$$$, a card pyramid of height $$$h$$$ is constructed by placing a card pyramid of height $$$h-1$$$ onto a base. A base consists of $$$h$$$ pyramids of height $$$1$$$, and $$$h-1$$$ cards on top. For example, card pyramids of heights $$$1$$$, $$$2$$$, and $$$3$$$ look as follows:  You start with $$$n$$$ cards and build the tallest pyramid that you can. If there are some cards remaining, you build the tallest pyramid possible with the remaining cards. You repeat this process until it is impossible to build another pyramid. In the end, how many pyramids will you have constructed?

Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. Each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^9$$$) — the number of cards. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^9$$$.

For each test case output a single integer — the number of pyramids you will have constructed in the end.

NoteIn the first test, you construct a pyramid of height $$$1$$$ with $$$2$$$ cards. There is $$$1$$$ card remaining, which is not enough to build a pyramid.In the second test, you build two pyramids, each of height $$$2$$$, with no cards remaining.In the third test, you build one pyramid of height $$$3$$$, with no cards remaining.In the fourth test, you build one pyramid of height $$$3$$$ with $$$9$$$ cards remaining. Then you build a pyramid of height $$$2$$$ with $$$2$$$ cards remaining. Then you build a final pyramid of height $$$1$$$ with no cards remaining.In the fifth test, one card is not enough to build any pyramids.

t = gets.to_i

0.upto t-1 do
  card = gets.to_i
  count = 0
  h = 1    # height
  while card > 1 do
    h = 1
    while card > 1 do
      if card >= (2*h + (h-1))
        card -= (2*h + (h-1))
        h += 1
        if card == 0 or card == 1
          count += 1
        end
      else
        count += 1
        break
      end
    end
  end
  puts count
end

# coding: utf-8

t = gets.to_i

def required(h)
    2 * (h*(h+1)/2) + ((h-1)*h/2)
end

def near_max(ar, v)
    b, e = 0, ar.length
    while b < e
        mid = (b + e)/2
        if v < ar[mid]
            if e - b == 1
                return ar[b]
            else
                e = mid
            end
        elsif v > ar[mid]
            if e - b == 1
                return ar[b]
            else
                b = mid
            end
        else
            return ar[mid]
        end
    end
end
precalc = [0]
for i in 1..25900
    precalc << required(i)
end
# p precalc
# puts near_max(precalc, 10**9)
t.times {
    n = gets.to_i # the number of cards (1<=n<=10**9)
    # if h, required_cards = 2*(from 1 to h, sum) + (from 0 to h-1, sum)
    # h*h + h + h*h/2 - h/2
    pyramids = 0
    while n >= 2
        subtractor = near_max(precalc, n)

        if subtractor == 0
            break
        else
            pyramids += 1
            n -= subtractor
        end
    end
    puts pyramids

}


Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.The way to split up game pieces is split into several steps:  First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B.  Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once.  Alice will get all the pieces marked A and Bob will get all the pieces marked B. The strength of a player is then the sum of strengths of the pieces in the group.Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.

The first line contains integer n (1 ≤ n ≤ 5·105) — the number of game pieces. The second line contains n integers pi (1 ≤ pi ≤ 109) — the strength of the i-th piece. The third line contains n characters A or B — the assignment of teams after the first step (after Alice's step).

Print the only integer a — the maximum strength Bob can achieve.

NoteIn the first sample Bob should flip the suffix of length one.In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.In the third sample Bob should do nothing.

#!/usr/bin/ruby
n=gets.to_i
a=gets.split.map(&:to_i)
s=gets.chomp.bytes
r=0
n.times{|i|r+=a[i] if s[i]==66}
r0=r1=r
n.times{|i|
	if s[i]==65
		r0+=a[i]
	else
		r0-=a[i]
	end
	r=[r,r0].max
}
(n-1).downto(0){|i|
	if s[i]==65
		r1+=a[i]
	else
		r1-=a[i]
	end
	r=[r,r1].max
}
p r

n = gets.to_i
a = gets.split(' ')
s = gets
ori = 0
for i in 0..n-1
	a[i] = a[i].to_i
	if s[i]=='B'
		ori+=a[i]
		a[i]=-a[i]
	end
end
tot = ans = ori
for i in 0..n-1
	tot+=a[i]
	ans = [ans, tot].max
end
tot = ori
i=n-1
while i>=0
	tot+=a[i]
	ans = [ans, tot].max
	i-=1
end
puts ans

n = gets.to_i
a = gets.split(' ')
s = gets
ori = 0
for i in 0..n-1
	a[i] = a[i].to_i
	if s[i]=='B'
		ori+=a[i]
		a[i]=-a[i]
	end
end
tot = ans = ori
a.each do |v|
	tot+=v
	ans = [ans, tot].max
end
tot = ori
a.reverse_each do |v|
	tot+=v
	ans = [ans, tot].max
end
puts ans

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

init = 0

n.times do |i|
  init += pieces[i] if teams[i] == "B"
end

ret = init

# left
curr = init
n.times do |i|
  if teams[i] == "A" then
    curr += pieces[i]
  else
    curr -= pieces[i]
  end
  if curr > ret then
    ret = curr
  end
end

# right
curr = init
(n - 1).downto(0) do |i|
  if teams[i] == "A" then
    curr += pieces[i]
  else
    curr -= pieces[i]
  end
  if curr > ret then
    ret = curr
  end
end

puts ret

n = gets.to_i
a = gets.split(' ')
s = gets
exit if n>400000
ori = 0
for i in 0..n-1
	ori+=a[i].to_i if s[i]=='B'
end
tot = ans = ori
for i in 0..n-1
	tot+=a[i].to_i if s[i]=='A'
	tot-=a[i].to_i if s[i]=='B'
	ans = [ans, tot].max
end
tot = ori
i=n-1;
while i>=0
	tot+=a[i].to_i if s[i]=='A'
	tot-=a[i].to_i if s[i]=='B'
	ans = [ans, tot].max
	i-=1
end
puts ans

n = gets.to_i
a = gets.split(' ')
s = gets
ori = 0
for i in 0..n-1
	a[i] = a[i].to_i
	ori+=a[i] if s[i]=='B'
end
exit if n>400000
tot = ans = ori
for i in 0..n-1
	tot+=a[i] if s[i]=='A'
	tot-=a[i] if s[i]=='B'
	ans = [ans, tot].max
end
tot = ori
i=n-1
while i>=0
	tot+=a[i] if s[i]=='A'
	tot-=a[i] if s[i]=='B'
	ans = [ans, tot].max
	i-=1
end
puts ans

n = gets.to_i
a = gets.split(' ')
s = gets
ori = 0
for i in 0..n-1
	a[i] = a[i].to_i
	ori+=a[i] if s[i]=='B'
end
tot = ans = ori
for i in 0..n-1
	tot+=a[i] if s[i]=='A'
	tot-=a[i] if s[i]=='B'
	ans = [ans, tot].max
end
exit if n>400000
tot = ori
i=n-1
while i>=0
	tot+=a[i] if s[i]=='A'
	tot-=a[i] if s[i]=='B'
	ans = [ans, tot].max
	i-=1
end
puts ans

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

init = 0

n.times do |i|
  init += pieces[i] if teams[i] == "B"
end
ret = init

# left
curr = init
n.times do |i|
  break if teams[i] == "B"
  curr += pieces[i]
end
ret = [ret, curr].max

# right
curr = init
(n - 1).downto(0) do |i|
  break if teams[i] == "B"
  curr += pieces[i]
end
ret = [ret, curr].max

puts ret


Om Nom really likes candies and doesn't like spiders as they frequently steal candies. One day Om Nom fancied a walk in a park. Unfortunately, the park has some spiders and Om Nom doesn't want to see them at all.  The park can be represented as a rectangular n × m field. The park has k spiders, each spider at time 0 is at some cell of the field. The spiders move all the time, and each spider always moves in one of the four directions (left, right, down, up). In a unit of time, a spider crawls from his cell to the side-adjacent cell in the corresponding direction. If there is no cell in the given direction, then the spider leaves the park. The spiders do not interfere with each other as they move. Specifically, one cell can have multiple spiders at the same time.Om Nom isn't yet sure where to start his walk from but he definitely wants:  to start walking at time 0 at an upper row cell of the field (it is guaranteed that the cells in this row do not contain any spiders);  to walk by moving down the field towards the lowest row (the walk ends when Om Nom leaves the boundaries of the park). We know that Om Nom moves by jumping. One jump takes one time unit and transports the little monster from his cell to either a side-adjacent cell on the lower row or outside the park boundaries.Each time Om Nom lands in a cell he sees all the spiders that have come to that cell at this moment of time. Om Nom wants to choose the optimal cell to start the walk from. That's why he wonders: for each possible starting cell, how many spiders will he see during the walk if he starts from this cell? Help him and calculate the required value for each possible starting cell.

The first line contains three integers n, m, k (2 ≤ n, m ≤ 2000; 0 ≤ k ≤ m(n - 1)).  Each of the next n lines contains m characters — the description of the park. The characters in the i-th line describe the i-th row of the park field. If the character in the line equals ".", that means that the corresponding cell of the field is empty; otherwise, the character in the line will equal one of the four characters: "L" (meaning that this cell has a spider at time 0, moving left), "R" (a spider moving right), "U" (a spider moving up), "D" (a spider moving down).  It is guaranteed that the first row doesn't contain any spiders. It is guaranteed that the description of the field contains no extra characters. It is guaranteed that at time 0 the field contains exactly k spiders.

Print m integers: the j-th integer must show the number of spiders Om Nom will see if he starts his walk from the j-th cell of the first row. The cells in any row of the field are numbered from left to right.

NoteConsider the first sample. The notes below show how the spider arrangement changes on the field over time:...        ...        ..U       ...R.L   ->   .*U   ->   L.R   ->  ...R.U        .R.        ..R       ...Character "*" represents a cell that contains two spiders at the same time.  If Om Nom starts from the first cell of the first row, he won't see any spiders.  If he starts from the second cell, he will see two spiders at time 1.  If he starts from the third cell, he will see two spiders: one at time 1, the other one at time 2.

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

$results = Array.new($m, 0)
# $results = []

def spiders_indersection(line, position, direction)
  index = nil
  case direction
  when 'L'
    index = position - line
  when 'R'
    index = position + line
  when 'U'
    index = position unless line.odd?
  end
  # if index
  #   $results[index] = ($results[index] || 0) + 1
  # end
  if (index && index >= 0 && index < $m)
    # puts [index, position, line].join(' ')
    $results[index] += 1
  end
end

$n.times do |i|
  gets.chars.first($m).each_with_index do |char, j|
    spiders_indersection(i, j, char)
  end
end

puts $results.first($m).join(' ')

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

init_field = n.times.map {
  readline.strip
}
res = Array.new(m, 0)

init_field.each_with_index{|line, row_idx|
  line.each_char.with_index{|cell, col_idx|
    if cell == 'L'
      col_corr = col_idx - row_idx
      res[col_corr] += 1  if col_corr >= 0
    elsif cell == 'R'
      col_corr = col_idx + row_idx
      res[col_corr] += 1  if col_corr < m
    elsif cell == 'U' && row_idx % 2 == 0
      res[col_idx] += 1
    end
  }
}

puts res.join(' ')

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

$results = Array.new(2*$m, 0)

def spiders_indersection(line, position, direction)
  # $m.times do |omnom_start_position|
  #   met = case direction
  #   when 'L'
  #     position - line == omnom_start_position
  #   when 'R'
  #     omnom_start_position == line + position
  #   when 'U'
  #     omnom_start_position == position
  #   else
  #     false
  #   end
  #   $results[omnom_start_position] += 1 if met
  # end

  case direction
  when 'L'
    $results[position - line] += 1
  when 'R'
    $results[position + line] += 1
  when 'U'
    $results[position] += 1
  end
end

$n.times do |i|
  gets.chars.first($m).each_with_index do |char, j|
    spiders_indersection(i, j, char)
  end
end

puts $results.first($m).join(' ')

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

$results = Array.new($m, 0)

def spiders_indersection(line, position, direction)
  index = -1
  case direction
  when 'L'
    index = position - line
  when 'R'
    index = position + line
  when 'U'
    index = position if line > 1
  end
  $results[index] += 1 if (index >= 0 && index < $m)
end

$n.times do |i|
  gets.chars.first($m).each_with_index do |char, j|
    spiders_indersection(i, j, char)
  end
end

puts $results.first($m).join(' ')

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

$results = Array.new($m, 0)
# $results = []

def spiders_indersection(line, position, direction)
  index = nil
  case direction
  when 'L'
    index = position - line
  when 'R'
    index = position + line
  when 'U'
    index = position if line > 1
  end
  # if index
  #   $results[index] = ($results[index] || 0) + 1
  # end
  if (index && index >= 0)
    # puts [index, position, line].join(' ')
    # $results[index] += 1
    $results[index] = ($results[index] || 0) + 1
  end
end

$n.times do |i|
  gets.chars.first($m).each_with_index do |char, j|
    spiders_indersection(i, j, char)
  end
end

puts $results.first($m).join(' ')


A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition — when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do. Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation. Thus, your cup is a cylinder with diameter equals d centimeters. Initial level of water in cup equals h centimeters from the bottom.   You drink a water with a speed equals v milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on e centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously. Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.Note one milliliter equals to one cubic centimeter.

The only line of the input contains four integer numbers d, h, v, e (1 ≤ d, h, v, e ≤ 104), where:   d — the diameter of your cylindrical cup,  h — the initial level of water in the cup,  v — the speed of drinking process from the cup in milliliters per second,  e — the growth of water because of rain if you do not drink from the cup.

If it is impossible to make the cup empty, print "NO" (without quotes). Otherwise print "YES" (without quotes) in the first line. In the second line print a real number — time in seconds needed the cup will be empty. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. It is guaranteed that if the answer exists, it doesn't exceed 104.

NoteIn the first example the water fills the cup faster than you can drink from it.In the second example area of the cup's bottom equals to , thus we can conclude that you decrease the level of water by  centimeters per second. At the same time water level increases by 1 centimeter per second due to rain. Thus, cup will be empty in  seconds.

d,h,v,e=gets.split.map(&:to_f)
v/=Math::PI*d*d/4
puts v<e ? "NO" : "YES\n"+(h/(v-e)).to_s

def calc(d, h, v, e)
  speed = v / (d * d * 0.25 * Math::PI)
  return "NO" if speed <= e

  diff = speed - e
  time = h / diff
  time <= 10000.0 ? "YES\n#{time}" : "NO"
end

d, h, v, e = gets.chomp.split.map(&:to_f)
puts calc(d, h, v, e)

d, h, v, e = readline.split(' ').collect(&:to_i)
pi = Math.acos(-1.0)
inc = e * pi * d * d / 4.0
if inc >= v
  puts "NO"
else
  puts "YES"
  puts (pi * d * d / 4.0 * h) / (v - inc)
end

a=gets.chomp.split(" ").map{|i| i.to_i}
pi=3.141592653589793
x=(4*a[2])/((a[0]**2)*pi)
if x>a[3]
k=x-a[3]
time=a[1]/k

if time<=10000
puts"YES"
puts"#{time}"
else
puts"NO"
end

else
puts "NO"
end

d, h, v, e = gets.split.map { |x| x.to_i }
s = (d / 2.0) ** 2 * Math::PI

if v / s > e
	puts "YES"
	ans = h / (v / s - e)
	puts "%.12f" % ans
else
	puts "NO"
end

input = gets.chomp.split(' ').map {|i| i.to_i}
d, h, v, e = input[0], input[1], input[2], input[3]

decreaseSpeed = (4 * v) / ((d ** 2) * Math::PI)
ans = h / (decreaseSpeed - e)

if ans < 0
	puts 'NO'
else
	puts 'YES'
	puts ans
end

input = gets.chomp.split(' ').map {|i| i.to_i}
d, h, v, e = input[0], input[1], input[2], input[3]

decreaseSpeed = (4 * v) / ((d ** 2) * Math::PI)
ans = h / (decreaseSpeed - e)

if ans < 0
	puts 'NO'
else
	puts ans
end


You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \le x \le r$$$.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$, $$$1 \le d_i \le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers.

gets
$<.map{|e|l,r,d=e.split.map &:to_i;p d+(d<l ? 0 : r/d*d)}

def solve(l, r, x)
  return x unless x.between?(l, r)
  return r - ((r + x) % x) + x
end

gets.strip.to_i.times do
l, r, x = gets.strip.split.map(&:to_i)
puts solve(l, r, x)
end

# Utility
def process(l, r, d)
  re = d
  while re >= l && re <= r
    re += d * (1 + (r - re) / d)
  end
  re
end

# Input
q = gets.to_i
result = Array.new(q)
q.times { |i| result[i] = process(*gets.split(" ").map { |e| e.to_i }) }

# Output
puts result

n = gets.to_i
n.times do
  l, r, d = gets.split(' ').map(&:to_i)
  if d < l
    puts d
  else
    t = (r + 1) * 1.0 / d
    puts t.ceil * d
  end
end

DBG = true
n = gets.to_i
for i in 0...n
  l,r,d = gets.split.map{|x| x.to_i}
  if d < l
    puts "#{d}"
    next
  end
  puts "#{((r+d)/d)*d}"
end

if File.exists?("input")
  $stdin = File.open("input")
  $stdout = File.open("output","w")
end

q = gets.to_i
q.times do
  lrd = gets.chomp.split(" ").map(&:to_i)
  l = lrd[0]
  r = lrd[1]
  d = lrd[2]
  if d<l
    puts d
  else
    a = (r/d)*d
    while a<=r
      a += d
    end
    puts a
  end
end

# You are given 𝑞 queries in the following form:

# Given three integers 𝑙𝑖, 𝑟𝑖 and 𝑑𝑖, find minimum
# positive integer 𝑥𝑖 such that it is divisible by 𝑑𝑖 and
# it does not belong to the segment [𝑙𝑖,𝑟𝑖].

# Can you answer all the queries?

# Recall that a number 𝑥 belongs to segment [𝑙,𝑟] if 𝑙≤𝑥≤𝑟.

# Input
# The first line contains one integer 𝑞 (1≤𝑞≤500) — the number of queries.

# Then 𝑞 lines follow, each containing a query given in
# the format 𝑙𝑖 𝑟𝑖 𝑑𝑖 (1≤𝑙𝑖≤𝑟𝑖≤109, 1≤𝑑𝑖≤109). 𝑙𝑖, 𝑟𝑖 and 𝑑𝑖 are integers.

# Output
# For each query print one integer: the answer to this query.

# Example
# Input
# 5
# 2 4 2
# 5 10 4
# 3 10 1
# 1 2 3
# 4 6 5

# Output
# 6
# 4
# 1
# 3
# 10

def minimum_integer(queries)
  queries.each do |query|
    query = query.split(' ')

    return 0 unless query.length == 3

    low  = query.first.to_i
    high = query[1].to_i
    div  = query.last.to_i

    puts div < low ? div : high + (div - (high % div))
  end

  return nil
end

# Codeforces required setup
number_of_queries = gets.rstrip.to_i

queries = []

number_of_queries.times do |query|
  queries << gets.rstrip
end

result = minimum_integer queries
puts result

# You are given 𝑞 queries in the following form:

# Given three integers 𝑙𝑖, 𝑟𝑖 and 𝑑𝑖, find minimum
# positive integer 𝑥𝑖 such that it is divisible by 𝑑𝑖 and
# it does not belong to the segment [𝑙𝑖,𝑟𝑖].

# Can you answer all the queries?

# Recall that a number 𝑥 belongs to segment [𝑙,𝑟] if 𝑙≤𝑥≤𝑟.

# Input
# The first line contains one integer 𝑞 (1≤𝑞≤500) — the number of queries.

# Then 𝑞 lines follow, each containing a query given in
# the format 𝑙𝑖 𝑟𝑖 𝑑𝑖 (1≤𝑙𝑖≤𝑟𝑖≤109, 1≤𝑑𝑖≤109). 𝑙𝑖, 𝑟𝑖 and 𝑑𝑖 are integers.

# Output
# For each query print one integer: the answer to this query.

# Example
# Input
# 5
# 2 4 2
# 5 10 4
# 3 10 1
# 1 2 3
# 4 6 5

# Output
# 6
# 4
# 1
# 3
# 10

MAX_NUMBER = 1_000_000_000

def minimum_integer(string)
  numbers = string.split(' ')

  return 0 unless numbers.length == 3

  low  = numbers.first.to_i
  high = numbers[1].to_i
  div  = numbers.last.to_i

  min_int = 0

  if low > 1
    for i in (1..(low - 1)) do
      if i % div == 0
        min_int = i
        break
      end
    end
  end

  return min_int if min_int > 0

  for i in ((high + 1)..MAX_NUMBER) do
    if i % div == 0
      min_int = i
      break
    end
  end

  return min_int
end

# Codeforces required setup
s = gets.rstrip

result = minimum_integer s
puts result

# You are given 𝑞 queries in the following form:

# Given three integers 𝑙𝑖, 𝑟𝑖 and 𝑑𝑖, find minimum
# positive integer 𝑥𝑖 such that it is divisible by 𝑑𝑖 and
# it does not belong to the segment [𝑙𝑖,𝑟𝑖].

# Can you answer all the queries?

# Recall that a number 𝑥 belongs to segment [𝑙,𝑟] if 𝑙≤𝑥≤𝑟.

# Input
# The first line contains one integer 𝑞 (1≤𝑞≤500) — the number of queries.

# Then 𝑞 lines follow, each containing a query given in
# the format 𝑙𝑖 𝑟𝑖 𝑑𝑖 (1≤𝑙𝑖≤𝑟𝑖≤109, 1≤𝑑𝑖≤109). 𝑙𝑖, 𝑟𝑖 and 𝑑𝑖 are integers.

# Output
# For each query print one integer: the answer to this query.

# Example
# Input
# 5
# 2 4 2
# 5 10 4
# 3 10 1
# 1 2 3
# 4 6 5

# Output
# 6
# 4
# 1
# 3
# 10

MAX_NUMBER = 1_000_000_000

def minimum_integer(queries)
  queries.each do |query|
    query = query.split(' ')

    return 0 unless query.length == 3

    low  = query.first.to_i
    high = query[1].to_i
    div  = query.last.to_i

    min_int = 0

    if low > 1
      for i in (1..(low - 1)) do
        if i % div == 0
          min_int = i
          break
        end
      end
    end

    return min_int if min_int > 0

    for i in ((high + 1)..MAX_NUMBER) do
      if i % div == 0
        min_int = i
        break
      end
    end

    puts min_int.to_i
  end
end

# Codeforces required setup
number_of_queries = gets.rstrip.to_i

queries = []

number_of_queries.times do |query|
  queries << gets.rstrip
end

result = minimum_integer queries
puts result

# You are given 𝑞 queries in the following form:

# Given three integers 𝑙𝑖, 𝑟𝑖 and 𝑑𝑖, find minimum
# positive integer 𝑥𝑖 such that it is divisible by 𝑑𝑖 and
# it does not belong to the segment [𝑙𝑖,𝑟𝑖].

# Can you answer all the queries?

# Recall that a number 𝑥 belongs to segment [𝑙,𝑟] if 𝑙≤𝑥≤𝑟.

# Input
# The first line contains one integer 𝑞 (1≤𝑞≤500) — the number of queries.

# Then 𝑞 lines follow, each containing a query given in
# the format 𝑙𝑖 𝑟𝑖 𝑑𝑖 (1≤𝑙𝑖≤𝑟𝑖≤109, 1≤𝑑𝑖≤109). 𝑙𝑖, 𝑟𝑖 and 𝑑𝑖 are integers.

# Output
# For each query print one integer: the answer to this query.

# Example
# Input
# 5
# 2 4 2
# 5 10 4
# 3 10 1
# 1 2 3
# 4 6 5

# Output
# 6
# 4
# 1
# 3
# 10

MAX_NUMBER = 1_000_000_000

def minimum_integer(queries)
  queries.each do |query|
    query = query.split(' ')

    return 0 unless query.length == 3

    low  = query.first.to_i
    high = query[1].to_i
    div  = query.last.to_i

    min_int = 0

    if low > 1
      for i in (1..(low - 1)) do
        if i % div == 0
          min_int = i
          break
        end
      end
    end

    if min_int == 0
      for i in ((high + 1)..MAX_NUMBER) do
        if i % div == 0
          min_int = i
          break
        end
      end
    end

    puts min_int.to_i
  end

  return nil
end

# Codeforces required setup
number_of_queries = gets.rstrip.to_i

queries = []

number_of_queries.times do |query|
  queries << gets.rstrip
end

result = minimum_integer queries
puts result

# You are given 𝑞 queries in the following form:

# Given three integers 𝑙𝑖, 𝑟𝑖 and 𝑑𝑖, find minimum
# positive integer 𝑥𝑖 such that it is divisible by 𝑑𝑖 and
# it does not belong to the segment [𝑙𝑖,𝑟𝑖].

# Can you answer all the queries?

# Recall that a number 𝑥 belongs to segment [𝑙,𝑟] if 𝑙≤𝑥≤𝑟.

# Input
# The first line contains one integer 𝑞 (1≤𝑞≤500) — the number of queries.

# Then 𝑞 lines follow, each containing a query given in
# the format 𝑙𝑖 𝑟𝑖 𝑑𝑖 (1≤𝑙𝑖≤𝑟𝑖≤109, 1≤𝑑𝑖≤109). 𝑙𝑖, 𝑟𝑖 and 𝑑𝑖 are integers.

# Output
# For each query print one integer: the answer to this query.

# Example
# Input
# 5
# 2 4 2
# 5 10 4
# 3 10 1
# 1 2 3
# 4 6 5

# Output
# 6
# 4
# 1
# 3
# 10

MAX_NUMBER = 1_000_000_000

def minimum_integer(queries)
  queries.each do |query|
    query = query.split(' ')

    return 0 unless query.length == 3

    low  = query.first.to_i
    high = query[1].to_i
    div  = query.last.to_i

    min_int = 0

    if low > 1
      for i in (1..(low - 1)) do
        if i % div == 0
          min_int = i
          break
        end
      end
    end

    if min_int == 0
      for i in ((high + 1)..Float::INFINITY) do
        if i % div == 0
          min_int = i
          break
        end
      end
    end

    puts min_int.to_i
  end
end

# Codeforces required setup
number_of_queries = gets.rstrip.to_i

queries = []

number_of_queries.times do |query|
  queries << gets.rstrip
end

result = minimum_integer queries
puts result


Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:  There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.  The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.  After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.  The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament. You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.Write the code that calculates for each knight, the name of the knight that beat him.

The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight. It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.

Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.

NoteConsider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won.

input = lambda {
  gets.chomp.split.map(&:to_i)
}

n , m = input.call

next_i = (1..n).to_a + [-1]
whoKilled = [0] * (n+1)

m.times do
  l , r , w = input.call
  while l <= r && l != -1
    x = next_i[l]
    if l < w
      whoKilled[l] = w if whoKilled[l] == 0
      next_i[l] = w
    elsif l > w
      whoKilled[l] = w if whoKilled[l] == 0
      next_i[l] = next_i[r]
    end
    l = x
  end
end

print whoKilled[1..n].join(" ")


Bob watches TV every day. He always sets the volume of his TV to $$$b$$$. However, today he is angry to find out someone has changed the volume to $$$a$$$. Of course, Bob has a remote control that can change the volume.There are six buttons ($$$-5, -2, -1, +1, +2, +5$$$) on the control, which in one press can either increase or decrease the current volume by $$$1$$$, $$$2$$$, or $$$5$$$. The volume can be arbitrarily large, but can never be negative. In other words, Bob cannot press the button if it causes the volume to be lower than $$$0$$$.As Bob is so angry, he wants to change the volume to $$$b$$$ using as few button presses as possible. However, he forgets how to do such simple calculations, so he asks you for help. Write a program that given $$$a$$$ and $$$b$$$, finds the minimum number of presses to change the TV volume from $$$a$$$ to $$$b$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$T$$$ ($$$1 \le T \le 1\,000$$$). Then the descriptions of the test cases follow. Each test case consists of one line containing two integers $$$a$$$ and $$$b$$$ ($$$0 \le a, b \le 10^{9}$$$) — the current volume and Bob's desired volume, respectively.

For each test case, output a single integer — the minimum number of presses to change the TV volume from $$$a$$$ to $$$b$$$. If Bob does not need to change the volume (i.e. $$$a=b$$$), then print $$$0$$$.

NoteIn the first example, Bob can press the $$$-2$$$ button twice to reach $$$0$$$. Note that Bob can not press $$$-5$$$ when the volume is $$$4$$$ since it will make the volume negative. In the second example, one of the optimal ways for Bob is to press the $$$+5$$$ twice, then press $$$-1$$$ once.In the last example, Bob can press the $$$+5$$$ once, then press $$$+1$$$.

t = gets.chomp.to_i
t.times do |testcase|
    a,b = gets.split.map(&:to_i)
    c = (a-b).abs
    puts ( c/5 + (c%5)/2 + (c%5)%2 )
end

t = gets.to_i
op = [-5, 2, -1, 1, 2, 5]
t.times do
  a, b = gets.split.map(&:to_i)
  ans = (a-b).abs/5
  a += (a-b) < 0 ? ans*5 : -ans*5
  if (a-b).abs == 0
  elsif (a-b).abs <= 2
    ans += 1
  else
    ans += 2
  end
  puts ans
end

def lol
	b, a = gets.chomp.split(" ").map { |e| e.to_i}
	if a > b
		a -= b
	else
		a = b - a
	end
	k = a/5
	if a%5 == 0
		p k
	elsif a%5 == 1
		p k + 1
	elsif a%5 == 2
		p k + 1
	elsif a%5 == 3
		p k + 2
	elsif a%5 == 4
		p k + 2
	end

end

n = gets.chomp.to_i

n.times do
	lol
end


You are given a bracket sequence $$$s$$$ of length $$$n$$$, where $$$n$$$ is even (divisible by two). The string $$$s$$$ consists of $$$\frac{n}{2}$$$ opening brackets '(' and $$$\frac{n}{2}$$$ closing brackets ')'.In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index $$$i$$$, remove the $$$i$$$-th character of $$$s$$$ and insert it before or after all remaining characters of $$$s$$$).Your task is to find the minimum number of moves required to obtain regular bracket sequence from $$$s$$$. It can be proved that the answer always exists under the given constraints.Recall what the regular bracket sequence is:  "()" is regular bracket sequence;  if $$$s$$$ is regular bracket sequence then "(" + $$$s$$$ + ")" is regular bracket sequence;  if $$$s$$$ and $$$t$$$ are regular bracket sequences then $$$s$$$ + $$$t$$$ is regular bracket sequence. For example, "()()", "(())()", "(())" and "()" are regular bracket sequences, but ")(", "()(" and ")))" are not.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$2 \le n \le 50$$$) — the length of $$$s$$$. It is guaranteed that $$$n$$$ is even. The second line of the test case containg the string $$$s$$$ consisting of $$$\frac{n}{2}$$$ opening and $$$\frac{n}{2}$$$ closing brackets.

For each test case, print the answer — the minimum number of moves required to obtain regular bracket sequence from $$$s$$$. It can be proved that the answer always exists under the given constraints.

NoteIn the first test case of the example, it is sufficient to move the first bracket to the end of the string.In the third test case of the example, it is sufficient to move the last bracket to the beginning of the string.In the fourth test case of the example, we can choose last three openning brackets, move them to the beginning of the string and obtain "((()))(())".

gets.to_i.times do
	n = gets.to_i
	s = gets.chomp
	while s.gsub!('()', ''); end
	puts s.size / 2
end

t = (gets || "").to_i
t.times do
	cnt = 0
	neg = 0
	n = (gets || "").to_i
	s = (gets || "").chomp

	s.each_char do |c|
		case c
		when '('
			cnt += 1
		when ')'
			cnt -= 1
		end
		if cnt < 0
			neg -= cnt
			cnt = 0
		end
	end

	p [neg, cnt].max
end

def run
  n = gets.chomp.to_i
  s = gets.chomp
  st = 0
  min_st = 0

  s.each_char do |ch|
    if ch == "("
      st += 1
    else
      st -= 1
      if st < min_st
        min_st = st
      end
    end
  end

  puts min_st.abs
end

def main
  t = gets.chomp.to_i

  t.times do
    run
  end
end

main

n = gets.chomp.to_i
n.times do
    nn = gets.chomp.to_i
    arr = Array.new(nn,0)
    kakko = gets.chomp.split("")
    mezirusi = 1
    count = 0
        while true
        if kakko[mezirusi-1] == "(" && kakko[mezirusi] == ")"
            kakko[mezirusi-1] = " "
            kakko[mezirusi] = " "
            kakko = kakko.join("").gsub(" ", "")
            kakko = kakko.split("")
            ookisa = kakko.size
            if kakko == []
                kakko_size = 0
                break
            end
             mezirusi = 1
        else
            mezirusi += 1
            if kakko[mezirusi] == nil
                break
            end
        end

    end
    kakko_size = kakko.size
    if  kakko.count("(") != kakko.count(")")
        puts "-1"
        next
    elsif kakko_size % 2 == 0
        puts kakko_size /2
        next
    end
end

n = gets.chomp.to_i
n.times do
    nn = gets.chomp.to_i
    arr = Array.new(nn,0)
    kakko = gets.chomp.split("")
#p kakko
    mezirusi = 1
    #while
    count = 0
    #2.times do
        while true
        if kakko[mezirusi-1] == "(" && kakko[mezirusi] == ")"
            kakko[mezirusi-1] = " "
            kakko[mezirusi] = " "
            kakko = kakko.join("").gsub(" ", "")
            #p kakko
            kakko = kakko.split("")
           # p kakko
            ookisa = kakko.size
           #kakko = kakko.delte(" ")
            #p kakko
            if kakko == []
                kakko_size = 0
                break
            end
            #mezirusi -= 1
            # if kakko[mezirusi] == nil && mezirusi >= 1
            #     mezirusi -= 1
            # end
             mezirusi = 1
        else
            mezirusi += 1
            #p mezirusi
            #puts "UU"
            if kakko[mezirusi] == nil
                break
            end
        end

    end
    #p kakko.size
    #puts "UUUUUUUUU"
    kakko_size = kakko.size
    # p kakko
    # p kakko.count("(")
    if  kakko.count("(") != kakko.count(")")
        puts "-1"
        next
    elsif kakko_size % 2 == 0
        puts kakko_size /2
        next
    end

end

n = gets.chomp.to_i
n.times do
    nn = gets.chomp.to_i
    kakko = gets.chomp.split("")
    mezirusi = 1
        while true
            if kakko[mezirusi-1] == "(" && kakko[mezirusi] == ")"
                kakko[mezirusi-1] = " "
                kakko[mezirusi] = " "
                kakko = kakko.join("").gsub(" ", "")
                kakko = kakko.split("")
                ookisa = kakko.size
                if kakko == []
                    kakko_size = 0
                    break
                end
                mezirusi = 1
            else
                mezirusi += 1
                if kakko[mezirusi] == nil
                    break
                end
            end
        end
    kakko_size = kakko.size
        if  kakko.count("(") != kakko.count(")")
            puts "-1"
            next
        else
            puts kakko_size /2
            next
        end
end

t = gets.chomp.to_i

for i in 1..t
    n = gets.chomp.to_i
    s = gets.chomp

    p = 0
    c = 0
    for j in 0..n-1
        ch = s[j]
        if ch == '('
            c+=1
        else
            c-=1
        end

        if c < 0
            p+=1
            c = 0
        end
    end
    puts p
end

gets.to_i.times do
  ans = 0
  n = gets.to_i
  s = gets.chomp
  s.chars.inject(0) do |state, x|
    state += 1 if x == '('
    state -= 1 if x == ')'
    if state < 0
      state += 1
      ans += 1
    end
    state
  end
  puts ans
end

gets.to_i.times do
  gets
  a = gets.chomp.split('')
  result = 0

  while !a.size.zero?
    x = a.shift

    case x
    when '('
      a.delete_at(a.index(')')) if a.index(')')
    when ')'
      result += 1
    end
  end

  puts result
end

n = gets.chomp.to_i
n.times do
    nn = gets.chomp.to_i
    arr = Array.new(nn,0)
    kakko = gets.chomp.split("")
p kakko
    mezirusi = 1
    #while
    count = 0
    #2.times do
        while true
        if kakko[mezirusi-1] == "(" && kakko[mezirusi] == ")"
            kakko[mezirusi-1] = " "
            kakko[mezirusi] = " "
            kakko = kakko.join("").gsub(" ", "")
            #p kakko
            kakko = kakko.split("")
           # p kakko
            ookisa = kakko.size
           #kakko = kakko.delte(" ")
            #p kakko
            if kakko == []
                kakko_size = 0
                break
            end
            #mezirusi -= 1
            if kakko[mezirusi] == nil && mezirusi >= 1
                mezirusi -= 1
            end
            #p mezirusi
        else
            mezirusi += 1
            #p mezirusi
            #puts "UU"
            if kakko[mezirusi] == nil
                break
            end
        end

    end
    #p kakko.size
    #puts "UUUUUUUUU"
    kakko_size = kakko.size
    if kakko_size % 2 == 1
        puts "-1"
    elsif kakko_size % 2 == 0
        puts kakko_size /2
    end

end

n = gets.chomp.to_i
n.times do
    nn = gets.chomp.to_i
    arr = Array.new(nn,0)
    kakko = gets.chomp.split("")
#p kakko
    mezirusi = 1
    #while
    #count = 0
    #2.times do
        while true
        if kakko[mezirusi-1] == "(" && kakko[mezirusi] == ")"
            kakko[mezirusi-1] = " "
            kakko[mezirusi] = " "
            kakko = kakko.join("").gsub(" ", "")
            #p kakko
            kakko = kakko.split("")
           # p kakko
            ookisa = kakko.size
           #kakko = kakko.delte(" ")
            #p kakko
            if kakko == []
                kakko_size = 0
                break
            end
            #mezirusi -= 1
            if kakko[mezirusi] == nil && mezirusi >= 1
                mezirusi -= 1
            end
            #p mezirusi
        else
            mezirusi += 1
            #p mezirusi
            #puts "UU"
            if kakko[mezirusi] == nil
                break
            end
        end

    end
    #p kakko.size
    #puts "UUUUUUUUU"
    kakko_size = kakko.size
    # p kakko
    # p kakko.count("(")
    if  kakko.count("(") != kakko.count(")")
        puts "-1"
        next
    elsif kakko_size % 2 == 0
        puts kakko_size /2
        next
    end

end

n = gets.chomp.to_i
n.times do
    nn = gets.chomp.to_i
    arr = Array.new(nn,0)
    kakko = gets.chomp.split("")
#p kakko
    mezirusi = 1
    #while
    count = 0
    #2.times do
        while true
        if kakko[mezirusi-1] == "(" && kakko[mezirusi] == ")"
            kakko[mezirusi-1] = " "
            kakko[mezirusi] = " "
            kakko = kakko.join("").gsub(" ", "")
            #p kakko
            kakko = kakko.split("")
           # p kakko
            ookisa = kakko.size
           #kakko = kakko.delte(" ")
            #p kakko
            if kakko == []
                kakko_size = 0
                break
            end
            #mezirusi -= 1
            if kakko[mezirusi] == nil && mezirusi >= 1
                mezirusi -= 1
            end
            #p mezirusi
        else
            mezirusi += 1
            #p mezirusi
            #puts "UU"
            if kakko[mezirusi] == nil
                break
            end
        end

    end
    #p kakko.size
    #puts "UUUUUUUUU"
    kakko_size = kakko.size
    # p kakko
    # p kakko.count("(")
    if  kakko.count("(") != kakko.count(")")
        puts "-1"
        next
    elsif kakko_size % 2 == 0
        puts kakko_size /2
        next
    end

end

n = gets.chomp.to_i
n.times do
    nn = gets.chomp.to_i
    arr = Array.new(nn,0)
    kakko = gets.chomp.split("")
#p kakko
    mezirusi = 1
    #while
    count = 0
    #2.times do
        while true
        if kakko[mezirusi-1] == "(" && kakko[mezirusi] == ")"
            kakko[mezirusi-1] = " "
            kakko[mezirusi] = " "
            kakko = kakko.join("").gsub(" ", "")
            #p kakko
            kakko = kakko.split("")
           # p kakko
            ookisa = kakko.size
           #kakko = kakko.delte(" ")
            #p kakko
            if kakko == []
                kakko_size = 0
                break
            end
            #mezirusi -= 1
            if kakko[mezirusi] == nil && mezirusi >= 1
                mezirusi -= 1
            end
            #p mezirusi
        else
            mezirusi += 1
            #p mezirusi
            #puts "UU"
            if kakko[mezirusi] == nil
                break
            end
        end

    end
    #p kakko.size
    #puts "UUUUUUUUU"
    kakko_size = kakko.size
    # p kakko
    # p kakko.count("(")
    if  kakko.count("(") != kakko.count(")")
        puts "-1"
    elsif kakko_size % 2 == 0
        puts kakko_size /2
    end

end

n = gets.chomp.to_i
n.times do
    nn = gets.chomp.to_i
    arr = Array.new(nn,0)
    kakko = gets.chomp.split("")
#p kakko
    mezirusi = 1
    #while
    count = 0
    #2.times do
        while true
        if kakko[mezirusi-1] == "(" && kakko[mezirusi] == ")"
            kakko[mezirusi-1] = " "
            kakko[mezirusi] = " "
            kakko = kakko.join("").gsub(" ", "")
            #p kakko
            kakko = kakko.split("")
           # p kakko
            ookisa = kakko.size
           #kakko = kakko.delte(" ")
            p kakko
            if kakko == []
                kakko_size = 0
                break
            end
            #mezirusi -= 1
            # if kakko[mezirusi] == nil && mezirusi >= 1
            #     mezirusi -= 1
            # end
             mezirusi = 1
        else
            mezirusi += 1
            #p mezirusi
            #puts "UU"
            if kakko[mezirusi] == nil
                break
            end
        end

    end
    #p kakko.size
    #puts "UUUUUUUUU"
    kakko_size = kakko.size
    # p kakko
    # p kakko.count("(")
    if  kakko.count("(") != kakko.count(")")
        puts "-1"
        next
    elsif kakko_size % 2 == 0
        puts kakko_size /2
        next
    end

end

n = gets.chomp.to_i
n.times do
    nn = gets.chomp.to_i
    arr = Array.new(nn,0)
    kakko = gets.chomp.split("")
#p kakko
    mezirusi = 1
    #while
    count = 0
    #2.times do
        while true
        if kakko[mezirusi-1] == "(" && kakko[mezirusi] == ")"
            kakko[mezirusi-1] = " "
            kakko[mezirusi] = " "
            kakko = kakko.join("").gsub(" ", "")
            #p kakko
            kakko = kakko.split("")
           # p kakko
            ookisa = kakko.size
           #kakko = kakko.delte(" ")
            #p kakko
            if kakko == []
                kakko_size = 0
                break
            end
            #mezirusi -= 1
            if kakko[mezirusi] == nil && mezirusi >= 1
                mezirusi -= 1
            end
            #p mezirusi
        else
            mezirusi += 1
            #p mezirusi
            #puts "UU"
            if kakko[mezirusi] == nil
                break
            end
        end

    end
    #p kakko.size
    #puts "UUUUUUUUU"
    kakko_size = kakko.size
    if kakko_size % 2 == 1
        puts "-1"
    elsif kakko_size % 2 == 0
        puts kakko_size /2
    end

end

class String
  def regular_bracket_sequence?
    if self.chars.inject(0) do |state, c|
      state += 1 if c == '('
      state -= 1 if c == ')'
      break false if state < 0
      state
    end then true else false end
  end
end
gets.to_i.times do
  ans = 0
  n = gets.to_i
  s = gets.chomp
  while not s.regular_bracket_sequence? do
    ans += 1
    idx = s.index(')')
    s[idx, idx + 1] = ''
    s << ')'
  end
  puts ans
end


A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of n painters who decided to organize their work as follows.Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1, the second one uses color 2, and so on. Each picture will contain all these n colors. Adding the j-th color to the i-th picture takes the j-th painter tij units of time.Order is important everywhere, so the painters' work is ordered by the following rules:  Each picture is first painted by the first painter, then by the second one, and so on. That is, after the j-th painter finishes working on the picture, it must go to the (j + 1)-th painter (if j < n);  each painter works on the pictures in some order: first, he paints the first picture, then he paints the second picture and so on;  each painter can simultaneously work on at most one picture. However, the painters don't need any time to have a rest;  as soon as the j-th painter finishes his part of working on the picture, the picture immediately becomes available to the next painter. Given that the painters start working at time 0, find for each picture the time when it is ready for sale.

The first line of the input contains integers m, n (1 ≤ m ≤ 50000, 1 ≤ n ≤ 5), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers ti1, ti2, ..., tin (1 ≤ tij ≤ 1000), where tij is the time the j-th painter needs to work on the i-th picture.

Print the sequence of m integers r1, r2, ..., rm, where ri is the moment when the n-th painter stopped working on the i-th picture.

m,n=gets.chomp.split.map(&:to_i)
t=[0,0,0,0,0]
m.times do
	a=gets.chomp.split.map(&:to_i)
	a.length.times {|j| (j!=0 && t[j]<t[j-1]) ? (t[j]=t[j-1]+a[j]) : (t[j]+=a[j]) }
	print "#{t[n-1]} "
end
puts

def run
  m, n = $stdin.gets.split.map(&:to_i)
  t = $stdin.readlines.map do |line|
    line.chomp.split.map(&:to_i)
  end

  a = []
  m.times do |i|
    a << []
  end

  count = 0
  m.times do |j|
    count += t[j][0]
    a[j][0] = count
  end

  1.upto(n - 1) do |i|
    m.times do |j|
      x = a[j][i - 1] || 0
      y = a[j - 1][i] || 0
      max = [x, y].max
      a[j][i] = max + t[j][i]
    end
  end

  puts a.map { |x| x.last}.join(" ")
end

run if $0 == __FILE__

m,n = gets.split(" ").map(&:to_i)
arr = []
m.times do
	arr << gets.split(" ").map(&:to_i)
end
dp = []

arr.each_with_index do |a,i|
	dp << []
	a.each_with_index do |ele,j|
		calc = [0]
		calc << dp[i][j-1] if j > 0
		calc << dp[i-1][j] if i > 0

		dp[i][j] = calc.max + arr[i][j]
	end
end

ans = []
dp.each do |a|
	ans << a[-1]
end
puts ans.join(" ")


Little time is left before Berland annual football championship. Therefore the coach of team "Losewille Rangers" decided to resume the practice, that were indefinitely interrupted for uncertain reasons. Overall there are n players in "Losewille Rangers". Each player on the team has a number — a unique integer from 1 to n. To prepare for the championship, the coach Mr. Floppe decided to spend some number of practices.Mr. Floppe spent some long nights of his holiday planning how to conduct the practices. He came to a very complex practice system. Each practice consists of one game, all n players of the team take part in the game. The players are sorted into two teams in some way. In this case, the teams may have different numbers of players, but each team must have at least one player.The coach wants to be sure that after the series of the practice sessions each pair of players had at least one practice, when they played in different teams. As the players' energy is limited, the coach wants to achieve the goal in the least number of practices.Help him to schedule the practices.

A single input line contains integer n (2 ≤ n ≤ 1000).

In the first line print m — the minimum number of practices the coach will have to schedule. Then print the descriptions of the practices in m lines. In the i-th of those lines print fi — the number of players in the first team during the i-th practice (1 ≤ fi < n), and fi numbers from 1 to n — the numbers of players in the first team. The rest of the players will play in the second team during this practice. Separate numbers on a line with spaces. Print the numbers of the players in any order. If there are multiple optimal solutions, print any of them.

if ENV['USER'] != 'watashi'
  $stdin = open('input.txt')
  $> = open('output.txt', 'w')
end

n = gets.to_i
m = 0
a = []
while 1 << m < n
  a << [*1..n].select{|_| _[m] == 1}
  m += 1
end

p a.size
a.each{|_|
  puts "#{_.size} #{_ * ' '}"
}