You are given two polynomials:  P(x) = a0·xn + a1·xn - 1 + ... + an - 1·x + an and  Q(x) = b0·xm + b1·xm - 1 + ... + bm - 1·x + bm.  Calculate limit .

The first line contains two space-separated integers n and m (0 ≤ n, m ≤ 100) — degrees of polynomials P(x) and Q(x) correspondingly. The second line contains n + 1 space-separated integers — the factors of polynomial P(x): a0, a1, ..., an - 1, an ( - 100 ≤ ai ≤ 100, a0 ≠ 0). The third line contains m + 1 space-separated integers — the factors of polynomial Q(x): b0, b1, ..., bm - 1, bm ( - 100 ≤ bi ≤ 100, b0 ≠ 0).

If the limit equals  + ∞, print "Infinity" (without quotes). If the limit equals  - ∞, print "-Infinity" (without the quotes). If the value of the limit equals zero, print "0/1" (without the quotes). Otherwise, print an irreducible fraction — the value of limit , in the format "p/q" (without the quotes), where p is the — numerator, q (q > 0) is the denominator of the fraction.

NoteLet's consider all samples:           You can learn more about the definition and properties of limits if you follow the link: http://en.wikipedia.org/wiki/Limit_of_a_function

# cook your code here

n,m = gets.split.map{ |x| x.to_i }

first = gets.split.map{ |x| x.to_i }
second = gets.split.map{ |x| x.to_i }

if n>m
    if first[0]*second[0]>0
        puts "Infinity"
    else
        puts "-Infinity"
    end
elsif n<m
    puts "0/1"
else
    puts Rational(first[0],second[0])
end

def gcd(a, b)
	if b == 0
		return a
	end
	return gcd(b, a % b)
end

n, m = gets.split
n = n.to_i
m = m.to_i

p = gets.split.reverse
q = gets.split.reverse

if n > m
	if p.last.to_i * q.last.to_i > 0
		print "Infinity\n"
	else
		print "-Infinity\n"
	end
elsif n == m
	a, b = p.last.to_i, q.last.to_i
	if a * b > 0
		if a < 0
			a, b = -a, -b
		end
		g = gcd(a, b)
		print "%d/%d\n" % [a / g, b / g]
	else
		if a < 0
			a = -a
		end
		if b < 0
			b = -b
		end
		g = gcd(a, b)
		print "-%d/%d\n" % [a / g, b / g]
	end
else
	print "0/1\n"
end

n,m = gets.split.map{|e| e.to_i}
a1 = gets.split.map{|e| e.to_i}
a2 = gets.split.map{|e| e.to_i}
if m>n
  puts "0/1"
  exit
end
if n>m
  k = a1[0]*a2[0]
  if k>0 then puts "Infinity" else puts "-Infinity" end
  exit
end
if a2[0]<0
  a2[0]*=-1
  a1[0]*=-1
end

g = a1[0].gcd(a2[0])
puts "#{a1[0]/g}/#{a2[0]/g}"

require 'mathn'

n, m = gets.split.map(&:to_i)
pn = gets.split.first.to_i
qm = gets.split.first.to_i

sign = pn/qm < 0

if n > m
  puts "#{sign ? "-" : ""}Infinity"
elsif n < m
  puts "0/1"
else
  divs_p = pn.abs.prime_division Prime::TrialDivisionGenerator.new
  divs_q = qm.abs.prime_division Prime::TrialDivisionGenerator.new
  divs_p.each_with_index do |d, ip|
    l = divs_q.assoc d.first
    if l
      iq = divs_q.index l
      delta = [d.last, l.last].min
      divs_p[ip] = [d.first, d.last - delta]
      divs_q[iq] = [d.first, l.last - delta]
    end
  end

  puts "#{sign ? "-" : ""}#{Integer.from_prime_division divs_p }/#{Integer.from_prime_division divs_q }"
end

def gcd(a,b)
if b == 0
  return a;
else
  return gcd(b, a % b);
end
end

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

sign = nil
ans = nil
if n > m
	ans = "Infinity"
	sign = "-" if (a[0]/b[0]) < 0
elsif n < m
	ans = "0/1"
	# sign = "-" if (a[0]/b[0]) < 0
else
	num = a[0]
	den = b[0]
	if num < den
		a,b = den,num
	else
		a,b = num,den
	end
	gc = gcd(a,b)
	num /= gc
	den /= gc
	ans = "#{num.abs}/#{den.abs}"
	# puts "here"
	sign = "-" if (num/den) < 0
end

puts "#{sign}#{ans}"

# https://en.wikipedia.org/wiki/Limit_of_a_function
# Rational functions

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

if n==m
  g = a[0].gcd(b[0])
  if b[0]<0 then a[0], b[0] = -a[0], -b[0] end
  print a[0]/g,'/',b[0]/g
elsif n>m
  print (a[0]*b[0]<0 ? "-" :""),"Infinity"
elsif n<m
  print "0/1"
end

def gcd(x,y)
  return x==0?y:gcd(y%x, x)
end

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

if n==m
  g = gcd(a[0].abs, b[0].abs)
  if b[0]<0 then a[0], b[0] = -a[0], -b[0] end
  print a[0]/g,'/',b[0]/g
elsif n>m
  print (a[0]*b[0]<0 ? "-" :""),"Infinity"
elsif n<m
  print "0/1"
end

#!/usr/bin/ruby

def gcd(a, b)
	return (b != 0) ? gcd(b, a % b) : a
end

while line = gets
	m, n = line.split.map(&:to_i)
	as = gets.split.map(&:to_i)
	bs = gets.split.map(&:to_i)
	if m > n
		puts (as[0] * bs[0] < 0) ? "-Infinity" : "Infinity"
	elsif m < n
		puts "0/1"
	else
		p = as[0]
		q = bs[0]
		g = gcd(p, q);
		p /= g
		q /= g
		if q < 0
			p *= -1
			q *= -1
		end
		puts "#{p}/#{q}"
	end
end

# cook your code here

n,m = gets.split.map{ |x| x.to_i }

first = gets.split.map{ |x| x.to_i }
second = gets.split.map{ |x| x.to_i }

if n>m
    if n*m>0
        puts "Infinity"
    else
        puts "-Infinity"
    end
elsif n<m
    puts "0/1"
else
    puts Rational(first[0],second[0])
end

def gcd(a, b)
	if b == 0
		return a
	end
	return gcd(b, a % b)
end

n, m = gets.split
n = n.to_i
m = m.to_i

p = gets.split.reverse
q = gets.split.reverse

if n > m
	if p.last.to_i > 0
		print "Infinity\n"
	else
		print "-Infinity\n"
	end
elsif n == m
	a, b = p.last.to_i, q.last.to_i
	if a * b > 0
		if a < 0
			a, b = -a, -b
		end
		g = gcd(a, b)
		print "%d/%d\n" % [a / g, b / g]
	else
		if a < 0
			a = -a
		end
		if b < 0
			b = -b
		end
		g = gcd(a, b)
		print "-%d/%d\n" % [a / g, b / g]
	end
else
	print "0/1\n"
end

require 'mathn'

n, m = gets.split.map(&:to_i)
pn = gets.split.first.to_i
qm = gets.split.first.to_i

if n > m
  puts "#{pn < 0 ? "-" : ""}Infinity"
elsif n < m
  puts "#{qm < 0 ? "-" : ""}0/1"
else
  sign = pn/qm < 0
  divs_p = pn.abs.prime_division Prime::EratosthenesGenerator.new
  divs_q = qm.abs.prime_division Prime::EratosthenesGenerator.new
  divs_p.each_with_index do |d, ip|
    l = divs_q.assoc d.first
    if l
      iq = divs_q.index l
      delta = [d.last, l.last].min
      divs_p[ip] = [d.first, d.last - delta]
      divs_q[iq] = [d.first, l.last - delta]
    end
  end

  puts "#{sign ? "-" : ""}#{Integer.from_prime_division divs_p }/#{Integer.from_prime_division divs_q }"
end

require 'mathn'

n, m = gets.split.map(&:to_i)
pn = gets.split.first.to_i
qm = gets.split.first.to_i

if n > m
  puts "#{pn < 0 ? "-" : ""}Infinity"
elsif n < m
  puts "#{qm < 0 ? "-" : ""}0/1"
else
  sign = pn/qm < 0
  divs_p = pn.abs.prime_division
  divs_q = qm.abs.prime_division
  divs_p.each_with_index do |d, ip|
    l = divs_q.assoc d.first
    if l
      iq = divs_q.index l
      delta = [d.last, l.last].min
      divs_p[ip] = [d.first, d.last - delta]
      divs_q[iq] = [d.first, l.last - delta]
    end
  end

  puts "#{sign ? "-" : ""}#{Integer.from_prime_division divs_p }/#{Integer.from_prime_division divs_q }"
end

require 'mathn'

n, m = gets.split.map(&:to_i)
pn = gets.split.first.to_i
qm = gets.split.first.to_i

if n > m
  puts "#{pn < 0 ? "-" : ""}Infinity"
elsif n < m
  puts "0/1"
else
  sign = pn/qm < 0
  divs_p = pn.abs.prime_division Prime::TrialDivisionGenerator.new
  divs_q = qm.abs.prime_division Prime::TrialDivisionGenerator.new
  divs_p.each_with_index do |d, ip|
    l = divs_q.assoc d.first
    if l
      iq = divs_q.index l
      delta = [d.last, l.last].min
      divs_p[ip] = [d.first, d.last - delta]
      divs_q[iq] = [d.first, l.last - delta]
    end
  end

  puts "#{sign ? "-" : ""}#{Integer.from_prime_division divs_p }/#{Integer.from_prime_division divs_q }"
end

require 'mathn'

n, m = gets.split.map(&:to_i)
pn = gets.split.first.to_i
qm = gets.split.first.to_i

if n > m
  puts "#{pn < 0 ? "-" : ""}Infinity"
elsif n < m
  puts "#{qm < 0 ? "-" : ""}0/1"
else
  sign = pn/qm < 0
  divs_p = pn.abs.prime_division
  divs_q = qm.abs.prime_division
  divs_p.each_with_index do |d, ip|
    l = divs_q.assoc d.first
    if l
      iq = divs_q.index l
      delta = (d.last - l.last).abs
      divs_p[ip] = [d.first, d.last - delta]
      divs_q[iq] = [d.first, l.last - delta]
    end
  end

  puts "#{sign ? "-" : ""}#{Integer.from_prime_division divs_p }/#{Integer.from_prime_division divs_q }"
end

require 'mathn'

n, m = gets.split.map(&:to_i)
pn = gets.split.first.to_i
qm = gets.split.first.to_i

if n > m
  puts "#{pn < 0 ? "-" : ""}Infinity"
elsif n < m
  puts "#{qm < 0 ? "-" : ""}0/1"
else
  sign = pn/qm < 0
  divs_p = pn.abs.prime_division Prime::TrialDivisionGenerator.new
  divs_q = qm.abs.prime_division Prime::TrialDivisionGenerator.new
  divs_p.each_with_index do |d, ip|
    l = divs_q.assoc d.first
    if l
      iq = divs_q.index l
      delta = [d.last, l.last].min
      divs_p[ip] = [d.first, d.last - delta]
      divs_q[iq] = [d.first, l.last - delta]
    end
  end

  puts "#{sign ? "-" : ""}#{Integer.from_prime_division divs_p }/#{Integer.from_prime_division divs_q }"
end

def gcd(a,b)
if b == 0
  return a;
else
  return gcd(b, a % b);
end
end

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

sign = nil
ans = nil
if n > m
	ans = "Infinity"
	sign = "-" if (a[0]/b[0]) < 0
elsif n < m
	ans = "0/1"
	sign = "-" if (a[0]/b[0]) < 0
else
	num = a[0]
	den = b[0]
	if num < den
		a,b = den,num
	else
		a,b = num,den
	end
	gc = gcd(a,b)
	num /= gc
	den /= gc
	ans = "#{num}/#{den}"
	# puts "here"
	# sign = "-" if (num/den) < 0
end

puts "#{sign}#{ans}"

# https://en.wikipedia.org/wiki/Limit_of_a_function
# Rational functions

def gcd(a,b)
if b == 0
  return a;
else
  return gcd(b, a % b);
end
end

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

sign = nil
ans = nil
if n > m
	ans = "Infinity"
	sign = "-" if (a[0]/b[0]) < 0
elsif n < m
	ans = "0/1"
	# sign = "-" if (a[0]/b[0]) < 0
else
	num = a[0]
	den = b[0]
	if num < den
		a,b = den,num
	else
		a,b = num,den
	end
	gc = gcd(a,b)
	num /= gc
	den /= gc
	ans = "#{num}/#{den}"
	# puts "here"
	# sign = "-" if (num/den) < 0
end

puts "#{sign}#{ans}"

# https://en.wikipedia.org/wiki/Limit_of_a_function
# Rational functions

def gcd(x,y)
  return x==0?y:gcd(y%x, x)
end

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

if n==m
  g = gcd(a[0].abs, b[0].abs)
  if b[0]<0 then a[0], b[0] = -a[0], -b[0] end
  print a[0]/g,'/',b[0]/g
elsif n>m
  print (a[0]<0?"-":""),"Infinity"
elsif n<m
  print "0/1"
end


There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.New parliament assembly hall is a rectangle consisting of a × b chairs — a rows of b chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hallWe know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.

The first line of the input contains three integers n, a and b (1 ≤ n ≤ 10 000, 1 ≤ a, b ≤ 100) — the number of parliamentarians, the number of rows in the assembly hall and the number of seats in each row, respectively.

