You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.

The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.

Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).

NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .

def checks(sizes, selections, array_1, array_2)
  selections = selections.split(' ').map(&:to_i)
  array_1 = array_1.split(' ').map(&:to_i)
  array_2 = array_2.split(' ').map(&:to_i)

  max_1 = array_1.sort.first(selections[0]).max
  max_2 = array_2.sort.last(selections[1]).min

  if max_1 < max_2
    r = 'YES'
  else
    r = 'NO'
  end
  puts r
end
checks(gets.chomp, gets.chomp, gets.chomp, gets.chomp)

la,lb = gets.split(" ").map(&:to_i)
k,m = gets.split(" ").map(&:to_i)

arr = gets.split(" ").map(&:to_i)
brr = gets.split(" ").map(&:to_i)
puts arr[k-1]<brr[-m] ? "YES" : "NO"

la,lb = gets.split(" ").map(&:to_i)
k,m = gets.split(" ").map(&:to_i)

arr = gets.split(" ").map(&:to_i)
brr = gets.split(" ").map(&:to_i)
for i in 0...lb
    if arr[k-1]<brr[i]
        break
    else
        i = lb
    end
end
if (lb-i)>=m
    puts "YES"
else
    puts "NO"
end

n = gets.chomp.split(" ").map!{|val| val=val.to_i}
na=n[0]
nb=n[1]

km = gets.chomp.split(" ").map!{|val| val=val.to_i}
k = km[0]
m = km[1]

Aarray = gets.chomp.split(" ").map! {|val| val=val.to_i}
Barray = gets.chomp.split(" ").map! {|val| val=val.to_i}

puts "YES" if Aarray[k-1] < Barray[nb-m]
puts "NO" unless Aarray[k-1] < Barray[nb-m]

# http://codeforces.com/contest/572/problem/A
x, y = gets.chomp.split.map(&:to_i)
n, m = gets.chomp.split.map(&:to_i)

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

puts a[n - 1] < b[y - m] ? 'YES' : 'NO'

class TaskA
  def initialize
    @nA, @nB = gets.split.map(&:to_i)
    @k, @m = gets.split.map(&:to_i)
    @a = gets.split.map(&:to_i)
    @b = gets.split.map(&:to_i)
  end

  def solve
    if @a[@k-1] < @b[-@m] then
      puts "YES"
    else
      puts "NO"
    end
  end
end

TaskA.new.solve

na, nb = gets.split.map(&:to_i)
k, m = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)[0..-1]
b = gets.split.map(&:to_i)[0..-1]
if(a[k-1] < b[nb - m])
    puts "YES"
else
    puts "NO"
end

gets
n,m=gets.split.map{|e| e.to_i}
a=gets.split.map{|e| e.to_i}
b=gets.split.map{|e| e.to_i}

puts (a[n-1]<b[b.size-m])?"YES":"NO"

gets
(k, m), a, b = 3.times.map { gets.split(' ').map(&:to_i) }

res = if k <= a.size && m <= b.size && a[k-1] < b[b.size-m]
  "YES"
else
  "NO"
end

puts res

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

q1 = gets.split.map(&:to_i)
q2 = gets.split.map(&:to_i)

puts q1[k-1] < q2[-m] ? "YES" : "NO"

na,nb = gets.split(' ').map(&:to_i)

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

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

if a1[k-1] < a2[-m]
  puts "YES"
else
   puts "NO"
 end

# coding: utf-8
C = Struct.new(:num, :tag)
na, nb = gets.split.map(&:to_i)
k, m = gets.split.map(&:to_i)
nar = gets.split.map(&:to_i) # non-desc order
nbr = gets.split.map(&:to_i) # non-desc order

if nar[k-1] < nbr[nb - m] # 이미 정렬되어있으므로 마지막에서 세번째 숫자만 비교하면 OK
    puts "YES"
else
    puts "NO"
end

na, nb = gets.chomp.split(' ').map(&:to_i)
k, m = gets.chomp.split(' ').map(&:to_i)
as = gets.chomp.split(' ').map(&:to_i)
bs = gets.chomp.split(' ').map(&:to_i)

puts as[k-1] < bs[nb-m] ? 'YES' : 'NO'

na, nb = gets.split.map(&:to_i)
k, m = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
b = gets.split.map(&:to_i)
puts a[k - 1] < b[-m] ? 'YES' : 'NO'

na, nb = gets.split.map(&:to_i)
k, m = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
b = gets.split.map(&:to_i)
bb = b.find_index{|x| x > a[k - 1]}
puts bb && b[bb..-1].size >= m ? 'YES' : 'NO'

na, nb = gets.split.map(&:to_i)
k, m = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
b = gets.split.map(&:to_i)
bb = b.find_index{|x| x > a[k - 1]}
c = []
c = b[bb..-1] if bb
puts c.size >= m ? 'YES' : 'NO'

nA,nB = gets.split.map(&:to_i)
k,m = gets.split.map(&:to_i)
x = gets.split.map(&:to_i)
y = gets.split.map(&:to_i)
puts x[(k-1)] < y[(nB - m)] ? "YES" : "NO"

n1, n2 = gets.split.map(&:to_i)
k, m = gets.split.map(&:to_i)
array1 = gets.split.map(&:to_i)
array2 = gets.split.map(&:to_i)
puts array1[k-1 ] < array2[n2 - m] ? 'YES' : 'NO'

# Ý tưởng:
# Để có khả năng k số trong array a luôn nhỏ hơn m số trong mảng b
# thì ta phải luôn chọn k số nhỏ nhất trong mảng a và m số lớn nhất trong b.
# Nói cách khác, ta phải luôn chọn k số đầu tiên ở a và m số cuối cùng ở b.
# Sau đó ta so sánh số lớn nhất được chọn trong k số ở a và số nhỏ nhất được chọn trong m số ở b.
# Nếu số lớn nhất trong k số đó nhỏ hơn số nhỏ nhất trong m số kia thì kết quả luôn là “YES”, ngược lại là “NO”

size_a, size_b = gets.chomp.split.map(&:to_i)
k, m = gets.chomp.split.map(&:to_i)

array_a = gets.chomp.split.map(&:to_i)
array_b = gets.chomp.split.map(&:to_i)

puts array_a[k - 1] < array_b[-m] ? "YES" : "NO"

def checks(sizes, selections, array_1, array_2)
  selections = selections.split.map(&:to_i)
  array_1 = array_1.split.map(&:to_i)
  array_2 = array_2.split.map(&:to_i)
  puts array_1.sort.first(selections[0]).max < array_2.sort.last(selections[1]).min ? 'YES' : 'NO'
end
checks(gets, gets, gets, gets)

# Array1: Find min elements base on selection after that find max element
# Array2: Find max elements base on selection after that find min element
# Condition value of 2 array if array 1 < array 2 then print 'Yes' otherwise print 'No'

#!/usr/bin/ruby

# def qselect(a, b, k, m)
#   def qloc(a, b)
#     l = a.length
#     return -1 if b <= a[0]
#     return l if b > a[-1]
#     i = 0
#     loop do
#       break -1 if i < 0 or i >= l
#       break i if a[i+1] and b > a[i] and b <= a[i+1]
#       break i if not a[i+1] and b > a[i]
#       i = b > a[i] ? (l + i + 1) / 2 : i / 2
#     end
#   end
#   return false if k > a.length or m > b.length
#   p = qloc(a, b[-m])
#   k <= p + 1
# end

def algo
  gets
  k, m = gets.split(' ').map { |e| e.to_i }
  a = gets.split(' ').map { |e| e.to_i }
  b = gets.split(' ').map { |e| e.to_i }
  # puts qselect(a, b, k, m) ? "YES" : "NO"
  puts b[-m] > a[k-1] ? "YES" : "NO"
end

algo

#!/usr/bin/ruby
z,(k,m),A,B=$<.map{|e|e.split.map &:to_i}
puts A.sort[k-1]<B.sort[-m] ? :YES : :NO

def checks(sizes, selections, array_1, array_2)
  selections = selections
  array_1 = array_1.split
  array_2 = array_2.split
  puts 1 < 2 ? 'YES' : 'NO'
end
checks(gets.chomp, gets.chomp, gets.chomp, gets.chomp)

la,lb = gets.split(" ").map(&:to_i)
k,m = gets.split(" ").map(&:to_i)

arr = gets.split(" ").map(&:to_i)
brr = gets.split(" ").map(&:to_i)
for i in 0...lb
    if arr[k-1]<brr[i]
        break
    end
end
if (lb-(i+1))>=m
    puts "YES"
else
    puts "NO"
end

la,lb = gets.split(" ").map(&:to_i)
k,m = gets.split(" ").map(&:to_i)

arr = gets.split(" ").map(&:to_i)
brr = gets.split(" ").map(&:to_i)
if k<=la && m<=lb && arr[k-1]<brr[0]
    puts "YES"
else
    puts "NO"
end

la,lb = gets.split(" ").map(&:to_i)
k,m = gets.split(" ").map(&:to_i)

arr = gets.split(" ").map(&:to_i)
brr = gets.split(" ").map(&:to_i)
for i in 0...lb
    if arr[k-1]<brr[i]
        break
    end
end
if (lb-i)>=m
    puts "YES"
else
    puts "NO"
end

na,nb = gets.split(' ').map(&:to_i)

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

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

if a1[k-1] < a2[0]
  puts "YES"
else
   puts "NO"
 end

na, nb = gets.split.map(&:to_i)
k, m = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
b = gets.split.map(&:to_i)
bb = b.find_index{|x| x > a[k - 1]}
puts b[(bb || 0)..-1].size >= m ? 'YES' : 'NO'

skip = gets.chomp.to_i
number_choose = gets.split.map(&:to_i)
arrayA = gets.split.map(&:to_i)
arrayB = gets.split.map(&:to_i)
choosenA = arrayA.last(number_choose[0])
minB = arrayB.first(number_choose[1]).min
puts choosenA.all?{|x| x < minB}  ? 'YES' : 'NO'

