Burenka came to kindergarden. This kindergarten is quite strange, so each kid there receives two fractions ($$$\frac{a}{b}$$$ and $$$\frac{c}{d}$$$) with integer numerators and denominators. Then children are commanded to play with their fractions.Burenka is a clever kid, so she noticed that when she claps once, she can multiply numerator or denominator of one of her two fractions by any integer of her choice (but she can't multiply denominators by $$$0$$$). Now she wants know the minimal number of claps to make her fractions equal (by value). Please help her and find the required number of claps!

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then follow the descriptions of each test case. The only line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$ and $$$d$$$ ($$$0 \leq a, c \leq 10^9$$$, $$$1 \leq b, d \leq 10^9$$$) — numerators and denominators of the fractions given to Burenka initially.

For each test case print a single integer — the minimal number of claps Burenka needs to make her fractions equal.

NoteIn the first case, Burenka can multiply $$$c$$$ by $$$2$$$, then the fractions will be equal.In the second case, fractions are already equal.In the third case, Burenka can multiply $$$a$$$ by $$$4$$$, then $$$b$$$ by $$$3$$$. Then the fractions will be equal ($$$\frac{1 \cdot 4}{2 \cdot 3} = \frac{2}{3}$$$).

def solve(a, b, c, d)
  x = b*c
  y = a*d

  return 0 if x == y
  return 1 if x == 0 || y == 0 || x % y == 0 || y % x == 0

  return 2
end

def main
  n = gets.chomp.to_i
  n.times do
    a, b, c, d = gets.chomp.split
    puts solve(a.to_i, b.to_i, c.to_i, d.to_i)
  end
end

main

def solve(a, b, c, d)
  x = b*c
  y = a*d

  return 0 if x == y
  return 1 if x == 0 || y == 0 || x % y == 0 || y % x == 0

  return 2
end

def main
  n = $stdin.gets.to_i
  n.times do
    a = gets.to_i
    b = gets.to_i
    c = gets.to_i
    d = gets.to_i

    puts solve(a, b, c, d)
  end
end

main


You are given two integers $$$n$$$ and $$$k$$$. You are asked to choose maximum number of distinct integers from $$$1$$$ to $$$n$$$ so that there is no subset of chosen numbers with sum equal to $$$k$$$.A subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it.

The first line contains the number of test cases $$$T$$$ ($$$1 \le T \le 100$$$). Each of the next $$$T$$$ lines contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 1000$$$) — the description of test cases.

For each test case output two lines. In the first line output a single integer $$$m$$$ — the number of chosen integers. In the second line output $$$m$$$ distinct integers from $$$1$$$ to $$$n$$$ — the chosen numbers. If there are multiple answers, print any. You can print the numbers in any order.

gets.to_i.times do
  n, k = gets.split.map &:to_i
  puts n - k + k / 2
    (k + 1..n).each do |i|
    print i, ' '
  end
  ((k + 1) / 2...k).each do |i|
    print i, ' '
  end
  puts
end

gets.to_i.times do
  n, k = gets.split.map &:to_i
  puts n - k + 1
  (k + 1..n).each do |i|
    print i, ' '
  end
  ((k + 1) / 2...k).each do |i|
    print i, ' '
  end
  puts
end

gets.to_i.times do
  n, k = gets.split.map &:to_i
  puts n - k + 1
  (k + 1..n).each do |i|
    print i, ' '
  end
  ((k + 1) / 2..k).each do |i|
    print i, ' '
  end
  puts
end


You are given two lists of segments $$$[al_1, ar_1], [al_2, ar_2], \dots, [al_n, ar_n]$$$ and $$$[bl_1, br_1], [bl_2, br_2], \dots, [bl_n, br_n]$$$.Initially, all segments $$$[al_i, ar_i]$$$ are equal to $$$[l_1, r_1]$$$ and all segments $$$[bl_i, br_i]$$$ are equal to $$$[l_2, r_2]$$$.In one step, you can choose one segment (either from the first or from the second list) and extend it by $$$1$$$. In other words, suppose you've chosen segment $$$[x, y]$$$ then you can transform it either into $$$[x - 1, y]$$$ or into $$$[x, y + 1]$$$.Let's define a total intersection $$$I$$$ as the sum of lengths of intersections of the corresponding pairs of segments, i.e. $$$\sum\limits_{i=1}^{n}{\text{intersection_length}([al_i, ar_i], [bl_i, br_i])}$$$. Empty intersection has length $$$0$$$ and length of a segment $$$[x, y]$$$ is equal to $$$y - x$$$.What is the minimum number of steps you need to make $$$I$$$ greater or equal to $$$k$$$?

The first line contains the single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$1 \le k \le 10^9$$$) — the length of lists and the minimum required total intersection. The second line of each test case contains two integers $$$l_1$$$ and $$$r_1$$$ ($$$1 \le l_1 \le r_1 \le 10^9$$$) — the segment all $$$[al_i, ar_i]$$$ are equal to initially. The third line of each test case contains two integers $$$l_2$$$ and $$$r_2$$$ ($$$1 \le l_2 \le r_2 \le 10^9$$$) — the segment all $$$[bl_i, br_i]$$$ are equal to initially. It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$.

Print $$$t$$$ integers — one per test case. For each test case, print the minimum number of step you need to make $$$I$$$ greater or equal to $$$k$$$.

NoteIn the first test case, we can achieve total intersection $$$5$$$, for example, using next strategy:   make $$$[al_1, ar_1]$$$ from $$$[1, 2]$$$ to $$$[1, 4]$$$ in $$$2$$$ steps;  make $$$[al_2, ar_2]$$$ from $$$[1, 2]$$$ to $$$[1, 3]$$$ in $$$1$$$ step;  make $$$[bl_1, br_1]$$$ from $$$[3, 4]$$$ to $$$[1, 4]$$$ in $$$2$$$ steps;  make $$$[bl_2, br_2]$$$ from $$$[3, 4]$$$ to $$$[1, 4]$$$ in $$$2$$$ steps.  In result, $$$I = \text{intersection_length}([al_1, ar_1], [bl_1, br_1]) + \text{intersection_length}([al_2, ar_2], [bl_2, br_2]) + \\ + \text{intersection_length}([al_3, ar_3], [bl_3, br_3]) = 3 + 2 + 0 = 5$$$In the second test case, we can make $$$[al_1, ar_1] = [0, 1000000000]$$$ in $$$1000000000$$$ steps and $$$[bl_1, br_1] = [0, 1000000000]$$$ in $$$1000000000$$$ steps.In the third test case, the total intersection $$$I$$$ is already equal to $$$10 > 3$$$, so we don't need to do any steps.

def read
    gets.split.map &:to_i
end
gets.to_i.times do
    n, k = read
    l1, r1 = read
    l2, r2 = read
    if [l1, l2].max <= [r1, r2].min
        rem = [0, k - n * ([r1, r2].min - [l1, l2].max)].max
        mx = n * ((l2 - l1).abs + (r2 - r1).abs)
        res = [rem, mx].min + 2 * [0, rem - mx].max
    else
        res = 1E18.to_i
        add = [l1, l2].max - [r1, r2].min
        (1..n).each do |i|
            cur = add * i
            mx = i * ([r1, r2].max - [l1, l2].min)
            cur += [k, mx].min + 2 * [0, k - mx].max
            res = [res, cur].min
        end
    end
    puts res
end


Over time, Alexey's mail box got littered with too many letters. Some of them are read, while others are unread.Alexey's mail program can either show a list of all letters or show the content of a single letter. As soon as the program shows the content of an unread letter, it becomes read letter (if the program shows the content of a read letter nothing happens). In one click he can do any of the following operations: Move from the list of letters to the content of any single letter. Return to the list of letters from single letter viewing mode. In single letter viewing mode, move to the next or to the previous letter in the list. You cannot move from the first letter to the previous one or from the last letter to the next one.The program cannot delete the letters from the list or rearrange them.Alexey wants to read all the unread letters and go watch football. Now he is viewing the list of all letters and for each letter he can see if it is read or unread. What minimum number of operations does Alexey need to perform to read all unread letters?

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of letters in the mailbox. The second line contains n space-separated integers (zeros and ones) — the state of the letter list. The i-th number equals either 1, if the i-th number is unread, or 0, if the i-th letter is read.

Print a single number — the minimum number of operations needed to make all the letters read.

NoteIn the first sample Alexey needs three operations to cope with the task: open the second letter, move to the third one, move to the fourth one.In the second sample the action plan: open the first letter, move to the second letter, return to the list, open the fifth letter.In the third sample all letters are already read.

=begin
Dear online judge:
I've wasted time reading the problem and trying to figure out the solution
If you insist on the penalty system, please don't include the time of debugging
I hope my code compile and get accepted. KEE O.o
     ____________
    /         __ \
   /   __    |  | \
  /   |__|   |  |  \
 (           |__|   )
  \                /
   \      ___     /
    \____________/
=end

class Solve
  def solve()
    $n = Integer(gets)
    $list = gets().split()
    $res = 0
    $count = $list.count("1")
    $n -= 1
    for $i in 0..$n do
      if $list[$i] == "1"
        $res+= 1
        $count -= 1
        if $count > 0 && $list[$i + 1]!= "1"
          $res+= 1
        end
      end
    end
    puts $res
  end
end

Solve.new.solve

#!/usr/bin/ruby
gets
a=gets.split.map(&:to_i)
p [0,a.count(1)*2-1-a.each_cons(2).count{|x,y|x==1&&y==1}].max

#!/usr/bin/ruby

n = STDIN.readline.to_i
letters = STDIN.readline.split.collect {|s| s == '1' }

indices = []
letters.each_index {|i| indices.push(i) if letters[i] }

count = [1, indices.length].min
(1...indices.length).each do |i|
	count += [2, indices[i] - indices[i-1]].min
end

puts count

#!/usr/bin/ruby
gets
puts gets.scan(/1|(?<=1) (0 )+(?=1)/).size

n=gets.to_i
xs=gets.split.map{|e| e.to_i}
p1=xs.index(1)
if p1==nil then
	puts 0
else
	p1.times{
		xs.shift
	}
	while xs.empty? == false
		t=xs.pop
		if t==1
			xs.push(t)
			break
		end
	end

	ans=0
	old=1
	xs.each{|e|
		if e==0 then
			if old==1 then
				ans+=1
			end
		else
			ans+=1
		end
		old=e
	}
	puts ans
end

# -*- coding: utf-8 -*-
n = gets.to_i
xs = gets.split.map(&:to_i)
flag = false
ret = 0
xs.each do |x|
  if x == 1
    flag = true
    ret += 1
  elsif flag == true && x == 0
    flag = false
    ret += 1
  end
end
ret -= 1 if xs[-1] == 0 && ret > 0
puts ret

n = Integer(gets)
nums = gets.chomp.split
letters = []
for i in 0...n
    letters[i] = Integer(nums[i])
end
op = 0
pointer = 0
for i in 0...n-1
    if letters[i] == 1
        op += 1
        if letters[i+1] == 0 && i + 1 != n-1
            pointer = i + 1
            op += 1
        end
    end
end
x = 0
for j in pointer...n
    if letters[j] != 0
        x = 1
        break
    end
end
if x == 0 && op != 0
    op -= 1
end
if letters[n-1] == 1
    op += 1
end
puts op

n = gets.to_i
a = gets.split(/\s+/).map(&:to_i)

answer = 0
i = 0

i += 1 while i < n && a[i] != 1

answer = 1 if a[i] == 1
current = i
i += 1

while i < n
  i += 1 while i < n && a[i] != 1

#  p [current, i, answer]

  if a[i] == 1
    answer += (i - current > 2) ? 2 : i - current
  end

  current = i
  i += 1
end

p answer

gets # ignore first line
groups = gets.strip.tr(' ', '').split("0").delete_if { |x| x.length == 0 }.map(&:length)
puts [groups.inject(0, :+) + groups.length - 1, 0].max

n = gets.chomp.to_i
x = gets.split()

i = 0
m = 0

for i in 0..n-1
  if x[i].to_i==1
     m=m+1
  else
   if i>0
    if x[i-1].to_i==1
       m=m+1
     end
   end
  end

end

if  x[n-1].to_i==0
  if m >0
     m=m-1
  end
end
print m