If there is no way to assigns seats to parliamentarians in a proper way print -1. Otherwise print the solution in a lines, each containing b integers. The j-th integer of the i-th line should be equal to the index of parliamentarian occupying this seat, or 0 if this seat should remain empty. If there are multiple possible solution, you may print any of them.

NoteIn the first sample there are many other possible solutions. For example, 3 20 1and 2 13 0The following assignment 3 21 0is incorrect, because parliamentarians 1 and 3 are both from Democrats party but will occupy neighbouring seats.

n, a, b = readline.split(' ').collect(&:to_i)
if a * b < n
  puts "-1"
else
  x, y = 1, 2
  1.upto(a) do |row|
    1.upto(b) do |col|
      if col != 1
        print " "
      end
      if ((row + col) & 1) == 0
        if (x <= n)
          print x
          x += 2
        else
          print "0"
        end
      else
        if (y <= n)
          print y
          y += 2
        else
          print "0"
        end
      end
    end
    puts ""
  end
end

n,a,b = gets.split.map(&:to_i)
res = ''
ans = []
if n>a*b
  p -1
else
  if b.odd?
    for i in (0..(a-1))
      for j in (0..(b-1))
        res+=n.to_s+' '
        if (n > 0)
          n-=1
        end
      end
      puts res
      res=''
    end
  else
    for i in (0..(a-1))
      if i.odd?
        for j in (0..(b-1))
          ans[b-1-j] = n
          if (n > 0)
            n-=1
          end
        end
      else
        for j in (0..(b-1))
          ans[j] = n
          if (n > 0)
            n-=1
          end
        end
      end
      puts ans.join(' ')
      ans.clear
    end
  end
end

n, a, b = gets().split(' ').map { |e| e.to_i  }

if a * b < n
  puts -1
  exit()
end

current = 1
total = a * b
arr = []
(0 .. a - 1).each do |row|
  r = []
  (0 .. b - 1).each do |column|
    cond = (row % 2 == 0 && column % 2 == 0) || (row % 2 == 1 && column % 2 == 1)
    r.push(cond)
  end
  arr.push(r)
end
odd = (1 .. n).to_a.select { |e| e % 2 == 1}
even = (1 .. n).to_a.select { |e| e % 2 == 0}

(0 .. a - 1).each do |row|
  (0 .. b - 1).each do |column|
    print ' ' if column > 0
    if arr[row][column]
      if odd.size > 0
        print odd.pop
      else
        print 0
      end
    else
      if even.size > 0
        print even.pop
      else
        print 0
      end
    end
  end
  puts()
end

g = gets.split(" ")
n,a,b=g[0].to_i,g[1].to_i,g[2].to_i
if n>a*b
	puts -1
else
	f=Array.new(a)
	for i in 0..a-1
		f[i] = Array.new(b, 0)
	end
	x=y=0
	dir=c=1
	while x<a && c<=n
		f[x][y]=c
		c+=1
		y+=dir
		if y<0||y>=b
			y-=dir
			x+=1
			dir*=-1
		end
	end
	for i in 0..a-1
		puts f[i].join(" ")
	end
end

array_as_string = gets
n, a, b = array_as_string.split.map(&:to_i)
if ((a * b + 1) / 2 < (n + 1) / 2)
   puts -1
else
   oddidx = 0
   evenidx = 0
   1.upto a do |row|
      arr = []
      1.upto b do |column|
         if ((row + column) % 2 == 0)
            if (oddidx < (n + 1) / 2)
               arr << (oddidx * 2 + 1)
               oddidx = oddidx + 1
            else
               arr << 0
            end
         else
            if (evenidx < n / 2)
               evenidx = evenidx + 1
               arr << evenidx * 2
            else
               arr << 0
            end
         end
      end
      puts arr.join(" ")
   end
end

n, a, b = gets.split.map(&:to_i)
res = ''
temp = []
temp.push(0)
if (n > a*b)
    p -1
else
    if b.odd?
        for i in (0..(a-1))
            for j in (0..(b-1))
                res+=n.to_s+' '
                if (n > 0)
                    n-=1
                end
            end
            puts res
            res=''
        end
    else
        for i in (0..(a-1))
            for j in (0..(b-1))
                if ((n == 0) and (temp != []))
                    res+=temp[0].to_s+' '
                    temp.delete(temp[0])
                else
                    res+=n.to_s+' '
                end
                if (n > 0)
                    n-=1
                end
            end
            if (n > 0)
                temp.push(n)
                n-=1
            end
            puts res
            res=''
        end
    end
end


Reminder: the median of the array $$$[a_1, a_2, \dots, a_{2k+1}]$$$ of odd number of elements is defined as follows: let $$$[b_1, b_2, \dots, b_{2k+1}]$$$ be the elements of the array in the sorted order. Then median of this array is equal to $$$b_{k+1}$$$.There are $$$2n$$$ students, the $$$i$$$-th student has skill level $$$a_i$$$. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the $$$2$$$ classes such that each class has odd number of students (not divisible by $$$2$$$). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of students halved. The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2 n}$$$ ($$$1 \le a_i \le 10^9$$$) — skill levels of students. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.

NoteIn the first test, there is only one way to partition students — one in each class. The absolute difference of the skill levels will be $$$|1 - 1| = 0$$$.In the second test, one of the possible partitions is to make the first class of students with skill levels $$$[6, 4, 2]$$$, so that the skill level of the first class will be $$$4$$$, and second with $$$[5, 1, 3]$$$, so that the skill level of the second class will be $$$3$$$. Absolute difference will be $$$|4 - 3| = 1$$$.Note that you can't assign like $$$[2, 3]$$$, $$$[6, 5, 4, 1]$$$ or $$$[]$$$, $$$[6, 5, 4, 1, 2, 3]$$$ because classes have even number of students.$$$[2]$$$, $$$[1, 3, 4]$$$ is also not possible because students with skills $$$5$$$ and $$$6$$$ aren't assigned to a class.In the third test you can assign the students in the following way: $$$[3, 4, 13, 13, 20], [2, 5, 8, 16, 17]$$$ or $$$[3, 8, 17], [2, 4, 5, 13, 13, 16, 20]$$$. Both divisions give minimal possible absolute difference.

T = gets.to_i

T.times do
  n = gets.to_i
  a = gets.split.map(&:to_i).sort

  puts a[n] - a[n - 1]
end

n = gets.to_i
arr = []
nums = []
n.times do
  nums << gets.to_i
  arr << gets.split.map(&:to_i).sort
end

arr.each_with_index do |ar, i|
  puts ar[nums[i]] - ar[nums[i] - 1]
end


ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a n × n magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a positive integer into the empty cell.Chris tried filling in random numbers but it didn't work. ZS the Coder realizes that they need to fill in a positive integer such that the numbers in the grid form a magic square. This means that he has to fill in a positive integer so that the sum of the numbers in each row of the grid (), each column of the grid (), and the two long diagonals of the grid (the main diagonal —  and the secondary diagonal — ) are equal. Chris doesn't know what number to fill in. Can you help Chris find the correct positive integer to fill in or determine that it is impossible?

The first line of the input contains a single integer n (1 ≤ n ≤ 500) — the number of rows and columns of the magic grid. n lines follow, each of them contains n integers. The j-th number in the i-th of them denotes ai, j (1 ≤ ai, j ≤ 109 or ai, j = 0), the number in the i-th row and j-th column of the magic grid. If the corresponding cell is empty, ai, j will be equal to 0. Otherwise, ai, j is positive. It is guaranteed that there is exactly one pair of integers i, j (1 ≤ i, j ≤ n) such that ai, j = 0.

Output a single integer, the positive integer x (1 ≤ x ≤ 1018) that should be filled in the empty cell so that the whole grid becomes a magic square. If such positive integer x does not exist, output  - 1 instead. If there are multiple solutions, you may print any of them.

NoteIn the first sample case, we can fill in 9 into the empty cell to make the resulting grid a magic square. Indeed, The sum of numbers in each row is:4 + 9 + 2 = 3 + 5 + 7 = 8 + 1 + 6 = 15.The sum of numbers in each column is:4 + 3 + 8 = 9 + 5 + 1 = 2 + 7 + 6 = 15.The sum of numbers in the two diagonals is:4 + 5 + 6 = 2 + 5 + 8 = 15.In the third sample case, it is impossible to fill a number in the empty square such that the resulting grid is a magic square.

#!/usr/bin/ruby
def chk(m)
	n=m.size
	x=y=0
	n.times{|i|
		x+=m[i][i]
		y+=m[i][n-i-1]
	}
	(
		[x]+[y]+
		m.map{|e|e.reduce(:+)}+
		m.transpose.map{|e|e.reduce(:+)}
	).group_by{|e|e}
end

n=gets.to_i
if n==1
	p 1
else
	m=$<.map{|e|e.split.map(&:to_i)}
	a=chk(m)
	if a.size!=2
		p -1
	else
		k=-a.map(&:first).minmax.reduce(:-)
		n.times{|i|n.times{|j|
			m[i][j]=k if m[i][j]==0
		}}
		a=chk(m)
		p a.size!=1 ? -1 : k
	end
end

# http://codeforces.com/contest/711/problem/B
n = gets.chomp.to_i
rows = [].tap do |a|
  n.times { a << gets.chomp.split.map(&:to_i) }
end
arr = rows.tap do |a|
  # cols
  (0...n).each { |i| a << (0...n).map { |j| rows[j][i] } }
  # diagonal
  a << (0...n).map { |i| rows[i][i] }
  a << (0...n).map { |i| rows[n - i - 1][i] }
end
not_filled, filled = arr.partition { |a| a.include?(0) }
sum_of_not_filled = not_filled.map { |a| a.inject(0, :+) }.uniq
sum_of_filled = filled.map { |a| a.inject(0, :+) }.uniq
if n == 1
  puts 1
elsif sum_of_filled.length == 1 && sum_of_not_filled.length == 1
  diff = sum_of_filled.first - sum_of_not_filled.first
  puts diff > 0 ? diff : -1
else
  puts -1
end

def magic_grid?( grid )
    n = grid.length
    sum_rows = Array.new(n, 0)
    sum_cols = Array.new(n, 0)
    sum_diag_left = sum_diag_right = 0
    n.times do |i|
        n.times do |j|
            sum_rows[i] += grid[i][j]
            sum_cols[i] += grid[j][i]
        end
        sum_diag_right += grid[i][i]
        sum_diag_left += grid[i][n - i - 1]
    end
    return false if sum_rows.uniq.length != 1 || sum_cols.uniq.length != 1
    sum_cols[0] == sum_rows[0] && sum_rows[0] == sum_diag_left && sum_diag_left == sum_diag_right
end
n = gets.strip.to_i
grid = Array.new(n) { Array.new(n, 0) }
missing_pos = Array.new(2, 0)
in_left_diag = false
in_right_diag = false
if n == 1
    puts 1
else
    n.times do |i|
        grid[i] = gets.strip.split.map(&:to_i)
        j = grid[i].each_index.select { |z| grid[i][z] == 0 } [0]
        if !j.nil?
            in_right_diag = true if i == j
            in_left_diag = true if n - i - 1 == j
            missing_pos[0] = i
            missing_pos[1] = j
        end
    end
    sum_rows = Array.new(n, 0)
    sum_cols = Array.new(n, 0)
    sum_diag_left = sum_diag_right = 0
    n.times do |i|
        n.times do |j|
            sum_rows[i] += grid[i][j]
            sum_cols[i] += grid[j][i]
        end
        sum_diag_right += grid[i][i]
        sum_diag_left += grid[i][n - i - 1]
    end
    x, y = missing_pos
    sum_req = 0
    if in_left_diag && in_right_diag
        if x == 0
            sum_req = sum_rows[n - 1]
        elsif x == n - 1
            sum_req = sum_rows[0]
        else
            sum_req = sum_rows[x - 1]
        end
        ans = sum_req - sum_diag_left
    elsif in_right_diag
        sum_req = sum_diag_left
        ans = sum_req - sum_diag_right
    elsif in_left_diag
        sum_req = sum_diag_right
        ans = sum_req - sum_diag_left
    else
        sum_req = sum_diag_left
        ans = sum_req - sum_rows[x]
    end
    grid[x][y] = ans
    if magic_grid? grid
        if ans <= 0
            puts "-1"
        else
            puts ans
        end
    else
        puts "-1"
    end
end

def mysum(a)
  nozero = true
  sum = 0
  a.each do |e|
    if e != 0
      sum += e
    else
      nozero = false
      break
    end
  end
  if nozero
    return sum
  else
    return -1
  end
end

def realsum(a)
  sum = 0
  a.each do |e|
    sum += e
  end
  return sum
end

def checkmat(mat, num)
  valid = true
  for i in 0..(mat.length-1) do
    rowsum = 0
    for ii in 0..(mat[i].length-1) do
      rowsum += mat[i][ii]
    end
    if rowsum != num
      valid = false
      break
    end
  end
  if not valid
    return false
  end
  for i in 0..(mat[0].length-1) do
    colsum = 0
    for ii in 0..(mat.length-1) do
      colsum += mat[ii][i]
    end
    if colsum != num
      valid = false
      break
    end
  end
  if not valid
    return false
  end
  dia1 = 0
  for i in 0..(mat.length-1) do
    dia1 += mat[i][i]
  end
  if dia1 != num
    return false
  end
  dia2 = 0
  for i in 0..(mat.length-1) do
    dia2 += mat[i][mat.length-1-i]
  end
  if dia2 != num
    return false
  end
  return true
end

