During a daily walk Alina noticed a long number written on the ground. Now Alina wants to find some positive number of same length without leading zeroes, such that the sum of these two numbers is a palindrome. Recall that a number is called a palindrome, if it reads the same right to left and left to right. For example, numbers $$$121, 66, 98989$$$ are palindromes, and $$$103, 239, 1241$$$ are not palindromes.Alina understands that a valid number always exist. Help her find one!

The first line of input data contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. Next, descriptions of $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 100\,000$$$) — the length of the number that is written on the ground. The second line of contains the positive $$$n$$$-digit integer without leading zeroes — the number itself. It is guaranteed that the sum of the values $$$n$$$ over all test cases does not exceed $$$100\,000$$$.

For each of $$$t$$$ test cases print an answer — a positive $$$n$$$-digit integer without leading zeros, such that the sum of the input integer and this number is a palindrome. We can show that at least one number satisfying the constraints exists. If there are multiple solutions, you can output any of them.

NoteIn the first test case $$$99 + 32 = 131$$$ is a palindrome. Note that another answer is $$$12$$$, because $$$99 + 12 = 111$$$ is also a palindrome.In the second test case $$$1023 + 8646 = 9669$$$.In the third test case $$$385 + 604 = 989$$$.

gets.to_i.times do
  n = gets.to_i
  x = gets
  case
  when x[0] == '9'
    puts(('1'*(n + 1)).to_i - x.to_i)
  else
    puts(('9'*n).to_i - x.to_i)
  end
end

gets.to_i.times do
   n = gets.to_i
   x = gets
   x[0] == '9' ? puts(('1'*(n + 1)).to_i - x.to_i) : puts(('9'*n).to_i - x.to_i)
end

t = gets.chomp.to_i
for i in 1..t
    n = gets.chomp.to_i
    x = gets.chomp
    if x[0] != '9'
        w = ""
        for j in 0..(n - 1)
            w.concat((9 - x[j].to_i).to_s)
        end
        puts(w)
    else
        x.reverse!
        w = ""
        c = 0
        for j in 0..(n - 1)
            c += x[j].to_i
            if (c <= 1)
                w.concat((1 - c).to_s)
                c = 0
            else
                w.concat((11 - c).to_s)
               c = 1
            end
        end
        w.reverse!
        puts(w)
    end
end

t = gets.chomp.to_i

while t > 0
  t -= 1
  n = gets.chomp.to_i
  a = gets.chomp

  res = if a.length == 1
    11 - a.to_i
  elsif a[0] == '9'
    # a + res = final
    # res = final - a
    res = "0" * a.length
    final = "1" * (a.length + 1)

    (0..a.length - 1).reverse_each do |i|
      nu = final[i].to_i
      de = a[i].to_i
      d = nu - de
      if d < 0
        d += 10
        final[i - 1] = '0'
      end
      res[i] = d.to_s
    end
    res
  else
    a.chars.map { |c| (9 - c.to_i).to_s }.join("")
  end

  puts res
end

# puts inp.length
# puts inp[0]
# puts inp[1]
# puts inp
2
3
123
2
99

gets.to_i.times do
  n = gets.to_i
  s = gets.to_i
  v = ('9' * n).to_i - s
  v = ('1' * (n + 1)).to_i - s if v.to_s.size != n
  puts v
end

t = gets.chomp.to_i
for i in 1..t
    n = gets.chomp.to_i
    x = gets.chomp
    if x[0] != '9'
        w = ""
        for j in 0..(n - 1)
            w.concat((9 - x[j].to_i).to_s)
        end
        puts(w)
    else
        w = ""
        for j in 0..(n - 2)
            w.concat((10 - x[j].to_i).to_s)
        end
        w.concat((11 - x[j].to_i).to_s)
        puts(w)
    end
end

t = gets.chomp.to_i
for i in 1..t
    n = gets.chomp.to_i
    x = gets.chomp
    if x[0] != '9'
        w = ""
        for j in 0..(n - 1)
            print((9 - x[j].to_i).to_s)
        end
        puts()
    else
        w = ""
        for j in 0..(n - 2)
            print((10 - x[j].to_i).to_s)
        end
        puts((11 - x[j].to_i).to_s)
    end
end


A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$).

For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer  — the minimum possible value of $$$k$$$.

NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$.

limit = 10 ** 12
fact = [1]
fact << fact[-1] * fact.size while fact[-1] < limit
map = { 0 => 0 }
(1..fact.size).each do |i|
  fact.combination(i).map(&:sum).each do |sum|
    map[sum] = i unless map[sum]
  end
end

gets.to_i.times do
  n = gets.to_i
  p(map.filter_map do |f, c|
    c + (n - f).to_s(2).count("1") if n - f >= 0
  end.min)
end


There's a chessboard of size $$$n \times n$$$. $$$m$$$ rooks are placed on it in such a way that:   no two rooks occupy the same cell;  no two rooks attack each other. A rook attacks all cells that are in its row or column.Is it possible to move exactly one rook (you can choose which one to move) into a different cell so that no two rooks still attack each other? A rook can move into any cell in its row or column if no other rook stands on its path.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 8$$$) — the size of the chessboard and the number of the rooks. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — the position of the $$$i$$$-th rook: $$$x_i$$$ is the row and $$$y_i$$$ is the column. No two rooks occupy the same cell. No two rooks attack each other.

For each testcase, print "YES" if it's possible to move exactly one rook into a different cell so that no two rooks still attack each other. Otherwise, print "NO".

NoteIn the first testcase, the rooks are in the opposite corners of a $$$2 \times 2$$$ board. Each of them has a move into a neighbouring corner, but moving there means getting attacked by another rook.In the second testcase, there's a single rook in a middle of a $$$3 \times 3$$$ board. It has $$$4$$$ valid moves, and every move is fine because there's no other rook to attack it.

r=gets.to_i
for i in 1..r
    a = gets.chomp.split
    n = a[0].to_i
    m = a[1].to_i
    for j in 1..m
        a=gets.chomp.split
    end
    if n!=m
        puts "YES"
    else
        puts "NO"
    end
end


You are given an integer $$$x$$$. Can you make $$$x$$$ by summing up some number of $$$11, 111, 1111, 11111, \ldots$$$? (You can use any number among them any number of times).For instance,   $$$33=11+11+11$$$  $$$144=111+11+11+11$$$

The first line of input contains a single integer $$$t$$$ $$$(1 \leq t \leq 10000)$$$ — the number of testcases. The first and only line of each testcase contains a single integer $$$x$$$ $$$(1 \leq x \leq 10^9)$$$ — the number you have to make.

For each testcase, you should output a single string. If you can make $$$x$$$, output "YES" (without quotes). Otherwise, output "NO". You can print each letter of "YES" and "NO" in any case (upper or lower).

NoteWays to make $$$33$$$ and $$$144$$$ were presented in the statement. It can be proved that we can't present $$$69$$$ this way.

require "set"

ok = [*0..111].flat_map { |a| [*0..11].map { |b| a * 11 + b * 111 } }.to_set

gets.to_i.times do
  n = gets.to_i
  puts ok.include?(n) || n >= 1111 ? "YES" : "NO"
end


Today the «Z» city residents enjoy a shell game competition. The residents are gathered on the main square to watch the breath-taking performance. The performer puts 3 non-transparent cups upside down in a row. Then he openly puts a small ball under one of the cups and starts to shuffle the cups around very quickly so that on the whole he makes exactly 3 shuffles. After that the spectators have exactly one attempt to guess in which cup they think the ball is and if the answer is correct they get a prize. Maybe you can try to find the ball too?

The first input line contains an integer from 1 to 3 — index of the cup which covers the ball before the shuffles. The following three lines describe the shuffles. Each description of a shuffle contains two distinct integers from 1 to 3 — indexes of the cups which the performer shuffled this time. The cups are numbered from left to right and are renumbered after each shuffle from left to right again. In other words, the cup on the left always has index 1, the one in the middle — index 2 and the one on the right — index 3.

In the first line output an integer from 1 to 3 — index of the cup which will have the ball after all the shuffles.

file = File.new("input.txt", "r")
pos = file.gets.to_i
a = (1..3).to_a
(1..3).each do
  x, y = file.gets.split.map{|z| z.to_i-1}
  a[x], a[y] = a[y], a[x]
end
file.close
File.open("output.txt", "w") {|file| file.write(a.find_index(pos)+1)}

f = open("input.txt", "r")
fw = open("output.txt", "w")
idx = f.gets.chomp.to_i
for i in 0..2
	i1, i2 = f.gets.chomp.split(/ /).map!{|x|x.to_i}
	if idx == i1
		idx = i2
	elsif idx == i2
		idx = i1
	end
end
fw.puts idx
f.close
fw.close

#!/usr/bin/ruby
$stdin=open("input.txt","rb")
$>=open("output.txt","wb")
a=[0]*4
a[gets.to_i]=1
while gets
	x,y=$_.split.map(&:to_i)
	a[x],a[y]=a[y],a[x]
end
p a.index(1)

I=open('input.txt')
O=open('output.txt','w')
n=I.gets.to_i
3.times do
	a, b = I.gets.split.map &:to_i
	n = n == a ? b : n == b ? a : n
end
O.puts n

ball_pos = 0
File.open('input.txt').each do |line|
  if ball_pos == 0
		ball_pos = line.to_i
	else
		temp = line.split.collect { |n| n.to_i }
		if temp[0] == ball_pos
			ball_pos = temp[1]
		elsif temp[1] == ball_pos
			ball_pos = temp[0]
		end
	end
end
out = File.open('output.txt','w')
out << ball_pos.to_s
out.close

$stdin=open("input.txt")
$stdout=open("output.txt","w")
k=gets.to_i
3.times do
	m,n=gets.chomp.split.map(&:to_i)
	k = (m==k)? n : ((n==k)? m : k)
end
puts k

$stdin = File.new( "input.txt", 'r' )
$stdout = File.new( "output.txt", 'w' )

index = gets.strip.to_i
3.times do
    a, b = gets.strip.split.map(&:to_i)
    if index == a
        index = b
    elsif index == b
        index = a
    end
end
puts index

line = File.read("input.txt")
inputs = line.split("\n")

arr = Array.new(3,false)

start = inputs[0].to_i
arr[start-1] = true

3.times do |inp|
	i,j = inputs[inp+1].split(" ").map(&:to_i)
	i -= 1
	j -= 1
	arr[i],arr[j] = arr[j],arr[i]
end

File.open("output.txt", 'w') { |file|
	file.puts arr.index(true) + 1
}

$stdin = File.open("input.txt","r")
$stdout = File.open("output.txt","w")
k=gets.to_i
3.times {|x| l=gets.split.map &:to_i ; l[0]==k ?k=l[1]:(l[1]==k ?k=l[0]:0)}
puts k

input = open('input.txt','r')
output = open('output.txt','w')

curr = input.gets.chomp!.to_i

for i in 1..3
  s = input.gets.chomp!.split(" ")
  mas = []
  mas[0] = s[0].to_i
  mas[1] = s[1].to_i

  if (curr == mas[0])
    curr = mas[1]
  else
    if (curr == mas[1])
      curr = mas[0]
    end
  end
end

output.puts(curr)

File.open('input.txt') do |f|
  now = f.gets.to_i
  3.times do
    a, b = f.gets.split.map(&:to_i)
    if [a, b].index(now)
      now ^= a ^ b
    end
  end
  File.open('output.txt', 'w') { |f| f.puts now }
end

#!/usr/bin/ruby
a=[0]*4
a[gets.to_i]=1
while gets
	x,y=$_.split.map(&:to_i)
	a[x],a[y]=a[y],a[x]
end
puts 2
puts(a.index(1))

#!/usr/bin/ruby
f=open("output.txt","wb")
a=[0]*4
a[gets.to_i]=1
while gets
	x,y=$_.split.map(&:to_i)
	f.puts x
	f.puts y
	a[x],a[y]=a[y],a[x]
end
f.puts(a.index(1))

#!/usr/bin/ruby
f=open("output.txt","wb")
a=[0]*4
a[gets.to_i]=1
while gets
	x,y=$_.split.map(&:to_i)
	a[x],a[y]=a[y],a[x]
end
f.puts(a.index(1))

#!/usr/bin/ruby
f=open("output.txt","w")
a=[0]*4
a[gets.to_i]=1
while gets
	x,y=$_.split.map(&:to_i)
	a[x],a[y]=a[y],a[x]
end
f.puts a.index(1)

#!/usr/bin/ruby
a=[0]*4
a[gets.to_i]=1
while gets
	x,y=$_.split.map(&:to_i)
	a[x],a[y]=a[y],a[x]
end
puts(a.index(1))

