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


A subway scheme, classic for all Berland cities is represented by a set of n stations connected by n passages, each of which connects exactly two stations and does not pass through any others. Besides, in the classic scheme one can get from any station to any other one along the passages. The passages can be used to move in both directions. Between each pair of stations there is no more than one passage.Berland mathematicians have recently proved a theorem that states that any classic scheme has a ringroad. There can be only one ringroad. In other words, in any classic scheme one can find the only scheme consisting of stations (where any two neighbouring ones are linked by a passage) and this cycle doesn't contain any station more than once.This invention had a powerful social impact as now the stations could be compared according to their distance from the ringroad. For example, a citizen could say "I live in three passages from the ringroad" and another one could reply "you loser, I live in one passage from the ringroad". The Internet soon got filled with applications that promised to count the distance from the station to the ringroad (send a text message to a short number...).The Berland government decided to put an end to these disturbances and start to control the situation. You are requested to write a program that can determine the remoteness from the ringroad for each station by the city subway scheme.

The first line contains an integer n (3 ≤ n ≤ 3000), n is the number of stations (and trains at the same time) in the subway scheme. Then n lines contain descriptions of the trains, one per line. Each line contains a pair of integers xi, yi (1 ≤ xi, yi ≤ n) and represents the presence of a passage from station xi to station yi. The stations are numbered from 1 to n in an arbitrary order. It is guaranteed that xi ≠ yi and that no pair of stations contain more than one passage. The passages can be used to travel both ways. It is guaranteed that the given description represents a classic subway scheme.

Print n numbers. Separate the numbers by spaces, the i-th one should be equal to the distance of the i-th station from the ringroad. For the ringroad stations print number 0.

#!/usr/bin/env ruby

n = gets.to_i
roads = Array.new(n) { [] }
n.times do
    r = gets.split.map(&:to_i)
    r[0] -= 1
    r[1] -= 1
    roads[r[0]] << r[1]
    roads[r[1]] << r[0]
end

eliminated = [false]*n
loop {
    flag = false
    roads.each_with_index do |r, idx|
        next if eliminated[idx]
        cnt = 0
        r.each do |i|
            cnt += 1 if !eliminated[i]
        end
        if cnt == 1
            eliminated[idx] = true
            flag = true
        end
    end
    break if !flag
}
lp = []
eliminated.each_with_index do |e, i|
    lp << i if !e
end

res = [nil]*n
q = []
lp.each do |i|
    q << [i, 0]
end
while q.size > 0
    cur = q.shift
    next if res[cur[0]]

    res[cur[0]] = cur[1]
    roads[cur[0]].each do |nx|
        q << [nx, cur[1]+1] unless res[nx]
    end
end

puts res.join(' ')

#!/usr/bin/env ruby

def find_loop(roads, stack, pos, visited)
    stack = [0]
    visited = [false]*roads.size

    roads[pos].each do |nx|
        if visited[nx]
            if stack.size >= 2 && stack[-2] != nx && stack.index(nx)
                res = []
                while stack[-1] != nx
                    res << stack.pop
                end
                res << stack.pop
                return res
            end
        else
            res = find_loop(roads, stack, nx, visited)
            return res if res
        end
    end
    visited[pos] = false
    stack.pop
    nil
end

def dfs(roads, pos, cost, res)
    res[pos] = cost
    roads[pos].each do |nx|
        next if res[nx]
        dfs(roads, nx, cost+1, res)
    end
end

n = gets.to_i
roads = Array.new(n) { [] }
n.times do
    r = gets.split.map(&:to_i)
    r[0] -= 1
    r[1] -= 1
    roads[r[0]] << r[1]
    roads[r[1]] << r[0]
end

eliminated = [false]*n
loop {
    flag = false
    roads.each_with_index do |r, idx|
        next if eliminated[idx]
        cnt = 0
        r.each do |i|
            cnt += 1 if !eliminated[i]
        end
        if cnt == 1
            eliminated[idx] = true
            flag = true
        end
    end
    break if !flag
}
lp = []
eliminated.each_with_index do |e, i|
    lp << i if !e