skip = gets.chomp
select_numbers = gets.split.map(&:to_i)
array1 = gets.split.map(&:to_i)
array2 = gets.split.map(&:to_i)
count = 0
array = array1 + array2
(array1.length...array.length).each do|index|
  if array[index] <= array[index-1]
    count = index
    break
  end
end

puts ( count > select_numbers.max) ? 'YES' : 'NO'

skip = gets.chomp
select_numbers = gets.split.map(&:to_i)
array1 = gets.split.map(&:to_i)
array2 = gets.split.map(&:to_i)
count = 0
array = array1 + array2
(1...array.length).each do|index|
  if array[index] <= array[index-1]
    count = index
    break
  end
end
puts ( count > select_numbers.max) ? 'YES' : 'NO'

skip = gets.chomp.to_i
number_choosens = gets.split.map(&:to_i)
arrayA = gets.split.map(&:to_i)
arrayB = gets.split.map(&:to_i)
possile_of_a = arrayA.select{|x| x < arrayB.min}
possile_of_b = arrayB.select{|x| x > arrayA.max}
puts (possile_of_a.size >= number_choosens[0] && possile_of_b.size >= number_choosens[1]) ? 'YES' : 'NO'

#!/usr/bin/ruby

def qselect(a, b, k, m)
  def qloc(a, b)
    l = a.length
    i = 0
    loop do
      break -1 if i < 0 or i >= l
      break i if a[i+1] and b > a[i] and b <= a[i+1]
      break i if not a[i+1] and b > a[i]
      i = b >= a[i] ? (l + i + 1) / 2 : (i - 1) / 2
    end
  end

  p = qloc(a, b[0])
  return false if p < 0
  k <= p + 1 && m <= b.length
end

def algo
  gets
  k, m = gets.split(' ').map { |e| e.to_i }
  a = gets.split(' ').map { |e| e.to_i }
  b = gets.split(' ').map { |e| e.to_i }
  puts qselect(a, b, k, m) ? "YES" : "NO"
end

algo

#!/usr/bin/ruby

# def qselect(a, b, k, m)
#   def qloc(a, b)
#     l = a.length
#     return -1 if b <= a[0]
#     return l if b > a[-1]
#     i = 0
#     loop do
#       break -1 if i < 0 or i >= l
#       break i if a[i+1] and b > a[i] and b <= a[i+1]
#       break i if not a[i+1] and b > a[i]
#       i = b > a[i] ? (l + i + 1) / 2 : i / 2
#     end
#   end
#   return false if k > a.length or m > b.length
#   p = qloc(a, b[-m])
#   k <= p + 1
# end

def algo
  gets
  k, m = gets.split(' ').map { |e| e.to_i }
  a = gets.split(' ').map { |e| e.to_i }
  b = gets.split(' ').map { |e| e.to_i }
  # puts qselect(a, b, k, m) ? "YES" : "NO"
  puts b[-m] > a[-k] ? "YES" : "NO"
end

algo

#!/usr/bin/ruby

def qselect(a, b, k, m)
  def qloc(a, b)
    l = a.length
    return -1 if b <= a[0]
    return l if b > a[-1]
    i = 0
    loop do
      break -1 if i < 0 or i >= l
      break i if a[i+1] and b > a[i] and b <= a[i+1]
      break i if not a[i+1] and b > a[i]
      i = b > a[i] ? (l + i + 1) / 2 : i / 2
    end
  end

  p = qloc(a, b[0])
  return false if p < 0
  k <= p + 1 && m <= b.length
end

def algo
  gets
  k, m = gets.split(' ').map { |e| e.to_i }
  a = gets.split(' ').map { |e| e.to_i }
  b = gets.split(' ').map { |e| e.to_i }
  puts qselect(a, b, k, m) ? "YES" : "NO"
end

algo

def checks(sizes, selections, array_1, array_2)
  selections = selections
  puts 1 < 2 ? 'YES' : 'NO'
end
checks(gets.chomp, gets.chomp, gets.chomp, gets.chomp)

def checks(sizes, selections, array_1, array_2)

  puts 'YES'
end
checks(gets.chomp, gets.chomp, gets.chomp, gets.chomp)


Michael is accused of violating the social distancing rules and creating a risk of spreading coronavirus. He is now sent to prison. Luckily, Michael knows exactly what the prison looks like from the inside, especially since it's very simple.The prison can be represented as a rectangle $$$a\times b$$$ which is divided into $$$ab$$$ cells, each representing a prison cell, common sides being the walls between cells, and sides on the perimeter being the walls leading to freedom. Before sentencing, Michael can ask his friends among the prison employees to make (very well hidden) holes in some of the walls (including walls between cells and the outermost walls). Michael wants to be able to get out of the prison after this, no matter which cell he is placed in. However, he also wants to break as few walls as possible.Your task is to find out the smallest number of walls to be broken so that there is a path to the outside from every cell after this.

The first line contains a single integer $$$t$$$ ($$$1\leq t\leq 100$$$) — the number of test cases. Each of the following $$$t$$$ lines contains two integers $$$a$$$ and $$$b$$$ ($$$1\leq a, b\leq 100$$$), representing a corresponding test case.

For each test case print the single integer on a separate line — the answer to the problem.

NoteSome possible escape plans for the example test cases are shown below. Broken walls are shown in gray, not broken walls are shown in black.

gets.to_i.times{
    a,b=gets.split
    puts a.to_i*b.to_i
}

t = gets.chomp.to_i
t.times do
	a,b = gets.split()
	p a.to_i*b.to_i
end


Alexandra has an even-length array $$$a$$$, consisting of $$$0$$$s and $$$1$$$s. The elements of the array are enumerated from $$$1$$$ to $$$n$$$. She wants to remove at most $$$\frac{n}{2}$$$ elements (where $$$n$$$ — length of array) in the way that alternating sum of the array will be equal $$$0$$$ (i.e. $$$a_1 - a_2 + a_3 - a_4 + \dotsc = 0$$$). In other words, Alexandra wants sum of all elements at the odd positions and sum of all elements at the even positions to become equal. The elements that you remove don't have to be consecutive.For example, if she has $$$a = [1, 0, 1, 0, 0, 0]$$$ and she removes $$$2$$$nd and $$$4$$$th elements, $$$a$$$ will become equal $$$[1, 1, 0, 0]$$$ and its alternating sum is $$$1 - 1 + 0 - 0 = 0$$$.Help her!

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^3$$$, $$$n$$$ is even)  — length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$)  — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^3$$$.

For each test case, firstly, print $$$k$$$ ($$$\frac{n}{2} \leq k \leq n$$$) — number of elements that will remain after removing in the order they appear in $$$a$$$. Then, print this $$$k$$$ numbers. Note that you should print the numbers themselves, not their indices. We can show that an answer always exists. If there are several answers, you can output any of them.

NoteIn the first and second cases, alternating sum of the array, obviously, equals $$$0$$$.In the third case, alternating sum of the array equals $$$1 - 1 = 0$$$.In the fourth case, alternating sum already equals $$$1 - 1 + 0 - 0 = 0$$$, so we don't have to remove anything.

t = gets.chomp.to_i
t.times do
    n = gets.chomp.to_i
    a = gets.chomp.split(" ")
    number_zero = a.count("0")
    number_ichi = n - number_zero
    if number_zero >= number_ichi
        a.delete("1")
        puts a.size
        puts a.join(" ")
    else
        a.delete("0")
        ookisa = a.size
        if ookisa % 2 == 0
            puts a.size
            puts a.join(" ")
        else
            a.pop
            puts a.size
            puts a.join(" ")
        end
    end
end

T = gets.to_i

T.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  rui_e = [0]
  rui_o = [0]

  a.each_with_index do |x, i|
    if i.even?
      rui_e << rui_e.last + x
      rui_o << rui_o.last
    else
      rui_e << rui_e.last
      rui_o << rui_o.last + x
    end
  end

  idx = -1

  n.times do |i|
    v1 = (rui_e[i] - rui_e[0]) + (rui_o[n] - rui_o[i + 1])
    v2 = (rui_o[i] - rui_o[0]) + (rui_e[n] - rui_e[i + 1])

    if v1 == v2
      idx = i
      break
    end
  end

  if idx != -1
    a.delete_at(idx)
  end

  puts a.size
  puts a.join(' ')
end

T = gets.to_i

T.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  s = a.sum
  t = s / 2
  ans = []
  sum = [0, 0]

  if n <= 2
    puts 1
    puts 0
    next
  end

  until a.empty?
    x = a.shift

    if ans.size.even?
      next if x + sum[0] > t

      sum[0] += x
      ans << x
    else
      next if x + sum[1] > t

      sum[1] += x
      ans << x
    end
  end

  puts ans.size
  puts ans.join(' ')
end

t = gets.chomp.to_i
t.times do
    n = gets.chomp.to_i
    a = gets.chomp.split(" ")
    number_zero = a.count("0")
    number_ichi = n - number_zero
    if number_zero >= number_ichi
        a.delete("1")
        puts a.join(" ")
    else
        a.delete("0")
        ookisa = a.size
        if ookisa % 2 == 0
            puts a.join(" ")
        else
            a.pop
            puts a.join(" ")
        end
    end
end

T = gets.to_i

T.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  s = a.sum
  t = s / 2
  ans = []
  sum = [0, 0]

  until a.empty?
    x = a.shift

    if ans.size.even?
      next if x + sum[0] > t

      sum[0] += x
      ans << x
    else
      next if x + sum[1] > t

      sum[1] += x
      ans << x
    end
  end

  puts ans.size
  puts ans.join(' ')
end

T = gets.to_i

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

  counter = a.tally
  counter.default = 0

  if counter[0] >= 1
    puts 1
    puts 0
  elsif counter[1] >= 2
    puts 2
    puts "1 1"
  end
end


