Vasya has recently found out what a digital root of a number is and he decided to share his knowledge with you.Let's assume that S(n) is the sum of digits of number n, for example, S(4098) = 4 + 0 + 9 + 8 = 21. Then the digital root of number n equals to:   dr(n) = S(n), if S(n) < 10;  dr(n) = dr( S(n) ), if S(n) ≥ 10. For example, dr(4098)  =  dr(21)  =  3.Vasya is afraid of large numbers, so the numbers he works with are at most 101000. For all such numbers, he has proved that dr(n)  =  S( S( S( S(n) ) ) ) (n ≤ 101000).Now Vasya wants to quickly find numbers with the given digital root. The problem is, he hasn't learned how to do that and he asked you to help him. You task is, given numbers k and d, find the number consisting of exactly k digits (the leading zeroes are not allowed), with digital root equal to d, or else state that such number does not exist.

The first line contains two integers k and d (1 ≤ k ≤ 1000; 0 ≤ d ≤ 9).

In a single line print either any number that meets the requirements (without the leading zeroes) or "No solution" (without the quotes), if the corresponding number does not exist. The chosen number must consist of exactly k digits. We assume that number 0 doesn't contain any leading zeroes.

NoteFor the first test sample dr(5881)  =  dr(22)  =  4.For the second test sample dr(36172)  =  dr(19)  =  dr(10)  =  1.

line = gets
line = line.split(" ");
k = line[0].to_i
d = line[1].to_i

ans = d * 10**(k-1)

if d == 0 && k > 1
    ans = "No solution"
end

ans = ans.to_s << "\n"
print(ans)

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

if d == 0 && k > 1
  print "No solution"
else
  print d
  for i in 1...k
    print 0
  end
end

k,d=gets.chomp.split.map(&:to_i)
if d==0 && k>1
  puts "No solution"
else
  print d
  (k-1).times { print 0}
end

k,d=gets.chomp.split.map &:to_i
puts d==0&&k>1?"No solution":d.to_s+'0'*(k-1)

dcnt, droot = gets.split.map{|s| s.to_i}

if droot == 0 && dcnt > 1
	puts "No solution"
else
	print droot
	(dcnt-1).times {print 0}
end

k,d=gets.chomp.split.map(&:to_i)
if d==0
	if k==1
		puts "0"
	else
		puts "No solution"
	end
elsif d>0
	puts d*(10**(k-1))
else
	puts "No solution"
end

class A
  def initialize
    k, n = gets.chomp.split(' ').map(&:to_i)

    start = 0
    limit = 9 * k

    if k > 1 && n == 0
      puts "No solution"
      exit
    end

    (0..limit).each do |num|
      res = dfs(num)

      if res == n
        puts answer(num, k)
        exit
      end
    end

    puts "No solution"
  end

  def answer(num, k)
    list = [ 9, 8, 7, 6, 5, 4, 3, 2, 1 ]
    index = 0
    answer = ""
    while num != 0
      count = num / list[index]
      num %= list[index]
      answer += list[index].to_s * count
      index += 1
    end

    if answer.to_s.size != k
      diff = k - answer.to_s.size
      answer += "0" * diff
    end

    answer
  end

  def dfs(num)
    if num < 10
      return num
    else
      return dfs(sum_digit(num))
    end
  end

  def sum_digit(num)
    str = num.to_s

    str.chars.map(&:to_i).inject(:+)
  end
end

a = A.new

k, d = gets.chomp.split(/ /).map(&:to_i)
if k > 1 && d == 0
    puts "No solution"
else
    if k == 1 && d == 0
        puts 0
    else
        puts "#{d * (10 ** (k - 1))}"
    end
end

k, d = gets.split.map(&:to_i)
if d == 0 && k > 1
  print "No solution"
else
  print d
  for i in 1..k-1
    print 0
  end
end

# def digital_root(n)
# 	return @dp[n] if @dp[n]
# 	s = n.to_s.split("").map(&:to_i).inject(&:+)
# 	if s < 10
# 		@dp[n] = s
# 		return s
# 	end
# 	@dp[n] = digital_root(s)
# 	return @dp[n]
# end

# digits,d = gets.split(" ").map(&:to_i)
# @dp = {}
# start = 10 ** (digits - 1)
# start = 0 if start == 1
# finish = (10 ** digits) - 1
# ans = nil
# if d == 0
# 	if digits == 1
# 		ans = 0
# 	end
# else
# 	(start..finish).each do |a|
# 		if digital_root(a) == d
# 			ans = a
# 			break
# 		end
# 	end
# end
# if ans
# 	puts ans
# else
# 	puts "No solution"
# end

def digital_root(n)
	s = n.to_s.split("").map(&:to_i).inject(&:+)
end

digits,d = gets.split(" ").map(&:to_i)
@dp = {}
start = 10 ** (digits - 1)
start = 0 if start == 1
finish = start + 10
ans = nil

(start..finish).each do |a|
	if digital_root(a) == d
		ans = a
		break
	end
end

if ans
	puts ans
else
	puts "No solution"
end

def digital_root(n)
	return @dp[n] if @dp[n]
	s = n.to_s.split("").map(&:to_i).inject(&:+)
	if s < 10
		@dp[n] = s
		return s
	end
	@dp[n] = digital_root(s)
	return @dp[n]
end

digits,d = gets.split(" ").map(&:to_i)
@dp = {}
start = 10 ** (digits - 1)
start = 0 if start == 1
finish = (10 ** digits) - 1
ans = nil
if d == 0
	if digits == 1
		ans = 0
	end
else
	(start..finish).each do |a|
		if digital_root(a) == d
			ans = a
			break
		end
	end
end
if ans
	puts ans
else
	puts "No solution"
end

k, d = gets.split.collect{|i| i.to_i}
if d == 0
    if k == 1
        puts 0
    else
        puts 'No solution'
    end
    exit
end
puts (Array.new([d])+Array.new(k-1,0)).join

def solution(k, n)
  return 0 if n == 0 && k == 1
  return "No solution" if n == 0 && k > 1

  num = num_k(k)

  until dr(num) == n || num.to_s.size != k do
    num += 1
  end

  return "No solution" if num.to_s.size != k
  num
end

def num_k(k)
  min_num = "1"

  (k-1).times { |i| min_num << "0" }
  min_num.to_i
end

def dr(n)
  return n if n < 10
  num = n.to_s.split('').map(&:to_i).inject(:+)
  dr(num)
end

k, n = STDIN.gets.chomp.split(" ").map(&:to_i)
puts solution(k, n)

k, d = gets.split

if k == '1'
  puts d
else
  if d == '0'
    puts 'No solution'
  else
    puts d + ('0' * k.to_i.pred)
  end
end

k, d = gets.chomp.split.map{ |i| i.to_i}

if d == 0 and k > 1
	puts "No solution"
else
	puts (d.to_s + ("0" * (k - 1)))
end

line = gets
line = line.split(" ");
k = line[0].to_i
d = line[1].to_i
max = 10 ** (d-1)

while 1 && d != 0
    ans = rand((10**d) - 1) + max
    if ans % 9 == k
        break
    end
end

if d == 0
    ans = 0
end

p ans

line = gets
line = line.split(" ");
k = line[0].to_i
d = line[1].to_i
max = 10 ** (k-1)

if d != 0
    d = 0 if d == 9
    ans = rand((10**k) - 1) + max
    while ans % 9 != d
        ans += 1
    end
else
    if k == 1
        ans = 0
    else
        ans = "No solution"
    end
end

ans = ans.to_s << "\n"
print(ans)

line = gets
line = line.split(" ");
k = line[0].to_i
d = line[1].to_i
max = 10 ** (k-1)

while 1 && d != 0
    ans = rand((10**k) - 1) + max
    if ans % 9 == d
        break
    end
end

if d == 0
    ans = 0
end

p ans

line = gets
line = line.split(" ");
k = line[0].to_i
d = line[1].to_i
max = 10 ** d

while 1
    ans = rand(max-1) + max
    if ans % 9 == k
        break
    end
end

p ans

line = gets
line = line.split(" ");
k = line[0].to_i
d = line[1].to_i
max = 10 ** d

while 1 && d != 0
    ans = rand(max-1) + max
    if ans % 9 == k
        break
    end
end

if d == 0
    ans = 0
end

p ans

class A
  def initialize
    k, n = gets.chomp.split(' ').map(&:to_i)

    start = 0
    limit = 9 * k

    (0..limit).each do |num|
      res = dfs(num)

      if res == n
        puts answer(num, k)
        exit
      end
    end

    puts "No solution"
  end

  def answer(num, k)
    list = [ 9, 8, 7, 6, 5, 4, 3, 2, 1 ]
    index = 0
    answer = ""
    while num != 0
      count = num / list[index]
      num %= list[index]
      answer += list[index].to_s * count
      index += 1
    end

    if answer.to_s.size != k
      diff = k - answer.to_s.size
      answer += "0" * diff
    end

    answer
  end

  def dfs(num)
    if num < 10
      return num
    else
      return dfs(sum_digit(num))
    end
  end

  def sum_digit(num)
    str = num.to_s

    str.chars.map(&:to_i).inject(:+)
  end
end

a = A.new

k, d = gets.chomp.split(/ /).map(&:to_i)
if k > 1 && d == 0
    puts "No solution"
else
    if k == 1 && d == 0
        puts 0
    else
        puts "#{k * (10 ** (d - 1))}"
    end
end

def digital_root(n)
	return @dp[n] if @dp[n]
	s = n.to_s.split("").map(&:to_i).inject(&:+)
	if s < 10
		@dp[n] = s
		return s
	end
	@dp[n] = digital_root(s)
	return @dp[n]
end

digits,d = gets.split(" ").map(&:to_i)
@dp = {}
start = 10 ** (digits - 1)
start = 0 if start == 1
finish = (10 ** digits) - 1
ans = nil
if d == 0
	if digits == 0
		ans = 0
	end
else
	(start..finish).each do |a|
		if digital_root(a) == d
			ans = a
			break
		end
	end
end
if ans
	puts ans
else
	puts "No Solution"
end

def digital_root(n)
	return @dp[n] if @dp[n]
	s = n.to_s.split("").map(&:to_i).inject(&:+)
	if s < 10
		@dp[n] = s
		return s
	end
	@dp[n] = digital_root(s)
	return @dp[n]
end

digits,d = gets.split(" ").map(&:to_i)
@dp = {}
start = 10 ** (digits - 1)
start = 0 if start == 1
finish = (10 ** digits) - 1
ans = nil
if d == 0
	if digits == 1
		ans = 0
	end
else
	(start..finish).each do |a|
		if digital_root(a) == d
			ans = a
			break
		end
	end
end
if ans
	puts ans
else
	puts "No Solution"
end

def solution(k, n)
  return 0 if n == 0

  num = num_k(k)

  until dr(num) == n || num.to_s.size != k do
    num += 1
  end

  return "No solution" if num.to_s.size != k
  num
end

def num_k(k)
  num = "1"
  (k-1).times { |i| num << "0" }
  num.to_i
end

def dr(n)
  num = n.to_s.split('').map(&:to_i).inject(:+)
  return dr(num) if num >= 10
  num
end

k, n = STDIN.gets.chomp.split(" ").map(&:to_i)
puts solution(k, n)

def solution(k, n)
  return 0 if n == 0

  num = num_k(k)

  until dr(num) == n || num.to_s.size != k do
    num += 1
  end

  return "No solution" if num.to_s.size != k
  num
end

def num_k(k)
  min_num = "1"

  (k-1).times { |i| min_num << "0" }
  min_num.to_i
end

def dr(n)
  return n if n < 10
  num = n.to_s.split('').map(&:to_i).inject(:+)
  dr(num)
end

k, n = STDIN.gets.chomp.split(" ").map(&:to_i)
puts solution(k, n)

def solution(k, n)
  return 0 if n == 0

  min_num, max_num = num_k(k)

  num = rand(min_num..max_num)

  until dr(num) == n || num.to_s.size != k do
    num += 1
  end

  return "No solution" if num.to_s.size != k
  num
end

def num_k(k)
  min_num = "1"
  max_num = "1"

  (k-1).times { |i| min_num << "0" }
  k.times { |i| max_num << "0" }
  [min_num.to_i, max_num.to_i]
end

def dr(n)
  num = n.to_s.split('').map(&:to_i).inject(:+)
  return dr(num) if num >= 10
  num
end

k, n = STDIN.gets.chomp.split(" ").map(&:to_i)
puts solution(k, n)

def solution(k, n)
  return 0 if n == 0

  num = num_k(k)
  until dr(num) == n && num.to_s.size == k do
    num += 1
  end

  return "No solution" if num.to_s.size != k
  num
end

def num_k(k)
  num = "1"
  (k-1).times { |i| num << "0" }
  num.to_i
end

def dr(n)
  num = n.to_s.split('').map(&:to_i).inject(:+)
  return dr(num) if num >= 10
  num
end

k, n = STDIN.gets.chomp.split(" ").map(&:to_i)
puts solution(k, n)

def solution(k, n)
  return 0 if n == 0

  min_num, max_num = num_k(k)

  num = rand(min_num..max_num)

  until dr(num) == n || num.to_s.size != k do
    num += 1
  end

  return "No solution" if num.to_s.size != k
  num