n = gets.strip.to_i
matris = []
n.times do
  input = gets.strip.split(' ').map(&:to_i)
  matris << input
end

if n == 1
  puts 3
else
  thesum = 0
  zeroline = -1
  for i in 0..(matris.length-1) do
    x = mysum(matris[i])
    if x != -1
      thesum = x
      if zeroline != -1
        break
      end
    else
      zeroline = i
      next
    end
  end

  lol = realsum(matris[zeroline])
  trol = thesum - lol
  if trol > 0
    for i in 0..(matris[zeroline].length-1) do
      if matris[zeroline][i] == 0
        matris[zeroline][i] = trol
        break
      end
    end
    if checkmat(matris, thesum)
      puts trol
    else
      puts -1
    end
  else
    puts -1
  end
end

def func(a, n, s, t)
    a.each{|v|
        v.include?(0) ?  s<<v.inject(:+) : t<<v.inject(:+)
    }

    x=0
    f=false
    n.times{|i|
        x+=a[i][i]
        f=true if !f and a[i][i]==0
    }
    f ? s<<x : t<<x
end

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

s=[]
t=[]
func(a, n, s, t)
func(a.reverse.transpose, n, s, t)

if n==1
    p 1
elsif s.uniq.size>1 or t.uniq.size>1 or s[0]>=t[0]
    p -1
else
    p t[0]-s[0]
end

n=gets.to_i
if n==1
  p 1
  exit(0)
end
a=[]
x=n
y=n
max=0
min=10**15
n.times{|i|a<< gets.split.map(&:to_i)}
n.times{|i|
  l=0
  n.times{|j|
    l+=a[i][j]
    x,y=i,j if a[i][j]==0
  }
  max=[max,l].max
  min=[min,l].min
}
a[x][y] =[max-min,1].max
max=0
n.times{|i| max+=a[x][i]}
n.times{|i|
  v,h=0,0
  n.times{|j|
    v+=a[i][j]
    h+=a[j][i]
  }
  if v!=max || h!=max
    p -1
    exit(0)
  end
}
v,h=0,0
n.times{|i|
  v+=a[i][i]
  h+=a[i][n-1-i]
}
if (v!=max)||(h!=max)
  p -1
  exit(0)
end
p a[x][y]

n = gets.to_i
a = n.times.map{gets.split.map(&:to_i)}
sum_row, sum_col, sum_dia = Array.new(n, 0), Array.new(n, 0), Array.new(2, 0)
x, y = 0, 0
n.times do |i|
  n.times do |j|
    sum_row[i] += a[i][j]
    sum_col[j] += a[i][j]
    sum_dia[0] += a[i][j] if i == j
    sum_dia[1] += a[i][j] if i + j == n - 1
    x, y = i, j if a[i][j] == 0
  end
end
candidate = ( sum_row.uniq.last - sum_row.uniq.first ).abs
if n == 1
  puts 1
else
  sum_row[x] += candidate
  sum_col[y] += candidate
  sum_dia[0] += candidate if x == y
  sum_dia[1] += candidate if x + y == n - 1
  possible = candidate != 0 &&
    sum_row.uniq.size == 1 &&
    sum_col.uniq.size == 1 &&
    sum_dia.uniq.size == 1 &&
    sum_row.first == sum_col.first &&
    sum_col.first == sum_dia.first
  puts possible ? candidate : -1
end

n = gets.to_i
a = n.times.map{gets.split.map(&:to_i)}
sum_row = Array.new(n, 0)
sum_col = Array.new(n, 0)
sum_dia = Array.new(2, 0)
x, y = nil, nil
n.times do |i|
  n.times do |j|
    cur = a[i][j]
    sum_row[i] += cur
    sum_col[j] += cur
    sum_dia[0] += cur if i == j
    sum_dia[1] += cur if i + j == n - 1
    x, y = i, j if cur == 0
  end
end
ans = (sum_row.uniq.last - sum_row.uniq.first).abs
if n == 1
  puts 1437
else
  sum_row[x] += ans
  sum_col[y] += ans
  sum_dia[0] += ans if x == y
  sum_dia[1] += ans if x + y == n - 1
  valid = ans != 0 && (sum_row + sum_col + sum_dia).uniq.size == 1
  puts valid ? ans : -1
end

n = gets.to_i
a = Array.new(n)
w = 0
h = 0
s1 = 0
s2 = 0
b = Array.new(n, 0)
c = Array.new(n, 0)
n.times{|i|
    a[i] = gets.split.map(&:to_i)
    n.times{|j|
        if a[i][j] == 0
            w = j
            h = i
        end
        if i == j
            s1 += a[i][j]
        end
        if i + j == n - 1
            s2 += a[i][j]
        end
        b[i] += a[i][j]
        c[j] += a[i][j]
        }
    }
if h == 0
    if n == 1
        p 1
        exit
    end
    sum = b[1]
else
    sum = b[0]
end
n.times{|i|
    if i != h && sum != b[i]
        p -1
        exit
    end
    }
n.times{|i|
    if i != w && sum != c[i]
        p -1
        exit
    end
    }
tmp1 = b[h]
tmp2 = c[w]
if tmp1 == tmp2 && sum > tmp1
    if w == h
        if s1 != tmp1
            p -1
            exit
        end
    elsif s1 != sum
        p -1
        exit
    end
    if w + h == n - 1
        if s2 != tmp1
            p -1
            exit
        end
    elsif s2 != sum
        p -1
        exit
    end
    p sum - tmp1
else
    p -1
end

n=readline.to_i
a = []
found = false
(1..n).each do
	ai = readline.split.map(&:to_i)
	a << ai
end

filled = []
not_filled = []
(0...n).each do |i|
	row = a[i]
	if row.include? 0
		not_filled << row.reduce(&:+)
	else
		filled << row.reduce(&:+)
	end

	col = (0...n).map{|j| a[j][i]}
	if col.include? 0
		not_filled << col.reduce(&:+)
	else
		filled << col.reduce(&:+)
	end
end

dia_1 = (0...n).map{|j| a[j][j]}
dia_2 = (0...n).map{|j| a[n-j-1][j]}

if dia_1.include? 0
	not_filled << dia_1.reduce(&:+)
else
	filled << dia_1.reduce(&:+)
end

if dia_2.include? 0
	not_filled << dia_2.reduce(&:+)
else
	filled << dia_2.reduce(&:+)
end

filled.uniq!
not_filled.uniq!
if n == 1
	puts 1
elsif filled.size == 1 && not_filled.size == 1 && filled[0] > not_filled[0]
	puts filled[0]-not_filled[0]
else
	puts -1
end

#!/usr/bin/ruby
n=gets.to_i
if n==1
	p 1
else
	m=$<.map{|e|e.split.map(&:to_i)}
	x=y=0
	n.times{|i|
		x+=m[i][i]
		y+=m[i][n-i-1]
	}
	a=(
		[x]+[y]+
		m.map{|e|e.reduce(:+)}+
		m.transpose.map{|e|e.reduce(:+)}
	).group_by{|e|e}
	if a.size==2
		p -a.map(&:first).minmax.reduce(:-)
	else
		p -1
	end
end

#!/usr/bin/ruby
n=gets.to_i
if n==1
	p 1
else
	m=$<.map{|e|e.split}
	a=(
		m.map{|e|e.map(&:to_i).reduce(:+)}+
		m.transpose.map{|e|e.map(&:to_i).reduce(:+)}
	).group_by{|e|e}
	if a.size==2
		p -a.map(&:first).minmax.reduce(:-)
	else
		p -1
	end
end

#!/usr/bin/ruby
def chk(m)
	n=m.size
	x=y=0
	n.times{|i|
		x+=m[i][i]
		y+=m[i][n-i-1]
	}
	(
		[x]+[y]+
		m.map{|e|e.reduce(:+)}+
		m.transpose.map{|e|e.reduce(:+)}
	).group_by{|e|e}
end

n=gets.to_i
if n==1
	p 1
else
	m=$<.map{|e|e.split.map(&:to_i)}
	a=chk(m)
	if a.size!=2
		p -1
	else
		k=-a.map(&:first).minmax.reduce(:-)
		n.times{|i|n.times{|j|
			m[i][j]=k if m[i][j]==0
		}}
		a=chk(m)
		p a.size!=2 ? -1 : k
	end
end

# http://codeforces.com/contest/711/problem/B
n = gets.chomp.to_i
rows = [].tap do |a|
  n.times { a << gets.chomp.split.map(&:to_i) }
end
arr = rows.tap do |a|
  # cols
  (0...n).each { |i| a << (0...n).map { |j| rows[j][i] } }
  # diagonal
  a << (0...n).map { |i| rows[i][i] }
  a << (0...n).map { |i| rows[n - i - 1][i] }
end
not_filled, filled = arr.partition { |a| a.include?(0) }
sum_of_not_filled = not_filled.map { |a| a.inject(0, :+) }.uniq
sum_of_filled = filled.map { |a| a.inject(0, :+) }.uniq
if n == 1
  puts 1
elsif sum_of_filled.length == 1 && sum_of_not_filled.length == 1
  puts sum_of_filled.first - sum_of_not_filled.first
else
  puts -1
end

def magic_grid?( grid )
    n = grid.length
    sum_rows = Array.new(n, 0)
    sum_cols = Array.new(n, 0)
    sum_diag_left = sum_diag_right = 0
    n.times do |i|
        n.times do |j|
            sum_rows[i] += grid[i][j]
            sum_cols[i] += grid[j][i]
        end
        sum_diag_right += grid[i][i]
        sum_diag_left += grid[i][n - i - 1]
    end
    return false if sum_rows.uniq.length != 1 || sum_cols.uniq.length != 1
    sum_cols[0] == sum_rows[0] && sum_rows[0] == sum_diag_left && sum_diag_left == sum_diag_right
end
n = gets.strip.to_i
grid = Array.new(n) { Array.new(n, 0) }
missing_pos = Array.new(2, 0)
in_left_diag = false
in_right_diag = false
n.times do |i|
    grid[i] = gets.strip.split.map(&:to_i)
    j = grid[i].each_index.select { |z| grid[i][z] == 0 } [0]
    if !j.nil?
        in_right_diag = true if i == j
        in_left_diag = true if n - i - 1 == j
        missing_pos[0] = i
        missing_pos[1] = j
    end
end
sum_rows = Array.new(n, 0)
sum_cols = Array.new(n, 0)
sum_diag_left = sum_diag_right = 0
n.times do |i|
    n.times do |j|
        sum_rows[i] += grid[i][j]
        sum_cols[i] += grid[j][i]
    end
    sum_diag_right += grid[i][i]
    sum_diag_left += grid[i][n - i - 1]
end
x, y = missing_pos
sum_req = 0
if in_left_diag && in_right_diag
    if x == 0
        sum_req = sum_rows[n - 1]
    elsif x == n - 1
        sum_req = sum_rows[0]
    else
        sum_req = sum_rows[x - 1]
    end
    ans = sum_req - sum_diag_left
elsif in_right_diag
    sum_req = sum_diag_left
    ans = sum_req - sum_diag_right
elsif in_left_diag
    sum_req = sum_diag_right
    ans = sum_req - sum_diag_left
else
    sum_req = sum_diag_left
    ans = sum_req - sum_rows[x]
end
grid[x][y] = ans
if magic_grid? grid
    puts ans
else
    puts "-1"
end

def magic_grid?( grid )
    n = grid.length
    sum_rows = Array.new(n, 0)
    sum_cols = Array.new(n, 0)
    sum_diag_left = sum_diag_right = 0
    n.times do |i|
        n.times do |j|
            sum_rows[i] += grid[i][j]
            sum_cols[i] += grid[j][i]
        end
        sum_diag_right += grid[i][i]
        sum_diag_left += grid[i][n - i - 1]
    end
    return false if sum_rows.uniq.length != 1 || sum_cols.uniq.length != 1
    sum_cols[0] == sum_rows[0] && sum_rows[0] == sum_diag_left && sum_diag_left == sum_diag_right
end
n = gets.strip.to_i
grid = Array.new(n) { Array.new(n, 0) }
missing_pos = Array.new(2, 0)
in_left_diag = false
in_right_diag = false
if n == 1
    puts 1
else
    n.times do |i|
        grid[i] = gets.strip.split.map(&:to_i)
        j = grid[i].each_index.select { |z| grid[i][z] == 0 } [0]
        if !j.nil?
            in_right_diag = true if i == j
            in_left_diag = true if n - i - 1 == j
            missing_pos[0] = i
            missing_pos[1] = j
        end
    end
    sum_rows = Array.new(n, 0)
    sum_cols = Array.new(n, 0)
    sum_diag_left = sum_diag_right = 0
    n.times do |i|
        n.times do |j|
            sum_rows[i] += grid[i][j]
            sum_cols[i] += grid[j][i]
        end
        sum_diag_right += grid[i][i]
        sum_diag_left += grid[i][n - i - 1]
    end
    x, y = missing_pos
    sum_req = 0
    if in_left_diag && in_right_diag
        if x == 0
            sum_req = sum_rows[n - 1]
        elsif x == n - 1
            sum_req = sum_rows[0]
        else
            sum_req = sum_rows[x - 1]
        end
        ans = sum_req - sum_diag_left
    elsif in_right_diag
        sum_req = sum_diag_left
        ans = sum_req - sum_diag_right
    elsif in_left_diag
        sum_req = sum_diag_right
        ans = sum_req - sum_diag_left
    else
        sum_req = sum_diag_left
        ans = sum_req - sum_rows[x]
    end
    grid[x][y] = ans
    if magic_grid? grid
        puts ans
    else
        puts "-1"
    end
