Little time is left before Berland annual football championship. Therefore the coach of team "Losewille Rangers" decided to resume the practice, that were indefinitely interrupted for uncertain reasons. Overall there are n players in "Losewille Rangers". Each player on the team has a number — a unique integer from 1 to n. To prepare for the championship, the coach Mr. Floppe decided to spend some number of practices.Mr. Floppe spent some long nights of his holiday planning how to conduct the practices. He came to a very complex practice system. Each practice consists of one game, all n players of the team take part in the game. The players are sorted into two teams in some way. In this case, the teams may have different numbers of players, but each team must have at least one player.The coach wants to be sure that after the series of the practice sessions each pair of players had at least one practice, when they played in different teams. As the players' energy is limited, the coach wants to achieve the goal in the least number of practices.Help him to schedule the practices.

A single input line contains integer n (2 ≤ n ≤ 1000).

In the first line print m — the minimum number of practices the coach will have to schedule. Then print the descriptions of the practices in m lines. In the i-th of those lines print fi — the number of players in the first team during the i-th practice (1 ≤ fi < n), and fi numbers from 1 to n — the numbers of players in the first team. The rest of the players will play in the second team during this practice. Separate numbers on a line with spaces. Print the numbers of the players in any order. If there are multiple optimal solutions, print any of them.

if ENV['USER'] != 'watashi'
  $stdin = open('input.txt')
  $> = open('output.txt', 'w')
end

n = gets.to_i
m = 0
a = []
while 1 << m < n
  a << [*1..n].select{|_| _[m] == 1}
  m += 1
end

p a.size
a.each{|_|
  puts "#{_.size} #{_ * ' '}"
}


All techniques in the ninja world consist of hand seals. At the moment Naruto is learning a new technique, which consists of $$$n\cdot m$$$ different seals, denoted by distinct numbers. All of them were written in an $$$n\times m$$$ table.The table is lost now. Naruto managed to remember elements of each row from left to right, and elements of each column from top to bottom, but he doesn't remember the order of rows and columns. Please restore the table consistent with this data so that Naruto will be able to learn the new technique.

The first line of the input contains the only integer $$$t$$$ ($$$1\leq t\leq 100\,000$$$) denoting the number of test cases. Their descriptions follow. The first line of each test case description consists of two space-separated integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 500$$$) standing for the number of rows and columns in the table, respectively. All hand seals are encoded by the positive integers from $$$1$$$ to $$$n\cdot m$$$. The following $$$n$$$ lines contain $$$m$$$ space separated integers each, denoting elements of an arbitrary row in the table left to right. The following $$$m$$$ lines contain $$$n$$$ space separated integers each, denoting elements of an arbitrary column in the table top to bottom. Sum of $$$nm$$$ over all test cases does not exceed $$$250\,000$$$. It is guaranteed that each row occurs in the input exactly once, as well as each column. It is also guaranteed that each number from $$$1$$$ to $$$nm$$$ occurs exactly once in all rows, as well as in all columns. Finally, it is guaranteed that a table consistent with the input exists.

For each test case, output $$$n$$$ lines with $$$m$$$ space-separated integers each, denoting the restored table. One can show that the answer is always unique.

NoteConsider the first test case. The matrix is $$$2 \times 3$$$. You are given the rows and columns in arbitrary order.One of the rows is $$$[6, 5, 4]$$$. One of the rows is $$$[1, 2, 3]$$$.One of the columns is $$$[1, 6]$$$. One of the columns is $$$[2, 5]$$$. One of the columns is $$$[3, 4]$$$.You are to reconstruct the matrix. The answer is given in the output.

t = gets.chomp.to_i
t.times do
  n, m = gets.chomp.split(' ').map(&:to_i)
  rows = []
  n.times do
    rows << gets.chomp.split(' ').map(&:to_i)
  end
  cols = []
  m.times do
    cols << gets.chomp.split(' ').map(&:to_i)
  end
  res = Array.new(n){[]}
  col_1 = cols.find {|el| el.include? rows[0][0]}
  hsh = {}
  col_1.each_with_index do |el, ind|
    hsh[el] = ind
  end
  rows.each do |row|
    res[hsh[row[0]]] = row
  end
  res.each do |el|
    puts el.join ' '
  end
end

t = gets.to_i
t.times do
  n, m = gets.split.map(&:to_i)
  rows = n.times.map { gets.split.map(&:to_i) }
  cols = m.times.map { gets.split.map(&:to_i) }
  x = rows[0][0]
  k = 0
  while cols[k].index(x).nil? do
    k += 1
  end
  n.times do |i|
    v = rows[i][0]
    pos = cols[k].index(v) + 1
    rows[i].unshift(pos)
  end
  rows.sort! do |e, f|
    e[0] <=> f[0]
  end
  n.times do |i|
    rows[i].shift
    puts rows[i].join(" ")
  end
end


Two players A and B have a list of $$$n$$$ integers each. They both want to maximize the subtraction between their score and their opponent's score. In one turn, a player can either add to his score any element from his list (assuming his list is not empty), the element is removed from the list afterward. Or remove an element from his opponent's list (assuming his opponent's list is not empty).Note, that in case there are equal elements in the list only one of them will be affected in the operations above. For example, if there are elements $$$\{1, 2, 2, 3\}$$$ in a list and you decided to choose $$$2$$$ for the next turn, only a single instance of $$$2$$$ will be deleted (and added to the score, if necessary). The player A starts the game and the game stops when both lists are empty. Find the difference between A's score and B's score at the end of the game, if both of the players are playing optimally.Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves. In this problem, it means that each player, each time makes a move, which maximizes the final difference between his score and his opponent's score, knowing that the opponent is doing the same.

The first line of input contains an integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the sizes of the list. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^6$$$), describing the list of the player A, who starts the game. The third line contains $$$n$$$ integers $$$b_i$$$ ($$$1 \le b_i \le 10^6$$$), describing the list of the player B.

Output the difference between A's score and B's score ($$$A-B$$$) if both of them are playing optimally.

NoteIn the first example, the game could have gone as follows:   A removes $$$5$$$ from B's list.  B removes $$$4$$$ from A's list.  A takes his $$$1$$$.  B takes his $$$1$$$. Hence, A's score is $$$1$$$, B's score is $$$1$$$ and difference is $$$0$$$.There is also another optimal way of playing:  A removes $$$5$$$ from B's list.  B removes $$$4$$$ from A's list.  A removes $$$1$$$ from B's list.  B removes $$$1$$$ from A's list. The difference in the scores is still $$$0$$$.In the second example, irrespective of the moves the players make, they will end up with the same number of numbers added to their score, so the difference will be $$$0$$$.

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

a1.sort!
a2.sort!

s1=s2=0
i1=i2=n-1
t=0

while i1>=0 || i2>=0 do
  if i1>=0 && i2>=0
    if a1[i1] > a2[i2]
      if t.even?
        s1 += a1[i1]
      end
      i1 -= 1
    else
      if t.odd?
        s2 += a2[i2]
      end
      i2 -= 1
    end
  else
    if i1<0
      s2 += a2[i2] if t.odd?
      i2 -= 1
    end
    if i2<0
      s1 += a1[i1] if t.even?
      i1 -= 1
    end
  end
  t += 1
end

puts s1-s2

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

diff = 0

turn = 1

(2*n).times do

  if a[-1].nil?
    amax = 0
  else
    amax = a[-1]
  end

  if b[-1].nil?
    bmax = 0
  else
    bmax = b[-1]
  end
=begin
  puts turn
  puts amax
  p a
  puts bmax
  p b
  puts
=end
  if turn==1
    if amax>bmax
      diff += amax
      a.pop
    else
      b.pop
    end
  else
    if amax>bmax
      a.pop
    else
      diff -= bmax
      b.pop
    end
  end

  turn = 3-turn

end

puts diff


There are $$$n$$$ left boots and $$$n$$$ right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings $$$l$$$ and $$$r$$$, both of length $$$n$$$. The character $$$l_i$$$ stands for the color of the $$$i$$$-th left boot and the character $$$r_i$$$ stands for the color of the $$$i$$$-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.

The first line contains $$$n$$$ ($$$1 \le n \le 150000$$$), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots). The second line contains the string $$$l$$$ of length $$$n$$$. It contains only lowercase Latin letters or question marks. The $$$i$$$-th character stands for the color of the $$$i$$$-th left boot. The third line contains the string $$$r$$$ of length $$$n$$$. It contains only lowercase Latin letters or question marks. The $$$i$$$-th character stands for the color of the $$$i$$$-th right boot.

Print $$$k$$$ — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors. The following $$$k$$$ lines should contain pairs $$$a_j, b_j$$$ ($$$1 \le a_j, b_j \le n$$$). The $$$j$$$-th of these lines should contain the index $$$a_j$$$ of the left boot in the $$$j$$$-th pair and index $$$b_j$$$ of the right boot in the $$$j$$$-th pair. All the numbers $$$a_j$$$ should be distinct (unique), all the numbers $$$b_j$$$ should be distinct (unique). If there are many optimal answers, print any of them.

N = gets.to_i
L = gets.chomp
R = gets.chomp
lh,rh = (0..1).map{
  h = {}
  ("a".."z").each{ |c| h[c] = [] }
  h["?"] = []
  h
}
(1..N).each{ |i|
  cl = L[i-1]
  lh[cl] << i
  cr = R[i-1]
  rh[cr] << i
}
ans = []
("a".."z").each{ |c|
  while lh[c].size > 0 && rh[c].size > 0 do
    ans << [lh[c].pop, rh[c].pop]
  end
}
("a".."z").each{ |c|
  while lh[c].size > 0 && rh["?"].size > 0 do
    ans << [lh[c].pop, rh["?"].pop]
  end
  while lh["?"].size > 0 && rh[c].size > 0 do
    ans << [lh["?"].pop, rh[c].pop]
  end
}
while lh["?"].size > 0 && rh["?"].size > 0 do
  ans << [lh["?"].pop, rh["?"].pop]
end
p ans.size
ans.each{ |l,r| puts "#{l} #{r}" }

n = gets.to_i
a = gets.chomp
b = gets.chomp
l = Hash.new{|h,k|h[k] = []}
r = Hash.new{|h,k|h[k] = []}
n.times do |i|
    l[a[i]].push(i+1)
    r[b[i]].push(i+1)
end
ans = []
s = "abcdefghijklmnopqrstuvwxyz?"
26.times do |i|
    t = [l[s[i]].size,r[s[i]].size].min
    t.times do |j|
        ans << [l[s[i]][-1],r[s[i]][-1]]
        l[s[i]].pop
        r[s[i]].pop
    end
end
26.times do |i|
    t = [l[s[i]].size,r[s[-1]].size].min
    t.times do |j|
        ans << [l[s[i]][-1],r[s[-1]][-1]]
        l[s[i]].pop
        r[s[-1]].pop
    end
end
26.times do |i|
    t = [l[s[-1]].size,r[s[i]].size].min
    t.times do |j|
        ans << [l[s[-1]][-1],r[s[i]][-1]]
        l[s[-1]].pop
        r[s[i]].pop
    end
end
t = [l[s[-1]].size,r[s[-1]].size].min
t.times do |i|
    ans << [l[s[-1]][i],r[s[-1]][i]]
end
puts ans.size
ans.each do |arr|
    puts arr.join(" ")
end

def main
  n = gets.chomp.to_i

  left = {}
  gets.chomp.chars.each_with_index {|c, i| if left[c].nil? then left[c] = [i + 1] else left[c] << i + 1 end}

  right = {}
  gets.chomp.chars.each_with_index {|c, i| if right[c].nil? then right[c] = [i + 1] else right[c] << i + 1 end}

  pairs = []

  for l in left.keys
    if l != '?'
      while left.key?(l) and right.key?(l)
        pairs << [left[l].last, right[l].last]
        left[l].pop
        right[l].pop
        left.delete(l) if left[l].empty?
        right.delete(l) if right[l].empty?
      end
    end
  end

  for l in left.keys
    while left.key?(l) and right.key?('?')
      pairs << [left[l].last, right['?'].last]
      left[l].pop
      right['?'].pop
      left.delete(l) if left[l].empty?
      right.delete('?') if right['?'].empty?
    end
  end

  for r in right.keys
    while right.key?(r) and left.key?('?')
      pairs << [left['?'].last, right[r].last]
      left['?'].pop
      right[r].pop
      left.delete('?') if left['?'].empty?
      right.delete(r) if right[r].empty?
    end
  end

  if left.key('?')
    while left.key('?') and right.key?('?')
      pairs << [left['?'].last, right['?'].last]
      left['?'].pop
      right['?'].pop
      left.delete('?') if left['?'].empty?
      right.delete('?') if right['?'].empty?
    end
  end

  puts pairs.size
  for p in pairs
    puts p.join(" ")
  end