gets
puts gets.prepend("0").strip.delete(" ").gsub(/01/,"11").count("1").pred.to_s.gsub(/-1/,"0")

gets
puts gets.delete(" ").tr_s('0',' ').strip.length

gets
puts gets.delete(" ").squeeze("0").tr('0',' ').strip.length

#!/usr/bin/ruby
gets
a=gets.split.map(&:to_i)
p a.count('1')*2-1-a.each_cons(2).count{|x,y|x==1&&y==1}

#!/usr/bin/ruby
gets
a=gets.split.map(&:to_i)
p a.count(1)*2-1-a.each_cons(2).count{|x,y|x==1&&y==1}

n = Integer(gets)
nums = gets.chomp.split
letters = []
for i in 0...n
    letters[i] = Integer(nums[i])
end
op = 0
pointer = 0
for i in 0...n-1
    if letters[i] == 1
        op += 1
        if letters[i+1] == 0 && i + 1 != n-1
            pointer = i + 1
            op += 1
        end
    end
end
x = 0
for j in pointer...n-1
    if letters != 0
        x = 1
        break
    end
end
if x == 0
    op -= 1
end
if letters[n-1] == 1
    op += 1
end
puts op

n = Integer(gets)
nums = gets.chomp.split
letters = []
for i in 0...n
    letters[i] = Integer(nums[i])
end
op = 0
pointer = 0
for i in 0...n-1
    if letters[i] == 1
        op += 1
        if letters[i+1] == 0 && i + 1 != n-1
            pointer = i + 1
            op += 1
        end
    end
end
x = 0
for j in pointer...n-1
    if letters[j] != 0
        x = 1
        break
    end
end
if x == 0
    op -= 1
end
if letters[n-1] == 1
    op += 1
end
puts op

n = Integer(gets)
nums = gets.chomp.split
letters = []
for i in 0...n
    letters[i] = Integer(nums[i])
end
op = 0
pointer = 0
for i in 0...n-1
    if letters[i] == 1
        op += 1
        if letters[i+1] == 0 && i + 1 != n-1
            pointer = i + 1
            op += 1
        end
    end
end
x = 0
for j in pointer...n
    if letters[j] != 0
        x = 1
        break
    end
end
if x == 0
    op -= 1
end
if letters[n-1] == 1
    op += 1
end
puts op

n = Integer(gets)
nums = gets.chomp.split
letters = []
for i in 0...n
    letters[i] = Integer(nums[i])
end
op = 0
for i in 0...n-1
    if letters[i] == 1
        op += 1
        if letters[i+1] == 0 && i + 1 != n-1
            op += 1
        end
    end
end
if letters[n-1] == 1
    op += 1
end
puts op

n = gets.chomp.to_i
x = gets.split()

i = 0
m = 0

for i in 0..n-1
  if x[i].to_i==1
  m=m+1
  end

if x[i].to_i==0
  if x[i-1].to_i==1
  m=m+1
 end
end

end

if  x[n-1].to_i==0
  if m >0
m=m-1
end
end
print m

n = gets.chomp.to_i
x = gets.split()

i = 0
m = 0

for i in 0..n
  if x[i].to_i==1
  m=m+1
  end
if x[i].to_i==0
  if x[i-1].to_i==1
  m=m+1
 end
end
end

if  x[n].to_i==0
  if m>1
m=m-1
end
end
print m

n = gets.chomp.to_i
x = gets.split()

i = 0
m = 0

for i in 0..n-1
  if x[i].to_i==1
  m=m+1
  end
if x[i].to_i==0
  if x[i-1].to_i==1
  m=m+1
 end
end
end

if  x[n-1].to_i==0
  if m>1
m=m-1
end
end
print m

n = gets.chomp.to_i
x = gets.split()

i = 0
m = 0

for i in 0..n-1
  if x[i].to_i==1
     m=m+1
  else
    if x[i-1].to_i==1
       m=m+1
     end
  end

end

if  x[n-1].to_i==0
  if m >0
     m=m-1
  end
end
print m

gets
puts gets.split.join.tr_s('0',' ').split.length

gets
puts gets.split(%r{ ?(0 )+}).join.split.length


Numbers $$$1, 2, 3, \dots n$$$ (each integer from $$$1$$$ to $$$n$$$ once) are written on a board. In one operation you can erase any two numbers $$$a$$$ and $$$b$$$ from the board and write one integer $$$\frac{a + b}{2}$$$ rounded up instead.You should perform the given operation $$$n - 1$$$ times and make the resulting number that will be left on the board as small as possible. For example, if $$$n = 4$$$, the following course of action is optimal:  choose $$$a = 4$$$ and $$$b = 2$$$, so the new number is $$$3$$$, and the whiteboard contains $$$[1, 3, 3]$$$;  choose $$$a = 3$$$ and $$$b = 3$$$, so the new number is $$$3$$$, and the whiteboard contains $$$[1, 3]$$$;  choose $$$a = 1$$$ and $$$b = 3$$$, so the new number is $$$2$$$, and the whiteboard contains $$$[2]$$$. It's easy to see that after $$$n - 1$$$ operations, there will be left only one number. Your goal is to minimize it.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The only line of each test case contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of integers written on the board initially. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, in the first line, print the minimum possible number left on the board after $$$n - 1$$$ operations. Each of the next $$$n - 1$$$ lines should contain two integers — numbers $$$a$$$ and $$$b$$$ chosen and erased in each operation.

T = gets.to_i

T.times do
  n = gets.to_i
  stack = [*1..n]

  puts 2
  (n - 1).times do
    a, b = stack.pop(2)

    puts "%d %d" % [a, b]
    stack.push((a + b + 1) / 2)
  end
end


It's now 260 AD. Shapur, being extremely smart, became the King of Persia. He is now called Shapur, His majesty King of kings of Iran and Aniran.Recently the Romans declared war on Persia. They dreamed to occupy Armenia. In the recent war, the Romans were badly defeated. Now their senior army general, Philip is captured by Shapur and Shapur is now going to capture Valerian, the Roman emperor.Being defeated, the cowardly Valerian hid in a room at the top of one of his castles. To capture him, Shapur has to open many doors. Fortunately Valerian was too scared to make impenetrable locks for the doors.Each door has 4 parts. The first part is an integer number a. The second part is either an integer number b or some really odd sign which looks like R. The third one is an integer c and the fourth part is empty! As if it was laid for writing something. Being extremely gifted, after opening the first few doors, Shapur found out the secret behind the locks.c is an integer written in base a, to open the door we should write it in base b. The only bad news is that this R is some sort of special numbering system that is used only in Roman empire, so opening the doors is not just a piece of cake!Here's an explanation of this really weird number system that even doesn't have zero:Roman numerals are based on seven symbols: a stroke (identified with the letter I) for a unit, a chevron (identified with the letter V) for a five, a cross-stroke (identified with the letter X) for a ten, a C (identified as an abbreviation of Centum) for a hundred, etc.: I=1 V=5 X=10 L=50 C=100 D=500 M=1000Symbols are iterated to produce multiples of the decimal (1, 10, 100, 1, 000) values, with V, L, D substituted for a multiple of five, and the iteration continuing: I 1, II 2, III 3, V 5, VI 6, VII 7, etc., and the same for other bases: X 10, XX 20, XXX 30, L 50, LXXX 80; CC 200, DCC 700, etc. At the fourth and ninth iteration, a subtractive principle must be employed, with the base placed before the higher base: IV 4, IX 9, XL 40, XC 90, CD 400, CM 900.Also in bases greater than 10 we use A for 10, B for 11, etc.Help Shapur capture Valerian and bring peace back to Persia, especially Armenia.

The first line contains two integers a and b (2 ≤ a, b ≤ 25). Only b may be replaced by an R which indicates Roman numbering system. The next line contains a single non-negative integer c in base a which may contain leading zeros but its length doesn't exceed 103.  It is guaranteed that if we have Roman numerals included the number would be less than or equal to 300010 and it won't be 0. In any other case the number won't be greater than 101510.

Write a single line that contains integer c in base b. You must omit leading zeros.

NoteYou can find more information about roman numerals here: http://en.wikipedia.org/wiki/Roman_numerals

def to_r(n)
	if n < 1
		''
	elsif n < 10
		%w(I II III IV V VI VII VIII IX)[n - 1]
	elsif n < 100
		%w(X XX XXX XL L LX LXX LXXX XC)[n / 10 - 1] + to_r(n % 10)
	elsif n < 1000
		%w(C CC CCC CD D DC DCC DCCC CM)[n / 100 - 1] + to_r(n % 100)
	else
		%w(M MM MMM)[n / 1000 - 1] + to_r(n % 1000)
	end
end

a, b = gets.split.map(&:to_i)
n = gets.to_i(a)
puts b > 0 ? n.to_s(b).upcase : to_r(n)

include Math
require "prime"
require "bigdecimal"
require "bigdecimal/math"
require "matrix"
require "pp"
require "benchmark"

Infinity = 1/0.0

alias p! p
def p(*objs)
    def onep(obj)
        case obj
        when Matrix
            puts"Matrix["
            obj.to_a.each{|row|p row}
            puts"]"
        else
            p! obj
        end
    end
    objs.each{|obj|
        onep obj
    }
end
def pbin(obj);case obj;when Integer;puts obj.to_s(2);end;end
class String;def to_ia;self.split.map(&:to_i);end;end
def getia;gets.to_ia;end
def geti;gets.to_i;end
class Object;def dcopy;Marshal.load(Marshal.dump(self));end;end

class Integer
    RomaTbl = {1 => 'I', 4 => 'IV', 5 => 'V', 9=> 'IX', 10 =>  'X',
        40 => 'XL', 50 => 'L', 90 => 'XC', 100 => 'C', 400 => 'CD',
        500 => 'D', 900=> 'CM', 1000 => 'M'}
    def roman(s=self)
        return "-" if s==0
        k = RomaTbl.keys.delete_if{|x| x > s}.sort[-1]
        return RomaTbl[k] + roman(s - k).gsub('-','')
    end
end

f=gets
a,b=f.split(" ")

n=gets.to_i(a.to_i)

if b=="R"
    puts n.roman
else
    puts n.to_s(b.to_i).upcase
end

def f(n)
    m, c, x, l = [1000, 100, 10, 1].map { |t| r = (n/t).floor; n %= t; r }
    'M'*m +
    case c
        when 9 then 'CM'
        when 5..8 then 'D' + 'C'*(c-5)
        when 4 then 'CD'
        when 1..3 then 'C'*c
    else ''
    end +
    case x
        when 9 then 'XC'
        when 5..8 then 'L' + 'X'*(x-5)
        when 4 then 'XL'
        when 1..3 then 'X'*x
    else ''
    end +
    case l
        when 9 then 'IX'
        when 5..8 then 'V' + 'I'*(l-5)
        when 4 then 'IV'
        when 1..3 then 'I'*l
    else ''
    end
end

a, b = gets.split
c = gets.to_i(a.to_i)
puts (b == 'R' ? f(c) : c.to_s(b.to_i).upcase)

include Math
require "prime"
require "bigdecimal"
require "bigdecimal/math"
require "matrix"
require "pp"
require "benchmark"

Infinity = 1/0.0

alias p! p
def p(*objs)
    def onep(obj)
        case obj
        when Matrix
            puts"Matrix["
            obj.to_a.each{|row|p row}
            puts"]"
        else
            p! obj
        end
    end
    objs.each{|obj|
        onep obj
    }
end
def pbin(obj);case obj;when Integer;puts obj.to_s(2);end;end
class String;def to_ia;self.split.map(&:to_i);end;end
def getia;gets.to_ia;end
def geti;gets.to_i;end
class Object;def dcopy;Marshal.load(Marshal.dump(self));end;end

class Integer
    RomaTbl = {1 => 'I', 4 => 'IV', 5 => 'V', 9=> 'IX', 10 =>  'X',
        40 => 'XL', 50 => 'L', 90 => 'XC', 100 => 'C', 400 => 'CD',
        500 => 'D', 900=> 'CM', 1000 => 'M'}
    def roman(s=self)
        return "-" if s==0
        k = RomaTbl.keys.delete_if{|x| x > s}.sort[-1]
        return RomaTbl[k] + roman(s - k).gsub('-','')
    end
end

