You are given an array $$$a$$$ of $$$n$$$ elements. You can apply the following operation to it any number of times:  Select some subarray from $$$a$$$ of even size $$$2k$$$ that begins at position $$$l$$$ ($$$1\le l \le l+2\cdot{k}-1\le n$$$, $$$k \ge 1$$$) and for each $$$i$$$ between $$$0$$$ and $$$k-1$$$ (inclusive), assign the value $$$a_{l+k+i}$$$ to $$$a_{l+i}$$$. For example, if $$$a = [2, 1, 3, 4, 5, 3]$$$, then choose $$$l = 1$$$ and $$$k = 2$$$, applying this operation the array will become $$$a = [3, 4, 3, 4, 5, 3]$$$.Find the minimum number of operations (possibly zero) needed to make all the elements of the array equal.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 2 \cdot 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the array. The second line of each test case consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq n$$$) — the elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

Print $$$t$$$ lines, each line containing the answer to the corresponding test case — the minimum number of operations needed to make equal all the elements of the array with the given operation.

NoteIn the first test, all elements are equal, therefore no operations are needed.In the second test, you can apply one operation with $$$k=1$$$ and $$$l=1$$$, set $$$a_1 := a_2$$$, and the array becomes $$$[1, 1]$$$ with $$$1$$$ operation.In the third test, you can apply one operation with $$$k=1$$$ and $$$l=4$$$, set $$$a_4 := a_5$$$, and the array becomes $$$[4, 4, 4, 4, 4]$$$.In the fourth test, you can apply one operation with $$$k=1$$$ and $$$l=3$$$, set $$$a_3 := a_4$$$, and the array becomes $$$[4, 2, 3, 3]$$$, then you can apply another operation with $$$k=2$$$ and $$$l=1$$$, set $$$a_1 := a_3$$$, $$$a_2 := a_4$$$, and the array becomes $$$[3, 3, 3, 3]$$$.In the fifth test, there is only one element, therefore no operations are needed.

t = gets.chomp.to_i

for i in (1..t)
    n = gets.chomp.to_i
    a = (gets.chomp.split.map {|e| e.to_i}).reverse
    x = 0
    for j in (1..n-1)
        if a[j] != a[0]
            break
        end
        x += 1
    end
    ans = 0
    until x >= n-1
        # Aplique a operacao em que os valores (0, x) são copiados para (x+1, 2x+1)
        x = [n-1, 2*x+1].min
        ans += 1
        for j in (x+1..n-1)
            if a[j] != a[0]
                break
            end
            x += 1
        end
    end
    puts ans
end

gets.to_i.times do
  n = gets.to_i
  xs = gets.split.map(&:to_i)

  ans = 0
  g = n - 1

  while g > 0
    if xs[g - 1] == xs[n - 1]
      g -= 1
    else
      g = 2 * g - n
      ans += 1
    end
  end

  p ans
end


Vanya is doing his maths homework. He has an expression of form , where x1, x2, ..., xn are digits from 1 to 9, and sign  represents either a plus '+' or the multiplication sign '*'. Vanya needs to add one pair of brackets in this expression so that to maximize the value of the resulting expression.

The first line contains expression s (1 ≤ |s| ≤ 5001, |s| is odd), its odd positions only contain digits from 1 to 9, and even positions only contain signs  +  and  * .  The number of signs  *  doesn't exceed 15.

In the first line print the maximum possible value of an expression.

NoteNote to the first sample test. 3 + 5 * (7 + 8) * 4 = 303.Note to the second sample test. (2 + 3) * 5 = 25.Note to the third sample test. (3 * 4) * 5 = 60 (also many other variants are valid, for instance, (3) * 4 * 5 = 60).

def max(a,b)
    return a>b ? a : b
end

s=gets
n=s.length
res=eval(s)
for i in -1..n-1 do
    if i==-1 || s[i]=='*'
        for j in i+1..n do
            if j==n || s[j]=='*'
                res=max(res,eval(s[0...i+1]+'('+s[i+1...j]+')'+s[j...n]))
            end
        end
    end
end
puts res

s = gets.chomp.to_s
s = "1*" + s + "*1"
#p s
a = (0...s.length).find_all{ |i| s[i] == '*' }
ans = -1
for i in a
 for j in a
   if( i != j )
     if( i < j )
     k = i
     else k = j
     end
     l = i + j - k
     x = s[0..k] + "(" + s[k+1..l-1] + ")" + s[l..s.length]
 #        p "#{x}  #{i}  #{j} #{k} #{l} "
     if( eval(x) > ans )
      ans = eval(x)
     end
   end
 end
end
puts ans

c = gets.strip
max = eval(c)

lpos = [0]
rpos = [c.length]
c.chars.each_with_index do |ci, idx|
  if ci == '*'
    lpos.push idx + 1
    rpos.push idx
  end
end

lpos.each do |l|
  rpos.each do |r|
    next if l > r
    exp = c[0...l] + '(' + c[l...r] + ')' + c[r...c.length]
    max = [max, eval(exp)].max
  end
end
p max

def max(a,b)
    return a>b ? a : b
end

s=gets
n=s.length
res=eval(s)
for i in -1..n-1 do
    if i==-1 || s[i]=='*'
        for j in i+1..n do
            if j==n || s[j]=='*'
                res=max(res,eval(s[0,i+1]+'('+s[i+1,j]+')'+s[j,n-1]))
            end
        end
    end
end
puts res


The city administration of IT City decided to fix up a symbol of scientific and technical progress in the city's main square, namely an indicator board that shows the effect of Moore's law in real time.Moore's law is the observation that the number of transistors in a dense integrated circuit doubles approximately every 24 months. The implication of Moore's law is that computer performance as function of time increases exponentially as well.You are to prepare information that will change every second to display on the indicator board. Let's assume that every second the number of transistors increases exactly 1.000000011 times.

The only line of the input contains a pair of integers n (1000 ≤ n ≤ 10 000) and t (0 ≤ t ≤ 2 000 000 000) — the number of transistors in the initial time and the number of seconds passed since the initial time.

Output one number — the estimate of the number of transistors in a dence integrated circuit in t seconds since the initial time. The relative error of your answer should not be greater than 10 - 6.

factor = 1.000000011
n, t = gets.split(" ").map { |x| x.to_i }

ans = n * factor ** t
puts ans.round(16)

arg = STDIN.gets
args = arg.split
n = args[0].to_i
t = args[1].to_i

printf("%.6f", (n * (1.000000011 ** t)))
puts

inp = gets.chomp.split(' ');
n = inp[0].to_i
t = inp[1].to_i

ans = n * (1.000000011 ** t)

p ans

n , t = gets.chomp.split.map(&:to_i)
ans = n
ref = 1.000000011
help = ref ** t
ans = ans * help
puts ans


You are given a text that consists of lowercase Latin letters, spaces and punctuation marks (dot, comma, exclamation mark and question mark). A word is defined as a sequence of consecutive Latin letters.Your task is to add spaces to the text by the following rules:  if there is no punctuation mark between two words, then they should be separated by exactly one space  there should be no spaces before each punctuation mark  there should be exactly one space after each punctuation mark It is guaranteed that there is at least one word between any two punctuation marks. The text begins and ends with a Latin letter.

The input data contains of a single non-empty line — the text whose length is no more than 10000 characters.

Print the text, edited according to the rules. In this problem you should follow the output format very strictly. For example, extra space at the end of the output line is considered as wrong answer. Note that a newline character at the end of the line doesn't matter.

def delp(s)
    k = -1
    while (k = s.index(" ", k+1)) do
        k += 1

        while s[k] == " " do
            s = s[0...k] + s[k+1..-1]
        end
    end
    return s
end

def cpz (s,z)
    str = ""
    while s.size > 0 do
        if (k = s.index(z)) then
            if s[k+1] != " " then
                s = s[0..k] + " " + s[k+1..-1]
            end
            if s[k-1] == " " then
                s = s[0...k-1] + s[k..-1]
            end
            str += s[0..k]
            s = s[k+1..-1]
        else
            str += s
            s = ""
        end
    end
    return str
end

s = gets.chomp
s = delp(s)
s = cpz(s,".")
s = cpz(s,",")
s = cpz(s,"!")
s = cpz(s,"?")
puts s

input=gets
while true
        back=input.length
        input.gsub!("  "," ");
        break if back==input.length
end
input.gsub!(" !","!");
input.gsub!(" ?","?");
input.gsub!(" .",".");
input.gsub!(" ,",",");

for i in 0..25
        t="abcdefghijklmnopqrstuvwxyz"[i]
        input.gsub!("!"+t,"! "+t);
        input.gsub!("?"+t,"? "+t);
        input.gsub!("."+t,". "+t);
        input.gsub!(","+t,", "+t);
end
print input

str=gets
s=str.chars.to_a
res=''
i=0
def isPunc(str)
  a=("a".."z").to_a+("A".."X").to_a
  a.each{|c|
    if str==c then
      return false
    end
    }
    return true
end
while i<str.length do
  if s[i]==" " then
    for j in i+1..s.length-1 do
      if s[j]!=" " then
        if !isPunc(s[j]) then
          res+=" "
        end
        i=j
        break
      end
    end
  elsif isPunc(s[i]) then
    j=0
    for j in i+1..s.length do
      if s[j]!=" " then
        break
      end
    end
    res+=s[i]+" "
    i=j
  else
    res+=s[i]
    i+=1
  end
end
puts res

words = gets.chomp.scan(/[.,!?]|\w+/)
finalString = String.new

words.each { |word|
  if word.match(/[,.?!]/)
    finalString += word
  else
    finalString += ' ' + word
  end
}

puts finalString[1..finalString.length]

words = gets.chomp.scan(/[.,!?]|\w+/)
ans = String.new

words.each do |word|
  if word.match(/[,.?!]/)
    ans += word
  else
    ans += ' ' + word
  end
end

puts ans[1..ans.length]

def punctuation
  str = gets.split(' ').map{|s| s.strip}.join(' ')

  i = 0
  while i < str.length
    if str[i] == '.' or str[i] == ',' or str[i] == '!' or str[i] == '?'
      if str[i-1] == ' '
        str[i-1] = ''
        i -= 1
      end

      unless str[i+1] == ' '
        str = "#{str[0..i]} #{str[i+1..-1]}"
        i += 1
      end
    end
    i += 1
  end

  puts str
  #galileo galilei was an italian physicist, mathematician, astronomer
  #galileo galilei was an italian physicist, mathematician, astronomer
end

punctuation

result = gets
result.strip!
result.gsub!(/\s+/, ' ')
result.gsub!(/([,.!?]+)(\w)/, '\1 \2')
result.gsub!(/(\w)\s+([,.!?]+)/, '\1\2')
print result

#s = "galileo galilei was an   italian physicist  ,mathematician,astronomer"
s = gets
print s.gsub(/ +/,' ').gsub(/ *([,\.!\?]) */, '\1 ')

input = STDIN.read.gsub(/ +/, ' ')

chars = ".,?!:;"