end

def num_k(k)
  min_num = "1"
  max_num = "1"

  (k-1).times { |i| min_num << "0" }
  k.times { |i| max_num << "0" }
  [min_num.to_i, max_num.to_i]
end

def dr(n)
  return n if n < 10
  num = n.to_s.split('').map(&:to_i).inject(:+)
  return dr(num) if num >= 10
  num
end

k, n = STDIN.gets.chomp.split(" ").map(&:to_i)
puts solution(k, n)

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

if k.zero?
  if d.zero?
    puts 0
  else
    puts 'No solution'
  end
else
  puts d.to_s + ('0' * k.pred)
end

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

if d.zero?
  if k.zero?
    puts 0
  else
    puts 'No solution'
  end
else
  puts d.to_s + ('0' * k.pred)
end


Boboniu likes playing chess with his employees. As we know, no employee can beat the boss in the chess game, so Boboniu has never lost in any round.You are a new applicant for his company. Boboniu will test you with the following chess question:Consider a $$$n\times m$$$ grid (rows are numbered from $$$1$$$ to $$$n$$$, and columns are numbered from $$$1$$$ to $$$m$$$). You have a chess piece, and it stands at some cell $$$(S_x,S_y)$$$ which is not on the border (i.e. $$$2 \le S_x \le n-1$$$ and $$$2 \le S_y \le m-1$$$).From the cell $$$(x,y)$$$, you can move your chess piece to $$$(x,y')$$$ ($$$1\le y'\le m, y' \neq y$$$) or $$$(x',y)$$$ ($$$1\le x'\le n, x'\neq x$$$). In other words, the chess piece moves as a rook. From the cell, you can move to any cell on the same row or column.Your goal is to visit each cell exactly once. Can you find a solution?Note that cells on the path between two adjacent cells in your route are not counted as visited, and it is not required to return to the starting point.

The only line of the input contains four integers $$$n$$$, $$$m$$$, $$$S_x$$$ and $$$S_y$$$ ($$$3\le n,m\le 100$$$, $$$2 \le S_x \le n-1$$$, $$$2 \le S_y \le m-1$$$) — the number of rows, the number of columns, and the initial position of your chess piece, respectively.

You should print $$$n\cdot m$$$ lines. The $$$i$$$-th line should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \leq x_i \leq n$$$, $$$1 \leq y_i \leq m$$$), denoting the $$$i$$$-th cell that you visited. You should print exactly $$$nm$$$ pairs $$$(x_i, y_i)$$$, they should cover all possible pairs $$$(x_i, y_i)$$$, such that $$$1 \leq x_i \leq n$$$, $$$1 \leq y_i \leq m$$$. We can show that under these constraints there always exists a solution. If there are multiple answers, print any.

w,h,sx,sy = gets.chomp.split(" ").map(&:to_i)
x = sx
y = sy
w.times do |i|
  h.times do |j|
    puts "#{x} #{y}"
    if j != h-1
      y = (y+1) % h
      y = h if y == 0
    end
  end
  x = (x+1) % w
  x = w if x == 0
end

h,w,sx,sy = gets.chomp.split(" ").map(&:to_i)
x = sx
y = sy
w.times do |i|
  h.times do |j|
    puts "#{x} #{y}"
    if j != h-1
      y = (y+1) % h
      y = h if y == 0
    end
  end
  x = (x+1) % w
  x = w if x == 0
end


You are given a positive integer $$$n$$$. Your task is to find any three integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$0 \le a, b, c \le 10^9$$$) for which $$$(a\oplus b)+(b\oplus c)+(a\oplus c)=n$$$, or determine that there are no such integers.Here $$$a \oplus b$$$ denotes the bitwise XOR of $$$a$$$ and $$$b$$$. For example, $$$2 \oplus 4 = 6$$$ and $$$3 \oplus 1=2$$$.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The following lines contain the descriptions of the test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^9$$$).

For each test case, print any three integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$0 \le a, b, c \le 10^9$$$) for which $$$(a\oplus b)+(b\oplus c)+(a\oplus c)=n$$$. If no such integers exist, print $$$-1$$$.

NoteIn the first test case, $$$a=3$$$, $$$b=3$$$, $$$c=1$$$, so $$$(3 \oplus 3)+(3 \oplus 1) + (3 \oplus 1)=0+2+2=4$$$.In the second test case, there are no solutions.In the third test case, $$$(2 \oplus 4)+(4 \oplus 6) + (2 \oplus 6)=6+2+4=12$$$.

num_cases = gets.to_i
for i in (1..num_cases)
  n = gets.to_i
  if n % 2 == 0
    puts "0 0 #{n/2}"
  else
    puts "-1"
  end
end

gets.to_i.times do
  n = gets.to_i
  if n % 2 == 0
    a, b, c = n / 2 ^ 1, n / 2 ^ 1, 1
    puts [a, b, c] * " "
  else
    p -1
  end
end

gets.to_i.times do
  n = gets.to_i

  if n.odd?
    puts '-1'
    next
  end

  puts "0 0 #{n / 2}"
end

a = gets.chomp.to_i
until a == 0 do
    x = gets.chomp.to_i
    if x % 2 == 0
        puts "#{x/2} 0 #{x/2}"
    else
        puts -1
    end
    a -= 1
end

num_cases = gets.to_i
for i in (1..num_cases)
  n = gets.to_i
  if n % 2 == 0
    puts "0 #{n/2} #{n/2+1}"
  else
    puts "-1"
  end
end


While working at DTL, Ela is very aware of her physical and mental health. She started to practice various sports, such as Archery, Yoga, and Football.Since she started engaging in sports activities, Ela switches to trying a new sport on days she considers being "Luxury" days. She counts the days since she started these activities, in which the day she starts is numbered as day $$$1$$$. A "Luxury" day is the day in which the number of this day is a luxurious number. An integer $$$x$$$ is called a luxurious number if it is divisible by $$${\lfloor \sqrt{x} \rfloor}$$$.Here $$$\lfloor r \rfloor$$$ denotes the "floor" of a real number $$$r$$$. In other words, it's the largest integer not greater than $$$r$$$.For example: $$$8$$$, $$$56$$$, $$$100$$$ are luxurious numbers, since $$$8$$$ is divisible by $$$\lfloor \sqrt{8} \rfloor = \lfloor 2.8284 \rfloor = 2$$$, $$$56$$$ is divisible $$$\lfloor \sqrt{56} \rfloor = \lfloor 7.4833 \rfloor = 7$$$, and $$$100$$$ is divisible by $$$\lfloor \sqrt{100} \rfloor = \lfloor 10 \rfloor = 10$$$, respectively. On the other hand $$$5$$$, $$$40$$$ are not, since $$$5$$$ are not divisible by $$$\lfloor \sqrt{5} \rfloor = \lfloor 2.2361 \rfloor = 2$$$, and $$$40$$$ are not divisible by $$$\lfloor \sqrt{40} \rfloor = \lfloor 6.3246 \rfloor = 6$$$.Being a friend of Ela, you want to engage in these fitness activities with her to keep her and yourself accompanied (and have fun together, of course). Between day $$$l$$$ and day $$$r$$$, you want to know how many times she changes the activities.

Each test contains multiple test cases. The first line has the number of test cases $$$t$$$ ($$$1 \le t \le 10\ 000$$$). The description of the test cases follows. The only line of each test case contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le 10^{18}$$$) — the intervals at which you want to know how many times Ela changes her sports.

For each test case, output an integer that denotes the answer.

NoteIn the first test case, $$$5$$$ luxury numbers in range $$$[8, 19]$$$ are: $$$8, 9, 12, 15, 16$$$.

# This problem can be solved by finding a pattern
# the first 24 numbers have the following corresponding sqrt floored value:
# {*1=>1, *2=>1, *3=>1, *4=>2, 5=>2, *6=>2, 7=>2, *8=>2, *9=>3, 10=>3, 11=>3, *12=>3, 13=>3, 14=>3, *15=>3, *16=>4, 17=>4, 18=>4, 19=>4, *20=>4, 21=>4, 22=>4, 23=>4, *24=>4}
# also I've marked each luxurious number with a star (*)
# you can observe that each sqrt has exactly 3 luxurious numbers associated with it
# also the each set of 3 luxurious numbers is evenly spaced i.e. its separated by a space of sqrt - 1
# thus using the above two points we can find the amount of luxurious numbers leading upto any given number

def lux_nums_upto(limit)
  return 0 if limit.zero?

  floor_sqrt = Integer.sqrt(limit)
  result = ((floor_sqrt - 1) * 3) # lux nums for sqrt before limit
  result + 1 + ((limit - (floor_sqrt**2)) / floor_sqrt) # lux nums for sqrt at limit
end

def lux_nums_in_range(left_limit, right_limit)
  lux_nums_upto(right_limit) - lux_nums_upto(left_limit - 1)
end

# code for tests:

num_of_cases = gets.chomp.to_i

num_of_cases.times do
  left_limit, right_limit = gets.chomp.split.map(&:to_i)

  puts lux_nums_in_range(left_limit, right_limit)
end


Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.Rules of the game are very simple: at first number of rounds n is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her!

The first line of the input contains single integer n n (1 ≤ n ≤ 100) — the number of game rounds. The next n lines contains rounds description. i-th of them contains pair of integers mi and ci (1 ≤ mi,  ci ≤ 6) — values on dice upper face after Mishka's and Chris' throws in i-th round respectively.

If Mishka is the winner of the game, print "Mishka" (without quotes) in the only line. If Chris is the winner of the game, print "Chris" (without quotes) in the only line. If the result of the game is draw, print "Friendship is magic!^^" (without quotes) in the only line.

NoteIn the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris.

#!/usr/bin/ruby
a=b=0
gets;$<.each{|_|
	x,y=_.split.map &:to_i
	a+=1 if x>y
	b+=1 if x<y
}
puts ['Friendship is magic!^^','Chris','Mishka'][b<=>a]

n = gets.to_i

m = 0
c = 0

n.times do
  a,b = gets.split.map(&:to_i)
  m+=1 if a > b
  c+=1 if b > a
end

if m > c
  puts "Mishka"
elsif c > m
  puts "Chris"
else
  puts "Friendship is magic!^^"
end

n = gets.chomp.to_i
a, b = 0, 0

n.times do
  c, d = gets.chomp.split.map(&:to_i)
  next if c == d
  c > d ? a += 1 : b += 1
end

case
when a == b
  puts "Friendship is magic!^^"
when a > b
  puts "Mishka"
else
  puts "Chris"
end

gets;r=0;$<.map{|e|r+=eval(e.split*"<=>")};puts r>0?'Mishka':r<0?'Chris':'Friendship is magic!^^'

n = gets.to_i
c = 0
m = 0
(0...n).each do
    a, b = gets.split.map &:to_i
    if (a < b)
        c += 1
    else
        if (a > b)
            m += 1
        end
    end
end

if (c == m)
    puts "Friendship is magic!^^"
else
    if (m > c)
        puts "Mishka"
    else
        puts "Chris"
    end
end

n = gets.to_i()
mishka = 0
chris = 0
for i in (1..n)
  mc = gets.split(' ')
  if mc[0].to_i() > mc[1].to_i()
    mishka += 1
  elsif mc[0].to_i() < mc[1].to_i()
    chris += 1
  end
end
if mishka > chris
  puts "Mishka"
elsif mishka == chris
  puts "Friendship is magic!^^"
else
  puts "Chris"
end

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

N = gi
MC = ngis N

v = MC.map{|m, c| m <=> c }.inject(:+)

case
when v < 0
    puts 'Chris'
when v > 0
    puts 'Mishka'
else
    puts 'Friendship is magic!^^'
end

n = gets.to_i
ar = [0,0]
n.times do
  s = gets.split.map(&:to_i)
  ar[0] += 1 if s[0] > s[1]
  ar[1] += 1 if s[1] > s[0]
end
puts "Mishka" if ar[0] > ar[1]
puts "Chris" if ar[1] > ar[0]
puts "Friendship is magic!^^" if ar[0] == ar[1]

mc = 0
cc = 0
gets.to_i.times do
  m, c = gets.split.map(&:to_i)
  if m > c
    mc += 1
  elsif m < c
    cc += 1
  end
end

if mc > cc
  puts 'Mishka'
elsif mc < cc
  puts 'Chris'
else
  puts 'Friendship is magic!^^'
end

n = gets.strip.to_i
m_count = c_count = 0
n.times do
    m, c = gets.strip.split.map(&:to_i)
    m_count += 1 if m > c
    c_count += 1 if c > m
end
ans = "Friendship is magic!^^"
if m_count > c_count
    ans = "Mishka"
elsif m_count < c_count
    ans = "Chris"
end
puts ans

n=gets.to_i
ans=0
n.times{
	a,b=gets.split.map{|e| e.to_i}
	ans=ans+(a<=>b)
}
puts ["Chris","Friendship is magic!^^","Mishka"][(ans<=>0)+1]

n = gets.to_i
r = 0
n.times do |i|
	m,c = gets.split.map(&:to_i)
	if m > c
		r += 1
	elsif c > m
		r -= 1
	end
end
if r > 0
	puts 'Mishka'
elsif r < 0
	puts 'Chris'