f=gets
a,b=f.split(" ")

n=gets.to_i(a.to_i)

if b=="R"
    puts n.roman
else
    puts n.to_s(b.to_i)
end

def f(n)
    m, c, x, l = [1000, 100, 10, 1].map { |t| r = (n/t).floor; n %= t; r }
    'M'*m +
    case c
        when 9 then 'CM'
        when 5..8 then 'D' + 'C'*(c-5)
        when 4 then 'CD'
        when 1..3 then 'C'*c
    else ''
    end +
    case x
        when 9 then 'XC'
        when 5..8 then 'L' + 'X'*(x-5)
        when 4 then 'XL'
        when 1..3 then 'X'*x
    else ''
    end +
    case l
        when 9 then 'IX'
        when 5..8 then 'V' + 'I'*(l-5)
        when 4 then 'IV'
        when 1..3 then 'I'*l
    else ''
    end
end

a, b = gets.split
c = gets.to_i(a.to_i)
puts (b == 'R' ? f(c) : c.to_s(b.to_i))


A penguin Rocher has $$$n$$$ sticks. He has exactly one stick with length $$$i$$$ for all $$$1 \le i \le n$$$.He can connect some sticks. If he connects two sticks that have lengths $$$a$$$ and $$$b$$$, he gets one stick with length $$$a + b$$$. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his set and can be used for the next connections.He wants to create the maximum number of sticks that have the same length. It is not necessary to make all sticks have the same length, some sticks can have the other length. How many sticks with the equal length he can create?

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case, the only line contains a single integer $$$n$$$ ($$$1 \le n \le 10^{9}$$$).

For each test case, print a single integer  — the answer to the problem.

NoteIn the third case, he can connect two sticks with lengths $$$1$$$ and $$$2$$$ and he will get one stick with length $$$3$$$. So, he will have two sticks with lengths $$$3$$$.In the fourth case, he can connect two sticks with lengths $$$1$$$ and $$$3$$$ and he will get one stick with length $$$4$$$. After that, he will have three sticks with lengths $$$\{2, 4, 4\}$$$, so two sticks have the same length, and one stick has the other length.

t = gets.to_i
t.times do
	n = gets.to_i
	p (n + 1) / 2
end

require 'set'; require 'prime'; require 'pp'
INF=Float::INFINITY; MOD=10**9+7
t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  puts (n+1)/2
end

n = gets.chomp.to_i
n.times do
    t = gets.chomp.to_i
    if t % 2 == 1 && t >= 3
        kai = t -1
        kazu = kai / 2
        puts kazu + 1
    elsif t % 2 == 1 && t < 3
        puts "1"
    elsif  t % 2 == 0 && t >= 2
        puts t / 2
    end
end

t=gets.chomp.to_i
for i in 1..t
	n=gets.chomp.to_i
	puts"#{(1+n)/2}"
end

T = gets.to_i
for i in 1..T
  x = gets.to_i
  puts (x + 1) / 2
end

def f(n)
  return 0 if n.zero?
  n.even? ? n / 2 : f(n - 1) + 1
end

gets.to_i.times do
  puts f(gets.to_i)
end

def get_res(n)
  res = n / 2
  res += 1 if (n % 2 == 1)
  return res
end

def solve
  t = gets.chomp
  (1..t.to_i).each {puts get_res(gets.chomp.to_i)}
end

solve

def f(n)
  return 1 if n == 1
  return 2 if n == 3

  n / 2
end

gets.to_i.times do
  puts f(gets.to_i)
end


You went to the store, selling $$$n$$$ types of chocolates. There are $$$a_i$$$ chocolates of type $$$i$$$ in stock.You have unlimited amount of cash (so you are not restricted by any prices) and want to buy as many chocolates as possible. However if you buy $$$x_i$$$ chocolates of type $$$i$$$ (clearly, $$$0 \le x_i \le a_i$$$), then for all $$$1 \le j < i$$$ at least one of the following must hold:  $$$x_j = 0$$$ (you bought zero chocolates of type $$$j$$$) $$$x_j < x_i$$$ (you bought less chocolates of type $$$j$$$ than of type $$$i$$$) For example, the array $$$x = [0, 0, 1, 2, 10]$$$ satisfies the requirement above (assuming that all $$$a_i \ge x_i$$$), while arrays $$$x = [0, 1, 0]$$$, $$$x = [5, 5]$$$ and $$$x = [3, 2]$$$ don't.Calculate the maximum number of chocolates you can buy.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$), denoting the number of types of chocolate. The next line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$), denoting the number of chocolates of each type.

Print the maximum number of chocolates you can buy.

NoteIn the first example, it is optimal to buy: $$$0 + 0 + 1 + 3 + 6$$$ chocolates.In the second example, it is optimal to buy: $$$1 + 2 + 3 + 4 + 10$$$ chocolates.In the third example, it is optimal to buy: $$$0 + 0 + 0 + 1$$$ chocolates.

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

p = 10**9+1
ans = 0
a.each do |x|
  x = [x, p - 1].min
  ans += x
  p = [1, x].max
end
puts ans

def main
  n = gets.chomp
  a = gets.chomp.split.map(&:to_i).reverse

  m = 0
  a.inject(nil) do |prev, x|
    if prev.nil? or prev > x
      m += x
      x
    else
      q = prev - 1 >= 0 ? prev - 1 : 0
      m += q
      q
    end
  end

  puts m
end

main


There are $$$n$$$ people sitting in a circle, numbered from $$$1$$$ to $$$n$$$ in the order in which they are seated. That is, for all $$$i$$$ from $$$1$$$ to $$$n-1$$$, the people with id $$$i$$$ and $$$i+1$$$ are adjacent. People with id $$$n$$$ and $$$1$$$ are adjacent as well.The person with id $$$1$$$ initially has a ball. He picks a positive integer $$$k$$$ at most $$$n$$$, and passes the ball to his $$$k$$$-th neighbour in the direction of increasing ids, that person passes the ball to his $$$k$$$-th neighbour in the same direction, and so on until the person with the id $$$1$$$ gets the ball back. When he gets it back, people do not pass the ball any more.For instance, if $$$n = 6$$$ and $$$k = 4$$$, the ball is passed in order $$$[1, 5, 3, 1]$$$. Consider the set of all people that touched the ball. The fun value of the game is the sum of the ids of people that touched it. In the above example, the fun value would be $$$1 + 5 + 3 = 9$$$.Find and report the set of possible fun values for all choices of positive integer $$$k$$$. It can be shown that under the constraints of the problem, the ball always gets back to the $$$1$$$-st player after finitely many steps, and there are no more than $$$10^5$$$ possible fun values for given $$$n$$$.

The only line consists of a single integer $$$n$$$ ($$$2 \leq n \leq 10^9$$$) — the number of people playing with the ball.

Suppose the set of all fun values is $$$f_1, f_2, \dots, f_m$$$. Output a single line containing $$$m$$$ space separated integers $$$f_1$$$ through $$$f_m$$$ in increasing order.

NoteIn the first sample, we've already shown that picking $$$k = 4$$$ yields fun value $$$9$$$, as does $$$k = 2$$$. Picking $$$k = 6$$$ results in fun value of $$$1$$$. For $$$k = 3$$$ we get fun value $$$5$$$ and with $$$k = 1$$$ or $$$k = 5$$$ we get $$$21$$$.   In the second sample, the values $$$1$$$, $$$10$$$, $$$28$$$, $$$64$$$ and $$$136$$$ are achieved for instance for $$$k = 16$$$, $$$8$$$, $$$4$$$, $$$10$$$ and $$$11$$$, respectively.

require "prime"
N = gets.to_i
$ans = []
QS = N.prime_division

def dig(v = 1,i = 0)
  if i == QS.size
    n = N/v
    s = (1 + ((n-1) * v + 1))*n/2
    $ans << s
    return
  end

  q,d = QS[i]
  b = 1
  (0..d).each{ |d|
    dig(v*b,i+1)
    b *= q
  }
end
dig
puts $ans.sort.join(" ")

require 'prime'

n = gets.to_i
$f = Prime.prime_division(n)
#p $f
$d = []
$x = []

a = []

def bf(depth)
    if depth == $f.size
        #p $x
        s = 1
        $f.each_with_index do |e, i|
            s *= e[0]**$x[i]
        end
        $d << s
        #p s
        return
    end
    (0..$f[depth][1]).each do |i|
        $x[depth] = i
        bf(depth + 1)
    end
end

bf(0)
$d.uniq!
#p $d
$d.each do |d|
    a1 = 1
    m = n/d
    am = a1 + (m - 1)*d
    a << (a1 + am)*m/2
#    p (a1 + am)*m/2
end

a.sort!
puts a.join(' ')


A permutation of length $$$n$$$ is an array $$$p=[p_1,p_2,\dots,p_n]$$$, which contains every integer from $$$1$$$ to $$$n$$$ (inclusive) and, moreover, each number appears exactly once. For example, $$$p=[3,1,4,2,5]$$$ is a permutation of length $$$5$$$.For a given number $$$n$$$ ($$$n \ge 2$$$), find a permutation $$$p$$$ in which absolute difference (that is, the absolute value of difference) of any two neighboring (adjacent) elements is between $$$2$$$ and $$$4$$$, inclusive. Formally, find such permutation $$$p$$$ that $$$2 \le |p_i - p_{i+1}| \le 4$$$ for each $$$i$$$ ($$$1 \le i < n$$$).Print any such permutation for the given integer $$$n$$$ or determine that it does not exist.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is described by a single line containing an integer $$$n$$$ ($$$2 \le n \le 1000$$$).

Print $$$t$$$ lines. Print a permutation that meets the given requirements. If there are several such permutations, then print any of them. If no such permutation exists, print -1.

gets.to_i.times{
    n=gets.to_i
    if n<4
        puts -1
    else
        res=[3, 1, 4, 2]
        (5..n).each{|i|
            if i.odd?
                res.unshift i
            else
                res.push i
            end
        }
        puts res*' '
    end
}


Anna is a girl so brave that she is loved by everyone in the city and citizens love her cookies. She is planning to hold a party with cookies. Now she has $$$a$$$ vanilla cookies and $$$b$$$ chocolate cookies for the party.She invited $$$n$$$ guests of the first type and $$$m$$$ guests of the second type to the party. They will come to the party in some order. After coming to the party, each guest will choose the type of cookie (vanilla or chocolate) to eat. There is a difference in the way how they choose that type:If there are $$$v$$$ vanilla cookies and $$$c$$$ chocolate cookies at the moment, when the guest comes, then  if the guest of the first type: if $$$v>c$$$ the guest selects a vanilla cookie. Otherwise, the guest selects a chocolate cookie.  if the guest of the second type: if $$$v>c$$$ the guest selects a chocolate cookie. Otherwise, the guest selects a vanilla cookie. After that:  If there is at least one cookie of the selected type, the guest eats one.  Otherwise (there are no cookies of the selected type), the guest gets angry and returns to home. Anna wants to know if there exists some order of guests, such that no one guest gets angry. Your task is to answer her question.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case, the only line contains four integers $$$a$$$, $$$b$$$, $$$n$$$, $$$m$$$ ($$$0 \le a,b,n,m \le 10^{18}, n+m \neq 0$$$).

For each test case, print the answer in one line. If there exists at least one valid order, print "Yes". Otherwise, print "No". You can print each letter in any case (upper or lower).

NoteIn the first test case, let's consider the order $$$\{1, 2, 2\}$$$ of types of guests. Then:  The first guest eats a chocolate cookie. After that, there are $$$2$$$ vanilla cookies and $$$1$$$ chocolate cookie.  The second guest eats a chocolate cookie. After that, there are $$$2$$$ vanilla cookies and $$$0$$$ chocolate cookies.  The last guest selects a chocolate cookie, but there are no chocolate cookies. So, the guest gets angry. So, this order can't be chosen by Anna.Let's consider the order $$$\{2, 2, 1\}$$$ of types of guests. Then:  The first guest eats a vanilla cookie. After that, there is $$$1$$$ vanilla cookie and $$$2$$$ chocolate cookies.  The second guest eats a vanilla cookie. After that, there are $$$0$$$ vanilla cookies and $$$2$$$ chocolate cookies.  The last guest eats a chocolate cookie. After that, there are $$$0$$$ vanilla cookies and $$$1$$$ chocolate cookie. So, the answer to this test case is "Yes".In the fifth test case, it is illustrated, that the number of cookies ($$$a + b$$$) can be equal to zero, but the number of guests ($$$n + m$$$) can't be equal to zero.In the sixth test case, be careful about the overflow of $$$32$$$-bit integer type.