input = input.split(//)

input.each.with_index do |v, k|
	if chars.include? v
		if input[k - 1] == " "
			input[k - 1] = v
			input[k + 1] != " " ? input[k] = " " : input[k] = ""
		elsif input[k + 1] != " "
			input[k] = v + " "
		end
	end
end

STDOUT.puts input.join('')

str=gets
s=str.chars.to_a
res=''
i=0
while i<str.length do
  if s[i]==" " then
    for j in i+1..s.length-1 do
      if s[j]!=" " then
        if s[j]!="," then
          res+=" "
        end
        i=j
        break
      end
    end
  elsif s[i]=="," then
    for j in i+1..s.length do
      if s[j]!=" " then
        i=j
        break
      end
    end
    res+=", "
  else
    res+=s[i]
    i+=1
  end
end
puts res

words = gets.chomp.scan(/[.,?!]?[[:word:]]+/)
finalString = String.new
p words
words.each_index { |index|
  if index+1 != words.length
    if words[index+1][0..0].match(/[.,?!]/)
      puts words[index+1][0..0]
      finalString += ' ' + words[index] + words[index+1][0..0]
      words[index+1] = words[index+1][1..words[index+1].length]
    else
      finalString += ' ' + words[index]
    end

  else
    finalString += ' ' + words[index]
  end
}

puts finalString[1..finalString.length]

words = gets.chomp.scan(/[.,?!]?[[:word:]]+/)
finalString = String.new
words.each_index { |index|
  if index+1 != words.length
    if words[index+1][0..0].match(/[.,?!]/)
      finalString += ' ' + words[index] + words[index+1][0..0]
      words[index+1] = words[index+1][1..words[index+1].length]
    else
      finalString += ' ' + words[index]
    end

  else
    finalString += ' ' + words[index]
  end
}

puts finalString[1..finalString.length]

def punctuation
  str = gets.strip

  str = str.split(' ').map{|s| s.strip}.join(' ')
  fin = ''

  (0...str.length).each do |i|
    if str[i] == '.' or str[i] == ',' or str[i] == '!' or str[i] == '?'
      j = i
      if str[i-1] == ' '
        str[i-1] = ''
        j -= 1
      end
      str = "#{str[0..j]} #{str[j+1..-1]}" unless str[j+1] == ' '
    end
  end

  print str
end

punctuation

def punctuation
  str = gets.strip

  str = str.split(' ').map{|s| s.strip}
  fin = ''
  str.each_with_index do |s, ind|
    fin += " " if ind > 0

    (0...s.size).each do |i|
      if s[i] == '.' or s[i] == ',' or s[i] == '!' or s[i] == '?'
        if i == 0
          fin = "#{fin[0...fin.length-1]}#{s[i]} "
        else
          fin += "#{s[i]} "
        end
      else
        fin += s[i]
      end
    end
  end

  puts fin
end

def punctuation
  str = "galileo galilei was an   italian physicist  ,mathematician,astronomer"#gets.strip

  str = str.split(' ').map{|s| s.strip}
  fin = ''
  str.each_with_index do |s, ind|
    fin += " " if ind > 0

    (0...s.size).each do |i|
      if s[i] == '.' or s[i] == ',' or s[i] == '!' or s[i] == '?'
        fin = "#{fin[0...fin.length-1]}#{s[i]} "
      else
        fin += s[i]
      end
    end
  end

  p fin
end

punctuation

def punctuation
  str = gets.strip

  str = str.split(' ').map{|s| s.strip}
  fin = ''
  str.each_with_index do |s, ind|
    fin += " " if ind > 0

    (0...s.size).each do |i|
      if s[i] == '.' or s[i] == ',' or s[i] == '!' or s[i] == '?'
        if i == 0
          fin = "#{fin[0...fin.length-1]}#{s[i]} "
        else
          fin += "#{s[i]} "
        end
      else
        fin += s[i]
      end
    end
  end

  puts fin# == 'galileo galilei was an italian physicist, mathematician, astronomer'
end

def punctuation
  str = gets.strip

  str = str.split(' ').map{|s| s.strip}
  fin = ''
  str.each_with_index do |s, ind|
    fin += " " if ind > 0

    (0...s.size).each do |i|
      if s[i] == '.' or s[i] == ',' or s[i] == '!' or s[i] == '?'
        fin = "#{fin[0...fin.length-1]}#{s[i]} "
      else
        fin += s[i]
      end
    end
  end

  puts fin
end

punctuation

def punctuation
  str = gets.strip

  str = str.split(' ').map{|s| s.strip}.join(' ')
  fin = ''

  i = 0
  while i < str.length
    if str[i] == '.' or str[i] == ',' or str[i] == '!' or str[i] == '?'
      if str[i-1] == ' '
        str[i-1] = ''
        i -= 1
      end

      unless str[i+1] == ' '
        str = "#{str[0..i]} #{str[i+1..-1]}"
        i += 1
      end
    end
    i += 1
  end

  print str
end

def punctuation
  str = gets.strip

  str = str.split(' ').map{|s| s.strip}
  fin = ''
  str.each_with_index do |s, ind|
    fin += " " if ind > 0

    (0...s.size).each do |i|
      if s[i] == '.' or s[i] == ',' or s[i] == '!' or s[i] == '?'
        if i == 0
          fin = "#{fin[0...fin.length-1]}#{s[i]} "
        else
          fin += "#{s[i]} "
        end
      else
        fin += s[i]
      end
    end
  end

  print fin
end

punctuation

def punctuation
  str = gets.strip

  str = str.split(' ').map{|s| s.strip}
  fin = ''
  str.each_with_index do |s, ind|
    fin += " " if ind > 0

    (0...s.size).each do |i|
      if s[i] == '.' or s[i] == ',' or s[i] == '!' or s[i] == '?'
        fin = "#{fin[0...fin.length-1]}#{s[i]} "
      else
        fin += s[i]
      end
    end
  end

  p fin
end

punctuation

input = STDIN.read

input.gsub!(/ +/, ' ')

input.each_char.with_index do |v, k|
	if v == ","
		if input[k - 1] == " "
			input[k] = " "
			input[k - 1] = ","
		elsif input[k + 1] != " "
			input[k] = ", "
		end
	end
end

STDOUT.puts input

input = STDIN.read.gsub(/ +/, ' ')

chars = ".,?!:;"

input.each_char.with_index do |v, k|
	if chars.include? v
		if input[k - 1] == " "
			input[k - 1] = v
			input[k + 1] != " " ? input[k] = " " : input[k] = ""
		elsif input[k + 1] != " "
			input[k] = v + " "
		end
	end
end

STDOUT.puts input


New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows $$$h$$$ hours and $$$m$$$ minutes, where $$$0 \le hh < 24$$$ and $$$0 \le mm < 60$$$. We use 24-hour time format!Your task is to find the number of minutes before the New Year. You know that New Year comes when the clock shows $$$0$$$ hours and $$$0$$$ minutes.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1439$$$) — the number of test cases. The following $$$t$$$ lines describe test cases. The $$$i$$$-th line contains the time as two integers $$$h$$$ and $$$m$$$ ($$$0 \le h < 24$$$, $$$0 \le m < 60$$$). It is guaranteed that this time is not a midnight, i.e. the following two conditions can't be met at the same time: $$$h=0$$$ and $$$m=0$$$. It is guaranteed that both $$$h$$$ and $$$m$$$ are given without leading zeros.

For each test case, print the answer on it — the number of minutes before the New Year.

readline.to_i.times do
  h, m = readline.split.map(&:to_i)
  p((24-h)*60-m)
end

gets.to_i.times do
	a, b = gets.split.map(&:to_i)
	puts 24 * 60 - (a * 60 + b)
end

gets.strip.to_i.times do
  h, m = gets.strip.split(' ').map(&:to_i)
  puts 24 * 60 - (h * 60 + m)
end

gets.to_i.times do
  h, m = gets.split.map(&:to_i)
  puts (23*60+60)-(h*60+m)
end

#exec({'RUBY_THREAD_VM_STACK_SIZE'=>'100000000'},'/usr/bin/ruby', $0) if !ENV['RUBY_THREAD_VM_STACK_SIZE']

def inpf() a=gets.chomp.split(" ").map(&:to_f)end

def inps() a=gets.chomp.split(" ")end

def copy(a) Marshal.load(Marshal.dump(a)) end

def kaijo(n,r = 10**9+7)(n < 2)? 1 : (2..n).inject{|memo,u|memo=(memo*u)%r} end

def na(n,d=0) Array.new(n,d)end

def na2(n,m,d=0) Array.new(n){Array.new(m,d)}end

def na3(n,m,l,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end

def inp() a=gets.chomp.split(" ").map(&:to_i)end

def r_up(a, b) (a+b-1)/b end

def sum(a) a.inject(:+) end

def big(a,b) return (a>b)? a:b end

def small(a,b) return (a<b)? a:b end

n = inp[0]

n.times do |i|
  h,m = inp
  p (23-h)*60+(60-m)
end

# coding: utf-8

# if __FILE__ == $0
# end

gets.to_i.times {
    hh, mm = gets.split.map(&:to_i)
    puts (23 - hh) * 60 + (60 - mm)
}

t=gets.to_i
t.times do
    h,m=gets.split.map(&:to_i)
    puts (23-h)*60 + 60-m
end

1.upto(gets.to_i) do
  h, m = gets.split(' ').map(&:to_i)

  puts (23-h)*60 + (60-m)
end


On the number line there are $$$m$$$ points, $$$i$$$-th of which has integer coordinate $$$x_i$$$ and integer weight $$$w_i$$$. The coordinates of all points are different, and the points are numbered from $$$1$$$ to $$$m$$$.A sequence of $$$n$$$ segments $$$[l_1, r_1], [l_2, r_2], \dots, [l_n, r_n]$$$ is called system of nested segments if for each pair $$$i, j$$$ ($$$1 \le i < j \le n$$$) the condition $$$l_i < l_j < r_j < r_i$$$ is satisfied. In other words, the second segment is strictly inside the first one, the third segment is strictly inside the second one, and so on.For a given number $$$n$$$, find a system of nested segments such that:  both ends of each segment are one of $$$m$$$ given points;  the sum of the weights $$$2\cdot n$$$ of the points used as ends of the segments is minimal. For example, let $$$m = 8$$$. The given points are marked in the picture, their weights are marked in red, their coordinates are marked in blue. Make a system of three nested segments:  weight of the first segment: $$$1 + 1 = 2$$$  weight of the second segment: $$$10 + (-1) = 9$$$  weight of the third segment: $$$3 + (-2) = 1$$$  sum of the weights of all the segments in the system: $$$2 + 9 + 1 = 12$$$     System of three nested segments

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of input test cases. An empty line is written before each test case. The first line of each test case contains two positive integers $$$n$$$ ($$$1 \le n \le 10^5$$$) and $$$m$$$ ($$$2 \cdot n \le m \le 2 \cdot 10^5$$$).  The next $$$m$$$ lines contain pairs of integers $$$x_i$$$ ($$$-10^9 \le x_i \le 10^9$$$) and $$$w_i$$$ ($$$-10^4 \le w_i \le 10^4$$$) — coordinate and weight of point number $$$i$$$ ($$$1 \le i \le m$$$) respectively. All $$$x_i$$$ are different. It is guaranteed that the sum of $$$m$$$ values over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output $$$n + 1$$$ lines: in the first of them, output the weight of the composed system, and in the next $$$n$$$ lines output exactly two numbers  — the indices of the points which are the endpoints of the $$$i$$$-th segment ($$$1 \le i \le n$$$). The order in which you output the endpoints of a segment is not important — you can output the index of the left endpoint first and then the number of the right endpoint, or the other way around. If there are several ways to make a system of nested segments with minimal weight, output any of them.

NoteThe first test case coincides with the example from the condition. It can be shown that the weight of the composed system is minimal.The second test case has only $$$6$$$ points, so you need to use each of them to compose $$$3$$$ segments.

Point = Struct.new(:i, :x, :w)

gets.to_i.times do
  gets
  n, m = gets.split.map(&:to_i)
  points = m.times.map do |i|
    x, w = gets.split.map(&:to_i)
    Point.new(i + 1, x, w)
  end.sort_by(&:w).take(n * 2).sort_by(&:x)
  puts points.map(&:w).sum
  puts points.take(n).zip(points.drop(n).reverse).map { |a, b| "#{a.i} #{b.i}" }
  puts
end


Mike and Joe are playing a game with some stones. Specifically, they have $$$n$$$ piles of stones of sizes $$$a_1, a_2, \ldots, a_n$$$. These piles are arranged in a circle.The game goes as follows. Players take turns removing some positive number of stones from a pile in clockwise order starting from pile $$$1$$$. Formally, if a player removed stones from pile $$$i$$$ on a turn, the other player removes stones from pile $$$((i\bmod n) + 1)$$$ on the next turn.If a player cannot remove any stones on their turn (because the pile is empty), they lose. Mike goes first.If Mike and Joe play optimally, who will win?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 50$$$)  — the number of piles. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)  — the size of the piles.

For each test case print the winner of the game, either "Mike" or "Joe" on its own line (without quotes).

NoteIn the first test case, Mike just takes all $$$37$$$ stones on his first turn.In the second test case, Joe can just copy Mike's moves every time. Since Mike went first, he will hit $$$0$$$ on the first pile one move before Joe does so on the second pile.

def solve(piles)
  return "Mike" if piles.length % 2 != 0
  ans = [Float::INFINITY, -1]
  piles.each_with_index do |pile, i|
    ans = [pile, i] if pile < ans[0]
  end
  ans[1] % 2 == 0 ? "Joe" : "Mike"
end
cases = gets.to_i
cases.times do
  gets
  piles = gets.chomp.split(' ').map(&:to_i)
  puts solve(piles)
end

t = gets.to_i
t.times {
  n = gets.to_i
  a = gets.split.map &:to_i
  if n % 2 == 1
    puts "Mike"
  else
    m = a.min
    i = a.index(m)
    if i % 2 == 0
      puts "Joe"
    else
      puts "Mike"
    end
  end
}

def solve(piles)
  p piles
  return "Mike" if piles.length % 2 != 0
  ans = [Float::INFINITY, -1]
  piles.each_with_index do |pile, i|
    ans = [pile, i] if pile < ans[0]
  end
  ans[1] % 2 == 0 ? "Joe" : "Mike"
end
cases = gets.to_i
cases.times do
  gets
  piles = gets.chomp.split(' ').map(&:to_i)
  puts solve(piles)
end


Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes.Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels.Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit ≠ ermit).Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines):   Clerihew (aabb);  Alternating (abab);  Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa).If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme.Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task.

The first line contains two integers n and k (1 ≤ n ≤ 2500, 1 ≤ k ≤ 5) — the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on.

Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes.

2 1
day
may
sun
fun
test
hill
fest
thrill

NoteIn the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".