end

res = [nil]*n
q = []
lp.each do |i|
    q << [i, 0]
end
while q.size > 0
    cur = q.shift
    next if res[cur[0]]

    res[cur[0]] = cur[1]
    roads[cur[0]].each do |nx|
        q << [nx, cur[1]+1] unless res[nx]
    end
end

puts res.join(' ')

def cycle(node, e, r)
  que = [[node, r]]

  until que.empty?
    node, r = que.pop

    if r.include?(node)
      i = r.index(node)
      return r[i..-1]
    end

    e[node].each do |m|
      next if m == r.last

      que << [m, r+[node]]
    end
  end
  nil
end

n = gets.to_i
e = {}
while l = gets
  x, y = l.split.map(&:to_i)
  (e[x] ||= []) << y
  (e[y] ||= []) << x
end

c = cycle(1, e, [])
depth = {}
c.each{|x| depth[x] = 0 }
g = c
while depth.size < n
  g2 = []
  g.each do |x|
    e[x].each do |y|
      if !depth[y]
        depth[y] = depth[x]+1
        g2 << y
      end
    end
  end
  g = g2
end

puts (1..n).map{|x|depth[x]}*" "


Phoenix has a string $$$s$$$ consisting of lowercase Latin letters. He wants to distribute all the letters of his string into $$$k$$$ non-empty strings $$$a_1, a_2, \dots, a_k$$$ such that every letter of $$$s$$$ goes to exactly one of the strings $$$a_i$$$. The strings $$$a_i$$$ do not need to be substrings of $$$s$$$. Phoenix can distribute letters of $$$s$$$ and rearrange the letters within each string $$$a_i$$$ however he wants.For example, if $$$s = $$$ baba and $$$k=2$$$, Phoenix may distribute the letters of his string in many ways, such as:   ba and ba  a and abb  ab and ab  aa and bb But these ways are invalid:   baa and ba  b and ba  baba and empty string ($$$a_i$$$ should be non-empty) Phoenix wants to distribute the letters of his string $$$s$$$ into $$$k$$$ strings $$$a_1, a_2, \dots, a_k$$$ to minimize the lexicographically maximum string among them, i. e. minimize $$$max(a_1, a_2, \dots, a_k)$$$. Help him find the optimal distribution and print the minimal possible value of $$$max(a_1, a_2, \dots, a_k)$$$.String $$$x$$$ is lexicographically less than string $$$y$$$ if either $$$x$$$ is a prefix of $$$y$$$ and $$$x \ne y$$$, or there exists an index $$$i$$$ ($$$1 \le i \le min(|x|, |y|))$$$ such that $$$x_i$$$ < $$$y_i$$$ and for every $$$j$$$ $$$(1 \le j < i)$$$ $$$x_j = y_j$$$. Here $$$|x|$$$ denotes the length of the string $$$x$$$.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case consists of two lines. The first line of each test case consists of two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^5$$$) — the length of string $$$s$$$ and the number of non-empty strings, into which Phoenix wants to distribute letters of $$$s$$$, respectively. The second line of each test case contains a string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ over all test cases is $$$\le 10^5$$$.

Print $$$t$$$ answers — one per test case. The $$$i$$$-th answer should be the minimal possible value of $$$max(a_1, a_2, \dots, a_k)$$$ in the $$$i$$$-th test case.

6
4 2
baba
5 2
baacb
5 3
baacb
5 3
aaaaa
6 4
aaxxzz
7 1
phoenix

NoteIn the first test case, one optimal solution is to distribute baba into ab and ab. In the second test case, one optimal solution is to distribute baacb into abbc and a.In the third test case, one optimal solution is to distribute baacb into ac, ab, and b.In the fourth test case, one optimal solution is to distribute aaaaa into aa, aa, and a.In the fifth test case, one optimal solution is to distribute aaxxzz into az, az, x, and x.In the sixth test case, one optimal solution is to distribute phoenix into ehinopx.