else
	puts 'Friendship is magic!^^'
end

n = gets.to_i
r = 0

(1..n).each do
  a, b = gets.split.map(&:to_i)
  r += a <=> b
end

puts case
       when r > 0
         'Mishka'
       when r < 0
         'Chris'
       else
         'Friendship is magic!^^'
     end

# coding: utf-8

# if __FILE__ == $0
# end

rounds = gets.to_i
mishka_wins = 0
chris_wins = 0
draws = 0
rounds.times {
    mishka, chris = gets.split.map(&:to_i)

    if mishka > chris
        mishka_wins += 1
    elsif mishka < chris
        chris_wins += 1
    else
        draws += 0
    end
}

if mishka_wins > chris_wins
    puts "Mishka"
elsif mishka_wins < chris_wins
    puts "Chris"
else
    puts "Friendship is magic!^^"
end

games = gets.chomp.to_i
results = []
for i in (0..games-1)
	results[i] = gets.chomp
end

count = 0
for i in (0..games-1)
	split = results[i].split
	if split[0].to_i > split[1].to_i
		count += 1
	elsif split[0].to_i < split[1].to_i
		count -= 1
	else
		count += 0
	end
end

if count > 0
	print "Mishka"
elsif count == 0
	print "Friendship is magic!^^"
else
	print "Chris"
end

a=[0,0,0]
g=["Friendship is magic!^^","Mishka","Chris"]
gets.to_i.times {|x| s=gets.split.map(&:to_i); a[s[0]<=>s[1]]+=1; }
puts g[a[1]<=>a[-1]]

n = gets.to_i
wins = Hash.new(0)
n.times.map do
  a, b = gets.split.map(&:to_i)
  if a - b > 0
    wins['Mishka'] += 1
  elsif a - b < 0
    wins['Chris'] += 1
  end
end
puts wins['Mishka'] == wins['Chris'] ? 'Friendship is magic!^^' : wins.max_by{|k, v| v}[0]

n = gets.to_i
m = c = 0
for i in 1..n
  mi, ch = gets.split.map(&:to_i)
  if mi > ch
    m += 1
  elsif ch > mi
    c += 1
  end
end

if m > c
  puts 'Mishka'
elsif m < c
  puts 'Chris'
else
  puts 'Friendship is magic!^^'
end

a=b=0
gets.to_i.times do
	x = gets.split.map(&:to_i)
	a+=1 if x[0]>x[1]
	b+=1 if x[0]<x[1]
end

puts ["Friendship is magic!^^","Mishka","Chris"] [a<=>b]

n = gets.to_i
m=0
c=0
n.times do
	x,y = gets.split.map(&:to_i)
	if x>y
		m+=1
	elsif x<y
		c+=1
	end
end
if m>c
	puts "Mishka"
elsif c>m
	puts "Chris"
else
	puts "Friendship is magic!^^"
end

n = Integer(gets)
a, b = 0, 0
n.times do
  aa, bb = gets.split.map(&:to_i)
  if aa > bb
    a += 1
  end
  if aa < bb
    b += 1
  end
end

if a > b
  puts "Mishka"
end

if a < b
  puts "Chris"
end

if a == b
  puts "Friendship is magic!^^"
end

jj = 0
gets.to_i.times do
  aa, bb = gets.split.map(&:to_i)
  jj += aa <=> bb
end

if jj > 0
  puts "Mishka"
elsif jj < 0
  puts "Chris"
else
  puts "Friendship is magic!^^"
end

n = gets.to_i

result = (1..n).map do
  a, b = gets.split(' ').map(&:to_i)
  (a == b) ? 0 : (a - b) / (a - b).abs
end.inject(&:+)

if result > 0
  puts 'Mishka'
elsif result < 0
  puts 'Chris'
else
  puts 'Friendship is magic!^^'
end

n = gets.to_i
s = 0
for i in 1..n do
    a, b = gets.split.map(&:to_i)
    if a > b then
        s += 1
    elsif a < b then
        s -= 1
    end
end
if s > 0 then
    puts 'Mishka'
elsif s < 0 then
    puts 'Chris'
else
    puts 'Friendship is magic!^^'
end

gameNum = gets.chomp.to_i

mWin = 0
cWin = 0

gameNum.times do
	m, c = gets.chomp.split(' ').map(&:to_i)

	if m > c
		mWin += 1
	elsif c > m
		cWin += 1
	end
end

if mWin > cWin
	puts 'Mishka'
elsif cWin > mWin
	puts 'Chris'
else
	puts 'Friendship is magic!^^'
end

n = gets.to_i
ar = [0,0]
n.times do
  s = gets.split.map(&:to_i)
  ar[0] += s[0]
  ar[1] += s[1]
end
puts "Mishka" if ar[0] > ar[1]
puts "Chris" if ar[1] > ar[0]
puts "Friendship is magic!^^" if ar[0] == ar[1]

n = gets.to_i
r = 0
n.times do |i|
	m,c = gets.split.map(&:to_i)
	if m > c
		r += 1
	elsif c > m
		r -= 1
	end
end
if r > 0
	p 'Mishka'
elsif r < 0
	p 'Chris'
else
	p 'Friendship is magic!^^'
end

gets;r=0;$<.map{|e|r+=eval(e.split*"<=>")};puts r>0?'Mishka':r<0?'Chris':'Friendship is magic^^'

games = gets.chomp.to_i
results = []
for i in (0..games-1)
	results[i] = gets.chomp
end

count = 0
for i in (0..games-1)
	split = results[i].split
	for x in (0..1)
		if split[0].to_i > split[1].to_i
			count += 1
		else
			count -= 1
		end
	end
end

if count > 0
	print "Mishka"
elsif count == 0
	print "Friendship is magic!^^"
else
	print "Chris"
end

games = gets.chomp.to_i
results = []
for i in (0..games-1)
	results[i] = gets.chomp
end

mishka = 0
chris = 0
for i in (0..games-1)
	split = results[i].split
	mishka += split[0].to_i
	chris += split[1].to_i
end

if mishka > chris
	print "Mishka"
elsif mishka == chris
	print "Friendship is magic!^^"
else
	print "Chris"
end

a=[0,0,0]
g=["Friendship is magic!^^","Mishka","Chris"]
gets.to_i.times {|x| s=gets.split.map(&:to_i); a[s[1]<=>s[0]]+=1; }
puts g[a[1]<=>a[-1]]

n = gets.to_i
wins = Hash.new(0)
n.times.map do
  a, b = gets.split.map(&:to_i)
  if a - b > 0
    wins['Mishka'] += 1
  elsif a - b < 0
    wins['Chris'] += 1
  end
end
puts wins['Mishka'] == wins['Chris'] ? 'Friendship is magic!^^' : wins.max[0]

n = gets.to_i
wins = Hash.new(0)
n.times.map do
  a, b = gets.split.map(&:to_i)
  if a - b > 0
    wins['Misha'] += 1
  elsif a - b < 0
    wins['Chris'] += 1
  end
end
puts wins['Misha'] == wins['Chris'] ? 'Friendship is magic!^^' : wins.max[0]


You are given some Tetris field consisting of $$$n$$$ columns. The initial height of the $$$i$$$-th column of the field is $$$a_i$$$ blocks. On top of these columns you can place only figures of size $$$2 \times 1$$$ (i.e. the height of this figure is $$$2$$$ blocks and the width of this figure is $$$1$$$ block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one $$$a_i$$$ is greater than $$$0$$$:  You place one figure $$$2 \times 1$$$ (choose some $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$a_i$$$ with $$$a_i + 2$$$);  then, while all $$$a_i$$$ are greater than zero, replace each $$$a_i$$$ with $$$a_i - 1$$$. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of columns in the Tetris field. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the initial height of the $$$i$$$-th column of the Tetris field.

For each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.

NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process, the field becomes $$$[2, 0, 2]$$$. Then place the figure in the second column and after the second step of the process, the field becomes $$$[0, 0, 0]$$$.And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes $$$[0, 2]$$$. Then place the figure in the first column and after the second step of the process, the field becomes $$$[0, 0]$$$.In the fourth test case of the example, place the figure in the first column, then the field becomes $$$[102]$$$ after the first step of the process, and then the field becomes $$$[0]$$$ after the second step of the process.

tc = gets.to_i

tc.times do
    n = gets.to_i
    arr = gets.split().map{|x| x.to_i}
    ev = od = 0
    arr.each do |x|
        if x % 2 == 0
            ev += 1
        else
            od += 1
        end
    end
    if(ev == 0 || od == 0)
        puts "YES"
    else
        puts "NO"
    end
end

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  ok = true
  for i in 0...(n-1) do
    if (a[i+1] - a[i]) % 2 != 0
      ok = false
    end
  end
  puts ok ? "YES" : "NO"
end

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

  puts a.all? { |e| e.even? == a.first.even? } ? 'YES' : 'NO'
end

t = gets.chomp.to_i
(0...t).each do |_|
  n = gets.chomp.to_i
  l = gets.chomp.split.map(&:to_i)
  has_odd, has_even = false, false
  l.each{|c| c.odd? ? (has_odd = true) : (has_even = true); (break) if has_odd && has_even }
  puts (has_odd && has_even ? "NO" : "YES")
end

t = gets.chomp.to_i
(0...t).each do |_|
  n = gets.chomp.to_i
  l = gets.chomp.split.map(&:to_i)
  num_of_odd, num_of_even = l.partition{|c| c.odd? }
  puts (!num_of_odd.size.zero? && !num_of_even.size.zero? ? "NO" : "YES")
end


Vus the Cossack has $$$n$$$ real numbers $$$a_i$$$. It is known that the sum of all numbers is equal to $$$0$$$. He wants to choose a sequence $$$b$$$ the size of which is $$$n$$$ such that the sum of all numbers is $$$0$$$ and each $$$b_i$$$ is either $$$\lfloor a_i \rfloor$$$ or $$$\lceil a_i \rceil$$$. In other words, $$$b_i$$$ equals $$$a_i$$$ rounded up or down. It is not necessary to round to the nearest integer.For example, if $$$a = [4.58413, 1.22491, -2.10517, -3.70387]$$$, then $$$b$$$ can be equal, for example, to $$$[4, 2, -2, -4]$$$. Note that if $$$a_i$$$ is an integer, then there is no difference between $$$\lfloor a_i \rfloor$$$ and $$$\lceil a_i \rceil$$$, $$$b_i$$$ will always be equal to $$$a_i$$$.Help Vus the Cossack find such sequence!

The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of numbers. Each of the next $$$n$$$ lines contains one real number $$$a_i$$$ ($$$|a_i| < 10^5$$$). It is guaranteed that each $$$a_i$$$ has exactly $$$5$$$ digits after the decimal point. It is guaranteed that the sum of all the numbers is equal to $$$0$$$.

In each of the next $$$n$$$ lines, print one integer $$$b_i$$$. For each $$$i$$$, $$$|a_i-b_i|<1$$$ must be met. If there are multiple answers, print any.

NoteThe first example is explained in the legend.In the second example, we can round the first and fifth numbers up, and the second and third numbers down. We can round the fourth number neither up, nor down.

N = gets.to_i
sd = 0
incremantables = {}
cs = []
(0...N).map{ |i|
  a = gets.to_f
  c = a.floor
  cs << c
  d = a - c
  sd += d
  incremantables[i] = 1 if d > 0
}
sd = (sd + 0.5).floor

puts (0...N).map{ |i|
  if sd > 0 && incremantables[i]
    sd -= 1
    cs[i] + 1
  else
    cs[i]
  end
}

n = gets.to_i
a = n.times.map{gets.chomp}
b = Array.new(n,0)
sum = 0
a.each_with_index do |s,i|
    b[i] = s.to_i
    if s[0] == "-" && s[-5..-1] != "00000"
        b[i] -= 1
    end
    sum += b[i]
end
a.each_with_index do |s,i|
    break if sum == 0
    next if s[-5..-1] == "00000"
    sum += 1
    b[i] += 1
end
puts b

n=gets.to_i
a=Array.new(n)
k=0
for i in 0...n do
    q=gets
    a[i]=q.to_f
    k+=q.to_i
end
    for i in 0...n do
        if k>0 then
            if a[i].to_i != a[i].floor or a[i].to_i != a[i].ceil then
                if a[i]>0 then
                    puts a[i].floor
                else
                    puts a[i].floor
                    k-=1
                end
                else
                    puts a[i].to_i
            end
        elsif k<0 then
            if a[i].to_i != a[i].floor or a[i].to_i != a[i].ceil then
                if a[i]>0 then
                    puts a[i].ceil
                    k+=1
                else
                    puts a[i].ceil
                end
                    else
                    puts a[i].to_i
            end
            else
            puts a[i].to_i
        end
    end

N = gets.to_i
sd = 0
incremantables = {}
cs = []
(0...N).map{ |i|
  a = gets.to_f
  c = a.floor
  cs << c
  d = a - c
  sd += d
  incremantables[i] = 1 if d > 0
}

puts (0...N).map{ |i|
  if sd > 0 && incremantables[i]
    sd -= 1
    cs[i] + 1
  else
    cs[i]
  end
} * " "

n = gets.to_i
a = n.times.map{gets.chomp}
b = a.map(&:to_i)
sum = b.inject(:+)
a.each_with_index do |s,i|
    break if sum == 0
    next if s[-5..-1] == "00000"
    sum += 1
    b[i] += 1
end
puts b

n=gets.to_i
a=Array.new(n)
k=0
for i in 0...n do
    q=gets
    a[i]=q.to_f
    k+=q.to_i
end
    for i in 0...n do
        if k>0 then
            if a[i]>0 and a[i].to_i!=a[i].ceil.to_i then
                puts a[i].ceil
            else
                puts a[i].floor
                k-=1
            end
        elsif k<0 then
            if a[i]>0 and a[i].to_i!=a[i].ceil.to_i then
                puts a[i].ceil
                k+=1
            else
                puts a[i].floor
            end
        else
                puts a[i].to_i
        end
    end

n=gets.to_i
a=Array.new(n)
k=0
for i in 0...n do
    q=gets
    a[i]=q.to_f
    k+=q.to_i
end
    for i in 0...n do
        if k>0 then
            if a[i]>0 then
                puts a[i].ceil
            else
                puts a[i].floor
                k-=1
            end
        elsif k<0 then
            if a[i]>0 then
                puts a[i].ceil
            else
                puts a[i].floor
                k+=1
            end
        else
                puts a[i].to_i
        end
    end

n=gets.to_i
a=Array.new(n)
k=0
for i in 0...n do
    q=gets
    a[i]=q.to_f
    k+=q.to_i
end
    for i in 0...n do
        if k>0 then
            if a[i]>0 then
                puts a[i].floor
                k-=1
            else
                puts a[i].ceil
            end
        elsif k<0 then
            if a[i]>0 then
                puts a[i].ceil
            else
                puts a[i].floor
            end
        else
                puts a[i].to_i
        end
    end

n=gets.to_i
a=Array.new(n)
k=0
for i in 0...n do
    q=gets
    a[i]=q.to_f
    k+=q.to_i
end
    for i in 0...n do
        if k>0 then
            if a[i].to_i != a[i].floor then
                if a[i]>0 then
                    puts a[i].floor
                else
                    puts a[i].floor
                    k-=1
                end
                else
                    puts a[i].to_i
            end
        elsif k<0 then
            if a[i].to_i != a[i].floor then
                if a[i]>0 then
                    puts a[i].ceil
                    k+=1
                else
                    puts a[i].ceil
                end
                    else
                    puts a[i].to_i
            end
            else
            puts a[i].to_i
        end
    end


There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held.Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos.The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible.

The first line contains a single integer — n (1 ≤ n ≤ 5·105). Each of the next n lines contains an integer si — the size of the i-th kangaroo (1 ≤ si ≤ 105).

Output a single integer — the optimal number of visible kangaroos.

n=gets.to_i
a=[]
n.times{a<<gets.to_i}
a.sort!.reverse!
i=c=0
j=(n+1)/2
while j<n
  (c+=1;i+=1)if a[i]/2>=a[j]
  j+=1
end
p n-c

n = gets.to_i
a = []
dem = []
dem1 = 0

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

a.sort!

i = 0

while (a[i]<= (a[n-1]/2)) && (i<=(n/2-1)) do
    if i == 0
        j = i+1
    else
        j = n - dem[i-1]
    end
    while ((2*a[i])>a[j]) && (j<n) do
        j += 1
    end
    dem[i] = n - j
    i += 1
end

i -= 1
while i>=0 do
    if dem[i] > dem1
        dem1 += 1
    end
    i -= 1
end

puts n-dem1

n = gets.to_i
a = []
dem = []
dem1 = 0

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

a.sort!

i = 0

while (a[i]<= (a[n-1]/2)) && (i<=(n/2-1)) do
    j = i+1
    while ((2*a[i])>a[j]) && (j<n) do
        j += 1
    end
    dem[i] = n - j
    i += 1
end

puts dem

i -= 1
while i>=0 do
    if dem[i] > dem1
        dem1 += 1
    end
    i -= 1
end

puts n-dem1

n=gets.to_i
a=[]
n.times{a<<gets.to_i}
a.sort!.reverse!
i=c=0
j=n/2
while j<n
  (c+=1;i+=1)if a[i]/2>=a[j]
  j+=1
end
p n-c

n=gets.to_i
a=[]
n.times{a<<gets.to_i}
a.sort!.reverse!
i=j=c=0
while j<n
  (c+=1;i+=1)if a[i]/2>=a[j]
  j+=1
end
p n-c


The Berland language consists of words having exactly two letters. Moreover, the first letter of a word is different from the second letter. Any combination of two different Berland letters (which, by the way, are the same as the lowercase letters of Latin alphabet) is a correct word in Berland language.The Berland dictionary contains all words of this language. The words are listed in a way they are usually ordered in dictionaries. Formally, word $$$a$$$ comes earlier than word $$$b$$$ in the dictionary if one of the following conditions hold:  the first letter of $$$a$$$ is less than the first letter of $$$b$$$;  the first letters of $$$a$$$ and $$$b$$$ are the same, and the second letter of $$$a$$$ is less than the second letter of $$$b$$$. So, the dictionary looks like that:  Word $$$1$$$: ab  Word $$$2$$$: ac  ...  Word $$$25$$$: az  Word $$$26$$$: ba  Word $$$27$$$: bc  ...  Word $$$649$$$: zx  Word $$$650$$$: zy You are given a word $$$s$$$ from the Berland language. Your task is to find its index in the dictionary.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 650$$$) — the number of test cases. Each test case consists of one line containing $$$s$$$ — a string consisting of exactly two different lowercase Latin letters (i. e. a correct word of the Berland language).