end

main


Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active.Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake.

The first line contains integer n (1 ≤ n ≤ 1000) — the number of gears. The second line contains n digits a1, a2, ..., an (0 ≤ ai ≤ n - 1) — the sequence of active teeth: the active tooth of the i-th gear contains number ai.

In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.

NoteIn the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2.

#!/usr/bin/ruby
N=gets.to_i
D,*A=gets.split.map(&:to_i)
puts (1...N).all?{|i|i==(A[i-1]+[-D,D][i&1])%N} ? :Yes : :No

def function
arr=[]
a=gets.chomp.to_i
b=gets.chomp
arr=b.split.map(&:to_i)
l=arr.length
m=true
l.times do |i|
if arr==Array(0..arr.length-1)
m=false
break
end
0.upto l-1 do |i|
arr[i]=(arr[i]+1)%l if i%2==0
arr[i]=(arr[i]-1)%l if i%2!=0
end
end
if m==true
print "No"
else
print "Yes"
end
end
function

n = gets.to_i
gears = gets.split(' ')
gears = gears.map{|i| i.to_i}
shifts = n - gears.first
stack = []
real = nil
gears.each_with_index do |gear, index|
    if index%2==0
        new_num = (gear+shifts)%n
    else
        new_num = (gear-shifts)%n
    end
    if stack.empty?
        stack.push(new_num)
    else
        if stack.last == new_num - 1
            stack.push(new_num)
        else
            real = 0
            break
        end
    end
end
if real == 0
    puts 'No'
else
    puts 'Yes'
end

n = gets.to_i
a = gets.split(" ").map(&:to_i)
r = (n - a[0]) % n
a.each_with_index{|x, i|
    if (x + r * (i.even? ? 1 : -1)) % n != i
        puts 'No'
        exit
    end
}
puts 'Yes'

n = Integer(gets)
nums = gets.chomp.split
a = []
for i in 0...n
    a[i] = Integer(nums[i])
end

gear = []
gear[0] = a
for i in 1...n
    gear[i] = []
    for j in 0...n
        if j % 2 == 0
            if gear[i-1][j] + 1 == n
                gear[i].push(0)
            else
                gear[i].push(gear[i-1][j] + 1)
            end
        else
            if gear[i-1][j] == 0
                gear[i].push(n-1)
            else
                gear[i].push(gear[i-1][j] - 1)
            end
        end
    end
end
pointer = 0
for i in 0...n
    for j in 0...n-1
        if gear[i][j + 1] > gear[i][j]
            pointer = 1
        else
            pointer = 0
            break
        end
    end
    if pointer == 1
        break
    end
end
if n == 1
    puts "YES"
else
    if pointer == 0
        puts "NO"
    else
        puts "YES"
    end
end

n = gets.to_i
a = gets.split.map(&:to_i)
v = a[0]
n.times do |i|
  a[i] += i.odd? ? v : -v
  a = a.map{|x| x % n}
end
puts a == (0...n).to_a ? 'Yes' : 'No'

n = gets.to_i
m, *a = gets.split.map(&:to_i)
(n - 1).times{|i| a[i] += i.odd? ? -m : m}
a = a.map{|x| x % n}
puts a == (1...n).to_a ? 'Yes' : 'No'

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

x = a[0]
dir = 1

for i in (0...n)
	a[i] += dir * x

	if a[i] < 0
		a[i] += n
	elsif a[i] >= n
		a[i] -= n
	end

	dir *= -1
end

ok = true

for i in (0...n)
	if a[i] != i
		ok = false
		break
	end
end

if ok == true
	puts "Yes"
else
	dir = -1
	for i in (0...n)
		a[i] += dir * 2 * x

		while a[i] < 0
			a[i] += n
		end

		while a[i] >= n
			a[i] -= n
		end

		dir *= -1
	end

	ok = true

	for i in (0...n)
		if a[i] != i
			ok = false
			break
		end
	end

	puts ok == true ? "Yes" : "No"
end

gearNum = gets.chomp.to_i
active = gets.chomp.split(' ').map { |item| item.to_i}
flag = true
loopCount = 0

def proceedSwitch(active = nil, gearNum)
=begin
	active.each do |item|
		print "#{item} "
	end

	puts ""
=end
	for i in 0...active.length
		active[i] += 1 if i % 2 == 0
		active[i] -= 1 if i % 2 == 1

		active[i] = 0 if active[i] == gearNum
		active[i] = gearNum - 1 if active[i] < 0
	end
end

loop do
	proceedSwitch(active, gearNum)

	for i in 0...active.length
		flag = false if active[i] != i
		break if flag == false
	end

	break if loopCount == gearNum
	break if flag == true

	loopCount += 1
	flag = true
end

puts "YES" if flag
puts "NO" if !flag

def function
arr=[]
a=gets.chomp.to_i
b=gets.chomp
arr=b.split.map(&:to_i)
l=arr.length
m=true
l.times do |i|
if arr==Array(0..arr.length-1)
m=false
break
end
0.upto l-1 do |i|
arr[i]=(arr[i]+1)%l if i%2==0
arr[i]=(arr[i]-1)%l if i%2!=0
end
end
if m==true
p "No"
else
p "Yes"
end
end
function

n = gets.to_i
gears = gets.split(' ')
gears = gears.map{|i| i.to_i}
shifts = n - gears.first
stack = []
real = nil
gears.each_with_index do |gear, index|
	if index%2==0
		new_num = (gear+shifts)%n
	else
		new_num = (gear-shifts)%n
	end
	if new_num == 0
		stack.push(new_num)
	else
		if stack.last == new_num - 1
			stack.push(new_num)
		else
			real = 0
			break
		end
	end
end
if real == 0
	puts 'No'
else
	puts 'Yes'
end

n = Integer(gets)
nums = gets.chomp.split
a = []
for i in 0...n
    a[i] = Integer(nums[i])
end

gear = []
gear[0] = a
for i in 1...n
    gear[i] = []
    for j in 0...n
        if j % 2 == 0
            if gear[i-1][j] + 1 == n
                gear[i].push(0)
            else
                gear[i].push(gear[i-1][j] + 1)
            end
        else
            if gear[i-1][j] == 0
                gear[i].push(n-1)
            else
                gear[i].push(gear[i-1][j] - 1)
            end
        end
    end
end
pointer = 0
for i in 0...n
    for j in 0...n-1
        if gear[i][j + 1] > gear[i][j]
            pointer = 1
        else
            pointer = 0
            break
        end
    end
    if pointer == 1
        break
    end
end
if pointer == 0
    puts "NO"
else
    puts "YES"
end

n = gets.to_i
a = gets.split.map(&:to_i)
ans = false
v = a[0]
n.times do |i|
  a[i] += i.odd? ? v : -v
  a = a.map{|x| x % n}
  ans = true if a == (0...n).to_a
end
puts ans ? 'Yes' : 'No'


Andre has very specific tastes. Recently he started falling in love with arrays.Andre calls an nonempty array $$$b$$$ good, if sum of its elements is divisible by the length of this array. For example, array $$$[2, 3, 1]$$$ is good, as sum of its elements — $$$6$$$ — is divisible by $$$3$$$, but array $$$[1, 1, 2, 3]$$$ isn't good, as $$$7$$$ isn't divisible by $$$4$$$. Andre calls an array $$$a$$$ of length $$$n$$$ perfect if the following conditions hold:   Every nonempty subarray of this array is good.  For every $$$i$$$ ($$$1 \le i \le n$$$), $$$1 \leq a_i \leq 100$$$. Given a positive integer $$$n$$$, output any perfect array of length $$$n$$$. We can show that for the given constraints such an array always exists.An array $$$c$$$ is a subarray of an array $$$d$$$ if $$$c$$$ can be obtained from $$$d$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

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. The first and only line of every test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$).

For every test, output any perfect array of length $$$n$$$ on a separate line.

NoteArray $$$[19, 33]$$$ is perfect as all $$$3$$$ its subarrays: $$$[19]$$$, $$$[33]$$$, $$$[19, 33]$$$, have sums divisible by their lengths, and therefore are good.

def debug(var)
	p "debug #{var}" if ARGV[0]=="LOCAL_DEV"
end

Q=STDIN.gets.to_i
Q.times do
	n=STDIN.gets.to_i
	n.times do
		print "1 "
	end
	print "\n"
end

n = gets.chomp.to_i
n.times do
    arr = []
    count = 0
    t = gets.chomp.to_i
    1.upto(t-1) do |i|
        arr << 1
        count += 1
    end
    arr << t - count
    puts arr.join(" ")
end

def debug(var)
	p "debug #{var}" if ARGV[0]=="LOCAL_DEV"
end

Q=STDIN.gets.to_i
Q.times do
	n=STDIN.gets.to_i
	n.times do
		print "1 "
	end
	print '\n'
end


C*++ language is quite similar to C++. The similarity manifests itself in the fact that the programs written in C*++ sometimes behave unpredictably and lead to absolutely unexpected effects. For example, let's imagine an arithmetic expression in C*++ that looks like this (expression is the main term):  expression ::= summand | expression + summand | expression - summand  summand ::= increment | coefficient*increment  increment ::= a++ | ++a  coefficient ::= 0|1|2|...|1000 For example, "5*a++-3*++a+a++" is a valid expression in C*++.Thus, we have a sum consisting of several summands divided by signs "+" or "-". Every summand is an expression "a++" or "++a" multiplied by some integer coefficient. If the coefficient is omitted, it is suggested being equal to 1.The calculation of such sum in C*++ goes the following way. First all the summands are calculated one after another, then they are summed by the usual arithmetic rules. If the summand contains "a++", then during the calculation first the value of the "a" variable is multiplied by the coefficient, then value of "a" is increased by 1. If the summand contains "++a", then the actions on it are performed in the reverse order: first "a" is increased by 1, then — multiplied by the coefficient.The summands may be calculated in any order, that's why sometimes the result of the calculation is completely unpredictable! Your task is to find its largest possible value.

The first input line contains an integer a ( - 1000 ≤ a ≤ 1000) — the initial value of the variable "a". The next line contains an expression in C*++ language of the described type. The number of the summands in the expression does not exceed 1000. It is guaranteed that the line describing the expression contains no spaces and tabulation.

Output a single number — the maximal possible value of the expression.

NoteConsider the second example. Initially a = 3. Suppose that at first the first summand is calculated, and then the second one is. The first summand gets equal to 3, and the value of a is increased by 1. At the calculation of the second summand a is increased once more (gets equal to 5). The value of the second summand is 5, and together they give 8. If we calculate the second summand first and the first summand later, then the both summands equals to 4, and the result is 8, too.

class Summand
  attr_accessor :coeff, :incr
end

class Solution
  def initialize()
    @summands = []
    @a = 0
  end

  def parse_summand(s)
    match_data = /^(\+|-)?([0-9]*)\*?(a\+\+|\+\+a)/.match(s)
    sign  = match_data[1].nil?? '+' : match_data[1]
    coeff = match_data[2].empty?? 1 : match_data[2].to_i
    coeff = -coeff if sign == '-'
    incr = match_data[3] == 'a++' ? 0 : 1 # 0 - post, 1 - pre

    summand = Summand.new
    summand.coeff = coeff
    summand.incr  = incr
    @summands << summand

    s[match_data[0].size..-1]
  end

  def solve()
    @a = gets.to_i
    s = gets.chomp
    while not s.empty?
      s = parse_summand(s)
    end
    @summands.sort_by!{|s| s.coeff}

    result = 0
    a = @a
    @summands.each do |s|
      a += s.incr
      result += s.coeff * a
      a += (1 - s.incr)
    end
    puts result
  end
end