def solve str, k
  chars = str.chars.sort
  return chars.join if k == 1
  return chars[k - 1] if chars[0] != chars[k - 1]
  res = []
  res << chars[0]
  if chars[k] == chars[str.length - 1]
    res << chars[k] * ((str.length - k) / k)
    res << chars[k] if (str.length - k) % k != 0
  else
    res << chars[k..-1]
  end
  res.flatten.join
end

t = STDIN.gets.chomp.to_i

(1..t).each do |i|
  n, k = STDIN.gets.chomp.split.map {|i| i.to_i}
  str = STDIN.gets.chomp
  res = solve str, k
  puts res
end

def solve str, k
  chars = str.chars.sort
  return chars[k - 1] if chars[0] != chars[k - 1]
  res = []
  res << chars[0]
  if chars[k] == chars[str.length - 1]
    res << chars[k]
  else
    res << chars[k..-1]
  end
  res.flatten.join
end

t = STDIN.gets.chomp.to_i

(1..t).each do |i|
  n, k = STDIN.gets.chomp.split.map {|i| i.to_i}
  str = STDIN.gets.chomp
  res = solve str, k
  puts res
end

def solve str, k
  chars = str.chars.sort
  return chars.join if k == 1
  return chars[k - 1] if chars[0] != chars[k - 1]
  res = []
  res << chars[0]
  if chars[k] == chars[str.length - 1]
    res << chars[k] * ((str.length - k) / k)
    res << chars[k] * ((str.length - k) % k)
  else
    res << chars[k..-1]
  end
  res.flatten.join
end

t = STDIN.gets.chomp.to_i

(1..t).each do |i|
  n, k = STDIN.gets.chomp.split.map {|i| i.to_i}
  str = STDIN.gets.chomp
  res = solve str, k
  puts res
end

def solve str, k
  return str if k == 1
  chars = str.chars.sort
  return chars[k - 1] if chars[0] != chars[k - 1]
  res = []
  res << chars[0]
  if chars[k] == chars[str.length - 1]
    res << chars[k]
  else
    res << chars[k..-1]
  end
  res.flatten.join
end

t = STDIN.gets.chomp.to_i

(1..t).each do |i|
  n, k = STDIN.gets.chomp.split.map {|i| i.to_i}
  str = STDIN.gets.chomp
  res = solve str, k
  puts res
end

def solve str, k
  chars = str.chars.sort
  return chars.join if k == 1
  return chars[k - 1] if chars[0] != chars[k - 1]
  res = []
  res << chars[0]
  if chars[k] == chars[str.length - 1]
    res << chars[k]
  else
    res << chars[k..-1]
  end
  res.flatten.join
end

t = STDIN.gets.chomp.to_i

(1..t).each do |i|
  n, k = STDIN.gets.chomp.split.map {|i| i.to_i}
  str = STDIN.gets.chomp
  res = solve str, k
  puts res
end

def solve str, k
  chars = str.chars.sort
  if chars[0] != chars[k - 1]
    return chars[k - 1]
  end
  res = []
  idx = 0
  while chars[idx] == chars[idx + k - 1] do
    res << chars[idx]
    idx += k - 1
    break if idx + 1 >= str.length
    break if idx + k >= str.length
    idx += 1
  end
  res << chars[(idx + 1)..-1] if idx < str.length - 1
  res.flatten.join
end

t = STDIN.gets.chomp.to_i

(1..t).each do |i|
  n, k = STDIN.gets.chomp.split.map {|i| i.to_i}
  str = STDIN.gets.chomp
  res = solve str, k
  puts res
end


Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items.

In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week).

Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now.

NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25.

n, k = gets.chomp.split.map(&:to_i)
a_week = gets.chomp.split.map(&:to_i)
b_week = gets.chomp.split.map(&:to_i)
diff = []
Diff = Struct.new(:index, :diff,:purchased)
n.times do |i|
  diff << Diff.new(i,(a_week[i] - b_week[i]), false)