#!/usr/bin/ruby
a=[0]*4
a[gets.to_i]=1
while gets
	x,y=$_.split.map(&:to_i)
	a[x],a[y]=a[y],a[x]
end
p a.index 1

#!/usr/bin/ruby
a=[0]*4
a[gets.to_i]=1
while gets
	x,y=$_.split.map(&:to_i)
puts x
	a[x],a[y]=a[y],a[x]
end
puts(a.index(1))

#!/usr/bin/ruby
a=[0]*4
a[gets.to_i]=1
while gets
	x,y=$_.split.map(&:to_i)
	a[x],a[y]=a[y],a[x]
end
p a.index(1)

#!/usr/bin/ruby
f=open("output.txt","w")
a=[0]*4
a[gets.to_i]=1
while gets
	x,y=$_.split.map(&:to_i)
	a[x],a[y]=a[y],a[x]
end
f.puts a.inspect
f.puts a.index(1)


Mashmokh is playing a new game. In the beginning he has k liters of water and p coins. Additionally he has a rooted tree (an undirected connected acyclic graph) that consists of m vertices. Each vertex of the tree contains a water tank that is empty in the beginning.The game begins with the fact that Mashmokh chooses some (no more than k) of these tanks (except the root) and pours into each of them exactly 1 liter of water. Then the following process is performed until there is no water remained in tanks.  The process consists of several steps.  At the beginning of each step Mashmokh opens doors of all tanks. Then Mashmokh closes doors of some tanks (he is not allowed to close door of tank in the root) for the duration of this move. Let's denote the number of liters in some tank with closed door as w, Mashmokh pays w coins for the closing of that tank during this move.  Let's denote by x1, x2, ..., xm as the list of vertices of the tree sorted (nondecreasing) by their depth. The vertices from this list should be considered one by one in the order. Firstly vertex x1 (which is the root itself) is emptied. Then for each vertex xi (i > 1), if its door is closed then skip the vertex else move all the water from the tank of vertex xi to the tank of its father (even if the tank of the father is closed). Suppose l moves were made until the tree became empty. Let's denote the amount of water inside the tank of the root after the i-th move by wi then Mashmokh will win max(w1, w2, ..., wl) dollars. Mashmokh wanted to know what is the maximum amount of dollars he can win by playing the above game. He asked you to find this value for him.

The first line of the input contains three space-separated integers m, k, p (2 ≤ m ≤ 105; 0 ≤ k, p ≤ 109).  Each of the following m - 1 lines contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ m; ai ≠ bi) — the edges of the tree. Consider that the vertices of the tree are numbered from 1 to m. The root of the tree has number 1.

Output a single integer, the number Mashmokh asked you to find.

NoteThe tree in the first sample is shown on the picture below. The black, red, blue colors correspond to vertices with 0, 1, 2 liters of water.One way to achieve the maximum amount of money is to put 1 liter of water in each of vertices 3 and 4. The beginning state is shown on the picture below.Then in the first move Mashmokh will pay one token to close the door of the third vertex tank. The tree after the first move is shown on the picture below.After the second move there are 2 liters of water in the root as shown on the picture below.

m,k,p = gets.split.map(&:to_i)
h={}
(m-1).times{
a,b = gets.split.map(&:to_i)
(h[a]||=[])<<b
(h[b]||=[])<<a
}
q=[1]
d={1=>0}
i=1
j=0
s=0
ans=0
while j<q.size
x=q[j]
m=d[x]
s+=m
(s-=d[q[i]];i+=1)while (j-i+1)*m-s>p||j-i+1>k
h[x].each{|y|
next if d[y]
d[y]=m+1
q<<y
}
ans=[ans,j-i+1].max if j>0
j+=1
end
p ans


Gregor is learning about RSA cryptography, and although he doesn't understand how RSA works, he is now fascinated with prime numbers and factoring them.Gregor's favorite prime number is $$$P$$$. Gregor wants to find two bases of $$$P$$$. Formally, Gregor is looking for two integers $$$a$$$ and $$$b$$$ which satisfy both of the following properties.  $$$P \bmod a = P \bmod b$$$, where $$$x \bmod y$$$ denotes the remainder when $$$x$$$ is divided by $$$y$$$, and  $$$2 \le a < b \le P$$$. Help Gregor find two bases of his favorite prime number!

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Each subsequent line contains the integer $$$P$$$ ($$$5 \le P \le {10}^9$$$), with $$$P$$$ guaranteed to be prime.

Your output should consist of $$$t$$$ lines. Each line should consist of two integers $$$a$$$ and $$$b$$$ ($$$2 \le a < b \le P$$$). If there are multiple possible solutions, print any.

NoteThe first query is $$$P=17$$$. $$$a=3$$$ and $$$b=5$$$ are valid bases in this case, because $$$17 \bmod 3 = 17 \bmod 5 = 2$$$. There are other pairs which work as well.In the second query, with $$$P=5$$$, the only solution is $$$a=2$$$ and $$$b=4$$$.

t = gets.to_i
while(t>0)
    num = gets.to_i
    puts("2 " + (num-1).to_s)
    t-=1
end

t = gets.to_i
t.times do
	prime = gets.to_i
	puts [2, prime - 1] * " "
end

t = gets.chomp.to_i

t.times do
  p = gets.chomp.to_i
  puts "2 #{p-1}\n"
end

def i(x)
	x.to_i
end

n = gets
for i in 1..i(n)
	a = gets
	a = i(a)
	puts "2 #{a - 1}"
end

t = gets.chomp.to_i
t.times do
  hash = {}
  n = gets.chomp.to_i
  puts "#{2} #{n-1}"
end


William has two numbers $$$a$$$ and $$$b$$$ initially both equal to zero. William mastered performing three different operations with them quickly. Before performing each operation some positive integer $$$k$$$ is picked, which is then used to perform one of the following operations: (note, that for each operation you can choose a new positive integer $$$k$$$)  add number $$$k$$$ to both $$$a$$$ and $$$b$$$, or  add number $$$k$$$ to $$$a$$$ and subtract $$$k$$$ from $$$b$$$, or  add number $$$k$$$ to $$$b$$$ and subtract $$$k$$$ from $$$a$$$. Note that after performing operations, numbers $$$a$$$ and $$$b$$$ may become negative as well.William wants to find out the minimal number of operations he would have to perform to make $$$a$$$ equal to his favorite number $$$c$$$ and $$$b$$$ equal to his second favorite number $$$d$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The only line of each test case contains two integers $$$c$$$ and $$$d$$$ $$$(0 \le c, d \le 10^9)$$$, which are William's favorite numbers and which he wants $$$a$$$ and $$$b$$$ to be transformed into.

For each test case output a single number, which is the minimal number of operations which William would have to perform to make $$$a$$$ equal to $$$c$$$ and $$$b$$$ equal to $$$d$$$, or $$$-1$$$ if it is impossible to achieve this using the described operations.

NoteLet us demonstrate one of the suboptimal ways of getting a pair $$$(3, 5)$$$:  Using an operation of the first type with $$$k=1$$$, the current pair would be equal to $$$(1, 1)$$$.  Using an operation of the third type with $$$k=8$$$, the current pair would be equal to $$$(-7, 9)$$$.  Using an operation of the second type with $$$k=7$$$, the current pair would be equal to $$$(0, 2)$$$.  Using an operation of the first type with $$$k=3$$$, the current pair would be equal to $$$(3, 5)$$$.

t = gets.to_i
t.times do

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

if (c + d) < 0 || (c + d).odd?
  puts -1
  next
end

if c == 0 && d == 0
  puts 0
  next
end

if c == d
  puts 1
  next
end

puts 2

end


Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.Strictly speaking, it makes a photo of all points with coordinates $$$(x, y)$$$, such that $$$x_1 \leq x \leq x_2$$$ and $$$y_1 \leq y \leq y_2$$$, where $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.After taking the photo, Pavel wrote down coordinates of $$$n$$$ of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.

The first line of the input contains an only integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$), the number of points in Pavel's records. The second line contains $$$2 \cdot n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{2 \cdot n}$$$ ($$$1 \leq a_i \leq 10^9$$$), coordinates, written by Pavel in some order.

Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records.

NoteIn the first sample stars in Pavel's records can be $$$(1, 3)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$. In this case, the minimal area of the rectangle, which contains all these points is $$$1$$$ (rectangle with corners at $$$(1, 3)$$$ and $$$(2, 4)$$$).

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

ans1 = (as[2*N-1] - as[N]) * (as[N-1] - as[0])

min = 10**9
(0..N).each do |i|
    result = as[i+N-1] - as[i]
    min = result if min > result
end
ans2 = min * (as[2*N-1] - as[0])

puts [ans1, ans2].min


For some time the program of rounding numbers that had been developed by the Codeforces participants during one of the previous rounds, helped the citizens of Far Far Away to convert numbers into a more easily readable format. However, as time went by, the economy of the Far Far Away developed and the scale of operations grew. So the King ordered to found the Bank of Far Far Away and very soon even the rounding didn't help to quickly determine even the order of the numbers involved in operations. Besides, rounding a number to an integer wasn't very convenient as a bank needed to operate with all numbers with accuracy of up to 0.01, and not up to an integer.The King issued yet another order: to introduce financial format to represent numbers denoting amounts of money. The formal rules of storing a number in the financial format are as follows:   A number contains the integer part and the fractional part. The two parts are separated with a character "." (decimal point).  To make digits in the integer part of a number easier to read, they are split into groups of three digits, starting from the least significant ones. The groups are separated with the character "," (comma). For example, if the integer part of a number equals 12345678, then it will be stored in the financial format as 12,345,678  In the financial format a number's fractional part should contain exactly two digits. So, if the initial number (the number that is converted into the financial format) contains less than two digits in the fractional part (or contains no digits at all), it is complemented with zeros until its length equals 2. If the fractional part contains more than two digits, the extra digits are simply discarded (they are not rounded: see sample tests).  When a number is stored in the financial format, the minus sign is not written. Instead, if the initial number had the minus sign, the result is written in round brackets.  Please keep in mind that the bank of Far Far Away operates using an exotic foreign currency — snakes ($), that's why right before the number in the financial format we should put the sign "$". If the number should be written in the brackets, then the snake sign should also be inside the brackets. For example, by the above given rules number 2012 will be stored in the financial format as "$2,012.00" and number -12345678.9 will be stored as "($12,345,678.90)".The merchants of Far Far Away visited you again and expressed much hope that you supply them with the program that can convert arbitrary numbers to the financial format. Can you help them?

The input contains a number that needs to be converted into financial format. The number's notation length does not exceed 100 characters, including (possible) signs "-" (minus) and "." (decimal point). The number's notation is correct, that is:    The number's notation only contains characters from the set {"0" – "9", "-", "."}.  The decimal point (if it is present) is unique and is preceded and followed by a non-zero quantity on decimal digits  A number cannot start with digit 0, except for a case when its whole integer part equals zero (in this case the integer parts is guaranteed to be a single zero: "0").  The minus sign (if it is present) is unique and stands in the very beginning of the number's notation  If a number is identically equal to 0 (that is, if it is written as, for example, "0" or "0.000"), than it is not preceded by the minus sign.  The input data contains no spaces.  The number's notation contains at least one decimal digit.

Print the number given in the input in the financial format by the rules described in the problem statement.

NotePay attention to the second and third sample tests. They show that the sign of a number in the financial format (and consequently, the presence or absence of brackets) is determined solely by the sign of the initial number. It does not depend on the sign of the number you got after translating the number to the financial format.

class Integer
  def to_currency()
    self.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\1,').reverse
  end
end

s = gets.chomp
sa = s.split(".")
if sa.length == 1
	sa << "00"
else
	sa[1] = sa[1].slice(0,2)
	if sa[1].length == 1
		sa[1] += "0"
	end
end
minus = false
if sa[0].slice(0,1) == "-"
	minus = true
end
sa[0] = sa[0].sub("-", "")
sa[0] = sa[0].to_i.to_currency
ret = "$" + sa.join(".")
if minus
	ret = "(" + ret + ")"
end
puts ret

t=gets.split[0]
minus=false
if t[0]=="-" then
        minus=true
        t=t.slice(1,t.length-1)
end
a,b=(t+'.0000.0').split('.')
res=""
a=a.to_i
b+="0000"
while a>0
        res=sprintf(",%03d",a%1000)+res;
        a/=1000
end
res=res.slice(1,res.length-1) if res[0]==','
res=res.slice(1,res.length-1) while res.size()>1 && res[0]=='0'
res="0" if res==""
res="$"+res+"."+b.slice(0,2)
res="("+res+")" if minus
puts res