You have an array $$$a$$$ of length $$$n$$$. For every positive integer $$$x$$$ you are going to perform the following operation during the $$$x$$$-th second:  Select some distinct indices $$$i_{1}, i_{2}, \ldots, i_{k}$$$ which are between $$$1$$$ and $$$n$$$ inclusive, and add $$$2^{x-1}$$$ to each corresponding position of $$$a$$$. Formally, $$$a_{i_{j}} := a_{i_{j}} + 2^{x-1}$$$ for $$$j = 1, 2, \ldots, k$$$. Note that you are allowed to not select any indices at all. You have to make $$$a$$$ nondecreasing as fast as possible. Find the smallest number $$$T$$$ such that you can make the array nondecreasing after at most $$$T$$$ seconds.Array $$$a$$$ is nondecreasing if and only if $$$a_{1} \le a_{2} \le \ldots \le a_{n}$$$.You have to answer $$$t$$$ independent test cases.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^{4}$$$) — the number of test cases. The first line of each test case contains single integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the length of array $$$a$$$. It is guaranteed that the sum of values of $$$n$$$ over all test cases in the input does not exceed $$$10^{5}$$$. The second line of each test case contains $$$n$$$ integers $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$-10^{9} \le a_{i} \le 10^{9}$$$).

For each test case, print the minimum number of seconds in which you can make $$$a$$$ nondecreasing.

NoteIn the first test case, if you select indices $$$3, 4$$$ at the $$$1$$$-st second and $$$4$$$ at the $$$2$$$-nd second, then $$$a$$$ will become $$$[1, 7, 7, 8]$$$. There are some other possible ways to make $$$a$$$ nondecreasing in $$$2$$$ seconds, but you can't do it faster.In the second test case, $$$a$$$ is already nondecreasing, so answer is $$$0$$$.In the third test case, if you do nothing at first $$$2$$$ seconds and select index $$$2$$$ at the $$$3$$$-rd second, $$$a$$$ will become $$$[0, 0]$$$.

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  x_max = 0
  c = a[0]
  a.each do |v|
    if c > v
      d = c - v
      x = 0
      while d > 0 do
        d /= 2
        x += 1
      end
      x_max = x if x_max < x
    else
      c = v
    end
  end
  puts x_max
end


Consider a tunnel on a one-way road. During a particular day, $$$n$$$ cars numbered from $$$1$$$ to $$$n$$$ entered and exited the tunnel exactly once. All the cars passed through the tunnel at constant speeds.A traffic enforcement camera is mounted at the tunnel entrance. Another traffic enforcement camera is mounted at the tunnel exit. Perfectly balanced.Thanks to the cameras, the order in which the cars entered and exited the tunnel is known. No two cars entered or exited at the same time.Traffic regulations prohibit overtaking inside the tunnel. If car $$$i$$$ overtakes any other car $$$j$$$ inside the tunnel, car $$$i$$$ must be fined. However, each car can be fined at most once.Formally, let's say that car $$$i$$$ definitely overtook car $$$j$$$ if car $$$i$$$ entered the tunnel later than car $$$j$$$ and exited the tunnel earlier than car $$$j$$$. Then, car $$$i$$$ must be fined if and only if it definitely overtook at least one other car.Find the number of cars that must be fined.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$), denoting the number of cars. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$), denoting the ids of cars in order of entering the tunnel. All $$$a_i$$$ are pairwise distinct. The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$), denoting the ids of cars in order of exiting the tunnel. All $$$b_i$$$ are pairwise distinct.

NoteThe first example is depicted below:Car $$$2$$$ definitely overtook car $$$5$$$, while car $$$4$$$ definitely overtook cars $$$1$$$, $$$2$$$, $$$3$$$ and $$$5$$$. Cars $$$2$$$ and $$$4$$$ must be fined.In the second example car $$$5$$$ was definitely overtaken by all other cars.In the third example no car must be fined.

n = gets.to_i
a = gets.split.map(&:to_i)
b = gets.split.map(&:to_i)
out = [false]*(n+1)

ans = 0
j = 0
n.times do |i|
  if !out[a[i]]
    while b[j] != a[i]
      out[b[j]] = true
      j += 1
      ans += 1
    end
    out[b[j]] = true
    j += 1
  end
end
p ans

def calcs(x,y,ax,ay,bx,by) ((ax-x)*(by-y)-(bx-x)*(ay-y))/2.0 end
def inpf() a=gets.chomp.split(" ").map(&:to_f)end
def inps() a=gets.chomp.split(" ")end
def copy(a) Marshal.load(Marshal.dump(a)) end
def kaizyo(n)(n < 2)? 1 : (2..n).inject(:*) end
def scount(a) b=na(a.max+1);a.each{|n|b[n]+=1};return b end
def na(n=0,d=0) Array.new(n,d)end
def na2(n=0,m=0,d=0) Array.new(n){Array.new(m,d)}end
def na3(n=0,m=0,l=0,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end
def bit(n) n.to_s(2).split("").map(&:to_i) end
def inp() a=gets.chomp.split(" ").map(&:to_i)end

n = inp[0]
a = inp
b = inp
table = na(n)
encoded = na(n)
n.times do |i|
  encoded[a[i]-1] = i
end

pl = 0
ans = 0
i = 0
while i < n
  if(table[i] == 1)
    pl -= 1
    i += 1
    next
  end
  if(a[i] != b[i+pl])
    ans += 1
    table[encoded[b[i+pl]-1]] = 1
    pl +=1
  else
    i += 1
  end
end
p ans


Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do:   If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$;  if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$;  if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.

For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.

NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.

q = gets.chomp.to_i

for ii in 1..q
  (k, n, a, b) = gets.chomp.split(" ").map {|aaa| aaa.to_i}
  _min = n*b
  k -= 1
  d = a-b
  if _min > k
    print -1
  else
    _max = (k -_min)/d
    print _max > n ? n : _max
  end
  print "\n"
end

q = gets.to_i
(1..q).each do
  res = 0
  read = gets.split(" ").map{|c| c.to_i}
  k = read[0]
  n = read[1]
  a = read[2]
  b = read[3]
  if n * b >= k
    res = -1
  else
    l = 0
    r = n
    while l < r
      m = (l + r + 1)/2
      if m * a + (n - m) * b < k
        l = m
      else
        r = m - 1
      end
    end
    res = l
  end
  puts res
end

MOD=10**9+7
cnt=0; sum=0; prev=nil; can=true; h=Hash.new(0)
def gs() gets.chomp end
def gi() gets.to_i end
def gsmi() gets.chomp.split.map(&:to_i) end

def desc(ar) ar.sort!{|x,y|y<=>x} end
def min(a,b) a<=b ? a : b end
def max(a,b) a>=b ? a : b end
def sum(ar) ar.inject(:+) end

def C(a,b) b==0||a==b ? 1 : (b=a-b if a/2<b;(a-b+1..a).inject(:*)/(1..b).inject(:*)) end

def puts_yesno(can) puts(can ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def debug(k,v) puts "#{k}:#{v}" end
########### ( ˘ω˘ )ｽﾔｧ… ###########
q=gi
q.times do
  bat,turn,a,b=gsmi

  if bat <= turn*b
    puts -1
    next
  end

  b_bat = bat - turn*b
  puts [(b_bat-1)/(a-b),turn,((bat-a).to_f/a).ceil].min
end

MOD=10**9+7
cnt=0; sum=0; prev=nil; can=true; h=Hash.new(0)
def gs() gets.chomp end
def gi() gets.to_i end
def gsmi() gets.chomp.split.map(&:to_i) end

def desc(ar) ar.sort!{|x,y|y<=>x} end
def min(a,b) a<=b ? a : b end
def max(a,b) a>=b ? a : b end
def sum(ar) ar.inject(:+) end

def C(a,b) b==0||a==b ? 1 : (b=a-b if a/2<b;(a-b+1..a).inject(:*)/(1..b).inject(:*)) end

def puts_yesno(can) puts(can ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def debug(k,v) puts "#{k}:#{v}" end
########### ( ˘ω˘ )ｽﾔｧ… ###########
q=gi
q.times do
  bat,turn,a,b=gsmi

  if bat <= turn*b
    puts -1
    next
  end

  b_bat = bat - turn*b
  puts [b_bat/(a-b),turn,((bat-a).to_f/a).ceil].min
end


You are given $$$n$$$ strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings.String $$$a$$$ is a substring of string $$$b$$$ if it is possible to choose several consecutive letters in $$$b$$$ in such a way that they form $$$a$$$. For example, string "for" is contained as a substring in strings "codeforces", "for" and "therefore", but is not contained as a substring in strings "four", "fofo" and "rof".

The first line contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of strings. The next $$$n$$$ lines contain the given strings. The number of letters in each string is from $$$1$$$ to $$$100$$$, inclusive. Each string consists of lowercase English letters. Some strings might be equal.

If it is impossible to reorder $$$n$$$ given strings in required order, print "NO" (without quotes). Otherwise print "YES" (without quotes) and $$$n$$$ given strings in required order.

NoteIn the second example you cannot reorder the strings because the string "abab" is not a substring of the string "abacaba".

n = gets.to_i
s = (1..n).map { gets.chomp }.sort_by(&:size)
if s.each_cons(2).all? { |s, t| (0...t.size).any? { |i| s == t[i, s.size] } }
	puts 'YES', s.join("\n")
else
	puts 'NO'
end

n = gets.to_i
ar = []
n.times {ar << gets.chomp}
ar.sort!{|a,b| a.size <=> b.size}
n.times do |i|
  next if i == 0
  s = ar[i]
  s0 = ar[i-1]
  if !s.include? s0
    puts "NO"
    exit 0
  end
end
puts "YES"
puts ar

n = gets.to_i
a = []
for i in 0..n-1
      x = gets.chomp
      a.push(x)
      end
y = a.sort_by(&:length)
v = 1
for i in 0..n-2
      if y[i+1].include?y[i] or y[i+1] == y[i]
       v += 1
     end
  end
if v != a.length
   puts "NO"
else
   puts "YES"
   for i in 0..a.length-1
      puts "#{y[i]}"
      end
  end

#!/usr/bin/env ruby

n=gets.chomp.to_i
str=[]
n.times{str.push(gets.chomp)}

str.sort!{|l, r| l.size<=>r.size}

(n-1).downto 1 do |i|
  s, t=str[i-1], str[i]
  if t.index(s).nil?
    puts 'NO'
    exit 0
  end
end

puts 'YES'
puts str.join("\n")


Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.

The first line contains two space-separated integers: n and p (1 ≤ n ≤ 1000; 1 ≤ p ≤ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).

If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).

NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 > ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.

def fill_string(string, i, max_ord)
  (i...string.size).each do |i|
    ('a'.ord..max_ord).each { |j|
      if (i-1<0 || j.chr != string[i-1]) && (i-2<0 || j.chr != string[i-2])
        string[i] = j.chr
        break
      end
    }
  end
  string
end

p = gets.split[1].to_i + 'a'.ord - 1
string = gets[0..-2]
no = true
(0...string.size).reverse_each do |i|
  (string[i].ord+1..p).each do |j|
    if (i-1<0 || j.chr != string[i-1]) && (i-2<0 || j.chr != string[i-2])
      string[i] = j.chr
      puts fill_string string, i+1, p
      no = false
      break
    end
  end
  break unless no
end

puts "NO" if no

n, p = gets.split(/\s+/).map(&:to_i)
s = gets.strip

def get_next(s, n, p)
  if n == 1
    if s[0].ord == p.ord
      nil
    else
      s[0].succ
    end
  else
    q = s[-1] == 'z' ? '{' : s[-1].succ
    x = s[0...-1]
    begin
      while q.ord <= p.ord && (q == x[-1] || q == x[-2])
        q = q == 'z' ? '{' : q.succ
      end

      if q.ord <= p.ord
        return "#{x}#{q}"
      else
        x = get_next(x, n-1, p)
        q = 'a'
      end
    end while x

    nil
  end
end

p = ('a'.ord + p.ord-1).chr

if (s = get_next(s, n, p))
  puts s
else
  puts "NO"
end


You are given an array a with n elements. Each element of a is either 0 or 1.Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).

The first line contains two integers n and k (1 ≤ n ≤ 3·105, 0 ≤ k ≤ n) — the number of elements in a and the parameter k. The second line contains n integers ai (0 ≤ ai ≤ 1) — the elements of a.

On the first line print a non-negative integer z — the maximal value of f(a) after no more than k changes of zeroes to ones. On the second line print n integers aj — the elements of the array a after the changes. If there are multiple answers, you can print any one of them.

a=gets.chomp.split(" ").map{|i| i.to_i}
b=gets.chomp.split(" ")

maxind=0
z=0
max=0
p=0
sq=0

if a[1]>0
0.upto(a[0]-1) do |i|

	if i>0
	sq=sq-1
	if b[i-1]=="0"
	z=z-1
	else
	z=z
	end
	end

  loop do
    break if p>=a[0]
    if b[p]=="0"
        z+=1
    end
	break if z>a[1]
        sq+=1
		p+=1
    end
     z-=1
    if sq>max
        max=sq
        maxind=i
    end

	break if p==a[0]
end
   k=0
loop do
	break if maxind==a[0]
	break if k==a[1]
    if b[maxind]=="0"
        b[maxind]="1"
        k+=1
    end
	 maxind +=1
end
puts "#{max}"
puts b.join(" ")

else

sq=0
b.each do |i|
if i== "0"
if sq>max
max=sq
end
sq=0
else
sq+=1
end
end
if sq>max
max=sq
end
puts "#{max}"
puts b.join(" ")

end

buf=gets.split(' ')
n,k=buf[0].to_i, buf[1].to_i
t=k
a=gets.split(' ')
r=ma=st=0
for l in 0..n-1
	k+=1 if l>0 && a[l-1]=='0'
	while r<n && (a[r]=='1' || k>0)
		k-=1 if a[r]=='0'
		r+=1
	end
	ma,st=r-l,l if r-l>ma
end
puts ma
while st<n && t>=0
	break if t<1 && a[st]==?0
	t-=1 if a[st]==?0
	a[st]=?1
	st+=1
end
puts a*" "

a=gets.chomp.split(" ").map{|i| i.to_i}
b=gets.chomp.split(" ")
maxind=0
max=0
0.upto(a[0]-2) do |i|
	p=0
    p=i
    sq=0
    z=0
    loop do
    if b[p]=="0"
        z+=1
    end
       p+=1
	break if p==a[0]
    break if z>a[1]
        sq+=1
    end
    if sq>max
        max=sq
        maxind=i
    end
end

k=0
loop do
    if b[maxind]=="0"
        b[maxind]="1"
        k+=1
    end
	 maxind +=1

    break if k==a[1]
end
puts "#{max}"
puts b.join(" ")


Ujan decided to make a new wooden roof for the house. He has $$$n$$$ rectangular planks numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th plank has size $$$a_i \times 1$$$ (that is, the width is $$$1$$$ and the height is $$$a_i$$$).Now, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some order. Then he will glue together all of these planks by their vertical sides. Finally, he will cut out a square from the resulting shape in such a way that the sides of the square are horizontal and vertical.For example, if Ujan had planks with lengths $$$4$$$, $$$3$$$, $$$1$$$, $$$4$$$ and $$$5$$$, he could choose planks with lengths $$$4$$$, $$$3$$$ and $$$5$$$. Then he can cut out a $$$3 \times 3$$$ square, which is the maximum possible. Note that this is not the only way he can obtain a $$$3 \times 3$$$ square.  What is the maximum side length of the square Ujan can get?

The first line of input contains a single integer $$$k$$$ ($$$1 \leq k \leq 10$$$), the number of test cases in the input. For each test case, the first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 1\,000$$$), the number of planks Ujan has in store. The next line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$), the lengths of the planks.