end
diff.sort! { |num1, num2| num1.diff <=> num2.diff}

negatives = diff.count{ |num| num.diff < 0}
minimum_money_spent = 0
[k,negatives].max.times do |i|
  curr_item = diff[i]
  minimum_money_spent += a_week[curr_item.index]
  curr_item.purchased = true
end
diff.each do |item|
  minimum_money_spent+= b_week[item.index] if item.purchased == false
end
puts minimum_money_spent

#少计算就是打折！
#实在不成，我自己把c里面的merge sort搬过来！
number=gets.chomp.split
n=number[0].to_i
k=number[1].to_i
a=gets.chomp.split
b=gets.chomp.split
Pair=Struct.new(:index,:value)
indexed_ab=[]
for i in 0...n
	some=Pair.new(i,a[i].to_i-b[i].to_i)
	indexed_ab<<some
end
#看起来需要降价幅度最大的！优先更换！
#从大到小排序
indexed_ab.sort!{|a,b| b.value <=> a.value }
#新思路是做出一个替换!
use=Array.new(n,0)
#use[i]=0表示使用打折前的价格
#use[i]=1表示使用打折后的价格
#for i in 0...n
#	print "  #{indexed_ab[i].index} #{indexed_ab[i].value}"
#end
#puts
for i in 0...(n-k)
	if indexed_ab[i].value>0
		use[indexed_ab[i].index]=1
	end
end
cost=0
for i in 0...n
	if use[i]==0
		cost+=a[i].to_i
		#print " #{a[i]}"
	else
		cost+=b[i].to_i
		#print " #{b[i]}"
	end
end
#puts
puts cost

#少计算就是打折！
#实在不成，我自己把c里面的merge sort搬过来！
number=gets.chomp.split
n=number[0].to_i
k=number[1].to_i
a=gets.chomp.split
b=gets.chomp.split
Pair=Struct.new(:index,:value)
indexed_ab=[]
for i in 0...n
	some=Pair.new(i,a[i].to_i-b[i].to_i)
	indexed_ab<<some
end
#看起来需要降价幅度最大的！优先更换！
#从大到小排序
indexed_ab.sort!{|a,b| b.value <=> a.value }
#新思路是做出一个替换!
#use[i]=0表示使用打折前的价格
#use[i]=1表示使用打折后的价格
#for i in 0...n
#	print "  #{indexed_ab[i].index} #{indexed_ab[i].value}"
#end
#puts
cost=0
item=n-k
for i in 0...n
	if indexed_ab[i].value>0 && item > 0
		cost+=b[indexed_ab[i].index].to_i
		#print " #{b[indexed_ab[i].index]}"
		item-=1
	else
		cost+=a[indexed_ab[i].index].to_i
		#print " #{a[indexed_ab[i].index]}"
	end
end
#puts
puts cost

n, k = gets.split.map(&:to_i)
aa = gets.split.map(&:to_i)
t = aa.inject(0, :+)
aa = aa.zip(gets.split.map(&:to_i)).map { |a, b| a - b }.sort
aa.push 0
while aa[k] < 0 do
  k += 1
end
p aa[k, n - k].inject(t, :-)

n, k = gets.split.map(&:to_i)
k = k.to_i
aa = gets.split.map(&:to_i)
bb = aa.zip(gets.split.map(&:to_i)).map { |a, b| a - b }.sort
bb.push 0
while bb[k] < 0 do
  k += 1
end
p aa.inject(bb[k, n - k].inject(0, :-), :+)

ii = lambda { gets.split.map(&:to_i) }
n, k = ii.call
t = (aa = ii.call).inject(0, :+)
(aa = aa.zip(ii.call).map { |a, b| a - b }.sort).push 0
while aa[k] < 0 do k += 1 end
p aa[k, n - k].inject(t, :-)