require 'set'; require 'prime'; require 'pp'
INF=Float::INFINITY; MOD=10**9+7
t = gets.chomp.to_i
t.times do
  v,c,n,m = gets.chomp.split.map(&:to_i)
  v,c=c,v if v > c
  if v < m
    puts 'No'
  else
    v -= m
    if v + c < n
      puts 'No'
    else
      puts 'Yes'
    end
  end
end

s = gets.chomp.to_i
s.times do
    a, b, n, m = gets.chomp.split(" ").map(&:to_i)
    if a > b
        kazu = b - m
        if kazu < 0
            #no += 1
            puts "No"
            next
        elsif kazu >= 0
            all = kazu + a
            if all >= n
                #yes += 1
                puts "Yes"
                next
            else
                puts "No"
                next
                #no += 1
            end
        end
    elsif a < b
        kazu = a - m
        if kazu < 0
            #no += 1
            puts "No"
            next
        elsif kazu >= 0
            all = kazu + b
            if all >= n
                puts "Yes"
                next
                #yes += 1
            else
                puts "No"
                next
                #no += 1
            end
        end
    elsif a == b
        kazu = a - m
        if kazu < 0
            puts "No"
            next
            #no += 1
        elsif kazu >= 0
            all = kazu + b
            if all >= n
                puts "Yes"
                next
                #yes += 1
            else
                puts "No"
                next
                #no += 1
            end
        end
    end
end


Three swimmers decided to organize a party in the swimming pool! At noon, they started to swim from the left side of the pool.It takes the first swimmer exactly $$$a$$$ minutes to swim across the entire pool and come back, exactly $$$b$$$ minutes for the second swimmer and $$$c$$$ minutes for the third. Hence, the first swimmer will be on the left side of the pool after $$$0$$$, $$$a$$$, $$$2a$$$, $$$3a$$$, ... minutes after the start time, the second one will be at $$$0$$$, $$$b$$$, $$$2b$$$, $$$3b$$$, ... minutes, and the third one will be on the left side of the pool after $$$0$$$, $$$c$$$, $$$2c$$$, $$$3c$$$, ... minutes.You came to the left side of the pool exactly $$$p$$$ minutes after they started swimming. Determine how long you have to wait before one of the swimmers arrives at the left side of the pool.

The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contains test case descriptions, one per line. Each line contains four integers $$$p$$$, $$$a$$$, $$$b$$$ and $$$c$$$ ($$$1 \leq p, a, b, c \leq 10^{18}$$$), time in minutes after the start, when you came to the pool and times in minutes it take the swimmers to cross the entire pool and come back.

For each test case, output one integer — how long you have to wait (in minutes) before one of the swimmers arrives at the left side of the pool.

NoteIn the first test case, the first swimmer is on the left side in $$$0, 5, 10, 15, \ldots$$$ minutes after the start time, the second swimmer is on the left side in $$$0, 4, 8, 12, \ldots$$$ minutes after the start time, and the third swimmer is on the left side in $$$0, 8, 16, 24, \ldots$$$ minutes after the start time. You arrived at the pool in $$$9$$$ minutes after the start time and in a minute you will meet the first swimmer on the left side.In the second test case, the first swimmer is on the left side in $$$0, 6, 12, 18, \ldots$$$ minutes after the start time, the second swimmer is on the left side in $$$0, 10, 20, 30, \ldots$$$ minutes after the start time, and the third swimmer is on the left side in $$$0, 9, 18, 27, \ldots$$$ minutes after the start time. You arrived at the pool $$$2$$$ minutes after the start time and after $$$4$$$ minutes meet the first swimmer on the left side.In the third test case, you came to the pool $$$10$$$ minutes after the start time. At the same time, all three swimmers are on the left side. A rare stroke of luck!In the fourth test case, all swimmers are located on the left side in $$$0, 9, 18, 27, \ldots$$$ minutes after the start time. You arrived at the pool $$$10$$$ minutes after the start time and after $$$8$$$ minutes meet all three swimmers on the left side.

inputs = STDIN.read.strip.split("\n")
inputs.shift

inputs.each do |inp|
    p, a, b, c = inp.split(' ').map(&:to_i)

    r = []
    [a, b, c].each do |n|
        r << ((p / n) + [p % n, 1].min) * n
    end

    puts r.min - p
end

inputs = STDIN.read.strip.split("\n")
inputs.shift

inputs.each do |inp|
    p, a, b, c = inp.split(' ').map(&:to_i)

    r = []
    [a, b, c].each do |n|
        r << ((p / n) + (p % n == 0 ? 0 : 1)) * n
    end

    puts r.min - p
end

n = gets.to_i
a = []

def get_min(arr)
	[compare(arr[0],arr[1]), compare(arr[0],arr[2]), compare(arr[0],arr[3])].min
end

def compare(a,b)
  return b-a if a < b

	-a % b
end

(0..n-1).each do |x|
	q = gets.chomp.split().map { |e| e.to_i  }
	a.append(get_min(q))
end

a.each do |x|
 p x
end

f = lambda {|x,p| p%x==0? 0:(x-(p%x))}
gets.to_i.times  {
	p,a,b,c = gets.split.map(&:to_i)
	puts [a,b,c].map{|x| f.call(x,p)}.min
}

t = gets.to_i
ans = []
t.times do
  p,a,b,c = gets.chomp.split(" ").map(&:to_i)
  min = [((p+a-1)/a)*a-p,((p+b-1)/b)*b-p,((p+c-1)/c)*c-p].min
  ans << min
end
puts ans

gets.to_i.times do
  q,a,b,c=gets.split.map(&:to_i)
  puts [(a-q%a)%a,(b-q%b)%b,(c-q%c)%c].min
end

inputs = STDIN.read.strip.split("\n")
inputs.shift

inputs.each do |inp|
    p, a, b, c = inp.split(' ').map(&:to_i)

    r = []
    [a, b, c].each do |n|
        r << (p / n) * n
    end

    puts r.min - p
end

inputs = STDIN.read.strip.split("\n")
inputs.shift

inputs.each do |inp|
    p, a, b, c = inp.split(' ').map(&:to_i)

    r = []
    [a, b, c].each do |n|
        r << (p.to_f / n.to_f).ceil * n
    end

    puts r.min - p
end

n = gets.to_i
a = []

def get_min(arr)
	[compare(arr[0],arr[1]), compare(arr[0],arr[2]), compare(arr[0],arr[3])].min
end

def compare(a,b)
  return b-a if a < b

  while a / b != 0
  	b+=b
  end

	b % a
end

(0..n-1).each do |x|
	q = gets.chomp.split().map { |e| e.to_i  }
	a.append(get_min(q))
end

a.each do |x|
 p x
end


The city Valera lives in is going to hold elections to the city Parliament.The city has n districts and n - 1 bidirectional roads. We know that from any district there is a path along the roads to any other district. Let's enumerate all districts in some way by integers from 1 to n, inclusive. Furthermore, for each road the residents decided if it is the problem road or not. A problem road is a road that needs to be repaired.There are n candidates running the elections. Let's enumerate all candidates in some way by integers from 1 to n, inclusive. If the candidate number i will be elected in the city Parliament, he will perform exactly one promise — to repair all problem roads on the way from the i-th district to the district 1, where the city Parliament is located.Help Valera and determine the subset of candidates such that if all candidates from the subset will be elected to the city Parliament, all problem roads in the city will be repaired. If there are several such subsets, you should choose the subset consisting of the minimum number of candidates.

The first line contains a single integer n (2 ≤ n ≤ 105) — the number of districts in the city. Then n - 1 lines follow. Each line contains the description of a city road as three positive integers xi, yi, ti (1 ≤ xi, yi ≤ n, 1 ≤ ti ≤ 2) — the districts connected by the i-th bidirectional road and the road type. If ti equals to one, then the i-th road isn't the problem road; if ti equals to two, then the i-th road is the problem road. It's guaranteed that the graph structure of the city is a tree.

In the first line print a single non-negative number k — the minimum size of the required subset of candidates. Then on the second line print k space-separated integers a1, a2, ... ak — the numbers of the candidates that form the required subset. If there are multiple solutions, you are allowed to print any of them.

require 'set'
n=gets.to_i
h=Hash.new{|h,k|h[k]={}}
(n-1).times do
  a,b,t=gets.split.map(&:to_i)
  h[a][b]=h[b][a]=t
end
s=[[1,0,1]]
r=Set.new
n=Set.new
while (x=s.last)
  if x[1]==0
    h[x[0]].each{|k,v|s.push([k,0,v]);h[k].delete(x[0])}
    x[1]=1
  else
    s.pop
    if h[x[0]].any?{|k,v|n.include?(k)}
      n<<x[0]
    else
      if x[2]==2
        n<<x[0]
        r<<x[0]
      end
    end
  end
end
puts r.size, r.to_a*' '


Baby Ehab is known for his love for a certain operation. He has an array $$$a$$$ of length $$$n$$$, and he decided to keep doing the following operation on it:   he picks $$$2$$$ adjacent elements; he then removes them and places a single integer in their place: their bitwise XOR. Note that the length of the array decreases by one. Now he asks you if he can make all elements of the array equal. Since babies like to make your life harder, he requires that you leave at least $$$2$$$ elements remaining.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 15$$$) — the number of test cases you need to solve. The first line of each test case contains an integers $$$n$$$ ($$$2 \le n \le 2000$$$) — the number of elements in the array $$$a$$$. The second line contains $$$n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$0 \le a_i < 2^{30}$$$) — the elements of the array $$$a$$$.

If Baby Ehab can make all elements equal while leaving at least $$$2$$$ elements standing, print "YES". Otherwise, print "NO".

NoteIn the first sample, he can remove the first $$$2$$$ elements, $$$0$$$ and $$$2$$$, and replace them by $$$0 \oplus 2=2$$$. The array will be $$$[2,2]$$$, so all the elements are equal.In the second sample, there's no way to make all the elements equal.

def solve(a)
  xorall = a.reduce(0) {|acc, x| acc ^ x }
  tmp = 0
  lxor = 0.upto(a.size - 1).to_a.map {|i| tmp ^= a[i] }
  tmp = 0
  rxor = (a.size - 1).downto(0).to_a.map {|i| tmp ^= a[i] }

  # possible split in two parts
  1.upto(a.size - 1) do |lcount|
    return true if lxor[lcount - 1] == rxor[a.size - lcount - 1]
  end

  # possible split in three parts
  1.upto(a.size - 2) do |lcount|
    next if lxor[lcount - 1] != xorall
    1.upto(a.size - lcount - 1) do |rcount|
      next if rxor[rcount - 1] != xorall
      return true
    end
  end

  return false
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  a = gets.to_s.split.map {|x| x.to_i }

  if solve(a)
    printf("YES\n")
  else
    printf("NO\n")
  end
end

def solve(a)
  if a.size == 1
    return a[0] == 0
  end
  a0 = a[0]
  a.map! {|x| x ^ a0 }
  return solve(a[1 .. -1])
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  a = gets.to_s.split.map {|x| x.to_i }
  b = a.reverse

  if solve(a) || solve(b)
    printf("YES\n")
  else
    printf("NO\n")
  end
end

def solve(a)
  if a.size == 1
    return a[0] == 0
  end
  a0 = a[0]
  a.map! {|x| x ^ a0 }
  return solve(a[1 .. -1])
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  a = gets.to_s.split.map {|x| x.to_i }

  if solve(a)
    printf("YES\n")
  else
    printf("NO\n")
  end
end

def solve(a)
  a0 = a[0]
  i = 0
  i += 1 while i <= a.size - 1 && a[i] == a0

  return true if i == a.size - 1

  i += 1

  tmp = 0
  i.upto(a.size - 1) do |x|
    tmp ^= x
  end

  return true if a0 == tmp

  return false
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  a = gets.to_s.split.map {|x| x.to_i }

  if solve(a) || solve(a.reverse)
    printf("YES\n")
  else
    printf("NO\n")
  end
