Galois is one of the strongest chess players of Byteforces. He has even invented a new variant of chess, which he named «PawnChess».This new game is played on a board consisting of 8 rows and 8 columns. At the beginning of every game some black and white pawns are placed on the board. The number of black pawns placed is not necessarily equal to the number of white pawns placed.   Lets enumerate rows and columns with integers from 1 to 8. Rows are numbered from top to bottom, while columns are numbered from left to right. Now we denote as (r, c) the cell located at the row r and at the column c.There are always two players A and B playing the game. Player A plays with white pawns, while player B plays with black ones. The goal of player A is to put any of his pawns to the row 1, while player B tries to put any of his pawns to the row 8. As soon as any of the players completes his goal the game finishes immediately and the succeeded player is declared a winner.Player A moves first and then they alternate turns. On his move player A must choose exactly one white pawn and move it one step upward and player B (at his turn) must choose exactly one black pawn and move it one step down. Any move is possible only if the targeted cell is empty. It's guaranteed that for any scenario of the game there will always be at least one move available for any of the players.Moving upward means that the pawn located in (r, c) will go to the cell (r - 1, c), while moving down means the pawn located in (r, c) will go to the cell (r + 1, c). Again, the corresponding cell must be empty, i.e. not occupied by any other pawn of any color.Given the initial disposition of the board, determine who wins the game if both players play optimally. Note that there will always be a winner due to the restriction that for any game scenario both players will have some moves available.

The input consists of the board description given in eight lines, each line contains eight characters. Character 'B' is used to denote a black pawn, and character 'W' represents a white pawn. Empty cell is marked with '.'.  It's guaranteed that there will not be white pawns on the first row neither black pawns on the last row.

Print 'A' if player A wins the game on the given board, and 'B' if player B will claim the victory. Again, it's guaranteed that there will always be a winner on the given board.

NoteIn the first sample player A is able to complete his goal in 3 steps by always moving a pawn initially located at (4, 5). Player B needs at least 5 steps for any of his pawns to reach the row 8. Hence, player A will be the winner.

Board = Array.new( 8 ) do | i |
	gets.chomp.split( "" )
end
.transpose.freeze;

a = 8; b = 8
Board.each do |row|
	8.times do | i |
		if row[i] != '.'
			if row[i] == 'W'
				a = [ a, i ].min
			end
			break
		end
	end
	7.downto( 0 ) do | i |
		if row[i] != '.'
			if row[i] == 'B'
				b = [ b, 7 - i ].min
			end
			break
		end
	end
end

puts ( a <= b ? "A" : "B" )

matr=[]
8.times{matr<<gets.split("")}
a,b=9,9

8.times do |j|
  tmp=0
  8.times do |i|
    if matr[i][j] == "W"
      tmp=i
      a=[tmp,a].min
      break
    elsif matr[i][j] == "B"
      break
    end
  end
end

8.times do |j|
  tmp=0
   (0..7).to_a.reverse.each do |i|
    if matr[i][j] == "B"
      tmp=7-i
    b=[tmp,b].min
      break
    elsif matr[i][j] == "W"
      break
    end
  end
end

puts a>b ? "B" : "A"

# http://codeforces.com/contest/592/problem/A
# A. PawnChess

cols = [].tap do |arr|
  8.times { arr << gets.chomp.chars }
end
b_idx = []
w_idx = []
cols.transpose.each do |row|
  b = row.rindex('B')
  w = row.rindex('W')
  b_idx << 7 - b if b && (w.nil? || (b > w))

  b = row.index('B')
  w = row.index('W')
  w_idx << w if w && (b.nil? || (b > w))
end

if !b_idx.empty? && (w_idx.empty? || b_idx.min < w_idx.min)
  puts 'B'
else
  puts 'A'
end

#! /usr/bin/env ruby

board = 8.times.collect { $stdin.gets.chomp }

w = 100
b = 100
for c in 0..7
  for r in 0..7
    board[r][c] == 'B' and break
    board[r][c] == 'W' and w = [w, r].min
  end
  for r in (0..7).reverse_each
    board[r][c] == 'W' and break
    board[r][c] == 'B' and b = [b, 7-r].min
  end
end

puts (w <= b ? 'A': 'B')

#!/usr/bin/env ruby

require 'matrix'

rows = 8.times.map do gets.chars.to_a end
MATRIX = Matrix.rows(rows)

def win_in_colA(col_no)
  (0..7).each do |row_no|
    if MATRIX[row_no, col_no] == 'W'
      return row_no
    elsif MATRIX[row_no, col_no] == 'B'
      return 9
    end
  end
  return 9
end

def win_in_colB(col_no)
  (0..7).to_a.reverse.each do |row_no|
    if MATRIX[row_no, col_no] == 'B'
      return 7-row_no
    elsif MATRIX[row_no, col_no] == 'W'
      return 9
    end
  end
  return 9
end

steps_for_A = (0..7).map do |col_n|
  win_in_colA(col_n)
end

steps_for_B = (0..7).map do |col_n|
  win_in_colB(col_n)
end

who_won = (steps_for_B.min < steps_for_A.min) ? 'B' : 'A'
puts who_won

field = []
while line = gets
  field << line.chomp.split("")
end
field = field.transpose
stepA = []
stepB = []
field.each do |r|
  a = r.rindex("W")
  b = r.rindex("B")
  unless b.nil? then
    if a.nil? or (a < b) then
      stepB << 7 - b
    end
  end
  a = r.index("W")
  b = r.index("B")
  unless a.nil? then
    if b.nil? or (a < b) then
      stepA << a
    end
  end
end
if stepB.empty? or (stepA.min <= stepB.min) then
  puts "A"
elsif stepA.empty? or (stepA.min > stepB.min) then
  puts "B"
end

a = Array.new(8)
c = [0] * 8
for x in 0..7
    a[x] = gets
end
flag = 0
for x in 0..7
    for y in 0..7
        if a[x][y] == "W" and c[y] == 0
            w = x;
            flag = 1;
            break;
        end
        if a[x][y] == "B"
            c[y] = 1;
        end
    end
    if flag == 1
        break
    end
end
c = [0] * 8
flag = 0
for x in 0..7
    for y in 0..7
        if a[7 - x][y] == 'B' and c[y] == 0
            b = x;
            flag = 1;
            break;
        end
        if a[7 - x][y] == 'W'
            c[y] = 1;
        end
    end
    if flag == 1
        break;
    end
end
if w > b
    print "B\n"
else
    print "A\n"
end

n, a1, a2, min, c = [], [], [], 99999, ''
(0..7).each do |_|
  n << gets.chomp.split('')
end
(0..7).each do |i|
  arr, a1, a2 = [], [], []
  (0..7).each do |j|
    arr << n[j][i]
  end
  x = Array.new arr
  y = Array.new arr
  x.uniq!.delete('.')
  y.reverse!.uniq!.delete('.')
  a1 = x
  a2 = y
  if a1.size == 0
  	next
  elsif a1.size == 1
  	d = a1.first == 'W' ? arr.index('W') : arr.reverse.index('B')
  	if (d < min) || (d == min && a1.first == 'W')
  		min = d
  		c = a1.first
  	end
  else
		if a1.first == 'W' && arr.index('W') <= min
			min = arr.index('W')
			c = 'W'
		end
		if a2.first == 'B' && arr.reverse.index('B') < min
			min = arr.reverse.index('B')
			c = 'B'
		end
  end
end
puts c == 'W' ? 'A' : 'B'

class Solver
	def main
		f = []
		8.times { f << gets }
		ans_w = 10
		ans_b = 10
		8.times do |i|
			8.times do |j|
				if f[i][j] == "W" then
					flag = true
					tmp = i - 1
					while tmp >= 0 do
						flag = false if f[tmp][j] != '.'
						tmp -= 1
					end
					ans_w = [ans_w, i].min if flag
				elsif f[i][j] == "B" then
					flag = true;
					tmp = i + 1
					while tmp < 8 do
						flag = false if f[tmp][j] != '.'
						tmp += 1
					end
					ans_b = [ans_b, 7 - i].min if flag
				end
			end
		end
		puts ans_w <= ans_b ? "A" : "B"
	end
end

Solver.new.main

# http://codeforces.com/contest/592/problem/A
# A. PawnChess

cols = [].tap do |arr|
  8.times { arr << gets.chomp.chars }
end
rows = cols.transpose.reject do |row|
  row.include?('B') && row.include?('W')
end

b_indexes = rows.map { |row| row.rindex('B') }.compact.map { |idx| 8 - idx }
w_indexes = rows.map { |row| row.index('W') }.compact

if b_indexes.min < w_indexes.min
  puts 'B'
else
  puts 'A'
end

# http://codeforces.com/contest/592/problem/A
# A. PawnChess

cols = [].tap do |arr|
  8.times { arr << gets.chomp.chars }
end
rows = cols.transpose.reject do |row|
  row.include?('B') && row.include?('W')
end

b_indexes = rows.map { |row| row.rindex('B') }.compact.map { |idx| 7 - idx }
w_indexes = rows.map { |row| row.index('W') }.compact

if w_indexes.empty? || b_indexes.min < w_indexes.min
  puts 'B'
else
  puts 'A'
end

# http://codeforces.com/contest/592/problem/A
# A. PawnChess

cols = [].tap do |arr|
  8.times { arr << gets.chomp.chars }
end
b_idx = []
w_idx = []
rows = cols.transpose.reject do |row|
  b = row.rindex('B')
  w = row.rindex('W')
  if b && (w.nil? || (b > w))
    b_idx << 7 - b
  end

  b = row.index('B')
  w = row.index('W')
  if w && (b.nil? || (w > b))
    w_idx << w
  end
end

if !b_idx.empty? && (w_idx.empty? || b_idx.min < w_idx.min)
  puts 'B'
else
  puts 'A'
end

#!/usr/bin/env ruby

require 'matrix'

rows = 8.times.map do gets.chars.to_a end
MATRIX = Matrix.rows(rows)

def win_in_colA(col_no)
  (0..7).each do |row_no|
    if MATRIX[row_no, col_no] == 'W'
      return row_no
    elsif MATRIX[row_no, col_no] == 'B'
      return 9
    end
  end
  return 9
end

def win_in_colB(col_no)
  (0..7).to_a.reverse.each do |row_no|
    if MATRIX[row_no, col_no] == 'B'
      return 7-row_no
    elsif MATRIX[row_no, col_no] == 'W'
      return 9
    end
  end
  return 9
end

steps_for_A = (0..7).map do |col_n|
  win_in_colA(col_n)
end
print steps_for_A
puts

steps_for_B = (0..7).map do |col_n|
  win_in_colB(col_n)
end
print steps_for_B

who_won = (steps_for_B.min < steps_for_A.min) ? 'B' : 'A'
puts who_won

#!/usr/bin/env ruby

require 'matrix'

rows = 8.times.map do gets.chars.to_a end
MATRIX = Matrix.rows(rows)

def win_in_colB(col_no)
  (0..7).each do |row_no|
    if MATRIX[row_no, col_no] == 'B'
      return row_no+1
    elsif MATRIX[row_no, col_no] == 'W'
      return 9
    end
  end
  return 9
end

def win_in_colA(col_no)
  (0..7).to_a.reverse.each do |row_no|
    if MATRIX[row_no, col_no] == 'W'
      return 8-row_no
    elsif MATRIX[row_no, col_no] == 'B'
      return 9
    end
  end
  return 9
end

steps_for_A = (0..7).map do |col_n|
  win_in_colA(col_n)
end

steps_for_B = (0..7).map do |col_n|
  win_in_colB(col_n)
end

who_won = (steps_for_B.min < steps_for_A.min) ? 'B' : 'A'
puts who_won

field = []
while line = gets
  field << line.chomp.split("")
end
field = field.transpose
stepA = []
stepB = []
field.each do |r|
  a = r.rindex("W")
  b = r.rindex("B")
  unless b.nil? then
    if a.nil? or (a < b) then
      stepB << 7 - b
    end
  end
  a = r.index("W")
  b = r.index("B")
  unless a.nil? then
    if b.nil? or (a < b) then
      stepA << 7 - a
    end
  end
end
if stepB.empty? or (stepA.min < stepB.min) then
  puts "A"
elsif stepA.empty? or (stepA.min > stepB.min) then
  puts "B"
end

a = Array.new(8)
for x in 0..7
    a[x] = gets
end
for x in 0..7
    for y in 0..7
        if a[7 - x][y] == 'B'
            print "B\n"
            exit
        end
        if a[7 - x][y] == 'W'
            print "A\n"
            exit
        end
    end
end

n, a1, a2, min, c = [], [], [], 99999, ''
(0..7).each do |_|
  n << gets.chomp.split('')
end
(0..7).each do |i|
  arr, a1, a2 = [], [], []
  (0..7).each do |j|
    arr << n[j][i]
  end
  x = Array.new arr
  y = Array.new arr
  x.uniq!.delete('.')
  y.reverse!.uniq!.delete('.')
  a1 = x
  a2 = y
  if a1.size == 0
  	next
  elsif a1.size == 1
  	d = a1.first == 'W' ? arr.index('W') : arr.reverse.index('B')
  	if d < min || (d == min && c == 'W')
  		min = d
  		c = a1.first
  	end
  else
		if a1.first == 'W' && arr.index('W') <= min
			min = arr.index('W')
			c = 'W'
		end
		if a2.first == 'B' && arr.reverse.index('B') < min
			min = arr.reverse.index('B')
			c = 'B'
		end
  end
end
puts c == 'W' ? 'A' : 'B'

arr, arr1, arr2, index, min, result, c = [], [], [], 1000000, 99999, '', ''
(0..7).each do |_|
  arr << gets.chomp.split('')
end
(0..7).each do |i|
  arr1 = []
  (0..7).each do |j|
    arr1 << arr[j][i]
  end
  arr2 = Array.new arr1
  arr2.uniq!.delete('.')
  if arr2[0] && arr2.size == 1
    c = arr2[0]
    if c == 'W'
      index = arr1.index(c)
    else c == 'B'
      index = arr1.reverse.index(c)
    end
  end
  if index < min
    min = index
    result = c
  end