For each of the test cases, output a single integer, the maximum possible side length of the square.

NoteThe first sample corresponds to the example in the statement.In the second sample, gluing all $$$4$$$ planks will result in a $$$4 \times 4$$$ square.In the third sample, the maximum possible square is $$$1 \times 1$$$ and can be taken simply as any of the planks.

k = gets.to_i
k.times do
  n = gets.to_i
  as = gets.split.map(&:to_i).sort.reverse
  ans = 0
  as.each_with_index do |a, i|
    if a > ans
      ans += 1
    end
  end
  puts ans
end

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

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

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

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

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

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

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

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

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

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

q = inp[0]
q.times do
  n = inp[0]
  t = inp
  t.sort!.reverse!
  ans = 0
  n.times do |i|
    ans = [ans,[t[i],(i+1)].min].max
  end
  p ans
end

g = gets.chomp.to_i
g.times{
n = gets.to_i
max = 0
doski = gets.split(" ").map{|x|x.to_i}
jj = (1...1001).to_a
jj.map{|w|
q=0
doski.map{|e| if e >= w then q+=1 end}
if q >= w and max < w then max =  w end
}
puts max
}

g = gets.chomp.to_i
g.times{
n = gets.to_i
max = 0
doski = gets.split(" ").map{|x|x.to_i}
jj = (1...1000).to_a
jj.map{|w|
q=0
doski.map{|e| if e >= w then q+=1 end}
if q >= w and max < w then max =  w end
}
puts max
}


Our old friend Alexey has finally entered the University of City N — the Berland capital. Alexey expected his father to get him a place to live in but his father said it was high time for Alexey to practice some financial independence. So, Alexey is living in a dorm. The dorm has exactly one straight dryer — a 100 centimeter long rope to hang clothes on. The dryer has got a coordinate system installed: the leftmost end of the dryer has coordinate 0, and the opposite end has coordinate 100. Overall, the university has n students. Dean's office allows i-th student to use the segment (li, ri) of the dryer. However, the dean's office actions are contradictory and now one part of the dryer can belong to multiple students!Alexey don't like when someone touch his clothes. That's why he want make it impossible to someone clothes touch his ones. So Alexey wonders: what is the total length of the parts of the dryer that he may use in a such way that clothes of the others (n - 1) students aren't drying there. Help him! Note that Alexey, as the most respected student, has number 1.

The first line contains a positive integer n (1 ≤ n ≤ 100). The (i + 1)-th line contains integers li and ri (0 ≤ li < ri ≤ 100) — the endpoints of the corresponding segment for the i-th student.

On a single line print a single number k, equal to the sum of lengths of the parts of the dryer which are inside Alexey's segment and are outside all other segments.

NoteNote that it's not important are clothes drying on the touching segments (e.g. (0, 1) and (1, 2)) considered to be touching or not because you need to find the length of segments.In the first test sample Alexey may use the only segment (0, 1). In such case his clothes will not touch clothes on the segments (1, 6) and (2, 8). The length of segment (0, 1) is 1.In the second test sample Alexey may dry his clothes on segments (0, 1) and (5, 7). Overall length of these segments is 3.

ans,a=0,Array.new(100,0)
gets.to_i.times do |i|
	l,r=gets.chomp.split.map(&:to_i)
	for j in l...r
		a[j]=i==0
	end
end
puts a.count(true)

n = gets.to_i
alex_l,alex_r = gets.split(" ").map(&:to_i)

# (n-1).times do
# 	l,r = gets.split(" ").map(&:to_i)
# 	x,y = l+1,r-1
# 	# x,y = y,x if x > y
# 	if l + 1 == r
# 		# puts "here"
# 		alex -= [l]
# 	else
# 		alex -= (x..y).to_a
# 	end
# end
# length = 0
# (1..alex.length-1).each do |i|
# 	if (alex[i-1] + 1 == alex[i]) || (alex[i+1] && alex[i]+1 != alex[i+1])
# 		puts alex[i]
# 		length += 1
# 	end
# end
# puts "#{alex}"
# puts length
used = Array.new(100,true)

(n-1).times do
	l,r = gets.split(" ").map(&:to_i)
	(l..r-1).each do |i|
		used[i] = false
	end
end
puts "#{used[alex_l..alex_r-1].count(true)}"

class Array
	def f x
		self[0] - 1 < x && x < self[1]
	end
end

n = gets.to_i
l, r = gets.split.map(&:to_i)
seg = []
(n-1).times{seg<<gets.split.map(&:to_i)}
tot = 0
l.upto(r-1){|i| tot+=1 if !seg.any?{|s|s.f(i)}}
p tot