#少计算就是打折！
number=gets.chomp.split
n=number[0].to_i
k=number[1].to_i
a=gets.chomp.split
b=gets.chomp.split
c=[]
Pair=Struct.new(:before,:after)
for i in 0...n
	some=Pair.new(a[i].to_i,b[i].to_i)
	c<<some
end
#for i in 0...n
	#puts "#{c[i].before} #{c[i].after}"
#end
#这里只需要判断最小值来自哪里！
c.sort_by!{|e|
	if e.after < e.before
		e.after
	elsif e.after == e.before
		e.before
	else
		e.before
	end

}
#for i in 0...n
#	puts "#{c[i].before} #{c[i].after}"
#end
buy_before=0
buy_after=0
j=0
for i in 0...n
	if c[i].before > c[i].after && j< n-k
		buy_after+= c[i].after
		j+=1
	else
		buy_before+= c[i].before
	end
end
puts buy_before+buy_after

#一个思路是：sort一下，就是把a,b作为整体来sort！
#取前k个a<b的，取前n-k个b>a的
#第二次购买，应该买那些年价格降低的！
#或者同时处理，遇到价格降低的当作第二次购买，
#遇到价格不变的，甚至升高的，放在第一次购买！

#少计算就是打折！
#实在不成，我自己把c里面的merge sort搬过来！
number=gets.chomp.split
n=number[0].to_i
k=number[1].to_i
a=gets.chomp.split
b=gets.chomp.split
Pair=Struct.new(:index,:value)
indexed_ab=[]
for i in 0...n
	some=Pair.new(i,a[i].to_i-b[i].to_i)
	indexed_ab<<some
end
#看起来需要降价幅度最大的！优先更换！
#从大到小排序
indexed_ab.sort!{|a,b| b.value <=> a.value }
#新思路是做出一个替换!
use=Array.new(n,0)
#use[i]=0表示使用打折前的价格
#use[i]=1表示使用打折后的价格
#for i in 0...n
	#print "  #{indexed_ab[i].index} #{indexed_ab[i].value}"
#end
#puts
for i in 0...(n-k)
	if indexed_ab[i].value==0
		break
	else
		use[indexed_ab[i].index]=1
	end
end
cost=0
for i in 0...n
	if use[i]==0
		cost+=a[i].to_i
		#print " #{a[i]}"
	else
		cost+=b[i].to_i
		#print " #{b[i]}"
	end
end
#puts
puts cost

#少计算就是打折！
#实在不成，我自己把c里面的merge sort搬过来！
number=gets.chomp.split
n=number[0].to_i
k=number[1].to_i
a=gets.chomp.split
b=gets.chomp.split
Pair=Struct.new(:index,:value)
indexed_a=[]
for i in 0...n
	some=Pair.new(i,a[i].to_i)
	indexed_a<<some
end
indexed_b=[]
for i in 0...n
	some=Pair.new(i,b[i].to_i)
	indexed_b<<some
end

indexed_a.sort!{|a,b| a.value <=> b.value }
indexed_b.sort!{|a,b| a.value <=> b.value }
#for i in 0...n
#	puts "#{indexed_a[i].index} #{indexed_a[i].value}"
#end
#for i in 0...n
#	puts "#{indexed_b[i].index} #{indexed_b[i].value}"
#end
#
see=Array.new(n,0)
i=0
j=0
cost=0
item=n-k
while true do
	while i<n && see[indexed_a[i].index]==1
	       i+=1
	end
	while j<n && see[indexed_b[j].index]==1
	       j+=1
	end
	if i==n && j==n
		break
	elsif i==n && j!=n
		#这里只能买打折后的了！
		cost+=indexed_b[j].value
		j+=1
	elsif i!=n && j==n
		#这里只能买打折前的了！
		cost+=indexed_a[i].value
		i+=1
	else
		#可以从打折前后选择最小的！
		if indexed_a[i].value > indexed_b[j].value
			#这里我们在还有可以买非必需现在买的商品的额度时，可以购买
			#如果没有额度了，就无法购买，只能现在就买！
			if item > 0
				cost+=indexed_b[j].value
				see[indexed_b[j].index]=1
				item-=1
				j+=1
			else
				j=n
			end

		else
			cost+=indexed_a[i].value
			see[indexed_a[i].index]=1
			i+=1
		end
	end