end
puts result == 'W' ? 'A' : 'B'

arr, arr1, arr2, index, min, result, c = [], [], [], 1000000, 99999, '', ''
(0..7).each do |_|
  arr << gets.chomp.split('')
end
(0..7).each do |i|
  arr1 = []
  (0..7).each do |j|
    arr1 << arr[j][i]
  end
  arr2 = Array.new arr1
  arr2.uniq!.delete('.')
  if arr2[0] && arr2.size == 1
    c = arr2[0]
    if c == 'W'
      index = arr1.index(c)
    else c == 'B'
      index = arr1.reverse.index(c)
    end
  end
  min = index; result = c if index < min
end
p result == 'W' ? 'A' : 'B'

arr, arr1, arr2, index, min, result, c = [], [], [], 1000000, 99999, '', ''
(0..7).each do |_|
  arr << gets.chomp.split('')
end
(0..7).each do |i|
  arr1 = []
  (0..7).each do |j|
    arr1 << arr[j][i]
  end
  arr2 = Array.new arr1
  arr2.uniq!.delete('.')
  if arr2[0] && arr2.size == 1
    c = arr2[0]
    if c == 'W'
      index = arr1.index(c)
    else c == 'B'
      index = arr1.reverse.index(c)
    end
  end
  if index < min
    min = index
    result = c
  end
end
p result == 'W' ? 'A' : 'B'

arr, arr1, arr2, index, min, result, c = [], [], [], 1000000, 99999, '', ''
(0..7).each do |_|
  arr << gets.chomp.split('')
end
(0..7).each do |i|
  arr1 = []
  (0..7).each do |j|
    arr1 << arr[j][i]
  end
  arr2 = Array.new arr1
  arr2.uniq!.delete('.')
  if arr2[0] && arr2.size == 1
    c = arr2[0]
    if c == 'W'
      index = arr1.index(c)
    else c == 'B'
      index = arr1.reverse.index(c)
    end
  end
  if index < min
    min = index
    result = c
  end
end
p result == 'W' ? :A : :B

class Solver
	def main
		map = []
		8.times do
			map << gets.chomp
		end
		move_a = 9
		move_b = 9

		8.times do |i|
			up_most_w = 10
			down_most_b = -1
			8.times do |j|
				up_most_w = [up_most_w, j].min if map[j][i] == "W"
				down_most_b = [down_most_b, j].max if map[j][i] == "B"
			end
			if up_most_w == 10 && down_most_b != -1 then
				move_b = [move_b, 7 - down_most_b].min
			elsif up_most_w != 10 && down_most_b == -1 then
				move_a = [move_a, up_most_w].min
			elsif up_most_w != 10 && down_most_b != -1 then
				if up_most_w < down_most_b then
					move_a = [move_a, up_most_w].min
					move_b = [move_b, 7 - down_most_b].min
				end
			end
		end

		if move_a <= move_b then
			puts "A"
		else
			puts "B"
		end
	end
end

Solver.new.main


Nastya received a gift on New Year — a magic wardrobe. It is magic because in the end of each month the number of dresses in it doubles (i.e. the number of dresses becomes twice as large as it is in the beginning of the month).Unfortunately, right after the doubling the wardrobe eats one of the dresses (if any) with the 50% probability. It happens every month except the last one in the year. Nastya owns x dresses now, so she became interested in the expected number of dresses she will have in one year. Nastya lives in Byteland, so the year lasts for k + 1 months.Nastya is really busy, so she wants you to solve this problem. You are the programmer, after all. Also, you should find the answer modulo 109 + 7, because it is easy to see that it is always integer.

The only line contains two integers x and k (0 ≤ x, k ≤ 1018), where x is the initial number of dresses and k + 1 is the number of months in a year in Byteland.

In the only line print a single integer — the expected number of dresses Nastya will own one year later modulo 109 + 7.

NoteIn the first example a year consists on only one month, so the wardrobe does not eat dresses at all.In the second example after the first month there are 3 dresses with 50% probability and 4 dresses with 50% probability. Thus, in the end of the year there are 6 dresses with 50% probability and 8 dresses with 50% probability. This way the answer for this test is (6 + 8) / 2 = 7.

def power_mod(num, power)
    prod = 1
    num %= MOD
    while power > 0 do
        if power & 1 == 1
            prod = (prod * num) % MOD
        end
        num = (num * num) % MOD
        power >>= 1
    end
    return prod
end

MOD = 10**9+7

X, K = gets.split.map(&:to_i)
if X == 0
    puts 0
    exit
end

low = (X-1) * power_mod(2, K) + 1
high = X * power_mod(2, K)
puts (low + high) % MOD


Iahub is training for the IOI. What is a better way to train than playing a Zuma-like game? There are n balls put in a row. Each ball is colored in one of k colors. Initially the row doesn't contain three or more contiguous balls with the same color. Iahub has a single ball of color x. He can insert his ball at any position in the row (probably, between two other balls). If at any moment there are three or more contiguous balls of the same color in the row, they are destroyed immediately. This rule is applied multiple times, until there are no more sets of 3 or more contiguous balls of the same color. For example, if Iahub has the row of balls [black, black, white, white, black, black] and a white ball, he can insert the ball between two white balls. Thus three white balls are destroyed, and then four black balls become contiguous, so all four balls are destroyed. The row will not contain any ball in the end, so Iahub can destroy all 6 balls.Iahub wants to destroy as many balls as possible. You are given the description of the row of balls, and the color of Iahub's ball. Help Iahub train for the IOI by telling him the maximum number of balls from the row he can destroy.

The first line of input contains three integers: n (1 ≤ n ≤ 100), k (1 ≤ k ≤ 100) and x (1 ≤ x ≤ k). The next line contains n space-separated integers c1, c2, ..., cn (1 ≤ ci ≤ k). Number ci means that the i-th ball in the row has color ci. It is guaranteed that the initial row of balls will never contain three or more contiguous balls of the same color.

Print a single integer — the maximum number of balls Iahub can destroy.

n, k, x = $stdin.gets.chomp.split(' ').map { |v| v.to_i }
a = $stdin.gets.chomp.split(' ').map { |v| v.to_i }

class Solver
  def initialize(n, k, x, a)
    @n = n
    @k = k
    @x = x
    @a = a
  end

  def cnt(l, r)
    ans = 0
    flag = false
    while true do
      sum = 0
      while l>-1 && @a[l] == @a[r]
        l -= 1
        sum += 1
      end
      l += 1
      while r < @n && @a[l] == @a[r]
        r += 1
        sum += 1
      end
      r -= 1
      return ans if flag && sum < 3
      flag = 1
      ans = [ans, r - l + 1].max
      l -= 1
      r += 1
      return ans if l <0 || r >= @n || @a[l] != @a[r]
    end
  end
end

solver = Solver.new(n, k, x, a)
ans = 0
for i in 0..n-1
  ans = [ans, solver.cnt(i, i+1)].max if a[i] == a[i+1] && a[i] == x
end

puts ans

# Created by Alex
n, k, x = gets.split.map {|i| i.to_i}
a = gets.split.map {|i| i.to_i}
max = 0
maxi = -1
for i in 0...n - 1
  #print a[i].to_s + ' '
  if a[i] != x || a[i + 1] != x
    next
  end
  l = i - 1
  r = i + 2
  cnt = 3
  while l >= 0 && r < n && a[l] == a[r]
    p1 = l
    while p1 > 0 && a[p1 - 1] == a[r]
      p1 -= 1
    end
    p2 = r
    while p2 < n - 1 && a[p2 + 1] == a[l]
      p2 += 1
    end
    if l - p1 + p2 - r + 2 < 3
      break
    end
    cnt += l - p1 + p2 - r + 2
    l = p1 - 1
    r = p2 + 1
  end
  if cnt >= max
    #print ' (' + cnt.to_s + ' ' + p1.to_s + ' ' + p2.to_s + ') '
    max = cnt
    maxi = i
  end
end
if max < 3
  max = 1
end
puts max - 1

myArray = $stdin.readlines

input=[]

myArray.each do |l|
  input.push(l)
end

a = input[0].split(',').map{|x| x.to_i}

#insert your code within this function
def solution(a)
  a2 = a.sort
  n = a2.size
  index_swap = 0
  for i in 0..n-1
    index_swap +=1 if a[i] != a2[i]
  end
  return index_swap <= 2
end

puts solution(a)

# Created by Alex
n, k, x = gets.split.map {|i| i.to_i}
a = gets.split.map {|i| i.to_i}
max = 0
for i in 0...n - 1
  if a[i] != x || a[i + 1] != x
    next
  end
  l = i - 1
  r = i + 2
  cnt = 3
  while l >= 0 && r < n
    p1 = l
    while p1 > 0 && a[p1 - 1] == a[r]
      p1 -= 1
    end
    p2 = r
    while p2 < n - 1 && a[p2 + 1] == a[l]
      p2 += 1
    end
    if l - p1 + p2 - r + 2 < 3
      break
    end
    cnt += l - p1 + p2 - r + 2
    l = p1 - 1
    r = p2 + 1
  end
  if cnt > max
    max = cnt
  end
end
if max < 3
  max = 1
end
puts max - 1

# Created by Alex
n, k, x = gets.split.map {|i| i.to_i}
a = gets.split.map {|i| i.to_i}
max = 0
for i in 0...n - 2
  if a[i + 1] != x || a[i + 2] != x
    next
  end
  l = i - 1
  r = i + 2
  cnt = 3
  while l >= 0 && r < n
    p1 = l
    while p1 > 0 && a[p1 - 1] == a[r]
      p1 -= 1
    end
    p2 = r
    while p2 < n - 1 && a[p2 + 1] == a[l]
      p2 += 1
    end
    if l - p1 + p2 - r + 2 < 3
      break
    end
    cnt += l - p1 + p2 - r + 2
    l = p1 - 1
    r = p2 + 1
  end
  if cnt > max
    max = cnt
  end
end
if max < 3
  max = 1
end
puts max - 1

# Created by Alex
n, k, x = gets.split.map {|i| i.to_i}
a = gets.split.map {|i| i.to_i}
max = 0
for i in 0...n - 1
  if a[i] != x && a[i + 1] != x
    next
  end
  l = i
  r = i
  if a[i] == x && a[i + 1] == x
    l = i - 1
    r = i + 2
  end
  if a[i] == x && i > 0 && a[i - 1] == x
    l = i - 2
    r = i + 1
  end
  if a[i + 1] == x && i + 2 < n && a[i + 2] == x
    l = i
    r = i + 3
  end
  if l == i && r == i
    next
  end
  cnt = 3
  while l >= 0 && r < n
    p1 = l
    while p1 > 0 && a[p1 - 1] == a[r]
      p1 -= 1
    end
    p2 = r
    while p2 < n - 1 && a[p2 + 1] == a[l]
      p2 += 1
    end
    if l - p1 + p2 - r + 2 < 3
      break
    end
    cnt += l - p1 + p2 - r + 2
    l = p1 - 1
    r = p2 + 1
  end
  if cnt > max
    max = cnt
  end
end
if max < 3
  max = 1
end
puts max - 1


Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divides into four triangle plants: three of them will be directed in the same direction as the parent plant, and one of them will be directed in the opposite direction. Then each year the process repeats. The figure below illustrates this process.  Help the dwarfs find out how many triangle plants that point "upwards" will be in n years.

The first line contains a single integer n (0 ≤ n ≤ 1018) — the number of full years when the plant grew. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.

Print a single integer — the remainder of dividing the number of plants that will point "upwards" in n years by 1000000007 (109 + 7).

NoteThe first test sample corresponds to the second triangle on the figure in the statement. The second test sample corresponds to the third one.

LIMIT = 1000000007

@res = []
l = 1
while l < LIMIT
  @res << l
  l = l * 2
end

def power i
  return @res[i] if i < @res.size
  half_power = power(i/2)
  partial = (half_power * half_power) % LIMIT
  if i % 2 == 1
    partial = (partial * 2) % LIMIT
  end
  partial
end

years = gets.to_i

if years == 0
  puts 1
else
  partial = power(years-1)
  puts (partial * (((2 * partial) % LIMIT) + 1)) % LIMIT
end

# 2^(n-1) * (2^n +1)

def pow(a,k)
  n = 1000000007
  b = 1
  while (k!= 0) do
    if (k % 2 == 0 ) then
      k/=2
      a = (a*a) % n
    else
      k-=1
      b = (b*a) % n
    end
  end
  return b
end

n = gets.to_i
k = pow(2,n)
k = (k*(k-1)/2) % 1000000007
if (n == 0) then
  puts "1"
else
  ans = (pow(4,n) - k) % 1000000007
  puts ans
end

$p = 1000000007
def mul(a,b)
  n = a.size
  c = Array.new(n){Array.new(n){0}}
  n.times do |i|
    n.times do|j|
      n.times do |k|
        c[i][j] += a[i][k] * b[k][j]
        c[i][j] %= $p
      end
    end
  end
  c
end

def po(m)
  e = [[3,1],[1,3]]
  ret = [[1,0],[0,1]]

  while m > 0
    if m % 2 == 1
      ret = mul(ret,e)
    end
    e = mul(e,e)
    m /= 2
  end

  ret
end

def work(n)
    if n == 1
      puts 3
    else
      ret = po(n)
      ans = ret[0][0]
      puts ans % $p
    end
end

n = gets.to_i
work n
#10.times{|x| work x+1}

def pow(a,k)
  n = 1000000007
  b = 1
  while (k!= 0) do
    if (k % 2 == 0 ) then
      k/=2
      a = (a*a) % n
    else
      k-=1
      b = (b*a) % n
    end
  end
  return b
end

n = gets.to_i
if (n == 0) then
  puts "1"
else
  ans = pow(4,n)/2 + pow(2,n-1)
  puts ans