end

def solve(a)
  a0 = a[0]
  i = 0
  i += 1 while i <= a.size - 1 && a[i] == a0

  return true if i == a.size - 1

  tmp = 0
  i.upto(a.size - 1) do |x|
    tmp ^= x
  end

  return true if a0 == tmp

  return false
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  a = gets.to_s.split.map {|x| x.to_i }

  if solve(a) || solve(a.reverse)
    printf("YES\n")
  else
    printf("NO\n")
  end
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  a = gets.to_s.split.map {|x| x.to_i }

  good = true

  0.upto(30) do |i|
    bitmask = 1 << i
    cnt = 0
    a.each {|x| cnt += 1 if (x & bitmask) != 0 }
    good = false if cnt % 2 == 1
  end

  printf("%s\n", good ? "YES" : "NO")
end


String x is an anagram of string y, if we can rearrange the letters in string x and get exact string y. For example, strings "DOG" and "GOD" are anagrams, so are strings "BABA" and "AABB", but strings "ABBAC" and "CAABA" are not.You are given two strings s and t of the same length, consisting of uppercase English letters. You need to get the anagram of string t from string s. You are permitted to perform the replacing operation: every operation is replacing some character from the string s by any other character. Get the anagram of string t in the least number of replacing operations. If you can get multiple anagrams of string t in the least number of operations, get the lexicographically minimal one.The lexicographic order of strings is the familiar to us "dictionary" order. Formally, the string p of length n is lexicographically smaller than string q of the same length, if p1 = q1, p2 = q2, ..., pk - 1 = qk - 1, pk < qk for some k (1 ≤ k ≤ n). Here characters in the strings are numbered from 1. The characters of the strings are compared in the alphabetic order.

The input consists of two lines. The first line contains string s, the second line contains string t. The strings have the same length (from 1 to 105 characters) and consist of uppercase English letters.

In the first line print z — the minimum number of replacement operations, needed to get an anagram of string t from string s. In the second line print the lexicographically minimum anagram that could be obtained in z operations.

NoteThe second sample has eight anagrams of string t, that can be obtained from string s by replacing exactly two letters: "ADBADC", "ADDABC", "CDAABD", "CDBAAD", "CDBADA", "CDDABA", "DDAABC", "DDBAAC". These anagrams are listed in the lexicographical order. The lexicographically minimum anagram is "ADBADC".

a,b=IO.readlines "input.txt"
a.chomp!
b.chomp!
out=File.open("output.txt","w")
h={}
ha={}
b.each_char{|c| h[c]=(h.key? c) ? h[c]+1 : 1}
a.each_char{|c| h[c]=(h.key? c) ? h[c]-1 : -1;  ha[c]=(ha.key? c) ? ha[c]+1 : 1}
p=h.keys.sort.select{|c| h[c]>0}.reverse
out<<p.inject(0){|s,i| s+h[i] if h[i]>0}
out<<"\n"
o=""
a.size.times{|i|
	ha[a[i]]-=1
	break if p.size==0
	if h[a[i]]<0&&(p[-1]<a[i]||ha[a[i]]<(-h[a[i]]))
		h[a[i]]+=1
		a[i]=p[-1]
		h[p[-1]]-=1
	end
	p.pop if h[p[-1]]==0
}
out<<a
out.close

a,b=IO.readlines "input.txt"
a.chomp!
b.chomp!
out=File.open("output.txt","w")
h={}
b.each_char{|c| h[c]=(h.key? c) ? h[c]+1 : 1}
a.each_char{|c| h[c]=(h.key? c) ? h[c]-1 : -1}
p=h.keys.sort.select{|c| h[c]>0}.reverse
out<<p.inject(0){|s,i| s+h[i] if h[i]>0}
out<<"\n"
o=""
a.size.times{|i|
	break if p.size==0
	if h[a[i]]<0&&a[i]>p[-1]
		h[a[i]]+=1
		a[i]=p[-1]
		h[p[-1]]-=1
	end
	p.pop if h[p[-1]]==0
}
p.reverse!
(a.size-1).downto(0).each{|i|
	break if p.size==0
	if h[a[i]]<0
		a[i]=p[-1]
		h[p[-1]]-=1
	end
	p.pop if h[p[-1]]==0
}
out<<a
out.close


Santa Claus has Robot which lives on the infinite grid and can move along its lines. He can also, having a sequence of m points p1, p2, ..., pm with integer coordinates, do the following: denote its initial location by p0. First, the robot will move from p0 to p1 along one of the shortest paths between them (please notice that since the robot moves only along the grid lines, there can be several shortest paths). Then, after it reaches p1, it'll move to p2, again, choosing one of the shortest ways, then to p3, and so on, until he has visited all points in the given order. Some of the points in the sequence may coincide, in that case Robot will visit that point several times according to the sequence order.While Santa was away, someone gave a sequence of points to Robot. This sequence is now lost, but Robot saved the protocol of its unit movements. Please, find the minimum possible length of the sequence.

The first line of input contains the only positive integer n (1 ≤ n ≤ 2·105) which equals the number of unit segments the robot traveled. The second line contains the movements protocol, which consists of n letters, each being equal either L, or R, or U, or D. k-th letter stands for the direction which Robot traveled the k-th unit segment in: L means that it moved to the left, R — to the right, U — to the top and D — to the bottom. Have a look at the illustrations for better explanation.

The only line of input should contain the minimum possible length of the sequence.

NoteThe illustrations to the first three tests are given below.  The last example illustrates that each point in the sequence should be counted as many times as it is presented in the sequence.

require 'set'
n = gets.chomp
s = gets.chomp
rev = {"U" => "D", "D" => "U", "L" => "R", "R" => "L"}
otp = 0
set = Set.new
s.each_char do |i|
  x = i
  if(set.include?(rev[x])) || ((set.size() == 2)&& !(set.include?(x)))
    otp +=1
    set.clear
  end
  set.add(x)
end
if(set.size>0)
  otp +=1
end
puts otp

n = STDIN.gets.chomp.to_i
q = STDIN.gets.chomp

a = "LRUD"
b = "RLDU"

f = -1
s = -1

ans = 1

i = 0
while i < n do
  c = q[i]
  if f == -1
    f = c
  elsif s == -1
    if a.index(f) == b.index(c)
      ans += 1
      f = c
    elsif c != f
      s = c
    end
  elsif c != f && c != s
    ans += 1
    f = c
    s = -1
  end
  i += 1
end

puts ans

n = gets.to_i
s = gets.strip.split("")
sol = 1
h = "_"
v = "_"
for x in s
    if "RL".match(x) then
        if h != "_" && h != x then
            sol += 1
            v = "_"
        end
        h = x
    else
        if v != "_" && v != x then
            sol += 1
            h = "_"
        end
        v = x
    end
end
puts sol

n = gets.chomp
s = gets.chomp
rev = {}
rev['U'] = 'D'
rev['D'] = 'U'
rev['R'] = 'L'
rev['L'] = 'R'
res = 0
require 'set'
st = Set.new
s.each_char do |i|
    c = i
    if ((st.size() == 2 && !(st.include?(c))) || st.include?(rev[c]))
        res += 1
        st.clear
    end
    st.add(c)
end
if (st.size() > 0)
    res += 1
end
puts res


Convexity of a set of points on the plane is the size of the largest subset of points that form a convex polygon. Your task is to build a set of n points with the convexity of exactly m. Your set of points should not contain three points that lie on a straight line.

The single line contains two integers n and m (3 ≤ m ≤ 100, m ≤ n ≤ 2m).

If there is no solution, print "-1". Otherwise, print n pairs of integers — the coordinates of points of any set with the convexity of m. The coordinates shouldn't exceed 108 in their absolute value.

a,b=gets.split.map &:to_i
exit !puts(-1)if a>4&&b<4
(1..b).each{|i|puts i,i*i}
(1..a-b).each{|i|puts i,-i*i-318000}

n, m = gets.split.map(&:to_i)
if m == 3 and n >= 5
    puts -1
else
    INF = 100000
    x, y = [], []
    1.upto(m) do |i|
        x << i
        y << INF + i * i
    end
    1.upto(m) do |i|
        x << i
        y << -INF - i * i
    end
    n.times do |i|
        puts "#{x[i]} #{y[i]}"
    end
end

a,b=gets.split.map &:to_i
exit !puts(-1)if a>4&&b<4
(1..b).each{|i|puts i,i*i}
(1..a-b).each{|i|puts i,-i*i-1000000}

n, m = gets.split.map(&:to_i)
if m == 3 and n >= 5
    puts -1
else
    INF = 100000000
    x, y = [], []
    m.times do |i|
        x << 1 + i
        y << 1 + i * i
    end
    m.times do |i|
        x << -1 - i
        y << -1 - i * i
    end
    n.times do |i|
        puts "#{x[i]} #{y[i]}"
    end
end

n, m = gets.split.map(&:to_i)
if m == 3 and n >= 5
    puts -1
else
    INF = 100000000
    x, y = [], []
    m.times do |i|
        x << i
        y << 1 + i * i
    end
    m.times do |i|
        x << i
        y << -1 - i * i
    end
    n.times do |i|
        puts "#{x[i]} #{y[i]}"
    end
end

n, m = gets.split.map(&:to_i)
if m == 3 and n >= 5
    puts -1
else
    INF = 100000000
    x, y = [], []
    m.times do |i|
        x << 1 + i
        y << INF - i * i
    end
    m.times do |i|
        x << -1 - i
        y << -INF + i * i
    end
    n.times do |i|
        puts "#{x[i]} #{y[i]}"
    end
end

a,b=gets.split.map &:to_i
exit !puts(-1)if a>4&&b<4
(1..b).each{|i|puts i,i*i}
(1..a-b).each{|i|puts i,-i*i-237}

a,b=gets.split.map &:to_i
exit !puts(-1)if a>4&&b<4
(1..b).each{|i|puts i,i*i}
(1..a-b).each{|i|puts i,-i*i-318}

a,b=gets.split.map &:to_i
exit !puts(-1)if a>4&&b<4
(1..b).each{|i|puts i,i*i}
(1..a-b).each{|i|puts i+1,-i*i}

a,b=gets.split.map &:to_i
exit !puts(-1)if a>4&&b<4
(1..b).each{|i|puts i,i*i}
(1..a-b).each{|i|puts i,-i*i-2379}

a,b=gets.split.map &:to_i
exit !puts(-1)if a>4&&b<4
(1..b).each{|i|puts i,i*i}
(1..a-b).each{|i|puts i,-i*i-1}

a,b=gets.split.map &:to_i
exit !puts(-1)if a>4&&b<4
(1..b).each{|i|puts i,i*i}
(1..a-b).each{|i|puts i,-i*i}

a,b=gets.split.map &:to_i
exit !puts(-1)if a>4&&b<4
(1..b).each{|i|puts i,i*i}
(1..a-b).each{|i|puts i+10000,-i*i}


The Fair Nut likes kvass very much. On his birthday parents presented him $$$n$$$ kegs of kvass. There are $$$v_i$$$ liters of kvass in the $$$i$$$-th keg. Each keg has a lever. You can pour your glass by exactly $$$1$$$ liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by $$$s$$$ liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible.Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by $$$s$$$ liters of kvass.

The first line contains two integers $$$n$$$ and $$$s$$$ ($$$1 \le n \le 10^3$$$, $$$1 \le s \le 10^{12}$$$) — the number of kegs and glass volume. The second line contains $$$n$$$ integers $$$v_1, v_2, \ldots, v_n$$$ ($$$1 \le v_i \le 10^9$$$) — the volume of $$$i$$$-th keg.

If the Fair Nut cannot pour his glass by $$$s$$$ liters of kvass, print $$$-1$$$. Otherwise, print a single integer — how much kvass in the least keg can be.

NoteIn the first example, the answer is $$$3$$$, the Fair Nut can take $$$1$$$ liter from the first keg and $$$2$$$ liters from the third keg. There are $$$3$$$ liters of kvass in each keg.In the second example, the answer is $$$2$$$, the Fair Nut can take $$$3$$$ liters from the first keg and $$$1$$$ liter from the second keg.In the third example, the Fair Nut can't pour his cup by $$$7$$$ liters, so the answer is $$$-1$$$.