#!/usr/bin/ruby
def read_int; gets.chomp.to_i; end
def read_ints; gets.chomp.split.map(&:to_i); end

a = gets.chomp
arr = a.split('')

minus = false
if arr[0] == '-'
  minus = true
  arr.shift
end

index = arr.index('.')
len = 0
if index == nil
  len = arr.size
else
  len = index
end

print '(' if minus
print '$'

count = (3 - (len % 3)) % 3

#puts "count = #{len}"

0.upto(len-1) do |i|
  print arr[i]
  count += 1
#  puts " count = #{count}"
  print ',' if len > 3 and count % 3 == 0 and i+1 != len
end

print '.'

len.times { arr.shift }
arr.shift if arr[0] == '.'

if arr.size == 0
  print '00'
elsif arr.size == 1
  print arr[0]
  print '0'
else
  print arr[0]
  print arr[1]
end

print ')' if minus
puts

n = gets.strip
m = false

if n[0] == "-"
  m = true
  n.delete! "-"
end

i,f = n.split(/\./)

f = "00" if f == nil
f += "0" if f.size == 1

s = i.size
a = "$"
i.each_char do |c|
  a += c
  s -= 1
  a += ","if s % 3 == 0 && s != 0
end
a += "."
a += f[0,2]

if m
  a = "(" + a
  a += ")"
end
puts a

a,b = gets.split('.')

a = a.chomp
b = b.chomp if b != nil

last = "\n"
if a[0].chr == '-'
  print '('
  last = ")\n"
  a = a[1..-1]
end

print '$'

i = a.length % 3
first = true
count = 0
a.each_byte{|c|
  print ',' if !first && i == 0
  print c.chr
  i = (i+2) % 3
  first = false
  count += 1
}

if b == nil
  print '.00'
elsif b.length == 1
  print ".#{b}0"
else
  print ".#{b[0..1]}"
end

print last

#!/usr/bin/ruby
include Math
require 'pp'
minus = false
input = gets.chomp
minus = true if input[0] == '-'
input.delete!('-')
if(input.include? '.')
  input = input.split ('.')
  input[1] = input[1][0..1]
else
  input = [input,'00']
end
input[0].reverse!
output = []
input[0].chars.to_a.each_with_index do |c,i|
  if output[i/3]
    output[i/3] += c
  else
    output[i/3] = c
  end
end
output = output.reverse.map{ |x| x.reverse!}.join(',')
output = '$'+output+'.'+input[1]
output += '0' if input[1].size < 2
output = '(' + output + ')' if minus
puts output

number = gets.chomp
integer = nil
fraction = nil

if /\A([^\.]+)\.(\d+)\Z/=~ number
  integer = $1
  fraction = $2
elsif /\A([^\.]+)\Z/=~ number
  integer = $1
else
  raise
end

minus = false
minus = true if /\A\-/=~ integer
integer.gsub!( /\A\-/, "" )
integer = integer.reverse.gsub( /\d\d\d/, '\&,' ).reverse
integer.gsub!( /\A,/, "" )

if fraction.nil?
  fraction = "00"
end
if fraction.size < 2
  fraction += "0"