end

def pow(a,k)
  n = 1000000007
  b = 1
  while (k!= 0) do
    if (k % 2 == 0 ) then
      k/=2
      a = (a*a) % n
    else
      k-=1
      b = (b*a) % n
    end
  end
  return b
end

n = gets.to_i
if (n == 0) then
  puts "1"
else
  ans = (pow(4,n)/2 + pow(2,n-1)) % 1000000007
  puts ans
end


Ari the monster always wakes up very early with the first ray of the sun and the first thing she does is feeding her squirrel.Ari draws a regular convex polygon on the floor and numbers it's vertices 1, 2, ..., n in clockwise order. Then starting from the vertex 1 she draws a ray in the direction of each other vertex. The ray stops when it reaches a vertex or intersects with another ray drawn before. Ari repeats this process for vertex 2, 3, ..., n (in this particular order). And then she puts a walnut in each region inside the polygon.  Ada the squirrel wants to collect all the walnuts, but she is not allowed to step on the lines drawn by Ari. That means Ada have to perform a small jump if she wants to go from one region to another. Ada can jump from one region P to another region Q if and only if P and Q share a side or a corner.Assuming that Ada starts from outside of the picture, what is the minimum number of jumps she has to perform in order to collect all the walnuts?

The first and only line of the input contains a single integer n (3 ≤ n ≤ 54321) - the number of vertices of the regular polygon drawn by Ari.

Print the minimum number of jumps Ada should make to collect all the walnuts. Note, that she doesn't need to leave the polygon after.

NoteOne of the possible solutions for the first sample is shown on the picture above.

#! /usr/bin/env ruby

n = $stdin.gets.to_i
puts (n-2)**2

n=gets.chomp.to_i
n=(n-1)*(n-3)+1
puts n.inspect

#!/usr/bin/env ruby

N = gets.to_i

def total_sections
  return 1 if N == 3
  return 4 if N == 4

  sections_without_2_triangles = (3..N-2).map do |second_vertice|
    third_vertice = second_vertice + 1

    lines_from_second = N - second_vertice - 1
    lines_from_third = third_vertice - 3

    lines_from_second + lines_from_third + 1
  end.inject(:+)

  sections_without_2_triangles + (N-2)*2
end

puts total_sections

angles = gets.to_i
puts (angles - 2) * (angles - 2)

n = gets.chomp.to_i
puts n ** 2 - 4 * n + 4

class Solver
	def main
		n = gets.to_i
		puts (n - 2) ** 2
	end
end

Solver.new.main

n = gets.to_i
puts n * (n - 3) - (n - 4)

n = gets.chomp.to_i
if n == 3 then
  puts 1
else
  a1 = 1
  4.upto(n).each do |a|
    a1 += 3 + 2*(a-4)
  end
  puts a1
end


You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy.Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D environment. The dungeon can be represented as a rectangle matrix of n rows and m columns. Cell (x, y) is the cell in the x-th row in the y-th column. Lara can move between the neighbouring by side cells in all four directions.Moreover, she has even chosen the path for herself to avoid all the traps. She enters the dungeon in cell (1, 1), that is top left corner of the matrix. Then she goes down all the way to cell (n, 1) — the bottom left corner. Then she starts moving in the snake fashion — all the way to the right, one cell up, then to the left to the cell in 2-nd column, one cell up. She moves until she runs out of non-visited cells. n and m given are such that she always end up in cell (1, 2).Lara has already moved to a neighbouring cell k times. Can you determine her current position?

The only line contains three integers n, m and k (2 ≤ n, m ≤ 109, n is always even, 0 ≤ k < n·m). Note that k doesn't fit into 32-bit integer type!

Print the cell (the row and the column where the cell is situated) where Lara ends up after she moves k times.

mas = gets.split(" ")
n, m, k = mas[0].to_i, mas[1].to_i, mas[2].to_i
per, ch = k-n-m+2, 2*(m-1)
if k < (n+m-1)
	finvar = k < n ? [k+1, 1] : [n, k-n+2]
else
	is = per % (m-1) == 0 ? (n-per/(m-1)) : (n-per/(m-1)-1)
	prom = per % ch == 0 ? ch : (per % ch)
	finvar = prom <= (m-1) ? [is, m-prom+1] : [is, 1+prom-(m-1)]
end
puts finvar[0], finvar[1]

mas = gets.split(" ")
n, m, k = mas[0].to_i, mas[1].to_i, mas[2].to_i
per, ch = k-n-m+2, 2*(m-1)
if k < (n+m-1)
	finvar = k < n ? [k+1, 1] : [n, k-n+2]
else
	is = per % (m-1) == 0 ? (n-per/(m-1)) : (n-per/(m-1)-1)
	prom = per % ch
	if prom == 0
		prom = ch
	end
	finvar = prom <= (m-1) ? [is, m-prom+1] : [is, 1+prom-(m-1)]
end
puts finvar[0], finvar[1]

mas = gets.split(" ")
n, m, k = mas[0].to_i, mas[1].to_i, mas[2].to_i
per, ch = k-n-m+2, 2*(m-1)
if k < (n+m-1)
	finvar = k < n ? [k+1, 1] : [n, k-n+2]
else
	if per % (m-1) == 0
		is = n - per/(m-1)
	else
		is = n - per/(m-1) - 1
	end
	prom = per % ch
	if prom == 0
		prom = ch
	end
	finvar = prom <= (m-1) ? [is, m-prom+1] : [is, 1+prom-(m-1)]
end
puts finvar[0], finvar[1]

n, m, k = gets.split.map(&:to_i)
if k < n
    puts "#{k + 1} 1"
else
    hoge = (m - 1) * 2
    k -= n
    r = n - k / hoge * 2
    tmp = k % hoge
    c = 0
    if tmp < m - 1
        c = tmp + 2
    else
        c = 2 * (m - 1) - tmp + 1
        r -= 1
    end
    puts "#{r} #{c}"
end

mas = gets.split(" ")
n, m, k = mas[0].to_i, mas[1].to_i, mas[2].to_i
if k < (n+m - 1)
	finvar = k < n ? [k+1, 1] : [n, k-n+2]
else
	is = n - (Float(k-(n+m-2))/(m-1)).ceil
	ncheck = n % 2
	ischeck = is % 2
	if (ncheck ^ ischeck) == 0
		finvar = [is, 2 + ((k - (n+m-2)) % (m))]
	else
		if (per = ((k - (n+m-2)) % (m-1))) == 0
			finvar = [is, 2]
		else
			finvar = [is, m + 1 - per]
		end
	end
end
puts finvar[0], finvar[1]

mas = gets.split(" ")
n, m, k = mas[0].to_i, mas[1].to_i, mas[2].to_i
if k < (n+m - 1)
	finvar = k < n ? [k+1, 1] : [n, k-n+2]
else
	is = n - (Float(k-(n+m-2))/(m-1)).ceil
	finvar = [is, 2 + ((k - (n+m-2)) % (m-1))]
end
puts finvar[0], finvar[1]

mas = gets.split(" ")
n, m, k = mas[0].to_i, mas[1].to_i, mas[2].to_i
if k < (n+m - 1)
	finvar = k < n ? [k+1, 1] : [n, k-n+2]
else
	is = n - (Float(k-(n+m-2))/(m-1)).ceil
	prom = (k-n-m+2) % (2*(m-1))
	if prom == 0
		prom = 2*(m-1)
	end
	finvar = prom <= (m-1) ? [is, m-prom+1] : [is, 1+prom-(m-1)]
end
puts finvar[0], finvar[1]

mas = gets.split(" ")
n, m, k = mas[0].to_i, mas[1].to_i, mas[2].to_i
per, ch = k-n-m+2, 2*(m-1)
if k < (n+m-1)
	finvar = k < n ? [k+1, 1] : [n, k-n+2]
else
	if per % (m-1) == 0
		is = n - per/(m-1)
	else
		is = n - (Float(per)/(m-1)).floor - 1
	end
	prom = per % ch
	if prom == 0
		prom = ch
	end
	finvar = prom <= (m-1) ? [is, m-prom+1] : [is, 1+prom-(m-1)]
end
puts finvar[0], finvar[1]

mas = gets.split(" ")
n, m, k = mas[0].to_i, mas[1].to_i, mas[2].to_i
if k < (n+m - 1)
	finvar = k < n ? [k+1, 1] : [n, k-n+2]
else
	is = n - (Float(k-(n+m-2))/(m-1)).ceil
	ncheck = n % 2
	ischeck = is % 2
	if (ncheck ^ ischeck) == 0
		finvar = [is, 2 + ((k - (n+m-2)) % (m-1))]
	else
		if (per = ((k - (n+m-2)) % (m-1))) == 0
			finvar = [is, 2]
		else
			finvar = [is, m + 1 - per]
		end
	end
end
puts finvar[0], finvar[1]


Welcome to Codeforces Stock Exchange! We're pretty limited now as we currently allow trading on one stock, Codeforces Ltd. We hope you'll still be able to make profit from the market!In the morning, there are $$$n$$$ opportunities to buy shares. The $$$i$$$-th of them allows to buy as many shares as you want, each at the price of $$$s_i$$$ bourles.In the evening, there are $$$m$$$ opportunities to sell shares. The $$$i$$$-th of them allows to sell as many shares as you want, each at the price of $$$b_i$$$ bourles. You can't sell more shares than you have.It's morning now and you possess $$$r$$$ bourles and no shares.What is the maximum number of bourles you can hold after the evening?

The first line of the input contains three integers $$$n, m, r$$$ ($$$1 \leq n \leq 30$$$, $$$1 \leq m \leq 30$$$, $$$1 \leq r \leq 1000$$$) — the number of ways to buy the shares on the market, the number of ways to sell the shares on the market, and the number of bourles you hold now. The next line contains $$$n$$$ integers $$$s_1, s_2, \dots, s_n$$$ ($$$1 \leq s_i \leq 1000$$$); $$$s_i$$$ indicates the opportunity to buy shares at the price of $$$s_i$$$ bourles. The following line contains $$$m$$$ integers $$$b_1, b_2, \dots, b_m$$$ ($$$1 \leq b_i \leq 1000$$$); $$$b_i$$$ indicates the opportunity to sell shares at the price of $$$b_i$$$ bourles.

Output a single integer — the maximum number of bourles you can hold after the evening.

NoteIn the first example test, you have $$$11$$$ bourles in the morning. It's optimal to buy $$$5$$$ shares of a stock at the price of $$$2$$$ bourles in the morning, and then to sell all of them at the price of $$$5$$$ bourles in the evening. It's easy to verify that you'll have $$$26$$$ bourles after the evening.In the second example test, it's optimal not to take any action.

n,m,r = gets.split.map(&:to_i)
a = gets.split.map(&:to_i).min
b = gets.split.map(&:to_i).max
p a < b ? (r/a)*b + r % a : r

N, M, R = gets.split.map(&:to_i)
S = gets.split.map(&:to_i)
B = gets.split.map(&:to_i)

s = S.min
cnt = R / s
b = B.max
diff = b - s

money = R + diff * cnt
puts [money, R].max

n,m,r = gets.split.map(&:to_i)
s = gets.split.map(&:to_i).min
b = gets.split.map(&:to_i).max
if s > b
    puts r
else
    puts r%s+(r/s)*b
end

n, m, r = gets.chomp.split.map(&:to_i)
buy = gets.chomp.split.map(&:to_i).min
sell = gets.chomp.split.map(&:to_i).max

if sell > buy
  shares = r / buy
  profit = shares * (sell - buy)
  r += profit
end

puts r


I have an undirected graph consisting of n nodes, numbered 1 through n. Each node has at most two incident edges. For each pair of nodes, there is at most an edge connecting them. No edge connects a node to itself.I would like to create a new graph in such a way that:   The new graph consists of the same number of nodes and edges as the old graph.  The properties in the first paragraph still hold.  For each two nodes u and v, if there is an edge connecting them in the old graph, there is no edge connecting them in the new graph. Help me construct the new graph, or tell me if it is impossible.

The first line consists of two space-separated integers: n and m (1 ≤ m ≤ n ≤ 105), denoting the number of nodes and edges, respectively. Then m lines follow. Each of the m lines consists of two space-separated integers u and v (1 ≤ u, v ≤ n; u ≠ v), denoting an edge between nodes u and v.

If it is not possible to construct a new graph with the mentioned properties, output a single line consisting of -1. Otherwise, output exactly m lines. Each line should contain a description of edge in the same way as used in the input format.

NoteThe old graph of the first example:A possible new graph for the first example:In the second example, we cannot create any new graph.The old graph of the third example:A possible new graph for the third example:

n,m=gets.split.map(&:to_i)
h={}
m.times do
  a,b=gets.split.map(&:to_i)
  h[[a,b]]=h[[b,a]]=1
end
a=(1..n).to_a
s=Time.now
while Time.now-s < 2.8
  b=a.shuffle
  f=true
  m.times do |i|
    if !h[[b[i],b[(i+1)%n]]].nil?
      f=false
      break
    end
  end
  if f
    m.times do |i|
      puts "#{b[i]} #{b[(i+1)%n]}"
    end
    exit
  end
end
p -1

n,m=gets.split.map(&:to_i)
h={}
m.times do
  a,b=gets.split.map(&:to_i)
  h[[a,b]]=h[[b,a]]=1
end
a=(1..n).to_a
s=Time.now
while Time.now-s < 2.8
  b=a.shuffle
  f=true
  for i in 0...n
    if !h[[b[i],b[(i+1)%n]]].nil?
      f=false
      break
    end
  end
  if f
    m.times do |i|
      puts "#{b[i]} #{b[(i+1)%n]}"
    end
    exit
  end
end
p -1


Vanya got an important task — he should enumerate books in the library and label each book with its number. Each of the n books should be assigned with a number from 1 to n. Naturally, distinct books should be assigned distinct numbers.Vanya wants to know how many digits he will have to write down as he labels the books.