n,s,*v=$<.read.split.map &:to_i
p [[(v.reduce(:+)-s)/n,*v].min,-1].max

n,s = gets.split.map(&:to_i)
v = gets.split.map(&:to_i)
min = 0
max = 10**9+10
while min < max-1
    mid = min+(max-min)/2
    ret = 0
    n.times do |i|
        ret += v[i]-mid if mid < v[i]
    end
    if ret < s
        max = mid-1
    else
        min = mid
    end
end

[max,min].each do |i|
    ret = 0
    n.times do |j|
        ret += v[j]-i if v[j] > i
    end
    if ret >= s
        ans = 10**9
        n.times do |j|
            ans = [ans,i,v[j]].min
        end
        puts ans
        exit
    end
end
puts -1

n,s = gets.split.map(&:to_i)
v = gets.split.map(&:to_i)
min = 0
max = 10**9+10
50.times do
    mid = min+(max-min)/2
    ret = 0
    n.times do |i|
        ret += v[i]-mid if mid < v[i]
    end
    if ret < s
        max = mid-1
    else
        min = mid
    end
end
for i in min..max
    ret = 0
    n.times do |j|
        ret += v[j]-i if i < v[j]
    end
    if ret >= s
        puts i
        exit
    end
end
puts -1

n,s = gets.split.map(&:to_i)
v = gets.split.map(&:to_i)
min = 0
max = 10**9+10
50.times do
    mid = min+(max-min)/2
    ret = 0
    n.times do |i|
        ret += v[i]-mid if mid < v[i]
    end
    if ret < s
        max = mid-1
    else
        min = mid
    end
end

[max,min].each do |i|
    ret = 0
    n.times do |j|
        ret += v[j]-i if v[j] > i
    end
    if ret >= s
        puts i
        exit
    end
end
puts -1

n,s = gets.split.map(&:to_i)
v = gets.split.map(&:to_i)
min = -1
max = 10**9+10
while min < max-1
    mid = min+(max-min)/2
    ret = 0
    n.times do |i|
        ret += v[i]-mid if mid < v[i]
    end
    if ret < s
        max = mid-1
    else
        min = mid
    end
end
p min

n,s = gets.split.map(&:to_i)
v = gets.split.map(&:to_i)
min = 0
max = 10**9+10
while min < max-1
    mid = min+(max-min)/2
    ret = 0
    n.times do |i|
        ret += v[i]-mid if mid < v[i]
    end
    if ret < s
        max = mid-1
    else
        min = mid
    end
end

[max,min].each do |i|
    ret = 0
    n.times do |j|
        ret += v[j]-i if v[j] > i
    end
    if ret >= s
        puts i
        exit
    end
end
puts -1

n,s = gets.split.map(&:to_i)
v = gets.split.map(&:to_i)
min = 0
max = 10**9+10
50.times do
    mid = min+(max-min)/2
    ret = 0
    n.times do |i|
        ret += v[i]-mid if mid < v[i]
    end
    if ret < s
        max = mid-1
    else
        min = mid
    end
end
for i in min..max
    ret = 0
    n.times do |j|
        ret += v[j]-i if i < v[j]
    end
    if ret == s
        puts i
        exit
    elsif ret > s
        puts i+1
        exit
    end
end
puts -1


You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest.Given the list of strings, output the lexicographically smallest concatenation.

The first line contains integer n — the number of strings (1 ≤ n ≤ 5·104). Each of the next n lines contains one string ai (1 ≤ |ai| ≤ 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5·104.

Print the only string a — the lexicographically smallest string concatenation.

n = gets.chomp.to_i
arr = []
n.times do
  arr << gets.chomp
end

puts arr.sort{|a, b| a + b <=> b + a}.join("")

#!/usr/bin/ruby
n=gets.to_i
puts $<.map{|e|e.chomp+'~'}.sort.map{|e|e[0..-2]}*''


Alice and Bob like games. And now they are ready to start a new game. They have placed n chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with equal speed). When the player consumes a chocolate bar, he immediately starts with another. It is not allowed to eat two chocolate bars at the same time, to leave the bar unfinished and to make pauses. If both players start to eat the same bar simultaneously, Bob leaves it to Alice as a true gentleman.How many bars each of the players will consume?

The first line contains one integer n (1 ≤ n ≤ 105) — the amount of bars on the table. The second line contains a sequence t1, t2, ..., tn (1 ≤ ti ≤ 1000), where ti is the time (in seconds) needed to consume the i-th bar (in the order from left to right).

Print two numbers a and b, where a is the amount of bars consumed by Alice, and b is the amount of bars consumed by Bob.

n = gets.chomp.to_i
ar = gets.chomp.split(/ /).map!{|x| x.to_i}

ai = 1
bi = n-1
at = ar[0]
bt = 0
while ai <= bi
	if at <= bt
		at += ar[ai]
		ai += 1
	else
		bt += ar[bi]
		bi -= 1
	end
end

puts ai.to_s + " " + (n-(bi+1)).to_s

n=STDIN.gets.chomp.to_i
t=STDIN.gets.chomp.split
t.map! {|x| x.to_i}
alice=0
bob=n-1
a=0
b=0
while true do
  consumed=t[alice]<t[bob]?t[alice]:t[bob]
  t[alice]-=consumed
  t[bob]-=consumed
  next_alice=t[alice]==0?1:0
  next_bob=t[bob]==0?-1:0
  a+=next_alice
  b+=-1*next_bob
  alice+=next_alice
  bob+=next_bob
  if alice<bob then next end
  if next_alice==0 && next_bob==-1 then a+=1;break
  elsif next_alice==1 && next_bob==0 then b+=1;break
  elsif alice==bob then a+=1;break
  else break
  end
end
print("#{a} #{b}\n")

n=STDIN.gets.to_i
t=STDIN.gets.split.map(&:to_i)
sum=[0]
t.each{|i|
        sum.push(sum[sum.length-1]+i)
}
sum+=[9999999999999]

rsum=[0]
t.reverse.each{|i|
        rsum.push(rsum[rsum.length-1]+i)
}
rsum+=[999999999999]
a1=a2=0
loop {
        t1=sum[0]
        t2=rsum[0]
        if t1<=t2 then
                sum.shift
                a1+=1
        else
                rsum.shift
                a2+=1
        end
        break if sum.size+rsum.size==n+2
}
puts "#{a1-1} #{a2-1}"

bar_num = gets.chomp.to_i
arr = []
arr = gets.split
arr.collect! {|x| x.to_i}

sum_alice = 0
sum_bob = 0
count_alice = 0
count_bob = 0

while arr[0] != nil
    if sum_alice <= sum_bob
        sum_alice += arr.shift
        count_alice += 1
    else
        sum_bob += arr.pop
        count_bob += 1
    end
end
puts count_alice.to_s + ' ' + count_bob.to_s

def run(input = STDIN.read)
  times = input.split("\n").last.split.map(&:to_i)

  i = 0
  j = times.size - 1
  alisa_time = 0
  bob_time = 0

  while j > i
    if bob_time > alisa_time
      while bob_time > alisa_time && j > i
        alisa_time += times[i]
        i += 1
      end
    else
      while bob_time <= alisa_time && j > i
        bob_time += times[j]
        j -= 1
      end
    end
  end

  if bob_time < alisa_time
    i -= 1
  end

  puts [i + 1, times.size - i - 1].join(' ')
end
run

num = gets.chomp.to_i
arr = gets.split.map(&:to_i)
if num == 1 then
	puts "1 0"
	exit
end
l = 0
r = num - 1
lcurr = arr[0]
rcurr = arr[num - 1]
while l + 1 < r do
	if lcurr <= rcurr then
		rcurr -= lcurr
		l += 1
		lcurr = arr[l]
	else
		lcurr -= rcurr
		r -= 1
		rcurr = arr[r]
	end
end
print l + 1, " ", num - r

n=gets.chomp.to_i
m=gets.chomp.split.map{|i| i.to_i}
if n==1
  puts "1 0"
  exit
end
if n==2
  puts "1 1"
  exit
end
a=0
b=n-1
ta=m[a]
tb=m[b]
while true
  if ta>tb
    b-=1
    ta=ta-tb
    tb=m[b]
  else
    a+=1
    tb=tb-ta
    ta=m[a]
  end
  if b-a==1
    break
  end
end
puts ""+(a+1).to_s+" "+(n-b).to_s

n = gets.to_i
t = gets.split.map(&:to_i)
a = 0
b = n-1
asum = 0
bsum = 0
while a <= b do
  if asum <= bsum then
    asum += t[a]
    a += 1
  else
    bsum += t[b]
    b -= 1
  end
end
print a, " ", n-a
puts

##
# 6C
# Author: Sammy Teahan
#

if __FILE__ == $0
  bars = gets.to_i
  time = gets.split.map(&:to_i)
  aliceCount = 0;
  bobCount = 0;
  aliceTotal = 0;
  bobTotal = 0;
  start = 0;
  last = bars - 1

  while start <= last do
    if aliceTotal <= bobTotal
      aliceTotal += time[start]
      start += 1
      aliceCount += 1
    else
      bobTotal += time[last]
      last -= 1
      bobCount += 1
    end
  end

  puts "#{aliceCount} #{bobCount}"
end

N = gets.to_i
consumeTime = gets.split.map{ |x| x.to_i}
a = 1
a_time = consumeTime.shift
b = 0
b_time = 0
until consumeTime.empty? do
  if a_time>b_time
    b += 1
    b_time += consumeTime.pop
  else
    a += 1
    a_time += consumeTime.shift
  end
end
print a," ",b,"\n"

n = gets.to_i
times = gets.split.map(&:to_i)
alice = 0
bob = n - 1
alice_time, bob_time = 0, 0

while alice <= bob
	if alice_time <= bob_time
		alice_time += times[alice]
		alice += 1
	else
		bob_time += times[bob]
		bob -= 1
	end
end

puts [alice, n - alice].join(' ')

n = gets.to_i
a = gets.split(/\s/).map {|x| x.to_i}

a1 = 0
a2 = 0
t1 = 0
t2 = 0
size = a.size
if size == 1
  puts "1 0"
else
  i = 0
  j = size-1
  while i < j
    if t1 > t2
      while t1 > t2 and i < j
        a2 += 1
        t2 += a[j]
        j -= 1
      end
    elsif t2 > t1
      while t2 > t1 and i < j
        a1 += 1
        t1 += a[i]
        i += 1
      end
    else
      a1 += 1
      a2 += 1
      t1 += a[i]
      t2 += a[j]
      i += 1
      j -= 1
    end
  end

  if a1+a2 != n
    if t1 <= t2
      a1 += 1
    else
      a2 += 1
    end
  end
  puts "#{a1} #{a2}"
end

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

i, j = 0, a.size - 1

if a.size > 1
  while true
    if a[i] == a[j]
      a[i] = a[j] = 0
      i += 1
      j -= 1
      if i > j
        break
      elsif i == j
        i += 1
        break
      end
    elsif a[i] > a[j]
      a[i] -= a[j]
      j -= 1
      if i == j
        i += 1
        break
      end
    elsif a[i] < a[j]
      a[j] -= a[i]
      i += 1
      if i == j
        j -= 1
        break
      end
    end
  end
else
  i = 1
  j = a.size - 1
end

puts "#{i} #{(a.size - 1) - j}"

# Discard input count
gets
# This gives us candy bars as an array of ints.
bars = gets.split.map { |a| a.to_i }
# Next we find the sum
sum = bars.inject(0,:+)
# Imagine the chocolate bars laid end to end on a line. We know that if both Bob and Alice keep eating at the same rate, The coordinate they will meet at is half the sum.
middle = sum / 2.0
# Now we need to find out which bar this is. If it is a clean split between two bars, we can simply return.
alice_dist = 0
alice_dist_to_middle_bar_start = nil
middle_bar_index = nil
bars.each_with_index do |bar,i|
  # Check if, by adding the distance, we surpass this bar.
  dist_to_end_of_bar = alice_dist + bar
  if(dist_to_end_of_bar > middle)
    middle_bar_index = i
    alice_dist_to_middle_bar_start = alice_dist
    break
  elsif (dist_to_end_of_bar == middle)
    # It's a clean split! alice eats [0..i] bars so add '1'
    puts (i+1).to_s + " " + (bars.length - (i+1)).to_s
    exit
  end
  alice_dist += bar