n = gets.to_i
l,r = gets.split(" ").map(&:to_i)
alex = (l..r).to_a
(n-1).times do
	l,r = gets.split(" ").map(&:to_i)
	alex -= (l+1..r-1).to_a
end
length = 0
(1..alex.length-1).each do |i|
	length += 1 if alex[i-1] + 1 == alex[i]
end

puts length

n = gets.to_i
l,r = gets.split(" ").map(&:to_i)
alex = (l..r).to_a
(n-1).times do
	l,r = gets.split(" ").map(&:to_i)
	x,y = l+1,r-1
	# x,y = y,x if x > y
	if l + 1 == r
		# puts "here"
		alex -= [l]
	else
		alex -= (x..y).to_a
	end
end
length = 0
(1..alex.length-1).each do |i|
	length += 1 if alex[i-1] + 1 == alex[i]
end
# puts "#{alex}"
puts length


You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems:  the Power Gem of purple color,  the Time Gem of green color,  the Space Gem of blue color,  the Soul Gem of orange color,  the Reality Gem of red color,  the Mind Gem of yellow color. Using colors of Gems you saw in the Gauntlet determine the names of absent Gems.

In the first line of input there is one integer $$$n$$$ ($$$0 \le n \le 6$$$) — the number of Gems in Infinity Gauntlet. In next $$$n$$$ lines there are colors of Gems you saw. Words used for colors are: purple, green, blue, orange, red, yellow. It is guaranteed that all the colors are distinct. All colors are given in lowercase English letters.

In the first line output one integer $$$m$$$ ($$$0 \le m \le 6$$$) — the number of absent Gems. Then in $$$m$$$ lines print the names of absent Gems, each on its own line. Words used for names are: Power, Time, Space, Soul, Reality, Mind. Names can be printed in any order. Keep the first letter uppercase, others lowercase.

NoteIn the first sample Thanos already has Reality, Power, Mind and Soul Gems, so he needs two more: Time and Space.In the second sample Thanos doesn't have any Gems, so he needs all six.

g = Hash.new
g['red'] = "Reality"
g['purple'] = "Power"
g['orange'] = "Soul"
g['yellow'] = "Mind"
g['blue'] = "Space"
g['green'] = "Time"

number = gets.to_i
number.times{
	s = gets.chomp
	g.delete(s)
}

puts g.length
g.each{
	|k, v|
	puts v
}

N = gets.to_i
hash = {
    'purple' => 'Power',
    'green' => 'Time',
    'blue' => 'Space',
    'orange' => 'Soul',
    'red' => 'Reality',
    'yellow' => 'Mind'
}

N.times do
    str = gets.chomp
    hash.delete(str)
end
puts hash.length, hash.values

n = gets.to_i
as = []

gems = Hash.new
gems['purple'] = 'Power'
gems['green'] = 'Time'
gems['blue'] = 'Space'
gems['orange'] = 'Soul'
gems['red'] = 'Reality'
gems['yellow'] = 'Mind'

n.times do
  as << gets.chomp
end

gems.reject! { |k, v| as.include?(k) }
puts gems.size
puts gems.values

s = %w(the Power Gem of purple color,
the Time Gem of green color,
the Space Gem of blue color,
the Soul Gem of orange color,
the Reality Gem of red color,
the Mind Gem of yellow color.)

t = (0...6).map { |i| [s[6 * i + 4], s[6 * i + 1]] }

n = gets.to_i
cols = (0...n).map { gets.strip }
cnt = {}
cols.each do |c|
  cnt[c] = 1
end
a = []
(0...6).each do |i|
  a << t[i][1] if cnt[t[i][0]].nil?
end
p a.size
puts a.join ?\n

shokti = {"purple"=>"Power", "green"=> "Time" , "blue"=>"Space" ,"orange"=> "Soul" , "red"=> "Reality" , "yellow"=> "Mind"}
shoktiray = ["purple","green","blue","orange","red","yellow"]

s = gets.to_i
a = []

for i in 0..s-1
    b = gets.chomp
    a.push(b)
end
notun = shoktiray - a
puts notun.length

notun.each{|k|
   puts shokti[k]
}

gems = {}
gems['purple'] = 'Power'
gems['green'] = 'Time'
gems['blue'] = 'Space'
gems['orange'] = 'Soul'
gems['red'] = 'Reality'
gems['yellow'] = 'Mind'

len = gets.to_i
0.upto(len-1) do
  word = gets.chomp
  gems.delete(word)
end

puts gems.values.count
gems.values.each{|val|
  if val != nil
    puts val
  end
}

n = gets.to_i
c = []
n.times{c << gets.strip}
h = {
  'purple' => 'Power',
  'green'  => 'Time',
  'blue'   => 'Space',
  'orange' => 'Soul',
  'red'    => 'Reality',
  'yellow' => 'Mind'
}
ans = []
h.each{|k, v| ans << v unless c.any?{|x| x == k}}
p ans.size
ans.each{|x| puts x}

#purple, green, blue,  orange, red,     yellow
#Power , Time,  Space, Soul,   Reality, Mind

arr = ["Power" , "Time",  "Space", "Soul",   "Reality", "Mind"]

a = gets.to_i

size = 6

for i in 0..a-1
	tmp = gets.chomp

	if(tmp == "purple")
		arr[0] = ""
		size -=1
	elsif (tmp == "green")
		arr[1] = ""
		size -=1
	elsif (tmp == "blue")
		arr[2] = ""
		size -=1
	elsif (tmp == "orange")
		arr[3] = ""
		size -=1
	elsif (tmp == "red")
		arr[4] = ""
		size -=1
	elsif (tmp == "yellow")
		arr[5] = ""
		size -=1

	end
end

puts (size)

for i in 0..6
	if(arr[i] == "")
		next
	else
		puts arr[i]
	end
end

h={}
h['purple']='Power'
h['green']='Time'
h['blue']='Space'
h['orange']='Soul'
h['red']='Reality'
h['yellow']='Mind'

n=gets.chomp.to_i
n.times do
  s=gets.chomp
  h.delete(s)
end

puts h.size
h.values.each do |s|
  puts s
end

gems = {}
gems['purple'] = 'Power'
gems['green'] = 'Time'
gems['blue'] = 'Space'
gems['orange'] = 'Soul'
gems['red'] = 'Reality'
gems['yellow'] = 'Mind'

len = gets.to_i
0.upto(len-1) do
  word = gets.chomp
  gems[word] = nil
end

puts gems.values.count
gems.values.each{|val|
  if val != nil
    puts val
  end
}
puts ''


Consider a simplified penalty phase at the end of a football match.A penalty phase consists of at most $$$10$$$ kicks, the first team takes the first kick, the second team takes the second kick, then the first team takes the third kick, and so on. The team that scores more goals wins; if both teams score the same number of goals, the game results in a tie (note that it goes against the usual football rules). The penalty phase is stopped if one team has scored more goals than the other team could reach with all of its remaining kicks. For example, if after the $$$7$$$-th kick the first team has scored $$$1$$$ goal, and the second team has scored $$$3$$$ goals, the penalty phase ends — the first team cannot reach $$$3$$$ goals.You know which player will be taking each kick, so you have your predictions for each of the $$$10$$$ kicks. These predictions are represented by a string $$$s$$$ consisting of $$$10$$$ characters. Each character can either be 1, 0, or ?. This string represents your predictions in the following way:  if $$$s_i$$$ is 1, then the $$$i$$$-th kick will definitely score a goal;  if $$$s_i$$$ is 0, then the $$$i$$$-th kick definitely won't score a goal;  if $$$s_i$$$ is ?, then the $$$i$$$-th kick could go either way. Based on your predictions, you have to calculate the minimum possible number of kicks there can be in the penalty phase (that means, the earliest moment when the penalty phase is stopped, considering all possible ways it could go). Note that the referee doesn't take into account any predictions when deciding to stop the penalty phase — you may know that some kick will/won't be scored, but the referee doesn't.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1\,000$$$) — the number of test cases. Each test case is represented by one line containing the string $$$s$$$, consisting of exactly $$$10$$$ characters. Each character is either 1, 0, or ?.

For each test case, print one integer — the minimum possible number of kicks in the penalty phase.

NoteConsider the example test:In the first test case, consider the situation when the $$$1$$$-st, $$$5$$$-th and $$$7$$$-th kicks score goals, and kicks $$$2$$$, $$$3$$$, $$$4$$$ and $$$6$$$ are unsuccessful. Then the current number of goals for the first team is $$$3$$$, for the second team is $$$0$$$, and the referee sees that the second team can score at most $$$2$$$ goals in the remaining kicks. So the penalty phase can be stopped after the $$$7$$$-th kick.In the second test case, the penalty phase won't be stopped until all $$$10$$$ kicks are finished.In the third test case, if the first team doesn't score any of its three first kicks and the second team scores all of its three first kicks, then after the $$$6$$$-th kick, the first team has scored $$$0$$$ goals and the second team has scored $$$3$$$ goals, and the referee sees that the first team can score at most $$$2$$$ goals in the remaining kicks. So, the penalty phase can be stopped after the $$$6$$$-th kick.In the fourth test case, even though you can predict the whole penalty phase, the referee understands that the phase should be ended only after the $$$9$$$-th kick.

def calculate(string_result)
  team_a_best_score = 0
  team_a_worst_score = 0
  team_a_kick_count = 0
  team_b_best_score = 0
  team_b_worst_score = 0
  team_b_kick_count = 0

  (0..(string_result.length - 2)).step(2).each do |index|
    team_a_kick_count += 1
    case string_result[index]
    when '1'
      team_a_best_score += 1
      team_a_worst_score += 1
    when '?'
      team_a_best_score += 1
    end
    return team_a_kick_count + team_b_kick_count if team_a_best_score > team_b_worst_score + (5 - team_b_kick_count) ||
        team_a_worst_score + (5 - team_a_kick_count) < team_b_best_score

    team_b_kick_count += 1
    case string_result[index + 1]
    when '1'
      team_b_best_score += 1
      team_b_worst_score += 1
    when '?'
      team_b_best_score += 1
    end

    return team_a_kick_count + team_b_kick_count if (team_a_best_score > team_b_worst_score + (5 - team_b_kick_count)) ||
        team_a_worst_score + (5 - team_a_kick_count) < team_b_best_score
  end

  return 10