end
puts cost

#少计算就是打折！
#实在不成，我自己把c里面的merge sort搬过来！
number=gets.chomp.split
n=number[0].to_i
k=number[1].to_i
a=gets.chomp.split
b=gets.chomp.split
Pair=Struct.new(:index,:value)
indexed_ab=[]
for i in 0...n
	some=Pair.new(i,a[i].to_i-b[i].to_i)
	indexed_ab<<some
end
#看起来需要降价幅度最大的！优先更换！
#从大到小排序
indexed_ab.sort!{|a,b| b.value <=> a.value }
#新思路是做出一个替换!
#use[i]=0表示使用打折前的价格
#use[i]=1表示使用打折后的价格
#for i in 0...n
#	print "  #{indexed_ab[i].index} #{indexed_ab[i].value}"
#end
#puts
cost=0
for i in 0...n
	if indexed_ab[i].value>0
		cost+=b[indexed_ab[i].index].to_i
	else
		cost+=a[indexed_ab[i].index].to_i
	end
end
puts cost


Vasya wants to turn on Christmas lights consisting of m bulbs. Initially, all bulbs are turned off. There are n buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs?If Vasya presses the button such that some bulbs connected to it are already turned on, they do not change their state, i.e. remain turned on.

The first line of the input contains integers n and m (1 ≤ n, m ≤ 100) — the number of buttons and the number of bulbs respectively.  Each of the next n lines contains xi (0 ≤ xi ≤ m) — the number of bulbs that are turned on by the i-th button, and then xi numbers yij (1 ≤ yij ≤ m) — the numbers of these bulbs.

If it's possible to turn on all m bulbs print "YES", otherwise print "NO".

NoteIn the first sample you can press each button once and turn on all the bulbs. In the 2 sample it is impossible to turn on the 3-rd lamp.

a=gets.chomp.split(" ")
light=[]
1.upto(a[0].to_i) do
b=gets.chomp.split(" ")
b.shift
light += b
end
light.uniq!
if light.length<a[1].to_i
	puts "NO"
elsif a[1]=="0" || (a[1]=="0" && a[0]=="0")
 	puts "NO"
else
	puts "YES"
end

n,m=gets.split.map{|e| e.to_i}
arr=[]
n.times{
	x=gets.split.map{|e| e.to_i}
	x.shift
	arr<<x
}

puts (arr.flatten.uniq.size==m)?"YES":"NO"

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

a = Array.new(m, 0)

n.times do
  x = gets.split.map(&:to_i)
  x.shift
  x.each do |v|
    a[v - 1] = 1
  end
end

if a.include?(0)
  puts 'NO'
else
  puts 'YES'
end

# coding: utf-8

n, m = gets.split.map(&:to_i)
bulbs = Array.new(m) { false }
n.times {
    presses = gets.split.map(&:to_i)
    presses.shift # first item for how many commands are coming to next
    presses.each { |i|
        bulbs[i - 1] = true
    }
}

if bulbs.count(false) == 0
    puts "YES"
else
    puts "NO"
end

n, m = gets.chomp.split.map(&:to_i)
ys = []
n.times do
  xy = gets.chomp.split.map(&:to_i)
  ys += xy[1, xy[0]]
  ys.sort!.uniq!
end

puts ys.size == m ? 'YES' : 'NO'

nm = gets.chomp.split.map(&:to_i)
n = nm[0]
m = nm[1]
bulbs = []
for i in (0..n-1)
	bulbs[i] = gets.chomp.split.map(&:to_i)
end

turn_on = []
for i in (0..n-1)
	for x in (1..bulbs[i][0])
		if turn_on.include?(bulbs[i][x]) == false
			turn_on << bulbs[i][x]
		end
	end
end