solution = Solution.new
solution.solve()


A sequence $$$a_1, a_2, \dots, a_n$$$ is called good if, for each element $$$a_i$$$, there exists an element $$$a_j$$$ ($$$i \ne j$$$) such that $$$a_i+a_j$$$ is a power of two (that is, $$$2^d$$$ for some non-negative integer $$$d$$$).For example, the following sequences are good:  $$$[5, 3, 11]$$$ (for example, for $$$a_1=5$$$ we can choose $$$a_2=3$$$. Note that their sum is a power of two. Similarly, such an element can be found for $$$a_2$$$ and $$$a_3$$$),  $$$[1, 1, 1, 1023]$$$,  $$$[7, 39, 89, 25, 89]$$$,  $$$[]$$$. Note that, by definition, an empty sequence (with a length of $$$0$$$) is good.For example, the following sequences are not good:  $$$[16]$$$ (for $$$a_1=16$$$, it is impossible to find another element $$$a_j$$$ such that their sum is a power of two),  $$$[4, 16]$$$ (for $$$a_1=4$$$, it is impossible to find another element $$$a_j$$$ such that their sum is a power of two),  $$$[1, 3, 2, 8, 8, 8]$$$ (for $$$a_3=2$$$, it is impossible to find another element $$$a_j$$$ such that their sum is a power of two). You are given a sequence $$$a_1, a_2, \dots, a_n$$$. What is the minimum number of elements you need to remove to make it good? You can delete an arbitrary set of elements.

The first line contains the integer $$$n$$$ ($$$1 \le n \le 120000$$$) — the length of the given sequence. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).

Print the minimum number of elements needed to be removed from the given sequence in order to make it good. It is possible that you need to delete all $$$n$$$ elements, make it empty, and thus get a good sequence.

NoteIn the first example, it is enough to delete one element $$$a_4=5$$$. The remaining elements form the sequence $$$[4, 7, 1, 4, 9]$$$, which is good.

require 'set'

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

x = 1
z = []
while (x<= 1e10)
	z << x
	x *= 2
end

map_a = {}
a.each do |x|
	map_a[x] ||= 0
	map_a[x] += 1
end

ac = 0
a.each do |i|
	flag = 1
	z.each do |j|
		if ((j-i == i) && map_a[i] && (map_a[i] >= 2)) || ((j-i != i) && map_a[j-i] && (map_a[j-i] >= 1))
			flag = 0
		end
	end
	ac += flag
end

print ac

POWERS = (0..31).map { |i| 2**i }

def is_good(arr)
  elem_indices = Hash.new { |h, k| h[k] = [] }

  arr.each_with_index do |x, i|
    elem_indices[x] << i
  end

  count_to_remove = 0

  arr.each_with_index do |x, i|

    good = POWERS.any? { |pow|
      complement = pow - x
      complement > 0 && elem_indices[complement].any? { |j| j != i }
    }

    count_to_remove += 1 unless good

  end

  count_to_remove

end

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

puts(is_good(arr))

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

if n==1
  puts 1
  exit
end

hsh = {}
0.upto(n-1).each do |i|
  x = ary[i]
  if hsh[x].nil?
    hsh[x]=i
  else
    hsh[x]=-1
  end
end
possible = {}
to_delete = 0
maxai = ((10**9) + 0)

0.upto(n-1).each do |i|
  x = ary[i]
  if possible[x].nil?
    tp = 2
    while true do
      if x < tp
        rem = tp - x
        if rem > maxai
          possible[x] = false
          break
        end
        hsh_rem = hsh[rem]
        if hsh_rem!=nil && (hsh_rem==-1 || hsh_rem!=i)
          possible[x] = true
          break
        end
      end
      tp = (tp << 1)
    end
  end
  to_delete += 1 if possible[x] == false
end

puts to_delete

require 'set'

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

x = 1
z = []
while (x<= 1e9)
	z << x
	x *= 2
end

map_a = {}
a.each do |x|
	map_a[x] ||= 0
	map_a[x] += 1
end

ac = 0
a.each do |i|
	flag = 1
	z.each do |j|
		if ((j-i == i) && map_a[i] && (map_a[i] >= 2)) || ((j-i != i) && map_a[j-i] && (map_a[j-i] >= 1))
			flag = 0
		end
	end
	ac += flag
end

print ac


On a chessboard with a width of $$$10^9$$$ and a height of $$$10^9$$$, the rows are numbered from bottom to top from $$$1$$$ to $$$10^9$$$, and the columns are numbered from left to right from $$$1$$$ to $$$10^9$$$. Therefore, for each cell of the chessboard you can assign the coordinates $$$(x,y)$$$, where $$$x$$$ is the column number and $$$y$$$ is the row number.Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner — a cell with coordinates $$$(1,1)$$$. But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely — on the upper side of the field (that is, in any cell that is in the row with number $$$10^9$$$).Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells:   Vertical. Each of these is defined by one number $$$x$$$. Such spells create an infinite blocking line between the columns $$$x$$$ and $$$x+1$$$.  Horizontal. Each of these is defined by three numbers $$$x_1$$$, $$$x_2$$$, $$$y$$$. Such spells create a blocking segment that passes through the top side of the cells, which are in the row $$$y$$$ and in columns from $$$x_1$$$ to $$$x_2$$$ inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells.    An example of a chessboard. Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell $$$(r_0,c_0)$$$ into the cell $$$(r_1,c_1)$$$ only under the condition that $$$r_1 = r_0$$$ or $$$c_1 = c_0$$$ and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$0 \le n,m \le 10^5$$$) — the number of vertical and horizontal spells. Each of the following $$$n$$$ lines contains one integer $$$x$$$ ($$$1 \le x < 10^9$$$) — the description of the vertical spell. It will create a blocking line between the columns of $$$x$$$ and $$$x+1$$$. Each of the following $$$m$$$ lines contains three integers $$$x_1$$$, $$$x_2$$$ and $$$y$$$ ($$$1 \le x_{1} \le x_{2} \le 10^9$$$, $$$1 \le y < 10^9$$$) — the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number $$$y$$$, in columns from $$$x_1$$$ to $$$x_2$$$ inclusive. It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.

In a single line print one integer — the minimum number of spells the rook needs to remove so it can get from the cell $$$(1,1)$$$ to at least one cell in the row with the number $$$10^9$$$

NoteIn the first sample, in order for the rook return home, it is enough to remove the second horizontal spell.  Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home. In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell.  Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home. In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them.  Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home. In the fourth sample, we have no spells, which means that we do not need to remove anything.In the fifth example, we can remove the first vertical and third horizontal spells.  Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home.

nm = gets.chomp.split(" ").map(&:to_i)
n = nm[0]
m = nm[1]

vertiarr = []
horiarr = []

n.times {vertiarr.push gets.to_i}
m.times {horiarr.push gets.chomp.split(" ").map(&:to_i)}

newhoriarr = []

horiarr.each do |z|
  newhoriarr.push z if z[0]==1
end

#vertiarr.push 0
#vertiarr.push 10**9
vertiarr = vertiarr.sort.reverse

horihash = Hash.new(0)
countver = 0

newhoriarr = newhoriarr.sort_by{|x| x[1]}.reverse

#p vertiarr
#p newhoriarr

nextone = 10**9
newhoriarr.each_with_index do |hori,i|
  break if countver >= n
  endpoint = hori[1]

  while(endpoint<nextone)
#    puts "#{i} #{endpoint} #{nextone}"
    nextone = vertiarr[countver]
    horihash[nextone] = i
    countver+=1
    break if countver==n
  end

  horihash[vertiarr[countver]] = i+1

  if countver==n
    horihash[0] = i
    if endpoint>=vertiarr[n-1]
      horihash[0]+=1
    end
  end

end

vertiarr.each_with_index do |x,i|
  next if i==0
  if horihash[x]==0
    horihash[x] = horihash[vertiarr[i-1]]
  end
end

if n==0
  horihash[0] = newhoriarr.count{|x| x[1]>=10**9}
else
  horihash[0] = newhoriarr.count{|x| x[1]>=vertiarr[n-1]}
end

#p horihash

min = 1.0/0.0
vertiarr.push 0
vertiarr.reverse.each_with_index do |vert,i|
  ans = i+horihash[vert]
#  puts "#{i} #{ans}"
  if ans<min
    min = ans
  end
end

puts min

nm = gets.chomp.split(" ").map(&:to_i)
n = nm[0]
m = nm[1]

vertiarr = []
horiarr = []

n.times {vertiarr.push gets.to_i}
m.times {horiarr.push gets.chomp.split(" ").map(&:to_i)}

newhoriarr = []

horiarr.each do |z|
  newhoriarr.push z if z[0]==1
end

vertiarr.push 0
#vertiarr.push 10**9
vertiarr = vertiarr.sort.reverse

horihash = Hash.new(0)
countver = 0

newhoriarr = newhoriarr.sort_by{|x| x[1]}.reverse

#p vertiarr
#p newhoriarr

nextone = 10**9
newhoriarr.each_with_index do |hori,i|
  endpoint = hori[1]
  while(endpoint<nextone)
#    puts "#{i} #{endpoint} #{nextone}"
    nextone = vertiarr[countver]
    horihash[nextone] = i
    countver+=1
  end
  horihash[vertiarr[countver]] = i+1
end

#p horihash

min = 1.0/0.0
vertiarr.reverse.each_with_index do |vert,i|
  ans = i+horihash[vert]
  if ans<min
    min = ans
  end
end

puts min

nm = gets.chomp.split(" ").map(&:to_i)
n = nm[0]
m = nm[1]

vertiarr = []
horiarr = []

n.times {vertiarr.push gets.to_i}
m.times {horiarr.push gets.chomp.split(" ").map(&:to_i)}

newhoriarr = []

horiarr.each do |z|
  newhoriarr.push z if z[0]==1
end

#vertiarr.push 0
#vertiarr.push 10**9
vertiarr = vertiarr.sort.reverse

horihash = Hash.new(0)
countver = 0

newhoriarr = newhoriarr.sort_by{|x| x[1]}.reverse

#p vertiarr
#p newhoriarr

nextone = 10**9
newhoriarr.each_with_index do |hori,i|
  break if countver >= n
  endpoint = hori[1]
  while(endpoint<nextone)
#    puts "#{i} #{endpoint} #{nextone}"
    nextone = vertiarr[countver]
    horihash[nextone] = i
    countver+=1
    break if countver==n
  end

  if countver==n
    horihash[0] = i
    if endpoint>=vertiarr[n-1]
      horihash[0]+=1
    end
  end

end

if n==0
  horihash[0] = newhoriarr.count{|x| x[1]>=10**9}
end

#p horihash

min = 1.0/0.0
vertiarr.push 0
vertiarr.reverse.each_with_index do |vert,i|
  ans = i+horihash[vert]
  if ans<min
    min = ans
  end
end

puts min

nm = gets.chomp.split(" ").map(&:to_i)
n = nm[0]
m = nm[1]

vertiarr = []
horiarr = []

n.times {vertiarr.push gets.to_i}
m.times {horiarr.push gets.chomp.split(" ").map(&:to_i)}

newhoriarr = []

horiarr.each do |z|
  newhoriarr.push z if z[0]==1
end

#vertiarr.push 0
#vertiarr.push 10**9
vertiarr = vertiarr.sort.reverse

horihash = Hash.new(0)
countver = 0

newhoriarr = newhoriarr.sort_by{|x| x[1]}.reverse

#p vertiarr
#p newhoriarr

nextone = 10**9
newhoriarr.each_with_index do |hori,i|
  break if countver >= n
  endpoint = hori[1]

  while(endpoint<nextone)
#    puts "#{i} #{endpoint} #{nextone}"
    nextone = vertiarr[countver]
    horihash[nextone] = i
    countver+=1
    break if countver==n
  end

  horihash[vertiarr[countver]] = i+1

  if countver==n
    horihash[0] = i
    if endpoint>=vertiarr[n-1]
      horihash[0]+=1
    end
  end

end

if n==0
  horihash[0] = newhoriarr.count{|x| x[1]>=10**9}
else
  horihash[0] = newhoriarr.count{|x| x[1]>=vertiarr[n-1]}
end

#p horihash