For each test case, print one integer — the index of the word $$$s$$$ in the dictionary.

a=" "*27
for i in 0..25
	a[i]=('a'.ord+i).chr
end
r=[]
a.split('').each do |e|
	a.split('').each do |u|
		if e!=u && e!=" " && u!=" "
			r.append(e+u)
		end
	end
end
for t in 1..gets[..-2].to_i
	puts r.index(gets[..-2])+1
end

m, az = {}, "abcdefghijklmnopqrstuvwxyz".chars
az.product(az).filter {|a| a[0] !=  a[1]}.map{|a| a[0] + a[1]}.each_with_index {|a,i| m[a] = i+1}
gets.to_i.times  { puts m[gets.chomp] }

words = {}
cnt = 1
('a'..'z').each do |a|
  ('a'..'z').each do |b|
    next if a == b
    words[a + b] = cnt
    cnt += 1
  end
end

gets.to_i.times do
  s = gets.strip
  p words[s]
end

map = [*"a".."z"].flat_map do |a|
  ([*"a".."z"] - [a]).map do |b|
    a + b
  end
end.zip(1..).to_h

gets.to_i.times do
  p map[gets.chomp]
end

t=gets.chomp.to_i
arr = ('a'..'z').to_a
arrAZ =[]
kol=0
for i in 0..25
    for j in 0..25
        if (arr[i].to_s!=arr[j].to_s)
            kol+=1
            arrAZ[kol]=arr[i]+arr[j]
        end
    end
end

#puts arrAZ.compact
#puts arrAZ.length

t.times do
    puts arrAZ.index(gets.chomp.to_s)
end

t = gets.to_i
a = ?a.ord
t.times do
    x, y = gets.chomp.each_byte.map { |b| b - a }
    i = x * 25 + y + 1
    i -= 1 if y > x
    puts i
end

h = {}
q = 1
for i in 'a'..'z'
  for j in 'a'..'z'
    next if i == j
    h[i + j] = q
    q += 1
  end
end

gets.to_i.times do
  puts h[gets.chomp]
end


Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1, x2, ..., xn. Vasya starts at the point with coordinate a. His goal is to visit at least n - 1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order.Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.

The first line of the input contains two integers n and a (1 ≤ n ≤ 100 000,  - 1 000 000 ≤ a ≤ 1 000 000) — the number of checkpoints and Vasya's starting position respectively. The second line contains n integers x1, x2, ..., xn ( - 1 000 000 ≤ xi ≤ 1 000 000) — coordinates of the checkpoints.

Print one integer — the minimum distance Vasya has to travel in order to visit at least n - 1 checkpoint.

NoteIn the first sample Vasya has to visit at least two checkpoints. The optimal way to achieve this is the walk to the third checkpoints (distance is 12 - 10 = 2) and then proceed to the second one (distance is 12 - 7 = 5). The total distance is equal to 2 + 5 = 7.In the second sample it's enough to visit only one checkpoint so Vasya should just walk to the point  - 10.

#!/usr/bin/ruby
n,s,*a=$<.read.split.map &:to_i
a.sort!
if n<2
	p 0
else
	p [[0,-2],[1,-1]].map{|i,j|
		x,y=[[s-a[i],0].max,[a[j]-s,0].max].minmax
		x*2+y
	}.min
end

#!/usr/bin/ruby
n,s,*a=$<.read.split.map &:to_i
a.sort!
if n<2
	p 0
elsif s<a[0]
	p a[-2]-s
elsif a[-1]<s
	p s-a[1]
else
	p [[0,-2],[1,-1]].map{|i,j|
		x,y=[[s-a[i],0].max,[a[j]-s,0].max].minmax
		x*2+y
	}.min
end

input = gets.strip.split(' ').map(&:to_i)
n = input[0]
a = input[1]
checkps = gets.strip.split(' ').map(&:to_i).sort
left_dists = []
right_dists = []
checkps.each do |cp|
  if cp < a
    left_dists << a - cp
  elsif cp > a
    right_dists << cp - a
  end
end
checkps.delete(a)

if checkps.length > 0
  if left_dists.length > 0 and right_dists.length > 0
    mindist1 = 0
    mindist2 = 0

    old_left = left_dists.dup
    left_dists.slice! left_dists.index(left_dists.max)
    ldm = 0
    rdm = 0
    if not left_dists.max.nil?
      ldm = left_dists.max
    end
    if not right_dists.max.nil?
      rdm = right_dists.max
    end
    if (ldm > rdm)
      mindist1 = 2 * rdm + ldm
    else
      mindist1 = rdm + 2 * ldm
    end

    left_dists = old_left
    right_dists.slice! right_dists.index(right_dists.max)
    ldm = 0
    rdm = 0
    if not left_dists.max.nil?
      ldm = left_dists.max
    end
    if not right_dists.max.nil?
      rdm = right_dists.max
    end
    if (ldm > rdm)
      mindist2 = 2 * rdm + ldm
    else
      mindist2 = rdm + 2 * ldm
    end

    puts [mindist1, mindist2].min

  elsif left_dists.length > 0
    left_dists.slice! left_dists.index(left_dists.max)
    ldm = 0
    if not left_dists.max.nil?
      ldm = left_dists.max
    end
    puts ldm
  else
    right_dists.slice! right_dists.index(right_dists.max)
    rdm = 0
    if not right_dists.max.nil?
      rdm = right_dists.max
    end
    puts rdm
  end
else
  puts 0
end

input = gets.strip.split(' ').map(&:to_i)
n = input[0]
a = input[1]
checkps = gets.strip.split(' ').map(&:to_i).sort
dists = []
checkps.each do |cp|
  dists << (cp-a).abs
end
tbr = dists.index(dists.max)
checkps.slice! tbr
dists.slice! tbr
left_exists = false
right_exists = false
checkps.each do |cp|
  if cp < a
    left_exists = true
  elsif cp > a
    right_exists = true
  end
end
if left_exists and right_exists
  tbds = dists.index(dists.max)
  mindist = 0
  if checkps[tbds] - a > 0
    mindist = dists[0] * 2 + dists[dists.length-1]
  else
    mindist = dists[dists.length-1] * 2 + dists[0]
  end
  puts mindist
else
  if left_exists
    puts dists[0]
  elsif right_exists
    puts dists[dists.length-1]
  else
    puts 0
  end
end

input = gets.strip.split(' ').map(&:to_i)
n = input[0]
a = input[1]
checkps = gets.strip.split(' ').map(&:to_i).sort
dists = []
left_exists = false
right_exists = false
checkps.each do |cp|
  dists << (cp-a).abs
  if cp < a
    left_exists = true
  elsif cp > a
    right_exists = true
  end
end
tbr = dists.index(dists.max)
checkps.slice! tbr
dists.slice! tbr
if left_exists and right_exists
  tbds = dists.index(dists.max)
  mindist = 0
  if checkps[tbds] - a > 0
    mindist = dists[0] * 2 + dists[dists.length-1]
  else
    mindist = dists[dists.length-1] * 2 + dists[0]
  end
  puts mindist
else
  if left_exists
    puts dists[0]
  elsif right_exists
    puts dists[dists.length-1]
  else
    puts 0
  end
end

input = gets.strip.split(' ').map(&:to_i)
n = input[0]
a = input[1]
checkps = gets.strip.split(' ').map(&:to_i).sort
dists = []
checkps.each do |cp|
  dists << (cp-a).abs
end
tbr = dists.index(dists.max)
checkps.slice! tbr
dists.slice! tbr
tbds = dists.index(dists.max)
mindist = 0
if checkps[tbds] - a > 0
  mindist = dists[0] * 2 + dists[dists.length-1]
else
  mindist = dists[dists.length-1] * 2 + dists[0]
end
puts mindist