end

#And now we know that the middle bar is 'i', and that alice's distance from it. From there we can get Bob's distance.
bob_dist_to_middle_bar_end = sum - (alice_dist_to_middle_bar_start + bars[middle_bar_index])

if(alice_dist_to_middle_bar_start <= bob_dist_to_middle_bar_end)
  puts (1 + middle_bar_index).to_s + " " + (bars.length - (1 + middle_bar_index)).to_s
else
  puts (middle_bar_index).to_s + ' ' + (bars.length - middle_bar_index).to_s
end

n = gets.to_i

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

if a.size == 1
	print 1,' ', 0
	exit
end

l,r = 0, a.size-1

while l+1 < r
	# print [l,r],"\n"
	min = [a[l],a[r]].min
	a[l] -= min
	a[r] -= min

	if a[l] == 0 and l < r-1
		l+=1
	end
	if a[r] == 0 and r-1 > l
		r-=1
	end
end

print l+1, ' ', a.size - r

n=STDIN.gets.chomp.to_i
t=STDIN.gets.chomp.split
t.map! {|x| x.to_i}
alice=0
bob=n-1
a=0
b=0
while true do
  consumed=t[alice]<t[bob]?t[alice]:t[bob]
  t[alice]-=consumed
  t[bob]-=consumed
  next_alice=t[alice]==0?1:0
  next_bob=t[bob]==0?-1:0
  a+=next_alice
  b+=-1*next_bob
  alice+=next_alice
  bob+=next_bob
  if alice<bob then next end
  if next_alice==0 && next_bob==-1 then a+=1;break
  elsif next_alice==1 && next_bob==0 then b+=1;break
  elsif alice+next_alice==bob+next_bob then a+=1;break
  else break
  end
end
print("#{a} #{b}\n")

##
# 6C
# Author: Sammy Teahan
#

if __FILE__ == $0
  bars = gets.to_i
  time = gets.split.map(&:to_i)
  aliceCount = 0;
  aliceTotal = 0;
  bobCount = 0;
  bobTotal = 0;

  start = 0;
  last = time.length - 1

  while start <= last do
    if aliceCount <= bobCount
      aliceTotal += time[start += 1]
      aliceCount += 1
    else
      bobTotal += time[last -= 1]
      bobCount += 1
    end
  end

  puts "#{aliceCount} #{bobCount}"
end

n = gets.to_i
a = gets.split(/\s/).map {|x| x.to_i}

a1 = 0
a2 = 0
t1 = 0
t2 = 0
size = a.size
if size == 1
  puts "1 0"
else
  i = 0
  j = size-1
  z = size%2 == 1
  x = true
  while i < j
    x = true
    if t1 > t2
      while t1 > t2 and i < j
        a2 += 1
        t2 += a[j]
        j -= 1
      end
    elsif t2 > t1
      while t2 > t1 and i < j
        a1 += 1
        t1 += a[i]
        i += 1
      end
    else
      a1 += 1
      a2 += 1
      t1 += a[i]
      t2 += a[j]
      i += 1
      j -= 1
      x = z
    end
  end

  if x
    if t1 <= t2
      a1 += 1
    else
      a2 += 1
    end
  end
  puts "#{a1} #{a2}"
end

n = gets.to_i
a = gets.split(/\s/).map {|x| x.to_i}

a1 = 0
a2 = 0
t1 = 0
t2 = 0
size = a.size
if size == 1
  puts "1 0"
else
  i = 0
  j = size-1
  while i < j
    if t1 > t2
      while t1 > t2 and i < j
        a2 += 1
        t2 += a[j]
        j -= 1
      end
    elsif t2 > t1
      while t2 > t1 and i < j
        a1 += 1
        t1 += a[i]
        i += 1
      end
    else
      a1 += 1
      a2 += 1
      t1 += a[i]
      t2 += a[j]
      i += 1
      j -= 1
    end
  end

  if t1+t2 != n
    if t1 <= t2
      a1 += 1
    else
      a2 += 1
    end
  end
  puts "#{a1} #{a2}"
end

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

i, j = 0, a.size - 1

if a.size > 1
  while i < j
    if a[i] == a[j]
      if i + 1 >= j
        i += 1
      else
        i += 1
        j -= 1
      end
    elsif a[i] < a[j]
      a[j] -= a[i]
      i += 1
    elsif a[i] > a[j]
      a[i] -= a[j]
      j -= 1
    end
  end
else
  i = 1
  j = a.size
end

puts "#{i} #{a.size - j}"

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

i, j = 0, a.size - 1

if a.size > 1
  while i < j
    if a[i] == a[j]
      if i + 1 >= j - 1
        i += 1
      else
        i += 1
        j -= 1
      end
    elsif a[i] < a[j]
      a[j] -= a[i]
      i += 1
    elsif a[i] > a[j]
      a[i] -= a[j]
      j -= 1
    end
  end
else
  i = 1
  j = a.size
end

puts "#{i} #{a.size - j}"

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

i, j = 0, a.size - 1

if a.size > 1
  while true
    if a[i] == a[j]
      a[i] = a[j] = 0
      i += 1
      j -= 1
      if i > j
        break
      elsif i == j
        i += 1
        break
      end
    elsif a[i] > a[j]
      a[i] -= a[j]
      i += 1
      if i == j
        j -= 1
        break
      end
    elsif a[i] < a[j]
      a[j] -= a[i]
      j -= 1
      if i == j
        i += 1
        break
      end
    end
  end
else
  i = 1
  j = a.size - 1
end

puts "#{i} #{(a.size - 1) - j}"

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

i, j = 0, a.size - 1

if a.size > 1
  while i < j
    if a[i] == a[j]
      if i + 1 >= j - 1
        i += 1
      else
        i += 1
        j -= 1
      end
    elsif a[i] < a[j]
      a[j] -= a[i]
      if i + 1 >= j
        j -= 1
        break
      end
      i += 1
    elsif a[i] > a[j]
      a[i] -= a[j]
      if i >= j - 1
        i += 1
        break
      end
      j -= 1
    end
  end
else
  i = 1
  j = a.size
end

puts "#{i} #{a.size - j}"

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

i, j = 0, a.size - 1

while i < j
  if a[i] == a[j]
    if i + 1 >= j
      i += 1
    else
      i += 1
      j -= 1
    end
  elsif a[i] < a[j]
    a[j] -= a[i]
    i += 1
  elsif a[i] > a[j]
    a[i] -= a[j]
    j -= 1
  end
end

puts "#{i} #{a.size - j}"

n = gets.to_i

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

l,r = 0, a.size-1

while l+1 < r
	# print [l,r],"\n"
	min = [a[l],a[r]].min
	a[l] -= min
	a[r] -= min

	if a[l] == 0 and l < r-1
		l+=1
	end
	if a[r] == 0 and r-1 > l
		r-=1
	end
end

print l+1, ' ', a.size - r


You are given an array $$$a$$$ of size $$$n$$$.You can perform the following operation on the array:   Choose two different integers $$$i, j$$$ $$$(1 \leq i < j \leq n$$$), replace $$$a_i$$$ with $$$x$$$ and $$$a_j$$$ with $$$y$$$. In order not to break the array, $$$a_i | a_j = x | y$$$ must be held, where $$$|$$$ denotes the bitwise OR operation. Notice that $$$x$$$ and $$$y$$$ are non-negative integers. Please output the minimum sum of the array you can get after using the operation above any number of times.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ $$$(1 \leq t \leq 1000)$$$. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(2 \leq n \leq 100)$$$ — the size of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots ,a_n$$$ $$$(0 \leq a_i < 2^{30})$$$.

For each test case, print one number in a line — the minimum possible sum of the array.

NoteIn the first example, you can perform the following operations to obtain the array $$$[1, 0, 2]$$$:1. choose $$$i = 1, j = 2$$$, change $$$a_1 = 1$$$ and $$$a_2 = 2$$$, it's valid since $$$1 | 3 = 1 | 2$$$. The array becomes $$$[1, 2, 2]$$$.2. choose $$$i = 2, j = 3$$$, change $$$a_2 = 0$$$ and $$$a_3 = 2$$$, it's valid since $$$2 | 2 = 0 | 2$$$. The array becomes $$$[1, 0, 2]$$$.We can prove that the minimum sum is $$$1 + 0 + 2 = 3$$$In the second example, We don't need any operations.

t = readline.strip.to_i

t.times do
  n = readline.strip.to_i
  nums = readline.strip.split(/\s+/).map(&:to_i)

  res = 0
  nums.each do |e|
  res |= e
  end

  puts res
end

gets.to_i.times {
  gets
  xs = gets.split.map!(&:to_i)
  p xs.inject(:|)
}


Bessie and the cows are playing with sequences and need your help. They start with a sequence, initially containing just the number 0, and perform n operations. Each operation is one of the following:  Add the integer xi to the first ai elements of the sequence.  Append an integer ki to the end of the sequence. (And hence the size of the sequence increases by 1)  Remove the last element of the sequence. So, the size of the sequence decreases by one. Note, that this operation can only be done if there are at least two elements in the sequence. After each operation, the cows would like to know the average of all the numbers in the sequence. Help them!

The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of operations. The next n lines describe the operations. Each line will start with an integer ti (1 ≤ ti ≤ 3), denoting the type of the operation (see above). If ti = 1, it will be followed by two integers ai, xi (|xi| ≤ 103; 1 ≤ ai). If ti = 2, it will be followed by a single integer ki (|ki| ≤ 103). If ti = 3, it will not be followed by anything. It is guaranteed that all operations are correct (don't touch nonexistent elements) and that there will always be at least one element in the sequence.

Output n lines each containing the average of the numbers in the sequence after the corresponding operation. The answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6.

NoteIn the second sample, the sequence becomes

#!/usr/bin/ruby1.9

command_num = STDIN.readline.to_i

sums = [0]
add = (command_num+1).times.collect { 0 }
added = 0

command_num.times do

	command = STDIN.readline.split.collect {|s| s.to_i }

	if command[0] == 1
		a, x = command.slice(1, 2)
		add[a-1] += x
		added += a*x

	elsif command[0] == 2
		k = command[1]
		sums.push(sums.last+k)

	else
		n = sums.length
		sums.pop
		added -= add[n-1]
		add[n-2] += add[n-1]
		add[n-1] = 0

	end

	puts ( 1.0 * (sums.last + added) / sums.length )

end


A team of students from the city S is sent to the All-Berland Olympiad in Informatics. Traditionally, they go on the train. All students have bought tickets in one carriage, consisting of n compartments (each compartment has exactly four people). We know that if one compartment contain one or two students, then they get bored, and if one compartment contain three or four students, then the compartment has fun throughout the entire trip.The students want to swap with other people, so that no compartment with students had bored students. To swap places with another person, you need to convince him that it is really necessary. The students can not independently find the necessary arguments, so they asked a sympathetic conductor for help. The conductor can use her life experience to persuade any passenger to switch places with some student.However, the conductor does not want to waste time persuading the wrong people, so she wants to know what is the minimum number of people necessary to persuade her to change places with the students. Your task is to find the number. After all the swaps each compartment should either have no student left, or have a company of three or four students.

The first line contains integer n (1 ≤ n ≤ 106) — the number of compartments in the carriage. The second line contains n integers a1, a2, ..., an showing how many students ride in each compartment (0 ≤ ai ≤ 4). It is guaranteed that at least one student is riding in the train.

If no sequence of swapping seats with other people leads to the desired result, print number "-1" (without the quotes). In another case, print the smallest number of people you need to persuade to swap places.


Let $$$LCM(x, y)$$$ be the minimum positive integer that is divisible by both $$$x$$$ and $$$y$$$. For example, $$$LCM(13, 37) = 481$$$, $$$LCM(9, 6) = 18$$$.You are given two integers $$$l$$$ and $$$r$$$. Find two integers $$$x$$$ and $$$y$$$ such that $$$l \le x < y \le r$$$ and $$$l \le LCM(x, y) \le r$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases. Each test case is represented by one line containing two integers $$$l$$$ and $$$r$$$ ($$$1 \le l < r \le 10^9$$$).

For each test case, print two integers:   if it is impossible to find integers $$$x$$$ and $$$y$$$ meeting the constraints in the statement, print two integers equal to $$$-1$$$;  otherwise, print the values of $$$x$$$ and $$$y$$$ (if there are multiple valid answers, you may print any of them).

$,, $\= ' ', "\n"
gets.to_i.times do
    l, r = gets.split.map &:to_i
    print -1, -1 if 2 * l > r
    print l, 2 * l if 2 * l <= r
end

n = gets.to_i
ans = []
n.times do
  l,r = gets.chomp.split(" ").map(&:to_i)
  if l * 2 <= r
    ans << [l,l*2]
  else
    ans << [-1,-1]
  end
end
ans.each do |x|
  puts "#{x[0]} #{x[1]}"
end

$, = ' '
gets.to_i.times do
    l, r = gets.split.map &:to_i
    print -1, -1 if 2 * l > r
    print l, 2 * l if 2 * l <= r
end


Masha has $$$n$$$ types of tiles of size $$$2 \times 2$$$. Each cell of the tile contains one integer. Masha has an infinite number of tiles of each type.Masha decides to construct the square of size $$$m \times m$$$ consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of this square has to be covered with exactly one tile cell, and also sides of tiles should be parallel to the sides of the square. All placed tiles cannot intersect with each other. Also, each tile should lie inside the square. See the picture in Notes section for better understanding.Symmetric with respect to the main diagonal matrix is such a square $$$s$$$ that for each pair $$$(i, j)$$$ the condition $$$s[i][j] = s[j][i]$$$ holds. I.e. it is true that the element written in the $$$i$$$-row and $$$j$$$-th column equals to the element written in the $$$j$$$-th row and $$$i$$$-th column.Your task is to determine if Masha can construct a square of size $$$m \times m$$$ which is a symmetric matrix and consists of tiles she has. Masha can use any number of tiles of each type she has to construct the square. Note that she can not rotate tiles, she can only place them in the orientation they have in the input.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$1 \le m \le 100$$$) — the number of types of tiles and the size of the square Masha wants to construct. The next $$$2n$$$ lines of the test case contain descriptions of tiles types. Types of tiles are written one after another, each type is written on two lines.  The first line of the description contains two positive (greater than zero) integers not exceeding $$$100$$$ — the number written in the top left corner of the tile and the number written in the top right corner of the tile of the current type. The second line of the description contains two positive (greater than zero) integers not exceeding $$$100$$$ — the number written in the bottom left corner of the tile and the number written in the bottom right corner of the tile of the current type. It is forbidden to rotate tiles, it is only allowed to place them in the orientation they have in the input.