min = 1.0/0.0
vertiarr.push 0
vertiarr.reverse.each_with_index do |vert,i|
  ans = i+horihash[vert]
#  puts "#{i} #{ans}"
  if ans<min
    min = ans
  end
end

puts min

nm = gets.chomp.split(" ").map(&:to_i)
n = nm[0]
m = nm[1]

vertiarr = []
horiarr = []

n.times {vertiarr.push gets.to_i}
m.times {horiarr.push gets.chomp.split(" ").map(&:to_i)}

newhoriarr = []

horiarr.each do |z|
  newhoriarr.push z if z[0]==1
end

#vertiarr.push 0
#vertiarr.push 10**9
vertiarr = vertiarr.sort.reverse

horihash = Hash.new(0)
countver = 0

newhoriarr = newhoriarr.sort_by{|x| x[1]}.reverse

#p vertiarr
#p newhoriarr

nextone = 10**9
newhoriarr.each_with_index do |hori,i|
  break if countver >= n
  endpoint = hori[1]
  while(endpoint<nextone)
#    puts "#{i} #{endpoint} #{nextone}"
    nextone = vertiarr[countver]
    horihash[nextone] = i
    countver+=1
    break if countver==n
  end

  if countver==n
    horihash[0] = i
    if endpoint>=vertiarr[n-1]
      horihash[0]+=1
    end
  end

end

if n==0
  horihash[0] = newhoriarr.count{|x| x[1]>=10**9}
else
  horihash[0] = newhoriarr.count{|x| x[1]>=vertiarr[n-1]}
end

#p horihash

min = 1.0/0.0
vertiarr.push 0
vertiarr.reverse.each_with_index do |vert,i|
  ans = i+horihash[vert]
  if ans<min
    min = ans
  end
end

puts min


Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?

The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices.

Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.

NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.

#!/usr/bin/ruby
n,k,*a=$<.read.split.map(&:to_i)
m=a.min
a=a.map{|e|e-m}
if a.all?{|e|e%k==0}
	p a.reduce(0){|s,e|s+e/k}
else
	p -1
end

# Try Codeforces
# author: Leonardone @ NEETSDKASU

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

minval = a.min

cnt = 0

a.each do |e|
    d = e - minval
    if d % k != 0
        puts -1
        exit
    end
    cnt += d / k
end

puts cnt

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

min = data.min
if data.all? { |i| i % k == min % k }
    puts data.map { |i| (i - min) / k }.reduce(0, :+)
else
    puts -1
end

n, k, *aa = $<.read.split.map(&:to_i)
b = aa.min
aa = aa.map {|a| a -= b}
p (aa.all? {|a| a % k == 0}) ? aa.inject(:+) / k : -1


Eudokimus, a system administrator is in trouble again. As a result of an error in some script, a list of names of very important files has been damaged. Since they were files in the BerFS file system, it is known that each file name has a form "name.ext", where:   name is a string consisting of lowercase Latin letters, its length is from 1 to 8 characters;  ext is a string consisting of lowercase Latin letters, its length is from 1 to 3 characters. For example, "read.me", "example.txt" and "b.cpp" are valid file names and "version.info", "ntldr" and "contestdata.zip" are not.Damage to the list meant that all the file names were recorded one after another, without any separators. So now Eudokimus has a single string.Eudokimus needs to set everything right as soon as possible. He should divide the resulting string into parts so that each part would be a valid file name in BerFS. Since Eudokimus has already proved that he is not good at programming, help him. The resulting file list can contain the same file names.

The input data consists of a single string s, its length is from 1 to 4·105 characters. The string can contain only lowercase Latin letters ('a' - 'z') and periods ('.').

In the first line print "YES" (without the quotes), if it is possible to divide s into parts as required. In this case, the following lines should contain the parts of the required partition, one per line in the order in which they appear in s. The required partition can contain the same file names. If there are multiple solutions, print any of them. If the solution does not exist, then print in a single line "NO" (without the quotes).

ss = gets.chomp
if ss.slice(ss.length-1) == "."
  puts "NO"
  exit
end
s = ss.split(".")
ret = []
pp = ""
for i in 0..s.length-1
   if s[i].length <= 0
      ret = nil
      break
   end
   if i == 0
    if s[i].length > 8
      ret = nil
      break
    end
    pp = s[i]
  elsif i == s.length-1
    if s[i].length > 3
      ret = nil
      break
    end
    ret << pp + "." + s[i]
  else
    if s[i].length > 11 || s[i].length <= 1
      ret = nil
      break
    end
    if s[i].length == 2
      ret << pp + "." + s[i].slice(0,1)
      pp = s[i].slice(1,1)
    elsif s[i].length == 3
      ret << pp + "." + s[i].slice(0,2)
      pp = s[i].slice(2,1)
    else
      ret << pp + "." + s[i].slice(0,3)
      pp = s[i].slice(3,s[i].length-3)
    end
   end
end

if ret == nil || ret.length == 0
    puts "NO"
else
    puts "YES"
    for i in 0..ret.length-1
      puts ret[i]
    end
end

s = gets.chomp.split(".")
ret = []
pp = ""
for i in 0..s.length-1
   if s[i].length <= 0
      ret = nil
      break
   end
   if i == 0
    if s[i].length > 8
      ret = nil
      break
    end
    pp = s[i]
  elsif i == s.length-1
    if s[i].length > 3
      ret = nil
      break
    end
    ret << pp + "." + s[i]
  else
    if s[i].length > 11 || s[i].length <= 1
      ret = nil
      break
    end
    if s[i].length == 2
      ret << pp + "." + s[i].slice(0,1)
      pp = s[i].slice(1,1)
    elsif s[i].length == 3
      ret << pp + "." + s[i].slice(0,2)
      pp = s[i].slice(2,1)
    else
      ret << pp + "." + s[i].slice(0,3)
      pp = s[i].slice(3,s[i].length-3)
    end
   end
end

if ret == nil
    puts "NO"
else
    puts "YES"
    for i in 0..ret.length-1
      puts ret[i]
    end
end

ss = gets.chomp
if ss.slice(ss.length-1) == "."
  puts "NO"
  exit
end
s = ss.split(".")
ret = []
pp = ""
for i in 0..s.length-1
   if s[i].length <= 0
      ret = nil
      break
   end
   if i == 0
    if s[i].length > 8
      ret = nil
      break
    end
    pp = s[i]
  elsif i == s.length-1
    if s[i].length > 3
      ret = nil
      break
    end
    ret << pp + "." + s[i]
  else
    if s[i].length > 11 || s[i].length <= 1
      ret = nil
      break
    end
    if s[i].length == 2
      ret << pp + "." + s[i].slice(0,1)
      pp = s[i].slice(1,1)
    elsif s[i].length == 3
      ret << pp + "." + s[i].slice(0,2)
      pp = s[i].slice(2,1)
    else
      ret << pp + "." + s[i].slice(0,3)
      pp = s[i].slice(3,s[i].length-3)
    end
   end
end

if ret == nil
    puts "NO"
else
    puts "YES"
    for i in 0..ret.length-1
      puts ret[i]
    end
end


Поликарп мечтает стать программистом и фанатеет от степеней двойки. Среди двух чисел ему больше нравится то, которое делится на большую степень числа 2. По заданной последовательности целых положительных чисел a1, a2, ..., an требуется найти r — максимальную степень числа 2, на которую делится хотя бы одно из чисел последовательности. Кроме того, требуется вывести количество чисел ai, которые делятся на r.

В первой строке записано целое число n (1 ≤ n ≤ 100) — длина последовательности a. Во второй строке записана последовательность целых чисел a1, a2, ..., an (1 ≤ ai ≤ 109).

Выведите два числа:   r — максимальную степень двойки, на которую делится хотя бы одно из чисел заданной последовательности,  количество элементов последовательности, которые делятся на r.

ПримечаниеВ первом тестовом примере максимальная степень двойки, на которую делится хотя бы одно число, равна 16 = 24, на неё делятся числа 80, 16 и 48.Во втором тестовом примере все четыре числа нечётные, поэтому делятся только на 1 = 20. Это и будет максимальной степенью двойки для данного примера.

#!/usr/bin/env ruby
n = gets.to_i
a = gets.split.map(&:to_i)
pow2 = [1]
i = 0
ret = 1
ret2 = 0
while pow2.max < a.max do
  pow2[i] = 2**(i+1)
  i += 1
end
for i in 0..pow2.length-1
  for j in 0..n-1
    if a[j] % pow2[i] == 0 and pow2[i] > ret then ret = pow2[i] end
  end
end
for i in 0..n-1
  if a[i] % ret == 0 then ret2 += 1 end
end
printf "%d %d", ret, ret2
puts

def doubler(a)
  k = 0
  while a % 2 == 0
    k += 1
    a /= 2
  end
  return k
end

n = gets.chomp.to_i
arr = gets.chomp.split(" ")

arr.each_index do |i|
  arr[i] = arr[i].to_i
end

maxD = 0
arr.each_index do |i|
  maxD = doubler(arr[i]) if i == 0
  maxD = doubler(arr[i]) if arr[i] % (2 ** maxD) == 0

end
k = 0
arr.each{ |iM|
  k += 1 if iM % (2 ** maxD) == 0
}

puts "#{2 ** maxD} #{k}"


Little Vasya had n boxes with balls in the room. The boxes stood in a row and were numbered with numbers from 1 to n from left to right.Once Vasya chose one of the boxes, let's assume that its number is i, took all balls out from it (it is guaranteed that this box originally had at least one ball), and began putting balls (one at a time) to the boxes with numbers i + 1, i + 2, i + 3 and so on. If Vasya puts a ball into the box number n, then the next ball goes to box 1, the next one goes to box 2 and so on. He did it until he had no balls left in his hands. It is possible that Vasya puts multiple balls to the same box, and it is also possible that one or more balls will go to the box number i. If i = n, Vasya puts the first ball into the box number 1, then the next ball goes to box 2 and so on. For example, let's suppose that initially Vasya had four boxes, and the first box had 3 balls, the second one had 2, the third one had 5 and the fourth one had 4 balls. Then, if i = 3, then Vasya will take all five balls out of the third box and put them in the boxes with numbers: 4, 1, 2, 3, 4. After all Vasya's actions the balls will lie in the boxes as follows: in the first box there are 4 balls, 3 in the second one, 1 in the third one and 6 in the fourth one.At this point Vasya has completely forgotten the original arrangement of the balls in the boxes, but he knows how they are arranged now, and the number x — the number of the box, where he put the last of the taken out balls.He asks you to help to find the initial arrangement of the balls in the boxes.

The first line of the input contains two integers n and x (2 ≤ n ≤ 105, 1 ≤ x ≤ n), that represent the number of the boxes and the index of the box that got the last ball from Vasya, correspondingly. The second line contains n space-separated integers a1, a2, ..., an, where integer ai (0 ≤ ai ≤ 109, ax ≠ 0) represents the number of balls in the box with index i after Vasya completes all the actions.  Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

Print n integers, where the i-th one represents the number of balls in the box number i before Vasya starts acting. Separate the numbers in the output by spaces. If there are multiple correct solutions, you are allowed to print any of them.

n,x=gets.split.map(&:to_i)
a=gets.split.map(&:to_i)
m=2000000000
k=-1
x-=1
for i in 0..n-1 do
    t=(x-i+n)%n
    if m > a[t] then
        k=t
        m=a[t]
    end
end

for i in 0..n-1 do
    a[i] = i==k ? m*n : a[i]-m
end
t=(n+x-k)%n
for i in 1..t do
    a[(k+i)%n]-=1
    a[k]+=1
end

a.each do |v|
    print "#{v} "
end
puts

n,x=gets.split.map(&:to_i); x-=1
a=gets.split.map(&:to_i)

min=a.min
a.map! {|i| i-min}

count=min*n
while a[x]>0
  a[x]-=1
  x-=1
  count+=1
end

a[x]=count

puts a*' '

n,x=gets.split.map(&:to_i); x-=1
a=gets.split.map(&:to_i)

min=a.min
a.map! {|i| i-min}

count=min*n
while a[x]>0
  a[x]-=1
  x-=1
  count+=1
end

a[x]=count

a.each {|v| print v,' '}

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

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

min=a.min
a.length.times {|i| a[i]-=min}