You are given an array $$$a$$$ of $$$2n$$$ distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its $$$2$$$ neighbours.More formally, find an array $$$b$$$, such that: $$$b$$$ is a permutation of $$$a$$$.For every $$$i$$$ from $$$1$$$ to $$$2n$$$, $$$b_i \neq \frac{b_{i-1}+b_{i+1}}{2}$$$, where $$$b_0 = b_{2n}$$$ and $$$b_{2n+1} = b_1$$$. It can be proved that under the constraints of this problem, such array $$$b$$$ always exists.

The first line of input contains a single integer $$$t$$$ $$$(1 \leq t \leq 1000)$$$ — the number of testcases. The description of testcases follows. The first line of each testcase contains a single integer $$$n$$$ $$$(1 \leq n \leq 25)$$$. The second line of each testcase contains $$$2n$$$ integers $$$a_1, a_2, \ldots, a_{2n}$$$ $$$(1 \leq a_i \leq 10^9)$$$ — elements of the array. Note that there is no limit to the sum of $$$n$$$ over all testcases.

For each testcase, you should output $$$2n$$$ integers, $$$b_1, b_2, \ldots b_{2n}$$$, for which the conditions from the statement are satisfied.

results = []
t = gets.chomp
(1..t.to_i).each do |iteration|
	n = gets.chomp.to_i
	a = gets.chomp.split(' ').map{|e| e.to_i}.sort
	b = []

	(0..n-1).each do |idx|
		b[2*idx] = a[idx]
		b[2*idx+1] = a[n+idx]
	end

	results.push(b)
end
results.each do |res|
	puts res
end

data_lines = gets.chomp

def prodess_arr arr
	# p '-----'
	# p arr
	# p '-----'
	new_arr = []
	arr = arr.sort
	middle = arr.length / 2
	(0..arr.length-1).each do |index|
		if index < middle
			new_arr[index * 2] = arr[index]
		else
			new_index = index - middle
			new_arr[new_index*2+1] = arr[index]
		end
	end
	new_arr

	# success = false
	# while success == false
	# 	flag = true
	# 	(0..arr.length-1).each do |index|
	# 		# p "number = #{arr[index]} index = #{index}"
	# 		neigh_l_index = index-1
	# 		neigh_l_index = arr.length-1 if neigh_l_index < 0
	# 		neigh_r_index = index+1
	# 		neigh_r_index = 0 if neigh_r_index > arr.length-1
	# 		sr_ar = (arr[neigh_l_index].to_f + arr[neigh_r_index].to_f) / 2.0
	# 		# p "sr_ar - arr[index] = #{sr_ar - arr[index]}"
	# 		if sr_ar - arr[index] == 0.0
	# 			# p arr
	# 			flag = false
	# 			neigh_rr_index = index+2
	# 			if neigh_rr_index > arr.length-1
	# 				if neigh_rr_index == arr.length-1
	# 					neigh_rr_index = 0
	# 				else
	# 					neigh_rr_index = 1
	# 				end
	# 			end
	# 			buffer = arr[neigh_r_index]
	# 			arr[neigh_r_index] = arr[neigh_rr_index]
	# 			arr[neigh_rr_index] = buffer
	# 			# p arr
	# 		end
	# 	end
	# 	# p success
	# 	success = true if flag
	# 	# p success
	# end
	# arr
end
arrs = []
(1..data_lines.to_i).each do
	b = gets.chomp
	arrs.push prodess_arr(gets.chomp.split(' ').map{|_e| _e.to_i}).join(' ')
end
arrs.each do |a|
	puts a
end

def solution(n, arr)
	i = 0

	while i < 2 * n
		prev_index = prev_index(arr, 2 * n, i)
		next_index = next_index(arr, 2 * n, i)

		if (arr[prev_index] + arr[next_index]) / 2.0 == 1.0 * arr[i]
			arr[i], arr[prev_index] = arr[prev_index], arr[i]
			i = 0
		else
			i += 1
		end
	end

	arr
end

def prev_index(arr, n,  i)
	if i == 0
		return n - 1
	else
		return i - 1
	end
end

def next_index(arr, n,  i)
	if i == n - 1
		return 0
	else
		return i + 1
	end
end

test_cases = gets.to_i

test_cases.times do |test_case|
  n = gets.to_i
  arr = gets.chomp.split(' ').map(&:to_i)
  puts solution(n, arr).join(' ')
end

def check_valid arr
	arr.each_with_index do |el, idx|
		mid = (arr[idx+1].to_f + arr[idx-1].to_f) / 2
		if mid == el.to_f
			return false
		end
	end
	true
end

results = []
t = gets.chomp
(1..t.to_i).each do |iteration|
	n = gets.chomp
	a = gets.chomp.split(' ').map{|e| e.to_i}

	a.permutation.each do |perm|
		if check_valid perm
			results.push perm
			break
		end
	end
end
results.each do |res|
	p res.join("\s")
end

def check_valid arr
	arr.each_with_index do |el, idx|
		mid = (arr[idx+1].to_f + arr[idx-1].to_f) / 2
		if mid == el.to_f
			return false
		end
	end
	true
end

results = []
t = gets.chomp
(1..t.to_i).each do |iteration|
	n = gets.chomp
	a = gets.chomp.split(' ').map{|e| e.to_i}

	a.permutation.each do |perm|
		if check_valid perm
			results.push perm
			break
		end
	end
end
p results

data_lines = gets.chomp

def prodess_arr arr
	# p '-----'
	# p arr
	# p '-----'
	new_arr = []
	arr = arr.sort
	(0..arr.length-1).each do |index|
		if index % 2 == 0
			new_arr[index / 2] = arr[index]
		else
			middle = arr.length / 2
			new_arr[(index / 2) + middle] = arr[index]
		end
	end
	new_arr

	# success = false
	# while success == false
	# 	flag = true
	# 	(0..arr.length-1).each do |index|
	# 		# p "number = #{arr[index]} index = #{index}"
	# 		neigh_l_index = index-1
	# 		neigh_l_index = arr.length-1 if neigh_l_index < 0
	# 		neigh_r_index = index+1
	# 		neigh_r_index = 0 if neigh_r_index > arr.length-1
	# 		sr_ar = (arr[neigh_l_index].to_f + arr[neigh_r_index].to_f) / 2.0
	# 		# p "sr_ar - arr[index] = #{sr_ar - arr[index]}"
	# 		if sr_ar - arr[index] == 0.0
	# 			# p arr
	# 			flag = false
	# 			neigh_rr_index = index+2
	# 			if neigh_rr_index > arr.length-1
	# 				if neigh_rr_index == arr.length-1
	# 					neigh_rr_index = 0
	# 				else
	# 					neigh_rr_index = 1
	# 				end
	# 			end
	# 			buffer = arr[neigh_r_index]
	# 			arr[neigh_r_index] = arr[neigh_rr_index]
	# 			arr[neigh_rr_index] = buffer
	# 			# p arr
	# 		end
	# 	end
	# 	# p success
	# 	success = true if flag
	# 	# p success
	# end
	# arr
end
arrs = []
(1..data_lines.to_i).each do
	b = gets.chomp
	arrs.push prodess_arr(gets.chomp.split(' ').map{|_e| _e.to_i}).join(' ')
end
arrs.each do |a|
	puts a
end

def solution(n, arr)
	(0..(2 * n - 1)).each do |i|
		prev_index = prev_index(arr, 2 * n, i)
		next_index = next_index(arr, 2 * n, i)

		# puts "i: #{i}"
		# puts "prev_index: #{prev_index}"
		# puts "next_index: #{next_index}"
		# puts "------------"
		if (arr[prev_index] + arr[next_index]) / 2.0 == 1.0 * arr[i]
			# prev_index = prev_index(arr, n, i - 1)
			arr[i], arr[prev_index] = arr[prev_index], arr[i]
		end
	end

	arr
end

def prev_index(arr, n,  i)
	if i == 0
		return n - 1
	else
		return i - 1
	end
end

def next_index(arr, n,  i)
	if i == n - 1
		return 0
	else
		return i + 1
	end
end

test_cases = gets.to_i

test_cases.times do |test_case|
  n = gets.to_i
  arr = gets.chomp.split(' ').map(&:to_i)
  puts solution(n, arr).join(' ')
end


You have three piles of candies: red, green and blue candies:  the first pile contains only red candies and there are $$$r$$$ candies in it,  the second pile contains only green candies and there are $$$g$$$ candies in it,  the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.

The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.

Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.

NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.

class SweetProblem

  def initialize(debug=false)
    @debug = debug
  end

  def get_num_days_can_eat(input_arr)
    sum = 0
    input_arr.each do |val|
      sum = sum + val
    end

    ans = sum / 2

    sum_red_green = input_arr[0] + input_arr[1]
    sum_green_blue = input_arr[1] + input_arr[2]
    sum_red_blue = input_arr[0] + input_arr[2]

    if sum_red_green < ans
      ans = sum_red_green
    end
    if sum_green_blue < ans
      ans = sum_green_blue
    end
    if sum_red_blue < ans
      ans = sum_red_blue
    end

    ans
  end

  def main
    i = 0
    num_lines = 0
    while input = gets
      if i == 0
        num_lines = input.to_i
        i = i + 1
        next
      else
        input_arr = input.split(' ').map!(&:to_i)

        num_days_can_eat = get_num_days_can_eat(input_arr)

        puts num_days_can_eat
        i = i + 1
        break if i > num_lines
      end
    end
  end

end

sweet_problem = SweetProblem.new
sweet_problem.main

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

require 'prime'

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

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

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

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

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

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

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

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

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

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

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

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

n = inp[0]
n.times do
  a,b,c = inp.sort
  d =  (a+b) - c
  puts  (d <= 0)? a+b : c + d/2
end

class SweetProblem

  def initialize(debug=false)
    @debug = debug
  end
  def to_hash(array)
    red = array[0]
    green = array[1]
    blue = array[2]
    result = Hash.new
    result['R'] = red
    result['G'] = green
    result['B'] = blue
    result
  end

  def min_color(hash)
    min = (10**8) + 1
    min_color_key = nil
    hash.each do |key,val|
      next if val == 0
      if val < min
        min = val
        min_color_key = key
      end
    end
    return min_color_key
  end

  def max_color(hash, color_key)
    two_colors_same_max = false
    max = 0
    max_color_key = nil
    hash.each do |key,val|
     if val == max and key != color_key
       two_colors_same_max = true
     end
     if val > max and key != color_key
        max = val
        max_color_key = key
      end
    end
    return max_color_key, two_colors_same_max
  end

  def num_colors_left(hash)
    num_colors = 0
    hash.each do |key,val|
      if val > 0
        num_colors = num_colors + 1
      end
    end
    num_colors
  end

  def get_num_days_can_eat(input_arr)
    hash = to_hash(input_arr)
    puts hash if @debug

    min_color = min_color(hash)
    puts "min_color: #{min_color}" if @debug
    max_color, two_colors_same_max = max_color(hash, min_color)
    puts "max_color: #{max_color}" if @debug
    puts "two_colors_same_max: #{two_colors_same_max}" if @debug

    num_days_can_eat = 0
    while num_colors_left(hash) >= 2
      min_color_count = hash[min_color]
      puts "min_color_count: #{min_color_count}" if @debug

      if two_colors_same_max and (num_colors_left(hash) == 3)
        max_color_count = hash[max_color] - 1
        hash[max_color] = max_color_count
      else
        max_color_count = hash[max_color] - min_color_count
        hash[max_color] = max_color_count
      end

      puts "max_color_count is now: #{hash[max_color]}" if @debug

      if two_colors_same_max and (num_colors_left(hash) == 3)
        min_color_count = hash[min_color] - 1
        hash[min_color] = min_color_count
      else
        hash[min_color] = 0
      end
      puts "min_color_count is now: #{hash[min_color]}" if @debug

      num_days_can_eat = num_days_can_eat + min_color_count
      puts "num_days_can_eat: #{num_days_can_eat}" if @debug

      min_color = min_color(hash)
      max_color, two_colors_same_max = max_color(hash, min_color)
      puts hash if @debug
      puts "min_color: #{min_color}" if @debug
      puts "max_color: #{max_color}" if @debug
    end
    num_days_can_eat
  end

  def main
    i = 0
    num_lines = 0
    while input = gets
      if i == 0
        num_lines = input.to_i
        i = i + 1
        next
      else
        input_arr = input.split(' ').map!(&:to_i)

        num_days_can_eat = get_num_days_can_eat(input_arr)

        puts num_days_can_eat
        i = i + 1
        break if i > num_lines
      end
    end
  end

end

sweet_problem = SweetProblem.new
sweet_problem.main

def to_hash(array)
  red = array[0]
  green = array[1]
  blue = array[2]
  result = Hash.new
  result['R'] = red
  result['G'] = green
  result['B'] = blue
  result
end

def min_color(hash)
  min = (10**8) + 1
  min_color_key = nil
  hash.each do |key,val|
    next if val == 0
    if val < min
      min = val
      min_color_key = key
    end
  end
  return min_color_key
end

def max_color(hash, color_key)
  max = 0
  max_color_key = nil
  hash.each do |key,val|
   if val > max and key != color_key
      max = val
      max_color_key = key
    end
  end
  return max_color_key
end