end

def magic_grid?( grid )
    n = grid.length
    sum_rows = Array.new(n, 0)
    sum_cols = Array.new(n, 0)
    sum_diag_left = sum_diag_right = 0
    n.times do |i|
        n.times do |j|
            sum_rows[i] += grid[i][j]
            sum_cols[i] += grid[j][i]
        end
        sum_diag_right += grid[i][i]
        sum_diag_left += grid[i][n - i - 1]
    end
    return false if sum_rows.uniq.length != 1 || sum_cols.uniq.length != 1
    sum_cols[0] == sum_rows[0] && sum_rows[0] == sum_diag_left && sum_diag_left == sum_diag_right
end
n = gets.strip.to_i
grid = Array.new(n) { Array.new(n, 0) }
missing_pos = Array.new(2, 0)
in_left_diag = false
in_right_diag = false
if n == 1
    puts 1
else
    n.times do |i|
        grid[i] = gets.strip.split.map(&:to_i)
        j = grid[i].each_index.select { |z| grid[i][z] == 0 } [0]
        if !j.nil?
            in_right_diag = true if i == j
            in_left_diag = true if n - i - 1 == j
            missing_pos[0] = i
            missing_pos[1] = j
        end
    end
    sum_rows = Array.new(n, 0)
    sum_cols = Array.new(n, 0)
    sum_diag_left = sum_diag_right = 0
    n.times do |i|
        n.times do |j|
            sum_rows[i] += grid[i][j]
            sum_cols[i] += grid[j][i]
        end
        sum_diag_right += grid[i][i]
        sum_diag_left += grid[i][n - i - 1]
    end
    x, y = missing_pos
    sum_req = 0
    if in_left_diag && in_right_diag
        if x == 0
            sum_req = sum_rows[n - 1]
        elsif x == n - 1
            sum_req = sum_rows[0]
        else
            sum_req = sum_rows[x - 1]
        end
        ans = sum_req - sum_diag_left
    elsif in_right_diag
        sum_req = sum_diag_left
        ans = sum_req - sum_diag_right
    elsif in_left_diag
        sum_req = sum_diag_right
        ans = sum_req - sum_diag_left
    else
        sum_req = sum_diag_left
        ans = sum_req - sum_rows[x]
    end
    grid[x][y] = ans
    if magic_grid? grid
        if ans == 0
            puts "-1"
        else
            puts ans
        end
    else
        puts "-1"
    end
end

def magic_grid?( grid )
    n = grid.length
    sum_rows = Array.new(n, 0)
    sum_cols = Array.new(n, 0)
    sum_diag_left = sum_diag_right = 0
    n.times do |i|
        n.times do |j|
            sum_rows[i] += grid[i][j]
            sum_cols[i] += grid[j][i]
        end
        sum_diag_right += grid[i][i]
        sum_diag_left += grid[i][n - i - 1]
    end
    return false if sum_rows.uniq.length != 1 || sum_cols.uniq.length != 1
    sum_cols[0] == sum_rows[0] && sum_rows[0] == sum_diag_left && sum_diag_left == sum_diag_right
end
n = gets.strip.to_i
grid = Array.new(n) { Array.new(n, 0) }
missing_pos = Array.new(2, 0)
in_left_diag = false
in_right_diag = false
n.times do |i|
    grid[i] = gets.strip.split.map(&:to_i)
    j = grid[i].each_index.select { |z| grid[i][z] == 0 } [0]
    if !j.nil?
        in_right_diag = true if i == j
        in_left_diag = true if n - i - 1 == j
        missing_pos[0] = i
        missing_pos[1] = j
    end
end
sum_rows = Array.new(n, 0)
sum_cols = Array.new(n, 0)
sum_diag_left = sum_diag_right = 0
n.times do |i|
    n.times do |j|
        sum_rows[i] += grid[i][j]
        sum_cols[i] += grid[j][i]
    end
    sum_diag_right += grid[i][i]
    sum_diag_left += grid[i][n - i - 1]
end
x, y = missing_pos
sum_req = 0
if in_left_diag && in_right_diag
    if x == 0
        sum_req = sum_rows[n - 1]
    elsif x == n - 1
        sum_req = sum_rows[0]
    else
        sum_req = sum_rows[x - 1]
    end
    ans = sum_req - sum_diag_left
elsif in_right_diag
    if x == 0
        sum_req = sum_rows[n - 1]
    elsif x == n - 1
        sum_req = sum_rows[0]
    else
        sum_req = sum_rows[x - 1]
    end
    ans = sum_req - sum_diag_right
elsif in_left_diag
    if x == 0
        sum_req = sum_rows[n - 1]
    elsif x == n - 1
        sum_req = sum_rows[0]
    else
        sum_req = sum_rows[x - 1]
    end
    ans = sum_req - sum_diag_left
else
    sum_req = sum_diag_left
    ans = sum_req - sum_rows[x]
end
grid[x][y] = ans
if magic_grid? grid
    puts ans
else
    puts "-1"
end

def mysum(a)
  nozero = true
  sum = 0
  a.each do |e|
    if e != 0
      sum += e
    else
      nozero = false
      break
    end
  end
  if nozero
    return sum
  else
    return -1
  end
end

def realsum(a)
  sum = 0
  a.each do |e|
    sum += e
  end
  return sum
end

def checkmat(mat, num)
  valid = true
  for i in 0..(mat.length-1) do
    rowsum = 0
    for ii in 0..(mat[i].length-1) do
      rowsum += mat[i][ii]
    end
    if rowsum != num
      valid = false
      break
    end
  end
  if not valid
    return false
  end
  for i in 0..(mat[0].length-1) do
    colsum = 0
    for ii in 0..(mat.length-1) do
      colsum += mat[ii][i]
    end
    if colsum != num
      valid = false
      break
    end
  end
  if not valid
    return false
  end
  dia1 = 0
  for i in 0..(mat.length-1) do
    dia1 += mat[i][i]
  end
  if dia1 != num
    return false
  end
  dia2 = 0
  for i in 0..(mat.length-1) do
    dia2 += mat[i][mat.length-1-i]
  end
  if dia2 != num
    return false
  end
  return true
end

n = gets.strip.to_i
matris = []
n.times do
  input = gets.strip.split(' ').map(&:to_i)
  matris << input
end

if n == 1
  puts matris[0][0]
else
  thesum = 0
  zeroline = -1
  for i in 0..(matris.length-1) do
    x = mysum(matris[i])
    if x != -1
      thesum = x
      if zeroline != -1
        break
      end
    else
      zeroline = i
      next
    end
  end

  lol = realsum(matris[zeroline])
  trol = thesum - lol
  if trol > 0
    for i in 0..(matris[zeroline].length-1) do
      if matris[zeroline][i] == 0
        matris[zeroline][i] = trol
        break
      end
    end
    if checkmat(matris, thesum)
      puts trol
    else
      puts -1
    end
  else
    puts -1
  end
end

def mysum(a)
  nozero = true
  sum = 0
  a.each do |e|
    if e != 0
      sum += e
    else
      nozero = false
      break
    end
  end
  if nozero
    return sum
  else
    return -1
  end
end

def realsum(a)
  sum = 0
  a.each do |e|
    sum += e
  end
  return sum
end

def checkmat(mat, num)
  valid = true
  for i in 0..(mat.length-1) do
    rowsum = 0
    for ii in 0..(mat[i].length-1) do
      rowsum += mat[i][ii]
    end
    if rowsum != num
      valid = false
      break
    end
  end
  if not valid
    return false
  end
  for i in 0..(mat[0].length-1) do
    colsum = 0
    for ii in 0..(mat.length-1) do
      colsum += mat[i][ii]
    end
    if colsum != num
      valid = false
      break
    end
  end
  if not valid
    return false
  end
  dia1 = 0
  for i in 0..(mat.length-1) do
    dia1 += mat[i][i]
  end
  if dia1 != num
    return false
  end
  dia2 = 0
  for i in 0..(mat.length-1) do
    dia2 += mat[i][mat.length-1-i]
  end
  if dia2 != num
    return false
  end
  return true
end

n = gets.strip.to_i
matris = []
n.times do
  input = gets.strip.split(' ').map(&:to_i)
  matris << input
end

if n == 1
  puts matris[0][0]
else
  thesum = 0
  zeroline = -1
  for i in 0..(matris.length-1) do
    x = mysum(matris[i])
    if x != -1
      thesum = x
      if zeroline != -1
        break
      end
    else
      zeroline = i
      next
    end
  end

  lol = realsum(matris[zeroline])
  trol = thesum - lol
  if trol > 0
    for i in 0..(matris[zeroline].length-1) do
      if matris[zeroline][i] == 0
        matris[zeroline][i] = trol
        break
      end
    end
    if checkmat(matris, thesum)
      puts trol
    else
      puts -1
    end
  else
    puts -1
  end
end

def func(a, n, s, t)
    a.each do |v|
        if v.include?(0)
            s<<v.inject(:+)
        else
            t<<v.inject(:+)
        end
    end

    x=0
    f=false
    n.times do |i|
        x+=a[i][i]
        f=true if !f and a[i][i]==0
    end
    f ? s<<x : t<<x
end

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

s=[]
t=[]
func(a, n, s, t)
func(a.transpose, n, s, t)

if s.uniq.size>1 or t.uniq.size>1 or s[0]>=t[0]
    p -1
else
    p s[0]-t[0]
end

def func(a, n, s, t)
    a.each{|v|
        v.include?(0) ?  s<<v.inject(:+) : t<<v.inject(:+)
    }

    x=0
    f=false
    n.times{|i|
        x+=a[i][i]
        f=true if !f and a[i][i]==0
    }
    f ? s<<x : t<<x
end

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

s=[]
t=[]
func(a, n, s, t)
func(a.transpose, n, s, t)

if n==1
    p 1
elsif s.uniq.size>1 or t.uniq.size>1 or s[0]>=t[0]
    p -1
else
    p t[0]-s[0]
end

n = gets.to_i
a = n.times.map{gets.split.map(&:to_i)}
summed = a.map{|x| x.inject(&:+)}.sort
possible = true
if n == 1
  possible = false
elsif !(summed.uniq.size == 2 && summed.last - summed.first > 0)
  possible = false
else
  possible = n.times.map{|x| a[x][x] == 0 ? summed.last - summed.first : a[x][x]}.inject(&:+) == n.times.map{|x| a[x][n - x - 1] == 0 ? summed.last - summed.first : a[x][n - x - 1]}.inject(&:+)
end
puts possible ? summed.last - summed.first : -1

n = gets.to_i
a = n.times.map{gets.split.map(&:to_i)}
summed = a.map{|x| x.inject(&:+)}.sort
possible = true
if n == 1
  possible = false
elsif summed.uniq.size != 2
  possible = false
elsif summed.last - summed.first <= 0
  possible = false
else
  possible = ( n.times.map{|x| a[x][x] == 0 ? summed.last - summed.first : a[x][x]}.inject(&:+) == n.times.map{|x| a[x][n - x - 1] == 0 ? summed.last - summed.first : a[x][n - x - 1]}.inject(&:+) )
end
puts possible ? summed.last - summed.first : -1

n = gets.to_i
a = n.times.map{gets.split.map(&:to_i)}
row, col = Array.new(n, 0), Array.new(n, 0)
n.times do |i|
  n.times do |j|
    row[i] += a[i][j]
    col[j] += a[i][j]
  end
end
guess1 = row.uniq.sort.last - row.uniq.sort.first
guess2 = col.uniq.sort.last - col.uniq.sort.first
dia1 = n.times.map{|x| a[x][x] == 0 ? guess1 : a[x][x]}.inject(&:+)
dia2 = n.times.map{|x| a[x][n - 1 - x] == 0 ? guess1 : a[x][n - 1 - x]}.inject(&:+)
if n == 1
  puts 1
else
  puts row.uniq.size == 2 && col.uniq.size == 2 && guess1 == guess2 && dia1 == dia2 ? guess1 : -1
end

n = gets.to_i
a = n.times.map{gets.split.map(&:to_i)}
summed = a.map{|x| x.inject(&:+)}.sort
if n == 1
  puts 1
else
  puts summed.uniq.size == 2 && summed.last - summed.first > 0 ? summed.last - summed.first : -1
end

n = gets.to_i
a = n.times.map{gets.split.map(&:to_i)}
row, col = Array.new(n, 0), Array.new(n, 0)
n.times do |i|
  n.times do |j|
    row[i] += a[i][j]
    col[j] += a[i][j]
  end
end
guess1 = row.uniq.sort.last - row.uniq.sort.first
guess2 = col.uniq.sort.last - col.uniq.sort.first
dia1 = n.times.map{|x| a[x][x] == 0 ? guess1 : a[x][x]}.inject(&:+)
dia2 = n.times.map{|x| a[x][n - 1 - x] == 0 ? guess1 : a[x][n - 1 - x]}.inject(&:+)
if n == 1
  puts 1
else
  puts guess1 == guess2 && dia1 == dia2 ? guess1 : -1
end

n = gets.to_i
a = n.times.map{gets.split.map(&:to_i)}
summed = a.map{|x| x.inject(&:+)}.sort
puts summed.uniq.size == 2 && summed.last - summed.first > 0 ? summed.last - summed.first : -1

n = gets.to_i
a = n.times.map{gets.split.map(&:to_i)}
sum_row, sum_col, sum_dia = Array.new(n, 0), Array.new(n, 0), Array.new(2, 0)
x, y = 0, 0
n.times do |i|
  n.times do |j|
    sum_row[i] += a[i][j]
    sum_col[j] += a[i][j]
    sum_dia[0] += a[i][j] if i == j
    sum_dia[1] += a[i][j] if i + j == n - 1
    x, y = i, j if a[i][j] == 0
  end