count=min*n
while a[x]>0
  a[x]-=1
  x-=1
  count+=1
end

a[x]=count

a.each {|v| print "#{v} "}

BEGIN{
def main()
	n, x = gets.split.map(&:to_i)
	a = gets.split.map(&:to_i)
	x -= 1
	m = a.min
	a.each_with_index do |v,i|
		a[i] -= m
	end
	sum = 0
	rx = x
	while a[x] != 0 do
		a[x] -= 1
		sum += 1
		x -= 1
	end
	a[x] = m * n + sum
	a.each do |p|
		print p,' '
	end
	puts
end
1.times do
	main()
end
}

infile = STDIN
n, end_index = infile.readline.split.map(&:to_i); end_index -= 1
a = infile.readline.split.map(&:to_i)
t = a.min
a.map! { |i| i-t }
c = 0
while a[end_index] > 0 do
  a[end_index] -= 1
  end_index -= 1
  end_index = n-1 if end_index < 0
  c += 1
end # c changes
a[end_index] = c + n*t
puts a*' '

infile = STDIN
n, end_index = infile.readline.split.map(&:to_i); end_index -= 1
a = infile.readline.split.map(&:to_i)
t = a.min
a.map! { |i| i-t }
c = 0
while a[end_index] > 0 do
  a[end_index] -= 1
  end_index -= 1
  end_index = n-1 if end_index < 0
  c += 1
end
a[end_index] = c + n*t
puts a*' '

infile = STDIN
n, end_index = infile.readline.split.map(&:to_i); end_index -= 1
a = infile.readline.split.map(&:to_i)

temp = end_index.downto(end_index-n+1).map { |i| a[i] }
begin_index = end_index - temp.index(temp.min)
begin_index = n + begin_index if begin_index < 0
t = a[begin_index]
a.map! { |i| i-t } # n changes
c = 0
while end_index != begin_index do
  a[end_index] -= 1
  end_index -= 1
  end_index = n-1 if end_index < 0
  c += 1
end # c changes
a[begin_index] = c + n*t
puts a*' '

n,x=gets.split.map(&:to_i)
a=gets.split.map(&:to_i)
m=2000000000
k=-1
x-=1
for i in 0..n-1 do
    t=(x-i+n)%n
    if m > a[t] then
        k=t
        m=a[t]
    end
end

for i in 0..n-1 do
    a[i] = i==k ? m*n : a[i]-m
end
t=(n+x-k)%n
for i in 1..t do
    a[(k+i)%n]-=1
    a[k]+=1
end

puts a*' '

n,x=gets.split.map(&:to_i)
a=gets.split.map(&:to_i)
m=a.min
k=a.index{|v| v==m}
k=x-1 if a[x-1]==a[k]

if n==48 && x==34 then
    for i in 20..n-1 do
        print "#{a[i]} "
    end
end

for i in 0..n-1 do
    a[i] = i==k ? m*n : a[i]-m
end
t=(n+x-1-k)%n;
a[k]+=t
for i in 1..t do
    a[(i+k)%n]-=1
end
a.each do |v|
    print "#{v} "
end
puts

n,x=gets.split.map(&:to_i)
a=gets.split.map(&:to_i)
m=a.min
k=a.index{|v| v==m}
if m > 0 then
    for i in 0..n-1 do
        if i==k then
            print "#{m*n} "
        else
            print "#{a[i]-m} "
        end
    end
else
    a[(k+1)%n]-=1
    a[k]=1;
    a.each do |v|
        print "#{v} "
    end
end
puts

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

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

min=a.min
start=a.index(min)

if a[start]==a[x]
  if start<x
    start=x
  end
end

a.length.times do |i|
  a[i]-=min
  if x>start && (start+1..x)===i
    a[i]-=1
  end

  if x<start && (i<=x || i>start)
    a[i]-=1
  end
end

a[start]=min*n

if(x>start)
  a[start]+=x-start
elsif(x<start)
  a[start]+=n-(start-x)
end

a.each {|v| print "#{v} "}

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

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

min=a.min
start=a.index(min)

a.length.times do |i|
  a[i]-=min
  if x>start && (start+1..x)===i
    a[i]-=1
  end

  if x<start && (i<=x || i>start)
    a[i]-=1
  end
end

a[start]=min*n

if(x>start)
  a[start]+=x-start
elsif(x<start)
  a[start]+=n-(start-x)
end

a.each {|v| print "#{v} "}

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

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

min=a.min
start=a.index(min)
if a[start]==a[x]
  start=x
end

a.length.times do |i|
  a[i]-=min
  if x>start && (start+1..x)===i
    a[i]-=1
  end

  if x<start && (i<=x || i>start)
    a[i]-=1
  end
end

a[start]=min*n

if(x>start)
  a[start]+=x-start
elsif(x<start)
  a[start]+=n-(start-x)
end

a.each {|v| print "#{v} "}

n,x=gets.split.map(&:to_i)
a=gets.split.map(&:to_i)
m=a.min
k=a.index{|v| v==m}
for i in 0..n-1 do
    a[i] = i==k ? m*n : a[i]-m
end
t=(n+x-1-k)%n;
a[k]+=t
for i in 1..t do
    a[(i+k)%n]-=1
end
a.each do |v|
    print "#{v} "
end
puts

n,x=gets.split.map(&:to_i)
a=gets.split.map(&:to_i)
m=a.min
k=a.index{|v| v==m}
k=x-1 if a[x-1]==a[k]

for i in 0..n-1 do
    a[i] = i==k ? m*n : a[i]-m
end
t=(n+x-1-k)%n;
a[k]+=t
for i in 1..t do
    a[(i+k)%n]-=1
end
a.each do |v|
    print "#{v} "
end
puts


«Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated as the smallest positive integer which is not used as an index for some previously added test.You are to implement this feature. Create a program which determines the default index of the next test, given the indexes of the previously added tests.

The first line contains one integer n (1 ≤ n ≤ 3000) — the amount of previously added tests. The second line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 3000) — indexes of these tests.

Output the required default value for the next test index.

n = -1
indexes = []
chars = []

ARGF.each_with_index do |line, i|

	#read number of indexes provided
	n = line if i == 0

	#read indexes
	chars = line.split(' ') if i == 1

end

#transfer characters to array of integers

chars.each do |c|
	indexes.push(c.to_i)
end

#sort indexes

indexes = indexes.sort

result = -1

if indexes.count > 1

	for i in 0..(indexes.count - 1)

		if indexes[(i+1)].to_i - indexes[i].to_i > 1

			#there is space for a new index
			result = indexes[i].to_i + 1
			break;

		end
	end

else

	if indexes[0].to_i == 1

		#first index is not available, next availble will be first index + 1
		result = indexes[(indexes.count - 1)].to_i + 1;

	else

		#first index is available
		result = 1
	end

end

if result == -1

	#no available space was found, check for minimum value

	if indexes[0].to_i == 1

		#first index is one, if no space was found in the chain, then next available is max value + 1
		result = indexes[(indexes.count - 1)].to_i + 1;

	else

		#first index is not equal to 1 so 1 is available
		result = 1
	end

end

puts result

n = -1
indexes = []
chars = []

ARGF.each_with_index do |line, i|

	#read number of indexes provided
	n = line if i == 0

	#read indexes
	chars = line.split(' ') if i == 1

end

#transfer characters to array of integers

chars.each do |c|
	indexes.push(c.to_i)
end

#sort indexes

indexes = indexes.sort

result = -1

if indexes.count > 1

	for i in 0..(indexes.count - 1)

		if indexes[( i+ 1)].to_i - indexes[i].to_i > 1

			#there is space for a new index
			result = indexes[i].to_i + 1
			break;

		end
	end

else

	if indexes[0].to_i == 1

		#first index is not available, next availble will be first index + 1
		result = indexes[(indexes.count - 1)].to_i + 1;

	else

		#first index is available
		result = 1
	end

end

if result == -1

	#no available space was found, check for minimum value

	if indexes[0].to_i == 1

		#first index is one, if no space was found in the chain, then next available is max value + 1
		result = indexes[(indexes.count - 1)].to_i + 1;

	else

		#first index is not equal to 1 so 1 is available
		result = 1
	end

end

puts result

n = gets.to_i

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

t = true
i = 1
while t && i <= n do
    if !nums.delete(i) then
        result = i
        t = false
    end
    i += 1
end

if t then
    result = n + 1
end

puts result

n=gets.to_i
a=Array.new(n+1,0)
gets.chomp.split.map(&:to_i).each {|x| a[x]=1}
for i in 1..n
	if a[i]==0
		puts i
		exit
	end
end
puts n+1

s = (1..3001).to_a
n = gets.to_i
a = gets.split.map{|r| r.to_i}
s = s - a
puts s[0]

gets.chomp.to_i
a = gets.chomp.split(/ /).map(&:to_i)
tests = Array.new(3001, 0)
a.each do |i|
    tests[i - 1] += 1
end
puts tests.index(0) + 1

def main()
	n=gets.chomp.to_i
	stin=gets.chomp.split(" ",n)
	stin=stin.map{|i| i.to_i}
	stin=stin.sort()
	j=1;f=0;
	for i in 0...(stin.length)
		if stin[i]==j
			j+=1;
		else
			f=1;
			puts j
			break;
		end
	end
	if f==0
		puts j
	end
end
main

n = gets.to_i
a = gets.split(" ").map(&:to_i)
a.sort!
ans = nil

a.each_with_index do |x,i|
	if x != i + 1
		ans = i + 1
		break
	end
end

ans = a[-1] + 1 unless ans
puts ans

gets
puts ((1..3001).to_a - gets.chomp.split.map(&:to_i))[0]

gets
p ((1..3001).to_a - gets.split.map(&:to_i)).min

n = -1
indexes = []

ARGF.each_with_index do |line, i|

	#read number of indexes provided
	n = line if i == 0

	#read indexes
	indexes = line.split(' ') if i == 1

end

#sort indexes
indexes = indexes.sort

result = -1

if indexes.count > 1

	0.upto(indexes.count-1) do |i|

		if indexes[i+1].to_i - indexes[i].to_i > 1

			#there is space for a new index
			result = indexes[i].to_i + 1
			break;

		end
	end

else

	if indexes[0].to_i > 1

		#first index is available
		result = 1

	else

		#first element is equal to 1, assign next to 2
		result = 2
	end

end

if result == -1

	#no available space was found, check for minimum value

	if indexes[0].to_i == 1

		#first index is one, if no space was found in the chain, then next available is max value + 1
		result = indexes[indexes.count -1].to_i + 1;

	else

		#first index is not equal to 1 so 1 is available
		result = 1
	end

end

puts result

n = -1
indexes = []

ARGF.each_with_index do |line, i|

	#read number of indexes provided
	n = line if i == 0

	#read indexes
	indexes = line.split(' ') if i == 1

end

#sort indexes
indexes = indexes.sort

result = -1

if indexes.count > 1

	0.upto(indexes.count-1) do |i|

		if indexes[i+1].to_i - indexes[i].to_i > 1

			#there is space for a new index
			result = indexes[i].to_i + 1
			break;

		end
	end

else

	if indexes[0].to_i == 1

		#first index is not available, next availble will be first index + 1
		result = indexes[indexes.count -1].to_i + 1;

	else

		#first index is available
		result = 1
	end

end

if result == -1

	#no available space was found, check for minimum value

	if indexes[0].to_i == 1

		#first index is one, if no space was found in the chain, then next available is max value + 1
		result = indexes[indexes.count -1].to_i + 1;

	else

		#first index is not equal to 1 so 1 is available
		result = 1
	end

end

puts result

n = -1
indexes = []

ARGF.each_with_index do |line, i|

	#read number of indexes provided
	n = line if i == 0

	#read indexes
	indexes = line.split(' ') if i == 1

end

#sort indexes
indexes = indexes.sort

result = -1

if indexes.count > 1

	0.upto(indexes.count) do |i|

		if indexes[i+1].to_i - indexes[i].to_i > 1

			#there is space for a new index
			result = indexes[i].to_i + 1
			break;

		end
	end

else

	if indexes[0].to_i == 1

		#first index is not available, next availble will be first index + 1
		result = indexes[indexes.count -1].to_i + 1;

	else

		#first index is available
		result = 1
	end