def num_colors_left(hash)
  num_colors = 0
  hash.each do |key,val|
    if val > 0
      num_colors = num_colors + 1
    end
  end
  num_colors
end

i = 0
num_lines = 0
while input = gets
  if i == 0
    num_lines = input.to_i
    i = i + 1
    next
  else
    input_arr = input.split(' ').map!(&:to_i)

    hash = to_hash(input_arr)

    min_color = min_color(hash)
    max_color = max_color(hash, min_color)

    num_days_can_eat = 0
    while num_colors_left(hash) >= 2
      min_color_count = hash[min_color]

      max_color_count = hash[max_color] - min_color_count
      hash[max_color] = max_color_count

      hash[min_color] = 0

      min_color = min_color(hash)
      max_color = max_color(hash, min_color)
      num_days_can_eat = num_days_can_eat + min_color_count
    end

    puts num_days_can_eat
    i = i + 1
    break if i > num_lines
  end
end


It is given a positive integer $$$n$$$. In $$$1$$$ move, one can select any single digit and remove it (i.e. one selects some position in the number and removes the digit located at this position). The operation cannot be performed if only one digit remains. If the resulting number contains leading zeroes, they are automatically removed.E.g. if one removes from the number $$$32925$$$ the $$$3$$$-rd digit, the resulting number will be $$$3225$$$. If one removes from the number $$$20099050$$$ the first digit, the resulting number will be $$$99050$$$ (the $$$2$$$ zeroes going next to the first digit are automatically removed).What is the minimum number of steps to get a number such that it is divisible by $$$25$$$ and positive? It is guaranteed that, for each $$$n$$$ occurring in the input, the answer exists. It is guaranteed that the number $$$n$$$ has no leading zeros.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing one integer $$$n$$$ ($$$25 \le n \le 10^{18}$$$). It is guaranteed that, for each $$$n$$$ occurring in the input, the answer exists. It is guaranteed that the number $$$n$$$ has no leading zeros.

For each test case output on a separate line an integer $$$k$$$ ($$$k \ge 0$$$) — the minimum number of steps to get a number such that it is divisible by $$$25$$$ and positive.

NoteIn the first test case, it is already given a number divisible by $$$25$$$.In the second test case, we can remove the digits $$$1$$$, $$$3$$$, and $$$4$$$ to get the number $$$75$$$.In the third test case, it's enough to remove the last digit to get the number $$$325$$$.In the fourth test case, we can remove the three last digits to get the number $$$50$$$.In the fifth test case, it's enough to remove the digits $$$4$$$ and $$$7$$$.

def f(dgts)
  n0 = dgts.length
  i0 = dgts.rindex("0") || 0
  j0 = i0 > 0 && dgts.rindex(/[05]/, i0 - 1) || -10000

  n5 = dgts.length
  i5 = dgts.rindex("5") || 0
  j5 = i5 > 0 && dgts.rindex(/[27]/, i5 - 1) || -10000

  # p [i0, j0, i5, j5]
  [n0 - 2 - j0, n5 - 2 - j5].min
end

gets.to_i.times do

n = gets.chomp
puts f(n)

end

t = gets.chomp.to_i

def solve
	n = gets.chomp.to_i
	d = n.digits
	d = d.reverse
	ans = 1e9
	inf = -1e9
	#25 75 50 00
	index = {2=>inf, 7=>inf, 5=>inf, 0=>inf}

	(0..(d.length - 1)).each { |i|
		if (d[i] == 5)
			ans = [ans, (i - index[2] - 1) + d.length - i - 1].min
			ans = [ans, (i - index[7] - 1) + d.length - i - 1].min
		end
		if (d[i] == 0)
			ans = [ans, (i - index[0] - 1) + d.length - i - 1].min
			ans = [ans, (i - index[5] - 1) + d.length - i - 1].min
		end
		if d[i] == 2 || d[i] == 7 || d[i] == 5 || d[i] == 0
			index[d[i]] = i
		end
	}
	puts ans
end

t.times {
	solve
}

t = gets.chomp.to_i

def solve
	n = gets.chomp.to_i
	d = n.digits
	d = d.reverse
	ans = 1e9
	inf = -1e9
	#25 75 50 00
	index = {2=>inf, 7=>inf, 5=>inf, 0=>inf}

	(0..(d.length - 1)).each { |i|
		if (d[i] == 5)
			ans = [ans, (i - index[2] - 1) + d.length - i - 1].min
			ans = [ans, (i - index[7] - 1) + d.length - i - 1].min
		end
		if (d[i] == 0)
			ans = [ans, (i - index[0] - 1) + d.length - i - 1].min
			ans = [ans, (i - index[5] - 1) + d.length - i - 1].min
		end
		index[d[i]] = i
	}
	puts ans
end

t.times {
	solve
}

def k(n)
    c1 = 0
    c2 = 0
    c3 = 0
    c4 = 0
    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    while n > 0
        dig = n % 10
        if dig == 0
            c1 += 1
        else
            d1 += 1
        end

        if c1 == 2
            return d1
        end

        if dig == 5 and c2 == 0
            c2+=1
        elsif dig == 2 and c2 == 1
            return d2
        else
            d2+=1
        end

        if(dig == 0 and c3 == 0)
            c3+=1
        elsif(dig == 5 and c3 == 1)
            return d3
        else
            d3+=1
        end

        if(dig == 5 and c4 == 0)
            c4+=1
        elsif(dig == 7 and c4 == 1)
            return d4
        else
            d4+=1
        end

        n = n / 10
    end

    return 1000

end

gets.to_i.times do
    n = gets.to_i
    puts k(n)
end

t = gets.chomp.to_i

def calc(pos, a, b)
    first = pos[b][-1]
    second = pos[a].reverse_each.find { |v| v > first }
    return Float::INFINITY if !second
    return first + second - first - 1
end

t.times do
    n = gets.chomp

    pos = Hash.new { |h, k| h[k] = [] }
    n.split('').each_with_index do |c, idx|
        if c == '0' || c == '2' || c == '5' || c == '7'
            pos[c] << n.length - idx - 1
        end
    end

    possibilities = []
    if pos['0'].length >= 2
        possibilities << calc(pos, '0', '0')
    end

    if pos['0'].length >= 1 && pos['5'].length >= 1
        possibilities << calc(pos, '5', '0')
    end

    if pos['2'].length >= 1 && pos['5'].length >= 1
        possibilities << calc(pos, '2', '5')
    end

    if pos['7'].length >= 1 && pos['5'].length >= 1
        possibilities << calc(pos, '7', '5')
    end

    puts possibilities.min
end

gets.to_i.times do
	n = gets.chomp
	if n.to_i % 25 == 0
		puts 0
		next
	end
	res = 1000000000
	for i in 0..n.length - 1 do
		for j in i+1..n.length - 1 do
			if (n[i].to_i * 10 + n[j].to_i) % 25 == 0
				res = [res, j - i - 1 + (n.length - 1 - j)].min
			end
		end
	end
	puts res
end

def f(dgts)
  n0 = dgts.length
  i0 = dgts.rindex("0") || 0
  j0 = i0 > 0 && dgts.rindex(/[05]/, i0 - 1) || -1

  dgts = dgts.gsub(/0+(?!0)/, "")
  n5 = dgts.length
  i5 = dgts.rindex("5") || 0
  j5 = i5 > 0 && dgts.rindex(/[27]/, i5 - 1) || -1

  [n0 - 2 - j0, n5 - 2 - j5].min
end

gets.to_i.times do

n = gets.chomp
puts f(n)

end

def f(dgts)
  n = dgts.length

  i0 = dgts.rindex("0") || 1
  i5 = dgts.rindex("5") || 1

  j0 = dgts.rindex(/[05]/, i0 - 1) || 0
  j5 = dgts.rindex(/[27]/, i5 - 1) || 0

  [n - 2 - j0, n - 2 - j5].min
end

gets.to_i.times do

n = gets.chomp
puts f(n)

end


This is the easy version of the problem. The only difference between the two versions is the constraint on $$$n$$$. You can make hacks only if all versions of the problem are solved.A forest is an undirected graph without cycles (not necessarily connected).Mocha and Diana are friends in Zhijiang, both of them have a forest with nodes numbered from $$$1$$$ to $$$n$$$, and they would like to add edges to their forests such that:   After adding edges, both of their graphs are still forests.  They add the same edges. That is, if an edge $$$(u, v)$$$ is added to Mocha's forest, then an edge $$$(u, v)$$$ is added to Diana's forest, and vice versa. Mocha and Diana want to know the maximum number of edges they can add, and which edges to add.

The first line contains three integers $$$n$$$, $$$m_1$$$ and $$$m_2$$$ ($$$1 \le n \le 1000$$$, $$$0 \le m_1, m_2 < n$$$) — the number of nodes and the number of initial edges in Mocha's forest and Diana's forest. Each of the next $$$m_1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$) — the edges in Mocha's forest. Each of the next $$$m_2$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$) — the edges in Diana's forest.

The first line contains only one integer $$$h$$$, the maximum number of edges Mocha and Diana can add (in each forest). Each of the next $$$h$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$) — the edge you add each time. If there are multiple correct answers, you can print any one of them.

NoteIn the first example, we cannot add any edge.In the second example, the initial forests are as follows.We can add an edge $$$(2, 4)$$$.

END { load __FILE__ unless $stdin.eof? }

module AtCoder
  class DSU
    def initialize(n = 0)
      @n = n
      @parent_or_size = Array.new(n, -1)
    end

    def merge(a, b)
      x, y = leader(a), leader(b)
      return x if x == y

      x, y = y, x if -@parent_or_size[x] < -@parent_or_size[y]
      @parent_or_size[x] += @parent_or_size[y]
      @parent_or_size[y] = x
    end

    def same(a, b)
      leader(a) == leader(b)
    end

    def leader(a)
      return a if @parent_or_size[a] < 0

      @parent_or_size[a] = leader(@parent_or_size[a])
    end

    def size(a)
      -@parent_or_size[leader(a)]
    end

    def groups
      @n.times.group_by { |i| leader(i) }.values
    end
  end
end

n, m1, m2 = gets.split.map!(&:to_i)
e1 = Array.new(m1) { gets.split.map!(&:to_i) }
e2 = Array.new(m2) { gets.split.map!(&:to_i) }

dsu1 = AtCoder::DSU.new(n + 1)
dsu2 = AtCoder::DSU.new(n + 1)

e1.each { |u, v| dsu1.merge(u, v) }
e2.each { |u, v| dsu2.merge(u, v) }

e3 = [*1..n].combination(2).select do |u, v|
  next false if dsu1.same(u, v) || dsu2.same(u, v)

  dsu1.merge(u, v)
  dsu2.merge(u, v)

  true
end

puts e3.size
e3.each { |uv| puts uv * " " }

# Disjoint Set Union
class DSU
  def initialize(n)
    @n = n
    @parent_or_size = Array.new(n, -1)
    # root node: -1 * component size
    # otherwise: parent
  end

  attr_reader :parent_or_size, :n

  def merge(a, b)
    x = leader(a)
    y = leader(b)
    return x if x == y

    x, y = y, x if -@parent_or_size[x] < -@parent_or_size[y]
    @parent_or_size[x] += @parent_or_size[y]
    @parent_or_size[y] = x
  end
  alias unite merge

  def same?(a, b)
    leader(a) == leader(b)
  end
  alias same same?

  def leader(a)
    unless 0 <= a && a < @n
      raise ArgumentError.new, "#{a} is out of range (0...#{@n})"
    end

    @parent_or_size[a] < 0 ? a : (@parent_or_size[a] = leader(@parent_or_size[a]))
  end
  alias root leader
  alias find leader

  def size(a)
    -@parent_or_size[leader(a)]
  end

  def groups
    (0 ... @parent_or_size.size).group_by{ |i| leader(i) }.values
  end
end

UnionFind = DSU

n,m1,m2=gets.split.map(&:to_i)
f1=DSU.new(n)
f2=DSU.new(n)

m1.times do
  u,v=gets.split.map(&:to_i).map{|x|x-1}
  f1.merge(u,v)
end
m2.times do
  u,v=gets.split.map(&:to_i).map{|x|x-1}
  f2.merge(u,v)
end

az=0
ans=[]
n.times do |j|
  j.times do |i|
    if !f1.same?(i,j)&&!f2.same?(i,j)
      f1.merge(i,j)
      f2.merge(i,j)
      ans << [i+1,j+1]
      az+=1
    end
  end
end

puts az
ans.each do |aa|
  puts aa.join(" ")
end


Polycarp has guessed three positive integers $$$a$$$, $$$b$$$ and $$$c$$$. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order — their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: $$$a+b$$$, $$$a+c$$$, $$$b+c$$$ and $$$a+b+c$$$.You have to guess three numbers $$$a$$$, $$$b$$$ and $$$c$$$ using given numbers. Print three guessed integers in any order.Pay attention that some given numbers $$$a$$$, $$$b$$$ and $$$c$$$ can be equal (it is also possible that $$$a=b=c$$$).

The only line of the input contains four positive integers $$$x_1, x_2, x_3, x_4$$$ ($$$2 \le x_i \le 10^9$$$) — numbers written on a board in random order. It is guaranteed that the answer exists for the given number $$$x_1, x_2, x_3, x_4$$$.