For each test case print the answer: "YES" (without quotes) if Masha can construct the square of size $$$m \times m$$$ which is a symmetric matrix. Otherwise, print "NO" (withtout quotes).

NoteThe first test case of the input has three types of tiles, they are shown on the picture below.  Masha can construct, for example, the following square of size $$$4 \times 4$$$ which is a symmetric matrix:

t = gets.chomp.to_i

t.times do
    line = gets.chomp.split(' ')
    n = line[0].to_i
    m = line[1].to_i
    result = false

    n.times do
        line = gets.chomp.split(' ')
        a = line[0].to_i
        b = line[1].to_i
        line = gets.chomp.split(' ')
        c = line[0].to_i
        d = line[1].to_i
        result ||= b == c
    end

    (m % 2).zero? && result ? (puts 'YES') : (puts 'NO')
end

t = gets.chomp.to_i
t.times do
    n, m = gets.chomp.split(" ").map(&:to_i)
    four = 0
    two = 0
    no = 0
    j = []
    n.times do
        i = []
        arr = []
        ar = []
        tokubetu = []
        a, b = gets.chomp.split(" ").map(&:to_i)
        c, d = gets.chomp.split(" ").map(&:to_i)
        arr << a
        arr << b
        ar << c
        ar << d
        i << arr
        i << ar
        if a == b && b == c && c == d
            four += 1
        elsif b == c
            two += 1
        else
            no += 1
            tokubetu << a
            tokubetu << d
            j << tokubetu
        end
    end
    # p four
    # p two
    # p no
    if m % 2 != 0
        puts "NO"
    elsif four >= 1
        puts "YES"
    elsif two >= 1
        puts "YES"
    else
        puts "NO"
    end
end

gets.to_i.times{n,m=gets.split.map(&:to_i);puts(if Array.new(n){_,a=gets.split.map(&:to_i);b,_=gets.split.map(&:to_i);a==b;}.reduce(:|)and m.even?then :YES else :NO end)}

t = gets.to_i
t.times {
  n, m = gets.split.map(&:to_i)
  puts (if Array.new(n) {
    _, a = gets.split.map(&:to_i)
    b, _ = gets.split.map(&:to_i)
    a == b
  }.reduce(:|) and m.even? then :YES else :NO end)
}


You helped Dima to have a great weekend, but it's time to work. Naturally, Dima, as all other men who have girlfriends, does everything wrong.Inna and Dima are now in one room. Inna tells Dima off for everything he does in her presence. After Inna tells him off for something, she goes to another room, walks there in circles muttering about how useless her sweetheart is. During that time Dima has time to peacefully complete k - 1 tasks. Then Inna returns and tells Dima off for the next task he does in her presence and goes to another room again. It continues until Dima is through with his tasks.Overall, Dima has n tasks to do, each task has a unique number from 1 to n. Dima loves order, so he does tasks consecutively, starting from some task. For example, if Dima has 6 tasks to do in total, then, if he starts from the 5-th task, the order is like that: first Dima does the 5-th task, then the 6-th one, then the 1-st one, then the 2-nd one, then the 3-rd one, then the 4-th one.Inna tells Dima off (only lovingly and appropriately!) so often and systematically that he's very well learned the power with which she tells him off for each task. Help Dima choose the first task so that in total he gets told off with as little power as possible.

The first line of the input contains two integers n, k (1 ≤ k ≤ n ≤ 105). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103), where ai is the power Inna tells Dima off with if she is present in the room while he is doing the i-th task. It is guaranteed that n is divisible by k.

In a single line print the number of the task Dima should start with to get told off with as little power as possible. If there are multiple solutions, print the one with the minimum number of the first task to do.

NoteExplanation of the first example.If Dima starts from the first task, Inna tells him off with power 3, then Dima can do one more task (as k = 2), then Inna tells him off for the third task with power 1, then she tells him off for the fifth task with power 5. Thus, Dima gets told off with total power 3 + 1 + 5 = 9. If Dima started from the second task, for example, then Inna would tell him off for tasks 2, 4 and 6 with power 2 + 6 + 4 = 12. Explanation of the second example.In the second example k = 5, thus, Dima manages to complete 4 tasks in-between the telling off sessions. Thus, Inna tells Dima off for tasks number 1 and 6 (if he starts from 1 or 6), 2 and 7 (if he starts from 2 or 7) and so on. The optimal answer is to start from task 3 or 8, 3 has a smaller number, so the answer is 3.

n,k=gets.chomp.split.map(&:to_i)
b,ans=Array.new(k,0),0
a=gets.chomp.split.map(&:to_i)
a.length.times {|i| b[i%k]+=a[i]}
puts b.index(b.min)+1

n,k = gets.split(" ").map(&:to_i)
arr = gets.split(" ").map(&:to_i)
m = n/k
k_list = []
(0..((n/m)-1)).each do |i|
	k_list << (i..(n-1)).step(k).to_a
end
sum = []
k_list.each do |a|
	sum << a.inject(0){|s,x| s += arr[x]}
end
# puts "#{sum}"
min,min_ind = sum.each_with_index.min
puts k_list[min_ind][0]+1

n,k=gets.split.map(&:to_i)
a=gets.split.map(&:to_i)
m,b,bi=n/k,1.0/0,-1
k.times do |i|
  s=0
  m.times{|j|s+=a[i+k*j]}
  b,bi=s,i+1 if s < b
end
p bi

def read_next_line
  gets.split.map { |x| x.to_i }
end

n, k = read_next_line
a = read_next_line
sums = Array.new(k)
for i in 0...k
  sum = 0
  for j in (i...n).step(k)
    sum += a[j]
  end
  sums[i] = sum
end
puts sums.index(sums.min) + 1


Pushok the dog has been chasing Imp for a few hours already.  Fortunately, Imp knows that Pushok is afraid of a robot vacuum cleaner. While moving, the robot generates a string t consisting of letters 's' and 'h', that produces a lot of noise. We define noise of string t as the number of occurrences of string "sh" as a subsequence in it, in other words, the number of such pairs (i, j), that i < j and  and . The robot is off at the moment. Imp knows that it has a sequence of strings ti in its memory, and he can arbitrary change their order. When the robot is started, it generates the string t as a concatenation of these strings in the given order. The noise of the resulting string equals the noise of this concatenation.Help Imp to find the maximum noise he can achieve by changing the order of the strings.

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of strings in robot's memory. Next n lines contain the strings t1, t2, ..., tn, one per line. It is guaranteed that the strings are non-empty, contain only English letters 's' and 'h' and their total length does not exceed 105.

Print a single integer — the maxumum possible noise Imp can achieve by changing the order of the strings.

NoteThe optimal concatenation in the first sample is ssshhshhhs.

n = gets.to_i

t_list = []
n.times do
   string = gets.strip
   s_count = string.scan(/s/).count
   h_count = string.scan(/h/).count
   factor = s_count / Float(h_count + s_count)
   t_list << [string, factor]
end

t_list.sort_by! { |i| i[1] }.reverse!

s_count, count = 0, 0

t_list.each do |t|
    t[0].each_char do |c|
        if c == 's'
            s_count += 1
        else
            count += s_count
        end
    end
end

puts count


Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel.  It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.

If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.

NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.

N = gets.to_i
M = gets.to_i
as = gets.split.map(&:to_i)
bs = gets.split.map(&:to_i)

cos = [bs[0], as[-1]]
(N-2).downto(0) do |i|
    cos.push(bs[i+1], as[i])
end

w = M.to_f
cos.each do |c|
    if c == 1
        puts -1
        exit
    end
    w *= c.to_f / (c-1)
end
puts sprintf("%.10f", w-M)

n = gets.to_i
m = gets.to_i
ais = gets.strip.split.map(&:to_i)
bis = gets.strip.split.map(&:to_i)

if ais.include?(1) || bis.include?(1)
  puts -1
  exit 0
end

ais = ais.map{|x|Rational(x)}
bis = bis.map{|x|Rational(x)}

def get_weight_before_landing(al, b)
  (b*al)/(b- Rational(1))
end

def get_weight_before_takeoff(at, a)
  (a*at)/(a- Rational(1))
end

rw = Rational(m)
rw = get_weight_before_landing(rw, bis[0])
(n-1).downto(1).each do |s|
  rw = get_weight_before_takeoff(rw, ais[s])
  rw = get_weight_before_landing(rw, bis[s])
end
rw = get_weight_before_takeoff(rw, ais[0])
puts (rw - Rational(m)).to_f

require 'bigdecimal'

gets
m = gets.to_i
p = 1
q = 1

2.times do
  gets.split.map{|x| x.to_i}.each do |x|
    p *= x
    q *= x-1
  end
end

if q == 0
  puts (-1)
else
  puts m*BigDecimal.new(p)/BigDecimal.new(q)-m
end

require 'bigdecimal'

gets
m = gets.to_i
p = 1
q = 1

2.times do
  gets.split.map{|x| x.to_i}.each do |x|
    p *= x
    q *= x-1
  end
end

if q == 0
  puts (-1)
else
  puts m*BigDecimal.new(p)/q-m
end

gets
m = gets.to_i
p = 1
q = 1

2.times do
  gets.split.map{|x| x.to_i}.each do |x|
    p *= x
    q *= x-1
  end
end

if q == 0
  puts (-1)
else
  puts m*p.to_f/q
end

gets
m = gets.to_i
p = 1
q = 1

2.times do
  gets.split.map{|x| x.to_i}.each do |x|
    p *= x
    q *= x-1
  end
end

if q == 0
  puts (-1)
else
  puts m*p.to_f/q-m
end

gets
m = gets.to_i
p = 1
q = 1

2.times do
  gets.split.map{|x| x.to_i}.each do |x|
    p *= x
    q *= x-1
  end
end

if q == 0
  puts (-1)
else
  puts m*p/q.to_f-m
end