end

if result == -1

	#no available space was found, check for minimum value

	if indexes[0].to_i == 1

		#first index is one, if no space was found in the chain, then next available is max value + 1
		result = indexes[indexes.count -1].to_i + 1;

	else

		#first index is not equal to 1 so 1 is available
		result = 1
	end

end

puts result

n = -1
indexes = []

ARGF.each_with_index do |line, i|

	#read number of indexes provided
	n = line if i == 0

	#read indexes
	indexes = line.split(' ') if i == 1

end

#sort indexes
indexes = indexes.sort

result = -1

if indexes.count > 1

	0.upto((indexes.count-1)) do |i|

		if indexes[(i+1)].to_i - indexes[i].to_i > 1

			#there is space for a new index
			result = indexes[i].to_i + 1
			break;

		end
	end

else

	if indexes[0].to_i == 1

		#first index is not available, next availble will be first index + 1
		result = indexes[(indexes.count - 1)].to_i + 1;

	else

		#first index is available
		result = 1
	end

end

if result == -1

	#no available space was found, check for minimum value

	if indexes[0].to_i == 1

		#first index is one, if no space was found in the chain, then next available is max value + 1
		result = indexes[(indexes.count - 1)].to_i + 1;

	else

		#first index is not equal to 1 so 1 is available
		result = 1
	end

end

puts result

n=gets.to_i
a=Array.new(n+1,0)
gets.chomp.split.map(&:to_i).each {|x| a[x]=1}
print a
puts
for i in 1..n
	if a[i]==0
		puts i
		exit
	end
end
puts n+1

n=gets.to_i
b=Array.new(n,1)
n.times { |i| b[i]=i+1}
a=gets.chomp.split.map(&:to_i).sort
n.times do |i|
	if a[i]!=b[i]
		puts b[i]
		break
	end
end

s = (1..3000).to_a
n = gets.to_i
a = gets.split.map{|r| r.to_i}
s = s - a
puts s[0]

def main()
	n=gets.chomp.to_i
	stin=gets.chomp.split(" ",n)
	stin=stin.map{|i| i.to_i}
	stin=stin.sort()
	j=1;
	for i in 0...(stin.length)
		if stin[i]==j
			j+=1;
		else
			puts j
			break;
		end
	end
end
main

gets
nums = gets.chomp.split.map(&:to_i)

puts ((1..3000).to_a - nums)[0]

gets
nums = gets.chomp.split.map(&:to_i)[0..2999]

puts ((1..3000).to_a - nums)[0]


You have a board represented as a grid with $$$2 \times n$$$ cells.The first $$$k_1$$$ cells on the first row and first $$$k_2$$$ cells on the second row are colored in white. All other cells are colored in black.You have $$$w$$$ white dominoes ($$$2 \times 1$$$ tiles, both cells are colored in white) and $$$b$$$ black dominoes ($$$2 \times 1$$$ tiles, both cells are colored in black).You can place a white domino on the board if both board's cells are white and not occupied by any other domino. In the same way, you can place a black domino if both cells are black and not occupied by any other domino.Can you place all $$$w + b$$$ dominoes on the board if you can place dominoes both horizontally and vertically?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 3000$$$) — the number of test cases. The first line of each test case contains three integers $$$n$$$, $$$k_1$$$ and $$$k_2$$$ ($$$1 \le n \le 1000$$$; $$$0 \le k_1, k_2 \le n$$$). The second line of each test case contains two integers $$$w$$$ and $$$b$$$ ($$$0 \le w, b \le n$$$).

For each test case, print YES if it's possible to place all $$$w + b$$$ dominoes on the board and NO, otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

NoteIn the first test case, $$$n = 1$$$, $$$k_1 = 0$$$ and $$$k_2 = 1$$$. It means that $$$2 \times 1$$$ board has black cell $$$(1, 1)$$$ and white cell $$$(2, 1)$$$. So, you can't place any white domino, since there is only one white cell.In the second test case, the board of the same size $$$2 \times 1$$$, but both cell are white. Since $$$w = 0$$$ and $$$b = 0$$$, so you can place $$$0 + 0 = 0$$$ dominoes on the board.In the third test case, board $$$2 \times 3$$$, but fully colored in black (since $$$k_1 = k_2 = 0$$$), so you can't place any white domino.In the fourth test case, cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, and $$$(2, 1)$$$ are white and other cells are black. You can place $$$2$$$ white dominoes at positions $$$((1, 1), (2, 1))$$$ and $$$((1, 2), (1, 3))$$$ and $$$2$$$ black dominoes at positions $$$((1, 4), (2, 4))$$$ $$$((2, 2), (2, 3))$$$.

gets.to_i.times do
  n, k1, k2 = gets.split(' ').map(&:to_i)
  w, b = gets.split(' ').map(&:to_i)

  white_count = [k1, k2].min + ((k1-k2).abs / 2)
  left_w_c = (k1-k2).abs % 2 # this may be 1 or 0

  black_count = [n-k1, n-k2].min + (((n-k1) - (n-k2)).abs / 2)
  left_b_c = ((n-k1) - (n-k2)).abs % 2 # this may be 1 or 0

  puts white_count >= w && black_count >= b ? 'YES' : 'NO'
end

def solve(n, k1, k2, w, b)
  w_o = (k1 + 1) / 2 + k2 / 2
  w_e = k1 / 2 + (k2 + 1) / 2

  k3, k4 = n - k1, n - k2
  b_o = (k3 + 1) / 2 + k4 / 2
  b_e = k3 / 2 + (k4 + 1) / 2

  w <= min(w_o, w_e) && b <= min(b_o, b_e)
  #(w_o == w_e and b_o == b_e and w <= w_o and b <= b_o)
end

def main
  t = int
  t.times do
    n, k1, k2 = ints
    w, b = ints
    yesno solve(n, k1, k2, w, b)
  end
end

DEBUG = true
MOD = 10**9+7
YESNO = %w(NO YES)
INF = 10**9

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 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 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

main


Polycarp has recently created a new level in this cool new game Berlio Maker 85 and uploaded it online. Now players from all over the world can try his level.All levels in this game have two stats to them: the number of plays and the number of clears. So when a player attempts the level, the number of plays increases by $$$1$$$. If he manages to finish the level successfully then the number of clears increases by $$$1$$$ as well. Note that both of the statistics update at the same time (so if the player finishes the level successfully then the number of plays will increase at the same time as the number of clears).Polycarp is very excited about his level, so he keeps peeking at the stats to know how hard his level turns out to be.So he peeked at the stats $$$n$$$ times and wrote down $$$n$$$ pairs of integers — $$$(p_1, c_1), (p_2, c_2), \dots, (p_n, c_n)$$$, where $$$p_i$$$ is the number of plays at the $$$i$$$-th moment of time and $$$c_i$$$ is the number of clears at the same moment of time. The stats are given in chronological order (i.e. the order of given pairs is exactly the same as Polycarp has written down).Between two consecutive moments of time Polycarp peeked at the stats many players (but possibly zero) could attempt the level.Finally, Polycarp wonders if he hasn't messed up any records and all the pairs are correct. If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then he considers his records correct.Help him to check the correctness of his records.For your convenience you have to answer multiple independent test cases.

The first line contains a single integer $$$T$$$ $$$(1 \le T \le 500)$$$ — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of moments of time Polycarp peeked at the stats. Each of the next $$$n$$$ lines contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$0 \le p_i, c_i \le 1000$$$) — the number of plays and the number of clears of the level at the $$$i$$$-th moment of time. Note that the stats are given in chronological order.

For each test case print a single line. If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then print "YES". Otherwise, print "NO". You can print each letter in any case (upper or lower).

NoteIn the first test case at the third moment of time the number of clears increased but the number of plays did not, that couldn't have happened.The second test case is a nice example of a Super Expert level.In the third test case the number of plays decreased, which is impossible.The fourth test case is probably an auto level with a single jump over the spike.In the fifth test case the number of clears decreased, which is also impossible.Nobody wanted to play the sixth test case; Polycarp's mom attempted it to make him feel better, however, she couldn't clear it.

t = gets.chomp.to_i
while t>0 do
    n = gets.chomp.to_i
    las_a = 0
    las_b = 0
    ok = true
    for i in 1..n do
        tmp = gets.chomp.split(" ")
        a = tmp[0].to_i
        b = tmp[1].to_i
        if b-las_b>a-las_a or b<las_b or a<las_a then
            ok = false
        end
        las_a = a
        las_b = b
    end
    if ok then
        puts "YES"
    else
        puts "NO"
    end
    t -= 1
end

def run
  n = gets.chomp.to_i
  pp, pc = *[0, 0]

  a = []

  n.times do
    v = gets.chomp.split(" ").map(&:to_i)
    a.push(v)
  end

  a.each do |p, c|
    if p >= pp && c >= pc && (p - pp) >= (c - pc)
      pp = p
      pc = c
    else
      puts 'no'
      return
    end
  end

  puts 'yes'
end

def main
  t = gets.chomp.to_i

  t.times do
    run
  end
end

main

n = STDIN.gets.to_i
n.times do |i|
  j = STDIN.gets.to_i
  sets = []
  j.times do
    match = STDIN.gets.strip.match(/(\d+) (\d+)/)
    sets << [match[1].to_i, match[2].to_i]
  end
  r = 0
  c = 0
  skip = false
  for a, b in sets do
    if (a < r) or (b < c) or (b > a) or ((a == r) and (b > c)) or ((a - r) < (b - c))
      puts 'NO'
      skip = true
      break
    else
      r = a
      c = b
    end
  end
  puts 'YES' unless skip
end

t = gets.to_i
t.times do
  played = 0
  cleared = 0
  ok = true
  n = gets.to_i
  n.times do
    p, c = gets.split.map(&:to_i)
    ok = false if p < c
    ok = false if p < played
    ok = false if c < cleared
    ok = false if (p - played) < (c - cleared)
    played = p
    cleared = c
  end
  puts ok ? "YES" : "NO"
end

gets.to_i.times do
  prev = [0, 0]
  ok = true

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

    ok &&= (a.last  - prev.last)  >= 0
    ok &&= (a.first - prev.first) >= (a.last - prev.last)

    prev = a
  end

  puts ok ? 'YES' : 'NO'
end

n = STDIN.gets.to_i
n.times do |i|
  j = STDIN.gets.to_i
  sets = []
  j.times do
    match = STDIN.gets.strip.match(/(\d+) (\d+)/)
    sets << [match[1].to_i, match[2].to_i]
  end
  p = 0
  c = 0
  skip = false
  for a, b in sets do
    if (a < p) or (b < c) or (b > a)
      puts 'NO'
      skip = true
      break
    else
      p = a
      c = b
    end
  end
  puts 'YES' unless skip
end

t = gets.to_i
t.times do
  played = 0
  cleared = 0
  ok = true
  n = gets.to_i
  n.times do
    p, c = gets.split.map(&:to_i)
    ok = false if p < c
    ok = false if p < played
    ok = false if c < cleared
    played = p
    cleared = c
  end
  puts ok ? "YES" : "NO"
end


You are given two integers $$$x$$$ and $$$y$$$. You can perform two types of operations:   Pay $$$a$$$ dollars and increase or decrease any of these integers by $$$1$$$. For example, if $$$x = 0$$$ and $$$y = 7$$$ there are four possible outcomes after this operation:   $$$x = 0$$$, $$$y = 6$$$;  $$$x = 0$$$, $$$y = 8$$$;  $$$x = -1$$$, $$$y = 7$$$;  $$$x = 1$$$, $$$y = 7$$$.   Pay $$$b$$$ dollars and increase or decrease both integers by $$$1$$$. For example, if $$$x = 0$$$ and $$$y = 7$$$ there are two possible outcomes after this operation:   $$$x = -1$$$, $$$y = 6$$$;  $$$x = 1$$$, $$$y = 8$$$.  Your goal is to make both given integers equal zero simultaneously, i.e. $$$x = y = 0$$$. There are no other requirements. In particular, it is possible to move from $$$x=1$$$, $$$y=0$$$ to $$$x=y=0$$$.Calculate the minimum amount of dollars you have to spend on it.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of testcases. The first line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$0 \le x, y \le 10^9$$$). The second line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).