The first line contains integer n (1 ≤ n ≤ 109) — the number of books in the library.

Print the number of digits needed to number all the books.

NoteNote to the first test. The books get numbers 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, which totals to 17 digits.Note to the second sample. The books get numbers 1, 2, 3, 4, which totals to 4 digits.

# coding: utf-8

# 총 기록해야하는 숫자의 개수를 의미를 가리킵니다.
# n = 13의 경우
# n[1..9]: 1, 2, 3, 4, 5, 6, 7, 8, 9 -> 9글자
# n[10..13]: 10, 11, 12, 13 -> 8글자
# 총 합쳐서 17글자가 필요합니다.

n = gets.to_i
t = 0
for i in 1..10
    s, e = 10**(i-1), (10**i) - 1
    #p [s,e]
    if e < n
        t += (e - s + 1) * i # 10 ~ 99 -> 총 몇개의 숫자가 존재할까, 89개가 아니라 90개
    else
        if s <= n
            t += (n - s + 1) * i
        else
            break
        end
    end
end

puts t

n = gets.chomp
ans = 0
num = 9
(1...n.size).each do |i|
    ans += i*num
    num *= 10
end
ans += n.size*(n.to_i-10**(n.size-1)+1)
puts ans

n = gets.to_i
ans = 0
n.to_s.chars.size.times do |i|
  a = [9 * (10 ** i), n].min
  n -= a
  ans += a * (i + 1)
end
p ans

#!/usr/bin/env ruby

num = ARGF.gets.chomp
length = num.length
count = 0
if length > 1
    num = (num.to_i - ('9' * (length - 1)).to_i).to_s
end

count += (num.to_i) * length

length -= 1
while (length > 0) do
    count += (9 * 10**(length - 1)) * length
    length -= 1
end

puts count

n = gets.to_i
d = n.to_s.length

ans = n * d
1.upto(d - 1) do |i|
	ans -= (d - i) * 9 * 10 ** (i - 1)
end
puts ans

# cook your code here

a = gets.to_i
b = 0
ans = 0

until a < b
    ans = ans + a - b;
    b = 10*b + 9
end

puts ans

def f(n)
    result, total, k = 0, 10, 1

    while n >= total do
       result += k * (total - total / 10)
       k += 1
       total *= 10
    end

    result + (n - total / 10 + 1) * k
end

puts f(gets.to_i)

n = gets.chomp

digit_count = n.length
n = n.to_i

result = (n - (10 ** (digit_count - 1) - 1)) * digit_count

result += (1..(digit_count - 1)).inject(0) do |sum, count|
	sum + (9 * 10 ** (count - 1)) * count
end

puts result

n = gets.to_i
ans = 0
len = 1
base = 10
while true
    if n < base then
        ans += (n - base / 10 + 1) * len
        break
    else
        ans += base / 10 * 9 * len
    end
    len += 1
    base *= 10
end
puts ans

# http://codeforces.com/contest/552/problem/B
n = gets.chomp.to_i
sum = 0

(0...n.to_s.chars.length).each do |idx|
  d = [9 * (10 ** idx), n].min
  n -= d
  sum += d * (idx + 1)
end

puts sum

#!/usr/bin/ruby
# Made With LOVE <3

n = gets.to_i
i=1
s=0
while i<=n
s = s + n - (i-1)
i*=10
end

puts s

number = gets.chomp.to_i
result = 0
maxDigit = 10
divisor = 1000000000

until number / divisor != 0
	maxDigit -= 1
	divisor /= 10
end

nowDigit = 1

until nowDigit == maxDigit
	result += (9 * (10**(nowDigit - 1))) * nowDigit

	nowDigit += 1
end

result += ((number - (10**(maxDigit - 1))) + 1) * maxDigit

puts result

a=gets.chomp
l=a.length-1
if l==0
puts a
else
ans=9
2.upto l do |i|
ans+= (9*(10**(i-1)))*i
end
ans+=(a.to_i-("9"*l).to_i)*(l+1)
puts ans.inspect
end

a=gets.to_i
r=9
ans=0
while a>0
	ans+=a
	a-=r
	r*=10
end

puts ans

n = gets.to_i
s = 1
ans = 0
while s.to_s.length < n.to_s.length
  ans += s * 9 * s.to_s.length
  s *= 10
end
ans += (n - s + 1) * n.to_s.length
p ans

#!/usr/bin/env ruby

num = ARGF.gets.chomp
length = num.length
count = 0
if length > 1
    num = num[1..-1]
end
count += (num.to_i + 1) * length
if length == 1
    count -= 1
end

length -= 1
while (length > 0) do
    count += (9 * 10**(length - 1)) * length
    length -= 1
end

puts count

n = gets.chomp

digit_count = n.length
n = n.to_i

result = (n - (10 ** (digit_count - 1) - 1)) * digit_count

result += (1..(digit_count - 1)).inject(0) do |sum, count|
	sum + ('9' * count).to_i * count
end

result

n = gets.chomp

digit_count = n.length
n = n.to_i

result = (n - (10 ** (digit_count - 1) - 1)) * digit_count

result += (1..(digit_count - 1)).inject(0) do |sum, count|
	sum + ('9' * count).to_i * count
end

puts result

#!/usr/bin/ruby
# Made With LOVE <3

n = gets.to_i
i=1
s=0
while i<n
s += n - (i-1)
i*=10
end

puts s

# coding: utf-8

# 총 기록해야하는 숫자의 개수를 의미를 가리킵니다.
# n = 13의 경우
# n[1..9]: 1, 2, 3, 4, 5, 6, 7, 8, 9 -> 9글자
# n[10..13]: 10, 11, 12, 13 -> 8글자
# 총 합쳐서 17글자가 필요합니다.

n = gets.to_i
t = 0
for i in 1..10
    s, e = 10**(i-1), (10**i) - 1
    #p [s,e]
    if e < n
        t += (e - s + 1) * i # 10 ~ 99 -> 총 몇개의 숫자가 존재할까, 89개가 아니라 90개
    else
        if s < n
            t += (n - s + 1) * i
        else
            break
        end
    end
end

puts t


You are a lover of bacteria. You want to raise some bacteria in a box. Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment. What is the minimum number of bacteria you need to put into the box across those days?

The only line containing one integer x (1 ≤ x ≤ 109).

The only line containing one integer: the answer.

NoteFor the first sample, we can add one bacterium in the box in the first day morning and at the third morning there will be 4 bacteria in the box. Now we put one more resulting 5 in the box. We added 2 bacteria in the process so the answer is 2.For the second sample, we can put one in the first morning and in the 4-th morning there will be 8 in the box. So the answer is 1.

#!/usr/bin/ruby

n = gets.to_i
ans = 0
while n > 0
  # p  "n=#{n}, ans=#{ans}"
  ans+=1 if n % 2 == 1
  n/=2
end

puts ans

p sprintf("%b", gets.chomp).gsub('0', '').length

#! /usr/bin/env ruby

x = gets.to_i
puts x.to_s(2).count('1')

a = gets.to_i
sum = 0
(0..48).each {|n| sum += a[n]}
puts sum

n = gets.chomp.to_i

c = 0

while n > 1

  if n % 2 == 0
    n /= 2
  else
    c += 1
    n -= 1
  end
end

puts c + 1

x = gets.to_i
ans = 0
while x>0
  x=x&(x-1)
  ans += 1
end
print ans

a=gets.chomp.to_i
ans=0
loop do
if a%2==1
    ans+=1
end
a=a/2
break if a==0
end
puts "#{ans}"

n=gets.to_i.to_s(2)
p n.chars.count{|e|
	e=="1"
}

n = gets.to_i
r = 0
while n > 0
	if n % 2 > 0
		r += 1
	end
	n = n / 2
end
p r

#$stdin = File.open('in.txt')
#$stdout = File.open('out.txt', 'w')

n = gets.to_i

ans = 0
while (n > 0) do
  ans += 1 if n % 2 == 1
  n /= 2
end

p ans

x = gets.chomp.to_i

rtn = 0
while 0 < x
  rtn += x % 2
  x /= 2
end
puts rtn

num = gets.chomp.to_i
count = 0
until num == 0
  count += num%2
  num = num/2
end
p count

a = gets.to_i
ans = 0
c = 2**30
while c > 0
  ans += a / c
  a %= c
  c /= 2
end
puts ans

user_input = gets.chomp
user_input = user_input.to_i
count = 0
while user_input != 0
  count += user_input & 1
  user_input = user_input >> 1
end
print count

class Solver
	def main
		n = gets.to_i
		ans = (0..30).to_a.count { |i| n[i] == 1 }
		puts ans
	end
end

Solver.new.main

#!/usr/bin/ruby

n = gets.to_i
x = 1
while x*2 <= n
  x*=2
end

puts 1 + n - x

a = gets.to_i
puts a.odd? && a != 1 ? 2 : 1


Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the following sequence of numbers: firstly all odd integers from 1 to n (in ascending order), then all even integers from 1 to n (also in ascending order). Help our hero to find out which number will stand at the position number k.

The only line of input contains integers n and k (1 ≤ k ≤ n ≤ 1012). Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

Print the number that will stand at the position number k after Volodya's manipulations.

NoteIn the first sample Volodya's sequence will look like this: {1, 3, 5, 7, 9, 2, 4, 6, 8, 10}. The third place in the sequence is therefore occupied by the number 5.

#!/usr/bin/env ruby
n, k = gets.split(' ').map(&:to_i)
odd = (n + 1) / 2
even = n / 2
if k <= odd
  puts k * 2 - 1
else
  puts (k - odd) * 2
end

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

  if k <= ((n + 1)/ 2)
    puts (k * 2 - 1)
  else
    puts ((k - ((n + 1)/ 2)) * 2)
  end
end

run if $0 == __FILE__

n, k = gets.chomp.split.map &:to_i
if k > (n / 2.0).ceil
  puts 2 * (k - (n / 2.0).ceil)
else
  puts 2 * k - 1
end

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

    if n.even?
      if k <= n/2
        puts 2*k-1
      else
        puts 2*(k-n/2)
      end
    else
      if k <= n/2+1
        puts 2*k-1
      else
        puts 2*(k-(n/2+1))
      end
    end
  end
end

a = A.new

a=gets.chomp.split(" ")
odd=(a[0].to_i/2.0).ceil
even=(a[0].to_i/2.0)
if a[1].to_i<=odd
ans=2*(a[1].to_i-1)+1
puts "#{ans}"
else
ans=2*(a[1].to_i-odd)
puts "#{ans}"
end

n, k = gets.chomp.split(/ /).map(&:to_i)
mid = n / 2
mid += 1 if n.odd?
ans = (k - mid) * 2
ans = (2 * k) - 1 if mid >= k
puts "#{ans}"

n,k=gets.split.map{|e| e.to_i}
e=n/2+n%2
puts (k<=e)?2*k-1:(k-e)*2

n, k = gets.chomp.split.map(&:to_i)
a = n.odd? ? n/2+1 : n/2
puts k <= a ? 2*k-1 : 2*(k-a)

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

t = (n.to_f / 2).ceil

if k < t
  puts 1 + 2 * k
else
  puts 2 + 2 * (k - t)
end

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

if d % 2 == 0
  ot = d/2
  if n <= ot
    puts (2*n) - 1
  else
    puts 2*(n-ot)
  end
else
  ot = (d/2.0).ceil
  if n <= ot
    puts (2*n) - 1
  else
    puts 2*(n-ot)
  end
end

n,k=gets.split.map(&:to_i)
odd=(n+1)/2
puts k<=odd ? 2*k-1 : 2*(k-odd)

n, k = gets.split(/\s+/).map {|x| x.to_i}
class Integer
  def num_at_position (k)
    chet_num, ostatok = self.divmod(2)
    nechet_num = chet_num + ostatok
    if k > nechet_num
      return (k - nechet_num) * 2
    else
      return k * 2 - 1
    end
  end
end

puts n.num_at_position(k)

num = gets.chomp
num = num.split
numbers = num[0].to_i
position = num[1].to_i

if position <= (numbers/2) + (numbers%2)
	new_number = (position * 2) - 1
else
	new_number = (position - ((numbers/2) + (numbers%2))) * 2
end

print new_number

#puts "Enter the total number and position to find the number\n"
n, v = gets.split.map(&:to_i)
if n%2 == 0
    m = n/2
else
    m = n/2 + 1
end
if v <= m
    puts (2*v)-1
else
    puts 2*v - (2*m)
end

n,k = gets.split(" ").map(&:to_i)
even_count = n /2
odd_count = n / 2
odd_count += 1 if n % 2 != 0
ans = k > odd_count ? (k - odd_count) * 2 : k * 2 - 1
puts ans

a, b = gets.split.map &:to_i

if a >= b * 2 - 1 - a % 2
  puts b * 2 - 1
else
  puts (b - a/2 - a % 2) * 2
end

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

if k <= n / 2 + (n % 2 == 1 ? 1 : 0)
	puts k * 2 - 1
else
	if n % 2 == 1
		puts (k - n / 2 - 1) * 2
	else
		puts (k - n / 2) * 2
	end
end

n, k = gets.chomp.split(' ').collect { |i| i.to_i }

if k <= (n+1)/2
	puts 2*k - 1
else
	puts 2*( k - (n+1)/2)
end

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

mid = (n+1)/2
if k>mid
 puts 2*(k-mid)
else
 puts (k*2)-1
end

n,k = gets.split(" ").map(&:to_i)
m = (n/2.0).ceil()
if(k<=m)
    print((2*k)-1)
else
    print(2*(k-m))
end

s = gets.split(' ')	#Танцы с бубном

n = s[0].to_i
k = s[1].to_i

f = k - n/2 - n%2

if f > 0
	puts 2 * f
else
	puts n - 1 + n % 2 + 2 * f
end

n, k = gets.strip.split(" ").collect{|v| v.to_i}
if k <= (n / 2.0).ceil then
  puts ((k-1)*2+1)