if turn_on.size == m
	print "YES"
else
	print "NO"
end

class Solver
	def main
		n, m = gets.split.map { |x| x.to_i }
		f = Array.new(m + 1, false)
		n.times do
			a = gets.split.map { |x| x.to_i }
			a.shift
			a.each do |x|
				f[x] = true
			end
		end
		cnt = f.count(true)
		if cnt == m
			puts "YES"
		else
			puts "NO"
		end
	end
end
Solver.new.main

#!/usr/bin/ruby
n,m=gets.split.map(&:to_i)
a=[]
n.times{a|=gets.split.map(&:to_i)[1..-1]}
puts a.size==m ? :YES : :NO

n, m = gets.split.map(&:to_i)
bulbs = []
n.times{ bulbs |= gets.split[1..-1] }
puts bulbs.size == m ? 'YES' : 'NO'

n, m = gets.split.map(&:to_i)
bulbs = []
n.times{ bulbs |= gets.split.map(&:to_i)[1..-1] }
puts bulbs.size == m ? 'YES' : 'NO'

n, m = gets.split.map(&:to_i)
bulbs = Array.new(m, 0)
n.times do
  a = gets.split.map(&:to_i)[1..-1]
  a.each{|x| bulbs[x] = 1}
end
puts bulbs.inject(:+) == m ? 'YES' : 'NO'

n, m = gets.chomp.split(" ").map(&:to_i)
bulbs = []
n.times do
  y = gets.chomp.split(" ").map(&:to_i)
  x = y.shift
  bulbs += y
end
if bulbs.uniq.length == m then
  puts "YES"
else
  puts "NO"
end

_, nbulbs = ARGF.gets.chomp.split(" ").map { |s| s.to_i }

on = Array.new(nbulbs + 1) { |e| FALSE }
on[0] = TRUE

while line = ARGF.gets do
    conns = line.chomp.split(" ").map {|s| s.to_i}
    conns.shift
    for c in conns do
        on[c] = TRUE
    end
end

if on.all? then puts "YES" else puts "NO" end

n, m = gets.split.map &:to_i
b = []
n.times do
  xs = gets.split.map &:to_i
  xs[1..-1].each {|x| b[x] = true}
end
puts b.count(true) == m ? 'YES' : 'NO'

require "set"

n, m = gets.split.map &:to_i
bulbs = Set.new
n.times do |_|
  bulbs.merge(gets.split[1..-1].map &:to_i)
end

if bulbs == (1..m).to_set
  puts "YES"
else
  puts "NO"
end

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

blobs = Array.new(m, 1)
1.upto(n).each do
	ar = gets.strip.split.map(&:to_i)
	ar[1..-1].each do |e|
		blobs[e-1] = 0
	end
end

puts blobs.any?{|e| e ==1} ? 'NO' : 'YES'

#! ruby
# Try Codeforces
# author: Leonardone @ NEETSDKASU
############################################################
def gs() gets.chomp end
def gi() gets.to_i end
def gss() gs.split end
def gis() gss.map(&:to_i) end
def nmapf(n,f) n.times.map{ __send__ f } end
def ngs(n) nmapf n,:gs end
def ngi(n) nmapf n,:gi end
def ngss(n) nmapf n,:gss end
def ngis(n) nmapf n,:gis end
def arr2d(h,w,v=0) h.times.map{[v] * w} end
def for2p(hr,wr,&pr) hr.each{|i|wr.each{|j| yield(i,j)}} end
def nsum(n) n * (n + 1) / 2 end
def vcount(d,r=Hash.new(0)) d.inject(r){|r,e| r[e]+=1;r} end
############################################################

n, m = gis

b = [true] + [false] * m

n.times do
    x, *y = gis
    y.each do |j|
        b[j] = true
    end
end

puts b.all? ? :YES : :NO

n, m = gets.split.map(&:to_i)
btns = Array.new(m, false)
n.times do
  nums = gets.split.map(&:to_i)
  x = nums[0]
  next if x == 0
  nums[1..-1].each do |y|
    btns[y-1] = true
  end