n, m = gets.split.map(&:to_i)
b = [true] * 4
n.times do
    a = Array.new(4){gets[/([aeiou][^aeiou]*){#{m}}$/]}
    1.upto(3) do |i|
        if b[i]
            b[i] &= a[0] && a[0] == a[i]
            j = i != 1 ? 1 : 2
            k = i != 3 ? 3 : 2
            b[i] &= a[j] && a[j] == a[k]
        end
    end
end

if b.all?
    puts :aaaa
elsif b[1]
    puts :aabb
elsif b[2]
    puts :abab
elsif b[3]
    puts :abba
else
    puts :NO
end

def check_quatrain(k)

	reg = Regexp.new("([aiueo][^aiueo]*){#{k}}$")

	suffixes = []
	4.times do
		if s = gets.slice(reg)
			suffixes << s
		else
			suffixes = []
			break
		end
	end

	case suffixes.uniq.size
	when 1 then
		"aaaa"
	when 2 then
		if suffixes[0] == suffixes[1] && suffixes[2] == suffixes[3]
			"aabb"
		elsif suffixes[0] == suffixes[2] && suffixes[1] == suffixes[3]
			"abab"
		elsif suffixes[0] == suffixes[3] && suffixes[1] == suffixes[2]
			"abba"
		else
			"NO"
		end
	else
		"NO"
	end
end

n, k = gets.split.map { |x| Integer(x)}

current = "aaaa"
n.times do |i|
	result = check_quatrain(k)
	if result == "aaaa" || result == current
		next
	elsif current == "aaaa"
		current = result
		next
	end
	current = "NO"
	break
end

puts current

n, k = gets.split.collect{|x| x.to_i}

old_scheme = "aaaa"
(1..n).each{
  scheme = nil
  lines = Array.new(4) { gets.chomp }

  lines.each_index{|i|
    pos = []
    lines[i].scan(/[aeiou]/){pos << $~.begin(0)}
    if pos[-k].nil?
      puts "NO"
      exit
    end
    lines[i] = lines[i][pos[-k]..-1]
  }

  scheme = "aabb" if lines[0] == lines[1] and lines[2] == lines[3]
  scheme = "abab" if lines[0] == lines[2] and lines[1] == lines[3]
  scheme = "abba" if lines[0] == lines[3] and lines[1] == lines[2]
  scheme = "aaaa" if lines[0] == lines[1] and lines[1] == lines[2] and lines[2] == lines[3]
  if scheme.nil? or (old_scheme != scheme and old_scheme != "aaaa" and scheme != "aaaa")
    puts "NO"
    exit
  end

  old_scheme = scheme if scheme != "aaaa"
}

puts old_scheme

n,k=gets.split.map(&:to_i)
ans=7
re=/.*(([aeiou].*){#{k}})$/

n.times{
	s=4.times.map{gets.chomp}
	if s[0]=~re
		if s[1].end_with?($1)
			if s[2].end_with?($1)
				if s[3].end_with?($1)
					ans&=7
				else
					ans=0
				end
			else
				if s[2]=~re #1
					if s[3].end_with?($1)
						ans&=1
					else
						ans=0
					end
				else
					ans=0
				end
			end
		else
			if s[2].end_with?($1) #2
				if s[1]=~re
					if s[3].end_with?($1)
						ans&=2
					else
						ans=0
					end
				else
					ans=0
				end
			elsif s[3].end_with?($1) #4
				if s[1]=~re
					if s[2].end_with?($1)
						ans&=4
					else
						ans=0
					end
				else
					ans=0
				end
			else
				ans=0
			end
		end
	else
		ans=0
	end
	break if ans==0
}

puts({0=>"NO",1=>"aabb",2=>"abab",4=>"abba",7=>"aaaa"}[ans])

n, m = gets.split.map(&:to_i)
b = [true] * 4
n.times do
    a = Array.new(4){gets.gsub(/[^aeiou]/, '').reverse[0, m]}
    1.upto(3) do |i|
        if b[i]
            b[i] &= a[0].size == m && a[0] == a[i]
            j = i != 1 ? 1 : 2
            k = i != 3 ? 3 : 2
            b[i] &= a[j].size == m && a[j] == a[k]
        end
    end
end

if b.all?
    puts :aaaa
elsif b[1]
    puts :aabb
elsif b[2]
    puts :abab
elsif b[3]
    puts :abba
else
    puts :NO
end

n, m = gets.split.map(&:to_i)
b = [true] * 4
n.times do
    a = Array.new(4){gets[/([aeiou].*?){#{m}}$/]}
    1.upto(3) do |i|
        if b[i]
            b[i] &= a[0] && a[0] == a[i]
            j = i != 1 ? 1 : 2
            k = i != 3 ? 3 : 2
            b[i] &= a[j] && a[j] == a[k]
        end
    end
end

if b.all?
    puts :aaaa
elsif b[1]
    puts :aabb
elsif b[2]
    puts :abab
elsif b[3]
    puts :abba
else
    puts :NO
end

n, k = gets.split.collect{|x| x.to_i}

old_scheme = "aaaa"
(1..n).each{
  scheme = nil
  lines = Array.new(4) { gets.chomp }

  lines.each_index{|i|
    pos = []
    lines[i].scan(/[aeiou]/){pos << $~.begin(0)}
    if pos[-k].nil?
      puts "NO"
      exit
    end
    lines[i] = lines[i][pos[-k]..-1]
  }

  scheme = "aabb" if lines[0] == lines[1] and lines[2] == lines[3]
  scheme = "abab" if lines[0] == lines[2] and lines[1] == lines[3]
  scheme = "abba" if lines[0] == lines[3] and lines[1] == lines[2]
  scheme = "aaaa" if lines[0] == lines[1] and lines[1] == lines[2] and lines[2] == lines[3]
  if scheme.nil? or (old_scheme != scheme and old_scheme != "aaaa")
    puts "NO"
    exit
  end

  old_scheme = scheme
}

puts old_scheme


Innovation technologies are on a victorious march around the planet. They integrate into all spheres of human activity!A restaurant called "Dijkstra's Place" has started thinking about optimizing the booking system. There are n booking requests received by now. Each request is characterized by two numbers: ci and pi — the size of the group of visitors who will come via this request and the total sum of money they will spend in the restaurant, correspondingly.We know that for each request, all ci people want to sit at the same table and are going to spend the whole evening in the restaurant, from the opening moment at 18:00 to the closing moment.Unfortunately, there only are k tables in the restaurant. For each table, we know ri — the maximum number of people who can sit at it. A table can have only people from the same group sitting at it. If you cannot find a large enough table for the whole group, then all visitors leave and naturally, pay nothing.Your task is: given the tables and the requests, decide which requests to accept and which requests to decline so that the money paid by the happy and full visitors was maximum.

The first line of the input contains integer n (1 ≤ n ≤ 1000) — the number of requests from visitors. Then n lines follow. Each line contains two integers: ci, pi (1 ≤ ci, pi ≤ 1000) — the size of the group of visitors who will come by the i-th request and the total sum of money they will pay when they visit the restaurant, correspondingly. The next line contains integer k (1 ≤ k ≤ 1000) — the number of tables in the restaurant. The last line contains k space-separated integers: r1, r2, ..., rk (1 ≤ ri ≤ 1000) — the maximum number of people that can sit at each table.

In the first line print two integers: m, s — the number of accepted requests and the total money you get from these requests, correspondingly. Then print m lines — each line must contain two space-separated integers: the number of the accepted request and the number of the table to seat people who come via this request. The requests and the tables are consecutively numbered starting from 1 in the order in which they are given in the input. If there are multiple optimal answers, print any of them.

def run
  n = $stdin.gets.to_i

  cp = []
  n.times do |i|
    ary = $stdin.gets.chomp.split.map(&:to_i)
    cp << [i] + ary
  end

  k = $stdin.gets.to_i
  r = []
  $stdin.gets.split.each_with_index do |x, i|
    r << [i, x.to_i]
  end

  cp = cp.sort_by {|x| -x[2] }
  r = r.sort_by {|x| x[1] }

  sum = 0
  flag = []
  ans = []
  cp.each do |c_index, people, money|
    r.each do |t_index, size|
      if size >= people && flag[t_index] == nil
        ans << [c_index + 1, t_index + 1]
        flag[t_index] = true
        sum += money
        break
      end
    end
  end

  puts "#{ans.length} #{sum}"
  ans.each do |ary|
    puts ary.join " "
  end
end

run if $0 == __FILE__


A way to make a new task is to make it nondeterministic or probabilistic. For example, the hard task of Topcoder SRM 595, Constellation, is the probabilistic version of a convex hull.Let's try to make a new task. Firstly we will use the following task. There are n people, sort them by their name. It is just an ordinary sorting problem, but we can make it more interesting by adding nondeterministic element. There are n people, each person will use either his/her first name or last name as a handle. Can the lexicographical order of the handles be exactly equal to the given permutation p?More formally, if we denote the handle of the i-th person as hi, then the following condition must hold: .

The first line contains an integer n (1 ≤ n ≤ 105) — the number of people. The next n lines each contains two strings. The i-th line contains strings fi and si (1 ≤ |fi|, |si| ≤ 50) — the first name and last name of the i-th person. Each string consists only of lowercase English letters. All of the given 2n strings will be distinct. The next line contains n distinct integers: p1, p2, ..., pn (1 ≤ pi ≤ n).

If it is possible, output "YES", otherwise output "NO".

3
gennady korotkevich
petr mitrichev
gaoyuan chen
1 2 3

3
gennady korotkevich
petr mitrichev
gaoyuan chen
3 1 2

2
galileo galilei
nicolaus copernicus
2 1

10
rean schwarzer
fei claussell
alisa reinford
eliot craig
laura arseid
jusis albarea
machias regnitz
sara valestin
emma millstein
gaius worzel
1 2 3 4 5 6 7 8 9 10

10
rean schwarzer
fei claussell
alisa reinford
eliot craig
laura arseid
jusis albarea
machias regnitz
sara valestin
emma millstein
gaius worzel
2 4 9 6 5 7 1 3 8 10

NoteIn example 1 and 2, we have 3 people: tourist, Petr and me (cgy4ever). You can see that whatever handle is chosen, I must be the first, then tourist and Petr must be the last.In example 3, if Copernicus uses "copernicus" as his handle, everything will be alright.

#!/usr/bin/ruby
n=gets.to_i
a=n.times.map{gets.split}
perm=gets.split.map{|e|e.to_i-1}
a=perm.map{|e|a[e]}
cur=a[0].min
puts (1...n).all?{|i|
	cur=a[i].select{|e|e>=cur}.min
} ? :YES : :NO

n=gets.to_i
a=Array.new(n)
for i in 0...n
	a[i]=gets.chomp.split.sort
end
cur,ans='','YES'
for i in gets.chomp.split.map(&:to_i)
	if a[i-1][0] > cur
		cur = a[i-1][0]
	elsif a[i-1][1] > cur
		cur = a[i-1][1]
	else
		ans = 'NO'
	end
end
puts ans

def can_p(p, names, use_n)
  can
end

n = gets.to_i
names = (1..n).map{gets.split(" ")}
p = gets.split(" ").map(&:to_i)

can_n = true
can_sn = true

(1..n-1).each do |i|
  prev_n, prev_sn = names[p[i-1] - 1]
  cur_n, cur_sn = names[p[i] - 1]
  can_n_next = can_n && cur_n > prev_n || can_sn && cur_n > prev_sn
  can_sn_next = can_n && cur_sn > prev_n || can_sn && cur_sn > prev_sn
  can_n, can_sn = can_n_next, can_sn_next
  break if ! can_n && ! can_sn
end

ans = can_n || can_sn ? "YES" : "NO"
puts ans

n = gets.to_i
a = n.times.map{gets.split.sort}.unshift(nil)
p = gets.split.map(&:to_i)
s = ''
ans = p.each do |i|
  if a[i][0] > s
    s = a[i][0]
  elsif a[i][1] > s
    s = a[i][1]
  else
    break
  end
end
puts ans ? 'YES' : 'NO'

n = gets.to_i
a = [[]] + n.times.map{gets.split.sort}
p = gets.split.map(&:to_i)
s = []
ans = true
p.each do |i|
  if i == p[0] || a[i][0] > s.last[0]
    s << a[i]
  elsif a[i].reverse[0] > s.last[0]
    s << a[i].reverse
  else
    ans = false
    break
  end
end
puts ans ? "YES" : "NO"

a = []
(n = gets.to_i).times {
  a << gets.chomp.split
}
order = gets.chomp.split.map { |c| c.to_i - 1 }
last = a[order[0]]
(1...n).each { |k|
  cur = []
  a[order[k]].each { |x|
    cur << x if last.any? { |v| x > v }
  }
  if cur.empty?
    puts 'NO'
    exit
  end
  last = cur
}
puts 'YES'

n=gets.to_i
h=[0]
n.times{h<<gets.split}
p=gets.split.map &:to_i
b=""
r="YES"
p.each do |i|
  if h[i].min > b
    b=h[i].min
  elsif h[i].max > b
    b=h[i].max
  else
    r="NO"
    break
  end
end
puts r

def can_p(p, names, use_n)
  can
end

n = gets.to_i
names = (1..n).map{gets.split(" ")}
p = gets.split(" ").map(&:to_i)

puts "NAMES: #{names}"
puts "P: #{p}"

can_n = true
can_sn = true

(1..n-1).each do |i|
  prev_n, prev_sn = names[p[i-1] - 1]
  cur_n, cur_sn = names[p[i] - 1]
  can_n_next = can_n && cur_n > prev_n || can_sn && cur_n > prev_sn
  can_sn_next = can_n && cur_sn > prev_n || can_sn && cur_sn > prev_sn
  can_n, can_sn = can_n_next, can_sn_next
  break if ! can_n && ! can_sn
end

ans = can_n || can_sn ? "YES" : "NO"
puts ans

n = gets.to_i
a = n.times.map{gets.chomp}
p = gets.split.map(&:to_i)
def change a
	name1, name2 = a.split
	tmp = name1
	return [name2, tmp].join(" ")
end
def compare i, j, a
	3.times do |k|
		if a[i-1] > a[j-1]
			if k == 0
				a[j-1] = change a[j-1]
			elsif k == 1
				a[i-1] = change a[i-1]
			elsif k == 2
				a[j-1] = change a[j-1]
			end
		elsif a[i-1] < a[j-1]
			return true
			break
		end
	end
end
n.times do |i|
	if compare(p[i], p[i+1], a) == false
		puts "NO"
		break
	elsif i == p.size - 2
		puts "YES"
		break
	end
end

a = []
(n = gets.to_i).times {
  a << gets.chomp.split
}
order = gets.chomp.split.map { |c| c.to_i - 1 }
(0...n - 1).each { |k|
  i, j = order[k, k + 2]
  unless a[i][0] < a[j][0] || a[i][0] < a[j][1] || a[i][1] < a[j][0] || a[i][1] < a[j][1]
    puts 'NO'
    exit
  end
}
puts 'YES'


Codeforces separates its users into $$$4$$$ divisions by their rating:  For Division 1: $$$1900 \leq \mathrm{rating}$$$  For Division 2: $$$1600 \leq \mathrm{rating} \leq 1899$$$  For Division 3: $$$1400 \leq \mathrm{rating} \leq 1599$$$  For Division 4: $$$\mathrm{rating} \leq 1399$$$ Given a $$$\mathrm{rating}$$$, print in which division the $$$\mathrm{rating}$$$ belongs.

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of testcases. The description of each test consists of one line containing one integer $$$\mathrm{rating}$$$ ($$$-5000 \leq \mathrm{rating} \leq 5000$$$).

For each test case, output a single line containing the correct division in the format "Division X", where $$$X$$$ is an integer between $$$1$$$ and $$$4$$$ representing the division for the corresponding rating.

Division 4
Division 4
Division 4
Division 4
Division 3
Division 2
Division 1

NoteFor test cases $$$1-4$$$, the corresponding ratings are $$$-789$$$, $$$1299$$$, $$$1300$$$, $$$1399$$$, so all of them are in division $$$4$$$.For the fifth test case, the corresponding rating is $$$1400$$$, so it is in division $$$3$$$.For the sixth test case, the corresponding rating is $$$1679$$$, so it is in division $$$2$$$.For the seventh test case, the corresponding rating is $$$2300$$$, so it is in division $$$1$$$.

def division?(n)
  if n <= 1399
    puts "Division 4"
  elsif n >= 1400 && n <= 1599
    puts "Division 3"
  elsif n >= 1600 && n <= 1899
    puts "Division 2"
  else
    puts "Division 1"
  end
end

t = gets.chomp.to_i

input = []
(0..t-1).each do |i|
  input.push(gets.chomp.to_i)
end

input.each do |i|
  division?(i)
end

input1 = gets.to_i
input1.times do
  output = ["Division"]
  case (input = gets.to_i)
  when (..1399) then output << "4"
  when (1400..1599) then output << "3"
  when (1600..1899) then output << "2"
  when (1900..) then output << "1"
  end
  puts output.join(" ")
end

gets.to_i.times do
  n = gets.to_i
  x = if n <= 1399
      4
    elsif n <= 1599
      3
    elsif n <= 1899
      2
    else
      1
    end
  puts "Division #{x}"
end

t = gets.chomp().to_i

for i in 1 .. t
    rating = gets.chomp().to_i
    if 1900 <= rating
        puts "Division 1"
    elsif 1600 <= rating and rating <= 1899
        puts "Division 2"
    elsif 1400 <= rating and rating <= 1599
        puts "Division 3"
    elsif rating <= 1399
        puts "Division 4"
    end
end

gets.to_i.times do
  a = gets.to_i
  if a>= 1900
    puts "Division 1"
  elsif a >= 1600
    puts "Division 2"
  elsif a >= 1400
    puts "Division 3"
  else
    puts "Division 4"
  end
end

tests = gets.to_i

tests.times do

    i = gets.to_i

    if i >= 1900
        puts "Division 1"
    elsif 1600 <= i and i <= 1899
        puts "Division 2"
    elsif 1400 <= i and i <= 1599
        puts "Division 3"
    else
        puts "Division 4"
    end
end

t=gets.chomp.to_i
t.times do
    r = gets.chomp.to_i
    if(r>=1900)
        puts "Division 1"
    end
    if(r>=1600 && r<=1899)
        puts "Division 2"
    end
    if(r>=1400 && r<=1599)
        puts "Division 3"
    end
    if(r<=1399)
        puts "Division 4"
    end
end


A little boy Laurenty has been playing his favourite game Nota for quite a while and is now very hungry. The boy wants to make sausage and cheese sandwiches, but first, he needs to buy a sausage and some cheese.The town where Laurenty lives in is not large. The houses in it are located in two rows, n houses in each row. Laurenty lives in the very last house of the second row. The only shop in town is placed in the first house of the first row.The first and second rows are separated with the main avenue of the city. The adjacent houses of one row are separated by streets.Each crosswalk of a street or an avenue has some traffic lights. In order to cross the street, you need to press a button on the traffic light, wait for a while for the green light and cross the street. Different traffic lights can have different waiting time.The traffic light on the crosswalk from the j-th house of the i-th row to the (j + 1)-th house of the same row has waiting time equal to aij (1 ≤ i ≤ 2, 1 ≤ j ≤ n - 1). For the traffic light on the crossing from the j-th house of one row to the j-th house of another row the waiting time equals bj (1 ≤ j ≤ n). The city doesn't have any other crossings.The boy wants to get to the store, buy the products and go back. The main avenue of the city is wide enough, so the boy wants to cross it exactly once on the way to the store and exactly once on the way back home. The boy would get bored if he had to walk the same way again, so he wants the way home to be different from the way to the store in at least one crossing.    Figure to the first sample. Help Laurenty determine the minimum total time he needs to wait at the crossroads.

The first line of the input contains integer n (2 ≤ n ≤ 50) — the number of houses in each row.  Each of the next two lines contains n - 1 space-separated integer — values aij (1 ≤ aij ≤ 100).  The last line contains n space-separated integers bj (1 ≤ bj ≤ 100).

Print a single integer — the least total time Laurenty needs to wait at the crossroads, given that he crosses the avenue only once both on his way to the store and on his way back home.

NoteThe first sample is shown on the figure above. In the second sample, Laurenty's path can look as follows:   Laurenty crosses the avenue, the waiting time is 3;  Laurenty uses the second crossing in the first row, the waiting time is 2;  Laurenty uses the first crossing in the first row, the waiting time is 1;  Laurenty uses the first crossing in the first row, the waiting time is 1;  Laurenty crosses the avenue, the waiting time is 1;  Laurenty uses the second crossing in the second row, the waiting time is 3.  In total we get that the answer equals 11.In the last sample Laurenty visits all the crossings, so the answer is 4.

n=gets.to_i
cross2=gets.split(" ").map(&:to_i)
cross1=gets.split(" ").map(&:to_i)
crossav=gets.split(" ").map(&:to_i)

t=999999999999999
for i in 0...n
	for j in 0...n
		next if i == j

		cost = 0
		cost += (cross1[i..-1].reduce(:+)||0) + crossav[i] + (cross2[0...i].reduce(:+)||0)
		cost += (cross1[j..-1].reduce(:+)||0) + crossav[j] + (cross2[0...j].reduce(:+)||0)

		t = [t, cost].min
	end
end

p t

n, first_row_traffic, second_row_traffic, avenue_traffic, sums =
	gets.chomp.to_i,
	gets.chomp.split(" ").map(&:to_i).unshift(0),
	gets.chomp.split(" ").map(&:to_i).push(0),
	gets.chomp.split(" ").map(&:to_i),
	[]

(n-1).downto 0 do |i|
	sum = 0

	sum += avenue_traffic[i]

	i.downto 0 do |j|
		sum += first_row_traffic[j]
	end

	i.upto (n-1) do |j|
		sum += second_row_traffic[j]
	end

	sums << sum
end
sums.sort!
puts (sums[0] + sums[1])

n = gets.chomp.to_i
top = gets.split.map{ |x| x.to_i }
bot = gets.split.map{ |x| x.to_i }
over = gets.split.map{ |x| x.to_i }
cost = []
n.times do |i|
  sum = over[i]
  (0...i).each { |j| sum += top[j] }
  (i...(n-1)).each { |j| sum += bot[j] }
  cost << sum
end

max= top.inject(:+) + bot.inject(:+) + over.inject(:+)
r1 = max
b1 = 0
n.times do |i|
  if cost[i] < r1
    r1 = cost[i]
    b1 = i
  end
end
r2 = max
n.times do |i|
  if cost[i] < r2 and i != b1
    r2 = cost[i]
  end
end

puts r1+r2

#! ruby
# try Codeforces Round 325 div2
# author: Leonardone @ NEETSDKASU

n = gets.to_i
*a, b = readlines.map{|x| x.chomp.split.map(&:to_i)}

f1 = [[:H2S, n - 1, 1, 0, 0]]

sp = 100 * 100
ans = 100 * 100
while !f1.empty?
	f2 = []
	f1.each do |f, x, y, c, r|
		case f
		when :H2S
			if x > 0
				nc = c + a[y][x - 1]
				if x - 1 == 0 && y == 0
					if nc < sp
						sp = nc
						f2 << [:S2H, 0, 0, nc, r]
					end
				else
					f2 << [f, x - 1, y, nc, r]
				end
			end
			if y == 1
				nc = c + b[x]
				if x == 0
					if nc < sp
						sp = nc
						f2 << [:S2H, 0, 0, nc, x]
					end
				else
					f2 << [f, x, 0, nc, x]
				end
			end
		when :S2H
			if x < n - 1
				nc = c + a[y][x]
				if x + 1 == n - 1 && y == 1
					ans = [ans, nc].min
				else
					f2 << [f, x + 1, y, nc, r]
				end
			end
			if y == 0 && r != x
				nc = c + b[x]
				if x == n - 1
					ans = [ans, nc].min
				else
					f2 << [f, x, 1, nc, r]
				end
			end
		end
	end
	f1 = f2
end
puts ans

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

cs = []
for i in 0..1
  c = [0]
  for j in 1..n - 1
    c << c[j-1] + as[i][j-1]
  end
  cs << c
end

ds = []
for i in 0..n-1
  ds << cs[0][i] + bs[i] + cs[1][n-1] - cs[1][i]
end

ds.sort!
puts ds[0] + ds[1]

# coding; utf-8

h = gets.strip.to_i
fr = gets.strip.split(' ').map(&:to_i)
sr = gets.strip.split(' ').map(&:to_i)
av = gets.strip.split(' ').map(&:to_i)

times = [ ]
h.times do |i|
  t = av[i]
  0.upto(i - 1) { |j| t += fr[j] }
  i.upto(sr.length - 1) { |j| t += sr[j] }

  times.push(t)
end

times.sort!
puts (times[0] + times[1]).to_s


Petya is preparing for his birthday. He decided that there would be $$$n$$$ different dishes on the dinner table, numbered from $$$1$$$ to $$$n$$$. Since Petya doesn't like to cook, he wants to order these dishes in restaurants.Unfortunately, all dishes are prepared in different restaurants and therefore Petya needs to pick up his orders from $$$n$$$ different places. To speed up this process, he wants to order courier delivery at some restaurants. Thus, for each dish, there are two options for Petya how he can get it:  the dish will be delivered by a courier from the restaurant $$$i$$$, in this case the courier will arrive in $$$a_i$$$ minutes,  Petya goes to the restaurant $$$i$$$ on his own and picks up the dish, he will spend $$$b_i$$$ minutes on this. Each restaurant has its own couriers and they start delivering the order at the moment Petya leaves the house. In other words, all couriers work in parallel. Petya must visit all restaurants in which he has not chosen delivery, he does this consistently.For example, if Petya wants to order $$$n = 4$$$ dishes and $$$a = [3, 7, 4, 5]$$$, and $$$b = [2, 1, 2, 4]$$$, then he can order delivery from the first and the fourth restaurant, and go to the second and third on your own. Then the courier of the first restaurant will bring the order in $$$3$$$ minutes, the courier of the fourth restaurant will bring the order in $$$5$$$ minutes, and Petya will pick up the remaining dishes in $$$1 + 2 = 3$$$ minutes. Thus, in $$$5$$$ minutes all the dishes will be at Petya's house.Find the minimum time after which all the dishes can be at Petya's home.

The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case begins with a line containing one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of dishes that Petya wants to order. The second line of each test case contains $$$n$$$ integers $$$a_1 \ldots a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the time of courier delivery of the dish with the number $$$i$$$. The third line of each test case contains $$$n$$$ integers $$$b_1 \ldots b_n$$$ ($$$1 \le b_i \le 10^9$$$) — the time during which Petya will pick up the dish with the number $$$i$$$. The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case output one integer — the minimum time after which all dishes can be at Petya's home.

t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  arr = gets.chomp.split(' ').map(&:to_i).zip(0..)
  brr = gets.chomp.split(' ').map(&:to_i)
  arr.sort!.reverse!
  cur = arr[0]
  p_time = 0
  while p_time + brr[cur[1]] < cur[0]
    p_time += brr[cur[1]]
    arr.shift
    cur = arr[0]
    break if cur.nil?
  end
  res = p_time
  res = [res, cur[0]].max unless cur.nil?
  puts res.to_s
end


Mahmoud and Ehab are in the fourth stage now.Dr. Evil has a hidden binary string of length n. He guarantees that there is at least one '0' symbol and at least one '1' symbol in it. Now he wants Mahmoud and Ehab to find a position of any '0' symbol and any '1' symbol. In order to do this, Mahmoud and Ehab can ask Dr. Evil up to 15 questions. They tell Dr. Evil some binary string of length n, and Dr. Evil tells the Hamming distance between these two strings. Hamming distance between 2 binary strings of the same length is the number of positions in which they have different symbols. You can find the definition of Hamming distance in the notes section below.Help Mahmoud and Ehab find these two positions.You will get Wrong Answer verdict if   Your queries doesn't satisfy interaction protocol described below.  You ask strictly more than 15 questions and your program terminated after exceeding queries limit. Please note, that you can do up to 15 ask queries and one answer query.  Your final answer is not correct.  You will get Idleness Limit Exceeded if you don't print anything or if you forget to flush the output, including for the final answer (more info about flushing output below).If you exceed the maximum number of queries, You should terminate with 0, In this case you'll get Wrong Answer, If you don't terminate you may receive any verdict because you'll be reading from a closed stream .

The first line of input will contain a single integer n (2 ≤ n ≤ 1000) — the length of the hidden binary string.

To print the final answer, print "! pos0 pos1" (without quotes), where pos0 and pos1 are positions of some '0' and some '1' in the string (the string is 1-indexed). Don't forget to flush the output after printing the answer!

NoteHamming distance definition: https://en.wikipedia.org/wiki/Hamming_distanceIn the first test case the hidden binary string is 101, The first query is 000, so the Hamming distance is 2. In the second query the hidden string is still 101 and query is 001, so the Hamming distance is 1.After some queries you find that symbol at position 2 is '0' and symbol at position 1 is '1', so you print "! 2 1".

def mq(str)
	puts "? " + str
	$stdout.flush()
	gets.to_i
end

n = gets.to_i

sample = "0" * n
l = 0
r = n - 1
last = false

d = mq(sample)

it = 14

pos0 = pos1 = -1

while r >= l
	exit(0) if it == 0

	mid = (l + r) >> 1
	len = mid - l + 1

	t = last ? "0" : "1"
	sample[l..mid] = t * len

	nd = mq(sample)

	if (d - nd).abs < len
		r = mid
		last = !last
	else
		if nd > d
			pos1 = l if last
			pos0 = l if !last
		else
			pos1 = l if !last
			pos0 = l if last
		end

		l = mid + 1
	end

	d = nd

	it -= 1
end

print "! ", pos0 + 1, " ", pos1 + 1
$stdout.flush()

def mq(str)
	puts "? " + str
	$stdout.flush()
	gets.to_i
end

n = gets.to_i

sample = "0" * n
l = 0
r = n - 1
last = false

d = mq(sample)

it = 14

while r - l > 1
	exit(0) if it == 0

	mid = (l + r) >> 1
	len = mid - l + 1

	t = last ? "0" : "1"
	sample[l..mid] = t * len

	nd = mq(sample)

	if (d - nd).abs < len
		r = mid
		last = !last
	else
		l = mid
	end

	d = nd

	it -= 1
end

exit(0) if it == 0

sample[l] = last ? "0" : "1"
nd = mq(sample)

it -= 1
exit(0) if it == 0

if nd < d
	l, r = r, l if sample[l] == "1"
else
	l, r = r, l if sample[l] == "0"
end

print "! ", l + 1, " ", r + 1
$stdout.flush()

def mq(str)
	puts "? " + str
	$stdout.flush()
	gets.to_i
end

n = gets.to_i

sample = "0" * n
l = 0
r = n - 1
last = false

d = mq(sample)

it = 13

while r - l > 1
	exit(0) if it == 0

	mid = (l + r) >> 1
	len = mid - l + 1

	t = last ? "0" : "1"
	sample[l..mid] = t * len

	nd = mq(sample)

	if (d - nd).abs < len
		r = mid
		last = !last
	else
		l = mid
	end

	d = nd

	it -= 1
end

sample[l] = last ? "0" : "1"
nd = mq(sample)

it -= 1
exit(0) if it == 0

if nd < d
	l, r = r, l if sample[l] == "1"
else
	l, r = r, l if sample[l] == "0"
end

print "! ", l + 1, " ", r + 1
$stdout.flush()

def mq(str)
	puts "? " + str
	$stdout.flush()
	gets.to_i
end

n = gets.to_i

sample = "0" * n
l = 0
r = n - 1
last = false

d = mq(sample)

it = 14

while r - l > 1
	exit(0) if it == 0

	mid = (l + r) >> 1
	len = mid - l + 1

	t = last ? "0" : "1"
	sample[l..mid] = t * len

	nd = mq(sample)

	if (d - nd).abs < len
		r = mid
		last = !last
	else
		l = mid
	end

	d = nd

	it -= 1
end

exit(0) if it == 0

sample[l] = last ? "0" : "1"
nd = mq(sample)

if nd < d
	l, r = r, l if sample[l] == "1"
else
	l, r = r, l if sample[l] == "0"
end

print "! ", l + 1, " ", r + 1
$stdout.flush()

def mq(str)
	puts "? " + str
	$stdout.flush()
	gets.to_i
end

n = gets.to_i

sample = "0" * n
l = 0
r = n - 1
last = false

d = mq(sample)

#it = 14

while r - l > 1
	#exit(0) if it == 0

	mid = (l + r) >> 1
	len = mid - l + 1

	t = last ? "0" : "1"
	sample[l..mid] = t * len

	nd = mq(sample)

	if (d - nd).abs < len
		r = mid
		last = !last
	else
		l = mid
	end

	d = nd

	#it -= 1
end

#exit(0) if it == 0

sample[l] = last ? "0" : "1"
nd = mq(sample)

if nd < d
	l, r = r, l if sample[l] == "1"
else
	l, r = r, l if sample[l] == "0"
end

print "! ", l + 1, " ", r + 1
$stdout.flush()

def mq(str)
	puts "? " + str
	$stdout.flush()
	gets.to_i
end

n = gets.to_i

sample = "0" * n
l = 0
r = n - 1
last = false

d = mq(sample)

it = 13

while r - l > 1
	exit(0) if it == 0

	mid = (l + r) >> 1
	len = mid - l + 1

	t = last ? "0" : "1"
	sample[l..mid] = t * len

	nd = mq(sample)

	if (d - nd).abs < len
		r = mid
		last = !last
	else
		l = mid
	end

	d = nd

	it -= 1
end
exit(0) if it == 0
sample[l] = last ? "0" : "1"
nd = mq(sample)

it -= 1
exit(0) if it == 0

if nd < d
	l, r = r, l if sample[l] == "1"
else
	l, r = r, l if sample[l] == "0"
end

print "! ", l + 1, " ", r + 1
$stdout.flush()


The marmots have prepared a very easy problem for this year's HC2 – this one. It involves numbers n, k and a sequence of n positive integers a1, a2, ..., an. They also came up with a beautiful and riveting story for the problem statement. It explains what the input means, what the program should output, and it also reads like a good criminal.However I, Heidi, will have none of that. As my joke for today, I am removing the story from the statement and replacing it with these two unhelpful paragraphs. Now solve the problem, fools!

The first line of the input contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 2200). The second line contains n space-separated integers a1, ..., an (1 ≤ ai ≤ 104).

n, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i).sort!
ans = 0
k.times{|i| ans += a[i] }
puts ans


Many years ago Berland was a small country where only $$$n$$$ people lived. Each person had some savings: the $$$i$$$-th one had $$$a_i$$$ burles.The government considered a person as wealthy if he had at least $$$x$$$ burles. To increase the number of wealthy people Berland decided to carry out several reforms. Each reform looked like that:   the government chooses some subset of people (maybe all of them);  the government takes all savings from the chosen people and redistributes the savings among the chosen people equally. For example, consider the savings as list $$$[5, 1, 2, 1]$$$: if the government chose the $$$1$$$-st and the $$$3$$$-rd persons then it, at first, will take all $$$5 + 2 = 7$$$ burles and after that will return $$$3.5$$$ burles to the chosen people. As a result, the savings will become $$$[3.5, 1, 3.5, 1]$$$.A lot of data was lost from that time, so we don't know how many reforms were implemented and to whom. All we can do is ask you to calculate the maximum possible number of wealthy people after several (maybe zero) reforms.

The first line contains single integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of test cases. Next $$$2T$$$ lines contain the test cases — two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le x \le 10^9$$$) — the number of people and the minimum amount of money to be considered as wealthy. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial savings of each person. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.

Print $$$T$$$ integers — one per test case. For each test case print the maximum possible number of wealthy people after several (maybe zero) reforms.

NoteThe first test case is described in the statement.In the second test case, the government, for example, could carry out two reforms: $$$[\underline{11}, \underline{9}, 11, 9] \rightarrow [10, 10, \underline{11}, \underline{9}] \rightarrow [10, 10, 10, 10]$$$.In the third test case, the government couldn't make even one person wealthy.In the fourth test case, the government could choose all people to carry out a reform: $$$[\underline{9}, \underline{4}, \underline{9}] \rightarrow [7\frac{1}{3}, 7\frac{1}{3}, 7\frac{1}{3}]$$$.

def run
  n, x = gets.chomp.split(" ").map(&:to_i)
  a = gets.chomp.split(" ").map(&:to_i)
  rich = a.select{|el| el >= x}
  poor = a.select{|el| el < x}.sort_by{|c| -c}
  count = rich.count
  surplus = rich.reduce(0) {|acc, el| acc + (el > x ? el - x : 0)}
  poor.each do |p|
    if surplus >= x - p
      surplus -= (x - p)
      count += 1
    else
      break
    end
  end
  puts count
end

def main
  t = gets.chomp.to_i

  t.times do
    run
  end
end

main

t = gets.to_i
t.times do
  n, x = gets.split.map(&:to_i)
  a = gets.split.map(&:to_i).sort.reverse
  count = 0
  savings_sum = 0
  a.each_with_index do |v, i|
    savings_sum += v
    if savings_sum >= x * (i + 1)
      count += 1
    else
      break
    end
  end
  puts count
end

1.upto(gets.to_i) do
  n, x = gets.split(' ').map(&:to_i)
  a = gets.split(' ').map(&:to_f).sort.reverse

  s = 0
  n = a.count { |c| c >= x }
  max = n

  a.each_with_index do |e, i|
    s += e

    n -= 1 if e >= x

    break if s/(i+1) < x

    max = [max, n + i + 1].max
  end

  puts max
end


Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them.The tree looks like a polyline on the plane, consisting of all sticks. The polyline starts at the point $$$(0, 0)$$$. While constructing the polyline, Alexey will attach sticks to it one by one in arbitrary order. Each stick must be either vertical or horizontal (that is, parallel to $$$OX$$$ or $$$OY$$$ axis). It is not allowed for two consecutive sticks to be aligned simultaneously horizontally or simultaneously vertically. See the images below for clarification.Alexey wants to make a polyline in such a way that its end is as far as possible from $$$(0, 0)$$$. Please help him to grow the tree this way.Note that the polyline defining the form of the tree may have self-intersections and self-touches, but it can be proved that the optimal answer does not contain any self-intersections or self-touches.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the number of sticks Alexey got as a present. The second line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$) — the lengths of the sticks.

Print one integer — the square of the largest possible distance from $$$(0, 0)$$$ to the tree end.

NoteThe following pictures show optimal trees for example tests. The squared distance in the first example equals $$$5 \cdot 5 + 1 \cdot 1 = 26$$$, and in the second example $$$4 \cdot 4 + 2 \cdot 2 = 20$$$.

# Author : Fuad Ashraful Mehmet
#Date: 18th April

def solve()
    n=gets.to_i
    ar=gets.split.map(&:to_i).sort
    if n==1
        return ar[0]**2
    else
        xcor=ar[0,n/2].inject(:+)
        ycor=ar[n/2,(n+1)/2].inject(:+)

        return xcor**2+ycor**2
    end
end

ans=solve()
puts ans

n = gets.to_i
a = gets.split.map(&:to_i).sort
if n == 1
  p a[0]**2
else
  x = a[0,n/2].inject(:+)
  y = a[n/2,(n+1)/2].inject(:+)
  p x**2 + y**2
end

n = gets.to_i
a = gets.split.map(&:to_i).sort
if n == 1
  p a[0]
else
  x = a[0,n/2].inject(:+)
  y = a[n/2,(n+1)/2].inject(:+)
  p x**2 + y**2
end


You are given a square matrix consisting of n rows and n columns. We assume that the rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to n from left to right. Some cells (n - 1 cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can apply the following operations to the matrix:  Swap i-th and j-th rows of the matrix;  Swap i-th and j-th columns of the matrix. You are asked to transform the matrix into a special form using these operations. In that special form all the ones must be in the cells that lie below the main diagonal. Cell of the matrix, which is located on the intersection of the i-th row and of the j-th column, lies below the main diagonal if i > j.

The first line contains an integer n (2 ≤ n ≤ 1000) — the number of rows and columns. Then follow n - 1 lines that contain one's positions, one per line. Each position is described by two integers xk, yk (1 ≤ xk, yk ≤ n), separated by a space. A pair (xk, yk) means that the cell, which is located on the intersection of the xk-th row and of the yk-th column, contains one. It is guaranteed that all positions are distinct.

Print the description of your actions. These actions should transform the matrix to the described special form. In the first line you should print a non-negative integer m (m ≤ 105) — the number of actions. In each of the next m lines print three space-separated integers t, i, j (1 ≤ t ≤ 2, 1 ≤ i, j ≤ n, i ≠ j), where t = 1 if you want to swap rows, t = 2 if you want to swap columns, and i and j denote the numbers of rows or columns respectively. Please note, that you do not need to minimize the number of operations, but their number should not exceed 105. If there are several solutions, you may print any of them.

#!/usr/bin/ruby1.9

def display_array(matrix)
	return
	matrix.each do |row|
		puts row.join(' ')
	end
	puts
end

def swap_row(matrix, a, b, step, lines)
	if step == 1
		lines.push('%d %d %d' % [step, a+1, b+1])
	else
		n = matrix.length
		lines.push('%d %d %d' % [step, n-a, n-b])
	end
	row = matrix[a]
	matrix[a] = matrix[b]
	matrix[b] = row
end

def sift_down(m, step, lines)
	n = m.length
	counts = n.times.collect {|r| [0, 0, r] }
	n.times do |r|
		n.times do |c|
			if m[r][c] == 1
				counts[r][0] += 1
				counts[r][1] = -c
			end
		end
	end
	counts.sort!

	target2found = Array.new(n, 0)
	found2target = Array.new(n, 0)
	n.times do |target|
		found = counts[target][2]
		target2found[target] = found
		found2target[found] = target
	end
	n.times do |target|
		found = target2found[target]
		next if found == target
		target2found[found2target[target]] = found
		found2target[found] = found2target[target]
		found2target[target] = target
		swap_row(m, found, target, step, lines)
	end
end

n = STDIN.readline.to_i
m = n.times.collect { Array.new(n, 0) }
(n-1).times do
	r, c = STDIN.readline.split.collect {|s| s.to_i }
	m[r-1][c-1] = 1
end
display_array(m)

lines = []

sift_down(m, 1, lines)
display_array(m)

m = m.transpose.reverse
#display_array(m)

sift_down(m, 2, lines)
#display_array(m)
display_array(m.reverse.transpose)

puts lines.length
puts lines.join("\n")

#!/usr/bin/ruby1.9

def display_array(matrix)
	return
	matrix.each do |row|
		puts row.join(' ')
	end
	puts
end

def swap_row(matrix, a, b, step, lines)
	if step == 1
		lines.push('%d %d %d' % [step, a+1, b+1])
	else
		n = matrix.length
		lines.push('%d %d %d' % [step, n-a, n-b])
	end
	row = matrix[a]
	matrix[a] = matrix[b]
	matrix[b] = row
end

def sift_down(m, step, lines)
	n = m.length
	counts = n.times.collect {|r| [0, 0, r] }
	n.times do |r|
		n.times do |c|
			if m[r][c] == 1
				counts[r][0] += 1
				counts[r][1] = -c
			end
		end
	end
	counts.sort!

	permute = Array.new(n, 0)
	n.times do |new_position|
		old_position = counts[new_position][2]
		permute[old_position] = new_position
	end

	n.times do |pos|
		while permute[pos] != pos
			swap_row(m, pos, permute[pos], step, lines)
			t = permute[pos]
			permute[pos] = permute[t]
			permute[t] = t
		end
	end
end

n = STDIN.readline.to_i
m = n.times.collect { Array.new(n, 0) }
(n-1).times do
	r, c = STDIN.readline.split.collect {|s| s.to_i }
	m[r-1][c-1] = 1
end
display_array(m)

lines = []

sift_down(m, 1, lines)
display_array(m)

m = m.transpose.reverse

sift_down(m, 2, lines)
display_array(m.reverse.transpose)

puts lines.length
puts lines.join("\n")

def swap_cols(mat,i,j)
	aux = 0
	n = mat.length
	(0..(n-1)).each {|k|
		aux = mat[k][i]
		mat[k][i] = mat[k][j]
		mat[k][j] = aux
	}
end

n = gets.chomp.to_i
mat = []
(1..n).each {|pp|
  line = []
  (1..n).each {|qq|
	line.push(0)
  }
  mat.push(line)
}

(1..(n-1)).each { |k|
   i,j = gets.chomp.split(" ").collect! {|x| x.to_i}
   mat[i-1][j-1] = 1
}

actions = []
arr = []
pos = []
m = 0
aaux = []
(0..(n-1)).each { |k|
	p = m
	q = m
	while mat[k][p]==1
	  q +=1
	  p +=1
	  m +=1
	end
	while q<n
	  if mat[k][q]==1
	    #mat[k][p] = 1
		#mat[k][q] = 0
		swap_cols(mat,p,q)
		actions.push("2 #{p+1} #{q+1}")
		p += 1
		m +=1

	  end
	  q +=1
	end

	pos.push(k)
}

(0..(n-1)).each {|k|
  st = n-1
  while mat[k][st]==0 and st>=0
   st -=1
  end
  arr.push(st)
}
p = 0
min = arr[0]
while p<n
 min = arr[p]
 pos = p
 q = p+1
 while q<n
	if min > arr[q]
		min = arr[q]
		pos = q
	end
	q +=1
 end
 if p != pos
 arr[pos] = arr[p]
 arr[p] = min
 actions.push("1 #{p+1} #{pos+1}")
 end
 p += 1
end

puts actions.length
actions.each { |t|
 puts t
}

#!/usr/bin/ruby1.9

def display_array(matrix)
	matrix.each do |row|
		puts row.join(' ')
	end
	puts
end

def swap_row(matrix, a, b, step, lines)
	if step == 1
		lines.push('%d %d %d' % [step, a+1, b+1])
	else
		n = matrix.length
		lines.push('%d %d %d' % [step, n-a, n-b])
	end
	row = matrix[a]
	matrix[a] = matrix[b]
	matrix[b] = row
end

def sift_down(m, step, lines)
	n = m.length
	counts = n.times.collect {|r| [0, 0, r] }
	n.times do |r|
		n.times do |c|
			if m[r][c] == 1
				counts[r][0] += 1
				counts[r][1] = -c
			end
		end
	end
	counts.sort!

	permute = Array.new(n, 0)
	n.times do |new_position|
		old_position = counts[new_position][2]
		permute[old_position] = new_position
	end

	n.times do |pos|
		while permute[pos] != pos
			swap_row(m, pos, permute[pos], step, lines)
			t = permute[pos]
			permute[pos] = permute[t]
			permute[t] = t
		end
	end
end

n = STDIN.readline.to_i
m = n.times.collect { Array.new(n, 0) }
(n-1).times do
	r, c = STDIN.readline.split.collect {|s| s.to_i }
	m[r-1][c-1] = 1
end
display_array(m)

lines = []

sift_down(m, 1, lines)
display_array(m)

m = m.transpose.reverse

sift_down(m, 2, lines)
display_array(m.reverse.transpose)

puts lines.length
puts lines.join("\n")

#!/usr/bin/ruby1.9

def display_array(matrix)
	return
	matrix.each do |row|
		puts row.join(' ')
	end
	puts
end

def swap_row(matrix, a, b, step, lines)
	if step == 1
		lines.push('%d %d %d' % [step, a+1, b+1])
	else
		n = matrix.length
		lines.push('%d %d %d' % [step, n-a, n-b])
	end
	row = matrix[a]
	matrix[a] = matrix[b]
	matrix[b] = row
end

def sift_down(m, step, lines)
	n = m.length
	counts = n.times.collect {|r| [0, 0, r] }
	n.times do |r|
		n.times do |c|
			if m[r][c] == 1
				counts[r][0] += 1
				counts[r][1] = -c
			end
		end
	end
	counts.sort!

	n.times do |target_r|
		found_r = counts[target_r][2]
		next if found_r <= target_r
		swap_row(m, found_r, target_r, step, lines)
	end
end

n = STDIN.readline.to_i
m = n.times.collect { Array.new(n, 0) }
(n-1).times do
	r, c = STDIN.readline.split.collect {|s| s.to_i }
	m[r-1][c-1] = 1
end
display_array(m)

lines = []

sift_down(m, 1, lines)
display_array(m)

m = m.transpose.reverse
#display_array(m)

sift_down(m, 2, lines)
#display_array(m)
display_array(m.reverse.transpose)

puts lines.length
puts lines.join("\n")

#!/usr/bin/ruby1.9

def display_array(matrix)
	return
	puts
	matrix.each do |row|
		puts row.join(' ')
	end
end

def swap_row(matrix, a, b, step, lines)
	lines.push('%d %d %d' % [step, a+1, b+1])
	row = matrix[a]
	matrix[a] = matrix[b]
	matrix[b] = row
end

def sift_down(m, step, lines)
	n = m.length
	counts = n.times.collect {|r| [0, 0, r] }
	n.times do |r|
		n.times do |c|
			if m[r][c] == 1
				counts[r][0] += 1
				counts[r][1] = -c
			end
		end
	end
	counts.sort!

	n.times do |target_r|
		found_r = counts[target_r][2]
		next if found_r <= target_r
		swap_row(m, found_r, target_r, step, lines)
	end
end

n = STDIN.readline.to_i
m = n.times.collect { Array.new(n, 0) }
(n-1).times do
	r, c = STDIN.readline.split.collect {|s| s.to_i }
	m[r-1][c-1] = 1
end
display_array(m)

lines = []

sift_down(m, 1, lines)
display_array(m)

m = m.transpose.reverse
#display_array(m)

sift_down(m, 2, lines)
#display_array(m)
display_array(m.reverse.transpose)

puts lines.length
puts lines.join("\n")

def swap_cols(mat,i,j)
	aux = 0
	n = mat.length
	(0..(n-1)).each {|k|
		aux = mat[k][i]
		mat[k][i] = mat[k][j]
		mat[k][j] = aux
	}
end

n = gets.chomp.to_i
mat = []
(1..n).each {|pp|
  line = []
  (1..n).each {|qq|
	line.push(0)
  }
  mat.push(line)
}

(1..(n-1)).each { |k|
   i,j = gets.chomp.split(" ").collect! {|x| x.to_i}
   mat[i-1][j-1] = 1
}

actions = []
arr = []
pos = []
m = 0
aaux = []
(0..(n-1)).each { |k|
	p = m
	q = m
	while mat[k][p]==1
	  q +=1
	  p +=1
	  m +=1
	end
	while q<n
	  if mat[k][q]==1
	    #mat[k][p] = 1
		#mat[k][q] = 0
		swap_cols(mat,p,q)
		actions.push("2 #{p+1} #{q+1}")
		p += 1
		m +=1

	  end
	  q +=1
	end

	pos.push(k)
}

(0..(n-1)).each {|k|
  st = n-1
  while mat[k][st]==0 and st>=0
   st -=1
  end
  arr.push(st)
}
pi = 0
pj = 0
while pi<n-1
 pj = pi+1
 while pj<n
	if arr[pi]>arr[pj]
		aux = arr[pi]
		arr[pi] = arr[pj]
		arr[pj] = aux

		aux = pos[pi]
		pos[pi] = pos[pj]
		pos[pj] = aux

		actions.push("1 #{pi+1} #{pj+1}")
	end
	pj +=1
 end
 pi += 1
end

puts actions.length
actions.each { |t|
 puts t
}

def swap_cols(mat,i,j)
	aux = 0
	n = mat.length
	(0..(n-1)).each {|k|
		aux = mat[k][i]
		mat[k][i] = mat[k][j]
		mat[k][j] = aux
	}
end

n = gets.chomp.to_i
mat = []
(1..n).each {|pp|
  line = []
  (1..n).each {|qq|
	line.push(0)
  }
  mat.push(line)
}

(1..(n-1)).each { |k|
   i,j = gets.chomp.split(" ").collect! {|x| x.to_i}
   mat[i-1][j-1] = 1
}

actions = []
arr = []
pos = []
m = 0
aaux = []
(0..(n-1)).each { |k|
	p = m
	q = m
	while mat[k][p]==1
	  q +=1
	  p +=1
	  m +=1
	end
	while q<n
	  if mat[k][q]==1
	    #mat[k][p] = 1
		#mat[k][q] = 0
		swap_cols(mat,p,q)
		actions.push("2 #{p+1} #{q+1}")
		p += 1
		m +=1

	  end
	  q +=1
	end

	pos.push(k)
}

(0..(n-1)).each {|k|
  st = n-1
  while mat[k][st]==0 and st>=0
   st -=1
  end
  arr.push(st)
}
pi = 0
pj = 0
while pi<n-1
 pj = pi+1
 while pj<n
	if arr[pi]>arr[pj]
		aux = arr[pi]
		arr[pi] = arr[pj]
		arr[pj] = aux

		aux = pos[pi]
		pos[pi] = pos[pj]
		pos[pj] = aux

		actions.push("1 #{pos[pi]+1} #{pos[pj]+1}")
	end
	pj +=1
 end
 pi += 1
end

puts actions.length
actions.each { |t|
 puts t
}


A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle. Each time a new user wants to register, he sends to the system a request with his name. If such a name does not exist in the system database, it is inserted into the database, and the user gets the response OK, confirming the successful registration. If the name already exists in the system database, the system makes up a new user name, sends it to the user as a prompt and also inserts the prompt into the database. The new name is formed by the following rule. Numbers, starting with 1, are appended one after another to name (name1, name2, ...), among these numbers the least i is found so that namei does not yet exist in the database.

The first line contains number n (1 ≤ n ≤ 105). The following n lines contain the requests to the system. Each request is a non-empty line, and consists of not more than 32 characters, which are all lowercase Latin letters.

Print n lines, which are system responses to the requests: OK in case of successful registration, or a prompt with a new name, if the requested name is already taken.

bd = {}
gets.to_i.times do
	name = gets.chomp
	if bd.has_key?(name)
		bd[name] += 1
		puts name + bd[name].to_s
	else
		bd[name] = 0
		puts "OK"
	end
end

users = Hash.new

n = gets.to_i
n.times do
	name = gets.chomp
	if(users[name]==nil) then
		puts("OK")
		users[name] = 1
	else
		puts("#{name}#{users[name]}")
		users[name] += 1
	end
end

n = gets.to_i

base = {}

answer = []

n.times do |i|
    z = gets.chomp
    if base[z] then
        answer << (z + base[z].to_s)
        base[z] += 1
    else
        answer << "OK"
        base[z] = 1
    end
end

answer.map{|i| puts i}

n = gets.chomp.to_i

db = Hash.new
for i in 0..n-1
	s = gets.chomp
	if db.has_key?(s)
		idx = db[s] + 1
		while true
			ss = s + idx.to_s
			if not db.has_key?(ss)
				db[s] = idx
				db[ss] = 0
				puts ss
				break
			else
				idx += 1
			end
		end
	else
		db[s] = 0
		puts "OK"
	end
end

#!/usr/bin/ruby
n=gets.to_i
h=Hash.new
n.times{|i|
  x=s=gets.chomp
  if !h[s]
    h[s]=0
    puts "OK"
  else
    h[s]+=1
    puts s+h[s].to_s
  end
}

n = gets.to_i
hash = Hash.new
n.times do
	str = gets.chomp!
	if hash.key?(str)
		hash[str] += 1
		puts str + hash[str].to_s
	else
		hash[str] = 0
		puts 'OK'
	end
end

n=STDIN.gets.chomp.to_i
db={}
db.default=-1
n.times() {
  name=STDIN.gets.chomp
  db[name]+=1
  if 0<db[name]
    print(name+db[name].to_s,"\n")
  else
    print("OK\n")
  end
}

require 'set'
n = gets.to_i
a = Hash.new
n.times do
  name = gets.strip
  if a.include? name
    puts name + a[name].to_s
    a[name]+=1
  else
    puts "OK"
    a[name]=1
  end
end

n = gets.to_i
names = {}
n.times do
    name = gets.strip
    if names.has_key? name then
        names[name] += 1
        puts name + names[name].to_s
    else
        names[name] = 0
        puts 'OK'
    end
end

gets
h={}
puts$<.map{|x|x.chomp!
(h[x]=1
next :OK) if !h[x]
i=h[x]
i+=1while h[x+i.to_s]
h[x]=i
h[x+i.to_s]=x+i.to_s}

n = gets.to_i
names  = Array.new
logins = Hash.new
for i in 1..n
    name = gets.chomp
    if not logins[name]
        logins[name] = 1
        names << "OK"
    else
        names << "#{name}#{logins[name]}"
        logins[name] += 1
    end
end

for login in names
    puts login
end

n = gets.to_i
names  = Array.new
logins = Hash.new
for i in 1..n
    name = gets.chomp
    names << name
end

for name in names
    if not logins[name]
        logins[name] = 1
        puts "OK"
    else
        puts "#{name}#{logins[name]}"
        logins[name] += 1
    end
end

using = Hash.new
(gets.to_i).times do
	s = gets.chomp
	puts using.key?(s) ? s+using[s].to_s : "OK"
	using[s] = using[s].to_i+1
end

class Database
  def initialize
    @size = 0
    @records = {}
    @names = []
  end

  def insert name
    if @records[name].nil?
      @records[name] = [name]
      @names <<  "OK"
    else
      id = @records[name].length
      @records[name] << "#{name}#{id}"
      @names << "#{name}#{id}"
    end
  end

  def print
    @names.each { |name| puts name }
  end
end

db = Database.new
amount_of_users = gets.chomp.to_i
users = []
while 0 < amount_of_users do
  amount_of_users -= 1
  user = gets.chomp
  users << user
end

users.each do |user|
  db.insert(user)
end

db.print

n = STDIN.readline
lines = STDIN.readlines
h = {}

lines.each do |l|
  l = l.chomp
  if !h[l]
    puts 'OK'
  else
    puts "#{l}#{h[l]}"
  end

  h[l] ||= 0
  h[l] += 1
end

N = gets.chomp.to_i
memo=Hash.new(-1)
N.times do
  name=gets.chomp
  memo[name]+=1
  if memo[name]==0
    puts "OK"
  else
    puts name+memo[name].to_s
  end
end

a = {}
n = gets.to_i
n.times do
    s = gets.chomp.to_s
    if a[s] then
        puts s + a[s].to_s
        a[s] += 1
    else
        a[s] = 1
        puts "OK"
    end
end

h=Hash.new(0)
n=gets.to_i
n.times{
	s=gets.chomp
	if h[s]==0 then
		puts "OK"
	else
		puts s+h[s].to_s
	end
	h[s]+=1
}

n,m = gets.chomp.to_i
o = {}
n.times.each do |i|
  s = gets.chomp
  if o[s].nil?
    o[s] = 1
    puts "OK"
  else
    puts s+o[s].to_s
    o[s] += 1
  end
end

n = gets.to_i
h = Hash.new { |hash, key| hash[key] = 0  }
n.times do |i|
	x = gets.chomp
	h[x] += 1
	puts h[x] > 1 ? "#{x}#{h[x]-1}" : 'OK'
end

c = gets

map = Hash.new

c.to_i.times {

  name = gets.strip

  if map[name] == nil
    puts "OK"
    map[name] = 0
  else
    map[name] += 1
    puts name + map[name].to_s
  end

}

n = gets.to_i
data = Hash.new
n.times do
  name = gets.chop!
  v = data[name]
  if(v == nil) then v = 0; puts "OK"
  else puts name + v.to_s end
  data[name] = v + 1
end

n= gets.to_i
res=[]
names ={}
while n>0
na=gets.chomp
if names[na]
 names[na]=names[na]+1
 res.push (na+names[na].to_s)
else
 res.push "OK"
 names[na]=0
end
n=n-1
end

res.each{|a| puts a.to_s  }

n = Integer gets
names = Hash.new
for i in 0...n
	str = gets.chomp
	if names.has_key? str
	  print str, names[str], "\n"
	  names[str] += 1
  else
    puts "OK"
    names[str] = 1
  end
end

a={}
gets.to_i.times{q=a[s=gets.chop];puts q ?s+q.to_s: "OK";a[s]=q.to_i+1}

n = gets.to_i

database = {}

n.times do
	username = gets.chomp
	if database[username].nil?
		database[username] = 1
		puts "OK"
	else
		puts username + database[username].to_s
		database[username] += 1
	end
end

#Made By Hasbi Hamza
n=gets.chomp.to_i
hash={}
lines=[]
for i in 1..n
  lines[i]=gets.chomp.to_s
  hash[lines[i]]=0
end
for i in 1..n
  if hash[lines[i]]==0 then puts "OK"
  else puts("#{lines[i]}#{hash[lines[i]]}")
end
   hash[lines[i]]+=1
end

n = gets.to_i
a = Hash.new(0)
n.times do
  s = gets.chomp
  if a[s] == 0
    a[s] = 1
    puts 'OK'
  else
    puts s + a[s].to_s
    a[s] += 1
  end
end

n = gets.chomp.to_i
h = {}
n.times do
  s = gets.chomp
  i = h[s]
  if i.nil?
    puts 'OK'
    h[s] = 1
  else
    puts "#{s}#{h[s]}"
    h[s] += 1
  end
end

class Array
  def r
    self.map { |q| q.to_i }
  end
end

def read_line
  STDIN.gets.split(" ")
end

def read_to_array
  read_line.to_a
end

def read_numbers_to_array
  read_to_array.r
end

a = Hash.new(0)

n = STDIN.gets.to_i
n.times do
  str = read_to_array[0]
  a[str] += 1
  if a[str] > 1
    print "#{str}#{a[str] - 1}"
    puts
  else
    puts "OK"
  end
end

n = gets.to_i
a = Hash.new(0)
n.times do
  s = gets.chomp
  puts a[s] >= 1 ? "#{s}#{a[s]}" : "OK"
  a[s] += 1
end

n = gets.to_i
a = Hash.new(0)
n.times do
  s = gets.chomp
  if a[s] >= 1
    puts s + a[s].to_s
    a[s] += 1
  else
    a[s] = 1
    puts 'OK'
  end
end

n = gets.to_i
a = Hash.new(false)
n.times do
  s = gets.chomp
  if a[s]
    a[s] += 1
    puts s + a[s].to_s
  else
    a[s] = 0
    puts 'OK'
  end
end

n = gets.chomp.to_i
h = {}
n.times do
  s = gets.chomp
  if h[s].nil? then
    puts 'OK'
    h[s] = 1
  else
    puts s + h[s].to_s
    h[s] += 1
  end
end

names = {}
noNames = gets.chomp.to_i
(1..noNames).each do |name|
  name = gets.chomp
  if names[name] == nil
    names[name] = 1
    puts "OK"
  else
    newName = "#{name}#{names[name]}"
    names[name] += 1
    names[newName] = 1
    puts newName
  end
end

numOfInputs = gets.to_i
inputHash = {}
numOfInputs.downto(1) do
    input = gets.chomp
    if (inputHash.has_key?(input))
        numOfOccurence = inputHash[input]

        puts "#{input}#{numOfOccurence}"

        numOfOccurence = numOfOccurence + 1
        inputHash[input] = numOfOccurence
    else
        inputHash[input] = 1
        puts "OK"
    end
end

n = gets.to_i
db = {}

while n > 0 do
  u = gets[0..-2]
  if db.key?(u)
    printf("%s%d\n", u, db[u])
    db[u] += 1
  else
    puts "OK"
    db[u] = 1
  end
  n -= 1
end

n = gets.to_i
db = {}

while n > 0 do
  u = gets.chomp
  if db.has_key?(u)
    puts u + db[u].to_s
    db[u] += 1
  else
    puts "OK"
    db[u] = 1
  end
  n -= 1
end

n = gets.to_i
db = {}

while n > 0 do
  u = gets.chomp
  if db.has_key?(u)
    printf("%s%d\n", u, db[u])
    db[u] += 1
  else
    puts "OK"
    db[u] = 1
  end
  n -= 1
end

h=Hash.new
gets
$<.map{|n|
	s=n.chop
    if(h.has_key?(s))
        h[s]+=1
        puts s+h[s].to_s
    else
    	h[s] = 0
        puts "OK"
    end
}

n = gets.chomp.to_i

hash = {}

n.times do |i|
    name = gets.chomp
    if hash[name] == nil
        hash[name] = 1
        puts "OK"
    else
        puts "#{name}#{hash[name]}"
        hash[name] += 1
    end
end

n = gets.to_i

cache = Hash.new { 0 }

1.upto(n) do
  name = gets.chomp

  puts cache[name].zero? ? 'OK' : "#{name}#{cache[name]}"

  cache[name] += 1
end

a = {}
for _ in 1..gets.chomp.to_i
  name = gets.chomp
  if a.has_key? name
    a[name] += 1
    puts "#{name}#{a[name]}"
  else
    puts 'OK'
    a[name] = 0
  end
end

n = gets.chomp.to_i

hash = {}

1.upto(n) do
	name = gets.chomp
	if hash[name] == nil
		hash[name] = 1
		puts "OK"
	else
		puts "#{name}#{hash[name]}"
		hash[name] += 1
	end
end

n, db = gets.to_i, Hash.new(-1)
n.times do
	name = gets.chomp.to_sym
	db[name] += 1
	if db[name] > 0
		print name, db[name], "\n"
	else
		puts :OK
	end
end

accountNum = gets.chomp.to_i

hash = {}
numberHash = {}

accountNum.times do
	account = gets.chomp

	if hash.has_key? account
		numberHash[account] += 1
		newAccount = account + numberHash[account].to_s
		puts "#{newAccount}"
	else
		puts 'OK'
		hash[account] = 1
		numberHash[account] = 0
	end
end

n=STDIN.gets.chomp.to_i
db={}
db.default=0
n.times() {
  name=STDIN.gets.chomp
  db[name]+=1
  if 1<db[name]
    print(name+db[name].to_s,"\n")
  else
    print("OK\n")
  end
}

gets
h={}
puts$<.map{|x|x.chomp!
next h[x]=:OK if !h[x]
i=x=~/\d+$/ ? (x=$`
$1.to_i) : 1
i+=1while h[x+i.to_s]
h[x]=x+i.to_s}

gets
h={}
puts$<.map{|x|x.chomp!
next h[x]=:OK if !h[x]
i=1
i+=1while h[x+i.to_s]
h[x]=x+i.to_s}

using = Hash.new(0)
(gets.to_i).times do
	s = gets.chomp
	id = using.key?(s) ? using[s].to_s : "";
	puts s+id
	using[s] = id.to_i+1
end

class Database
  def initialize
    @size = 0
    @records = {}
  end

  def insert name
    if @records[name].nil?
      @records[name] = [name]
      return "OK"
    else
      id = @records[name].length
      @records[name] << "#{name}#{id}"
    end
  end

  def print
    @records.each do |k, v|
      v.each do |user|
        if user == k
          puts "OK"
        else
          puts user
        end
      end
    end
  end
end

db = Database.new
amount_of_users = gets.chomp.to_i
users = []
while 0 < amount_of_users do
  amount_of_users -= 1
  user = gets.chomp
  users << user
end

users.each do |user|
  db.insert(user)
end

db.print

n = gets.to_i

database = Hash.new(0)

n.times do
	username = gets.chomp
	if database[username].nil?
		puts "OK"
		database[username] = 1
	else
		puts username + database[username].to_s
		database[username] += 1
	end
end

n = gets.to_i

database = {}

n.times do
	username = gets.strip
	count = 0
	if database[username].nil?
		database[username] = 1
		puts "OK"
	else
		test = username
		while database[test]
			count += 1
			test = username + count.to_s
		end
		username = test
		database[username] = 1
		puts username
	end
	print database
	puts
end

n = gets.to_i

database = Hash.new(0)

n.times do
	username = gets.chomp
	count = 0
	if database[username].nil?
		puts "OK"
		database[username] = 1
	else
		puts username + database[username].to_s
		database[username] += 1
	end
end

gets; names, db = STDIN.read.split("\n"), {}
names.each do |i|
	i = i.to_sym
	if db.keys.include? i
		n = db[i] + 1
		puts "#{i}#{n}"
	else
		db[i] = 0
		puts :OK
	end
end


Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles.Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle.Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number.

The first line contains integer n (1 ≤ n ≤ 100) — the number of bottles. The next n lines contain the bottles' description. The i-th line contains two integers ai, bi (1 ≤ ai, bi ≤ 1000) — the description of the i-th bottle.

In a single line print a single integer — the answer to the problem.

n = gets.to_i
a = []
b = []
n.times do
  s = gets.split.map(&:to_i)
  a << s[0]
  b << s[1]
end
x = []
n.times do |i|
  n.times do |j|
    x << j if (i!=j and a[j]==b[i])
  end
end
puts n - x.uniq.size

n=gets.to_i
a=[]
b=[]
n.times{
    s,t=gets.split.map(&:to_i)
    a<<s
    b<<t
}

x=[]
n.times{|i|
    n.times{|j|
        x<<j if (i!=j and a[j]==b[i])
    }
}
p n-x.sort.uniq.size

def main()
	n=gets.chomp.to_i
	b1=[]
	b2=[]
	ans=0
	for i in 0...n
		ini=gets.chomp.split(" ")
		ini=ini.map{|i| i.to_i}
		ai=ini[0]
		bi=ini[1]
		b1 << ai
		b2 << bi

	end
	for i in 0...(b1.size)
		ind=b2.index(b1[i])
		if ind.nil?
			ans+=1
		elsif ind==i
			ind2=b2.rindex(b1[i])
			if ind2.nil? || ind2==i
				ans+=1
			end
		end
	end
	puts ans
end

main

n = gets.chomp.to_i
data = []
n.times do
  a, b = gets.chomp.split(" ").map(&:to_i)
  data.push([a,b])
end
d = {}
(0...data.length).each do |i|
  d[i] = 0
end

(0...data.length).each do |i|
  a, b = data[i]
  (0...data.length).each do |j|
    candidate_a, candidate_b = data[j]
    if a == candidate_b && i != j
      d[i] = 1
      break
    end
  end
end

total = 0
d.each do |key, val|
  total += 1 if val == 0
end
puts total

array = Array.new(gets.to_i){ gets.split }
p array.select.with_index{ |(i,j),k|
    (array[0...k]+array[k+1..-1]).none?{ |l,m| m==i }
}.size

require 'set'

def run
  n    = $stdin.gets.to_i
  a, b = $stdin.readlines.map {|l| l.split.map(&:to_i)}.transpose

  r = []
  n.times do |i|
    n.times do |j|
      r[j] = true if i != j and b[i] == a[j]
    end
  end

  puts n - r.count(true)
end

run if $0 == __FILE__

require 'set'

def run
  a = []
  b = []
  n = $stdin.gets.to_i
  $stdin.readlines.each do |line|
    ai, bi = line.split.map(&:to_i)
    a << ai
    b << bi
  end

  r = []
  n.times do |i|
    n.times do |j|
      r[j] = true if i != j and b[i] == a[j]
    end
  end

  puts n - r.count(true)
end

run if $0 == __FILE__

n = gets.to_i
a = []
b = []
n.times do
  s = gets.split.map(&:to_i)
  a << s[0]
  b << s[1] if s[0]!= s[1]
end
x = []
n.times do |i|
  n.times do |j|
    x << j unless i==j || a[i]==b[i]
  end
end
puts n - x.uniq.size

n = gets.to_i
a = []
b = []
n.times do
  s = gets.split.map(&:to_i)
  a << s[0]
  b << s[1]
end
x = []
n.times do |i|
  n.times do |j|
    x << j if (i!=j and a[i]!=b[i])
  end
end
puts n - x.sort.uniq.size

n = gets.to_i
a = []
b = []
n.times do
  s = gets.split.map(&:to_i)
  a << s[0]
  b << s[1] if s[0]!= s[1]
end
x = []
n.times do |i|
  n.times do |j|
    x << j unless i==j or a[i]==b[i]
  end
end
puts n - x.uniq.size

n = gets.to_i
a = []
b = []
n.times do
  s = gets.split.map(&:to_i)
  a << s[0]
  b << s[1] if s[0]!= s[1]
end
x = []
n.times do |i|
  n.times do |j|
    x << j if i!=j || a[i]!=b[i]
  end
end
puts n - x.uniq.size

n=gets.to_i
a=[]
x=[]
n.times{
    s,t=gets.split.map(&:to_i)
    a<<t if s != t
    x<<s
    x<<t
}
a.sort!.uniq!
x.sort!.uniq!
puts x.size-a.size

n=gets.to_i
a=[]
x=[]
n.times{
    s,t=gets.split.map(&:to_i)
    a<<t if s != t
    x<<s
    x<<t
}
a.sort.uniq
x.sort.uniq
puts x.size-a.size

n=gets.to_i
a=[]
n.times{
    s,t=gets.split.map(&:to_i)
    a<<t if s != t
}
a.sort.uniq
puts n-a.size

n=gets.to_i
a=[]
n.times{
    s,t=gets.split.map(&:to_i)
    a<<t if s != t
}
a.sort.uniq
puts a.size

def main()
	n=gets.chomp.to_i
	b1=[]
	b2=[]
	ans=0
	for i in 0...n
		ini=gets.chomp.split(" ")
		ini=ini.map{|i| i.to_i}
		ai=ini[0]
		bi=ini[1]
		b1 << ai
		b2 << bi

	end
	for i in 0...(b1.size)
		ind=b2.index(b1[i])
		if ind.nil? || ind==i
			ans+=1
		end
	end
	puts ans
end

main

def main()
	n=gets.chomp.to_i
	ans=0
	for i in 0...n
		ini=gets.chomp.split(" ")
		ini=ini.map{|i| i.to_i}
		ai=ini[0]
		bi=ini[1]
		if ai==bi
			ans+=1
		end
	end
	puts ans
end
main

def main()
	n=gets.chomp.to_i
	b1=[]
	b2=[]
	check=[]
	ans=0
	for i in 0...n
		ini=gets.chomp.split(" ")
		ini=ini.map{|i| i.to_i}
		ai=ini[0]
		bi=ini[1]
		if ai==bi
			ans+=1
			check << bi
		else
			b1 << ai
			b2 << bi
		end
	end
	for i in check
		bx=i;
		ind=b2.index(bx)
		if !ind.nil?
			ans-=1
		end
	end
	puts (b2-b1).size+ans
end
main

def main()
	n=gets.chomp.to_i
	b1=[]
	b2=[]
	check=[]
	ans=0
	for i in 0...n
		ini=gets.chomp.split(" ")
		ini=ini.map{|i| i.to_i}
		ai=ini[0]
		bi=ini[1]
		if ai==bi
			ans+=1
			check << bi
		else
			b1 << ai
			b2 << bi
		end
	end
	for i in check
		bx=i;
		ind=b2.index(bx)
		if !ind.nil?
			ans-=1
		end
	end
	b2=b2.uniq
	b1=b1.uniq
	if !(b2.empty? && b1.empty?)
		if b2.size > b1.size
			puts ans
		else
			if (b2-b1).empty?
				puts ans
			else
				puts ((b2-b1).size)+ans
			end
		end
	else
		puts ans
	end
end

main

def main()
	n=gets.chomp.to_i
	b1=[]
	b2=[]
	ans=0
	for i in 0...n
		ini=gets.chomp.split(" ")
		ini=ini.map{|i| i.to_i}
		ai=ini[0]
		bi=ini[1]
		if ai==bi
			ans+=1
		end
		b1 << ai
		b2 << bi
	end
	puts (b2-b1).size+ans
end
main

def main()
	n=gets.chomp.to_i
	ans=0
	hs={}
	for i in 0...n
		ini=gets.chomp.split(" ")
		ini=ini.map{|i| i.to_i}
		ai=ini[0]
		bi=ini[1]
		hs[ai]=bi;
	end
	keys=hs.keys
	for i in keys
		b=i;
		v=hs[b]
		if v==b
			ans+=1;
		elsif !hs.has_value?(v)
			ans+=1
		end
	end
	puts ans
end
main

def main()
	n=gets.chomp.to_i
	b1=[]
	b2=[]
	check=[]
	ans=0
	for i in 0...n
		ini=gets.chomp.split(" ")
		ini=ini.map{|i| i.to_i}
		ai=ini[0]
		bi=ini[1]
		if ai==bi
			ans+=1
			check << bi
		else
			b1 << ai
			b2 << bi
		end
	end
	for i in check
		bx=i;
		ind=b2.index(bx)
		if !ind.nil?
			ans-=1
		end
	end
	puts ans
end
main

def main()
	nm=gets.chomp.split(" ")
	n=nm[0].to_i
	m=nm[1].to_i
	ar=gets.chomp.split(" ")
	ar=ar.map{|i| i.to_i}
	inc=0
	for i in 0...m
		stop=gets.chomp
		if stop[0].chr=="3"
			inop=stop.split(" ")
			inop=inop.map{|i| i.to_i}
			puts ar[inop[1]-1]+inc
		elsif stop[0].chr=="2"
			inop=stop.split(" ")
			inop=inop.map{|i| i.to_i}
			inc+=inop[1]
		else
			inop=stop.split(" ")
			inop=inop.map{|i| i.to_i}
			ar[inop[1]-1]=inop[2]-inc
		end

	end
end
main

def main()
	n=gets.chomp.to_i
	b1=[]
	b2=[]
	check=[]
	ans=0
	for i in 0...n
		ini=gets.chomp.split(" ")
		ini=ini.map{|i| i.to_i}
		ai=ini[0]
		bi=ini[1]
		if ai==bi
			ans+=1
			check << bi
		else
			b1 << ai
			b2 << bi
		end
	end
	for i in check
		bx=i;
		ind=b2.index(bx)
		if !ind.nil?
			ans-=1
		end
	end
	b1=b1.uniq
	b2=b2.uniq
	puts (b1-b2).size+ans
end
main

n = gets.chomp.to_i
brand_to_count = {}
brand_to_can_open = {}
brand_to_same_count = {}
n.times do
  a, b = gets.chomp.split(" ").map(&:to_i)
  if a == b
    brand_to_same_count[a] = brand_to_same_count.fetch(a, 0) + 1
  else
    brand_to_can_open[b] = brand_to_can_open.fetch(b, 0) + 1
    brand_to_count[a] = brand_to_count.fetch(a, 0) + 1
  end
end
total_unopenable = 0
brand_to_same_count.each do |brand, count|
  if count == 1
    total_unopenable += 1
  end
end
brand_to_count.each do |brand, count|
  # get count
  # see how many are openable from brand_to_can_open
  openable = brand_to_can_open.fetch(brand, 0)
  unopenable = [count - openable, 0].max
  total_unopenable += unopenable
end
puts total_unopenable

array = Array.new(gets.to_i){ gets.split }
p (array.map(&:first) - array.select{ |i,j| i != j }.map(&:last)).size

require 'set'

def run
  a = []
  s = Set.new
  n = $stdin.gets.to_i
  $stdin.readlines.each do |line|
    ai, bi = line.split.map(&:to_i)
    a << ai
    s.add(bi) if ai != bi
  end

  cnt = 0
  a.each do |ai|
    cnt += 1 unless s.include?(ai)
  end
  puts cnt
end

run if $0 == __FILE__

require 'set'

def run
  s = Set.new
  n = $stdin.gets.to_i
  $stdin.readlines.each do |line|
    a, b = line.split.map(&:to_i)
    s.add(b) if a != b
  end

  puts n - s.size
end

run if $0 == __FILE__

require 'set'

def run
  a = []
  b = []
  n = $stdin.gets.to_i
  $stdin.readlines.each do |line|
    ai, bi = line.split.map(&:to_i)
    a << ai
    b << bi
  end

  r = []
  n.times do |i|
    n.times do |j|
      r[i] = true if i != j and b[i] == a[j]
    end
  end

  puts n - r.count(true)
end

run if $0 == __FILE__

n = gets.to_i
a = []
b = []
n.times do
  s = gets.split.map(&:to_i)
  a << s[0]
  b << s[1] if s[0]!= s[1]
end
puts n - a.count{|i| b.include?(i)}

n = gets.to_i
a = []
b = []
n.times do
  s = gets.split.map(&:to_i)
  a << s[0]
  b << s[1] if s[0]!= s[1]
end
x = []
n.times do |i|
  n.times do |j|
    x << j if i!=j && a[i]!=b[i]
  end
end
puts n - x.uniq.size

n = gets.to_i
a = []
b = []
n.times do
  s = gets.split.map(&:to_i)
  a << s[0]
  b << s[1]
end
x = []
n.times do |i|
  n.times do |j|
    x << j if (i!=j and a[i]!=b[i])
  end
end
puts n - x.uniq.size