else
  puts ((k-(n/2.0).ceil)*2)
end

input = gets.split
n = input[0].to_i
k = input[1].to_i
half = (n/2.0).ceil

val = 0
if k > half
    val = 2
    k -= half
else
    val = 1
end

val += 2*(k-1)

print val

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

if 2*k-1 <= n
  puts 2*k-1
else
  puts 2*k - n - n%2
end

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

mid = n/2 + n%2

if k > mid
  puts (k-mid)*2
else
  puts 2*k-1
end

#!/usr/bin/env ruby

n, k = gets.split.map(&:to_i)
puts k > (n + 1) / 2 ? (k - (n + 1) / 2) * 2 : 2 * k - 1

g = gets.split(' ')

n = g[0].to_f
k = g[1].to_i

if k > (n/2).ceil
    if n.modulo(2) == 0
        i = 2*k - n
    else
        i = 2*k - n - 1
    end
else
    i = 2*k - 1
end

puts i.to_i

n,k =gets.split(' ').map{|i| i.to_i()}
ans=k+k-1
if(ans>n)
	ans=(k-((n+1)>>1))<<1
end
p ans

n, k = gets.split.map { |x| x.to_i }
evens = n / 2
odds = n - evens
offset = 0
if k > odds
	k -= odds
	offset = 1
end

puts k * 2 - 1 + offset

input = gets.chomp.split(' ').map {|item| item.to_i}

n = input[0]
k = input[1]

maxOdd = (n + 1) / 2

puts (2 * k) - 1 if k <= maxOdd
puts (2* (k - maxOdd)) if k > maxOdd

n, k = gets.split(' ').map(&:to_i)
ofs = (n+1)/2
if k <= ofs
  puts 2*k-1
else
  puts 2*(k-ofs)
end

sin = STDIN
sout = STDOUT
# sin = File.open("test.in", "r")
# sout = File.open("test.out", "w")

n, k = *sin.readline.split.map{|e| e.to_i}
sout.puts k <= (n + 1) / 2 ? (2 * k - 1) : ((k - (n + 1) / 2) * 2)

STDIN.each_line { |l|
    l.strip!
    t = l.split(/\s+/)
    n = t[0].to_i
    k = t[1].to_i

    if k <= (n + 1) / 2 then
        puts 2 * k - 1
    else
        puts 2 * (k - (n + 1) / 2)
    end
}

n_k = gets.split.map &:to_i

n = n_k[0]
k = n_k[1]

half_n = n.even? ? n / 2 : n / 2 + 1

kth_element = k <= half_n ? 2 * k - 1 : 2 * (k - half_n)

puts kth_element

n,k = gets.split.map(&:to_i)
t=(n/2.0).ceil
p k>t ? 2*(k-t) : 2*k-1

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

cs = (n+1)/2
if k > cs
    puts (k-cs)*2
else
    puts (k*2)-1
end

n, k = $stdin.readline.split.map(&:to_i)

if n%2==0
    if k <= n/2
        puts 2*(k-1)+1
    else
        k -= n/2
        puts 2*(k)
    end
else
    if k <= n/2+1
        puts 2*(k-1)+1
    else
        k -= n/2+1
        puts 2*(k)
    end
end

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

  if k < (n / 2)
    puts (k * 2 - 1)
  else
    puts (((k - 1) - (n / 2)) * 2)
  end
end

run if $0 == __FILE__

n, k = gets.chomp.split.map &:to_i
if k > (n / 2.0).ceil
  puts 2 * (n - (n / 2.0).ceil)
else
  puts 2 * k - 1
end

n, k = gets.chomp.split.map(&:to_i)
if k < n / 2
  puts 2 * (k-1) + 1
else
  puts 2 * ((k-1) / 2)
end

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

if k < n / 2
  puts 1 + 2 * k
else
  k -= (n + 1) / 2
  puts 2 + 2 * k
end

n,k=gets.split.map(&:to_i)
puts (2*k<=n ? 2*k-1 : k/2*2)

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

if k <= n / 2
	puts k * 2 - 1
else
	if n % 2 == 1
		puts (k - n / 2 - 1) * 2
	else
		puts (k - n / 2) * 2
	end
end

s = gets.split(' ')	#Танцы с бубном

n = s[0].to_i
k = s[1].to_i

a = 1
i = 1

while a <= n  && i < k
	a += 2
	i += 1
end

if i < k
	a = 2
end

while i < k
	a += 2
	i += 1
end

puts a

n = gets.to_i
k = gets.to_i

a = 1
i = 1

while a <= n  && i < k
	a += 2
	i += 1
end

if i < k
	a = 2
end

while i < k
	a += 2
	i += 1
end

puts a

input = gets.split
n = input[0].to_i
k = input[1].to_i
half = (n/2.0).ceil

val = 0
if k > half
    val = 2
    k -= half
else
    val = 1
end

for i in 1..k-1
    val += 2*(k-1)
end

print val

g = gets.split(' ')

n = g[0].to_f
k = g[1].to_i

if k > (n/2).ceil
    i = 2*k - n
else
    i = 2*k - 1
end

puts i

input = gets.chomp.split(' ').map {|item| item.to_i}

n = input[0]
k = input[1]

maxOdd = (n - 1) / 2

puts (2 * k) - 1 if k <= maxOdd
puts (k / 2) + maxOdd if k > maxOdd

n, k = $stdin.readline.split.map(&:to_i)

if n%2==0
    if k <= n/2
        puts 2*(k-1)+1
    else
        puts 2*(k-1-n/2)
    end
else
    if k < n/2
        puts 2*(k-1)+1
    else
        puts 2*(k-1-n/2)
    end
end

n, k = $stdin.readline.split.map(&:to_i)

if n%2==0
    if k <= n/2
        puts 2*(k-1)+1
    else
        puts 2*(k-n/2)
    end
else
    if k <= n/2+1
        puts 2*(k-1)+1
    else
        puts 2*(k-n/2)
    end
end

n, k = $stdin.readline.split.map(&:to_i)

if n%2==0
    if k <= n/2
        puts 2*(k-1)+1
    else
        puts 2*(k-n/2)
    end
else
    if k < n/2
        puts 2*(k-1)+1
    else
        puts 2*(k-1-n/2)
    end
end


Petr has just bought a new car. He's just arrived at the most known Petersburg's petrol station to refuel it when he suddenly discovered that the petrol tank is secured with a combination lock! The lock has a scale of $$$360$$$ degrees and a pointer which initially points at zero:  Petr called his car dealer, who instructed him to rotate the lock's wheel exactly $$$n$$$ times. The $$$i$$$-th rotation should be $$$a_i$$$ degrees, either clockwise or counterclockwise, and after all $$$n$$$ rotations the pointer should again point at zero.This confused Petr a little bit as he isn't sure which rotations should be done clockwise and which should be done counterclockwise. As there are many possible ways of rotating the lock, help him and find out whether there exists at least one, such that after all $$$n$$$ rotations the pointer will point at zero again.

The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 15$$$) — the number of rotations. Each of the following $$$n$$$ lines contains one integer $$$a_i$$$ ($$$1 \leq a_i \leq 180$$$) — the angle of the $$$i$$$-th rotation in degrees.

If it is possible to do all the rotations so that the pointer will point at zero after all of them are performed, print a single word "YES". Otherwise, print "NO". Petr will probably buy a new car in this case. You can print each letter in any case (upper or lower).

NoteIn the first example, we can achieve our goal by applying the first and the second rotation clockwise, and performing the third rotation counterclockwise.In the second example, it's impossible to perform the rotations in order to make the pointer point at zero in the end.In the third example, Petr can do all three rotations clockwise. In this case, the whole wheel will be rotated by $$$360$$$ degrees clockwise and the pointer will point at zero again.

n,*a=$<.read.split.map &:to_i
s=a.reduce :+
puts (1<<n).times.any?{|i|t=n.times.select{|j|i[j]>0}.map{|j|a[j]}.reduce 0,:+;(s-2*t)%360==0} ? :YES : :NO

# Utility

# Better use B-tree but eff that
def spin(angle, initial = [0])
  return Array.new(initial.length * 2) { |i| initial[i / 2] + angle * (-1)**(i % 2) }
end

# Input
n = gets.to_i
a = Array.new(n) { |i| gets.to_i }

# Processing
variants = [a[0]]
(n - 1).times do |i|
  variants = spin(a[1 + i], variants)
end

able_to_open = variants.detect { |el| el % 360 == 0 }

# Output
puts(able_to_open ? "YES" : "NO")

n = gets().to_i
arr = []
n.times do
  arr += [gets().to_i]
end
cur = "0" * n
last = "1" * n
f = false
while (cur.to_i(10) < last.to_i(10))
  d = 0
  arr.each_with_index do |e, ind|
    if cur[ind] == '0'
      d -= e
    else
      d += e
    end
  end
  if (d % 360 == 0)
    f = true
    break
  end
  cur = (cur.to_i(2) + 1).to_s(2)
  # puts cur
  cur = ("0" * (n - cur.size)) + cur
end
if f
  puts "YES"
else
  puts "NO"
end

N = gets.to_i
as = [0]
bs = nil
N.times {
  rot = gets.to_i
  bs = as.map{ |a| [(a+rot)%360, (a-rot+360)%360]}.flatten.uniq
  as,bs = bs,as
}
puts as.include?(0) ? "YES" : "NO"

n,*a=$<.read.split.map &:to_i
s=a.reduce :+
puts (1<<n).times.any?{|i|t=n.times.select{|j|i[j]>0}.map{|j|a[j]}.reduce 0,:+;t%360==0} ? :YES : :NO

n,*a=$<.read.split.map &:to_i
s=a.reduce :+
puts (1<<n).times.any?{|i|t=n.times.select{|j|i[j]>0}.map{|j|a[j]}.reduce 0,:+;t*2==s} ? :YES : :NO


Panic is rising in the committee for doggo standardization — the puppies of the new brood have been born multi-colored! In total there are 26 possible colors of puppies in the nature and they are denoted by letters from 'a' to 'z' inclusive.The committee rules strictly prohibit even the smallest diversity between doggos and hence all the puppies should be of the same color. Thus Slava, the committee employee, has been assigned the task to recolor some puppies into other colors in order to eliminate the difference and make all the puppies have one common color.Unfortunately, due to bureaucratic reasons and restricted budget, there's only one operation Slava can perform: he can choose a color $$$x$$$ such that there are currently at least two puppies of color $$$x$$$ and recolor all puppies of the color $$$x$$$ into some arbitrary color $$$y$$$. Luckily, this operation can be applied multiple times (including zero).For example, if the number of puppies is $$$7$$$ and their colors are represented as the string "abababc", then in one operation Slava can get the results "zbzbzbc", "bbbbbbc", "aaaaaac", "acacacc" and others. However, if the current color sequence is "abababc", then he can't choose $$$x$$$='c' right now, because currently only one puppy has the color 'c'.Help Slava and the committee determine whether it is possible to standardize all the puppies, i.e. after Slava's operations all the puppies should have the same color.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of puppies. The second line contains a string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters, where the $$$i$$$-th symbol denotes the $$$i$$$-th puppy's color.

If it's possible to recolor all puppies into one color, print "Yes". Otherwise print "No". Output the answer without quotation signs.

NoteIn the first example Slava can perform the following steps:   take all puppies of color 'a' (a total of two) and recolor them into 'b';  take all puppies of color 'd' (a total of two) and recolor them into 'c';  take all puppies of color 'b' (three puppies for now) and recolor them into 'c'. In the second example it's impossible to recolor any of the puppies.In the third example all the puppies' colors are the same; thus there's no need to recolor anything.

n=gets.to_i
puts n>gets.chomp.chars.uniq.size||n==1?:Yes: :No

N = gets.to_i
S = gets.chomp.split('').sort
if N == 1
    puts 'Yes'
    exit
end

(N-1).times do |i|
    if S[i] == S[i+1]
        puts 'Yes'
        exit
    end
end
puts 'No'

n = gets.to_i
s = gets.chomp
c = Hash.new(0)
for i in 0..n-1
  c[s[i]] += 1
end
puts (n == 1 || c.values.any?{|i|i > 1}) ? "Yes" : "No"

useless = gets.chomp
line = gets.chomp
a = Array.new(26,0)
if(line.size == 1)
	print ("Yes")
	exit
end
for i in 0...line.size
	a[line[i].ord - 97] += 1
end

for i in 0...26
	if(a[i] > 1)
		print("Yes")
		exit
	end
end
print("No")

n = gets.split()[0].to_i
s = gets.split()[0]
mx = 0
('a'..'z').each do |x|
    mx = [mx, (s.count x)].max
end
puts ((mx > 1 or s.length == 1) ? 'Yes' : 'No')

n = gets.to_i
str = gets.chomp

if n==1
  puts "Yes"
  exit
end

if n>26
  puts "Yes"
else
  hash = Hash.new(0)
  str.each_char {|x| hash[x]+=1}

  if hash.values.max==1
    puts "No"
  else
    puts "Yes"
  end
end

n=gets.to_i
puts n>gets.chars.uniq.size||n==1?:Yes: :No

n = gets.to_i
s = gets.chomp
c = Hash.new(0)
for i in 0..n-1
  c[s[i]] += 1
end
puts c.values.any?{|i|i > 1} ? "YES" : "NO"

useless = gets.chomp
line = gets.chomp
a = Array.new(26,0)

for i in 0...line.size
	a[line[i].ord - 97] += 1
end

for i in 0...26
	if(a[i] > 1)
		print("Yes")
		exit
	end
end
print("No")

n = gets.to_i
str = gets.chomp

if n==1
  puts "Yes"
end

#if n>26
#  puts "Yes"
#  exit
#else
  hash = Hash.new(0)
  str.each_char {|x| hash[x]+=1}

  if hash.values.max<2
    puts "No"
  else
    puts "Yes"
  end
#end

n = gets.to_i
str = gets.chomp

if n==1
  puts "Yes"
end