end

# ['1?0???1001', '1111111111', '??????????', '0100000000'].each do |str|
#   puts calculate(str)
# end

t = gets.to_i
t.times do
  puts calculate(gets.to_s)
end


It is known that there are k fish species in the polar ocean, numbered from 1 to k. They are sorted by non-decreasing order of their weight, which is a positive number. Let the weight of the i-th type of fish be wi, then 0 < w1 ≤ w2 ≤ ... ≤ wk holds.Polar bears Alice and Bob each have caught some fish, and they are guessing who has the larger sum of weight of the fish he/she's caught. Given the type of the fish they've caught, determine whether it is possible that the fish caught by Alice has a strictly larger total weight than Bob's. In other words, does there exist a sequence of weights wi (not necessary integers), such that the fish caught by Alice has a strictly larger total weight?

The first line contains three integers n, m, k (1 ≤ n, m ≤ 105, 1 ≤ k ≤ 109) — the number of fish caught by Alice and Bob respectively, and the number of fish species. The second line contains n integers each from 1 to k, the list of fish type caught by Alice. The third line contains m integers each from 1 to k, the list of fish type caught by Bob. Note that one may have caught more than one fish for a same species.

Output "YES" (without quotes) if it is possible, and "NO" (without quotes) otherwise.

NoteIn the first sample, if w1 = 1, w2 = 2, w3 = 2.5,  then Alice has a total of 2 + 2 + 2 = 6 weight units, while Bob only has 1 + 1 + 2.5 = 4.5.In the second sample, the fish that Alice caught is a subset of Bob's. Therefore, the total weight of Bob’s fish is always not less than the total weight of Alice’s fish.

gets
a=[0]+gets.split.map(&:to_i).sort
b=[0]+gets.split.map(&:to_i).sort
(1..[a.size,b.size].min).each{|i|exit !(puts"YES")if a[-i]>b[-i]}
puts"NO"

a,b,c = gets.chomp.split(" ").map{|v| v.to_i}
khanh = gets.chomp.split(" ").map{|v| v.to_i}
huy= gets.chomp.split(" ").map{|a| a.to_i}

khanh = khanh.sort.reverse!
huy = huy.sort.reverse!

result = "NO"
if khanh.length > huy.length
  result = "YES"
else
  stop = false
  i = 0
  while i < khanh.length && !stop do
    if khanh[i] > huy[i]
      result = "YES"
      stop = true
    elsif
      i = i + 1
    end
 end
end

puts result

_,a,b=$<.map{|s|s.split.map(&:to_i).sort.reverse}
puts a.zip(b).any?{|c,d|d.nil?||c>d}?:YES: :NO

n,m=gets.split.map(&:to_i)
a=gets.split.map(&:to_i).sort!
b=gets.split.map(&:to_i).sort!
p=0
n.times{ |i|
	while p<m&&b[p]<a[i]
		p+=1
	end
	if n-i>m-p
		puts 'YES'
		exit
	end
}
puts 'NO'

_,a,b=$<.map{|s|s.split.map(&:to_i).sort.reverse}
puts a.size>b.size||a.zip(b).any?{|c,d|c>d}?:YES: :NO

_,a,b=(1..3).map{gets.split.map(&:to_i).sort.reverse}
puts a.size>b.size||a.zip(b).any?{|c,d|c>d}?:YES: :NO

gets
a=gets.split.map(&:to_i).sort
b=gets.split.map(&:to_i).sort
(1..[a.size,b.size].min).each{|i|exit !(puts"YES")if a[-i]>b[-i]}
puts"NO"

gets
a=gets.split.map(&:to_i).sort.reverse
b=gets.split.map(&:to_i).sort.reverse
(0...[a.size,b.size].min).each{|i|exit !(puts"YES")if a[i]>b[i]}
puts"NO"

a,b,c = gets.chomp.split(" ").map{|v| v.to_i}
khanh = gets.chomp.split(" ").map{|v| v.to_i}
huy= gets.chomp.split(" ").map{|a| a.to_i}

khanh = khanh.reverse!
huy = huy.reverse!

result = "NO"
if khanh.length > huy.length
  result = "YES"
else
  stop = false
  i = 0
  while i < khanh.length && !stop do
    if khanh[i] > huy[i]
      result = "YES"
      stop = true
    elsif
      i = i + 1
    end
 end
end

puts result


In Chelyabinsk lives a much respected businessman Nikita with a strange nickname "Boss". Once Nikita decided to go with his friend Alex to the Summer Biathlon World Cup. Nikita, as a very important person, received a token which allows to place bets on each section no more than on one competitor.To begin with friends learned the rules: in the race there are n sections of equal length and m participants. The participants numbered from 1 to m. About each participant the following is known: li — the number of the starting section,  ri — the number of the finishing section (li ≤ ri), ti — the time a biathlete needs to complete an section of the path, ci — the profit in roubles. If the i-th sportsman wins on one of the sections, the profit will be given to the man who had placed a bet on that sportsman. The i-th biathlete passes the sections from li to ri inclusive. The competitor runs the whole way in (ri - li + 1)·ti time units. It takes him exactly ti time units to pass each section. In case of the athlete's victory on k sections the man who has betted on him receives k·ci roubles.In each section the winner is determined independently as follows: if there is at least one biathlete running this in this section, then among all of them the winner is the one who has ran this section in minimum time (spent minimum time passing this section). In case of equality of times the athlete with the smaller index number wins. If there are no participants in this section, then the winner in this section in not determined. We have to say that in the summer biathlon all the participants are moving at a constant speed.We should also add that Nikita can bet on each section and on any contestant running in this section.Help the friends find the maximum possible profit.

The first line contains two integers n and m (1 ≤ n, m ≤ 100). Then follow m lines, each containing 4 integers li, ri, ti, ci (1 ≤ li ≤ ri ≤ n, 1 ≤ ti, ci ≤ 1000).

Print a single integer, the maximal profit in roubles that the friends can get. In each of n sections it is not allowed to place bets on more than one sportsman.

NoteIn the first test the optimal bet is: in the 1-2 sections on biathlete 1, in section 3 on biathlete 3, in section 4 on biathlete 4. Total: profit of 5 rubles for 1 section, the profit of 5 rubles for 2 section, profit of 30 rubles for a 3 section, profit of 20 rubles for 4 section. Total profit 60 rubles.In the second test the optimal bet is: on 1 and 5 sections on biathlete 1, in the 2-4 sections on biathlete 2, in the 6-7 sections on athlete 4. There is no winner in the 8 section. Total: profit of 10 rubles for 1 section, the profit of 15 rubles for 2,3,4 section, profit of 10 rubles for a 5 section, profit of 20 rubles for 6, 7 section. Total profit 105 rubles.

n, m = gets.split.map(&:to_i)
a = []
m.times do
	a << gets.split.map(&:to_i)
end
s = 0
1.upto(n) do |i|
	b = 0
	d = -1
	a.each do |l, r, t, c|
		next if i < l || i > r
		if d == -1 || t < d
			d = t
			b = c
		end
	end
	s += b
end
p s

n,m=gets.split.map(&:to_i)
comp=[]
time=Array.new(n){[9999999,0]}
m.times{
        l,r,t,c=gets.split.map(&:to_i)
        for k in (l-1)..(r-1)
                if time[k][0]>t then
                        time[k][0]=t
                        time[k][1]=c
                end
        end
}
ans=0
n.times{|i|
        ans+=time[i][1]
}
p ans

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

sections = []

n.times do
	sections << []
end

time = {}
cost = {}

m.times do |i|
	l,r,t,c = gets.split(" ").map(&:to_i)

	(l..r).each do |j|
		sections[j-1] << i + 1
	end

	time[i+1] = t
	cost[i+1] = c
end

winner = []

# puts "#{sections}"
sections.each do |a|

	min_time = time[a[0]]
	min_ind = a[0]

	a.each_with_index do |x,i|
		# puts "x #{x} #{min_time}"
		if time[x] < min_time
			# puts "mitim #{min_time}"
			min_time = time[x]
			min_ind = x
		end
	end

	winner << min_ind
end

# puts "#{time}"
# puts "#{cost}"
# puts "#{winner}"
puts winner.compact.inject(0){|s,a| s += cost[a] }

n, m = gets.split.map(&:to_i)
a = [0]*(n+1)
tt = []
m.times do
  l, r, t, c = gets.split.map(&:to_i)
  l.upto(r) do |i|
    if !tt[i] || t < tt[i]
      tt[i] = t
      a[i] = c
    end
  end
  #p a, tt
end
p a.inject(0){|r,j| r+j}

n, m = gets.split.map(&:to_i)
arr = Array.new(n) { [] }
m.times do |j|
  l, r, t, c = gets.split.map(&:to_i)
  (l..r).each { |i| arr[i - 1] << [j, t, c] }
end

max_profit = 0
arr.each do |t|
  if !t.empty?
    t.sort! { |a, b| (a[1] == b[1]) ? a[0] <=> b[0] : a[1] <=> b[1] }
    max_profit += t[0][2]
  end
end

puts max_profit

n, m = gets.split.map(&:to_i)
a = [0]*(n+1)
tt = [2000]*(n+1)
m.times do
  l, r, t, c = gets.split.map(&:to_i)
  #p [l,r,t,c]
  l.upto(r) do |i|
    #p [i, tt[i], a[i]]
    if t < tt[i] || (t == tt[i] && a[i] < c)
      tt[i] = t
      a[i] = c
    end
  end
end
p a.inject(0){|r,j| r+j}