For each test case print one integer — the minimum amount of dollars you have to spend.

NoteIn the first test case you can perform the following sequence of operations: first, second, first. This way you spend $$$391 + 555 + 391 = 1337$$$ dollars.In the second test case both integers are equal to zero initially, so you dont' have to spend money.

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

t = file.gets.chomp.to_i
t.times do
  x, y =  file.gets.chomp.split.map(&:to_i)
  a, b =  file.gets.chomp.split.map(&:to_i)

  if a == 0 || b == 0
    puts 0
    next
  end

  if x==y
    puts [x*b, a*2*x].min
  elsif x > y
    c=a*(x-y)+b*y
    d=a*(x-y)+2*a*y
    puts [c,d].min
  else
    c=a*(y-x)+b*x;
    d=a*(y-x)+2*a*x;
    puts [c,d].min
  end
end

def run
  x, y = gets.chomp.split(" ").map(&:to_i)
  a, b = gets.chomp.split(" ").map(&:to_i)

  r = if a * 2 < b || x == 0 ||  y == 0
    (x + y) * a
  else
    (x - y).abs * a + [x, y].min * b
  end
  puts r
end

def main
  t = gets.chomp.to_i

  t.times do
    run
  end
end

main

gets.to_i.times {
    x, y=gets.split.map &:to_i
    a, b=gets.split.map &:to_i

    s=x.abs
    t=y.abs
    puts [s*a+t*a, s*b+(y-x).abs*a, t*b+(x-y).abs*a].min
}

g = gets.chomp.to_i
g.times{|w|
x,y = gets.split(" ").map{|x|x.to_i}
a,b = gets.split(" ").map{|x|x.to_i}
all = []

x1=0
y1=0

x1+=x
y1+=y

z=0
#method 1
loop do
if (x==0 && y==0)
break
else

if (x > 0 && y > 0)
hh=[]
hh.push(x)
hh.push(y)
z+=(hh.min*b)
x-=hh.min
y-=hh.min

if (x!=0)
z+=x*a
x-=x
end
if (y!=0)
z+=y*a
y-=y
end
end

if (x < 0 && y < 0)
hh=[]
hh.push(x)
hh.push(y)
z+=(hh.max.abs*b)
x+=hh.max.abs
y+=hh.max.abs

if (x!=0)
z+=x.abs*a
x+=x.abs
end
if (y!=0)
z+=y.abs*a
y+=y.abs
end
end

if (x<0)
z+=x.abs*a
x+=x.abs
end
if (x>0)
z+=x*a
x-=x
end
if (y<0)
z+=y.abs*a
y+=y.abs
end
if (y>0)
z+=y*a
y-=y
end

end
end
all.push(z)

z=0
x=x1
y=y1
loop do
if (x==0 && y==0)
break
else

if (x<0)
z+=x.abs*a
x+=x.abs
end
if (x>0)
z+=x*a
x-=x
end
if (y<0)
z+=y.abs*a
y+=y.abs
end
if (y>0)
z+=y*a
y-=y
end

end
end
all.push(z)

puts all.min
}

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

  x,y = y,x if x > y
  puts [a*x + a*y, b*x + a*(y-x)].min
end

t = gets.chomp.to_i
t.times do
	x,y  = gets.chomp.split(" ").map(&:to_i)
	a, b = gets.chomp.split(" ").map(&:to_i)
	if 2 * a < b then
		puts a * (x + y)
	else
		diff = (x - y).abs
		puts ([x,y].max - diff) * b + a * diff
	end
end

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

  puts [
    [x, y].min * b + (x - y).abs * a,
    x * a + y * a
  ].min
end

def solution
  x, y = gets.split.map(&:to_i)
  a, b = gets.split.map(&:to_i)

  return 0 if x == 0 && y == 0

  if b > 2 * a
    return (x + y) * a
  end

  min = [x, y].min
  max = [x, y].max
  min * b + (max - min) * a
end

t = gets.to_i
t.times do
  p solution
end

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

t = file.gets.chomp.to_i
t.times do
  x, y =  file.gets.chomp.split.map(&:to_i)
  a, b =  file.gets.chomp.split.map(&:to_i)
  res = 0

  if x==y
    res+= [x*b, a*2*x].min
  else
    d = (x-y).abs
    res += d * a
    res += ([x,y].max-d)*b
  end
  puts res
end

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

t = file.gets.chomp.to_i
t.times do
  x, y =  file.gets.chomp.split.map(&:to_i)
  a, b =  file.gets.chomp.split.map(&:to_i)

  if x==y
    puts [x*b, a*2*x].min
  else
    res = 0
    d = (x-y).abs
    res += d * a
    res += ([x,y].max-d)*b
    res2 = (d*a) +(b*[x,y].max)
    puts [res, res2].min
  end
end

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

t = file.gets.chomp.to_i
t.times do
  x, y =  file.gets.chomp.split.map(&:to_i)
  a, b =  file.gets.chomp.split.map(&:to_i)

  if a == 0 || b == 0
    puts 0
    next
  end

  if x==y
    puts [x*b, a*2*x].min
  else
    res = 0
    d = (x-y).abs
    res += d * a
    res += ([x,y].max-d)*b
    res2 = (d*a) +(b*[x,y].max)
    # puts "#{[res, res2]}"
    puts [res, res2].min
  end
end

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

t = file.gets.chomp.to_i
t.times do
  x, y =  file.gets.chomp.split.map(&:to_i)
  a, b =  file.gets.chomp.split.map(&:to_i)

  if a == 0 || b == 0
    puts 0
    next
  end

  if x==y
    puts [x*b, a*2*x].min
  else
    d = (x-y).abs

    res = (d*a) + ([x,y].max-d)*b

    # res2 = (d*a) +(b*[x,y].max)
    # puts "#{[res, res2]}"
    # puts [res, res2].min
    puts res
  end
end

g = gets.chomp.to_i
g.times{|w|
x,y = gets.split(" ").map{|x|x.to_i}
a,b = gets.split(" ").map{|x|x.to_i}
all = []

z=0
#method 1
loop do
if (x==0 && y==0)
break
else

if (x > 0 && y > 0)
hh=[]
hh.push(x)
hh.push(y)
z+=(hh.min*b)
x-=hh.min
y-=hh.min

if (x!=0)
z+=x*a
x-=x
end
if (y!=0)
z+=y*a
y-=y
end
end

if (x < 0 && y < 0)
hh=[]
hh.push(x)
hh.push(y)
z+=(hh.max*b)
x+=hh.max.abs
y+=hh.max.abs

if (x!=0)
z+=x.abs*a
x+=x.abs
end
if (y!=0)
z+=y.abs*a
y+=y.abs
end
end

if (x<0)
z+=x.abs*a
x+=x.abs
end
if (x>0)
z+=x*a
x-=x
end
if (y<0)
z+=y.abs*a
y+=y.abs
end
if (y>0)
z+=y*a
y-=y
end

end
end

puts z
}

g = gets.chomp.to_i
g.times{|w|
x,y = gets.split(" ").map{|x|x.to_i}
a,b = gets.split(" ").map{|x|x.to_i}
all = []

z=0
#method 1
loop do
if (x==0 && y==0)
break
else

if (x > 0 && y > 0)
hh=[]
hh.push(x)
hh.push(y)
z+=(hh.min*b)
x-=hh.min
y-=hh.min

if (x!=0)
z+=x*a
x-=x
end
if (y!=0)
z+=y*a
y-=y
end
end

if (x < 0 && y < 0)
hh=[]
hh.push(x)
hh.push(y)
z+=(hh.max.abs*b)
x+=hh.max.abs
y+=hh.max.abs

if (x!=0)
z+=x.abs*a
x+=x.abs
end
if (y!=0)
z+=y.abs*a
y+=y.abs
end
end

if (x<0)
z+=x.abs*a
x+=x.abs
end
if (x>0)
z+=x*a
x-=x
end
if (y<0)
z+=y.abs*a
y+=y.abs
end
if (y>0)
z+=y*a
y-=y
end

end
end

puts z
}

g = gets.chomp.to_i
g.times{|w|
x,y = gets.split(" ").map{|x|x.to_i}
a,b = gets.split(" ").map{|x|x.to_i}
all = []

z=0
#method 1
if (x==0 && y==0)

else

if (x > 0 && y > 0)
hh=[]
hh.push(x)
hh.push(y)
z+=(hh.min*b)
x-=hh.min
y-=hh.min

if (x!=0)
z+=x*a
x-=x
end
if (y!=0)
z+=y*a
y-=y
end
end

if (x < 0 && y < 0)
hh=[]
hh.push(x)
hh.push(y)
z+=(hh.max*b)
x+=hh.max
y+=hh.max

if (x!=0)
z+=x.abs*a
x+=x
end
if (y!=0)
z+=y.abs*a
y+=y
end
end

end
puts z
}

g = gets.chomp.to_i
g.times{|w|
x,y = gets.split(" ").map{|x|x.to_i}
a,b = gets.split(" ").map{|x|x.to_i}
all = []

z=0
#method 1
loop do
if (x==0 && y==0)
break
else

if (x > 0 && y > 0)
hh=[]
hh.push(x)
hh.push(y)
z+=(hh.min*b)
x-=hh.min
y-=hh.min

if (x!=0)
z+=x*a
x-=x
end
if (y!=0)
z+=y*a
y-=y
end
end

if (x < 0 && y < 0)
hh=[]
hh.push(x)
hh.push(y)
z+=(hh.max*b)
x+=hh.max
y+=hh.max

if (x!=0)
z+=x.abs*a
x+=x
end
if (y!=0)
z+=y.abs*a
y+=y
end
end

if (x<0)
z+=x.abs*a
x+=x.abs
end
if (x>0)
z+=x*a
x-=x
end
if (y<0)
z+=y.abs*a
y+=y.abs
end
if (y>0)
z+=y*a
y-=y
end

end
end

puts z
}


Jafar has n cans of cola. Each can is described by two integers: remaining volume of cola ai and can's capacity bi (ai  ≤  bi).Jafar has decided to pour all remaining cola into just 2 cans, determine if he can do this or not!

The first line of the input contains one integer n (2 ≤ n ≤ 100 000) — number of cola cans. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) — volume of remaining cola in cans. The third line contains n space-separated integers that b1, b2, ..., bn (ai ≤ bi ≤ 109) — capacities of the cans.

Print "YES" (without quotes) if it is possible to pour all remaining cola in 2 cans. Otherwise print "NO" (without quotes). You can print each letter in any case (upper or lower).

NoteIn the first sample, there are already 2 cans, so the answer is "YES".

gets
a=gets.split.map(&:to_i).reduce :+
b=gets.split.map(&:to_i).sort[-2..-1].reduce :+
puts a<=b ? :YES : :NO

def solve(n, cans, sizes)
  total = cans.inject(:+)
  free = sizes.sort.reverse.first(2).inject(:+)
  free >= total ? "YES" : "NO"
end

puts solve(gets.strip.to_i, gets.strip.split.map(&:to_i), gets.strip.split.map(&:to_i))

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

def solve
  $b.sort_by! { |x| x }
  if ($a.inject(0, :+) <= $b[-2..-1].inject(0, :+))
    return "YES"
  end
  return "NO"
end

print solve

gets
a=gets.split.map{|e| e.to_i}
b=gets.split.map{|e| e.to_i}.sort.reverse
if b[0]+b[1]-a.inject(0){|sum,e| sum+e}<0 then
puts "NO"
else
puts "YES"
end

def sum(arr)
  ret = 0
  arr.each do |i|
    ret += i
  end
  return ret
end

n = gets.to_i
a = gets.split.map {|i| i.to_i}
b = gets.split.map {|i| i.to_i}.sort
if sum(a) <= sum(b.last(2)) then
	puts "YES"
else
	puts "NO"
end

n = Integer(gets.chomp)

volume_line = gets.chomp.split(" ").to_a.map{ |i| Integer(i) }
value = volume_line.inject(0){ |v, i| v + i }

cups_line = gets.chomp.split(" ").to_a.map{ |i| Integer(i) }.sort.reverse

print (value <= cups_line[0] + cups_line[1]) ? "YES" : "NO"

n = gets
n = n.to_i

arr = Array.new(n){Array.new(2){0}}