end
candidate = ( sum_row.uniq.last - sum_row.uniq.first ).abs
if n == 1
  puts 1
else
  sum_row[x] += candidate
  sum_col[y] += candidate
  sum_dia[0] += candidate if x == y
  sum_dia[1] += candidate if x + y == n - 1
  puts sum_row.uniq.size == 1 && sum_col.uniq.size == 1 && sum_dia.uniq.size == 1 && candidate != 0 ? candidate : -1
end

n = gets.to_i
a = n.times.map{gets.split.map(&:to_i)}
sum_row, sum_col, sum_dia = Array.new(n, 0), Array.new(n, 0), Array.new(2, 0)
x, y = 0, 0
n.times do |i|
  n.times do |j|
    sum_row[i] += a[i][j]
    sum_col[j] += a[i][j]
    sum_dia[0] += a[i][j] if i == j
    sum_dia[1] += a[i][j] if i + j == n - 1
    x, y = i, j if a[i][j] == 0
  end
end
candidate = ( sum_row.uniq.last - sum_row.uniq.first ).abs
if n == 1
  puts 1
else
  sum_row[x] += candidate
  sum_col[y] += candidate
  sum_dia[0] += candidate if x == y
  sum_dia[1] += candidate if x + y == n - 1
  puts sum_row.uniq.size == 1 && sum_col.uniq.size == 1 && sum_dia.uniq.size == 1 ? candidate : -1
end

n = gets.to_i
a = Array.new(n)
w = 0
h = 0
n.times{|i|
    a[i] = gets.split.map(&:to_i)
    n.times{|j|
        if a[i][j] == 0
            w = j
            h = i
        end
        }
    }
sum = 0
if h == 0
    if n == 1
        p 1
        exit
    end
    sum = a[1].inject(:+)
else
    sum = a[0].inject(:+)
end
tmp = a[h].inject(:+)
if tmp == a.transpose[w].inject(:+) && sum > tmp
    p sum - tmp
else
    p -1
end

n = gets.to_i
a = Array.new(n)
w = 0
h = 0
s1 = 0
s2 = 0
n.times{|i|
    a[i] = gets.split.map(&:to_i)
    n.times{|j|
        if a[i][j] == 0
            w = j
            h = i
        end
        if i == j
            s1 += a[i][j]
        end
        if i + j == n - 1
            s2 += a[i][j]
        end
        }
    }
sum = 0
if h == 0
    if n == 1
        p 1
        exit
    end
    sum = a[1].inject(:+)
else
    sum = a[0].inject(:+)
end
tmp1 = a[h].inject(:+)
tmp2 = a.transpose[w].inject(:+)
if tmp1 == tmp2 && sum > tmp1
    if w == h && s1 != tmp1
        p -1
        exit
    end
    if w + h == n - 1 && s2 != tmp1
        p -1
        exit
    end
    p sum - tmp1
else
    p -1
end

n = gets.to_i
a = Array.new(n)
w = 0
h = 0
s1 = 0
s2 = 0
b = Array.new(n, 0)
c = Array.new(n, 0)
n.times{|i|
    a[i] = gets.split.map(&:to_i)
    n.times{|j|
        if a[i][j] == 0
            w = j
            h = i
        end
        if i == j
            s1 += a[i][j]
        end
        if i + j == n - 1
            s2 += a[i][j]
        end
        b[i] += a[i][j]
        c[j] += a[i][j]
        }
    }
if h == 0
    if n == 1
        p 1
        exit
    end
    sum = b[1]
else
    sum = b[0]
end
n.times{|i|
    if i != h && sum != b[i]
        p -1
        exit
    end
    }
n.times{|i|
    if i != w && sum != c[i]
        p -1
        exit
    end
    }
tmp1 = b[h]
tmp2 = c[w]
if tmp1 == tmp2 && sum > tmp1
    if w == h && s1 != tmp1
        p -1
        exit
    end
    if w + h == n - 1 && s2 != tmp1
        p -1
        exit
    end
    p sum - tmp1
else
    p -1
end

n = gets.to_i
a = Array.new(n)
w = 0
h = 0
s1 = 0
s2 = 0
b = Array.new(n, 0)
c = Array.new(n, 0)
n.times{|i|
    a[i] = gets.split.map(&:to_i)
    n.times{|j|
        if a[i][j] == 0
            w = j
            h = i
        end
        if i == j
            s1 += a[i][j]
        end
        if i + j == n - 1
            s2 += a[i][j]
        end
        b[i] += a[i][j]
        c[j] += a[i][j]
        }
    }
if h == 0
    if n == 1
        p 1
        exit
    end
    sum = b[1]
else
    sum = b[0]
end
n.times{|i|
    if i != h && sum != b[i]
        p -1
        exit
    end
    }
n.times{|i|
    if i != w && sum != c[i]
        p -1
        exit
    end
    }
tmp1 = b[h]
tmp2 = c[w]
if tmp1 == tmp2 && sum > tmp1
    if w == h && s1 != tmp1 || s1 != sum
        p -1
        exit
    end
    if w + h == n - 1 && s2 != tmp1 || s2 != sum
        p -1
        exit
    end
    p sum - tmp1
else
    p -1
end

n=readline.to_i
a = []
found = false
(1..n).each do
	ai = readline.split.map(&:to_i)
	a << ai
end

filled = []
not_filled = []
(0...n).each do |i|
	row = a[i]
	if row.include? 0
		not_filled << row.reduce(&:+)
	else
		filled << row.reduce(&:+)
	end

	col = (0...n).map{|j| a[j][i]}
	if col.include? 0
		not_filled << col.reduce(&:+)
	else
		filled << col.reduce(&:+)
	end
end

dia_1 = (0...n).map{|j| a[j][j]}
dia_2 = (0...n).map{|j| a[n-j-1][j]}

if dia_1.include? 0
	not_filled << dia_1.reduce(&:+)
else
	filled << dia_1.reduce(&:+)
end

if dia_2.include? 0
	not_filled << dia_2.reduce(&:+)
else
	filled << dia_2.reduce(&:+)
end

filled.uniq!
not_filled.uniq!
if filled.size == 1 && not_filled.size == 1 && filled[0] > not_filled[0]
	puts filled[0]-not_filled[0]
else
	puts -1
end

n=readline.to_i
a = []
found = false
(1..n).each do
	ai = readline.split.map(&:to_i)
	a << ai
end

filled = []
not_filled = []
(0...n).each do |i|
	row = a[i]
	if row.include? 0
		not_filled << row.reduce(&:+)
	else
		filled << row.reduce(&:+)
	end

	col = (0...n).map{|j| a[j][i]}
	if col.include? 0
		not_filled << col.reduce(&:+)
	else
		filled << col.reduce(&:+)
	end
end

dia_1 = (0...n).map{|j| a[j][j]}
dia_2 = (0...n).map{|j| a[n-j-1][j]}

if dia_1.include? 0
	not_filled << dia_1.reduce(&:+)
else
	filled << dia_1.reduce(&:+)
end

if dia_2.include? 0
	not_filled << dia_2.reduce(&:+)
else
	filled << dia_2.reduce(&:+)
end

filled.uniq!
not_filled.uniq!
if filled.size == 1 && not_filled.size == 1
	puts filled[0]-not_filled[0]
else
	puts -1
end


Another Codeforces Round has just finished! It has gathered $$$n$$$ participants, and according to the results, the expected rating change of participant $$$i$$$ is $$$a_i$$$. These rating changes are perfectly balanced — their sum is equal to $$$0$$$.Unfortunately, due to minor technical glitches, the round is declared semi-rated. It means that all rating changes must be divided by two.There are two conditions though:   For each participant $$$i$$$, their modified rating change $$$b_i$$$ must be integer, and as close to $$$\frac{a_i}{2}$$$ as possible. It means that either $$$b_i = \lfloor \frac{a_i}{2} \rfloor$$$ or $$$b_i = \lceil \frac{a_i}{2} \rceil$$$. In particular, if $$$a_i$$$ is even, $$$b_i = \frac{a_i}{2}$$$. Here $$$\lfloor x \rfloor$$$ denotes rounding down to the largest integer not greater than $$$x$$$, and $$$\lceil x \rceil$$$ denotes rounding up to the smallest integer not smaller than $$$x$$$.  The modified rating changes must be perfectly balanced — their sum must be equal to $$$0$$$. Can you help with that?

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 13\,845$$$), denoting the number of participants. Each of the next $$$n$$$ lines contains a single integer $$$a_i$$$ ($$$-336 \le a_i \le 1164$$$), denoting the rating change of the $$$i$$$-th participant. The sum of all $$$a_i$$$ is equal to $$$0$$$.

Output $$$n$$$ integers $$$b_i$$$, each denoting the modified rating change of the $$$i$$$-th participant in order of input. For any $$$i$$$, it must be true that either $$$b_i = \lfloor \frac{a_i}{2} \rfloor$$$ or $$$b_i = \lceil \frac{a_i}{2} \rceil$$$. The sum of all $$$b_i$$$ must be equal to $$$0$$$. If there are multiple solutions, print any. We can show that a solution exists for any valid input.

NoteIn the first example, $$$b_1 = 5$$$, $$$b_2 = -3$$$ and $$$b_3 = -2$$$ is another correct solution.In the second example there are $$$6$$$ possible solutions, one of them is shown in the example output.

def calcs(x,y,ax,ay,bx,by) ((ax-x)*(by-y)-(bx-x)*(ay-y))/2.0 end
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 kaizyo(n)(n < 2)? 1 : (2..n).inject(:*) end
def scount(a) b=na(a.max+1);a.each{|n|b[n]+=1};return b end
def na(n=0,d=0) Array.new(n,d)end
def na2(n=0,m=0,d=0) Array.new(n){Array.new(m,d)}end
def na3(n=0,m=0,l=0,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end
def bit(n) n.to_s(2).split("").map(&:to_i) end
def inp() a=gets.chomp.split(" ").map(&:to_i)end

n = inp[0]
f0 = false
f1 = false
n.times do
  ans = inp[0]
  ff = (ans % 2 == 1)
  if ff
    if(ans < 0 and f0 )
      ans += ans/ans.abs
      f0 = false
    elsif(ans <0)
      ans -= ans/ans.abs
      f0 = true
    end
    if(ans > 0 and f1 )
      ans += ans/ans.abs
      f1 = false
    elsif(ans > 0)
      ans -= ans/ans.abs
      f1 = true
    end
  end
  puts ans/2
end


Vlad came home and found out that someone had reconfigured the old thermostat to the temperature of $$$a$$$.The thermostat can only be set to a temperature from $$$l$$$ to $$$r$$$ inclusive, the temperature cannot change by less than $$$x$$$. Formally, in one operation you can reconfigure the thermostat from temperature $$$a$$$ to temperature $$$b$$$ if $$$|a - b| \ge x$$$ and $$$l \le b \le r$$$.You are given $$$l$$$, $$$r$$$, $$$x$$$, $$$a$$$ and $$$b$$$. Find the minimum number of operations required to get temperature $$$b$$$ from temperature $$$a$$$, or say that it is impossible.

The first line of input data contains the single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each case contains three integers $$$l$$$, $$$r$$$ and $$$x$$$ ($$$-10^9 \le l \le r \le 10^9$$$, $$$1 \le x \le 10^9$$$) — range of temperature and minimum temperature change. The second line of each case contains two integers $$$a$$$ and $$$b$$$ ($$$l \le a, b \le r$$$) — the initial and final temperatures.

Output $$$t$$$ numbers, each of which is the answer to the corresponding test case. If it is impossible to achieve the temperature $$$b$$$, output -1, otherwise output the minimum number of operations.

NoteIn the first example, the thermostat is already set up correctly.In the second example, you can achieve the desired temperature as follows: $$$4 \rightarrow 10 \rightarrow 5$$$.In the third example, you can achieve the desired temperature as follows: $$$3 \rightarrow 8 \rightarrow 2 \rightarrow 7$$$.In the fourth test, it is impossible to make any operation.

gets.to_i.times do
    l,r,x = gets.chomp.split(' ').map(&:to_i)
    a,b = gets.chomp.split(' ').map(&:to_i)
    if a==b
        puts 0
    elsif (a-b).abs >=x
        puts 1
    elsif ((a-l)>=x && (b-l)>=x)||((r-a)>=x && (r-b)>=x)
        puts 2
    elsif ((a-l)>=x || (r-a)>=x )&&((b-l)>=x || (r-b)>=x)
        puts 3
    else
        puts -1
    end
end


When you play the game of thrones, you win, or you die. There is no middle ground.Cersei Lannister, A Game of Thrones by George R. R. MartinThere are $$$n$$$ nobles, numbered from $$$1$$$ to $$$n$$$. Noble $$$i$$$ has a power of $$$i$$$. There are also $$$m$$$ "friendships". A friendship between nobles $$$a$$$ and $$$b$$$ is always mutual.A noble is defined to be vulnerable if both of the following conditions are satisfied:   the noble has at least one friend, and  all of that noble's friends have a higher power. You will have to process the following three types of queries.   Add a friendship between nobles $$$u$$$ and $$$v$$$.  Remove a friendship between nobles $$$u$$$ and $$$v$$$.  Calculate the answer to the following process. The process: all vulnerable nobles are simultaneously killed, and all their friendships end. Then, it is possible that new nobles become vulnerable. The process repeats itself until no nobles are vulnerable. It can be proven that the process will end in finite time. After the process is complete, you need to calculate the number of remaining nobles.Note that the results of the process are not carried over between queries, that is, every process starts with all nobles being alive!

The first line contains the integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2\cdot 10^5$$$, $$$0 \le m \le 2\cdot 10^5$$$) — the number of nobles and number of original friendships respectively. The next $$$m$$$ lines each contain the integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \ne v$$$), describing a friendship. No friendship is listed twice. The next line contains the integer $$$q$$$ ($$$1 \le q \le 2\cdot {10}^{5}$$$) — the number of queries.  The next $$$q$$$ lines contain the queries themselves, each query has one of the following three formats.    $$$1$$$ $$$u$$$ $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \ne v$$$) — add a friendship between $$$u$$$ and $$$v$$$. It is guaranteed that $$$u$$$ and $$$v$$$ are not friends at this moment.  $$$2$$$ $$$u$$$ $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \ne v$$$) — remove a friendship between $$$u$$$ and $$$v$$$. It is guaranteed that $$$u$$$ and $$$v$$$ are friends at this moment.  $$$3$$$ — print the answer to the process described in the statement.