Hr0d1y has $$$q$$$ queries on a binary string $$$s$$$ of length $$$n$$$. A binary string is a string containing only characters '0' and '1'.A query is described by a pair of integers $$$l_i$$$, $$$r_i$$$ $$$(1 \leq l_i \lt r_i \leq n)$$$. For each query, he has to determine whether there exists a good subsequence in $$$s$$$ that is equal to the substring $$$s[l_i\ldots r_i]$$$.   A substring $$$s[i\ldots j]$$$ of a string $$$s$$$ is the string formed by characters $$$s_i s_{i+1} \ldots s_j$$$. String $$$a$$$ is said to be a subsequence of string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deleting some characters without changing the order of the remaining characters. A subsequence is said to be good if it is not contiguous and has length $$$\ge 2$$$. For example, if $$$s$$$ is "1100110", then the subsequences $$$s_1s_2s_4$$$ ("1100110") and $$$s_1s_5s_7$$$ ("1100110") are good, while $$$s_1s_2s_3$$$ ("1100110") is not good. Can you help Hr0d1y answer each query?

The first line of the input contains a single integer $$$t$$$ ($$$1\leq t \leq 100$$$) — the number of test cases. The description of each test case is as follows. The first line contains two integers $$$n$$$ ($$$2 \leq n \leq 100$$$) and $$$q$$$ ($$$1\leq q \leq 100$$$) — the length of the string and the number of queries.  The second line contains the string $$$s$$$. The $$$i$$$-th of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \leq l_i \lt r_i \leq n$$$).

For each test case, output $$$q$$$ lines. The $$$i$$$-th line of the output of each test case should contain "YES" if there exists a good subsequence equal to the substring $$$s[l_i...r_i]$$$, and "NO" otherwise. You may print each letter in any case (upper or lower).

NoteIn the first test case,   $$$s[2\ldots 4] = $$$ "010". In this case $$$s_1s_3s_5$$$ ("001000") and $$$s_2s_3s_6$$$ ("001000") are good suitable subsequences, while $$$s_2s_3s_4$$$ ("001000") is not good.  $$$s[1\ldots 3] = $$$ "001". No suitable good subsequence exists.  $$$s[3\ldots 5] = $$$ "100". Here $$$s_3s_5s_6$$$ ("001000") is a suitable good subsequence.

t = gets.chomp.to_i
t.times do
  n, q = gets.chomp.split(' ').map(&:to_i)
  s = gets.chomp.split('').map(&:to_i)
  q.times do
    l, r = gets.chomp.split(' ').map(&:to_i)
    l -= 1
    r -= 1
    if (l > 0 && s[0..(l - 1)].include?(s[l])) || (r < s.size - 1 && s[(r + 1)..].include?(s[r]))
      puts "YES"
    else
      puts "NO"
    end
  end
end


Iahub wants to enhance his multitasking abilities. In order to do this, he wants to sort n arrays simultaneously, each array consisting of m integers.Iahub can choose a pair of distinct indices i and j (1 ≤ i, j ≤ m, i ≠ j). Then in each array the values at positions i and j are swapped only if the value at position i is strictly greater than the value at position j.Iahub wants to find an array of pairs of distinct indices that, chosen in order, sort all of the n arrays in ascending or descending order (the particular order is given in input). The size of the array can be at most  (at most  pairs). Help Iahub, find any suitable array.

The first line contains three integers n (1 ≤  n ≤ 1000), m (1 ≤ m ≤  100) and k. Integer k is 0 if the arrays must be sorted in ascending order, and 1 if the arrays must be sorted in descending order. Each line i of the next n lines contains m integers separated by a space, representing the i-th array. For each element x of the array i, 1 ≤ x ≤ 106 holds.

On the first line of the output print an integer p, the size of the array (p can be at most ). Each of the next p lines must contain two distinct integers i and j (1 ≤ i, j ≤ m, i ≠ j), representing the chosen indices. If there are multiple correct answers, you can print any.

NoteConsider the first sample. After the first operation, the arrays become [1, 3, 2, 5, 4] and [1, 2, 3, 4, 5]. After the second operation, the arrays become [1, 2, 3, 5, 4] and [1, 2, 3, 4, 5]. After the third operation they become [1, 2, 3, 4, 5] and [1, 2, 3, 4, 5].

n,m,k=gets.split.map(&:to_i)
p m*(m-1)/2
if k==0
  (m-1).times do |i|
    (m-i-1).times do |j|
      puts "#{j+1} #{j+2}"
    end
  end
else
  (m-1).times do |i|
    (m-i-1).times do |j|
      puts "#{m-j} #{m-j-1}"
    end
  end
end


Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya has a number consisting of n digits without leading zeroes. He represented it as an array of digits without leading zeroes. Let's call it d. The numeration starts with 1, starting from the most significant digit. Petya wants to perform the following operation k times: find the minimum x (1 ≤ x < n) such that dx = 4 and dx + 1 = 7, if x is odd, then to assign dx = dx + 1 = 4, otherwise to assign dx = dx + 1 = 7. Note that if no x was found, then the operation counts as completed and the array doesn't change at all.You are given the initial number as an array of digits and the number k. Help Petya find the result of completing k operations.

The first line contains two integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 109) — the number of digits in the number and the number of completed operations. The second line contains n digits without spaces representing the array of digits d, starting with d1. It is guaranteed that the first digit of the number does not equal zero.

In the single line print the result without spaces — the number after the k operations are fulfilled.

NoteIn the first sample the number changes in the following sequence: 4727447 → 4427447 → 4427477 → 4427447 → 4427477.In the second sample: 4478 → 4778 → 4478.


Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point $$$(x_1,y_1)$$$ to the point $$$(x_2,y_2)$$$.He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly $$$1$$$ unit away from the box in the direction of one of two coordinate axes. He will pull the box to where he is standing before moving out of the way in the same direction by $$$1$$$ unit.   For example, if the box is at the point $$$(1,2)$$$ and Wabbit is standing at the point $$$(2,2)$$$, he can pull the box right by $$$1$$$ unit, with the box ending up at the point $$$(2,2)$$$ and Wabbit ending at the point $$$(3,2)$$$.Also, Wabbit can move $$$1$$$ unit to the right, left, up, or down without pulling the box. In this case, it is not necessary for him to be in exactly $$$1$$$ unit away from the box. If he wants to pull the box again, he must return to a point next to the box. Also, Wabbit can't move to the point where the box is located.Wabbit can start at any point. It takes $$$1$$$ second to travel $$$1$$$ unit right, left, up, or down, regardless of whether he pulls the box while moving.Determine the minimum amount of time he needs to move the box from $$$(x_1,y_1)$$$ to $$$(x_2,y_2)$$$. Note that the point where Wabbit ends up at does not matter.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 1000)$$$: the number of test cases. The description of the test cases follows. Each of the next $$$t$$$ lines contains four space-separated integers $$$x_1, y_1, x_2, y_2$$$ $$$(1 \leq x_1, y_1, x_2, y_2 \leq 10^9)$$$, describing the next test case.

For each test case, print a single integer: the minimum time in seconds Wabbit needs to bring the box from $$$(x_1,y_1)$$$ to $$$(x_2,y_2)$$$.

NoteIn the first test case, the starting and the ending points of the box are $$$(1,2)$$$ and $$$(2,2)$$$ respectively. This is the same as the picture in the statement. Wabbit needs only $$$1$$$ second to move as shown in the picture in the statement.In the second test case, Wabbit can start at the point $$$(2,1)$$$. He pulls the box to $$$(2,1)$$$ while moving to $$$(3,1)$$$. He then moves to $$$(3,2)$$$ and then to $$$(2,2)$$$ without pulling the box. Then, he pulls the box to $$$(2,2)$$$ while moving to $$$(2,3)$$$. It takes $$$4$$$ seconds.

T = gets.to_i

T.times do
  x1, y1, x2, y2 = gets.split.map(&:to_i)

  dx = (x2 - x1).abs
  dy = (y2 - y1).abs

  if dx == 0 && dy == 0
    puts 0
  elsif dx == 0
    puts dy
  elsif dy == 0
    puts dx
  else
    puts dx + dy + 2
  end
end

t = gets.chomp.to_i
sa = 0
t.times do
    a, b, c, d = gets.chomp.split(" ").map(&:to_i)
    sa = 0
    if a == c || b == d
        puts (c-a).abs + (d-b).abs
    else
        sa = (c-a).abs + (d-b).abs + 2
        puts sa
    end
end

gets.to_i.times do
    x1, y1, x2, y2 = gets.split.map &:to_i
    puts (x2 - x1).abs + (y2 - y1).abs + (x1 == x2 || y1 == y2 ? 0 : 2)
end

t = gets.to_i
ans = []
t.times do
  x1,y1,x2,y2 = gets.chomp.split(" ").map(&:to_i)
  x = (x2-x1).abs + (y2-y1).abs
  if x1 != x2 && y1 != y2
    x += 2
  end
  ans << x
end
ans.each do |v|
  puts v
end

t = gets.chomp.to_i
sa = 0
t.times do
    a, b, c, d = gets.chomp.split(" ").map(&:to_i)
    sa = (a-c).abs + (b-d).abs
    puts sa
end

t = gets.chomp.to_i
sa = 0
t.times do
    a, b, c, d = gets.chomp.split(" ").map(&:to_i)
    sa = 0
    if a == c || b == d
        puts (c-a).abs + (d-b).abs
    else
        sa = (c-a).abs + (d-b).abs + 3
        puts sa
    end
end

gets.to_i.times do
    x1, y1, x2, y2 = gets.split.map &:to_i
    puts (x2 - x1).abs - (y2 - y1).abs + x1 == x2 || y1 == y2 ? 0 : 2
end