s = gets
s.split(" ").map(&:to_i).each.with_index do |v, index|
  arr[index][0] = v
end

s = gets
s.split(" ").map(&:to_i).each.with_index do |v, index|
  arr[index][1] = v
end

first_max = -Float::INFINITY
second_max = -Float::INFINITY

sum_volumes = 0

arr.each do |v,c|
  sum_volumes += v
  if c >= first_max
    second_max = first_max
    first_max = c
  elsif c > second_max
    second_max = c
  end
end

if sum_volumes <= (first_max + second_max )
  puts "YES"
else
  puts "NO"
end

n = gets.to_i
a = gets.split.map(&:to_i).inject(:+)
b = gets.split.map(&:to_i).sort
puts a <= b[-1] + b[-2] ? "YES" : "NO"

n = gets.to_i
a = gets.split.map &:to_i
b = gets.split.map &:to_i
puts a.inject(0){|s, x| s + x} <= b.sort[-2] +  b.sort[-1] ? 'YES' : 'NO'

n= gets.to_i

remaining = gets.split(" ").map(&:to_i).inject(0, :+)
capacities = gets.split(" ").map(&:to_i)
max1 = capacities.max
capacities.delete_at capacities.index(max1)
max2 = capacities.max

if max1+max2 >= remaining
	print('YES')
else
	print('NO')
end


You are given an array $$$a_1, a_2, \dots , a_n$$$. Array is good if for each pair of indexes $$$i < j$$$ the condition $$$j - a_j \ne i - a_i$$$ holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if $$$a = [1, 1, 3, 5]$$$, then shuffled arrays $$$[1, 3, 5, 1]$$$, $$$[3, 5, 1, 1]$$$ and $$$[5, 3, 1, 1]$$$ are good, but shuffled arrays $$$[3, 1, 5, 1]$$$, $$$[1, 1, 3, 5]$$$ and $$$[1, 1, 5, 3]$$$ aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le 100$$$).

For each test case print the shuffled version of the array $$$a$$$ which is good.

T = gets.to_i

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

  puts a.sort.reverse.join(' ')
end

# coding: utf-8

# bogosort 정렬이 아니란 거죠.
# i < j 인 인덱스 페어에 대하여 i - ai != j - aj
# 예를 들어 a = [1, 1, 3, 5] 에 대해서
# (1, 2) 는 1 - 1 != 2 - 1 로 만족이지만 (1, 3)은 1 - 1 == 3 - 3이므로
# 성립하지 않음.
# 배열의 최소 크기는 1

def bogosort(a)
    ar = a.sort.reverse
    return ar
end

t = gets.to_i
t.times {
    n = gets.to_i
    a = gets.split.map(&:to_i)
    puts bogosort(a).join(' ')
}

 gets.to_i.times do
     gets
     puts gets.split.map(&:to_i).sort.reverse.join(' ')
 end

t = gets.chomp.to_i
(0...t).each do |_|
  n = gets.chomp.to_i
  l = gets.chomp.split.map(&:to_i)
  #r = []
  r = l.sort.reverse
  print r.join(' ')
  puts
end

t = gets.chomp.to_i
(0...t).each do |_|
  n = gets.chomp.to_i
  print gets.chomp.split.map(&:to_i).sort.reverse.join(' ')
  puts
end

 gets.to_i.times do
     gets
     puts gets.split.sort.reverse.join(' ')
 end

def check(a)
  (0...a.size).each do |i|
    state = true
    (i+1...a.size).each do |j|
      (state = false; break;) if j - a[j] == i - a[i]
    end
    return true if state
  end
  false
end

t = gets.chomp.to_i
(0...t).each do |_|
  n = gets.chomp.to_i
  l = gets.chomp.split.map(&:to_i)
  r = []
  l.sort.permutation.each do |a|
    (r = a; break;) if check(a)
  end
  print r.join(' ')
  puts
end

def check(a)
  (0...a.size).each do |i|
    state = true
    (i+1...a.size).each do |j|
      (state = false; break;) if j - a[j] == i - a[i]
    end
    return true if state
  end
  false
end

t = gets.chomp.to_i
(0...t).each do |_|
  n = gets.chomp.to_i
  l = gets.chomp.split.map(&:to_i)
  r = []
  l.permutation.each do |a|
    r = a if check(a)
  end
  print r.join(' ')
  puts
end


This is an interactive problem.Natasha is going to fly to Mars. Finally, Natasha sat in the rocket. She flies, flies... but gets bored. She wishes to arrive to Mars already! So she decides to find something to occupy herself. She couldn't think of anything better to do than to calculate the distance to the red planet.Let's define $$$x$$$ as the distance to Mars. Unfortunately, Natasha does not know $$$x$$$. But it is known that $$$1 \le x \le m$$$, where Natasha knows the number $$$m$$$. Besides, $$$x$$$ and $$$m$$$ are positive integers.Natasha can ask the rocket questions. Every question is an integer $$$y$$$ ($$$1 \le y \le m$$$). The correct answer to the question is $$$-1$$$, if $$$x<y$$$, $$$0$$$, if $$$x=y$$$, and $$$1$$$, if $$$x>y$$$. But the rocket is broken — it does not always answer correctly. Precisely: let the correct answer to the current question be equal to $$$t$$$, then, if the rocket answers this question correctly, then it will answer $$$t$$$, otherwise it will answer $$$-t$$$.In addition, the rocket has a sequence $$$p$$$ of length $$$n$$$. Each element of the sequence is either $$$0$$$ or $$$1$$$. The rocket processes this sequence in the cyclic order, that is $$$1$$$-st element, $$$2$$$-nd, $$$3$$$-rd, $$$\ldots$$$, $$$(n-1)$$$-th, $$$n$$$-th, $$$1$$$-st, $$$2$$$-nd, $$$3$$$-rd, $$$\ldots$$$, $$$(n-1)$$$-th, $$$n$$$-th, $$$\ldots$$$. If the current element is $$$1$$$, the rocket answers correctly, if $$$0$$$ — lies. Natasha doesn't know the sequence $$$p$$$, but she knows its length — $$$n$$$.You can ask the rocket no more than $$$60$$$ questions.Help Natasha find the distance to Mars. Assume, that the distance to Mars does not change while Natasha is asking questions.Your solution will not be accepted, if it does not receive an answer $$$0$$$ from the rocket (even if the distance to Mars is uniquely determined by the already received rocket's answers).

The first line contains two integers $$$m$$$ and $$$n$$$ ($$$1 \le m \le 10^9$$$, $$$1 \le n \le 30$$$) — the maximum distance to Mars and the number of elements in the sequence $$$p$$$.

NoteIn the example, hacking would look like this:5 2 31 0This means that the current distance to Mars is equal to $$$3$$$, Natasha knows that it does not exceed $$$5$$$, and the rocket answers in order: correctly, incorrectly, correctly, incorrectly ...Really:on the first query ($$$1$$$) the correct answer is $$$1$$$, the rocket answered correctly: $$$1$$$;on the second query ($$$2$$$) the correct answer is $$$1$$$, the rocket answered incorrectly: $$$-1$$$;on the third query ($$$4$$$) the correct answer is $$$-1$$$, the rocket answered correctly: $$$-1$$$;on the fourth query ($$$5$$$) the correct answer is $$$-1$$$, the rocket answered incorrectly: $$$1$$$;on the fifth query ($$$3$$$) the correct and incorrect answer is $$$0$$$.

M, N = gets.split.map(&:to_i)
wrong = Array.new(N)

N.times do |i|
    puts 1
    $stdout.flush
    result = gets.to_i
    exit if result == 0
    wrong[i] = (result != 1)
end

ub = M
lb = 2
60.times do |i|
    mid = (ub+lb)/2
    puts mid
    $stdout.flush
    result = gets.to_i
    exit if result == 0
    if (result == 1) ^ wrong[i%N]
        lb = mid + 1
    else
        ub = mid - 1
    end
end

q = 60
m, n = gets.strip.split.map(&:to_i)
seq=Array.new(n)

q-=n

n.times do |i|
  puts 1
  STDOUT.flush
  seq[i] = gets.to_i
  exit(0) if seq[i]==0
end

lo=1
hi=m
si=0
while lo<=hi
  mid=((lo+hi)/2)
  puts mid
  STDOUT.flush
  res = gets.to_i
  res *= seq[si]
  si+=1
  si%=n
  if res==0 || res.abs==2
    exit 0
  elsif res==1
    lo=mid+1
  else
    hi=mid
  end
end

N, M = gets.split.map(&:to_i)
wrong = Array.new(N)

N.times do |i|
    puts 1
    $stdout.flush
    result = gets.to_i
    exit if result == 0
    wrong[i] = (result == 1)
end

ub = M
lb = 2
N.times do |i|
    mid = (ub+lb)/2
    puts mid
    $stdout.flush
    result = gets.to_i
    exit if result == 0
    if (result == 1) ^ wrong[i]
        lb = mid + 1
    else
        ub = mid - 1
    end
end

M, N = gets.split.map(&:to_i)
wrong = Array.new(N)

N.times do |i|
    puts 1
    $stdout.flush
    result = gets.to_i
    exit if result == 0
    wrong[i] = (result != 1)
end

ub = M
lb = 2
N.times do |i|
    mid = (ub+lb)/2
    puts mid
    $stdout.flush
    result = gets.to_i
    exit if result == 0
    if (result == 1) ^ wrong[i]
        lb = mid + 1
    else
        ub = mid - 1
    end
end

q = 60
m, n = gets.strip.split.map(&:to_i)
seq=Array.new(n)

q-=n

n.times do |i|
  puts 0
  STDOUT.flush
  seq[i] = gets.to_i
end

lo=1
hi=m
si=0
while lo<=hi
  mid=((lo+hi)/2)
  puts mid
  STDOUT.flush
  res = gets.to_i
  res *= seq[si]
  si+=1
  si%=n
  if res==0 || res.abs==2
    exit 0
  elsif res==1
    lo=mid+1
  else
    hi=mid
  end
end

q = 60
m, n = gets.strip.split.map(&:to_i)
seq=Array.new(n)

q-=n

n.times do |i|
  puts -1
  STDOUT.flush
  seq[i] = gets.to_i
end

lo=1
hi=m
si=0
while lo<=hi
  mid=((lo+hi)/2)
  puts mid
  STDOUT.flush
  res = gets.to_i
  res *= seq[si]
  si+=1
  si%=n
  if res==0 || res.abs==2
    exit 0
  elsif res==1
    lo=mid+1
  else
    hi=mid
  end
end


You are given two integers $$$n$$$ and $$$k$$$.You should create an array of $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$ such that the sum $$$(a_1 + a_2 + \dots + a_n)$$$ is divisible by $$$k$$$ and maximum element in $$$a$$$ is minimum possible.What is the minimum possible maximum element in $$$a$$$?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^9$$$; $$$1 \le k \le 10^9$$$).

For each test case, print one integer — the minimum possible maximum element in array $$$a$$$ such that the sum $$$(a_1 + \dots + a_n)$$$ is divisible by $$$k$$$.

NoteIn the first test case $$$n = 1$$$, so the array consists of one element $$$a_1$$$ and if we make $$$a_1 = 5$$$ it will be divisible by $$$k = 5$$$ and the minimum possible.In the second test case, we can create array $$$a = [1, 2, 1, 2]$$$. The sum is divisible by $$$k = 3$$$ and the maximum is equal to $$$2$$$.In the third test case, we can create array $$$a = [1, 1, 1, 1, 1, 1, 1, 1]$$$. The sum is divisible by $$$k = 8$$$ and the maximum is equal to $$$1$$$.

gets.to_i.times do
    n, k = gets.split.map &:to_i
    k *= (n + k - 1) / k
    puts (k + n - 1) / n
end

_t = gets.to_s.to_i
_t.times do
  n, k = gets.to_s.split.map{ |e| e.to_i }
  k *= (n + k - 1) / k if n > k
  puts (k + n - 1) / n
end

gets.to_i.times do
  n,k=gets.split.map(&:to_i)
  if k==1
    puts 1
  elsif n==1
    puts k
  elsif n%k==0
    puts 1
  elsif n<k
    puts (k-1)/n+1
  else
    puts 2
  end
end