For each type $$$3$$$ query print one integer to a new line. It is guaranteed that there will be at least one type $$$3$$$ query.

NoteConsider the first example. In the first type 3 query, we have the diagram below.In the first round of the process, noble $$$1$$$ is weaker than all of his friends ($$$2$$$ and $$$3$$$), and is thus killed. No other noble is vulnerable in round 1. In round 2, noble $$$3$$$ is weaker than his only friend, noble $$$4$$$, and is therefore killed. At this point, the process ends, and the answer is $$$2$$$.  In the second type 3 query, the only surviving noble is $$$4$$$.    The second example consists of only one type $$$3$$$ query. In the first round, two nobles are killed, and in the second round, one noble is killed. The final answer is $$$1$$$, since only one noble survives.

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

hash = Hash.new { |h, k| h[k] = 0 }
m.times do
	u, v = gets.split.map!(&:to_i)
	u, v = v, u if u > v
	hash[u] += 1
end

h = hash.dup
q = gets.to_i
q.times do
	type, u, v = gets.split.map!(&:to_i)

	case type
	when 1
		u, v = v, u if u > v
		h[u] += 1
	when 2
		u, v = v, u if u > v
		h[u] -= 1
		h.delete(u) if h[u] == 0
	else
		puts n - h.size
		# h = hash.dup
	end
end

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

hash = Hash.new { |h, k| h[k] = 0 }
m.times do
	u, v = gets.split.map!(&:to_i)
	u, v = v, u if u > v
	hash[u] += 1
end

h = hash.dup
q = gets.to_i
q.times do
	type, u, v = gets.split.map!(&:to_i)

	case type
	when 1
		u, v = v, u if u > v
		h[u] += 1
	when 2
		u, v = v, u if u > v
		h[u] -= 1
		h.delete(u) if h[u] == 0
	else
		puts n - h.size
		h = hash.dup
	end
end


Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2 × 2 which are the Cheaterius' magic amulets!    That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2 × 2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk.

The first line contains an integer n (1 ≤ n ≤ 1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located.

amulets, piles = [], []
n = STDIN.gets.to_i

n.times do
  li1, li2, sep = STDIN.gets.chomp, STDIN.gets.chomp.reverse, STDIN.gets
  amulets << li1 + li2
end

amulets.each do |amu|
  4.times do |n|
    amu_rotate = (amu * 2)[n, 4]
    break if piles.include?(amu_rotate)
    piles << amu if n == 3
  end
end

puts piles.count

def r(s)
  s[1..-1] + s[0..0]
end

n = gets.to_i

a = Array.new(n) do |i|
  s = gets[0..1] + gets[0..1].reverse
  gets if i != n - 1
  s
end

a = a.map do |s|
  [s, r(s), r(r(s)), r(r(r(s)))].min
end

puts a.uniq.count

def rot(a)
  a.push(a.shift)
end
def already(h,a)
  h.include?(a) || h.include?(rot(a)) || h.include?(rot(rot(a))) || h.include?(rot(rot(rot(a))))
end

n=gets.to_i
a=Array.new(4)
h={}
cnt=0
n.times{|x|
	a[0]=gets(1)
	a[1]=gets(1)
	gets
	a[3]=gets(1)
	a[2]=gets(1)
	gets
	if x!=n-1 then gets; end
	if !already(h,a) then
		cnt+=1
	    h[a]=true
	end
}
puts cnt

def rotate(amulet)
  a = amulet[0][0]
  b = amulet[0][1]
  c = amulet[1][0]
  d = amulet[1][1]

  [[c, a], [d, b]]
end
def equal(a, b)
  if a == b
    true
  elsif rotate(a) == b || rotate(rotate(a)) == b || rotate(rotate(rotate(a))) == b
    true
  else
    false
  end
end

number = gets.chomp.to_i

amulets = []
number.times {|i|
  str = gets.chomp
  a = str[0..0]
  b = str[1..1]
  str = gets.chomp
  c = str[0..0]
  d = str[1..1]
  amulets << [[a, b], [c, d]]
  gets if not i == number - 1
}

piles = []
amulets.each {|amulet|
  if index = piles.index {|item| equal(item[0], amulet)}
    piles[index] << amulet
  else
    piles << [amulet]
  end
}

puts piles.length

amulets = []
piles = {}

n = STDIN.gets
n.to_i.times do
  line1 = STDIN.gets.chomp
  line2 = STDIN.gets.chomp.reverse
  sep   = STDIN.gets

  amulets << line1 + line2
end

puts 1

def rot(a)
  a[0],a[1],a[2],a[3] = a[2],a[0],a[3],a[1]
end
def already(h,a)
  h.include?(a) || h.include?(rot(a)) || h.include?(rot(rot(a))) || h.include?(rot(rot(rot(a))))
end

n=gets.to_i
a=Array.new(4)
h={}
cnt=0
n.times{|x|
	a[0]=gets(1)
	a[1]=gets(1)
	gets
	a[2]=gets(1)
	a[3]=gets(1)
	gets
	if x!=n-1 then gets; end
	if !already(h,a) then
		cnt+=1
	    h[a]=true
	end
}
puts cnt

def rot(a)
  a[0],a[1],a[2],a[3] = a[2],a[0],a[2],a[1]
end
def already(h,a)
  h.include?(a) || h.include?(rot(a)) || h.include?(rot(rot(a))) || h.include?(rot(rot(rot(a))))
end

n=gets.to_i
a=Array.new(4)
h={}
cnt=0
n.times{|x|
	a[0]=gets(1)
	a[1]=gets(1)
	gets
	a[2]=gets(1)
	a[3]=gets(1)
	gets
	if x!=n-1 then gets; end
	if !already(h,a) then
		cnt+=1
	    h[a]=true
	end
}
puts cnt

def rot(a)
  a.push(a.shift)
end
def already(h,a)
  h.include?(a) || h.include?(rot(a)) || h.include?(rot(rot(a))) || h.include?(rot(rot(rot(a))))
end

n=gets.to_i
a=Array.new(4)
h={}
cnt=0
n.times{|x|
	gets
	a[0]=gets(1)
	a[1]=gets(1)
	gets
	a[2]=gets(1)
	a[3]=gets(1)
	gets
	if !already(h,a) then
		cnt+=1
	    h[a]=true
	end
}
puts cnt

def rotate(amulet)
  a = amulet[0][0]
  b = amulet[0][1]
  c = amulet[1][0]
  d = amulet[1][1]

  [[c, a], [d, b]]
end
def equal(a, b)
  if a == b
    true
  elsif rotate(a) == b || rotate(rotate(a)) == b || rotate(rotate(rotate(a))) == b
    true
  else
    false
  end
end

number = gets.chomp.to_i

amulets = []
number.times {|i|
  str = gets.chomp
  a = str[0..0]
  b = str[1..1]
  str = gets.chomp
  c = str[0..0]
  d = str[1..1]
  amulets << [[a, b], [c, d]]
  gets if not i == number - 1
}

piles = []
amulets.each {|amulet|
  if index = piles.index {|item| equal(item[0], amulet)}
    piles[index] << amulet
  else
    piles << [amulet]
  end
}

puts piles.select {|pile| pile.length != 1}.length


Polycarp studies at the university in the group which consists of n students (including himself). All they are registrated in the social net "TheContacnt!".Not all students are equally sociable. About each student you know the value ai — the maximum number of messages which the i-th student is agree to send per day. The student can't send messages to himself. In early morning Polycarp knew important news that the programming credit will be tomorrow. For this reason it is necessary to urgently inform all groupmates about this news using private messages. Your task is to make a plan of using private messages, so that:  the student i sends no more than ai messages (for all i from 1 to n);  all students knew the news about the credit (initially only Polycarp knew it);  the student can inform the other student only if he knows it himself. Let's consider that all students are numerated by distinct numbers from 1 to n, and Polycarp always has the number 1.In that task you shouldn't minimize the number of messages, the moment of time, when all knew about credit or some other parameters. Find any way how to use private messages which satisfies requirements above.

The first line contains the positive integer n (2 ≤ n ≤ 100) — the number of students.  The second line contains the sequence a1, a2, ..., an (0 ≤ ai ≤ 100), where ai equals to the maximum number of messages which can the i-th student agree to send. Consider that Polycarp always has the number 1.

Print -1 to the first line if it is impossible to inform all students about credit.  Otherwise, in the first line print the integer k — the number of messages which will be sent. In each of the next k lines print two distinct integers f and t, meaning that the student number f sent the message with news to the student number t. All messages should be printed in chronological order. It means that the student, who is sending the message, must already know this news. It is assumed that students can receive repeated messages with news of the credit.  If there are several answers, it is acceptable to print any of them.

NoteIn the first test Polycarp (the student number 1) can send the message to the student number 2, who after that can send the message to students number 3 and 4. Thus, all students knew about the credit.

n = gets.to_i
bob, *students = gets.split.each_with_index.map{|s,i| [s.to_i, i+1]} #His name is Bob. Deal with it.

students.sort! # more socialized will be in the end and recoverable with .pop

if bob[0]==0 # Bob is a very asocial programmer. Oops. :3
	puts -1
	exit
end

knowers = [bob]
msgs = [] # [src, dst] -- src => dst

while students.length>0 && knowers.length>0
	knower = knowers[-1]
	knower[0] -= 1
	knowers.pop         if (knower[0]==0)

	student = students.pop
	knowers << student  if (student[0]>0)

	msgs << [knower[1], student[1]]
end
if students.length==0
	puts msgs.length
	msgs.each do |m|
		puts m.join' '
	end
else
	puts -1
end


The term of this problem is the same as the previous one, the only exception — increased restrictions.

The first line contains two positive integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 109) — the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1, a2, ..., an (1 ≤ ai ≤ 109), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1, b2, ..., bn (1 ≤ bi ≤ 109), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has.

Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder.

n, k = readline.split(' ').collect(&:to_i)
a = readline.split(' ').collect(&:to_i)
b = readline.split(' ').collect(&:to_i)
down = 0
up = (b[0] + k) / a[0] + 1
while down + 1 < up
  mid = (down + up) / 2
  need = 0
  a.zip(b).each do |aa, bb|
    if aa * mid > bb
      need += aa * mid - bb
    end
  end
  if need <= k
    down = mid
  else
    up = mid
  end
end
puts down


Dima has a hamsters farm. Soon N hamsters will grow up on it and Dima will sell them in a city nearby.Hamsters should be transported in boxes. If some box is not completely full, the hamsters in it are bored, that's why each box should be completely full with hamsters.Dima can buy boxes at a factory. The factory produces boxes of K kinds, boxes of the i-th kind can contain in themselves ai hamsters. Dima can buy any amount of boxes, but he should buy boxes of only one kind to get a wholesale discount.Of course, Dima would buy boxes in such a way that each box can be completely filled with hamsters and transported to the city. If there is no place for some hamsters, Dima will leave them on the farm.Find out how many boxes and of which type should Dima buy to transport maximum number of hamsters.

The first line contains two integers N and K (0 ≤ N ≤ 1018, 1 ≤ K ≤ 105) — the number of hamsters that will grow up on Dima's farm and the number of types of boxes that the factory produces. The second line contains K integers a1, a2, ..., aK (1 ≤ ai ≤ 1018 for all i) — the capacities of boxes.

Output two integers: the type of boxes that Dima should buy and the number of boxes of that type Dima should buy. Types of boxes are numbered from 1 to K in the order they are given in input. If there are many correct answers, output any of them.

def solve(n, k, a)
  type = -1
  ans = -1
  for i in 0...k.to_i
    cmp = (n.to_i / a[i].to_i) * a[i].to_i
    if cmp > ans
      ans = cmp
      type = i
    end
  end

  ret = []
  ret.push(type.to_i + 1)
  ret.push(n.to_i / a[type.to_i].to_i)
  return ret;
end

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

ans = solve(n, k, a)
print ans[0].to_s + " " + ans[1].to_s

m, n = gets.split.map(&:to_i)
a = gets.split.map(&:to_i).shift(n)
ans = [0]
a.each_with_index do |i, j|
  ans = [ans, [m - m % i, j + 1, m / i]].max
end
puts "#{ans[1]} #{ans[2]}"

#Hamster farm