end
fraction = fraction.split(//)[0..1].join("")

if minus
  puts "($#{ integer }.#{ fraction })"
else
  puts "$#{ integer }.#{ fraction }"
end

n = gets.chomp
a,b = n.gsub("-","").split(".")
b = b || "0"
b = b[0..1].ljust(2,"0")
a = a.reverse.scan(/.{1,3}/).map(&:reverse).reverse.join(",")

number = "#{a}.#{b}"

if n[0] != "-"
	puts "$#{number}"
else
	puts "($#{number})"
end

s = gets.strip
if s[/\./]
  s += '00'
else
  s += '.00'
end
if s.match(/\A(-)?([\d]+)\.(\d\d)/)
  sign, main, sub = $1, $2, $3
  main = (main.reverse.scan(/.{1,3}/)*",").reverse
  if sign
    puts "($#{main}.#{sub})"
  else
    puts "$#{main}.#{sub}"
  end

end

n = gets.strip
m = false

if(n[0] == '-')
    m = true
    n.delete! '-'
end

i, f = n.split(/\./)

if(f == nil)
    f = "00";
end

if(f.size == 1)
    f += '0'
end

ans = '$'
siz = i.size

i.each_char do
    |c|
    siz -= 1;
    ans += c;

    if(siz % 3 == 0 and siz != 0)
        ans += ','
    end
    #puts(ans)
end

ans += '.'
ans += f[0,2]

if(m)
    print("(", ans, ")")
end

if(!m)
    print(ans)
end

input = gets.strip
surround = input[0] == "-" ? (input[0] = ""; true) : false

input = input.split '.'
l = []

input[0].split('').reverse.each_slice(3) { |s| l << s.reverse.join + "," }
l = l.reverse.join.chop

r = input[1]
r = "00"    if r.nil?
r = r + "0" if r.length == 1
r = r[0, 2] if r.length >= 2

print '(' if surround
print '$', l, '.', r
print ')' if surround

n = gets.strip
m = false

p n
if n[0] == "-"
  m = true
  n.delete! "-"
end

i,f = n.split(/\./)
p i
f = "00" if f == nil
f += "0" if f.size == 1

s = i.size
a = "$"
i.each_char do |c|
  a += c
  s -= 1
  a += ","if s % 3 == 0 && s != 0
end
a += "."
a += f[0,2]

if m
  a = "(" + a
  a += ")"
end
puts a

number = gets.chomp
integer = nil
fraction = nil

case number
  when /\A([^\.]+)\.(\d+)\Z/
  integer = $1
  fraction = $2
  when /\A([^\.]+)\Z/
  integer = $1
end

minus = false
minus = true if /\A\-/=~ integer
integer.gsub!( /\A\-/, "" )
if integer.size > 3
  integer = integer.reverse.gsub( /\d\d\d/, '\&,' ).reverse
end

if fraction.nil?
  fraction = "00"
end
if fraction.size < 2
  fraction += "0"
end
fraction = fraction.split(//)[0..1].join("")

if minus
  puts "($#{ integer }.#{ fraction })"
else
  puts "$#{ integer }.#{ fraction }"
end

number = gets.chomp
integer = nil
fraction = nil

if /\A([^\.]+)\.(\d+)\Z/=~ number
  integer = $1
  fraction = $2
elsif /\A([^\.]+)\Z/=~ number
  integer = $1
else
  raise
end

minus = false
minus = true if /\A\-/=~ integer
integer.gsub!( /\A\-/, "" )
if integer.size > 3
  integer = integer.reverse.gsub( /\d\d\d/, '\&,' ).reverse
end

if fraction.nil?
  fraction = "00"
end
if fraction.size < 2
  fraction += "0"
end
fraction = fraction.split(//)[0..1].join("")

if minus
  puts "($#{ integer }.#{ fraction })"
else
  puts "$#{ integer }.#{ fraction }"
end

number = gets.chomp
integer = nil
fraction = nil

case number
  when /\A([^\.]+)\.(\d+)\Z/
  integer = $1
  fraction = $2
  when /\A([^\.]+)\Z/
  integer = $1
end

minus = false
minus = true if /\A\-/=~ integer
integer.gsub!( /\A\-/, "" )
integer = integer.reverse.gsub( /\d\d\d/, '\&,' ).reverse

if fraction.nil?
  fraction = "00"
end
if fraction.size < 2
  fraction += "0"
end
fraction = fraction.split(//)[0..1].join("")

if minus
  puts "($#{ integer }.#{ fraction })"
else
  puts "$#{ integer }.#{ fraction }"
end

# p minus
# p integer
# p fraction

n = gets.strip
m = false

if(n[0] == '-')
    m = true
    n.delete! '-'
end

i, f = n.split(/\./)

if(f == nil)
    f = "00";
end

if(f.size == 1)
    f += '0'
end

ans = '$'
siz = i.size

i.each_char do
    |c|
    siz -= 1;
    ans += c;

    if(siz % 3 == 0 and siz != 0)
        ans += ','
    end
    #puts(ans)
end

ans += '.'
ans += f[0..2]

if(m)
    print("(", ans, ")")
end

if(!m)
    print(ans)
end


You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≤ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp × i. If the answer is positive, find one way to rearrange the characters.

The only line contains the initial string s, consisting of small Latin letters (1 ≤ |s| ≤ 1000).

If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO".

NoteIn the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba".In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4).In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid.

require"prime"
$char_num={}
def max_char
	a,max="",0
	?a.upto(?z){|c|
		if max<$char_num[c]
			max=$char_num[c]
			a=c
		end
	}
	[a,max]
end
s=gets.chomp
size=s.size
flag=Array.new(size+1,false)
?a.upto(?z){|c|$char_num[c]=s.count c}
Prime.each(size){|p|
	i=size/p
	1.upto(i){|j|flag[p*j]=true} if i>1
}
w=flag.count(true)
a,max=max_char
if w>max
	puts "NO"
else
	puts "YES"
	j=-1
	s=""
	$char_num[a]-=w
	?a.upto(?z){|c|s+=(c*$char_num[c])}
	1.upto(size+1){|k|
		print flag[k] ? a : s[j+=1]
	}
	puts
end

str = gets
str = str.chop
chararray = []
primeTable = [2]
3.upto(1000) { |i|
	dividable = false
	primeTable.each { |j|
		if i % j == 0
			dividable = true
			break
		end
	}
	primeTable.push(i) if !dividable
}
str.each_char {|i|
	chararray.push(i)
}
chararray.sort!

equlationSet = []
0.upto(str.length - 1) { |i|
	times = str.length / primeTable[i]
	break if(times <= 1)
	1.upto(times) { |j|
		equlationSet.push(primeTable[i] * j) if !equlationSet.include?(primeTable[i] * j)
	}
}
maxCharacter = ""
maxNumber = 0
num = 0
curChar = chararray[0]
chararray.each {|i|
	if(curChar != i)
		curChar = i
		num = 1
	else
		num += 1
		if maxNumber < num
			maxNumber = num
			maxCharacter = curChar
		end
	end
}

if(maxNumber >= equlationSet.length)
	puts "YES"
	equlationSet.sort!
	result = ""
	setInd = 0
	charInd = 0
	0.upto(str.length - 1) { |i|
		if equlationSet[setInd] == i + 1
			result.concat(maxCharacter)
			setInd += 1
		else
			while str[charInd] == maxCharacter
				charInd += 1
			end
			if(charInd < str.length)
				result.concat(str[charInd])
				charInd += 1
			else
				result.concat(maxCharacter)
			end
		end
	}
	puts result
else
	puts "NO"
end

str = gets
str = str.chop
chararray = []
primeTable = [2]
3.upto(1000) { |i|
	dividable = false
	primeTable.each { |j|
		if i % j == 0
			dividable = true
			break
		end
	}
	primeTable.push(i) if !dividable
}
str.each_char {|i|
	chararray.push(i)
}
chararray.sort!

equlationSet = []
0.upto(str.length - 1) { |i|
	times = str.length / primeTable[i]
	break if(times <= 1)
	1.upto(times) { |j|
		equlationSet.push(primeTable[i] * j) if !equlationSet.include?(primeTable[i] * j)
	}
}
maxCharacter = ""
maxNumber = 0
num = 0
curChar = chararray[0]
chararray.each {|i|
	if(curChar != i)
		curChar = i
		num = 1
	else
		if maxNumber < num
			maxNumber = num
			maxCharacter = curChar
		end
		num += 1
	end
}

if(maxNumber >= equlationSet.length)
	puts "YES"
	equlationSet.sort!
	result = ""
	setInd = 0
	charInd = 0
	0.upto(str.length - 1) { |i|
		if equlationSet[setInd] == i + 1
			result.concat(maxCharacter)
			setInd += 1
		else
			while str[charInd] == maxCharacter
				charInd += 1
			end
			if(charInd < str.length)
				result.concat(str[charInd])
				charInd += 1
			else
				result.concat(maxCharacter)
			end
		end
	}
	puts result
else
	puts "NO"
end


Vasya decided to go to the grocery store. He found in his wallet $$$a$$$ coins of $$$1$$$ burle and $$$b$$$ coins of $$$2$$$ burles. He does not yet know the total cost of all goods, so help him find out $$$s$$$ ($$$s > 0$$$): the minimum positive integer amount of money he cannot pay without change or pay at all using only his coins.For example, if $$$a=1$$$ and $$$b=1$$$ (he has one $$$1$$$-burle coin and one $$$2$$$-burle coin), then:  he can pay $$$1$$$ burle without change, paying with one $$$1$$$-burle coin,  he can pay $$$2$$$ burle without change, paying with one $$$2$$$-burle coin,  he can pay $$$3$$$ burle without change by paying with one $$$1$$$-burle coin and one $$$2$$$-burle coin,  he cannot pay $$$4$$$ burle without change (moreover, he cannot pay this amount at all). So for $$$a=1$$$ and $$$b=1$$$ the answer is $$$s=4$$$.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The description of each test case consists of one line containing two integers $$$a_i$$$ and $$$b_i$$$ ($$$0 \le a_i, b_i \le 10^8$$$) — the number of $$$1$$$-burle coins and $$$2$$$-burles coins Vasya has respectively.

For each test case, on a separate line print one integer $$$s$$$ ($$$s > 0$$$): the minimum positive integer amount of money that Vasya cannot pay without change or pay at all.

Note  The first test case of the example is clarified into the main part of the statement.  In the second test case, Vasya has only $$$1$$$ burle coins, and he can collect either any amount from $$$1$$$ to $$$4$$$, but $$$5$$$ can't.  In the second test case, Vasya has only $$$2$$$ burle coins, and he cannot pay $$$1$$$ burle without change.  In the fourth test case you don't have any coins, and he can't even pay $$$1$$$ burle.

Integer(gets).times do
    a, b = gets.split.map(&:to_i)
    if a == 0
        puts 1
    else
        puts a + b * 2 + 1
    end
end

t=gets.chomp.to_i

t.times do

s=gets.chomp.split
a=s[0].to_i
b=s[1].to_i
if (a==0 && b!=0)
    puts 1.to_i
else
    puts (a*1+b*2)+1
end
end


You've got a undirected graph G, consisting of n nodes. We will consider the nodes of the graph indexed by integers from 1 to n. We know that each node of graph G is connected by edges with at least k other nodes of this graph. Your task is to find in the given graph a simple cycle of length of at least k + 1.A simple cycle of length d (d > 1) in graph G is a sequence of distinct graph nodes v1, v2, ..., vd such, that nodes v1 and vd are connected by an edge of the graph, also for any integer i (1 ≤ i < d) nodes vi and vi + 1 are connected by an edge of the graph.

The first line contains three integers n, m, k (3 ≤ n, m ≤ 105; 2 ≤ k ≤ n - 1) — the number of the nodes of the graph, the number of the graph's edges and the lower limit on the degree of the graph node. Next m lines contain pairs of integers. The i-th line contains integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the indexes of the graph nodes that are connected by the i-th edge.  It is guaranteed that the given graph doesn't contain any multiple edges or self-loops. It is guaranteed that each node of the graph is connected by the edges with at least k other nodes of the graph.

In the first line print integer r (r ≥ k + 1) — the length of the found cycle. In the next line print r distinct integers v1, v2, ..., vr (1 ≤ vi ≤ n) — the found simple cycle. It is guaranteed that the answer exists. If there are multiple correct answers, you are allowed to print any of them.

require 'set'

n,m,k=gets.split.map(&:to_i)
graph=Array.new(n) {Set.new}
m.times {
  a,b=gets.split.map {|i| i.to_i-1}
  graph[a]<<b
  graph[b]<<a
}

path=Set.new
path<<0
last=0

while true
  ok=false
  graph[last].each {|i|
    if !path.include?(i)
      path<<i
      last=i
      ok=true
      break
    end
  }

  break if(!ok)
end

inpath=false
path.each_with_index {|v,i|
  if !inpath && graph[last].include?(v)
    inpath=true;
    puts path.size-i
  end

  print "#{v+1} " if inpath
}

require 'set'

n,m,k=gets.split.map(&:to_i)
graph=Array.new(n) {Set.new}
m.times {
  a,b=gets.split.map {|i| i.to_i-1}
  graph[a]<<b
  graph[b]<<a
}

path=Set.new
path<<0
last=0

while true
  ok=false
  graph[last].each {|i|
    if !path.include?(i)
      path<<i
      last=i
      ok=true
      break
    end
  }

  break if(!ok)
end

inpath=false
path.each_with_index {|v,i|
  if !inpath && graph[last].include?(v)
    inpath=true;
    puts path.size-i
  end

  print "#{i+1} " if inpath
}


Ayoub thinks that he is a very smart person, so he created a function $$$f(s)$$$, where $$$s$$$ is a binary string (a string which contains only symbols "0" and "1"). The function $$$f(s)$$$ is equal to the number of substrings in the string $$$s$$$ that contains at least one symbol, that is equal to "1".More formally, $$$f(s)$$$ is equal to the number of pairs of integers $$$(l, r)$$$, such that $$$1 \leq l \leq r \leq |s|$$$ (where $$$|s|$$$ is equal to the length of string $$$s$$$), such that at least one of the symbols $$$s_l, s_{l+1}, \ldots, s_r$$$ is equal to "1". For example, if $$$s = $$$"01010" then $$$f(s) = 12$$$, because there are $$$12$$$ such pairs $$$(l, r)$$$: $$$(1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5)$$$.Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers $$$n$$$ and $$$m$$$ and asked him this problem. For all binary strings $$$s$$$ of length $$$n$$$ which contains exactly $$$m$$$ symbols equal to "1", find the maximum value of $$$f(s)$$$.Mahmoud couldn't solve the problem so he asked you for help. Can you help him?

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$)  — the number of test cases. The description of the test cases follows. The only line for each test case contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n \leq 10^{9}$$$, $$$0 \leq m \leq n$$$) — the length of the string and the number of symbols equal to "1" in it.

For every test case print one integer number — the maximum value of $$$f(s)$$$ over all strings $$$s$$$ of length $$$n$$$, which has exactly $$$m$$$ symbols, equal to "1".

NoteIn the first test case, there exists only $$$3$$$ strings of length $$$3$$$, which has exactly $$$1$$$ symbol, equal to "1". These strings are: $$$s_1 = $$$"100", $$$s_2 = $$$"010", $$$s_3 = $$$"001". The values of $$$f$$$ for them are: $$$f(s_1) = 3, f(s_2) = 4, f(s_3) = 3$$$, so the maximum value is $$$4$$$ and the answer is $$$4$$$.In the second test case, the string $$$s$$$ with the maximum value is "101".In the third test case, the string $$$s$$$ with the maximum value is "111".In the fourth test case, the only string $$$s$$$ of length $$$4$$$, which has exactly $$$0$$$ symbols, equal to "1" is "0000" and the value of $$$f$$$ for that string is $$$0$$$, so the answer is $$$0$$$.In the fifth test case, the string $$$s$$$ with the maximum value is "01010" and it is described as an example in the problem statement.

T = gets.to_i

def sum(x)
  (x * (x + 1)) / 2
end

T.times do
  n, m = gets.split.map(&:to_i)

  if m == 0
    puts 0
    next
  end

  all = sum(n)

  if n == m
    puts all
    next
  end

  div = m + 1
  r = n - m

  if r <= div
    puts all - r
  else
    mod = r % div
    base = r / div
    res = all - (div - mod) * sum(base) - mod * sum(base + 1)

    puts res
  end
end


The tournament «Sleepyhead-2010» in the rapid falling asleep has just finished in Berland. n best participants from the country have participated in it. The tournament consists of games, each of them is a match between two participants. n·(n - 1) / 2 games were played during the tournament, and each participant had a match with each other participant. The rules of the game are quite simple — the participant who falls asleep first wins. The secretary made a record of each game in the form «xi yi», where xi and yi are the numbers of participants. The first number in each pair is a winner (i.e. xi is a winner and yi is a loser). There is no draws.Recently researches form the «Institute Of Sleep» have found that every person is characterized by a value pj — the speed of falling asleep. The person who has lower speed wins. Every person has its own value pj, constant during the life. It is known that all participants of the tournament have distinct speeds of falling asleep. Also it was found that the secretary made records about all the games except one. You are to find the result of the missing game.

The first line contains one integer n (3 ≤ n ≤ 50) — the number of participants. The following n·(n - 1) / 2 - 1 lines contain the results of the games. Each game is described in a single line by two integers xi, yi (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi и yi are the numbers of the opponents in this game. It is known that during the tournament each of the n participants played n - 1 games, one game with each other participant.

Output two integers x and y — the missing record. If there are several solutions, output any of them.

def findij(ar, n)
	for i in 0..n-1
		for j in 0..n-1
			next if i == j
			if ar[i][j] == 0
				return i,j
			end
		end
	end
end

n = gets.to_i
ar = Array.new(n)
for i in 0..n-1
	ar[i] = Array.new(n)
	for j in 0..n-1
		ar[i][j] = 0
	end
end

for i in 1..(n*(n-1)/2-1)
	s = gets.chomp
	as,bs = s.split(/ /)
	a = as.to_i-1
	b = bs.to_i-1

	ar[a][b] = 1
	ar[b][a] = -1
end

i,j = findij(ar,n)
for k in 0..n-1
	next if i == k
	next if j == k
	if ar[i][k] * ar[k][j] > 0
		if ar[i][k] > 0
			puts sprintf("%d %d",i+1,j+1)
		else
			puts sprintf("%d %d",j+1,i+1)
		end
		exit
	end
end
puts sprintf("%d %d",i+1,j+1)

n = gets.to_i

comb = (1..n).to_a.combination(2).to_a

list = []

won = {}
lost = {}

(((n * (n-1))/2)-1).times do
	l = gets.split(" ").map(&:to_i)
	won[l[0]] ||= []
	won[l[0]] << l[1]

	lost[l[1]] ||= []
	lost[l[1]] << l[0]

	list << l.minmax
end

missed = (comb - list).flatten
# puts "#{missed}"
# puts "#{won[missed[0]]}"
# puts "#{lost[missed[1]]}"
if ((won[missed[0]]||[]) & (lost[missed[1]] || [])).empty?
	missed[0],missed[1] = missed[1],missed[0]
end
puts "#{missed[0]} #{missed[1]}"

n = gets.to_i
h = Hash.new
for i in 1..n
	for j in i+1..n
		h[i.to_s + " " + j.to_s] = 0
	end
end

for i in 1..(n*(n-1)/2-1)
	s = gets.chomp
	as,bs = s.split(/ /)
	a = as.to_i
	b = bs.to_i
	if a > b
		ma = a
		mb = b
	else
		ma = b
		mb = a
	end
	h.delete(mb.to_s + " " + ma.to_s)
end

h.each_key { |m|
	puts m
}


Someone gave Alyona an array containing n positive integers a1, a2, ..., an. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1, b2, ..., bn such that 1 ≤ bi ≤ ai for every 1 ≤ i ≤ n. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of elements in the Alyona's array. The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the array.

Print one positive integer — the maximum possible value of mex of the array after Alyona applies some (possibly none) operations.

NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements.

#!/usr/bin/ruby
r=1
gets;gets.split.map(&:to_i).sort.each{|e|e.to_i>=r&&r+=1}
p r

n = gets.to_i

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

numbers.sort!

if numbers.count == 1
  puts 2
else
  max = 1
  numbers.each do |n|
    max = max + 1 if n >= max
  end
  puts max
end

#! /usr/bin/env ruby

n=gets.to_i
a=gets.split.map{|v|v.to_i}.sort
m=1
a.each {|v| m+=1 if v>=m }
puts m

gets
m=1
a=gets.chomp.split.map(&:to_i).sort
a.each{|k| m+=1 if k>=m}
print(m)

gets
mex = 1
nums = gets.split(' ').map(&:to_i).sort.each { |n|
  if n >= mex
    mex += 1
  end
}
puts mex

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

as.sort!

mex = 1
for i in 0...n
  if mex <= as[i]
    as [i] = mex
    mex += 1
  end
end

puts mex

p gets.to_i - gets.split.map(&:to_i).sort.map.with_index{|x,i| [i+1-x,0].max}.max + 1

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

n = read_line[0]
a = read_line.sort
x = 1

n.times { |i|
	x = x+1 if x<=a[i]
}

puts x

arrLength = gets.chomp.to_i
arr = gets.chomp.split(' ').map(&:to_i)

arr.sort!
currentNum = 1

arr.each_with_index do |val, index|
	currentNum += 1 if val >= currentNum
end

puts currentNum

#!/usr/bin/ruby
r=1
gets;gets.split.each{|e|e.to_i>=r&&r+=1}
p r

n = gets.to_i

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

numbers.sort!

if numbers.count == 1
  puts 2
else
  max = 1
  numbers.each do |n|
    if n > max + 1
      max = max + 1
    else
      max = n
    end
  end
  puts max + 1
end

n = gets.to_i

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

numbers.sort!

if numbers[0] == numbers[-1]
  puts numbers[0] + 1
elsif numbers[0] > 1
  puts numbers.count + 1
else
  max = 1
  numbers.each do |n|
    if n > max + 1
      max = max + 1
    else
      max = n
    end
  end
  puts max + 1
end

n = gets.to_i

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

numbers.sort!

if numbers[0] > 1
  puts 2
else
  max = 1
  numbers.each do |n|
    if n > max + 1
      max = max + 1
    else
      max = n
    end
  end
  puts max + 1
end

n = gets.to_i

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

numbers.sort!

if numbers[0] > 1 && numbers.count != 1 && numbers[0] == numbers[-1]
  puts 3
elsif numbers[0] > 1
  puts numbers.count + 1
else
  max = 1
  numbers.each do |n|
    if n > max + 1
      max = max + 1
    else
      max = n
    end
  end
  puts max + 1
end

n = gets.to_i

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

numbers.sort!

if numbers.count != 1 && numbers[0] == numbers[-1]
  puts numbers[0] + 1
elsif numbers[0] > 1
  puts numbers.count + 1
else
  max = 1
  numbers.each do |n|
    if n > max + 1
      max = max + 1
    else
      max = n
    end
  end
  puts max + 1
end

n = gets.to_i

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

numbers.sort!

if numbers[0] > 1
  puts numbers.count + 1
else
  max = 1
  numbers.each do |n|
    if n > max + 1
      max = max + 1
    else
      max = n
    end
  end
  puts max + 1
end

n = gets.to_i

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

numbers.sort!

if numbers[0] > 1
  puts numbers[0] - 1
else
  max = 1
  numbers.each do |n|
    if n > max + 1
      max = max + 1
    else
      max = n
    end
  end
  puts max + 1
end

n = gets.to_i

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

numbers.sort!

if numbers[0] == numbers[-1]
  puts numbers[0] + 1
elsif numbers[0] > 1
  puts numbers.count + 1
else
  max = 1
  numbers.each do |n|
    if n > max + 1
      max = max + 1
    else
      max = n
    end
    puts max
  end
  puts max + 1
end

n = gets.to_i

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

numbers.sort!

if numbers[0] > 1 || numbers[0] == numbers[-1]
  puts numbers.count + 1
else
  max = 1
  numbers.each do |n|
    if n > max + 1
      max = max + 1
    else
      max = n
    end
  end
  puts max + 1
end

n = gets.to_i

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

numbers.sort!

# if numbers[0] > 1
#   puts numbers.count + 1
# else
  max = 1
  numbers.each do |n|
    if n > max + 1
      max = max + 1
    else
      max = n
    end
  end
  puts max + 1
# end

n = gets.to_i

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

numbers.sort!

if numbers.count == 1
  puts 2
else
  max = 1
  numbers.each do |n|
    puts max
    if n > max + 1
      max = max + 1
    else
      max = n
    end
  end
  puts max + 1
end

n = gets.to_i

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

numbers.sort!

if numbers.count != 1 && numbers[0] == numbers[-1]
  puts 3
elsif numbers[0] > 1
  puts numbers.count + 1
else
  max = 1
  numbers.each do |n|
    if n > max + 1
      max = max + 1
    else
      max = n
    end
  end
  puts max + 1
end

gets
m=1
a=gets.chomp.split.map(&:to_i)
a.each{|k| m+=1 if k>=m}
print(m)

gets
m=1
for k in gets.split.sort
if k.to_i>=m
    m=m+1
end
end
print(m)


Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters.

For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints.

4

3 2

aab

3 3

aab

7 1

abacaba

2 0

ab

NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab.

class Array
  def n
    return length
  end
  def z
	return length-1
end
end

$__cur_readed = []
$__cur_index = 0

def rs
	while $__cur_index >= $__cur_readed.length
		$__cur_readed = gets.split(" ")
		$__cur_index = 0
	end
	$__cur_index+=1
	return $__cur_readed[$__cur_index-1]
end

def ri
	rs.to_i
end

def ra2 n
	Array.new(n) {ri}
end

def ra
	ra2 ri
end

t = ri

for _ in (1..t)
	ri
	k = ri
	s = rs
	res = 1
	if k > 0
		if s != s.reverse
			res = 2
		end
	end
	puts res
end

case_count = gets.to_i

case_count.times do
  n, k = gets.chomp.split(" ").map(&:to_i)
  str = gets.chomp

  if k.zero?
    puts 1
  else
    puts str == str.reverse ? 1 : 2
  end
end

gets.to_i.times do
  n, k = gets.split.map(&:to_i)
  s = gets.strip

  if k == 0 || s == s.reverse
    puts 1
  else
    puts 2
  end
end

case_count = gets.to_i

case_count.times do
  n, k = gets.split(" ").map(&:to_i)
  str = gets

  if k.zero?
    puts 1
  else
    puts str == str.reverse ? 1 : 2
  end
end

case_count = gets.to_i

case_count.times do
  n, k = gets.split(" ").map(&:to_i)
  str = gets

  puts str == str.reverse ? 1 : 2
end


It is well known that the planet suffers from the energy crisis. Little Petya doesn't like that and wants to save the world. For this purpose he needs every accumulator to contain the same amount of energy. Initially every accumulator has some amount of energy: the i-th accumulator has ai units of energy. Energy can be transferred from one accumulator to the other. Every time x units of energy are transferred (x is not necessarily an integer) k percent of it is lost. That is, if x units were transferred from one accumulator to the other, amount of energy in the first one decreased by x units and in other increased by  units.Your task is to help Petya find what maximum equal amount of energy can be stored in each accumulator after the transfers.

First line of the input contains two integers n and k (1 ≤ n ≤ 10000, 0 ≤ k ≤ 99) — number of accumulators and the percent of energy that is lost during transfers. Next line contains n integers a1, a2, ... , an — amounts of energy in the first, second, .., n-th accumulator respectively (0 ≤ ai ≤ 1000, 1 ≤ i ≤ n).

Output maximum possible amount of energy that can remain in each of accumulators after the transfers of energy. The absolute or relative error in the answer should not exceed 10 - 6.

#!/usr/bin/ruby

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

left = arr.min.to_f
right = arr.max.to_f

while right-left > 1e-6
	mid = (left+right)/2
	upper,lower = arr.partition { |v| v > mid }
	x = upper.map { |v| v - mid }.inject(&:+)
	l = lower.map { |v| v - mid }.inject(&:+)

	if l+x-x*k/100 >= 0
		left = mid
	else
		right = mid
	end
end

printf "%.7f\n", (left+right)/2

def rest(a, pr, x)
  a.inject(0){|r,j| r + (j>x ? (j-x)*pr : j-x)}
end

def solve(a, k)
  x0 = a.min.to_f
  x1 = a.max.to_f

  y0 = rest(a, 1-k/100.0, x0)
  return x0 if y0 == 0

  y1 = rest(a, 1-k/100.0, x1)
  return x1 if y1 == 0

  while x1-x0 > 1e-8
    x2 = (x0+x1)/2
    y2 = rest(a, 1-k/100.0, x2)
    return x2 if y2 == 0

    if y2 < 0
      x1 = x2
    else
      x0 = x2
    end
  end

  x0
end

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

#srand(123)
#a = 10000.times.map{rand(1000)}

p solve(a, k).to_f


Let's call an array of non-negative integers $$$a_1, a_2, \ldots, a_n$$$ a $$$k$$$-extension for some non-negative integer $$$k$$$ if for all possible pairs of indices $$$1 \leq i, j \leq n$$$ the inequality $$$k \cdot |i - j| \leq min(a_i, a_j)$$$ is satisfied. The expansion coefficient of the array $$$a$$$ is the maximal integer $$$k$$$ such that the array $$$a$$$ is a $$$k$$$-extension. Any array is a 0-expansion, so the expansion coefficient always exists.You are given an array of non-negative integers $$$a_1, a_2, \ldots, a_n$$$. Find its expansion coefficient.

The first line contains one positive integer $$$n$$$ — the number of elements in the array $$$a$$$ ($$$2 \leq n \leq 300\,000$$$). The next line contains $$$n$$$ non-negative integers $$$a_1, a_2, \ldots, a_n$$$, separated by spaces ($$$0 \leq a_i \leq 10^9$$$).

Print one non-negative integer — expansion coefficient of the array $$$a_1, a_2, \ldots, a_n$$$.

NoteIn the first test, the expansion coefficient of the array $$$[6, 4, 5, 5]$$$ is equal to $$$1$$$ because $$$|i-j| \leq min(a_i, a_j)$$$, because all elements of the array satisfy $$$a_i \geq 3$$$. On the other hand, this array isn't a $$$2$$$-extension, because $$$6 = 2 \cdot |1 - 4| \leq min(a_1, a_4) = 5$$$ is false.In the second test, the expansion coefficient of the array $$$[0, 1, 2]$$$ is equal to $$$0$$$ because this array is not a $$$1$$$-extension, but it is $$$0$$$-extension.

def min(a, b) ; return a < b ? a : b ; end
N = gets.to_i
arr = gets.split.map(&:to_i)
k = min(arr[0], arr[-1]) / (N-1)
for h in 1...arr.size-1
	tmp = min(arr[0], arr[h]) / h
	k = tmp if k > tmp
	tmp = min(arr[h], arr[-1])/ (N-1 - h)
	k = tmp if k > tmp
#	puts k
end
puts k

def min a, b ; return a < b ? a : b ; end
N = gets.to_i
arr = gets.split.map(&:to_i)
k = min(arr[0], arr[-1]) / (N-1)
MIN = arr.min
if MIN == 0
	puts 0
	exit
end
indexMIN = arr.index(MIN)
if indexMIN==0 || indexMIN==N-1
	puts MIN / (N-1)
	exit
end
tmp = MIN / indexMIN
k = tmp if k > tmp
tmp = MIN / (N-1 - indexMIN)
k = tmp if k > tmp
puts k


You are given an array $$$a$$$ of $$$n$$$ integers, where $$$n$$$ is odd. You can make the following operation with it:  Choose one of the elements of the array (for example $$$a_i$$$) and increase it by $$$1$$$ (that is, replace it with $$$a_i + 1$$$). You want to make the median of the array the largest possible using at most $$$k$$$ operations.The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array $$$[1, 5, 2, 3, 5]$$$ is $$$3$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n$$$ is odd, $$$1 \le k \le 10^9$$$) — the number of elements in the array and the largest number of operations you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).

Print a single integer — the maximum possible median after the operations.

NoteIn the first example, you can increase the second element twice. Than array will be $$$[1, 5, 5]$$$ and it's median is $$$5$$$.In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is $$$3$$$.In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be $$$[5, 1, 2, 5, 3, 5, 5]$$$ and the median will be $$$5$$$.

n, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i).sort.drop(n / 2)