if n>26
  puts "Yes"
  exit
else
  hash = Hash.new(0)
  str.each_char {|x| hash[x]+=1}

  if hash.values.max<2
    puts "No"
  else
    puts "Yes"
  end
end

n = gets.to_i
str = gets.chomp

if n>26
  puts "Yes"
  exit
else
  hash = Hash.new(0)
  str.each_char {|x| hash[x]+=1}

  if hash.values.max<2
    puts "No"
  else
    puts "Yes"
  end
end


Two players play a simple game. Each player is provided with a box with balls. First player's box contains exactly n1 balls and second player's box contains exactly n2 balls. In one move first player can take from 1 to k1 balls from his box and throw them away. Similarly, the second player can take from 1 to k2 balls from his box in his move. Players alternate turns and the first player starts the game. The one who can't make a move loses. Your task is to determine who wins if both players play optimally.

The first line contains four integers n1, n2, k1, k2. All numbers in the input are from 1 to 50. This problem doesn't have subproblems. You will get 3 points for the correct submission.

Output "First" if the first player wins and "Second" otherwise.

NoteConsider the first sample test. Each player has a box with 2 balls. The first player draws a single ball from his box in one move and the second player can either take 1 or 2 balls from his box in one move. No matter how the first player acts, the second player can always win if he plays wisely.

a, b = gets.strip.split.map( &:to_i )
puts a <= b ? "Second" : "First"

#!/usr/bin/ruby

input = STDIN.readline.chomp
input = input.split(' ')
if input[0].to_i > input[1].to_i
    puts "First"
elsif input[0] == input[1]
    puts "Second"
else
    puts "Second"
end

#!/usr/bin/ruby

input = STDIN.readline.chomp
input = input.split(' ')
if input[0].to_i > input[1].to_i
    puts "First"
elsif input[0].to_i == input[1].to_i
    puts "Second"
else
    puts "Second"
end

n1,n2,k1,k2=gets.chomp.split

n1 = n1.to_i
n2 = n2.to_i

case n1<=>n2
    when 0
        print "Second";
    when 1
        print "First";
    when -1
        print "Second";
end

n,m,k,l=gets.split.map &:to_i
puts n>m ? "First" : "Second"

n1, n2, k1, k2 = $stdin.readline.split.map(&:to_i)

if n1>n2
    puts "First"
else
    puts "Second"
end

#le roi est mort is here
k, l, c, d = gets.split.map &:to_i
if k > l
  puts "First"
else
  puts "Second"
end

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

a, b, c, d = gets.split.map &:to_i
puts (a > b) ? "First" : "Second"

n, m = gets.split.map &:to_i
if n == m
  puts "Second"
else
  if [n, m].max == n
    puts "First"
  else
    puts "Second"
  end
end

n, m, a, b = gets.split().map(&:to_i)
if n>m
  puts "First"
else
  puts "Second"
end

n1, n2, k1, k2 = gets.split.map(&:to_i)

if n1 > n2
  puts 'First'
else
  puts 'Second'
end

n1,n2,k1,k2=gets.split.map{|e| e.to_i}
if n1>n2 then
	puts "First"
else
	puts "Second"
end

n,m,k,l = gets.split.map(&:to_i)
puts n > m ? 'First' : 'Second'

#!/usr/bin/ruby

input_line = gets

params = input_line.split(' ')
n1 = params[0].to_i
n2 = params[1].to_i
k1 = params[2].to_i
k2 = params[3].to_i

if (n1<=n2)
    puts 'Second'
else
    puts 'First'
end

n1, n2, k1, k2 = gets.split.map &:to_i

puts (n1 > n2) ? "First" : "Second"

s = gets.split(" ").map { |e| e.to_i }
puts "First" if s[0] > s[1]
puts "Second" if s[0] <= s[1]

nk = gets.chomp.split.map(&:to_i)
n1 = nk[0]
n2 = nk[1]

if n1 <= n2
	print "Second"
elsif n1 > n2
	print "First"
end

arr = $stdin.readline.split(" ")
n1=  Float("#{arr[0]}")
n2 = Float("#{arr[1]}")
k1 = Float("#{arr[2]}")
k2 = Float("#{arr[3]}")
if (n2 + 1 > n1 )
    puts "Second"
else
    puts "First"
end

arr = $stdin.readline.split(" ")
n1 = arr[0].to_i
n2 = arr[1].to_i
puts n2 + 1 > n1 ? 'Second' : 'First'

arr = $stdin.readline.split(" ")
n1=  arr[0].to_i
n2 = arr[1].to_i
if (n2 + 1 > n1 )
    puts "Second"
else
    puts "First"
end

a,b,c,d=gets.chomp.split.map &:to_i
puts (a>b)? :First: :Second

n1, n2, k1, k2 = gets.split.map(&:to_i)
puts n1 > n2 ? "First" : "Second"

input = gets.split(" ")
n1 = input[0].to_i
n2 = input[1].to_i
if n1 > n2
  puts "First"
else
  puts "Second"
end

n_1, n_2, k_1, k_2 = gets.split.map{|x| x.to_i}
puts(n_1 > n_2 ? 'First' : 'Second')

a , b , c ,d = gets.split.map {|i| i.to_i}

if a > b
    puts "First"
else
    puts "Second"
end

pa=Array.new
str=gets.to_s
pa=str.split
n1=pa[0].to_i
n2=pa[1].to_i
if n1<=n2
  puts "Second"
else
  puts "First"
end

a, b, c, d = gets.split.map{|i| i.to_i}
puts a > b ? 'First' : 'Second'

n1, n2 = *gets.split.map(&:to_i)
puts n1 <= n2 ? "Second" : "First"

n1, n2, k1, k2 = gets.split.map { |x| x.to_i }
if n1 > n2
	puts 'First'
else
	puts 'Second'
end

a, b = gets.strip.split
puts a <= b ? "Second" : "First"

# cook your code here

n1,n2,k1,k2=gets.chomp.split

case n1<=>n2
    when 0
        print "Second";
    when 1
        print "First";
    when -1
        print "Second";
end

a,b,c,d=gets.split &:to_i
puts (a>b)? :Second: :First

a,b,c,d=gets.split &:to_i
puts (a<=b)? :Second: :First

a,b,c,d=gets.split &:to_i
puts (a>b)? :First: :Second

n_1, n_2, k_1, k_2 = gets.split
puts(n_1 > n_2 ? 'First' : 'Second')

pa=Array.new
str=gets.to_s
pa=str.split
n1=pa[0]
n2=pa[1]
if n1<=n2
  puts "Second"
else
  puts "First"
end


There are $$$b$$$ boys and $$$g$$$ girls participating in Olympiad of Metropolises. There will be a board games tournament in the evening and $$$n$$$ participants have accepted the invitation. The organizers do not know how many boys and girls are among them.Organizers are preparing red badges for girls and blue ones for boys.Vasya prepared $$$n+1$$$ decks of badges. The $$$i$$$-th (where $$$i$$$ is from $$$0$$$ to $$$n$$$, inclusive) deck contains $$$i$$$ blue badges and $$$n-i$$$ red ones. The total number of badges in any deck is exactly $$$n$$$.Determine the minimum number of decks among these $$$n+1$$$ that Vasya should take, so that there will be a suitable deck no matter how many girls and boys there will be among the participants of the tournament.

The first line contains an integer $$$b$$$ ($$$1 \le b \le 300$$$), the number of boys.  The second line contains an integer $$$g$$$ ($$$1 \le g \le 300$$$), the number of girls.  The third line contains an integer $$$n$$$ ($$$1 \le n \le b + g$$$), the number of the board games tournament participants.

Output the only integer, the minimum number of badge decks that Vasya could take.

NoteIn the first example, each of 4 decks should be taken: (0 blue, 3 red), (1 blue, 2 red), (2 blue, 1 red), (3 blue, 0 red).In the second example, 4 decks should be taken: (2 blue, 3 red), (3 blue, 2 red), (4 blue, 1 red), (5 blue, 0 red). Piles (0 blue, 5 red) and (1 blue, 4 red) can not be used.

b = gets.to_i
g = gets.to_i
n = gets.to_i

ans = 0
(0..n).each do |bb|
  gg = n - bb
  ans += 1 if bb <= b && gg <= g
end
puts ans

b = gets.to_i
g = gets.to_i
n = gets.to_i

cnt=0

if b>=n && g>=n
  cnt = n+1
elsif b<n && g<n
  diff = n-[b,g].max
  cnt = [b,g].min-diff+1
  cnt = 0 if cnt<0
else
  cnt = [b,g].min+1
end

puts cnt

b = gets.to_i
g = gets.to_i
n = gets.to_i

cnt=0

if b>=n && g>=n
  cnt = n+1
else
  cnt = [b,g].min+1
end

puts cnt