You are fighting with Zmei Gorynich — a ferocious monster from Slavic myths, a huge dragon-like reptile with multiple heads!   Initially Zmei Gorynich has $$$x$$$ heads. You can deal $$$n$$$ types of blows. If you deal a blow of the $$$i$$$-th type, you decrease the number of Gorynich's heads by $$$min(d_i, curX)$$$, there $$$curX$$$ is the current number of heads. But if after this blow Zmei Gorynich has at least one head, he grows $$$h_i$$$ new heads. If $$$curX = 0$$$ then Gorynich is defeated. You can deal each blow any number of times, in any order.For example, if $$$curX = 10$$$, $$$d = 7$$$, $$$h = 10$$$ then the number of heads changes to $$$13$$$ (you cut $$$7$$$ heads off, but then Zmei grows $$$10$$$ new ones), but if $$$curX = 10$$$, $$$d = 11$$$, $$$h = 100$$$ then number of heads changes to $$$0$$$ and Zmei Gorynich is considered defeated.Calculate the minimum number of blows to defeat Zmei Gorynich!You have to answer $$$t$$$ independent queries.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) – the number of queries. The first line of each query contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 100$$$, $$$1 \le x \le 10^9$$$) — the number of possible types of blows and the number of heads Zmei initially has, respectively. The following $$$n$$$ lines of each query contain the descriptions of types of blows you can deal. The $$$i$$$-th line contains two integers $$$d_i$$$ and $$$h_i$$$ ($$$1 \le d_i, h_i \le 10^9$$$) — the description of the $$$i$$$-th blow.

For each query print the minimum number of blows you have to deal to defeat Zmei Gorynich.  If Zmei Gorynuch cannot be defeated print $$$-1$$$.

NoteIn the first query you can deal the first blow (after that the number of heads changes to $$$10 - 6 + 3 = 7$$$), and then deal the second blow.In the second query you just deal the first blow three times, and Zmei is defeated. In third query you can not defeat Zmei Gorynich. Maybe it's better to convince it to stop fighting?

tt = gets.chomp.to_i
tt.times.map do
  nn, xx = gets.split.map(&:to_i)
  # 差分が大きい順
  dh = nn.times.map{gets.split.map(&:to_i)}.sort{|a,b|(b[0]-b[1])<=>(a[0]-a[1])}
  last = dh.sort{|a,b|b[0]<=>a[0]}[0][0]
  diff = dh[0][0]-dh[0][1]
  if last>=xx
    puts 1
    next
  elsif diff<=0
    puts -1
    next
  end
  cnt = 1 + ((xx-last)/diff.to_f).ceil
  puts cnt
end

t = gets.chomp.to_i

t.times do |i|
  n, x = gets.chomp.split.map(&:to_i)
  max_d, max_diff = 0, 0
  n.times do |j|
    d, h = gets.chomp.split.map(&:to_i)
    max_d = [max_d, d].max
    max_diff = [max_diff, d-h].max
  end
  if max_d >= x
    puts 1
  elsif max_diff == 0
    puts -1
  else
    puts ((x-max_d).to_f/max_diff).ceil + 1
  end
end


Berland crossword is a puzzle that is solved on a square grid with $$$n$$$ rows and $$$n$$$ columns. Initially all the cells are white.To solve the puzzle one has to color some cells on the border of the grid black in such a way that:   exactly $$$U$$$ cells in the top row are black;  exactly $$$R$$$ cells in the rightmost column are black;  exactly $$$D$$$ cells in the bottom row are black;  exactly $$$L$$$ cells in the leftmost column are black. Note that you can color zero cells black and leave every cell white.Your task is to check if there exists a solution to the given puzzle.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The only line of each testcase contains $$$5$$$ integers $$$n, U, R, D, L$$$ ($$$2 \le n \le 100$$$; $$$0 \le U, R, D, L \le n$$$).

For each testcase print "YES" if the solution exists 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).

NoteHere are possible solutions to testcases $$$1$$$, $$$2$$$ and $$$4$$$:

def solve
  n, u, r, d, l = ints
  (1 << 4).times.any? do |bits|
    lu, ru, ld, rd = (0 ... 4).map { |i| bits[i] == 1 }
    l_use = r_use = u_use = d_use = 0
    if lu
      l_use += 1
      u_use += 1
    end
    if ru
      r_use += 1
      u_use += 1
    end
    if ld
      l_use += 1
      d_use += 1
    end
    if rd
      r_use += 1
      d_use += 1
    end
    [l - l_use, r - r_use, u - u_use, d - d_use].all? { |x| 0 <= x and x <= n - 2}
  end
end

def main
  t = int
  t.times do
    yesno solve
  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

gets.to_i.times do
    n, u, r, d, l = gets.split.map &:to_i
    ok = false
    16.times do |msk|
        cu, cr, cd, cl = u, r, d, l
        if msk & 1 > 0
            cu -= 1
            cl -= 1
        end
        if msk & 2 > 0
            cl -= 1
            cd -= 1
        end
        if msk & 4 > 0
            cd -= 1
            cr -= 1
        end
        if msk & 8 > 0
            cr -= 1
            cu -= 1
        end
        if [cu, cr, cd, cl].min >= 0 && [cu, cr, cd, cl].max <= n - 2
            puts "YES"
            ok = true
            break
        end
    end
    puts "NO" if !ok
end

def solve
  n, u, r, d, l = ints
  (1 << 4).times.any? do |bits|
    lu, ru, ld, rd = (0 ... 4).map { |i| bits[i] == 1 }
    l_use = r_use = u_use = d_use = 0
    if lu
      l_use += 1
      u_use += 1
    end
    if ru
      r_use += 1
      u_use += 1
    end
    if ld
      l_use += 1
      d_use += 1
    end
    if rd
      r_use += 1
      d_use += 1
    end
    possible = (l_use <= l and r_use <= r and u_use <= u and d_use <= d)
    possible &&= lu ? (l >= 1 and u >= 1) : (l <= n - 1 and u <= n - 1)
    possible &&= ru ? (r >= 1 and u >= 1) : (r <= n - 1 and u <= n - 1)
    possible &&= ld ? (l >= 1 and d >= 1) : (l <= n - 1 and d <= n - 1)
    possible &&= rd ? (r >= 1 and d >= 1) : (r <= n - 1 and d <= n - 1)
    possible &&= (lu and ru) ? (u >= 2) : true
    possible &&= (lu and ld) ? (l >= 2) : true
    possible &&= (ru and rd) ? (r >= 2) : true
    possible &&= (ld and rd) ? (d >= 2) : true
    possible
  end
end

def main
  t = int
  t.times do
    yesno solve
  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

def solve
  n, u, r, d, l = ints
  (1 << 4).times.any? do |bits|
    lu, ru, ld, rd = (0 ... 4).map { |i| bits[i] == 1 }
    possible = true
    possible &&= lu ? (l >= 1 and u >= 1) : (l <= n - 1 and u <= n - 1)
    possible &&= ru ? (r >= 1 and u >= 1) : (r <= n - 1 and u <= n - 1)
    possible &&= ld ? (l >= 1 and d >= 1) : (l <= n - 1 and d <= n - 1)
    possible &&= rd ? (r >= 1 and d >= 1) : (r <= n - 1 and d <= n - 1)
    possible &&= (lu and ru) ? (u >= 2) : true
    possible &&= (lu and ld) ? (l >= 2) : true
    possible &&= (ru and rd) ? (r >= 2) : true
    possible &&= (ld and rd) ? (d >= 2) : true
    possible
  end
end

def main
  t = int
  t.times do
    yesno solve
  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

def solve
  n, u, r, d, l = ints
  (1 << 4).times.any? do |bits|
    lu, ru, ld, rd = (0 ... 4).map { |i| bits[i] == 1 }
    possible = true
    possible &&= lu ? (l >= 1 and u >= 1) : (l <= n - 1 and u <= n - 1)
    possible &&= ru ? (r >= 1 and u >= 1) : (r <= n - 1 and u <= n - 1)
    possible &&= ld ? (l >= 1 and d >= 1) : (l <= n - 1 and d <= n - 1)
    possible &&= rd ? (r >= 1 and d >= 1) : (r <= n - 1 and d <= n - 1)
    possible
  end
end

def main
  t = int
  t.times do
    yesno solve
  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

def solve
  n, u, r, d, l = ints
  [[u, d, l, r], [u, d, r, l], [l, r, u, d], [l, r, d, u]].all? { |(x, y, z, w)|
    if x == n
      if y == n
        z >= 2 and w >= 2
      elsif y == n - 1
        z >= 2 and w >= 1
      else
        z >= 1 and w >= 1
      end
    elsif x == n - 1
      if y == n
        z >= 2 and w >= 1
      elsif y == n - 1
        z >= 2 or z >= 1 and w >= 1
      else
        z >= 1 or w >= 1
      end
    else
      if y == n
        z >= 1 and w <= n - 1
      elsif y == n - 1
        z >= 1 and w <= n - 2
      else
        z == n and w <= n - 2 or z == n - 1 and w <= n - 1 or z <= n - 2
      end
    end
  }
end

def main
  t = int
  t.times do
    yesno solve
  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

def solve
  n, u, r, d, l = ints
  [[u, d, l, r], [u, d, r, l], [l, r, u, d], [l, r, d, u]].all? { |(x, y, z, w)|
    if x == n
      if y == n
        z >= 2 and w >= 2
      elsif y == n - 1
        z >= 2 and w >= 1
      else
        z >= 1 and w >= 1
      end
    elsif x == n - 1
      if y == n
        z >= 2 and w >= 1
      elsif y == n - 1
        z >= 2 or z >= 1 and w >= 1
      else
        z >= 1 or w >= 1
      end
    else
      true
    end
  }
end

def main
  t = int
  t.times do
    yesno solve
  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

gets.to_i.times do
    n, u, r, d, l = gets.split.map &:to_i
    ok = false
    16.times do |msk|
        cu, cr, cd, cl = u, r, d, l
        if msk & 1 > 0
            cu -= 1
            cl -= 1
        elsif msk & 2 > 0
            cl -= 1
            cd -= 1
        elsif msk & 4 > 0
            cd -= 1
            cr -= 1
        elsif msk & 8 > 0
            cr -= 1
            cu -= 1
        end
        if [cu, cr, cd, cl].min >= 0 && [cu, cr, cd, cl].max <= n - 2
            puts "YES"
            ok = true
            break
        end
    end
    puts "NO" if !ok
end