Print such positive integers $$$a$$$, $$$b$$$ and $$$c$$$ that four numbers written on a board are values $$$a+b$$$, $$$a+c$$$, $$$b+c$$$ and $$$a+b+c$$$ written in some order. Print $$$a$$$, $$$b$$$ and $$$c$$$ in any order. If there are several answers, you can print any. It is guaranteed that the answer exists.

def read_tokens
  return gets.chomp.to_s.strip.split(' ')
end

def read_ints
  data = []
  read_tokens.each { |s|
    data.push(s.to_i)
  }
  return data
end

arr = read_ints()

def solve(arr)
  maximum = arr.max
  arr.each { |el|
    if el != maximum
      print "#{maximum - el} "
    end
  }
end

solve(arr)

#!usr/bin/env ruby

# https://codeforces.com/problemset/problem/1154/A

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

max = numbers.max
answer = []

numbers.each do |n|
  if (temp = max - n) != 0
    answer << temp
  end
end

puts answer.join(' ')

a,b,c,d=gets.split.map(&:to_i).sort
puts"#{d-a} #{d-b} #{d-c}"

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

n=[a,b,c,d].max
arr=[a,b,c,d]-[n]
puts [n-arr[0],n-arr[1],n-arr[2]].join(' ')

def uwu(inte)
	max = 0
	output = ''
	for number in inte
		max = number.to_i if number.to_i >= max
	end
	inte.delete(max.to_s)
	for number in inte
		resutlat = max - number.to_i
		output << resutlat.to_s
		output << ' '
	end
	output[-1] = '' if output[-1] == ' '
	return output
end

inte = gets.chomp.split(" ")
puts(uwu(inte))

a,b,c,d = gets.split.map(&:to_i).sort
puts "#{d-a} #{d-b} #{d-c}"

# coding: utf-8

# if __FILE__ == $0
# end

inputs = gets.split.map { |i| i.to_i }

# inputs[?] = a + b
# inputs[?] = a + c
# inputs[?] = b + c
# inputs[?] = a + b + c
ans = []
# 모두 양수이므로, 가장 큰 수가 a + b + c
abc = inputs.max
inputs.delete abc
inputs.each { |i| ans.push abc - i }

puts ans.join ' '

arr = gets.split.map(&:to_i)
arr.sort!
arr.reverse!
answer = []
answer << arr[0]-arr[1]
answer << arr[0]-arr[2]
answer << arr[0]-arr[3]
puts answer.join(' ')

$n = gets
$a, $b, $c, $d = $n.split(' ').to_a
arr = [$a.to_i, $b.to_i, $c.to_i, $d.to_i]
$k = arr.max
arr.delete($k)
print $k.to_i-arr[0].to_i,' ',$k.to_i-arr[1].to_i,' ',$k.to_i-arr[2].to_i

require "matrix"
ngo = gets.chomp.split(" ").map(&:to_i).sort
puts Matrix[[1,1,0],[1,0,1],[0,1,1]].lup.solve(ngo.slice(0,3)).to_a.map(&:to_i).join(" ")

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

max = sums[0]
max_idx = 0
sums.each_with_index do |sum, idx|
    if sum > max
        max = sum
        max_idx = idx
    end
end

numbers = []

sums.each_with_index do |sum, idx|
    if idx != max_idx
        n = max - sum
        numbers.push(n)
    end
end

ans = numbers.join(" ")
puts ans

line = gets
n = line.split.map { |x| x.to_i }
sum = n.max
n.delete_at(n.index(sum))
n.map!{|x| sum - x}
puts(n.join ' ')

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

m = a.shift
puts a.map { |x| m-x }.join(' ')

x = gets.split(' ').map(&:to_i).sort
v = []
x.each do |xx|
  v.push(x[3]-xx)
end
puts "#{v[0]} #{v[1]} #{v[2]}"

a,b,c,d=gets.split.map(&:to_i).sort
p"#{d-a} #{d-b} #{d-c}"


In Berland the opposition is going to arrange mass walking on the boulevard. The boulevard consists of n tiles that are lain in a row and are numbered from 1 to n from right to left. The opposition should start walking on the tile number 1 and the finish on the tile number n. During the walk it is allowed to move from right to left between adjacent tiles in a row, and jump over a tile. More formally, if you are standing on the tile number i (i < n - 1), you can reach the tiles number i + 1 or the tile number i + 2 from it (if you stand on the tile number n - 1, you can only reach tile number n). We can assume that all the opposition movements occur instantaneously.In order to thwart an opposition rally, the Berland bloody regime organized the rain. The tiles on the boulevard are of poor quality and they are rapidly destroyed in the rain. We know that the i-th tile is destroyed after ai days of rain (on day ai tile isn't destroyed yet, and on day ai + 1 it is already destroyed). Of course, no one is allowed to walk on the destroyed tiles! So the walk of the opposition is considered thwarted, if either the tile number 1 is broken, or the tile number n is broken, or it is impossible to reach the tile number n from the tile number 1 if we can walk on undestroyed tiles.The opposition wants to gather more supporters for their walk. Therefore, the more time they have to pack, the better. Help the opposition to calculate how much time they still have and tell us for how many days the walk from the tile number 1 to the tile number n will be possible.

The first line contains integer n (1 ≤ n ≤ 103) — the boulevard's length in tiles. The second line contains n space-separated integers ai — the number of days after which the i-th tile gets destroyed (1 ≤ ai ≤ 103).

Print a single number — the sought number of days.

NoteIn the first sample the second tile gets destroyed after day three, and the only path left is 1 → 3 → 4. After day five there is a two-tile gap between the first and the last tile, you can't jump over it.In the second sample path 1 → 3 → 5 is available up to day five, inclusive. On day six the last tile is destroyed and the walk is thwarted.

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

days = 0
loop do
  break if a[0] == 0 or a[-1] == 0

  bang = false
  for i in 1 .. (n - 2) do
    bang = true if a[i] == 0 and a[i + 1] == 0
  end
  break if bang

  days += 1

  a.map!{|e|
    e > 0 ? e -= 1 : e
  }
end

puts days

n = gets.to_i
a = gets.split.map{|e| e.to_i}
min=[a[0],a[n-1]].min
for i in (0..n-2) do
  c = [a[i],a[i+1]].max
  if c<min then min=c end
end
puts min

def check(a)
  a.each_cons(2) do |ar|
    if ar[0] == false && ar[1] == false
      return false
    end
  end
  true
end

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

m = [a.first,a.last].min

(a.min).upto m do |i|
  unless check a.map{|e| e<=i ? false : true}
    p i
    exit
  end
end

p m

n = gets.to_i
arr = gets.split(" ").map(&:to_i)
l = arr.min
r = [arr[0],arr[-1]].min

avail = Array.new(n,true)
ans = nil
finish = false
(l..r).each do |i|
	# puts "i #{i} #{avail}"
	ans = i
	arr.each_with_index do |a,j|
		# puts "a #{a}"
		avail[j] = false if a == i
		if avail[j] == false && avail[j] == avail[j-1] && j > 0
			finish = true
			break
		end
	end
	break if finish
end
puts ans

gets
ns = gets.split.map(&:to_i)
sorted = ns.map.with_index{|n, i| [n, i]}.sort_by(&:first)
hash = {}
answer = ns.first
sorted.each do |n, i|
  hash[i] = true
  if hash[i-1] || hash[i+1] || hash[0] || hash[ns.length - 1]
    answer = n
    break
  end
end

puts answer

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

d = Array.new(v.length,-1)
d[0] = v[0]

0.upto(v.length-2) do |i|
	next if d[i] == -1
	if d[i+1] == -1 or d[i+1] < [d[i],v[i+1]].min
		d[i+1] = [d[i],v[i+1]].min
	end
	if i + 2 < v.length and (d[i+2] == -1 or d[i+2] < [d[i],v[i+2]].min)
		d[i+2] = [d[i],v[i+2]].min
	end
end

puts d[v.length-1]

gets
v = gets.split.collect { |x| x.to_i}

d = Array.new(v.length,-1)
d[0] = v[0]

begin
	ch = false
	0.upto(v.length-2) do |i|
		if d[i] != -1
			if d[i+1] == -1 or d[i+1] < [d[i],v[i+1]].min
				d[i+1] = [d[i],v[i+1]].min
				ch = true
			end
			if i + 2 < v.length and (d[i+2] == -1 or d[i+2] < [d[i],v[i+2]].min)
				d[i+2] = [d[i],v[i+2]].min
				ch = true
			end
		end
	end
end while ch

puts d[v.length-1]

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

a << 0
a << 0

days = 0
loop do
  bang = false
  for i in 0 .. (n - 2) do
    bang = true if ! ((a[i] > 0 and (a[i + 1] > 0 or a[i + 2] > 0)) or (a[i] == 0 and a[i + 1] > 0))
  end

  break if bang

  days += 1

  a.map!{|e|
    e > 0 ? e -= 1 : e
  }
end

puts days

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

days = 0
loop do
  bang = false
  for i in 0 .. (n - 3) do
    bang = true if !((a[i] > 0 and (a[i + 1] > 0 or a[i + 2] > 0)) or (a[i] <= 0 and (a[i + 1] > 0)))
  end

  break if bang

  days += 1

  a.map!{|e| e -= 1}
end

puts days

n = gets.to_i
a = gets.split.map{|e| e.to_i}
min=[a[0],a[n-1]].min
for i in (0..n-2) do
  c = [a[i],a[i+1]].max
  puts c
  if c<min then min=c end
end
puts min

n = gets.to_i
a = gets.split.map{|e| e.to_i}
min=100000
for i in (0..n-2) do
  c = [a[i],a[i+1]].max
  if c<min then min=c end
end
puts min

gets
ns = gets.split.map(&:to_i)
if ns.length == 1
  puts ns[0]
  exit
end
sorted = ns.map.with_index{|n, i| [n, i]}.sort_by(&:first)
hash = {}
answer = 0
sorted.each do |n, i|
  hash[i] = true
  if hash[i-1] || hash[i+1]
    answer = n
    break
  end
end

puts answer

gets
ns = gets.split.map(&:to_i)
sorted = ns.map.with_index{|n, i| [n, i]}.sort_by(&:first)
hash = {}
answer = 0
sorted.each do |n, i|
  hash[i] = true
  if hash[i-1] || hash[i+1]
    answer = n
    break
  end
end

puts answer


New Year is coming, and Jaehyun decided to read many books during 2015, unlike this year. He has n books numbered by integers from 1 to n. The weight of the i-th (1 ≤ i ≤ n) book is wi.As Jaehyun's house is not large enough to have a bookshelf, he keeps the n books by stacking them vertically. When he wants to read a certain book x, he follows the steps described below.  He lifts all the books above book x.  He pushes book x out of the stack.  He puts down the lifted books without changing their order.  After reading book x, he puts book x on the top of the stack.  He decided to read books for m days. In the j-th (1 ≤ j ≤ m) day, he will read the book that is numbered with integer bj (1 ≤ bj ≤ n). To read the book, he has to use the process described in the paragraph above. It is possible that he decides to re-read the same book several times.After making this plan, he realized that the total weight of books he should lift during m days would be too heavy. So, he decided to change the order of the stacked books before the New Year comes, and minimize the total weight. You may assume that books can be stacked in any possible order. Note that book that he is going to read on certain step isn't considered as lifted on that step. Can you help him?

The first line contains two space-separated integers n (2 ≤ n ≤ 500) and m (1 ≤ m ≤ 1000) — the number of books, and the number of days for which Jaehyun would read books. The second line contains n space-separated integers w1, w2, ..., wn (1 ≤ wi ≤ 100) — the weight of each book. The third line contains m space separated integers b1, b2, ..., bm (1 ≤ bj ≤ n) — the order of books that he would read. Note that he can read the same book more than once.

Print the minimum total weight of books he should lift, which can be achieved by rearranging the order of stacked books.

NoteHere's a picture depicting the example. Each vertical column presents the stacked books.

def g;gets.split.map(&:to_i)end
n,m=g
w=g
b=g
#[*1..n].permutation{|st|
#  sum=0
#  b.each{|i|
#    x=st.index(i)
#    st.delete_at(x)
#    sum+=st[x..-1].inject(0){|s,r|s+w[r-1]}
#    st<< i
#  }
#  p sum
#}
st=(1..n).sort_by{|i|-(b.index(i)||m)}
sum=0
b.each{|i|
  x=st.index(i)
  st.delete_at(x)
  sum+=st[x..-1].inject(0){|s,r|s+w[r-1]}
  st<< i
}
p sum

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

score = Array.new(n){ 0 }
ord = Array.new(n){ n }
ret = 0
wini = 0
bs.each do |x|
  if ord[x-1] == n
    ret += wini
    wini += ws[x-1]
  else
    ret += score[x-1]
  end
  n.times do |i|
    if ord[i] < ord[x-1]
      score[i] += ws[x-1]
      ord[i] += 1
    end
  end
  score[x-1] = 0
  ord[x-1] = 0
  #print "(#{ret})"
end
puts ret

# 500C

require 'set'

def read_line
  gets.chomp.split.map &:to_i
end

n, _ = read_line
w = read_line
s = Set.new(1..n)
a = []
b = read_line
b.each { |x|
  if s.include? x
    a << x
    s.delete x
  end
}
a += s.to_a

s = 0
b.each { |v|
  m = a.index v
  s += (0...m).map { |i| w[a[i] - 1] }.inject(&:+) || 0
  a.delete_at m
  a.unshift v
}
puts s

def run
  n, m = $stdin.gets.split.map(&:to_i)
  w = $stdin.gets.split.map(&:to_i)
  b = $stdin.gets.split.map(&:to_i)

  ordered_list = []
  ordered_hash = {}
  b.each_with_index do |book, i|
    if ordered_hash[book] == nil
      ordered_list << book
      ordered_hash[book] = true
    end
  end

  books_by_weight = (1..n).to_a.sort_by { |i| w[i - 1] }
  books_by_weight.each do |book|
    if ordered_hash[book] == nil
      ordered_list << book
    end
  end

  costs = 0
  b.each do |i|
    location = ordered_list.index(i)
    if location > 0
      lift_targets = ordered_list[0..(location - 1)]
      remaining    = ordered_list[(location + 1)..-1]
      costs += lift_targets.reduce(0) {|memo, item| memo + w[item - 1] }
      ordered_list = [ordered_list[location]] + lift_targets + remaining
    end
  end

  puts costs
end

run if $0 == __FILE__

def g;gets.split.map(&:to_i)end
n,_=g
w=g
b=g
#[*1..n].permutation{|st|
#  sum=0
#  b.each{|i|
#    x=st.index(i)
#    st.delete_at(x)
#    sum+=st[x..-1].inject(0){|s,r|s+w[r-1]}
#    st<< i
#  }
#  p sum
#}
st=(1..n).sort_by{|i|-(b.index(i)||n)}
sum=0
b.each{|i|
  x=st.index(i)
  st.delete_at(x)
  sum+=st[x..-1].inject(0){|s,r|s+w[r-1]}
  st<< i
}
p sum


You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.Let instability of the array be the following value: $$$\max\limits_{i = 1}^{n} a_i - \min\limits_{i = 1}^{n} a_i$$$.You have to remove exactly one element from this array to minimize instability of the resulting $$$(n-1)$$$-elements array. Your task is to calculate the minimum possible instability.

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of elements in the array $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$) — elements of the array $$$a$$$.