if n == 1
  puts a.first + k
  exit
end

puts (
  loop do
    i = a.index{ |i| i > a[0] }
    break a[0] + k / a.size unless i
    break a[0] + k / i unless i * (a[i] - a[0]) < k
    (0...i).each do |j|
      k -= a[i] - a[j]
      a[j] = a[i]
    end
  end
)

n, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i).sort.drop(n / 2)

if n == 1
  puts a.first + k
  exit
end

puts (
  loop do
    i = a.index{ |i| i > a[0] }
    break a[0] + k / a.size unless i
    break a[0] + k / i unless i * (a[i] - a[0]) < k
    (0...i).each do |j|
      k -= a[i] - a[0]
      a[j] = a[i]
    end
  end
)


An atom of element X can exist in n distinct states with energies E1 < E2 < ... < En. Arkady wants to build a laser on this element, using a three-level scheme. Here is a simplified description of the scheme. Three distinct states i, j and k are selected, where i < j < k. After that the following process happens:   initially the atom is in the state i, we spend Ek - Ei energy to put the atom in the state k, the atom emits a photon with useful energy Ek - Ej and changes its state to the state j, the atom spontaneously changes its state to the state i, losing energy Ej - Ei, the process repeats from step 1. Let's define the energy conversion efficiency as , i. e. the ration between the useful energy of the photon and spent energy.Due to some limitations, Arkady can only choose such three states that Ek - Ei ≤ U.Help Arkady to find such the maximum possible energy conversion efficiency within the above constraints.

The first line contains two integers n and U (3 ≤ n ≤ 105, 1 ≤ U ≤ 109) — the number of states and the maximum possible difference between Ek and Ei. The second line contains a sequence of integers E1, E2, ..., En (1 ≤ E1 < E2... < En ≤ 109). It is guaranteed that all Ei are given in increasing order.

If it is not possible to choose three states that satisfy all constraints, print -1. Otherwise, print one real number η — the maximum possible energy conversion efficiency. Your answer is considered correct its absolute or relative error does not exceed 10 - 9. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .

NoteIn the first example choose states 1, 2 and 3, so that the energy conversion efficiency becomes equal to .In the second example choose states 4, 5 and 9, so that the energy conversion efficiency becomes equal to .