inp = gets.chomp.split().map(&:to_i)
k = inp[0] ; n = inp[1]
inp = gets.chomp.split().map(&:to_i)
remain = inp.map { |e| k%e }
ind = remain.each_with_index.min[1]
model = ind + 1
num = k/inp[ind]
puts [model ,num]


Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins.Vasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent mi coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of shops in the city that sell Vasiliy's favourite drink. The second line contains n integers xi (1 ≤ xi ≤ 100 000) — prices of the bottles of the drink in the i-th shop. The third line contains a single integer q (1 ≤ q ≤ 100 000) — the number of days Vasiliy plans to buy the drink. Then follow q lines each containing one integer mi (1 ≤ mi ≤ 109) — the number of coins Vasiliy can spent on the i-th day.

Print q integers. The i-th of them should be equal to the number of shops where Vasiliy will be able to buy a bottle of the drink on the i-th day.

NoteOn the first day, Vasiliy won't be able to buy a drink in any of the shops.On the second day, Vasiliy can buy a drink in the shops 1, 2, 3 and 4.On the third day, Vasiliy can buy a drink only in the shop number 1.Finally, on the last day Vasiliy can buy a drink in any shop.

n = gets.to_i
mas = gets.split.map(&:to_i)
q = gets.to_i

mas.sort!

ans = {}

cnt = 0
mas.each do |x|
    ans[x] = cnt if ans[x].nil?
    cnt+=1
end

q.times do
   m = gets.to_i
   f = mas.bsearch{|x| x > m}

   puts f.nil? ? n : ans[f]
end

n = gets.chomp.to_i
hash = Hash.new { 0 }
arr = gets.chomp.split.map(&:to_i).sort
c = 0
arr.each do |x|
  hash[x] = c unless hash.key?(x)
  c += 1
end

q = gets.chomp.to_i
q.times do
  x = gets.chomp.to_i
  ans = arr.bsearch { |e| e > x }
  puts ans ? hash[ans] : n
end

c = []
for i in (1..100001)
  c.push(0)
end

n = gets.to_i()
x = gets.split(' ')
for i in x
  c[i.to_i()] += 1
end

for i in (1..100000)
  c[i] += c[i-1]
end

q = gets.to_i()
for i in (1..q)
  t = gets.to_i()
  if t > 100000
    puts c[100000]
  else
    puts (c[t])
  end
end

class Program
    def initialize(input)
        input.each_with_index do |line, idx|
            case idx
            when 0
                @shopNum = Integer(line)
            when 1
                @priceArr = line.split(" ")
                @priceArr = @priceArr.map{ |i| i = Integer(i) }
                @priceArr.sort!
            when 2
                @dayNum = Integer(line)
            else
                coin = Integer(line)
                puts searchResult(coin,0,@shopNum-1)
            end
        end
    end

    def searchResult(coin,lo,hi)
        while lo <= hi do
            mid = lo + (hi-lo)/2
            if coin < @priceArr[mid]
                hi = mid - 1
            elsif coin == @priceArr[mid]
                rtn = mid + 1;
                lo = mid + 1;
            else
                lo = mid + 1
            end
        end

        return rtn ? rtn : (coin > @priceArr[mid] ? mid + 1 : mid)
    end
end

main = Program.new(ARGF)

max1=100000
c=(0..max1).map{0}
gets
x=gets.split.map{|e| e.to_i}
x.each{|e|
	c[e]+=1
}

sum=0
0.upto(max1){|i|
	sum+=c[i]
	c[i]=sum
}
gets.to_i.times{
	n=gets.to_i
	if n>=max1 then
		puts c[max1]
	else
		puts c[n]
	end
}

# coding: utf-8

# if __FILE__ == $0
# end

n = gets.to_i

prev = -1
prices = gets.split.map(&:to_i)
days_staying = gets.to_i
last_pos = {}
prices.sort!
prev = -1
prices.each_with_index { |item, index|
    if prev != item
        prev = item
    end

    last_pos[prev] = index
}

days_staying.times {
    coins = gets.to_i

    # binary search (end will be exclusive b <= i < e)
    b, e = 0, prices.length
    # p last_pos # index test
    loop {
        mid = (b + e) / 2
        midval = prices[mid]
        # p [b, e, mid, coins]
        if midval < coins
            # p '#1'
            if (e - b) <= 1
                puts e
                break
            end

            b = mid
        elsif midval == coins
            # p '#2'
            puts last_pos[midval] + 1
            break
        else
            # p '#3'

            if (e - b) <= 1
                puts b
                break
            end

            e = mid
        end
    }
}

n = gets.chomp.to_i
x = gets.chomp.split.map(&:to_i).sort
q = gets.chomp.to_i
m = []
for i in (0..q-1)
	m[i] = gets.chomp.to_i
end

for i in (0..q-1)
	first = 0
	last = n-1
	mid = (first + last)/2
	while first < last
		if x[mid] <= m[i]
			first = mid+1
		else
			last = mid-1
		end
		mid = (first+last)/2
	end
	if x[mid] <= m[i]
		puts mid+1
	else
		if mid < 0
			puts 0
		else
			puts mid
		end
	end
end

n = gets.to_i
arr = gets.split(' ').map {|a| a.to_i}.sort!
gets.to_i.times do
	c = gets.to_i
	l = 0
	h = n-1
	while l<=h
		m = (l+h)/2
		if arr[m]>c then h = m - 1 else l = m + 1 end
	end
	puts l
end

n = gets.to_i
arr = gets.split(' ').map {|a| a.to_i}.sort!
gets.to_i.times do
	c = gets.to_i
	l = 0
	h = n-1
	17.times do
		m = (l+h)/2
		if arr[m]>c then h = m - 1 else l = m + 1 end
	end
	puts l
end

n = gets.to_i
arr = gets.split(' ').map {|a| a.to_i}.sort!
gets.to_i.times do
	c = gets.to_i
	l = 0
	h = n-1
	64.times do
		m = (l+h)/2
		if arr[m]>c then h = m - 1 else l = m + 1 end
	end
	puts l
end

n = gets.to_i
prices = gets.split.map(&:to_i).sort!
days = gets.to_i

for i in 0..(days - 1)
  money = gets.to_i
  left = 0
  right = n - 1

  while left != right do
    middle = (left + right) / 2

    if prices[middle] <= money
      left = middle + 1
    else
      right = middle
    end

  end

  if prices[left] <= money
      puts left + 1
  else
      puts left
  end
end

answer = {}
n = gets.to_i
prices = gets.split.map(&:to_i)
days = gets.to_i

prices.sort!

prices.each_with_index do |x, index|
    answer[x] = index if answer[x].nil?
end

days.times do
   money = gets.to_i
   value = prices.bsearch{ |x| x > money }
   puts value.nil? ? n : answer[value]
end

n = gets.to_i
prices = gets.split.map(&:to_i).sort!
days = gets.to_i

for i in 0..(days - 1)
  money = gets.to_i
  left = 0
  right = n - 1

  while left != right do
    middle = (left + right) / 2

    if prices[middle] < money
      left = middle + 1
    elsif prices[middle] > money
      right = middle
    else
      left = middle + 1
    end
  end

  if prices[left] <= money
      puts left + 1
  else
      puts left
  end
end

def bs(a, t, l, r)
  return l if l == r
  if a[(l + r) / 2] > t
    bs(a, t, l, (l + r) / 2)
  else
    bs(a, t, (l + r) / 2 + 1, r)
  end
end

n = gets.to_i
a = gets.split.map(&:to_i).sort
m = gets.to_i
ans = []
m.times do
  t = gets.to_i
  ans << bs(a, t, 0, n)
end
puts ans * "\n"

n = gets.to_i
a = gets.split.map(&:to_i).sort
m = gets.to_i
ans = []
m.times do
  t = gets.to_i
  ans << ((0...n).bsearch{|i| a[i] > t} || n)
end
puts ans * "\n"

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

q = gets.chomp.to_i
1.upto(q) do
	m = gets.chomp.to_i
	l = 0
	r = n-1

	while (r-l > 1) do
		if a[(r+l)/2]>m then
			r = (r+l)/2
		else
			l = (r+l)/2
		end
	end

	result = 0
	if a[l]<=m then
		if a[r]>m then
			result = r
		else
			result = n
		end
	end

	puts result
end

def binary_search(range)
  lower = 0
  upper = range.size
  while lower < upper
    mi = (lower + upper)/2
    yield(range[mi]) ? upper = mi : lower = mi + 1
  end
  [range[upper], upper]
end

n = gets.to_i
p = gets.split.map(&:to_i).sort
q = gets.to_i
(0...q).each do |i|
  b = gets.to_i
  puts binary_search(p){ |j| j > b}[1]
end

shopNum = gets.chomp.to_i
shopPrices = gets.chomp.split(' ').map(&:to_i)
dayNum = gets.chomp.to_i

shopPrices.sort!
indexHash = {}
duplicate = {}

shopPrices.each_with_index do |p, i|
	indexHash[p] = i + 1

	if duplicate.has_key? p
		duplicate[p] += 1
	else
		duplicate[p] = 0
	end
end

dayNum.times do
	coin = gets.chomp.to_i
	idx = shopPrices.bsearch { |x| x >= coin }

	#puts "idx : #{idx}"

	if idx.nil?
		puts shopPrices.length
	else
		if coin < idx
			puts indexHash[idx] - 1 - duplicate[idx]
		else
			puts indexHash[idx]
		end
	end
end

c = []
for i in (1..100001)
  c.push(0)
end

n = gets.to_i()
x = gets.split(' ')
for i in x
  c[i.to_i()] += 1
end

for i in (1..100000)
  c[i] += c[i-1]
end

q = gets.to_i()
for i in (1..q)
  t = gets.to_i()
  puts (c[t])
end

class Program
    def initialize(input)
        input.each_with_index do |line, idx|
            case idx
            when 0
                @shopNum = Integer(line)
            when 1
                @priceArr = line.split(" ")
                @priceArr = @priceArr.map{ |i| i = Integer(i) }
                @priceArr.sort!
            when 2
                @dayNum = Integer(line)
            else
                coin = Integer(line)
                p searchResult(coin,@shopNum/2)
            end
        end
    end

    def searchResult(coin,partition)

        if partition >= @shopNum - 1
            return @shopNum
        elsif @priceArr[partition] == coin
            return partition + 1
        elsif coin > @priceArr[partition] and coin < @priceArr[partition + 1]
            return partition + 1
        elsif coin < @priceArr[partition] and coin > @priceArr[partition - 1]
            return partition
        elsif coin < @priceArr[partition] and partition == 0
            return partition
        elsif @priceArr[partition] > coin
            return searchResult(coin,partition/2)
        elsif @priceArr[partition] < coin
            return searchResult(coin,(@shopNum + partition)/2 )
        end

    end
end

main = Program.new(ARGF)

class Program
    def initialize(input)
        input.each_with_index do |line, idx|
            case idx
            when 0
                @shopNum = Integer(line)
            when 1
                @priceArr = line.split(" ")
                @priceArr = @priceArr.map{ |i| i = Integer(i) }
                @priceArr.sort!
            when 2
                @dayNum = Integer(line)
            else
                coin = Integer(line)
                puts searchResult(coin,0,@shopNum-1)
            end
        end
    end

    def searchResult(coin,lo,hi)
        while lo <= hi do
            mid = lo + (hi-lo)/2
            if coin < @priceArr[mid]
                hi = mid - 1
            elsif coin == @priceArr[mid]
                rtn = mid + 1;
                lo = mid + 1;
            else
                lo = mid + 1
            end
        end

        return rtn ? rtn : (mid == 0 ? 0 : mid + 1)
    end
end

main = Program.new(ARGF)

class Program
    def initialize(input)
        input.each_with_index do |line, idx|
            case idx
            when 0
                @shopNum = Integer(line)
            when 1
                @priceArr = line.split(" ")
                @priceArr = @priceArr.map{ |i| i = Integer(i) }
                @priceArr.sort!
            when 2
                @dayNum = Integer(line)
            else
                coin = Integer(line)
                p searchResult(coin,@shopNum/2)
            end
        end
    end

    def searchResult(coin,partition)
        if partition <= 0
            return 0
        elsif partition >= @shopNum - 1
            return @shopNum
        elsif @priceArr[partition] == coin
            return partition + 1
        elsif coin > @priceArr[partition] and coin < @priceArr[partition + 1]
            return partition + 1
        elsif coin < @priceArr[partition] and coin > @priceArr[partition - 1]
            return partition
        elsif @priceArr[partition] > coin
            return searchResult(coin,partition/2)
        elsif @priceArr[partition] < coin
            return searchResult(coin,(@shopNum + partition)/2 )
        end

    end
end

main = Program.new(ARGF)

class Program
    def initialize(input)
        input.each_with_index do |line, idx|
            case idx
            when 0
                @shopNum = Integer(line)
            when 1
                @priceArr = line.split(" ")
                @priceArr = @priceArr.map{ |i| i = Integer(i) }
                @priceArr.sort!
            when 2
                @dayNum = Integer(line)
            else
                coin = Integer(line)
                p searchResult(coin,1,@shopNum)
            end
        end
    end

    def searchResult(coin,lo,hi)
        mid = lo+(hi-lo)/2
        if lo >= hi
            return mid
        elsif coin > @priceArr[mid-1]
            return searchResult(coin,mid+1,hi)
        elsif coin < @priceArr[mid-1]
            return searchResult(coin,lo,mid-1)
        elsif coin == @priceArr[mid-1]
            return mid
        end
    end
end

main = Program.new(ARGF)