As you have noticed, there are lovely girls in Arpa’s land.People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi.  Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows.The game consists of rounds. Assume person x wants to start a round, he calls crushx and says: "Oww...wwf" (the letter w is repeated t times) and cuts off the phone immediately. If t > 1 then crushx calls crushcrushx and says: "Oww...wwf" (the letter w is repeated t - 1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (t = 1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time.Mehrdad has an evil plan to make the game more funny, he wants to find smallest t (t ≥ 1) such that for each person x, if x starts some round and y becomes the Joon-Joon of the round, then by starting from y, x would become the Joon-Joon of the round. Find such t for Mehrdad if it's possible.Some strange fact in Arpa's land is that someone can be himself's crush (i.e. crushi = i).

The first line of input contains integer n (1 ≤ n ≤ 100) — the number of people in Arpa's land. The second line contains n integers, i-th of them is crushi (1 ≤ crushi ≤ n) — the number of i-th person's crush.

If there is no t satisfying the condition, print -1. Otherwise print such smallest t.

NoteIn the first sample suppose t = 3. If the first person starts some round:The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if x is 1.The process is similar for the second and the third person.If the fourth person starts some round:The fourth person calls himself and says "Owwwf", then he calls himself again and says "Owwf", then he calls himself for another time and says "Owf", so the fourth person becomes Joon-Joon of the round. So the condition is satisfied when x is 4.In the last example if the first person starts a round, then the second person becomes the Joon-Joon, and vice versa.

n = gets.to_i
p = gets.split.map(&:to_i).map{|x| x - 1}

if p.uniq.size != n
  puts(-1)
  exit
end

ls = []
n.times do |i|
  x = p[i]
  len = 1
  until x == i
    x = p[x]
    len += 1
  end
  ls << len
end

ans = 1
ls.each do |l|
  l /= 2 if l.even?
  ans = ans.lcm(l)
end
puts ans


Grandma Laura came to the market to sell some apples. During the day she sold all the apples she had. But grandma is old, so she forgot how many apples she had brought to the market.She precisely remembers she had n buyers and each of them bought exactly half of the apples she had at the moment of the purchase and also she gave a half of an apple to some of them as a gift (if the number of apples at the moment of purchase was odd), until she sold all the apples she had.So each buyer took some integral positive number of apples, but maybe he didn't pay for a half of an apple (if the number of apples at the moment of the purchase was odd).For each buyer grandma remembers if she gave a half of an apple as a gift or not. The cost of an apple is p (the number p is even).Print the total money grandma should have at the end of the day to check if some buyers cheated her.

The first line contains two integers n and p (1 ≤ n ≤ 40, 2 ≤ p ≤ 1000) — the number of the buyers and the cost of one apple. It is guaranteed that the number p is even. The next n lines contains the description of buyers. Each buyer is described with the string half if he simply bought half of the apples and with the string halfplus if grandma also gave him a half of an apple as a gift. It is guaranteed that grandma has at least one apple at the start of the day and she has no apples at the end of the day.

Print the only integer a — the total money grandma should have at the end of the day. Note that the answer can be too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.

NoteIn the first sample at the start of the day the grandma had two apples. First she sold one apple and then she sold a half of the second apple and gave a half of the second apple as a present to the second buyer.

#!/usr/bin/ruby
n,p=gets.split.map(&:to_i)
m=r=0
$<.map(&:chomp).reverse.each{|e|
	m+=1 if e.end_with?('plus')
	r+=m*p/2
	m*=2
}
p r

n, p = gets.split(' ').map(&:to_i)
rest = 0
sum = 0
records = []

for i in 1..n
  records.unshift(gets.to_s.chomp)
end

records.each do |record|
  if record == 'half'
    rest = rest * 2
    sum += rest * p / 2
  else
    rest = ( rest + 0.5 ) * 2
    sum += rest * p / 2
  end

end

puts sum.to_i

a=gets.chomp.split(" ")
pow=a[0].to_i
price=a[1].to_i
apple=0
half=0
0.upto(pow-1) do |i|
k=gets.chomp
if k.length!=4
apple=apple+2**i
half+=1
end
end

ans=(apple-(0.5*half))*price
puts "#{ans.to_i}"

n, p = gets.chomp.split.map(&:to_i)
apples = 1.0
com = []
n.times do
  com << gets.chomp
end
halfplus = 1
com.pop
com.reverse.each do |c|
  if c == "halfplus" then
    apples += 0.5
    apples *= 2
    halfplus += 1
  else
    apples *= 2
  end
end

puts ((apples - halfplus * 0.5) * p).to_i

N, P = gets.split.map(&:to_i)
A = N.times.map{ gets.chomp }

x = A.reverse.reduce(0){|acc, a| (a == 'half') ? (acc * 2) : (acc * 2 + 1)}

ans = 0
N.times do
  if x % 2 == 0
    ans += P * (x/2)
  else
    ans += P * (x/2) + P/2
  end
  x /= 2
end

puts ans


Ujan has been lazy lately, but now has decided to bring his yard to good shape. First, he decided to paint the path from his house to the gate.The path consists of $$$n$$$ consecutive tiles, numbered from $$$1$$$ to $$$n$$$. Ujan will paint each tile in some color. He will consider the path aesthetic if for any two different tiles with numbers $$$i$$$ and $$$j$$$, such that $$$|j - i|$$$ is a divisor of $$$n$$$ greater than $$$1$$$, they have the same color. Formally, the colors of two tiles with numbers $$$i$$$ and $$$j$$$ should be the same if $$$|i-j| > 1$$$ and $$$n \bmod |i-j| = 0$$$ (where $$$x \bmod y$$$ is the remainder when dividing $$$x$$$ by $$$y$$$).Ujan wants to brighten up space. What is the maximum number of different colors that Ujan can use, so that the path is aesthetic?

The first line of input contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^{12}$$$), the length of the path.

Output a single integer, the maximum possible number of colors that the path can be painted in.

NoteIn the first sample, two colors is the maximum number. Tiles $$$1$$$ and $$$3$$$ should have the same color since $$$4 \bmod |3-1| = 0$$$. Also, tiles $$$2$$$ and $$$4$$$ should have the same color since $$$4 \bmod |4-2| = 0$$$.In the second sample, all five colors can be used.

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

require 'set'

n = gets.to_i

dividers = Set.new []

i = 2
size = n

while i * i <= n
  if n % i == 0
    dividers.add(i)
    n /= i
    i -= 1
  end
  i += 1
end

dividers.add(n) if n > 1

arr = []
dividers.each { |num| arr << num }

if arr[0] == size
  puts size
elsif arr.size == 1
  puts arr[0]
else
  puts 1
end

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

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

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

def 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

require 'prime'
n = inp[0]

d = Prime.prime_division(n)
if(d.size == 1 )
  p d[0][0]
else
  p 1
end

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

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

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

def 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

n = inp[0]
(2..((n**0.5).ceil)).each do |d|
  if (n%d ==0)
    p d
    exit
  end
end
p n

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

n = inp[0]
(2..((n**0.5).ceil)).each do |d|
  if (n%d ==0)
    if ( n/d  == d)
      p d
    else
      p 1
    end
    exit
  end
end
p n


InputThe only line of input contains three integers a1, a2, a3 (1 ≤ a1, a2, a3 ≤ 20), separated by spaces.OutputOutput a single integer.ExamplesInput2 3 2Output5Input13 14 1Output14Input14 5 9Output464Input17 18 3Output53

x,y,z=gets.split.map(&:to_i)
(z-1).times{x,y=y,x+y}
p y

a, b, c = gets.split.map(&:to_i)
c.times do
    a, b = b, a + b
end
p a

a,b,n = gets.split.collect{|i| i.to_i}

for i in (2..n)
  tmp = a + b
  a = b
  b = tmp
end

puts b

n = gets.chomp.split(" ")
kol = n[2].to_i
k = Array.new(kol+1)
k[0] = n[0].to_i
k[1] = n[1].to_i

for i in(0..kol-2)
	k[i+2] = k[i] + k[i+1]
end

if kol == 1 then
	k[kol] = k[1]
end

puts k[kol]

x,y,z=gets.split.map(&:to_i)
(z-1).times{x,y=y,z+y}
p y


Kolya loves putting gnomes at the circle table and giving them coins, and Tanya loves studying triplets of gnomes, sitting in the vertexes of an equilateral triangle.More formally, there are 3n gnomes sitting in a circle. Each gnome can have from 1 to 3 coins. Let's number the places in the order they occur in the circle by numbers from 0 to 3n - 1, let the gnome sitting on the i-th place have ai coins. If there is an integer i (0 ≤ i < n) such that ai + ai + n + ai + 2n ≠ 6, then Tanya is satisfied. Count the number of ways to choose ai so that Tanya is satisfied. As there can be many ways of distributing coins, print the remainder of this number modulo 109 + 7. Two ways, a and b, are considered distinct if there is index i (0 ≤ i < 3n), such that ai ≠ bi (that is, some gnome got different number of coins in these two ways).

A single line contains number n (1 ≤ n ≤ 105) — the number of the gnomes divided by three.

Print a single number — the remainder of the number of variants of distributing coins that satisfy Tanya modulo 109 + 7.

Note20 ways for n = 1 (gnome with index 0 sits on the top of the triangle, gnome 1 on the right vertex, gnome 2 on the left vertex):

Mod = (1e9 + 7).to_i

n = gets.to_i

ans1 = 1
ans2 = 1

n.times do
	ans1 *= 27
	ans2 *= 7

	ans1 %= Mod
	ans2 %= Mod
end

ans = (ans1 - ans2 + Mod) % Mod
puts ans


You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied:   the i-th letter occurs in the string no more than ai times;  the number of occurrences of each letter in the string must be distinct for all the letters that occurred in the string at least once.

The first line of the input contains a single integer n (2  ≤  n  ≤  26) — the number of letters in the alphabet. The next line contains n integers ai (1 ≤ ai ≤ 109) — i-th of these integers gives the limitation on the number of occurrences of the i-th character in the string.

Print a single integer — the maximum length of the string that meets all the requirements.

NoteFor convenience let's consider an alphabet consisting of three letters: "a", "b", "c". In the first sample, some of the optimal strings are: "cccaabbccbb", "aabcbcbcbcb". In the second sample some of the optimal strings are: "acc", "cbc".

n = gets.to_i
a = gets.split(" ").map(&:to_i).sort.reverse
x = a[0]
ans = 0
a.each do |k|
    k = [k, x].min
    ans += k
    x = k-1
    break if x == 0
end
p ans

def function
b=gets.chomp
a=gets.chomp
a=a.split(' ').map(&:to_i).sort.reverse
1.upto a.length do |i|
if a[0..i-1].include?(a[i])
a[i]=a[i-1]-1
end
end
sum=0
a.each do |i|
if i>0
sum+=i
end
end
puts sum
end
function

gets
h={}
gets.split.map(&:to_i).each{|e| h[e] ? h[e]+=1 : h[e]=1}
f=->(n){n*(n+1)/2}
res=0
x=10**9*2
h.sort.reverse.each{|k,v|
    a=f[x=[k, x].min]
    b=f[[x-v, 0].max]
    res+=a-b
    x=[x-v, 0].max
}
puts res

n = gets.chomp.to_i
as = gets.chomp.split.map(&:to_i)
ans = 0

as.sort!.reverse!
b = as[0]
as.each do |a|
  ans += [a, b].min
  b = [[a - 1, b - 1].min, 0].max
end

puts ans

gets
a=gets.split.map &:to_i
h = {}
a.sort.each{|x|
  x -= 1 while h[x]
  h[x] = true
}
p h.map{|k,v|[k,0].max}.inject :+

n = gets.to_i
a = gets.split(' ').map &:to_i
r = []
for v in a
  while r.index(v) && v > 0
    v-=1
  end

  r << v
end

puts r.inject(&:+)

class Solver
	def main
		n = gets.to_i
		arr = gets.split.map { |x| x.to_i }
		arr = arr.sort.reverse

		ans = 0
		last = 1 << 30
		arr.each do |x|
			x = last - 1 if x >= last
			ans += x if x >= 0
			last = x
		end
		puts ans
	end
end
Solver.new.main

def function
b=gets.chomp
a=gets.chomp
a=a.split(' ').map(&:to_i).sort.reverse
b=a.clone
1.upto a.length do |i|
if a[i]==a[i-1]
b[i]-=1
end
end
sum=0
b.each do |i|
sum+=i
end
puts sum
end
function

gets
a=gets.split.map &:to_i
h = {}
a.sort.each{|x|
  x -= 1 while h[x]
  h[x] = true
}
if h[-1]
  p 0
else
  p h.map{|k,v|k}.inject :+
end

gets
a=gets.split.map &:to_i
h = {}
a.sort.each{|x|
  x -= 1 while h[x]
  h[x] = true
}
if h.find 0
  p 0
else
  p h.map{|k,v|k}.inject :+
end

n = gets.to_i
a = gets.split(' ').map &:to_i
r = []
broken = false
for v in a
  while r.index(v)
    v-=1
  end
  if v >= 0
    r << v
  else
    r = [0]
    break
  end
end

puts r.inject(&:+)


The dragon and the princess are arguing about what to do on the New Year's Eve. The dragon suggests flying to the mountains to watch fairies dancing in the moonlight, while the princess thinks they should just go to bed early. They are desperate to come to an amicable agreement, so they decide to leave this up to chance.They take turns drawing a mouse from a bag which initially contains w white and b black mice. The person who is the first to draw a white mouse wins. After each mouse drawn by the dragon the rest of mice in the bag panic, and one of them jumps out of the bag itself (the princess draws her mice carefully and doesn't scare other mice). Princess draws first. What is the probability of the princess winning?If there are no more mice in the bag and nobody has drawn a white mouse, the dragon wins. Mice which jump out of the bag themselves are not considered to be drawn (do not define the winner). Once a mouse has left the bag, it never returns to it. Every mouse is drawn from the bag with the same probability as every other one, and every mouse jumps out of the bag with the same probability as every other one.

The only line of input data contains two integers w and b (0 ≤ w, b ≤ 1000).

Output the probability of the princess winning. The answer is considered to be correct if its absolute or relative error does not exceed 10 - 9.

NoteLet's go through the first sample. The probability of the princess drawing a white mouse on her first turn and winning right away is 1/4. The probability of the dragon drawing a black mouse and not winning on his first turn is 3/4 * 2/3 = 1/2. After this there are two mice left in the bag — one black and one white; one of them jumps out, and the other is drawn by the princess on her second turn. If the princess' mouse is white, she wins (probability is 1/2 * 1/2 = 1/4), otherwise nobody gets the white mouse, so according to the rule the dragon wins.

w,b=gets.split.map(&:to_i)
$dp=Array.new(1002){Array.new(1002){Array.new(2,-1)}}
#t=0 姫 t=1 ドラゴン
def solve(w,b,t)
        return 0 if b<0 || w<0
        return 0 if w+b==0
        return $dp[w][b][t] if $dp[w][b][t]>=0
        res=0.0
        if t==0 then
                res+=w.to_f/(w+b)
                res+=b.to_f/(w+b)*solve(w,b-1,1-t)
        else
                #Wを取る
                res=0
                #Bを取る
                tb=b-1
                tw=w
                if tb+tw==0 then
                        res=0
                else
                        res+=b.to_f/(w+b)*tb.to_f/(tb+tw)*solve(w,b-2,1-t)
                        res+=b.to_f/(w+b)*tw.to_f/(tb+tw)*solve(w-1,b-1,1-t)
                end
        end
        return $dp[w][b][t]=res
end
p solve(w,b,0)

Memo = {}# Array.new(1001*1001)

def f(w, b)
  return 0 if w==0
  ix = w*1001 + b
  return Memo[ix] if Memo[ix]
  res = 1.0*w/(w+b)
  if b>1
    m = 1.0*b*(b-1)/(w+b)/(w+b-1)
    wr = 1.0*w/(w+b-2)
    wp = f(w-1, b-2)
    br = 1.0-wr
    bp = 0
    bp = f(w, b-3) if b>2
    res += m * (wr*wp + br*bp)
  end
  Memo[ix] = res
  #puts "for w=#{w} b=#{b}: #{res}"
  res
end

w,b = readline.split(' ').map(&:to_i)
puts f(w,b)

Memo = Array.new(1001*1001)

def f(w, b)
  return 0 if w==0
  ix = w*1001 + b
  return Memo[ix] if Memo[ix]
  res = 1.0*w/(w+b)
  if b>1
    m = 1.0*b*(b-1)/(w+b)/(w+b-1)
    wr = 1.0*w/(w+b-2)
    wp = f(w-1, b-2)
    br = 1.0-wr
    bp = 0
    bp = f(w, b-3) if b>2
    res += m * (wr*wp + br*bp)
  end
  Memo[ix] = res
  #puts "for w=#{w} b=#{b}: #{res}"
  res
end

w,b = readline.split(' ').map(&:to_i)
puts f(w,b)


Paul is at the orchestra. The string section is arranged in an r × c rectangular grid and is filled with violinists with the exception of n violists. Paul really likes violas, so he would like to take a picture including at least k of them. Paul can take a picture of any axis-parallel rectangle in the orchestra. Count the number of possible pictures that Paul can take.Two pictures are considered to be different if the coordinates of corresponding rectangles are different.

The first line of input contains four space-separated integers r, c, n, k (1 ≤ r, c, n ≤ 3000, 1 ≤ k ≤ min(n, 10)) — the number of rows and columns of the string section, the total number of violas, and the minimum number of violas Paul would like in his photograph, respectively. The next n lines each contain two integers xi and yi (1 ≤ xi ≤ r, 1 ≤ yi ≤ c): the position of the i-th viola. It is guaranteed that no location appears more than once in the input.

Print a single integer — the number of photographs Paul can take which include at least k violas.

NoteWe will use '*' to denote violinists and '#' to denote violists.In the first sample, the orchestra looks as follows: *#** Paul can take a photograph of just the viola, the 1 × 2 column containing the viola, the 2 × 1 row containing the viola, or the entire string section, for 4 pictures total.In the second sample, the orchestra looks as follows: #**##* Paul must take a photograph of the entire section.In the third sample, the orchestra looks the same as in the second sample.

l1 = gets.chomp
vals1 = l1.split(' ').map {|x| x.to_i}

r = vals1[0]
c = vals1[1]
n = vals1[2]
k = vals1[3]

violas = []
columns = []
c.times {|x| columns << 0}
r.times {|x| col = []; c.times {|y| col << 0}; violas << col }
minx = r
miny = c
maxx = -1
maxy = -1
n.times {
  indices = gets.chomp.split(' ').map {|x| x.to_i - 1}
  violas[indices[0]][indices[1]] = 1
  minx = indices[1] if indices[1] < minx
  miny = indices[0] if indices[0] < miny
  maxx = indices[1] if indices[1] > maxx
  maxy = indices[0] if indices[0] > maxy
}

Rect = Struct.new(:x, :y, :x2, :y2)