n, u = gets.chomp.split(" ").map {|e| e.to_i}
arr = gets.chomp.split(" ").map {|e| e.to_i}

i = 0
j = 1
ll = arr.length
li = ll - 1
maxn = -1
while i < li
	oldj = j
	while (j < ll && arr[j] - arr[i] <= u)
		j += 1
	end
	j -= 1 if j != oldj
	if (j - i > 1)
		me = (arr[j] - arr[i+1])/(arr[j] - arr[i]).to_f
		if me > maxn
			# puts arr[j], arr[i]
			maxn = me
		end
	end
	i += 1
end
puts maxn

n, u = gets.chomp.split(" ").map {|e| e.to_i}
arr = gets.chomp.split(" ").map {|e| e.to_i}

i = 0
j = 1
ll = arr.length
li = ll - 1
maxn = -1
smd = 10**9
while i < li
	while (j < ll && arr[j] - arr[i] <= u)
		j += 1
	end
	j -= 1
	if (j - i > 1)
		if (arr[i+1] - arr[i] <= smd)
			smd = arr[i+1] - arr[i]
			me = (arr[j] - arr[i+1])/(arr[j] - arr[i]).to_f
			maxn = me if me > maxn
		end
	end
	i += 1
end
puts maxn

n, u = gets.chomp.split(" ").map {|e| e.to_i}
arr = gets.chomp.split(" ").map {|e| e.to_i}

i = 0
j = 1
ll = arr.length
li = ll - 1
maxn = -1
smd = 10**9
while i < li
	oldj = j
	while (j < ll && arr[j] - arr[i] <= u)
		j += 1
	end
	j -= 1 if j != oldj
	if (j - i > 1)
		if (arr[i+1] - arr[i] <= smd)
			smd = arr[i+1] - arr[i]
			me = (arr[j] - arr[i+1])/(arr[j] - arr[i]).to_f
			maxn = me if me > maxn
		end
	end
	i += 1
end
puts maxn


One very well-known internet resource site (let's call it X) has come up with a New Year adventure. Specifically, they decided to give ratings to all visitors.There are n users on the site, for each user we know the rating value he wants to get as a New Year Present. We know that user i wants to get at least ai rating units as a present.The X site is administered by very creative and thrifty people. On the one hand, they want to give distinct ratings and on the other hand, the total sum of the ratings in the present must be as small as possible.Help site X cope with the challenging task of rating distribution. Find the optimal distribution.

The first line contains integer n (1 ≤ n ≤ 3·105) — the number of users on the site. The next line contains integer sequence a1, a2, ..., an (1 ≤ ai ≤ 109).

Print a sequence of integers b1, b2, ..., bn. Number bi means that user i gets bi of rating as a present. The printed sequence must meet the problem conditions.  If there are multiple optimal solutions, print any of them.

n=gets.to_i
a=gets.split.each_with_index.map{|c,i|[c.to_i,i]}
a.sort_by!{|x,i|x}
q=-1
b=[0]*n
a.each do|x,i|
  q=x if q<x
  b[i]=q
  q+=1
end
puts b*' '


Vlad, like everyone else, loves to sleep very much.Every day Vlad has to do $$$n$$$ things, each at a certain time. For each of these things, he has an alarm clock set, the $$$i$$$-th of them is triggered on $$$h_i$$$ hours $$$m_i$$$ minutes every day ($$$0 \le h_i < 24, 0 \le m_i < 60$$$). Vlad uses the $$$24$$$-hour time format, so after $$$h=12, m=59$$$ comes $$$h=13, m=0$$$ and after $$$h=23, m=59$$$ comes $$$h=0, m=0$$$.This time Vlad went to bed at $$$H$$$ hours $$$M$$$ minutes ($$$0 \le H < 24, 0 \le M < 60$$$) and asks you to answer: how much he will be able to sleep until the next alarm clock.If any alarm clock rings at the time when he went to bed, then he will sleep for a period of time of length $$$0$$$.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the test. The first line of the case contains three integers $$$n$$$, $$$H$$$ and $$$M$$$ ($$$1 \le n \le 10, 0 \le H < 24, 0 \le M < 60$$$) — the number of alarms and the time Vlad went to bed. The following $$$n$$$ lines contain two numbers each $$$h_i$$$ and $$$m_i$$$ ($$$0 \le h_i < 24, 0 \le m_i < 60$$$) — the time of the $$$i$$$ alarm. It is acceptable that two or more alarms will trigger at the same time. Numbers describing time do not contain leading zeros.

Output $$$t$$$ lines, each containing the answer to the corresponding test case. As an answer, output two numbers  — the number of hours and minutes that Vlad will sleep, respectively. If any alarm clock rings at the time when he went to bed, the answer will be 0 0.

def get_time(hour, minutes)
  hour * 60 + minutes
end

def get_time_range(hour1, minutes1, hour2, minutes2)
  time1 = get_time(hour1, minutes1)
  time2 = get_time(hour2, minutes2)

  time = time2 - time1
  if time < 0
    time + 24 * 60
  else
    time
  end
end

def print_time(time)
  hour = time / 60
  minutes = time - hour * 60
  puts hour.to_s + " " + minutes.to_s
end

n = gets.chomp.to_i
found_times = Array.new
(1..n).each {
  input = gets.chomp.split(" ").map(&:to_i)
  number_of_clocks = input[0]
  hour_sleep = input[1]
  minutes_sleep = input[2]

  min_time_range = 24 * 60
  (1..number_of_clocks).each {
    time_input = gets.chomp.split(" ").map(&:to_i)
    hour = time_input[0]
    minutes = time_input[1]

    time_range = get_time_range(hour_sleep, minutes_sleep, hour, minutes)
    if min_time_range > time_range
      min_time_range = time_range
    end
  }

  found_times << min_time_range
}

found_times.each { |time|
  print_time(time)
}


A sequence $$$(b_1, b_2, \ldots, b_k)$$$ is called strange, if the absolute difference between any pair of its elements is greater than or equal to the maximum element in the sequence. Formally speaking, it's strange if for every pair $$$(i, j)$$$ with $$$1 \le i<j \le k$$$, we have $$$|a_i-a_j|\geq MAX$$$, where $$$MAX$$$ is the largest element of the sequence. In particular, any sequence of length at most $$$1$$$ is strange.For example, the sequences $$$(-2021, -1, -1, -1)$$$ and $$$(-1, 0, 1)$$$ are strange, but $$$(3, 0, 1)$$$ is not, because $$$|0 - 1| < 3$$$.Sifid has an array $$$a$$$ of $$$n$$$ integers. Sifid likes everything big, so among all the strange subsequences of $$$a$$$, he wants to find the length of the longest one. Can you help him?A sequence $$$c$$$ is a subsequence of an array $$$d$$$ if $$$c$$$ can be obtained from $$$d$$$ by deletion of several (possibly, zero or all) elements.

The first line contains an integer $$$t$$$ $$$(1\le t\le 10^4)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1\le n\le 10^5)$$$ — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(-10^9\le a_i \le 10^9)$$$ — the elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case output a single integer — the length of the longest strange subsequence of $$$a$$$.

NoteIn the first test case, one of the longest strange subsequences is $$$(a_1, a_2, a_3, a_4)$$$In the second test case, one of the longest strange subsequences is $$$(a_1, a_3, a_4, a_5, a_7)$$$.In the third test case, one of the longest strange subsequences is $$$(a_1, a_3, a_4, a_5)$$$.In the fourth test case, one of the longest strange subsequences is $$$(a_2)$$$.In the fifth test case, one of the longest strange subsequences is $$$(a_1, a_2, a_4)$$$.

gets.to_i.times do
  gets
  xs, ys = gets.split.map(&:to_i).sort.partition { |n| n <= 0 }
  p xs.count + (ys.size > 0 && (xs + ys.take(1)).each_cons(2).all? { |a, b| (a - b).abs >= ys[0] } ? 1 : 0)
end

t=gets.to_i
t.times{
n=gets.to_i
i=gets.split.map &:to_i
i.sort!
last=-1e18
cnt=0
mn=1e18
i.each{|num|
mn=[mn,num-last].min if last != -1e18
last=num
break if num>0
cnt+=1
}
p cnt < n && last <= mn ? cnt + 1 : cnt
}

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  x = gets.to_s.split.map {|x| x.to_i }.sort
  a = x.select {|x| x <= 0}
  b = x.select {|x| x > 0}

  mindiff = 10 ** 15
  1.upto(a.size - 1) do |i|
    diff = a[i] - a[i - 1]
    mindiff = diff if diff < mindiff
  end

  if b.size != 0 && b[0] <= mindiff
    printf("%d\n", a.size + 1)
  else
    printf("%d\n", a.size)
  end
end

INF = 10**18

def solve
  n = gets.to_i
  a = gets.split.map(&:to_i).sort
  diff_min = INF
  prev = -INF
  count = 0
  a.each do |x|
    diff = x - prev
    diff_min = diff if diff_min > diff
    break if diff_min < x
    count += 1
    prev = x
  end
  puts count
end

t = gets.to_i
t.times do
  solve
end

gets.to_i.times do
  gets
  xs, ys = gets.split.map(&:to_i).sort.partition { |n| n <= 0 }
  p xs.count + (xs.size <= 1 && ys.size > 0 || (xs.size >= 2 && ys.size >= 1 && (xs[-1] - xs[-2]).abs >= ys[0]) ? 1 : 0)
end

gets.to_i.times do
  gets
  xs, ys = gets.split.map(&:to_i).sort.partition { |n| n <= 0 }
  p xs.count + (xs.size <= 1 && ys.size > 0 || (xs.size >= 2 && ys.size >= 1 && (xs[-1] - xs[-2]).abs > ys[0]) ? 1 : 0)
end

gets.to_i.times do
  gets
  xs, ys = gets.split.map(&:to_i).sort.partition { |n| n <= 0 }
  p xs.count + (xs.size <= 1 && ys.size > 0 || (xs.size >= 2 && ys.size >= 1 && (xs[-1] + xs[-2]).abs > ys[0]) ? 1 : 0)
end

gets.to_i.times do
  gets
  xs, ys = gets.split.map(&:to_i).sort.partition { |n| n <= 0 }
  p xs.count + (xs.size == 0 || (xs.size >= 2 && ys.size >= 1 && (xs[-1] + xs[-2]).abs > ys[0]) ? 1 : 0)
end


You are given an array $$$a$$$ of length $$$n$$$, which initially is a permutation of numbers from $$$1$$$ to $$$n$$$. In one operation, you can choose an index $$$i$$$ ($$$1 \leq i < n$$$) such that $$$a_i < a_{i + 1}$$$, and remove either $$$a_i$$$ or $$$a_{i + 1}$$$ from the array (after the removal, the remaining parts are concatenated). For example, if you have the array $$$[1, 3, 2]$$$, you can choose $$$i = 1$$$ (since $$$a_1 = 1 < a_2 = 3$$$), then either remove $$$a_1$$$ which gives the new array $$$[3, 2]$$$, or remove $$$a_2$$$ which gives the new array $$$[1, 2]$$$.Is it possible to make the length of this array equal to $$$1$$$ with these operations?

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 2 \cdot 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 3 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \leq a_i \leq n$$$, $$$a_i$$$ are pairwise distinct) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 \cdot 10^5$$$.

For each test case, output on a single line the word "YES" if it is possible to reduce the array to a single element using the aforementioned operation, or "NO" if it is impossible to do so.

NoteFor the first two test cases and the fourth test case, we can operate as follow (the bolded elements are the pair chosen for that operation):$$$[\text{1}, \textbf{2}, \textbf{3}] \rightarrow [\textbf{1}, \textbf{2}] \rightarrow [\text{1}]$$$$$$[\text{3}, \textbf{1}, \textbf{2}, \text{4}] \rightarrow [\text{3}, \textbf{1}, \textbf{4}] \rightarrow [\textbf{3}, \textbf{4}] \rightarrow [\text{4}]$$$$$$[\textbf{2}, \textbf{4}, \text{6}, \text{1}, \text{3}, \text{5}] \rightarrow [\textbf{4}, \textbf{6}, \text{1}, \text{3}, \text{5}] \rightarrow [\text{4}, \text{1}, \textbf{3}, \textbf{5}] \rightarrow [\text{4}, \textbf{1}, \textbf{5}] \rightarrow [\textbf{4}, \textbf{5}] \rightarrow [\text{4}]$$$

t = gets.to_i
(1..t).each do |i|
  n = gets.to_i
  a = gets.strip.split.map(&:to_i)
  puts "YES" if(a[0] < a[n-1])
  puts "NO" if(a[0] > a[n-1])