end
puts btns.all?{|b| b} ? 'YES' : 'NO'

n, m = gets.split.map(&:to_i)
btns = Array.new(m, false)
n.times do
  gets.split.map(&:to_i).each do |b|
    btns[b-1] = true
  end
end
puts btns.all?{|b| b} ? 'YES' : 'NO'

n, m = gets.split.map(&:to_i)
buttons = []
n.times do
  buttons << gets.split.map(&:to_i)
end
puts buttons.flatten.uniq.size == m ? 'YES' : 'NO'

n, m = gets.split.map(&:to_i)
btns = []
n.times do
  btn = gets.split.map(&:to_i)[0..m-1]
  next if btn.first == 0
  btns << btn
end
puts btns.flatten.uniq.size == m ? 'YES' : 'NO'

n, m = gets.split.map(&:to_i)
btns = Array.new(m, false)
n.times do
  gets.split.map(&:to_i)[0..m-1].each do |b|
    next if b == 0
    btns[b-1] = true
  end
end
puts btns.all?{|b| b} ? 'YES' : 'NO'

n,m=gets.split.map{|e| e.to_i}
puts (STDIN.read.split.uniq.count==m)?"YES":"NO"

n, m = gets.split.map(&:to_i)
bulbs = Array.new(m, 0)
n.times do
  a = gets.split.map(&:to_i)
  a.each{|x| bulbs[x] = 1}
end
puts bulbs.inject(:+) == m ? 'YES' : 'NO'

require "set"

n, m = gets.split.map &:to_i
bulbs = Set.new
n.times do |_|
  bulbs.merge(gets.split.map &:to_i)
end

if bulbs == (1..m).to_set
  puts "YES"
else
  puts "NO"
end

#Good luk for the Contest 615, Problem: a
n, m = gets.strip.split.map(&:to_i)
blubs = Array.new(m, 1)

1.upto(n).each do |i|
	b = gets.strip.split.map(&:to_i)

	b.each do |e|
		blubs[e-1] = 0 if blubs[e-1] == 1
	end
	if blubs.all?{|item| item == 0}
		break
	end
end

puts   blubs.all?{|e| e == 0} ? 'YES' : 'NO'

#Good luk for the Contest 615, Problem: a
n, m = gets.strip.split.map(&:to_i)
blubs = Array.new(m, 1)

1.upto(n).each do |i|
	b = gets.strip.split.map(&:to_i)

	b.each do |e|
		blubs[e-1] = 0 if blubs[e-1] == 1
	end
end

puts   blubs.all?{|e| e == 0} ? 'YES' : 'NO'

a=gets.chomp.split(" ")
light=[]
1.upto(a[0].to_i){light +=gets.chomp.split(" ")}
light.uniq!
if light.length<a[1].to_i
	puts "NO"
elsif a[1]=="0" || (a[1]=="0" && a[0]=="0")
 	puts "NO"
else
	puts "YES"
end

a=gets.chomp.split(" ")
light=[]
1.upto(a[0].to_i){light +=gets.chomp.split(" ")}
light.uniq!
if light.length<a[1].to_i
	puts "No"
else
	puts "YES"
end

a=gets.chomp.split(" ")
light=[]
1.upto(a[0].to_i){light +=gets.chomp.split(" ")}
light.uniq!
if light.length<a[1].to_i
	puts "No"
elsif a[1]=="0"
 	puts "NO"
else
	puts "Yes"
end

n, m = gets.split.map(&:to_i)
btns = []
n.times do
  btns << gets.split.map(&:to_i)[0..m-1]
end
puts btns.flatten.uniq.size == m ? 'YES' : 'NO'

n, m = gets.split.map(&:to_i)
btns = Array.new(m, false)
n.times do
  gets.split.map(&:to_i)[0..m-1].each do |b|
    btns[b-1] = true
  end
end
puts btns.all?{|b| b} ? 'YES' : 'NO'