class Program
    def initialize(input)
        input.each_with_index do |line, idx|
            case idx
            when 0
                @shopNum = Integer(line)
            when 1
                @priceArr = line.split(" ")
                @priceArr = @priceArr.map{ |i| i = Integer(i) }
                @priceArr.sort!
            when 2
                @dayNum = Integer(line)
            else
                coin = Integer(line)
                puts searchResult(coin,0,@shopNum-1)
            end
        end
    end

    def searchResult(coin,lo,hi)
        while lo <= hi do
            mid = lo + (hi-lo)/2
            if coin < @priceArr[mid]
                hi = mid - 1
            elsif coin == @priceArr[mid]
                rtn = mid + 1;
                lo = mid + 1;
            else
                lo = mid + 1
            end
        end

        return rtn ? rtn : mid
    end
end

main = Program.new(ARGF)

class Program
    def initialize(input)
        input.each_with_index do |line, idx|
            case idx
            when 0
                @shopNum = Integer(line)
            when 1
                @priceArr = line.split(" ")
                @priceArr = @priceArr.map{ |i| i = Integer(i) }
                @priceArr.sort!
            when 2
                @dayNum = Integer(line)
            else
                coin = Integer(line)
                p searchResult(coin,1,@shopNum)
            end
        end
    end

    def searchResult(coin,lo,hi)
        mid = lo+(hi-lo)/2
        if lo >= hi
            return lo - 1
        elsif coin > @priceArr[mid-1]
            return searchResult(coin,mid+1,hi)
        elsif coin < @priceArr[mid-1]
            return searchResult(coin,lo,mid-1)
        elsif coin == @priceArr[mid-1]
            return mid
        end
    end
end

main = Program.new(ARGF)

class Program
    def initialize(input)
        input.each_with_index do |line, idx|
            case idx
            when 0
                @shopNum = Integer(line)
            when 1
                @priceArr = line.split(" ")
                @priceArr = @priceArr.map{ |i| i = Integer(i) }
                @priceArr.sort!
            when 2
                @dayNum = Integer(line)
            else
                coin = Integer(line)
                puts searchResult(coin,1,@shopNum)
            end
        end
    end

    def searchResult(coin,lo,hi)
        mid = lo+(hi-lo)/2
        if lo >= hi
            if coin < @priceArr[mid-1] && mid != 0
                return mid - 1
            else
                return mid
            end
        elsif coin > @priceArr[mid-1]
            return searchResult(coin,mid+1,hi)
        elsif coin < @priceArr[mid-1]
            return searchResult(coin,lo,mid-1)
        elsif coin == @priceArr[mid-1]
            return mid
        end
    end
end

main = Program.new(ARGF)

# coding: utf-8

# if __FILE__ == $0
# end

n = gets.to_i
prices = gets.split.map(&:to_i)
days_staying = gets.to_i
prices.sort!
days_staying.times {
    coins = gets.to_i

    # binary search (end will be exclusive b <= i < e)
    b, e = 0, prices.length
    loop {
        mid = (b + e) / 2
        p [b, e, mid, coins]
        if prices[mid] < coins
            p '#1'
            if (e - b) <= 1
                puts e
                break
            end

            b = mid
        elsif prices[mid] == coins
            p '#2'
            printed = false
            for i in mid...e
                if prices[i] > coins
                    puts i
                    printed = true
                    break
                end
            end

            puts e if !printed
            break
        elsif prices[mid-1] <= coins && prices[mid+1] >= coins
            p '#3'
            puts mid
            break
        else
            p '#4'

            if (e - b) <= 1
                puts b
                break
            end

            e = mid
        end
    }
}

n = gets.chomp.to_i
x = gets.chomp.split
q = gets.chomp.to_i
m = []
for i in (0..q-1)
	m[i] = gets.chomp.to_i
end

x = x.sort_by { |a,b| a.to_i }
x = x.map(&:to_i)

for i in (0..q-1)
	if x.min.to_i > m[i]
		puts 0
	elsif x.max.to_i <= m[i]
		puts n
	elsif x.find_index(m[i]) != nil
		puts x.find_index(m[i]) + 1
	else
		mid = 0
		first = 0
		last = n
		while first < last
			mid = first + (last-first)/2
			if m[i] > x[mid]
				first = mid + 1
			else
				last = mid
			end
		end
		puts first
	end

end

n = gets.chomp.to_i
x = gets.chomp.split.map(&:to_i).sort
q = gets.chomp.to_i
m = []
for i in (0..q-1)
	m[i] = gets.chomp.to_i
end

for i in (0..q-1)
	first = 0
	last = n-1
	mid = (first + last)/2
	while first < last
		if x[mid] < m[i]
			first = mid+1
		else
			last = mid
		end
		mid = (first + last)/2
	end
	if x[mid] <= m[i]
		puts mid+1
	else
		puts mid
	end
end

n = gets.chomp.to_i
x = gets.chomp.split
q = gets.chomp.to_i
m = []
for i in (0..q-1)
	m[i] = gets.chomp.to_i
end

x = x.sort_by { |a,b| a.to_i }
x = x.map(&:to_i)

for i in (0..q-1)
	if x.min.to_i > m[i]
		puts 0
	elsif x.max.to_i <= m[i]
		puts n
	elsif x.find_index(m[i]) != nil
		puts x.find_index(m[i]) + 1
	else
		mid = 0
		first = 0
		last = n-1
		while first < last
			mid = first + (last-first)/2
			if m[i] > x[mid]
				first = mid + 1
			else
				last = mid
			end
		end
		puts first
	end

end

n = gets.chomp.to_i
x = gets.chomp.split
q = gets.chomp.to_i
m = []
for i in (0..q-1)
	m[i] = gets.chomp.to_i
end

# sorted_x = []
# for i in (0..n-1)
# 	sorted_x << [x[i].to_i, i]
# end
# x = sorted_x.sort { |a,b| a[0] <=> b[0] }
x = x.sort_by { |a,b| a.to_i }
x = x.map(&:to_i)

for i in (0..q-1)
	if x.min.to_i > m[i]
		puts 0
	elsif x.max.to_i <= m[i]
		puts n
	elsif x.find_index(m[i]) != nil
		puts x.find_index(m[i]) + 1
	else
		if m[i] < x[(n/2) + 1]
			temp = n/2
			while x[temp] > m[i]
				temp /= 2
			end
		else
			temp = (n/2) + 1
			while x[temp] > m[i]
				temp *= 2
			end
		end
		puts temp + 1
	end
end

class BinaryTree
  attr_accessor :root

  def insert(value)
    if @root.nil?
      @root = Node.new(value)
    else
      @root.insert(value)
    end
  end

  def count_elements(node = @root, sum_elements = 0)
    sum_elements = count_elements(node.left, sum_elements) if node.left
    sum_elements = sum_elements + 1
    node.count = sum_elements
    sum_elements = count_elements(node.right, node.count) if node.right
    sum_elements
  end

  def search(searched_value, last_count, node = @root)
    return last_count if node.nil?
    if searched_value < node.node_value
      search(searched_value, last_count, node.left)
    elsif searched_value > node.node_value
      search(searched_value, node.count, node.right)
    else
      return node.count
    end
  end

  class Node
    attr_reader :node_value
    attr_accessor :left, :right, :count

    def initialize(value)
      @node_value = value
      @count = 0
    end

    def insert(value)
      case node_value <=> value
      when 1 then insert_left(value)
      when -1 then insert_right(value)
      when 0 then false
      end
    end

    private

    def insert_left(value)
      if left
        left.insert(value)
      else
        self.left = Node.new(value)
      end
    end

    def insert_right(value)
      if right
        right.insert(value)
      else
        self.right = Node.new(value)
      end
    end
  end
end

bt = BinaryTree.new
n = gets.to_i
prices = gets.split.each do |price|
  bt.insert(price.to_i)
end
days = gets.to_i

bt.count_elements

for i in 0..(days - 1)
  money = gets.to_i
  puts bt.search(money, 0)
end

class BinaryTree
  attr_accessor :root

  def insert(value)
    if @root.nil?
      @root = Node.new(value)
    else
      @root.insert(value)
    end
  end

  def count_elements(node = @root, sum_elements = 0)
    sum_elements = count_elements(node.left, sum_elements) if node.left
    sum_elements = sum_elements + 1
    node.count = sum_elements
    sum_elements = count_elements(node.right, node.count) if node.right
    sum_elements
  end

  def search(value, node = @root, last_value = 0)
    return last_value if node.nil?
    if value < node.node_value
      search(value, node.left, node.count - 1)
    elsif value > node.node_value
      search(value, node.right, node.count)
    else
      return node.count
    end
  end

  class Node
    attr_reader :node_value
    attr_accessor :left, :right, :count

    def initialize(value)
      @node_value = value
      @count = 0
    end

    def insert(value)
      case node_value <=> value
      when 1 then insert_left(value)
      when -1 then insert_right(value)
      when 0 then false
      end
    end

    private

    def insert_left(value)
      if left
        left.insert(value)
      else
        self.left = Node.new(value)
      end
    end

    def insert_right(value)
      if right
        right.insert(value)
      else
        self.right = Node.new(value)
      end
    end
  end
end

bt = BinaryTree.new
n = gets.to_i
prices = gets.split.each do |price|
  bt.insert(price.to_i)
end
days = gets.to_i

bt.count_elements

for i in 0..(days - 1)
  money = gets.to_i
  puts bt.search(money)
end

shopNum = gets.chomp.to_i
shopPrices = gets.chomp.split(' ').map(&:to_i)
dayNum = gets.chomp.to_i

shopPrices.sort!
indexHash = {}

shopPrices.each_with_index do |p, i|
	indexHash[p] = i + 1
end

dayNum.times do
	coin = gets.chomp.to_i
	idx = shopPrices.bsearch { |x| x >= coin }

	#puts "idx : #{idx}"

	if idx.nil?
		puts shopPrices.length
	else
		if coin < idx
			puts indexHash[idx] - 1
		else
			puts indexHash[idx]
		end
	end
end


Polycarpus has a computer with n processors. Also, his computer has n memory cells. We'll consider the processors numbered by integers from 1 to n and that the memory cells are consecutively numbered by integers from 1 to n.Polycarpus needs to come up with a parallel program model. For each memory cell number i this program must record the value n - i to this cell. In other words, for each cell you've got to find the distance to cell n.Let's denote the value that is written in the i-th cell as ai. Initially, ai = 1 (1 ≤ i < n) and an = 0. We will consider that only processor i can write values in the memory cell number i. All processors can read an information from some cell (several processors can read an information from some cell simultaneously).The parallel program is executed in several steps. During each step we execute the parallel version of the increment operation. Executing the parallel version of the increment operation goes as follows:  Each processor independently of the other ones chooses some memory cell. Let's say that processor i has chosen a cell with number ci (1 ≤ ci ≤ n).  All processors simultaneously execute operation ai = ai + aci. Help Polycarpus come up with the parallel program model that is executed in exactly k steps. Calculate the operations that need to be executed. Note that after k steps for all i's value ai must be equal n - i.

The first line contains two space-separated integers n and k (1 ≤ n ≤ 104, 1 ≤ k ≤ 20). It is guaranteed that at the given n and k the required sequence of operations exists.

Print exactly n·k integers in k lines. In the first line print numbers c1, c2, ..., cn (1 ≤ ci ≤ n) for the first increment operation. In the second line print the numbers for the second increment operation. In the k-th line print the numbers for the k-th increment operation. As a result of the printed operations for any i value ai must equal n - i.

args = gets.split(" ").map(&:to_i)
n = args[0]
k = args[1]

arr1 = [1]*(n-1) + [0]
arr2 = arr1
add = []

k.times do |j|
    arr1.each_with_index do |e, i|
        if (2*e < n-i) and (i<n-1) then
            add[i] = n-(2**j)-1
        else
            add[i] = i+arr1[i]
        end
        arr2[i] = arr1[i]+arr1[add[i]]
    end
    arr1 = arr2
    puts add.map{ |e| e+1 }.join(" ")
end

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

lb = ub = 1

k.times do
  res = ''
  lb = ub
  ub *= 2
  n.times do |i|
    t = n - i - 1
    if t <= lb
      res << "#{n} "
    elsif t > ub
      res << "#{i + 1} "
    else
      res << "#{n - t + lb} "
    end
  end
  puts res
end

at_exit do
  n,k = get_numbers_from_line[0..1]
  numbers = [1]*n
  numbers[n-1] = 0

  targets = (n-1).downto(0).to_a

  ds = (0...n).map{|i| targets[i] - numbers[i] }

  max = 1
  (0...k).each do |i|
    ci = []
    (0...n).each do |j|
      t = ds[j]
      if t == 0
        ci << n
      elsif t >= max
        ci << n - max
        ds[j] -= max
      else
        ci << n - ds[j]
        ds[j] = 0
      end
    end
    puts ci.join(' ')
    max *= 2
  end

end

def get_numbers_from_line
  gets.strip.split.map(&:to_i)
end

args = gets.split(" ").map(&:to_i)
n = args[0]
k = args[1]

arr1 = [1]*(n-1) + [0]
arr2 = arr1
add = []

k.times do |j|
    arr1.each_with_index do |e, i|
        if 2*e < n-i then
            arr2[i] = arr1[i]+e
            add[i] = i
        else
            arr2[i] = arr1[i]+arr1[i+arr1[i]]
            add[i] = i+arr1[i]
        end
    end
    arr1 = arr2
    puts add.map{ |e| e+1 }.join(" ")
end

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

lb = ub = 1

k.times do
  res = ''
  lb = ub
  ub *= 2
  n.times do |i|
    t = n - i - 1
    if t <= lb
      res << "#{n} "
    elsif t > ub
      res << "#{i + 1} "
    else
      res << "#{t} "
    end
  end
  puts res
end