end


Petya is the most responsible worker in the Research Institute. So he was asked to make a very important experiment: to melt the chocolate bar with a new laser device. The device consists of a rectangular field of n × m cells and a robotic arm. Each cell of the field is a 1 × 1 square. The robotic arm has two lasers pointed at the field perpendicularly to its surface. At any one time lasers are pointed at the centres of some two cells. Since the lasers are on the robotic hand, their movements are synchronized — if you move one of the lasers by a vector, another one moves by the same vector.The following facts about the experiment are known:   initially the whole field is covered with a chocolate bar of the size n × m, both lasers are located above the field and are active;  the chocolate melts within one cell of the field at which the laser is pointed;  all moves of the robotic arm should be parallel to the sides of the field, after each move the lasers should be pointed at the centres of some two cells;  at any one time both lasers should be pointed at the field. Petya doesn't want to become a second Gordon Freeman. You are given n, m and the cells (x1, y1) and (x2, y2), where the lasers are initially pointed at (xi is a column number, yi is a row number). Rows are numbered from 1 to m from top to bottom and columns are numbered from 1 to n from left to right. You are to find the amount of cells of the field on which the chocolate can't be melted in the given conditions.

The first line contains one integer number t (1 ≤ t ≤ 10000) — the number of test sets. Each of the following t lines describes one test set. Each line contains integer numbers n, m, x1, y1, x2, y2, separated by a space (2 ≤ n, m ≤ 109, 1 ≤ x1, x2 ≤ n, 1 ≤ y1, y2 ≤ m). Cells (x1, y1) and (x2, y2) are distinct.

Each of the t lines of the output should contain the answer to the corresponding input test set.

def min(x, y)
  x < y ? x : y
end

def max(x, y)
  x > y ? x : y
end

class Rectangle
  attr_reader :x1, :y1, :x2, :y2

  def initialize(x1, y1, x2, y2)
    @x1, @y1, @x2, @y2 = x1, y1, x2, y2
  end

  def get_s
    if @x1 <= @x2 and @y1 <= @y2
      return (@x1 - @x2).abs * (@y1 - @y2).abs
    else
      return 0
    end
  end

  def self.intersect(a, b)
    x1, x2 = max(a.x1, b.x1), min(a.x2, b.x2)
    y1, y2 = max(a.y1, b.y1), min(a.y2, b.y2)
    return Rectangle.new(x1, y1, x2, y2)
  end
end

def make_rect(n, m, x1, y1, x2, y2)
  x, y = max(0, x1 - x2), max(0, y1 - y2)
  width, height = n - (x1 - x2).abs, m - (y1 - y2).abs
  Rectangle.new(x, y, x + width, y + height)
end

gets.to_i.times do
  n, m, x1, y1, x2, y2 = gets.split.map { |v| v.to_i }
  a = make_rect(n, m, x1, y1, x2, y2)
  b = make_rect(n, m, x2, y2, x1, y1)
  c = Rectangle.new(0, 0, n, m)
  d = Rectangle.intersect(a, b)
  puts d.get_s + c.get_s - a.get_s - b.get_s
end

class Rectangle
	attr_reader :x1, :y1, :x2, :y2

	def initialize(x1, y1, x2, y2)
		@x1, @y1, @x2, @y2 = x1, y1, x2, y2
	end

	def get_area
		if @x1 <= @x2 and @y1 <= @y2
			return (@x2 - @x1) * (@y2 - @y1)
		else
			return 0
		end
	end

	def self.intersect(rect1, rect2)
		x1, x2 = [rect1.x1, rect2.x1].max, [rect1.x2, rect2.x2].min
  	y1, y2 = [rect1.y1, rect2.y1].max, [rect1.y2, rect2.y2].min
  	return Rectangle.new(x1, y1, x2, y2)
	end
end

def make_rectangle(n, m, x1, y1, x2, y2)
	x = [0, x1 - x2].max
	y = [0, y1 - y2].max
	x2 = x + n - (x1 - x2).abs
	y2 = y + m - (y1 - y2).abs
	return Rectangle.new(x, y, x2, y2)
end

gets.to_i.times do
	n, m, x1, y1, x2, y2 = gets.chomp!.split.map(&:to_i)
	rect1 = make_rectangle(n, m, x1, y1, x2, y2)
	rect2 = make_rectangle(n, m, x2, y2, x1, y1)
	intersection = Rectangle.intersect(rect1, rect2)
	total_pieces = Rectangle.new(0, 0, n, m)
	puts total_pieces.get_area - rect1.get_area - rect2.get_area + intersection.get_area
end

def min(x, y)
  x < y ? x : y
end

def max(x, y)
  x > y ? x : y
end

class Rectangle
  attr_reader :x1, :y1, :x2, :y2

  def initialize(x1, y1, x2, y2)
    @x1, @x2 = min(x1, x2), max(x1, x2)
    @y1, @y2 = min(y1, y2), max(y1, y2)
  end

  def get_s
    if @x1 <= @x2 and @y1 <= @y2
      return (@x1 - @x2).abs * (@y1 - @y2).abs
    else
      return 0
    end
  end

  def self.intersect(a, b)
    x1, x2 = max(a.x1, b.x1), min(a.x2, b.x2)
    y1, y2 = max(a.y1, b.y1), min(a.y2, b.y2)
    return Rectangle.new(x1, y1, x2, y2)
  end
end

def make_rect(n, m, x1, y1, x2, y2)
  x, y = max(0, x1 - x2), max(0, y1 - y2)
  width, height = n - (x1 - x2).abs, m - (y1 - y2).abs
  Rectangle.new(x, y, x + width, y + height)
end

gets.to_i.times do
  n, m, x1, y1, x2, y2 = gets.split.map { |v| v.to_i }
  a = make_rect(n, m, x1, y1, x2, y2)
  b = make_rect(n, m, x2, y2, x1, y1)
  c = Rectangle.new(0, 0, n, m)
  d = Rectangle.intersect(a, b)
  puts d.get_s + c.get_s - a.get_s - b.get_s
end


A robot cleaner is placed on the floor of a rectangle room, surrounded by walls. The floor consists of $$$n$$$ rows and $$$m$$$ columns. The rows of the floor are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and columns of the floor are numbered from $$$1$$$ to $$$m$$$ from left to right. The cell on the intersection of the $$$r$$$-th row and the $$$c$$$-th column is denoted as $$$(r,c)$$$. The initial position of the robot is $$$(r_b, c_b)$$$.In one second, the robot moves by $$$dr$$$ rows and $$$dc$$$ columns, that is, after one second, the robot moves from the cell $$$(r, c)$$$ to $$$(r + dr, c + dc)$$$. Initially $$$dr = 1$$$, $$$dc = 1$$$. If there is a vertical wall (the left or the right walls) in the movement direction, $$$dc$$$ is reflected before the movement, so the new value of $$$dc$$$ is $$$-dc$$$. And if there is a horizontal wall (the upper or lower walls), $$$dr$$$ is reflected before the movement, so the new value of $$$dr$$$ is $$$-dr$$$.Each second (including the moment before the robot starts moving), the robot cleans every cell lying in the same row or the same column as its position. There is only one dirty cell at $$$(r_d, c_d)$$$. The job of the robot is to clean that dirty cell.  Illustration for the first example. The blue arc is the robot. The red star is the target dirty cell. Each second the robot cleans a row and a column, denoted by yellow stripes. Given the floor size $$$n$$$ and $$$m$$$, the robot's initial position $$$(r_b, c_b)$$$ and the dirty cell's position $$$(r_d, c_d)$$$, find the time for the robot to do its job.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. A test case consists of only one line, containing six integers $$$n$$$, $$$m$$$, $$$r_b$$$, $$$c_b$$$, $$$r_d$$$, and $$$c_d$$$ ($$$1 \le n, m \le 100$$$, $$$1 \le r_b, r_d \le n$$$, $$$1 \le c_b, c_d \le m$$$) — the sizes of the room, the initial position of the robot and the position of the dirt cell.

For each test case, print an integer — the time for the robot to clean the dirty cell. We can show that the robot always cleans the dirty cell eventually.

NoteIn the first example, the floor has the size of $$$10\times 10$$$. The initial position of the robot is $$$(6, 1)$$$ and the position of the dirty cell is $$$(2, 8)$$$. See the illustration of this example in the problem statement.In the second example, the floor is the same, but the initial position of the robot is now $$$(9, 9)$$$, and the position of the dirty cell is $$$(1, 1)$$$. In this example, the robot went straight to the dirty cell and clean it.   In the third example, the floor has the size $$$9 \times 8$$$. The initial position of the robot is $$$(5, 6)$$$, and the position of the dirty cell is $$$(2, 1)$$$.   In the fourth example, the floor has the size $$$6 \times 9$$$. The initial position of the robot is $$$(2, 2)$$$ and the position of the dirty cell is $$$(5, 8)$$$.   In the last example, the robot was already standing in the same column as the dirty cell, so it can clean the cell right away.

main = -> {
  t = int
  t.times do
    n, m, rb, cb, rd, cd = ints

    tate =
      if rb <= rd
        rd - rb
      else
        n - rd + n - rb
      end
    yoko =
      if cb <= cd
        cd - cb
      else
        m - cd + m - cb
      end
    ans = [yoko, tate].min
    puts ans
  end
}

DEBUG = true
MOD = 10**9+7
$yesno = %w(No Yes)
YesNo = %w(No Yes)
YESNO = %w(NO YES)
INF = 10**9

require "set"
require "prime"

def int; gets.to_s.to_i end
def ints; gets.to_s.split.map { |s| s.to_i } end
def int1s; gets.to_s.split.map { |s| s.to_i - 1 } end
def float; gets.to_s.to_f end
def floats; gets.to_s.split.map { |s| s.to_f } end
def array_of(&convert); gets.to_s.split.map(&convert) end
def string; gets.to_s.chomp end
def strings; gets.to_s.split end
def rep(n, &b); Array.new(n, &b) end
def yes; puts $yesno[1] end
def no; puts $yesno[0] end
def yesno t; puts $yesno[t] end
def YesNo t; puts YesNo[t] end
def YESNO t; puts YESNO[t] end
def zip(xs, *yss); Enumerator.new { |y| xs.zip(*yss) { |a| y.yield(*a) } } end
def max(*xs, &block); block_given? ? xs.max_by(&block) : xs.max end
def min(*xs, &block); block_given? ? xs.min_by(&block) : xs.min end
def minmax(*xs, &block); block_given? ? xs.minmax_by(&block) : xs.minmax end
def gcd(*xs); xs.inject(0, :gcd) end
def matrix(h, w, fill=nil, &block); return Array.new(h) { Array.new(w, &block) } if block_given?; Array.new(h) { [fill] * w } end
def debug(x = nil); STDERR.puts (block_given? ? yield(x) : x).inspect if DEBUG; x end
def debug_grid(grid, width = 1); grid.each { |row| STDERR.puts row.map { |x| x.inspect.ljust(width) }.join("") } if DEBUG; grid end
def if_debug; yield if DEBUG end

module Boolean
  def coerce(other); [other, to_i] end
  def +@; to_i end
  def to_int; to_i end
  def *(other); to_i * other end
end

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

class Integer
  def div_ceil(y); (self + y - 1) / y end
  def mod_inv(mod = MOD); pow(mod-2, mod) end
  def mod_div(y, mod = MOD); self * mod_inv(y, mod) % mod end
  def factorial(mod = MOD); (2..self).inject(1) { |f, x| f * x % mod } end
  def popcount; x = self; c = 0; while x > 0; c += 1 if x & 1 == 1; x >>= 1 end; c end #TODO: faster
  def bitbrute(&block); (1<<self).times(&block) end
  def nCr(r); x = 1; (1..r).each { |i| x *= self + 1 - i; x /= i }; x; end
  def each_divisor; return Enumerator.new { |y| each_divisor { |k| y << k } } unless block_given?; k = 1; while k * k < self; if self % k == 0; yield k; yield self / k end; k += 1; end; yield k if k * k == self end
  def divisors; each_divisor.to_a end
end

class Range
  def end_open; exclude_end? ? self.end : self.end + 1 end
  def end_close; exclude_end? ? self.end - 1 : self.end end
  def upper_bound; ac, wa = self.begin, self.end_open; while wa - ac > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def lower_bound; ac, wa = self.end_open, self.begin; while ac - wa > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def shakutori(r2, &pred); Enumerator.new { |y| j, r = r2.begin, r2.end_open; each { |i| j += 1 while j + 1 < r and pred[i, j+1]; y.yield(i, j) } }; end
  def widest(&block); Enumerator.new { |y| j, n = self.begin, self.end_open; each { |i| j += 1 while j < n and block[i, j]; y.yield(i, j) if block[i, j] } } end