Print one integer — the minimum possible instability of the array if you have to remove exactly one element from the array $$$a$$$.

NoteIn the first example you can remove $$$7$$$ then instability of the remaining array will be $$$3 - 1 = 2$$$.In the second example you can remove either $$$1$$$ or $$$100000$$$ then instability of the remaining array will be $$$100000 - 100000 = 0$$$ and $$$1 - 1 = 0$$$ correspondingly.

# Input
n = gets.to_i
a = gets.split.map { |s| s.to_i }

# Processing
a.sort!
s_1 = a[-2] - a[0] # Deleted largest element
s_2 = a[-1] - a[1] # Deleted smallest element
result = [s_1, s_2].min

# Output
puts result

def minimize_instability(n, a)
  min1 = min2 = 100_001
  max1 = max2 = 0
  n.times do |i|
    if a[i] < min1
      min2 = min1
      min1 = a[i]
    elsif a[i] < min2
      min2 = a[i]
    end
    if a[i] > max1
      max2 = max1
      max1 = a[i]
    elsif a[i] > max2
      max2 = a[i]
    end
  end

  min = 1_000_000
  n.times do |i|
    u = max1
    u = max2 if u == a[i]
    l = min1
    l = min2 if l == a[i]
    min = [min, u - l].min
  end
  return min
end

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

puts minimize_instability(n, a)

n = gets.to_i
a = gets.split.map &:to_i
a.sort!
puts [a[-1] - a[1], a[-2] - a[0]].min

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

max = 0
maxtwo = 0
min = 1.0/0.0
mintwo = 1.0/0.0

arr.each do |x|
  if x > max
    maxtwo = max
    max = x
  elsif x > maxtwo
    maxtwo = x
  end

  if x < min
    mintwo = min
    min = x
  elsif x <mintwo
    mintwo = x
  end
end

puts [maxtwo-min,max-mintwo].min


There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team.The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team.

The first line contains single integer n (2 ≤ n ≤ 2·105) — the number of groups. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 2), where ai is the number of people in group i.

Print the maximum number of teams of three people the coach can form.

NoteIn the first example the coach can form one team. For example, he can take students from the first, second and fourth groups.In the second example he can't make a single team.In the third example the coach can form three teams. For example, he can do this in the following way:  The first group (of two people) and the seventh group (of one person),  The second group (of two people) and the sixth group (of one person),  The third group (of two people) and the fourth group (of one person).


In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position i + 1) if the type of this bumper is '>', or one position to the left (to i - 1) if the type of the bumper at position i is '<'. If there is no such position, in other words if i - 1 < 1 or i + 1 > n, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position.

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper.

Print one integer — the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position.

NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field.

n = gets.strip.to_i
s = gets.strip
ans = 0
i = 0
while i < n && s[i] == '<'
    ans += 1
    i += 1
end
i = n - 1
while i >= 0 && s[i] == '>'
    ans += 1
    i -= 1
end
puts ans

n = gets.to_i
s = gets.strip

i = 0
while i < n && s[i] == '<'
    i += 1
end

j = 0

while j < n && s[n - j - 1] == '>'
    j += 1
end

puts i + j

gets
s=gets.chop
r=0
s.chars{|c|c==?>&&break;r+=1}
s.reverse.chars{|c|c==?<&&break;r+=1}
p r

#!/usr/bin/ruby

size = gets.to_i
str = gets
right = true
left = true
continue = true
final_number = 0
i=0
while continue do
	if right
		if str[i] == '<'
			final_number += 1
		else
			right = false
		end
	end
	if left
		if str[size - 1 - i] == '>'
			final_number += 1
		else
			left = false
		end
	end
	i+=1
	if !left and !right
		continue = false
	end
end
puts final_number

n = gets.to_i
s = gets.chomp
puts (s.index('>') || n) + (n - 1 - (s.rindex('<') || -1))

n = gets.to_i
a = gets.strip
cnt = 0
i = 0
len = a.length
while(1) do
   break if a[i] == '>' || i == len
   cnt += 1
   i += 1
end

i = len - 1
while(1) do
   break if a[i] == '<' || i == -1
   cnt += 1
   i -=1
end

printf("%d\n", cnt)

length = gets.to_i
bumpers = gets

first_greater = bumpers.index('>')
last_lesser = bumpers.rindex('<')

if first_greater.nil? || last_lesser.nil?
  total_falling_positions = length
else
  total_falling_positions = length - (last_lesser - first_greater + 1)
end

puts total_falling_positions

n = gets.strip.to_i
s = gets.strip
first = s[0]
last = s[n - 1]
ans = 0
if first == '<'
    ans = 1
elsif last == '>'
    ans = n
end
puts ans

n = gets.strip.to_i
s = gets.strip
first = s[0]
last = s[n - 1]
ans = 0
if first == '<'
    ans = 1
elsif last == '>'
    ans = n
else
    if first == '>' && last == '<'
        ans = 0
    end
end
puts ans

n = gets.to_i
s = gets.strip

i = 0
while i < n && s[i] == '<'
    i += 1
end

j = 0

while j < n && s[n - j + 1] == '>'
    i += 1
end

puts i + j

gets
s=gets
r=0
s.chars{|c|c==?>&&break;r+=1}
s.reverse.chars{|c|c==?<&&break;r+=1}
p r


Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.

The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109). Some positions may coincide.

Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.

NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and  for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.

n = gets.chomp.to_i
hx = Hash.new(0)
hy = Hash.new(0)
hxy = Hash.new(0)
n.times do
  x, y = gets.chomp.split.map(&:to_i)
  hx[x] += 1
  hy[y] += 1
  hxy[(x + 10**9) * 10**10 + (y + 10**9)] += 1
end

ans = 0
hx.each do |_, v|
  ans += v * (v - 1) / 2
end
hy.each do |_, v|
  ans += v * (v - 1) / 2
end
hxy.each do |_, v|
  ans -= v * (v - 1) / 2
end

puts ans

#!/usr/bin/ruby
require 'scanf'

x_paintings  = Hash.new(0)
y_paintings  = Hash.new(0)
xy_paintings = Hash.new(0)
watchmen = gets().to_i

pairs = 0
watchmen.times do
  x, y = gets().split(' ').map(&:to_i)
  pairs += x_paintings[x]; x_paintings[x] += 1
  pairs += y_paintings[y]; y_paintings[y] += 1
  pairs -= xy_paintings["#{x},#{y}"]; xy_paintings["#{x},#{y}"] += 1
end

puts pairs

n = gets.to_i
x=[]
y=[]
a=[]
n.times do
	b,c = gets.split.map(&:to_i)
	x << b
	y << c
	a << [b,c]
end

x.sort!
y.sort!
a.sort!
c="a"
cc = 1
ac = 0
n.times do |i|
	cx=x[i]
	if c!=cx
		ac += cc*(cc-1)/2
		c=cx
		cc=1
	else
		cc+=1
	end
end
ac += cc*(cc-1)/2

c="a"
cc = 1
n.times do |i|
	cx=y[i]
	if c!=cx
		ac += cc*(cc-1)/2
		c=cx
		cc=1
	else
		cc+=1
	end
end
ac += cc*(cc-1)/2

c=-1
cc = 1
n.times do |i|
	cx=a[i]
	if c!=cx
		ac -= cc*(cc-1)/2
		c=cx
		cc=1
	else
		cc+=1
	end
end
ac -= cc*(cc-1)/2

puts ac

n = gets.to_i
locations = []
n.times do
  locations << gets.split.map(&:to_i)
end
digit_count_x = {}
digit_count_y = {}
digit_count_xy = {}

count = 0
locations.each do |x, y|
  count += digit_count_x[x] if digit_count_x[x] && digit_count_x[x] > 0
  digit_count_x[x] = digit_count_x[x] ? digit_count_x[x] + 1 : 1
  count += digit_count_y[y] if digit_count_y[y] && digit_count_y[y] > 0
  digit_count_y[y] = digit_count_y[y] ? digit_count_y[y] + 1 : 1
  count -= digit_count_xy[[x, y]] if digit_count_xy[[x, y]] && digit_count_xy[[x, y]] > 0
  digit_count_xy[[x, y]] = digit_count_xy[[x, y]] ? digit_count_xy[[x, y]] + 1 : 1
end
puts count

def cal hash
  hash.values.map{|n| n * (n - 1) / 2}.reduce(0, :+)
end

n = readline.to_i
hx, hy, hxy = Hash.new(0), Hash.new(0), Hash.new(0)
n.times do
  x, y = readline.split(' ').collect(&:to_i)
  hx[x] += 1
  hy[y] += 1
  hxy[[x, y]] += 1
end

puts cal(hx) + cal(hy) - cal(hxy)

n=gets.to_i
a=Hash.new(0)
b=Hash.new(0)
p=Hash.new(0)
for i in 1..n
	buf = gets.split(" ")
	a[buf[0]]+=1
	b[buf[1]]+=1
	p[buf]+=1
end
ans=0
a.each_value{|v| ans+=v*(v-1)/2 }
b.each_value{|v| ans+=v*(v-1)/2 }
p.each_value{|v| ans-=v*(v-1)/2 }
puts ans

#!/usr/bin/ruby
require 'scanf'

x_paintings  = Hash.new(0)
y_paintings  = Hash.new(0)
xy_paintings = Hash.new(0)
watchmen = scanf("%d\n").first.to_i

pairs = 0
watchmen.times do
  x, y = scanf("%d %d").map(&:to_i)
  pairs += x_paintings[x]; x_paintings[x] += 1
  pairs += y_paintings[y]; y_paintings[y] += 1
  pairs -= xy_paintings["#{x},#{y}"]; xy_paintings["#{x},#{y}"] += 1
end

puts pairs

#!/usr/bin/ruby
require 'scanf'

x_paintings  = Hash.new(0)
y_paintings  = Hash.new(0)
xy_paintings = Hash.new(0)
watchmen = scanf("%d").first.to_i

pairs = 0
watchmen.times do
  x, y = scanf("%d %d").map(&:to_i)
  pairs += x_paintings[x]; x_paintings[x] += 1
  pairs += y_paintings[y]; y_paintings[y] += 1
  pairs -= xy_paintings["#{x},#{y}"]; xy_paintings["#{x},#{y}"] += 1
end

puts pairs

n = gets.to_i

locations = gets.split.map(&:to_i)
digit_count_x = {}
digit_count_y = {}
digit_count_xy = {}

count = 0
locations.each do |x, y|
  count += digit_count_x[x] if digit_count_x[x] && digit_count_x[x] > 0
  digit_count_x[x] = digit_count_x[x] ? digit_count_x[x] + 1 : 1
  count += digit_count_y[y] if digit_count_y[y] && digit_count_y[y] > 0
  digit_count_y[y] = digit_count_y[y] ? digit_count_y[y] + 1 : 1
  count -= digit_count_xy[[x, y]] if digit_count_xy[[x, y]] && digit_count_xy[[x, y]] > 0
  digit_count_xy[[x, y]] = digit_count_xy[[x, y]] ? digit_count_xy[[x, y]] + 1 : 1
end
puts count