rectangles = []
(0..r-1).each do |y|
  (0..c-1).each do |x|
    (y..r-1).each do |y2|
      (x..c-1).each do |x2|
        v = 0
        (y..y2).each do |yi|
          (x..x2).each do |xi|
            v += violas[yi][xi]
          end
        end
        if v >= k
          rectangles << Rect.new(x, y, x2, y2) unless rectangles.any? {|r|
            r.x == x && r.y == y && r.x2 == x2 && r.y2 == y2
          }
        end
      end
    end
  end
end
puts rectangles.length

r, c, n, k = gets.split.map(&:to_i)
pos = n.times.map{gets.split.map(&:to_i)}

photos = 0
for top in 1..r do
  for left in 1..c do
    for down in top..r do
      for right in left..c do
        alts = pos.count do |x, y|
          x >= top && x <= down && y >= left && y <= right
        end
        photos += 1 if alts >= k
      end
    end
  end
end
puts photos

buf = gets.split(' ')
r,c,n,k = buf[0].to_i, buf[1].to_i, buf[2].to_i, buf[3].to_i
a=Array.new(22)
for i in 0..r
	a[i]=Array.new(22, 0)
end
for i in 1..n
	buf = gets.split(' ')
	x, y = buf[0].to_i, buf[1].to_i
	a[x][y]=1
end
for i in 1..r
	for j in 1..c
		a[i][j]+=a[i-1][j]+a[i][j-1]-a[i-1][j-1]
	end
end
ans=0
for x1 in 1..r
	for y1 in 1..c
		for x2 in x1..r
			for y2 in y1..c
				tot = a[x2][y2]-a[x1-1][y2]-a[x2][y1-1]+a[x1-1][y1-1]
				ans+=1 if tot>=k
			end
		end
	end
end
puts ans


Masha lives in a multi-storey building, where floors are numbered with positive integers. Two floors are called adjacent if their numbers differ by one. Masha decided to visit Egor. Masha lives on the floor $$$x$$$, Egor on the floor $$$y$$$ (not on the same floor with Masha).The house has a staircase and an elevator. If Masha uses the stairs, it takes $$$t_1$$$ seconds for her to walk between adjacent floors (in each direction). The elevator passes between adjacent floors (in each way) in $$$t_2$$$ seconds. The elevator moves with doors closed. The elevator spends $$$t_3$$$ seconds to open or close the doors. We can assume that time is not spent on any action except moving between adjacent floors and waiting for the doors to open or close. If Masha uses the elevator, it immediately goes directly to the desired floor.Coming out of the apartment on her floor, Masha noticed that the elevator is now on the floor $$$z$$$ and has closed doors. Now she has to choose whether to use the stairs or use the elevator. If the time that Masha needs to get to the Egor's floor by the stairs is strictly less than the time it will take her using the elevator, then she will use the stairs, otherwise she will choose the elevator.Help Mary to understand whether to use the elevator or the stairs.

The only line contains six integers $$$x$$$, $$$y$$$, $$$z$$$, $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ ($$$1 \leq x, y, z, t_1, t_2, t_3 \leq 1000$$$) — the floor Masha is at, the floor Masha wants to get to, the floor the elevator is located on, the time it takes Masha to pass between two floors by stairs, the time it takes the elevator to pass between two floors and the time it takes for the elevator to close or open the doors. It is guaranteed that $$$x \ne y$$$.

If the time it will take to use the elevator is not greater than the time it will take to use the stairs, print «YES» (without quotes), otherwise print «NO> (without quotes). You can print each letter in any case (upper or lower).

NoteIn the first example:If Masha goes by the stairs, the time she spends is $$$4 \cdot 4 = 16$$$, because she has to go $$$4$$$ times between adjacent floors and each time she spends $$$4$$$ seconds. If she chooses the elevator, she will have to wait $$$2$$$ seconds while the elevator leaves the $$$4$$$-th floor and goes to the $$$5$$$-th. After that the doors will be opening for another $$$1$$$ second. Then Masha will enter the elevator, and she will have to wait for $$$1$$$ second for the doors closing. Next, the elevator will spend $$$4 \cdot 2 = 8$$$ seconds going from the $$$5$$$-th floor to the $$$1$$$-st, because the elevator has to pass $$$4$$$ times between adjacent floors and spends $$$2$$$ seconds each time. And finally, it will take another $$$1$$$ second before the doors are open and Masha can come out. Thus, all the way by elevator will take $$$2 + 1 + 1 + 8 + 1 = 13$$$ seconds, which is less than $$$16$$$ seconds, so Masha has to choose the elevator.In the second example, it is more profitable for Masha to use the stairs, because it will take $$$13$$$ seconds to use the elevator, that is more than the $$$10$$$ seconds it will takes to go by foot.In the third example, the time it takes to use the elevator is equal to the time it takes to walk up by the stairs, and is equal to $$$12$$$ seconds. That means Masha will take the elevator.

x,y,z,a,b,c=gets.split.map &:to_i
d=(x-y).abs
puts d*a<((x-z).abs+d)*b+3*c ? :No : :Yes

def solution
  x, y, z, stairs, elv, elv_doors = read_ints

  elv_time = ((z-x).abs + (x-y).abs) * elv + elv_doors * 3
  stair_time = (y-x).abs * stairs

  puts elv_time <= stair_time ? "YES" : "NO"

end

def read_int
  gets.to_i
end

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

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']

class A
  def self.run(s)
    x, y, z, t1, t2, t3 = s.split.map(&:to_i)
    walk = (x-y).abs * t1
    lift = (x-z).abs * t2 + t3*2 + (x-y).abs * t2 + t3
    if lift <= walk
      true
    else
      false
    end
  end
end

if A.run(gets.chomp)
  puts 'YES'
else
  puts 'NO'
end

x,y,z,t1,t2,t3 = gets.split.map { |e| Integer(e)  }
stair  = t1 * (x - y).abs
elevator =  t2 * (z - x).abs +  t3*2 + t2*(x-y).abs + t3
puts (if elevator <= stair then "YES" else "NO" end)

x, y, z, t1, t2, t3 = gets.split.map(&:to_i)

foot = (x-y).abs * t1
ev = (x-z).abs*t2+(x-y).abs*t2+t3*3

if foot < ev
  puts 'NO'
else
  puts 'YES'
end

line = gets.chomp

x, y, z, t1, t2, t3 = line.split.map(&:to_i)

elevator_time = ( (z-x).abs + (x-y).abs ) * t2 + 3 * t3
stair_time = (y-x).abs * t1

# puts elevator_time
# puts stair_time

if stair_time >= elevator_time
    puts "YES"
else
    puts "NO"
end

x, y, z, t1, t2, t3 = gets.split.map &:to_i
puts ((x - y).abs + (x - z).abs)*t2 + 3*t3 <= (x - y).abs*t1 ? 'YES' : 'NO'

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

x = xyzts[0]
y = xyzts[1]
z = xyzts[2]
t1 = xyzts[3]
t2 = xyzts[4]
t3 = xyzts[5]

st = (x-y).abs*t1
et = (x-z).abs*t2 + 3*t3 + (x-y).abs*t2

if et<=st
  puts "YES"
else
  puts "NO"
end


Alice has a lovely piece of cloth. It has the shape of a square with a side of length $$$a$$$ centimeters. Bob also wants such piece of cloth. He would prefer a square with a side of length $$$b$$$ centimeters (where $$$b < a$$$). Alice wanted to make Bob happy, so she cut the needed square out of the corner of her piece and gave it to Bob. Now she is left with an ugly L shaped cloth (see pictures below).Alice would like to know whether the area of her cloth expressed in square centimeters is prime. Could you help her to determine it?

The first line contains a number $$$t$$$ ($$$1 \leq t \leq 5$$$) — the number of test cases. Each of the next $$$t$$$ lines describes the $$$i$$$-th test case. It contains two integers $$$a$$$ and $$$b~(1 \leq b < a \leq 10^{11})$$$ — the side length of Alice's square and the side length of the square that Bob wants.

Print $$$t$$$ lines, where the $$$i$$$-th line is the answer to the $$$i$$$-th test case. Print "YES" (without quotes) if the area of the remaining piece of cloth is prime, otherwise print "NO". You can print each letter in an arbitrary case (upper or lower).

NoteThe figure below depicts the first test case. The blue part corresponds to the piece which belongs to Bob, and the red part is the piece that Alice keeps for herself. The area of the red part is $$$6^2 - 5^2 = 36 - 25 = 11$$$, which is prime, so the answer is "YES".  In the second case, the area is $$$16^2 - 13^2 = 87$$$, which is divisible by $$$3$$$.  In the third case, the area of the remaining piece is $$$61690850361^2 - 24777622630^2 = 3191830435068605713421$$$. This number is not prime because $$$3191830435068605713421 = 36913227731 \cdot 86468472991 $$$.In the last case, the area is $$$34^2 - 33^2 = 67$$$.

#ruby 2.4.1

require "prime"
t = gets.to_i
t.times do |a, b|
	flag = false
	nums = ""
	nums = gets
	a1, b1 = nums.split(' ')
	a = a1.to_i
	b = b1.to_i
	if Prime.prime?(a + b) == true && (a + b) * (a - b) == (a + b)
		puts "YES"
	else
		puts "NO"
	end
end

#ruby 2.4.1

require "prime"
t = gets.to_i
t.times do |a, b|
	flag = false
	nums = ""
	nums = gets
	a1, b1 = nums.split(' ')
	a = a1.to_i
	b = b1.to_i
	if ((a-b)*(a+b)) == (a + b)
		puts "YES"
	else
		puts "NO"
	end
end


There is a legend in the IT City college. A student that failed to answer all questions on the game theory exam is given one more chance by his professor. The student has to play a game with the professor.The game is played on a square field consisting of n × n cells. Initially all cells are empty. On each turn a player chooses and paint an empty cell that has no common sides with previously painted cells. Adjacent corner of painted cells is allowed. On the next turn another player does the same, then the first one and so on. The player with no cells to paint on his turn loses.The professor have chosen the field size n and allowed the student to choose to be the first or the second player in the game. What should the student choose to win the game? Both players play optimally.

The only line of the input contains one integer n (1 ≤ n ≤ 1018) — the size of the field.

Output number 1, if the player making the first turn wins when both players play optimally, otherwise print number 2.

# cook your code here

n = gets.chomp

if (n[-1].to_i)%2==0
    puts "2"
else
    puts "1"
end

n = gets.chomp.to_i
puts n % 2 == 0 ? 2 : 1


Since Grisha behaved well last year, at New Year's Eve he was visited by Ded Moroz who brought an enormous bag of gifts with him! The bag contains n sweet candies from the good ol' bakery, each labeled from 1 to n corresponding to its tastiness. No two candies have the same tastiness.The choice of candies has a direct effect on Grisha's happiness. One can assume that he should take the tastiest ones — but no, the holiday magic turns things upside down. It is the xor-sum of tastinesses that matters, not the ordinary sum!A xor-sum of a sequence of integers a1, a2, ..., am is defined as the bitwise XOR of all its elements: , here  denotes the bitwise XOR operation; more about bitwise XOR can be found here.Ded Moroz warned Grisha he has more houses to visit, so Grisha can take no more than k candies from the bag. Help Grisha determine the largest xor-sum (largest xor-sum means maximum happiness!) he can obtain.

The sole string contains two integers n and k (1 ≤ k ≤ n ≤ 1018).

Output one number — the largest possible xor-sum.

NoteIn the first sample case, one optimal answer is 1, 2 and 4, giving the xor-sum of 7.In the second sample case, one can, for example, take all six candies and obtain the xor-sum of 7.

n,k=gets.split.map &:to_i
p k==1 ? n : 2**n.to_s(2).size-1

#!/usr/bin/ruby
include Math

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

if k == 1 then
	puts n
else
	puts (1 << n.to_s(2).length) - 1
end

#!/usr/bin/ruby
include Math

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

if k == 1 then
	puts n
else
	puts (1 << n.to_s(2).length) - 1
end

x = gets.chomp.split(' ')
n = x[0].to_i
k = x[1].to_i
if k == 1
  puts n
else
  ans = 0
  i = 0
  while 2**i <= n
    ans += 2 ** i
    i += 1
  end
  puts ans
end


Everybody knows of spaghetti sort. You decided to implement an analog sorting algorithm yourself, but as you survey your pantry you realize you're out of spaghetti! The only type of pasta you have is ravioli, but you are not going to let this stop you...You come up with the following algorithm. For each number in the array ai, build a stack of ai ravioli. The image shows the stack for ai = 4.  Arrange the stacks in one row in the order in which the corresponding numbers appear in the input array. Find the tallest one (if there are several stacks of maximal height, use the leftmost one). Remove it and add its height to the end of the output array. Shift the stacks in the row so that there is no gap between them. Repeat the procedure until all stacks have been removed.At first you are very happy with your algorithm, but as you try it on more inputs you realize that it doesn't always produce the right sorted array. Turns out when two stacks of ravioli are next to each other (at any step of the process) and differ in height by two or more, the top ravioli of the taller stack slides down on top of the lower stack.Given an input array, figure out whether the described algorithm will sort it correctly.

The first line of input contains a single number n (1 ≤ n ≤ 10) — the size of the array. The second line of input contains n space-separated integers ai (1 ≤ ai ≤ 100) — the elements of the array.

Output "YES" if the array can be sorted using the described procedure and "NO" if it can not.

NoteIn the second example the array will change even before the tallest stack is chosen for the first time: ravioli from stack of height 3 will slide on the stack of height 1, and the algorithm will output an array {2, 2, 2}.

n,*a=$<.read.split.map &:to_i
puts a.each_cons(2).all?{|x,y|(x-y).abs<2} ? :YES : :NO

gets
puts (gets.split.map(&:to_i).each_cons(2).any? { |a| (a[0] - a[1]).abs > 1 } ? :NO : :YES)

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

bad = false
1.upto(n - 1){|i|
    if (a[i] - a[i-1]).abs >= 2 then
        bad = true;
    end
}

if bad then
    puts "NO"
else
    puts "YES"
end