end

class Array
  def power(&block); (0 ... 1 << size).each(&block) end
  def sorted_merge(other); a = []; i = j = 0; n, m = size, other.size; if j < m and other[j] < self[i]; a << other[j]; j += 1 else; a << self[i]; i += 1 end while i < n; a.push(*other[j..-1]) if j < m; a end
  def upper_bound; ac, wa = 0, size; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def lower_bound; ac, wa = size, 0; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def cum(*xs, &op); a = []; a << xs[0] if xs.size > 0; a << x = self[0]; (1...size).each { |i| a << x = op[x, self[i]] }; a end
  def cumdiff(range); self[range.end_open] - self[range.begin]; end
end

module Enumerable
  def sorted_uniq; x = nil; filter { |y| c = x === y; x = y; !c } end
  def cumsum; ys = [0]; each { |x| ys << x + ys[-1] }; ys end
end

# 複数の素数を求めるような問題に高速に答えられる
class PrimeTable
	def initialize(n)
		@lpf = [nil] * (n + 1)
		@primes = [2]
		(2 .. n).step(2) do |d| @lpf[d] = 2 end
		(3 .. n).step(2) do |d|
			unless @lpf[d]
				@lpf[d] = d
				@primes << d
			end
			@primes.each do |p|
				break if p * d > n or p > @lpf[d]
				@lpf[p * d] = p
			end
		end
	end
	def prime?(n); @lpf[n] == n; end
	def each(&block); @primes.each(&block); end
	def factorize(n); fs = []; while n > 1; fs << (f = @lpf[n]); n /= f; end; fs; end
end

class Factorial
  def initialize(max, mod)
    @mod = mod
    @fac = [1, 1]
    @fin = [1, 1]
    @inv = [nil, 1]
    (2 .. max).each do |i|
      @fac[i] = @fac[i - 1] * i % mod
      @inv[i] = mod - @inv[mod % i] * (mod / i) % mod
      @fin[i] = @fin[i - 1] * @inv[i] % mod
    end
  end

  def fact(n)
    @fac[n]
  end

  def comb(n, k)
    return 0 if n < k or n < 0 or k < 0
    @fac[n] * @fin[k] % @mod * @fin[n - k] % @mod
  end
end

class UnionFind
  def initialize(size); @p = Array.new(size, -1); end
  def leader(i); j = i; j, i = i, @p[j] = @p[i] until @p[i] < 0; i; end
  def merge(i, j); k, l = leader(i), leader(j); return false if k == l; k, l = l, k if @p[k] > @p[l]; @p[k] += @p[l]; @p[l] = k; true; end
  def same?(i, j); leader(i) == leader(j); end
  def size(i); -@p[leader(i)]; end
  def groups; gs = Array.new(@p.size) { [] }; (0...@p.size).each { |i| gs[leader(i)] << i }; gs.reject(&:empty?); end
end

main[]


You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers.For instance, if we are given an array $$$[10, 20, 30, 40]$$$, we can permute it so that it becomes $$$[20, 40, 10, 30]$$$. Then on the first and the second positions the integers became larger ($$$20>10$$$, $$$40>20$$$) and did not on the third and the fourth, so for this permutation, the number that Vasya wants to maximize equals $$$2$$$. Read the note for the first example, there is one more demonstrative test case.Help Vasya to permute integers in such way that the number of positions in a new array, where integers are greater than in the original one, is maximal.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the elements of the array.

Print a single integer — the maximal number of the array's elements which after a permutation will stand on the position where a smaller element stood in the initial array.

NoteIn the first sample, one of the best permutations is $$$[1, 5, 5, 3, 10, 1, 1]$$$. On the positions from second to fifth the elements became larger, so the answer for this permutation is 4.In the second sample, there is no way to increase any element with a permutation, so the answer is 0.

def countzz(xs)
  xss = xs.sort
  chunks = xss.chunk{|x|x}.map{|a,b|b.size}.to_a
  use_chunks = chunks.clone

  use_index = 0
  count = 0

  chunks.each.with_index do |size, i|
    use_index = [use_index, i + 1].max

    while size > 0 && use_index < use_chunks.size
      if use_chunks[use_index] > size
        take = size
        count += take
        size = 0
        use_chunks[use_index] -= take
      else
        take = use_chunks[use_index]
        count += take
        size -= take
        use_chunks[use_index] = 0
        use_index += 1
      end
    end
  end
  count
end

def solution
  gets
  xs = read_ints
  puts countzz(xs)
end

def read_ints
  gets.split.map &:to_i
end

def read_string
  gets.chomp
end

solution

N = gets.to_i
as = gets.split.map(&:to_i).sort
len = 1
max = 1
(1...N).each do |i|
    if as[i-1] == as[i]
        len += 1
        max = len if max < len
    else
        len = 1
    end
end
puts N - max

n = gets.to_i
ary = gets.strip.split.map(&:to_i)

hsh = {}
ary.each {|x| hsh[x] = ((hsh[x] || 0) + 1)}

puts n - hsh.values.max

def countzz(xs)
  xss = xs.sort
  chunks = xss.chunk{|x|x}.map{|a,b|b.size}.to_a
  use_chunks = chunks.clone

  use_index = 0
  count = 0

  chunks.each.with_index do |size, i|
    use_index = [use_index, i + 1].max

    return count if use_index >= use_chunks.size

    while size > 0 && use_index < use_chunks.size
      if use_chunks[use_index] > size
        count += size
        size = 0
        use_chunks[use_index] -= size
      else
        count += use_chunks[use_index]
        size -= count
        use_chunks[use_index] -= 0
        use_index += 1
      end
    end
  end
  count
end

def solution
  gets
  xs = read_ints
  puts countzz(xs)
end

def read_ints
  gets.split.map &:to_i
end

def read_string
  gets.chomp
end

solution

def countzz(xs)
  xss = xs.sort
  chunks = xss.chunk{|x|x}.map{|a,b|b.size}.to_a
  use_chunks = chunks.clone

  use_index = 0
  count = 0

  chunks.each.with_index do |size, i|
    use_index = [use_index, i + 1].max

    return count if use_index >= use_chunks.size

    while size > 0 && use_index < use_chunks.size
      if use_chunks[use_index] > size
        count += size
        size = 0
        use_chunks[use_index] -= size
      else
        count += use_chunks[use_index]
        size -= count
        use_chunks[use_index] = 0
        use_index += 1
      end
    end
  end
  count
end

def solution
  gets
  xs = read_ints
  puts countzz(xs)
end

def read_ints
  gets.split.map &:to_i
end

def read_string
  gets.chomp
end

solution

def countzz(xs)
  xss = xs.sort
  chunks = xss.chunk{|x|x}.map{|a,b|b.size}.to_a
  use_chunks = chunks.clone

  use_index = 0
  count = 0

  chunks.each.with_index do |size, i|
    use_index = [use_index, i + 1].max

    return count if use_index >= use_chunks.size

    while size > 0 && use_index < use_chunks.size
      if use_chunks[use_index] > size
        count += size
        size = 0
        use_chunks[use_index] -= size
      else
        count += use_chunks[use_index]
        size -= count
        use_chunks[use_index] -= 0
      end
      use_index += 1
    end
  end
  count
end

def solution
  gets
  xs = read_ints

  puts countzz(xs)

end

def read_ints
  gets.split.map &:to_i
end

def read_string
  gets.chomp
end

solution


Kana was just an ordinary high school girl before a talent scout discovered her. Then, she became an idol. But different from the stereotype, she is also a gameholic. One day Kana gets interested in a new adventure game called Dragon Quest. In this game, her quest is to beat a dragon. The dragon has a hit point of $$$x$$$ initially. When its hit point goes to $$$0$$$ or under $$$0$$$, it will be defeated. In order to defeat the dragon, Kana can cast the two following types of spells.  Void Absorption Assume that the dragon's current hit point is $$$h$$$, after casting this spell its hit point will become $$$\left\lfloor \frac{h}{2} \right\rfloor + 10$$$. Here $$$\left\lfloor \frac{h}{2} \right\rfloor$$$ denotes $$$h$$$ divided by two, rounded down. Lightning Strike This spell will decrease the dragon's hit point by $$$10$$$. Assume that the dragon's current hit point is $$$h$$$, after casting this spell its hit point will be lowered to $$$h-10$$$.Due to some reasons Kana can only cast no more than $$$n$$$ Void Absorptions and $$$m$$$ Lightning Strikes. She can cast the spells in any order and doesn't have to cast all the spells. Kana isn't good at math, so you are going to help her to find out whether it is possible to defeat the dragon.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$)  — the number of test cases. The next $$$t$$$ lines describe test cases. For each test case the only line contains three integers $$$x$$$, $$$n$$$, $$$m$$$ ($$$1\le x \le 10^5$$$, $$$0\le n,m\le30$$$)  — the dragon's intitial hit point, the maximum number of Void Absorptions and Lightning Strikes Kana can cast respectively.

If it is possible to defeat the dragon, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can print each letter in any case (upper or lower).

NoteOne possible casting sequence of the first test case is shown below: Void Absorption $$$\left\lfloor \frac{100}{2} \right\rfloor + 10=60$$$. Lightning Strike $$$60-10=50$$$. Void Absorption $$$\left\lfloor \frac{50}{2} \right\rfloor + 10=35$$$. Void Absorption $$$\left\lfloor \frac{35}{2} \right\rfloor + 10=27$$$. Lightning Strike $$$27-10=17$$$. Lightning Strike $$$17-10=7$$$. Lightning Strike $$$7-10=-3$$$.

t = gets.chomp.to_i
t.times do
  x, n, m =  gets.chomp.split.map(&:to_i)

  n.times do
    if (x/2)+10 < x
      x = (x/2)+10
    else
      break
    end

  end

  x = x-(m*10)

  if x <= 0
    puts "YES"
  else
    puts "NO"
  end
end

file = File.exist?('in.in') ? File.new('in.in','r') : STDIN

t = file.gets.to_i

while t != 0
  h, n, m = file.gets.split.map(&:to_i)
  defeat = 'NO'

  while n > 0 || m > 0
    if h >= 20 && n > 0
      h = h / 2 + 10
      n -= 1
    elsif m > 0
      h -= 10
      m -= 1
    else
      h = h / 2 + 10
      n -= 1
    end
    if h <= 0
      defeat = 'YES'
      break;
    end
  end
  puts defeat
  t -= 1
end

gets.to_i.times {
  x, n, m = gets.split.map { |v| v.to_i }
  n.times {
    break if x < 21
    x = x / 2 + 10
  }
  x -= m * 10
  puts x > 0 ? "NO" : "YES"
}

def can_defeat_dragon(x, n, m)
  while x > 0 && (n > 0 || m > 0)
    if m > 0 && x <= m * 10
      x = x - (m * 10)
      m = 0
    end

    if x > 0
      if n > 0
        x = x / 2 + 10
        n = n - 1
      elsif m > 0
        x = x - 10
        m = m - 1
      end
    end
  end

  if x <= 0
    "YES"
  else
    "NO"
  end
end

t = gets.chomp.to_i

t.times do
  x, n, m = gets.chomp.split(' ').map(&:to_i)
  puts can_defeat_dragon(x, n, m)
end

1.upto(gets.chomp.to_i) do
  x,n,m = gets.chomp.split.map(&:to_i)
  while x > 20 && n > 0
    n -= 1
    x = x/2 + 10
  end
  while x > 0 && m > 0
    m -= 1
    x -= 10
  end
  if x <= 0
    puts 'YES'
  else
    puts 'NO'
  end
end

t = gets.to_i
t.times do
  x, n, m = gets.split.map(&:to_i)
  n.times do
    if x > 20
      x = x / 2 + 10
    else
      break
    end
  end
  puts (x <= m * 10) ? "YES" : "NO"
end

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

  while x > 20 && a > 0
    x = x.div(2) + 10
    a -= 1
  end

  puts (10*b >= x) ? 'YES' : 'NO'
end

file = File.exist?('in.in') ? File.new('in.in','r') : STDIN

t = file.gets.to_i

while t != 0
  h, n, m = file.gets.split.map(&:to_i)
  defeat = 'NO'

  while n > 0 || m > 0
    if h >= 20 && n > 0
      h = h / 2 + 10
      n -= 1
    elsif m > 0
      h -= 10
      m -= 1
    else
      puts "--------------------------"
      puts "n: #{n}"
      puts "m: #{m}"
      puts "================="
      puts "h: #{h}"
      h = h / 2 + 10
      n -= 1
    end
    if h <= 0
      defeat = 'YES'
      break;
    end
  end
  puts defeat
  t -= 1
end