It's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one..There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is known that character "*" occurs no more than once in the pattern.Also, n query strings are given, it is required to determine for each of them if the pattern matches it or not.Everything seemed easy to Petya, but then he discovered that the special pattern characters differ from their usual meaning.A pattern matches a string if it is possible to replace each character "?" with one good lowercase English letter, and the character "*" (if there is one) with any, including empty, string of bad lowercase English letters, so that the resulting string is the same as the given string.The good letters are given to Petya. All the others are bad.

The first line contains a string with length from 1 to 26 consisting of distinct lowercase English letters. These letters are good letters, all the others are bad. The second line contains the pattern — a string s of lowercase English letters, characters "?" and "*" (1 ≤ |s| ≤ 105). It is guaranteed that character "*" occurs in s no more than once. The third line contains integer n (1 ≤ n ≤ 105) — the number of query strings. n lines follow, each of them contains single non-empty string consisting of lowercase English letters — a query string. It is guaranteed that the total length of all query strings is not greater than 105.

Print n lines: in the i-th of them print "YES" if the pattern matches the i-th query string, and "NO" otherwise. You can choose the case (lower or upper) for each letter arbitrary.

NoteIn the first example we can replace "?" with good letters "a" and "b", so we can see that the answer for the first query is "YES", and the answer for the second query is "NO", because we can't match the third letter.Explanation of the second example.   The first query: "NO", because character "*" can be replaced with a string of bad letters only, but the only way to match the query string is to replace it with the string "ba", in which both letters are good.  The second query: "YES", because characters "?" can be replaced with corresponding good letters, and character "*" can be replaced with empty string, and the strings will coincide.  The third query: "NO", because characters "?" can't be replaced with bad letters.  The fourth query: "YES", because characters "?" can be replaced with good letters "a", and character "*" can be replaced with a string of bad letters "x".

#!/usr/bin/env ruby
# encoding: utf-8
good = gets.to_str.chomp
pattern = gets.to_str
key = pattern.strip.gsub("?","["+good+"]").gsub("*","[^"+good+"]*")
rg = Regexp.new("^"+key+"$")

n = gets.to_i
n.times do
    buf = gets.to_str
    if rg =~ buf
        puts "YES"
    else
        puts "NO"
    end
end

# Codeforces My Practice
# author: Leonardone @ NEETSDKASU

gl = [false] * 256
gets.strip.each_char do |c|
    gl[c.swapcase.ord] = true
    gl[c.ord] = true
end
pt = ("[" + gets.strip + "]").split "*"
n = gets.to_i
if pt.size == 1
    px = pt[0]
    n.times do
        s = gets.strip
        if s.size != px.size - 2
            puts :NO
            next
        end
        ok = true
        s.size.times do |i|
            next if s[i] == px[i+1]
            if px[i+1] == '?'
                next if gl[s[i].ord]
            end
            ok = false
            break
        end
        puts ok ? :YES : :NO
    end
    exit
end

px, py = pt
n.times do
    s = gets.strip
    if s.size < px.size + py.size - 2
        puts :NO
        next
    end
    ok = true
    (px.size-1).times do |i|
        next if s[i] == px[i+1]
        if px[i+1] == '?'
            next if gl[s[i].ord]
        end
        ok = false
        break
    end
    if !ok
        puts :NO
        next
    end
    (py.size-1).times do |i|
        next if s[-i-1] == py[-i-2]
        if py[-i-2] == '?'
            next if gl[s[-i-1].ord]
        end
        ok = false
        break
    end
    if !ok
        puts :NO
        next
    end
    u = s.size - (px.size + py.size - 2)
    u.times do |i|
        next if !gl[s[i+px.size-1].ord]
        ok = false
        break
    end
    puts ok ? :YES : :NO
end

#!/usr/bin/env ruby
# encoding: utf-8
good = gets.to_str.chomp!
pattern = gets.to_str
key = ""
pattern.each_char do | c |
    if c == '?'
        key+="["+good+"]"
    elsif c == '*'
        key+="[^"+good+"]{0,1}"
    else
        key+=c
    end
end

ha = Regexp.new(key)

n = gets.to_i
n.times do | i |
    buf = gets.to_str
    m=ha.match(buf).to_s
    if m == nil
        puts("NO")
    elsif m == buf
        puts("YES")
    else
        puts("NO")
    end
end

# Try Codeforces
# author: Leonardone @ NEETSDKASU

gl = gets.strip
pt = gets.strip.gsub("?","[" + gl + "]").gsub("*", ".?")
rg = Regexp.compile("^" + pt + "$")
n = gets.to_i
n.times do
    s = gets.strip
    if s =~ rg
        puts "YES"
    else
        puts "NO"
    end
end

# Try Codeforces
# author: Leonardone @ NEETSDKASU

gl = gets.strip
pt = gets.strip.gsub("?","[" + gl + "]").gsub("*", ".*")
rg = Regexp.compile("^" + pt + "$", Regexp::IGNORECASE)
n = gets.to_i
n.times do
    s = gets.strip
    if s =~ rg
        puts "YES"
    else
        puts "NO"
    end
end

# Try Codeforces
# author: Leonardone @ NEETSDKASU

gl = gets.strip
pt = gets.strip.gsub("?","[" + gl + "]").gsub("*", ".?")
rg = Regexp.compile("^" + pt + "$", Regexp::IGNORECASE)
n = gets.to_i
n.times do
    s = gets.strip
    if s =~ rg
        puts "YES"
    else
        puts "NO"
    end
end


You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.You have to color this array in $$$k$$$ colors in such a way that:   Each element of the array should be colored in some color;  For each $$$i$$$ from $$$1$$$ to $$$k$$$ there should be at least one element colored in the $$$i$$$-th color in the array;  For each $$$i$$$ from $$$1$$$ to $$$k$$$ all elements colored in the $$$i$$$-th color should be distinct. Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the length of the array $$$a$$$ and the number of colors, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 5000$$$) — elements of the array $$$a$$$.

If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.

NoteIn the first example the answer $$$2~ 1~ 2~ 1$$$ is also acceptable.In the second example the answer $$$1~ 1~ 1~ 2~ 2$$$ is also acceptable.There exist other acceptable answers for both examples.

n, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
b = Array.new(5005) { [] }
a.each_with_index { |x, i| b[x] << i }

c = 1
ans = [-1] * n
b.each do |pos|
	puts('NO') + exit if pos.size > k
	pos.each do |i|
		ans[i] = c
		c = c < k ? c + 1 : 1
	end
end
puts 'YES', ans.join(' ')

input = STDIN.read.split("\n").map{|l| l.split(" ").map{|a| a.to_i}}
first = input.shift
ARR = input.shift
N = first[0]
COLORS = first[1]

NUM_USED_COLORS = {}
remained_color_i = 0

dic = {}
is_no = false

colored_arr = []

for i in ARR
  if !NUM_USED_COLORS.key?(i)
    NUM_USED_COLORS[i] = {}
  end

  if remained_color_i < COLORS
    NUM_USED_COLORS[i][remained_color_i] = true
    colored_arr.push(remained_color_i)
    remained_color_i = remained_color_i + 1
  else
    found = false
    for j in 0..(COLORS - 1)
      if !NUM_USED_COLORS[i].key?(j)
        NUM_USED_COLORS[i][j] = true
        colored_arr.push(j)
        found = true
        break
      end
    end
    if found == false
      is_no = true
    end
  end
  if is_no == true
    break
  end
end

if is_no
  puts 'NO'
else
  puts 'YES'
  puts colored_arr.map{|i| i + 1}.join(' ')
end

# Input
n, k = gets.split(" ").map { |e| e.to_i }
a = gets.split(" ").map { |e| e }

# Processing
count = Hash.new(0)
a.each { |n| count[n] += 1 }

current_color = Hash.new(count)
i = 1
count.each do |n, c|
  if c > k
    puts "NO"
    #puts "#{n} amount > k"
    exit
  end
  current_color[n] = i
  i = (i + c - 1) % k + 1
 end

c = Array.new(n) do |i|
  #puts current_color
  color = current_color[a[i]]
  current_color[a[i]] = current_color[a[i]] % k + 1
  color
end

# Output
puts "YES"
puts c.join(" ")

n, k = gets.split.map(&:to_i)
arr = gets.split.map(&:to_i)
h = Hash.new(0)
arr.each do |e|
  h[e] += 1
end
h.values.each do |v|
  if v > k
    puts "NO"
    exit
  end
end
cur_c = 0
prev_cur_c = 0
f = false
res = [0] * arr.size
mp = Array.new(k) {Array.new}
arr.each_with_index do |e, ind|
  while mp[cur_c].include?(e)
    if cur_c == prev_cur_c
      puts "NO"
      exit
    end
    cur_c = (cur_c + 1) % k
  end
  mp[cur_c] << e
  res[ind] = cur_c
  prev_cur_c = cur_c
  cur_c = (cur_c + 1) % k
end
puts "YES"
puts res.map{|x| x + 1}.join(" ")

N,K = gets.split.map(&:to_i)
ns = {}
is = []
a = gets.split.map(&:to_i)
a.each_with_index{ |x,i| ns[x] = (ns[x] || 0) + 1; is << [x,i]  }
if ns.values.max > K || N < K
    puts "NO"; exit
end
c = -1
is.sort!
#p is
is.each{ |x,i|
 a[i] = (c += 1) % K + 1
}
puts "YES", a.join(" ")

n, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
b = Array.new(10) { [] }
a.each_with_index { |x, i| b[x] << i }

c = 1
ans = [-1] * n
b.each do |pos|
	puts('NO') + exit if pos.size > k
	pos.each do |i|
		ans[i] = c
		c = c < k ? c + 1 : 1
	end
end
puts 'Yes', ans.join(' ')

# Input
n, k = gets.split(" ").map { |e| e.to_i }
a = gets.split(" ").map { |e| e }

# Processing
count = Hash.new(0)
current_color = Hash.new

a.each do |n|
  count[n] += 1
end

if count.length < k
  puts "NO"
  exit
end
count.each do |n, amount|
  if amount > k
    puts "NO"
    exit
  end
  current_color[n] = (current_color.length % k) + 1
end

c = Array.new(n) do |i|
  #puts current_color
  color = current_color[a[i]]
  current_color[a[i]] = current_color[a[i]] % k + 1
  color
end

# Output
puts "YES"
puts c.join(" ")

# Input
n, k = gets.split(" ").map { |e| e.to_i }
a = gets.split(" ").map { |e| e }

# Processing
count = Hash.new(0)
a.each { |n| count[n] += 1 }

current_color = Hash.new(count)
i = 1
count.each do |n, c|
  current_color[n] = i
  i = (i + c) % k + 1
 end

c = Array.new(n) do |i|
  #puts current_color
  color = current_color[a[i]]
  current_color[a[i]] = current_color[a[i]] % k + 1
  color
end

# Output
puts "YES"
puts c.join(" ")

# Input
n, k = gets.split(" ").map { |e| e.to_i }
a = gets.split(" ").map { |e| e }

# Processing
count = Hash.new(0)
a.each { |n| count[n] += 1 }

current_color = Hash.new(count)
i = 1
count.each do |n, c|
  if c > k
    puts "NO"
    #puts "#{n} amount > k"
    exit
  end
  current_color[n] = i
  i = (i + c) % k + 1
 end

c = Array.new(n) do |i|
  #puts current_color
  color = current_color[a[i]]
  current_color[a[i]] = current_color[a[i]] % k + 1
  color
end

# Output
puts "YES"
puts c.join(" ")

n, k = gets.split.map(&:to_i)
arr = gets.split.map(&:to_i)
h = Hash.new(0)
arr.each do |e|
  h[e] += 1
end
h.values.each do |v|
  if v > k
    puts "NO"
    exit
  end
end
cur_c = 0
prev_cur_c = 0
f = false
res = [0] * arr.size
mp = Array.new(k) {Array.new}
arr.each_with_index do |e, ind|
  while mp[cur_c].include?(e)
    cur_c += 1
    if cur_c == prev_cur_c
      puts "NO"
      exit
    end
  end
  mp[cur_c] << e
  res[ind] = cur_c
end
puts "YES"
puts res.map{|x| x + 1}.join(" ")

N,K = gets.split.map(&:to_i)
ns = {}
A = gets.split.map(&:to_i)
A.each{ |x| ns[x] = (ns[x] || 0) + 1 }
if ns.values.max > K
    puts "NO"; exit
end
puts "YES", A.map{ |x| (ns[x] -= 1) + 1 }.join(" ")


In the $$$2022$$$ year, Mike found two binary integers $$$a$$$ and $$$b$$$ of length $$$n$$$ (both of them are written only by digits $$$0$$$ and $$$1$$$) that can have leading zeroes. In order not to forget them, he wanted to construct integer $$$d$$$ in the following way:   he creates an integer $$$c$$$ as a result of bitwise summing of $$$a$$$ and $$$b$$$ without transferring carry, so $$$c$$$ may have one or more $$$2$$$-s. For example, the result of bitwise summing of $$$0110$$$ and $$$1101$$$ is $$$1211$$$ or the sum of $$$011000$$$ and $$$011000$$$ is $$$022000$$$;  after that Mike replaces equal consecutive digits in $$$c$$$ by one digit, thus getting $$$d$$$. In the cases above after this operation, $$$1211$$$ becomes $$$121$$$ and $$$022000$$$ becomes $$$020$$$ (so, $$$d$$$ won't have equal consecutive digits). Unfortunately, Mike lost integer $$$a$$$ before he could calculate $$$d$$$ himself. Now, to cheer him up, you want to find any binary integer $$$a$$$ of length $$$n$$$ such that $$$d$$$ will be maximum possible as integer.Maximum possible as integer means that $$$102 > 21$$$, $$$012 < 101$$$, $$$021 = 21$$$ and so on.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The first line of each test case contains the integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the length of $$$a$$$ and $$$b$$$. The second line of each test case contains binary integer $$$b$$$ of length $$$n$$$. The integer $$$b$$$ consists only of digits $$$0$$$ and $$$1$$$. It is guaranteed that the total sum of $$$n$$$ over all $$$t$$$ test cases doesn't exceed $$$10^5$$$.

For each test case output one binary integer $$$a$$$ of length $$$n$$$. Note, that $$$a$$$ or $$$b$$$ may have leading zeroes but must have the same length $$$n$$$.

NoteIn the first test case, $$$b = 0$$$ and choosing $$$a = 1$$$ gives $$$d = 1$$$ as a result.In the second test case, $$$b = 011$$$ so:   if you choose $$$a = 000$$$, $$$c$$$ will be equal to $$$011$$$, so $$$d = 01$$$;  if you choose $$$a = 111$$$, $$$c$$$ will be equal to $$$122$$$, so $$$d = 12$$$;  if you choose $$$a = 010$$$, you'll get $$$d = 021$$$.  If you select $$$a = 110$$$, you'll get $$$d = 121$$$.  We can show that answer $$$a = 110$$$ is optimal and $$$d = 121$$$ is maximum possible.In the third test case, $$$b = 110$$$. If you choose $$$a = 100$$$, you'll get $$$d = 210$$$ and it's the maximum possible $$$d$$$.In the fourth test case, $$$b = 111000$$$. If you choose $$$a = 101101$$$, you'll get $$$d = 212101$$$ and it's maximum possible $$$d$$$.In the fifth test case, $$$b = 001011$$$. If you choose $$$a = 101110$$$, you'll get $$$d = 102121$$$ and it's maximum possible $$$d$$$.

gets.to_i.times do
  n=gets.to_i
  b=gets.chomp.chars
  a=""
  d=0
  b.each do |bb|
    if bb=="1"
      if d==2
        a << "0"
        d=1
      elsif d==1
        a << "1"
        d=2
      else
        a << "1"
        d=2
      end
    else
      if d==2
        a << "1"
        d=1
      elsif d==1
        a << "0"
        d=0
      else
        a << "1"
        d=1
      end
    end
  end
  puts a
end


You are given three integers $$$n$$$, $$$d$$$ and $$$k$$$.Your task is to construct an undirected tree on $$$n$$$ vertices with diameter $$$d$$$ and degree of each vertex at most $$$k$$$, or say that it is impossible.An undirected tree is a connected undirected graph with $$$n - 1$$$ edges.Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree.Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex $$$u$$$ it is the number of edges $$$(u, v)$$$ that belong to the tree, where $$$v$$$ is any other vertex of a tree).

The first line of the input contains three integers $$$n$$$, $$$d$$$ and $$$k$$$ ($$$1 \le n, d, k \le 4 \cdot 10^5$$$).

If there is no tree satisfying the conditions above, print only one word "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), and then print $$$n - 1$$$ lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from $$$1$$$ to $$$n$$$. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1

f = 1
as = gets.split.map(&:to_i)
n = as[0]
d = as[1]
k = as[2]
tr = Array.new(n+5)
i = 0
while i<=n
      tr[i] = Array.new
      i+=1
end

node = 0
for i in 1..d
    if i>=n
       f = 0
       break
    end
    tr[i].push(i+1)
    tr[i+1].push(i)
    node = i+1
    if tr[i].size>k || tr[node].size>k
       f = 0
       break
    end
end

dep = Array.new(n+5)
vis = Array.new(n+5)
o = 0
while o<=n
      dep[o] = 0
      vis[o] = 0
      o+=1
end
cen1 = 0
cen2 = 0
mx_dep = 0
if node%2==1
   cen1 = (node+1)/2
   mx_dep = cen1-1
else
   cen1 = node/2
   cen2 = cen1+1
   mx_dep = cen1-1
end
dep[cen1] = 0
dep[cen2] = 0
vis[cen1] = 1
vis[cen2] = 1
c = 1
while node<n && c<=2 && f>0
      c+=1
      q=Array.new
      if cen1 > 0
         q.push(cen1)
         cen1 = 0
      elsif cen2>0
         q.push(cen2)
         cen2 = 0
      end

      while q.length > 0
            a = q.first
            q.shift
            if tr[a].size>k
               f = 0
               break
            end
            while tr[a].length<k && node<n && dep[a]<mx_dep
                  node+=1
                  tr[a].push(node)
                  tr[node].push(a)
            end

            for ii in tr[a]
                if vis[ii]>0
                   next
                end
                q.push(ii)
                vis[ii] = 1
                dep[ii] = dep[a] + 1
            end
      end

end

if f==0 || node!=n
   puts "NO"
else
   puts "YES"
   for z in (1..n)
    vis[z] = 0
   end
   for j in (1..n)
       for z in tr[j]
           if vis[z]>0 && vis[j]>0
              next
           end
           vis[z] = 1
           vis[j] = 1
           puts "#{j} #{z}"
       end
   end
end
=begin
=end

f = true
as = gets.split.map(&:to_i)
n = as[0]
d = as[1]
k = as[2]
tr = Array.new(n+5)
i = 0
while i<=n
      tr[i] = Array.new
      i+=1
end

node = 0
for i in 1..d
    if i>=n
       f = false
       break
    end
    tr[i].push(i+1)
    tr[i+1].push(i)
    node = i+1
    if tr[i].size>k || tr[node].size>k
       f = false
       break
    end
end

dep = Array.new(n+5)
vis = Array.new(n+5)
o = 0
while o<=n
      dep[o] = 0
      vis[o] = 0
      o+=1
end
cen1 = 0
cen2 = 0
mx_dep = 0
if node%2==1
   cen1 = (node+1)/2
   mx_dep = cen1-1
else
   cen1 = node/2
   cen2 = cen1+1
   mx_dep = cen1-1
end
dep[cen1] = 0
dep[cen2] = 0
vis[cen1] = 1
vis[cen2] = 1
c = 1
while node<n && c<=2 && f==true
      c+=1
      q=Array.new
      if cen1 > 0
         q.push(cen1)
         cen1 = 0
      elsif cen2>0
         q.push(cen2)
         cen2 = 0
      end

      while q.length > 0
            a = q.first
            q.shift
            if tr[a].size>k
               f = false
               break
            end
            while tr[a].length<k && node<n && dep[a]<mx_dep
                  node+=1
                  tr[a].push(node)
                  tr[node].push(a)
            end

            for ii in tr[a]
                if vis[ii]>0
                   next
                end
                q.push(ii)
                vis[ii] = 1
                dep[ii] = dep[a] + 1
            end
      end

end

if !f || node!=n
   puts "NO"
else
   puts "YES"
   for z in (1..n)
    vis[z] = 0
   end
   for j in (1..n)
       for z in tr[j]
           if vis[z]>0 && vis[j]>0
              next
           end
           vis[z] = 1
           vis[j] = 1
           puts "#{j} #{z}"
       end
   end
end
=begin
=end

f = true
as = gets.split.map(&:to_i)
n = as[0]
d = as[1]
k = as[2]
tr = Array.new(n+5)
i = 0
while i<=n
      tr[i] = Array.new
      i+=1
end

node = 0
for i in 1..d
    if i>=n
       f = false
       break
    end
    tr[i].push(i+1)
    tr[i+1].push(i)
    node = i+1
end

dep = Array.new(n+5)
vis = Array.new(n+5)
o = 0
while o<=n
      dep[o] = 0
      vis[o] = 0
      o+=1
end
cen1 = 0
cen2 = 0
mx_dep = 0
if node%2==1
   cen1 = (node+1)/2
   mx_dep = cen1-1
else
   cen1 = node/2
   cen2 = cen1+1
   mx_dep = cen1-1
end
dep[cen1] = 0
dep[cen2] = 0
vis[cen1] = 1
vis[cen2] = 1
c = 1
while node<n && c<=2
      c+=1
      q=Array.new
      if cen1 > 0
         q.push(cen1)
         cen1 = 0
      elsif cen2>0
         q.push(cen2)
         cen2 = 0
      end

      while q.length > 0
            a = q.first
            q.shift
            while tr[a].length<k && node<n && dep[a]<mx_dep
                  node+=1
                  tr[a].push(node)
                  tr[node].push(a)
            end

            for ii in tr[a]
                if vis[ii]>0
                   next
                end
                q.push(ii)
                vis[ii] = 1
                dep[ii] = dep[a] + 1
            end
      end

end

for z in (1..n)
    vis[z] = 0
end

if !f || node!=n
   puts "NO"
else
   puts "YES"
   for j in (1..n)
       for z in tr[j]
           if vis[z]>0 && vis[j]>0
              next
           end
           vis[z] = 1
           vis[j] = 1
           puts "#{j} #{z}"
       end
   end
end
=begin
=end

f = true
as = gets.split.map(&:to_i)
n = as[0]
d = as[1]
k = as[2]
tr = Array.new(n+5)
i = 0
while i<=n
      tr[i] = Array.new
      i+=1
end

node = 0
for i in 1..d
    if i>=n
       f = false
       break
    end
    tr[i].push(i+1)
    tr[i+1].push(i)
    node = i+1
end

dep = Array.new(n+5)
vis = Array.new(n+5)
o = 0
while o<=n
      dep[o] = 0
      vis[o] = 0
      o+=1
end
cen1 = 0
cen2 = 0
mx_dep = 0
if node%2==1
   cen1 = (node+1)/2
   mx_dep = cen1-1
else
   cen1 = node/2
   cen2 = cen1+1
   mx_dep = cen1-1
end
dep[cen1] = 0
dep[cen2] = 0
vis[cen1] = 1
vis[cen2] = 1
c = 1
while node<n && c<=2
      c+=1
      q=Array.new
      if cen1 > 0
         q.push(cen1)
         cen1 = 0
      elsif cen2>0
         q.push(cen2)
         cen2 = 0
      end

      while q.length > 0
            a = q.first
            q.shift
            if tr[a].length>k
               f=0
            end
            while tr[a].length<k && node<n && dep[a]<mx_dep
                  node+=1
                  tr[a].push(node)
                  tr[node].push(a)
            end

            for ii in tr[a]
                if vis[ii]>0
                   next
                end
                q.push(ii)
                vis[ii] = 1
                dep[ii] = dep[a] + 1
            end
      end

end

for z in (1..n)
    vis[z] = 0
end

if !f || node!=n
   puts "NO"
else
   puts "YES"
   for j in (1..n)
       for z in tr[j]
           if vis[z]>0 && vis[j]>0
              next
           end
           vis[z] = 1
           vis[j] = 1
           puts "#{j} #{z}"
       end
   end
end
=begin
=end


You are given an array $$$a[0 \ldots n-1]$$$ of length $$$n$$$ which consists of non-negative integers. Note that array indices start from zero.An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all $$$i$$$ ($$$0 \le i \le n - 1$$$) the equality $$$i \bmod 2 = a[i] \bmod 2$$$ holds, where $$$x \bmod 2$$$ is the remainder of dividing $$$x$$$ by 2.For example, the arrays [$$$0, 5, 2, 1$$$] and [$$$0, 17, 0, 3$$$] are good, and the array [$$$2, 4, 6, 7$$$] is bad, because for $$$i=1$$$, the parities of $$$i$$$ and $$$a[i]$$$ are different: $$$i \bmod 2 = 1 \bmod 2 = 1$$$, but $$$a[i] \bmod 2 = 4 \bmod 2 = 0$$$.In one move, you can take any two elements of the array and swap them (these elements are not necessarily adjacent).Find the minimum number of moves in which you can make the array $$$a$$$ good, or say that this is not possible.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 40$$$) — the length of the array $$$a$$$. The next line contains $$$n$$$ integers $$$a_0, a_1, \ldots, a_{n-1}$$$ ($$$0 \le a_i \le 1000$$$) — the initial array.

For each test case, output a single integer — the minimum number of moves to make the given array $$$a$$$ good, or -1 if this is not possible.

NoteIn the first test case, in the first move, you can swap the elements with indices $$$0$$$ and $$$1$$$, and in the second move, you can swap the elements with indices $$$2$$$ and $$$3$$$.In the second test case, in the first move, you need to swap the elements with indices $$$0$$$ and $$$1$$$.In the third test case, you cannot make the array good.

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i)
	b = (0...n).map { _1 % 2 }
	if [0, 1].all? { |k| a.count { _1 % 2 == k } == b.count { _1 % 2 == k } }
		puts (0...n).count { a[_1] % 2 != b[_1] % 2 } / 2
	else
		puts -1
	end
end

t = gets.to_i
t.times do
	n = gets.to_i
	ill_evens = 0
	ill_odds = 0
	odds = []
	gets.split.each_with_index do |w, i|
		if w.to_i.even?
			ill_evens += 1 if i.odd?
		else
			ill_odds += 1 if i.even?
		end
	end

	if ill_evens != ill_odds
		p -1
		next
	end

	p ill_evens

end

def count_arr(a,n)

    odds = 0
    evens = 0
    i=0

    while i<n
        evens +=1 if(i%2==0 && a[i]%2==1)
        odds += 1 if(i%2==1 && a[i]%2==0)
        i+=1
    end

    return [odds,evens]
end

gets.chomp.to_i.times do

    n = gets.chomp.to_i

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

    arr = count_arr(a,n)

    if(arr[0]==arr[1])
        puts arr[0]
    else
        puts -1
    end
end

n = gets.chomp.to_i
(0...n).each do |i|
    s = gets.chomp.to_i
    a = gets.chomp.split(" ").map(&:to_i)
    asize = a.size
    count1 = 0
    count2 = 0
    a.each_with_index do |item,j|
        if j % 2 == 0
            if item % 2 != 0
                count1 += 1
            end
        end
        if j % 2 != 0
            if item % 2 == 0
                count2 += 1
            end
        end
    end
    if count1 != count2
        puts "-1"
    else
        puts count1
    end
end

gets.to_i.times {
  gets
  data = gets.split.map { |v| v.to_i }
  s = Array.new(2, 0)
  for i in 0...data.size()
    if (i % 2) != (data[i] % 2)
      s[i % 2] += 1
    end
  end
  if s[0] != s[1]
    puts -1
  else
    puts s[0]
  end
}

data_lines = gets.chomp
result = []
(1..data_lines.to_i).each do
	length_s = gets.chomp.to_i
	s = gets.chomp.split(" ")
	odd_pos_count = length_s / 2
	odd_val_count = 0
	odd_val_not_place = 0
	even_val_not_place = 0
	(0..(length_s-1)).each do |index|
		if s[index].to_i % 2 == 1
			odd_val_count += 1
			if index % 2 == 0
				odd_val_not_place += 1
			end
		else
			if index % 2 == 1
				even_val_not_place += 1
			end
		end
	end
	if odd_val_not_place == 0 && even_val_not_place == 0
		result.push 0
		next
	end
	if odd_pos_count != odd_val_count
		result.push -1
		next
	end
	result.push odd_val_not_place
end
result.each do |res|
	puts res
end

t = gets.to_i

for i in 0..t-1

    n = gets.to_i
    array = gets.chomp.split
    k1 = 0
    k2 = 0

    for i in 0..n-1
        elt = array[i].to_i

        if elt%2 != (i)%2
            if elt%2 == 0
                k1+=1
            else
                k2+=1
            end
        end

    end

    puts k1 == k2 ? k1 : '-1'

end

def solve(arr_num)
	wrong_els = arr_num
		.map
		.with_index { |n,i| [n % 2 == i % 2, i.even?] }
		.reject { |is_good, _is_even| is_good }

	odd_els, even_els = wrong_els.partition { |is_good, is_even| is_even }
	if odd_els.size == even_els.size
		odd_els.size
	else
		-1
	end
end

inputs = ARGF.each_line.drop(1).map(&:strip).to_a

inputs.each_slice(2).map(&:last).each do |i|
	arr_num = i.split.map(&:to_i)
	puts solve(arr_num)
end

n = gets.chomp.to_i
n.times do
	t = gets.chomp.to_i
	arr = gets.chomp.split.map{|a| a.to_i % 2}
	iar = (0..arr.length-1).to_a.map{|i| i % 2}
	cnt0 = 0
	cnt1 = 0
	arr.length.times do |i|
		if arr[i] != iar[i]
			if arr[i] == 0
				cnt0 += 1
			else
				cnt1 += 1
			end
		end
	end

	# p arr
	# p iar
	# puts cnt0
	# puts cnt1
	if cnt0 == 0 && cnt1 == 0
		puts 0
	elsif cnt0 == cnt1
		puts cnt0
	else
		puts -1
	end
end

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

  res = [0, 0]

  a.each_with_index { |v, i| res[i%2] += 1 if i.odd? != v.odd? }

  puts -1 if res.first != res.last
  puts res.first if res.first == res.last
end

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i)
	m = (0...n).count { _1 % 2 != a[_1] % 2 }
	if m.even?
		puts m / 2
	else
		puts -1
	end
end

def count_arr(a,n)

    odds = 0
    evens = 0
    count = 0
    i=0

    while i<n

        if(a[i]%2==0)
            evens+=1
        else
            odds+=1
        end

        count +=1 if(i%2==0 && a[i]%2==1)
        i+=1
    end

    return [odds,evens,count]
end

gets.chomp.to_i.times do

    n = gets.chomp.to_i

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

    arr = count_arr(a,n)
    if(n%2==0)
        if(arr[0]!=arr[1])
            puts -1
        else
            puts arr[2]
        end
    else
        if(arr[0] >= arr[1])
            puts -1
        else
            puts arr[2]
        end
    end
end

gets.chomp.to_i.times do

    n = gets.chomp.to_i

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

    i=0
    count =0
    while i<n
       count += 1 if(i%2 != a[i]%2)
       i+=1
    end

    if(count %2 != 0)
        puts -1
    else
        puts count/2
    end
end

gets.to_i.times {
  gets
  data = gets.split.map { |v| v.to_i }
  s = 0
  for i in 0...data.size()
    if (i % 2) != (data[i] % 2)
      s += 1
    end
  end
  if s %2 == 1
    puts -1
  else
    puts s / 2
  end
}

n = gets.chomp.to_i
n.times do
	t = gets.chomp.to_i
	arr = gets.chomp.split.map{|a| a.to_i % 2}
	iar = (0..arr.length-1).to_a.map{|i| i % 2}
	cnt = 0
	arr.length.times do |i|
		cnt += 1 if arr[i] != iar[i]
	end
	if cnt % 2 == 1
		puts -1
	else
		puts cnt / 2
	end
end


William has a favorite bracket sequence. Since his favorite sequence is quite big he provided it to you as a sequence of positive integers $$$c_1, c_2, \dots, c_n$$$ where $$$c_i$$$ is the number of consecutive brackets "(" if $$$i$$$ is an odd number or the number of consecutive brackets ")" if $$$i$$$ is an even number.For example for a bracket sequence "((())()))" a corresponding sequence of numbers is $$$[3, 2, 1, 3]$$$.You need to find the total number of continuous subsequences (subsegments) $$$[l, r]$$$ ($$$l \le r$$$) of the original bracket sequence, which are regular bracket sequences.A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not.

The first line contains a single integer $$$n$$$ $$$(1 \le n \le 1000)$$$, the size of the compressed sequence. The second line contains a sequence of integers $$$c_1, c_2, \dots, c_n$$$ $$$(1 \le c_i \le 10^9)$$$, the compressed sequence.

Output a single integer — the total number of subsegments of the original bracket sequence, which are regular bracket sequences. It can be proved that the answer fits in the signed 64-bit integer data type.

NoteIn the first example a sequence (((()(()))( is described. This bracket sequence contains $$$5$$$ subsegments which form regular bracket sequences:  Subsequence from the $$$3$$$rd to $$$10$$$th character: (()(()))  Subsequence from the $$$4$$$th to $$$5$$$th character: ()  Subsequence from the $$$4$$$th to $$$9$$$th character: ()(())  Subsequence from the $$$6$$$th to $$$9$$$th character: (())  Subsequence from the $$$7$$$th to $$$8$$$th character: () In the second example a sequence ()))(()(()))) is described.In the third example a sequence ()()(()) is described.

n = gets.to_i
a = gets.split.map {|i| i.to_i}
res = 0
mopen = 0
sopen = 0
t, x = 0, 0
#each non starting must have a closing
#each non ending must have an opening
for i in 0...a.length
  next if i.odd?
  sopen = a[i]
  mopen =0
  for j in (i + 1)...a.length
    if j.odd?
      #optimize
      t = [mopen,x = a[j]].min
      mopen -= t
      x -= t
      if x >= 0
        res += [sopen, x].min
        sopen -= x
        res += 1 if mopen == 0 && j != i + 1
        break if sopen < 0
      end
    else
      mopen += a[j]
    end
    #puts "i: #{i}, j: #{j}, sopen: #{sopen}, mopen: #{mopen}, res: #{res}"
  end
end
puts res

n = gets.to_i
a = gets.split.map {|i| i.to_i}
res = 0
mopen = 0
sopen = 0
t, x = 0, 0
#each non starting must have a closing
#each non ending must have an opening
for i in 0...a.length
  next if i.odd?
  sopen = a[i]
  for j in (i + 1)...a.length
    if j.odd?
      #optimize
      t = [mopen,x = a[j]].min
      mopen -= t
      x -= t
      if x >= 0
        res += [sopen, x].min
        sopen -= x
        res += 1 if mopen == 0 && j != i + 1
        break if sopen < 0
      end
    else
      mopen += a[j]
    end
    #puts "i: #{i}, j: #{j}, sopen: #{sopen}, mopen: #{mopen}, res: #{res}"
  end
end
puts res


A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.

The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'.  It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.

For each test case given in the input print the answer in the following format:   If it is impossible to create a beautiful string, print "-1" (without quotes);  Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.

NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".

ans = []
st = Time.now
t = ["a","b","c"]
n = gets.to_i

n.times do|d_i|
  s = gets.split("")

  (s.size - 1).times do |i|
    if s[i] == "?"
      t.each do |drf|
        next if drf == s[i-1]
        next if drf == s[i+1]
        s[i] = drf
        break
      end
    else
      if s[i] == s[i+1]
        s = [-1]
        break
      end
    end
  end
  ans.push(s.join)
end
puts ans

gets.strip.to_i.times {
    x = gets.strip.split('')
    if x.size == 1
        puts x[0] == "?" ? "a" : x[0]
        next
    end
    c = ["a", "b", "c"]
    x.each_with_index { |element, index|
        if index == 0
            if x[index] == "?"
                if x[index + 1] == "?"
                    x[index] = "a"
                    next
                end
                x[index] = c[(c.find_index(x[index + 1]) + 1) % 3]
            end
        elsif index == x.size - 1
            if x[index] == "?"
                x[index] = c[(c.find_index(x[index - 1]) + 1) % 3]
            end
        else
            if x[index] == "?"
                if x[index + 1] == "?"
                    x[index] = c[(c.find_index(x[index - 1]) + 1) % 3]
                else
                    x[index] = "c" if x[index - 1] == "a" && x[index + 1] == "b" || x[index - 1] == "b" && x[index + 1] == "a"
                    x[index] = "a" if x[index - 1] == "b" && x[index + 1] == "c" || x[index - 1] == "c" && x[index + 1] == "b"
                    x[index] = "b" if x[index - 1] == "c" && x[index + 1] == "a" || x[index - 1] == "a" && x[index + 1] == "c"
                    x[index] = c[(c.find_index(x[index - 1]) + 1) % 3] if x[index - 1] == x[index + 1]
                end
            end
        end
    }
    flg = false
    x.each_with_index { |element, index|
        next if index == 0
        if x[index] == x[index - 1]
            flg = true
            break
        end
    }
    puts flg ? -1 : x.join
}

ans = []
st = Time.now
t = ["a","b","c"]
n = gets.to_i

n.times do|d_i|
  s = gets.split("")

  (s.size - 1).times do |i|
    if s[i] == "?"
      t.each do |drf|
        next if drf == s[i-1]
        next if drf == s[i+1]
        s[i] = drf
        break
      end
    else
      if s[i] == s[i+1]
        s = [-1]
        break
      end
    end
  end
  if(n == 1)
    puts Time.now - st
    exit
  end
  ans.push(s.join)
end
puts ans

n = gets.to_i
n.times do
  p s = gets
  ns = s.size
  if s[0] == "?"
    ("a".."c").each do |cc|
      s[0] = cc if cc != s[1]
    end
  else
    if s[0] == s[1]
      p -1
      next
    end
  end

  (1...(ns-1)).each do |i|
    c = s[i]
    if c == "?"
      ("a".."c").each do |cc|
        if cc != s[i-1]
          if cc != s[i+1]
            s[i] = cc
            break
          else
            next
          end
        end
      end
    else
      if s[i] == s[i+1]
        s = "-1"
        break
      end
    end
  end
  puts s
end

#exec({'RUBY_THREAD_VM_STACK_SIZE'=>'100000000'},'/usr/bin/ruby', $0) if !ENV['RUBY_THREAD_VM_STACK_SIZE']

require 'prime'

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

def big(a,b) return (a>b)? a:b end

def small(a,b) return (a<b)? a:b end

n = inp[0]
d = []
n.times{d<<gets}
n.times do |di|
  s=d[di]
  ans = na(n,0)
  ns = s.size
  f = false
  ns.times do |i|
    if(s[i] == "?")
      ("a".."c").each do |cc|
        if i==0 or cc != s[i-1]
          if(i+1 == ns or cc != s[i+1])
            ans[i] = cc
            s[i] = cc
            break
          else
            next
          end
        end
      end
    else
      if i < ns and s[i] == s[i+1]
        f = true
        p -1
        break
      else
        ans[i] = s[i]
      end
    end
  end
  unless f
    puts ans.join
  end
end

#exec({'RUBY_THREAD_VM_STACK_SIZE'=>'100000000'},'/usr/bin/ruby', $0) if !ENV['RUBY_THREAD_VM_STACK_SIZE']

require 'prime'

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

def big(a,b) return (a>b)? a:b end

def small(a,b) return (a<b)? a:b end

n = inp[0]
d = []
n.times{d<<gets}
n.times do |di|
  s=d[di]
  ans = na(n,0)
  ns = s.size
  f = false
  ns.times do |i|
    if(s[i] == "?")
      ("a".."c").each do |cc|
        if i==0 or cc != s[i-1]
          if(i+1 == ns or cc != s[i+1])
            ans[i] = cc
            s[i] = cc
            break
          else
            next
          end
        end
      end
    else
      if i < ns and s[i] == s[i+1]
        f = true
        p -1
        break
      else
        ans[i] = s[i]
      end
    end
  end
  unless f
    ans.each do |c|
      print c
    end
  end
end

n = gets.to_i
d = []
t = ["a","b","c"]
n.times do |di|
  s = ["?ab?a??cas"]*10
  s = s.join
  ns = s.size
  ans = ""
  if (s[0] == "?")
    t.each do |cc|
      s[0] = cc if(ns == 1 or cc != s[1])
    end
  else
    if s[0] == s[1]
      p -1
      next
    end
  end
  if s[-1] == "?"
    t.each do |cc|
      s[-1] = cc if cc != s[-2]
    end
  end

  (1...(ns-1)).each do |i|
    c = s[i]
    if(c == "?")
      t.each do |cc|
        if cc != s[i-1]
          if(cc != s[i+1])
            s[i] = cc
            break
          else
            next
          end
        end
      end
    else
      if s[i] == s[i+1]
        s = -1
        break
      end
    end
  end
  puts s
end

ans = []
st = Time.now
t = ["a","b","c"]
n = gets.to_i

n.times do|d_i|
  s = gets
  if(n == 1)
    puts Time.now - st
    exit
  end
  (s.size - 1).times do |i|
    if s[i] == "?"
      t.each do |drf|
        next if drf == s[i-1]
        next if drf == s[i+1]
        s[i] = drf
        break
      end
    else
      if s[i] == s[i+1]
        s = "-1"
        break
      end
    end
  end
  if(Time.now - st > 0.8)
    puts 12
  end
  ans.push(s)
end
puts ans


One day Vasya was on a physics practical, performing the task on measuring the capacitance. He followed the teacher's advice and did as much as n measurements, and recorded the results in the notebook. After that he was about to show the results to the teacher, but he remembered that at the last lesson, the teacher had made his friend Petya redo the experiment because the largest and the smallest results differed by more than two times. Vasya is lazy, and he does not want to redo the experiment. He wants to do the task and go home play computer games. So he decided to cheat: before Vasya shows the measurements to the teacher, he will erase some of them, so as to make the largest and the smallest results of the remaining measurements differ in no more than two times. In other words, if the remaining measurements have the smallest result x, and the largest result y, then the inequality y ≤ 2·x must fulfill. Of course, to avoid the teacher's suspicion, Vasya wants to remove as few measurement results as possible from his notes.Help Vasya, find what minimum number of measurement results he will have to erase from his notes so that the largest and the smallest of the remaining results of the measurements differed in no more than two times.

The first line contains integer n (2 ≤ n ≤ 105) — the number of measurements Vasya made. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 5000) — the results of the measurements. The numbers on the second line are separated by single spaces.

Print a single integer — the minimum number of results Vasya will have to remove.

NoteIn the first sample you can remove the fourth and the sixth measurement results (values 8 and 7). Then the maximum of the remaining values will be 5, and the minimum one will be 3. Or else, you can remove the third and fifth results (both equal 3). After that the largest remaining result will be 8, and the smallest one will be 4.

$stdin = File.open("input.txt")
$stdout = File.open("output.txt","w")

n = gets.chomp.to_i
H = {}
gets.chomp.split.each do |c|
	key = c.to_i
	if H.has_key? key
		H[key] += 1
	else
		H[key] = 1
	end
end
A = Array.new(5000,0)
for c in 1..5000 do
	A[c] = A[c-1] + (H.has_key?(c) ? H[c] : 0)
end
sol = 99999
for c in 1..2500 do
	sol = [sol , A[c-1] + (A[5000] - A[c*2])].min
end
puts sol

# -*- encoding: utf-8 -*-

$stdin = File.open("input.txt")
$stdout = File.open("output.txt", "w")

n = gets.chomp.to_i
c = {}
gets.chomp.split(" ").each do |n|
  key = n.to_i
  if c.has_key? key
    c[key] += 1
  else
    c[key] = 1
  end
end

field = Array.new(5000, 0)

for i in 1 .. 5000 do
  field[i] = field[i - 1] + (c.has_key?(i) ? c[i] : 0)
end
ans = 99999
for i in 1 .. 2500 do
  ans = [ans, field[i - 1] + (field[5000] - field[i * 2])].min
end

puts ans


Timur has a stairway with $$$n$$$ steps. The $$$i$$$-th step is $$$a_i$$$ meters higher than its predecessor. The first step is $$$a_1$$$ meters higher than the ground, and the ground starts at $$$0$$$ meters.   The stairs for the first test case. Timur has $$$q$$$ questions, each denoted by an integer $$$k_1, \dots, k_q$$$. For each question $$$k_i$$$, you have to print the maximum possible height Timur can achieve by climbing the steps if his legs are of length $$$k_i$$$. Timur can only climb the $$$j$$$-th step if his legs are of length at least $$$a_j$$$. In other words, $$$k_i \geq a_j$$$ for each step $$$j$$$ climbed.Note that you should answer each question independently.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains two integers $$$n, q$$$ ($$$1 \leq n, q \leq 2\cdot10^5$$$) — the number of steps and the number of questions, respectively. The second line of each test case contains $$$n$$$ integers ($$$1 \leq a_i \leq 10^9$$$) — the height of the steps. The third line of each test case contains $$$q$$$ integers ($$$0 \leq k_i \leq 10^9$$$) — the numbers for each question. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2\cdot10^5$$$, and the sum of $$$q$$$ does not exceed $$$2\cdot10^5$$$.

For each test case, output a single line containing $$$q$$$ integers, the answer for each question. Please note, that the answer for some questions won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).

NoteConsider the first test case, pictured in the statement.   If Timur's legs have length $$$1$$$, then he can only climb stair $$$1$$$, so the highest he can reach is $$$1$$$ meter.  If Timur's legs have length $$$2$$$ or $$$4$$$, then he can only climb stairs $$$1$$$, $$$2$$$, and $$$3$$$, so the highest he can reach is $$$1+2+1=4$$$ meters.  If Timur's legs have length $$$9$$$ or $$$10$$$, then he can climb the whole staircase, so the highest he can reach is $$$1+2+1+5=9$$$ meters.  In the first question of the second test case, Timur has no legs, so he cannot go up even a single step. :(

t=gets.to_i
t.times do
    n,q= gets.split.map(&:to_i)
    arr=gets.split.map(&:to_i)
    qs=gets.split.map(&:to_i)
    rslt=[]
    cur,sum=0,0
    arr.each do |x|
        if cur>=x
            sum+=x
        else
            rslt.push [cur,sum]
            cur=x
            sum+=x
        end
    end
    rslt.push [cur,sum]
    rslt.push [sum,sum]
    i=0
    while i<rslt.length-1 do
        rslt[i][0]=rslt[i+1][0]-1
        i+=1
    end
    rslt[-1][0]=10000000000000000
    qs.each_with_index do |x, idx|
        print (rslt.bsearch{|y,z|y>=x}[1])
        if idx==qs.length-1
            puts
        else
            print ' '
        end
    end
end

gets.to_i.times do
  n,q=gets.split.map(&:to_i)
  a=gets.split.map(&:to_i)
  m=Array.new(n+1)
  m[0]=0
  n.times {|i| m[i+1]=[m[i],a[i]].max}
  s=[0]
  a.each {|i| s << s[-1]+i}
  k=gets.split.map(&:to_i)
  puts k.map {|i|
    ans=m.bsearch_index {|j| j>i}
    ans.nil? ? s[n] : s[ans-1]
  }*' '
end


A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.

The first line contains a positive integer n (1 ≤ n ≤ 100), then follow n lines containing three integers each: the xi coordinate, the yi coordinate and the zi coordinate of the force vector, applied to the body ( - 100 ≤ xi, yi, zi ≤ 100).

Print the word "YES" if the body is in equilibrium, or the word "NO" if it is not.

n = $stdin.gets
sumx = 0
sumy = 0
sumz = 0
while line = $stdin.gets
  x,y,z = line.strip.split(' ').map{|v| v.to_i}
  sumx += x
  sumy += y
  sumz += z
end
if(sumx == 0 && sumy == 0 && sumz == 0)
  print "YES"
else
  print "NO"
end

n = gets.chomp.to_i
total_x, total_y, total_z = 0, 0, 0
n.times do
    x, y, z = gets.chomp.split(" ").map(&:to_i)
    total_x += x
    total_y += y
    total_z += z
end

if total_x == 0 && total_y == 0 && total_z == 0
    puts "YES"
else
    puts "NO"
end

puts gets.to_i.times.map{gets.split.map(&:to_i)}.transpose.all?{|a|a.inject(0){|r,j|r+j}==0} ? "YES" : "NO"

n = gets.chomp.to_i

a = b = c = 0

n.times{
	input = gets.chomp.split(" ")
	a += input[0].to_i
	b += input[1].to_i
	c += input[2].to_i
}

if a==0 && b==0 && c==0
	puts "YES"
else
	puts "NO"
end

n = readline.to_i
sum = [0,0,0]
i = 0
while i < n do
  a = readline.split(' ')
  sum[0] += a[0].to_i
  sum[1] += a[1].to_i
  sum[2] += a[2].to_i
  i += 1
end
puts (if(sum[0] == 0 && sum[1] == 0 && sum[2] == 0)
  begin
    "YES"
  end
else
  begin
    "NO"
  end
end)

n = gets.to_i
a =[]
b=[]
res = 0
d = 0

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

def check(c,d)
  sum = 0
  sum = sum+c[d]
end

b.each do |i|
    res = res + check(i,0)
    d = d+1
end

if res == 0
  puts "YES"
else
  puts "NO"
end

# https://codeforces.com/problemset/problem/69/A
n = gets.chomp.to_i
forcex = 0
forcey = 0
forcez = 0
1.upto(n) do |force|
    x, y, z = gets.chomp.split(" ").map(&:to_i)
    forcex += x
    forcey += y
    forcez += z
end

if forcex == 0 && forcey == 0 && forcez == 0
    puts "YES"
else
    puts "NO"
end

class Euler
  n=gets.to_i;
  k1=0;
  k2=0;
  k3=0;
  (1..n).each do
    a=gets;
    m=a.split(" ");
    k1+=m[0].to_i;
    k2+=m[1].to_i;
    k3+=m[2].to_i;
  end
  if (k1==k2 && k2==k3 && k3==0)
  puts("YES");
else
  puts("NO");
  end
end

x=0
y=0
z=0

gets.to_i.times{

x+=gets(' ').to_i
y+=gets(' ').to_i
z+=gets.to_i

}

if x == 0 && y == 0 && z == 0
print "YES\n"
else
print "NO\n"
end

n = gets.to_i

result = [0, 0, 0]

1.upto(n) do
  vec = gets.split(' ').map(&:to_i)
  0.upto(2) { |i| result[i] += vec[i] }
end

puts result.all? { |n| n == 0 } ? 'YES' : 'NO'

sum = [0, 0, 0]

n = gets.to_i

for str in $stdin.each_line.take(n)
  arr = str.split(' ').map &:to_i
  for i in 0..2
    sum[i] += arr[i]
  end
end

if sum.all? { |x| x == 0 }
  puts "YES"
else
  puts "NO"
end

n = gets.to_i
s1 = 0
s2 = 0
s3 = 0
while (n > 0)
    a,b,c = gets.split(' ').map{|s| s.to_i}
    s1 += a
    s2 += b
    s3 += c
    n -= 1
end

if (s1 == 0 && s2 == 0 && s3 == 0) then puts 'YES'
else puts 'NO'
end

t = gets.to_i
sum = [0,0,0]
for i in 1..t
 b = gets.chomp.split().map { |e| e.to_i  }
 for i in 0..2
     sum[i] +=  b[i]
 end
end

puts sum.uniq.size <= 1 && sum.inject(0, :+) == 0 ? 'YES' : 'NO'

n = gets.chomp.to_i
vec = [0, 0, 0]
n.times.each do |_i|
  force = gets.chomp.split(/ /).map(&:to_i)
  vec[0] += force[0]
  vec[1] += force[1]
  vec[2] += force[2]
end
puts vec.uniq.count > 1 ? 'NO' : vec[0] == 0 ? 'YES' : 'NO'

gets
puts $<.map{|_|_.split}.transpose.all?{|_|0==eval(_*?+)}? "YES" : "NO"

require"matrix"
gets
puts $<.map{|_|Vector[*_.split.map(&:to_i)]}.inject(:+).r==0? "YES" : "NO"

gets; input, x, y, z = STDIN.read.split("\n").map{ |i| i.split.map! &:to_i  }, 0, 0, 0

input.each { |i| x += i[0]; y += i[1]; z += i[2] }
print [x, y, z].join == "000" ? :YES : :NO

x,y,z=0,0,0
gets.to_i.times do
    a=gets.split
    x+=a[0].to_i
    y+=a[0].to_i
    z+=a[0].to_i
end
if x==0&&y==0&&z==0
    puts "YES"
else
    puts "NO"
end

n = gets.to_i
sum = [0, 0, 0]
n.times do
	f = gets.split.map { |x| x.to_i }
	3.times do |i|
		sum[i] += f[i]
	end
end

if sum.count(0) == 3
	puts 'YES'
else
	puts 'NO'
end

vectorNum = gets.chomp.to_i

totals = Array.new(3) { |elem| elem = 0 }

vectorNum.times do
	vector = gets.chomp.split(' ').map(&:to_i)
	for i in (0...vector.length)
		totals[i] += vector[i]
	end
end

# print totals

ans = if totals.all? { |elem| elem == 0 }
	'YES'
else
	'NO'
end

puts ans

puts %w[YES NO][STDIN.readlines.drop(1).reduce([0, 0, 0]) { |r, x| r.zip(x.split(' ').map(&:to_i)).map { |a, b| a + b } } == [0, 0, 0] ? 0 : 1]

n = gets.to_i
ar = [0, 0, 0]
n.times do
  gets.split(' ').map.with_index(0){|x,id| ar[id]+=x.to_i}
end
if ar.all?{|x| x==0}
  puts "YES"
else
  puts "NO"
end

matrix = Array.new
gets.to_i.times do
matrix.push(gets.split(" ").map(&:to_i))
end

for lines in matrix.transpose
  res = lines.inject { |sum, i| sum += i }
  (res == 0 )?(res):(puts "NO"; exit)
end
puts "YES"

    n = gets.to_i
    a = 0
    b = 0
    c = 0
    n.times do
        nums = gets.split(" ").map(&:to_i)
        a+=nums[0]
        b+=nums[1]
        c+=nums[2]
    end

    if(a==0 and b==0 and c==0)
        puts("YES")
    else
        puts("NO")
    end

n = gets.to_i

sumx = 0
sumy = 0
sumz = 0

n.times do |i|
    s = gets.split.map{|i| i.to_i}
    sumx += s[0]
    sumy += s[1]
    sumz += s[2]
end

if sumx != 0 || sumy != 0 || sumz != 0 then
    puts "NO"
else
    puts "YES"
end

forces_count = gets.to_i

force_vectors = []

forces_count.times do
  force_vectors.push(gets.split.map(&:to_i))
end

resultant_force = [0, 0, 0]

force_vectors.each do |force|
  resultant_force[0] += force[0]
  resultant_force[1] += force[1]
  resultant_force[2] += force[2]
end

if resultant_force[0] | resultant_force[1] | resultant_force[2] == 0
  puts "YES"
else
  puts "NO"
end

x, y, z = 0, 0, 0

gets.to_i.times do
  a, b, c = gets.split.map(&:to_i)
  x += a
  y += b
  z += c
end

puts [0, 0, 0] == [x, y, z] ? :YES : :NO

x, y, z = 0, 0, 0
gets.to_i.times do
	a, b, c = gets.split.map(&:to_i)
	x += a
	y += b
	z += c
end
puts [x, y, z] == [0, 0, 0] ? :YES : :NO

puts( Array.new(gets.to_i) do
  gets.split.map(&:to_i)
end.transpose.all?{ |r| r.inject(:+).zero? } ? :YES : :NO )

n = gets.to_i
p = [0, 0, 0]
n.times do
    a = gets.split.map(&:to_i)
    3.times {|i| p[i] += a[i]}
end
puts p == [0, 0, 0] ? "YES" : "NO"

n = gets.to_i
x0, y0, z0= 0,0,0
n.times do
  x, y, z = gets.split.map(&:to_i)
  x0, y0, z0 = x0 + x, y0 + y, z0 + z
end

if x0 == 0 && y0 == 0 && z0 == 0
  puts "YES"
else
  puts "NO"
end

q = []
a = gets.to_i
for i in 0..(a-1)
q[i] = gets.split(" ")
end
w = 0
e = 0
r = 0

q.each do |n|

  w = w + n[0].to_i
  e = e + n[1].to_i
  r = r + n[2].to_i

end

if w == 0 and e == 0 and r == 0
  puts "YES"
else
  puts "NO"
end

num_of_lines = gets.chomp.to_i
x = 0
y = 0
z = 0
num_of_lines.times do
  line = gets.chomp.split(" ")
  x += line[0].to_i
  y += line[1].to_i
  z += line[2].to_i
end
puts  (x == 0 && y == 0 && z == 0)? "YES" : "NO"

forces = gets.to_i

def solve(n_forces)
  all_forces = Array.new(3,0)

  (1..n_forces).each do |i|
    a = gets.split(/\s+/).map(&:to_i)
    all_forces = all_forces.zip(a).map(&:sum)
  end

  all_forces == [0,0,0] ? "YES" : "NO"
end

puts solve(forces)

n = gets.to_i
x = 0
y = 0
z = 0
for i in 1..n
	str = gets.chomp
	xi, yi, zi = str.split(" ").map { |num| num.to_i }
	x += xi
	y += yi
	z += zi
end
if x == 0 && y == 0 && z == 0
	puts "YES"
else
	puts "NO"
end

n=gets.chomp.to_i
a=[]
suma=0
sumb=0
sumc=0
n.times do
	b=gets.chomp.split.map(&:to_i)
	a.push(b)
	suma+=b[0]
	sumb+=b[1]
	sumc+=b[2]
end
if suma==0 && suma==sumb && sumb==sumc
	puts "YES"
else
	puts "NO"
end

STDIO = $stdin
STDIO.readline
puts STDIO.readlines.map(&:strip).map(&:split).transpose.map { |b| b.map(&:to_i).inject(0) { |acc, x| acc+x } }.eql?([0,0,0]) ? "YES" : "NO"

n = gets.to_i

r = [0, 0, 0]

n.times do
  s = gets.chomp.split(' ').map &:to_i

  r = r.zip(s).map {|a| a.inject(:+)}
end

if r.sort == [0,0,0].sort
  puts "YES"
else
  puts "NO"
end

n = gets.to_i
a = Array.new()
b = Array.new()
c = Array.new()

lo,xo,fo = 0,0,0
for i in 0..n-1
 a[i],b[i],c[i] = gets.split.map(&:to_i)
 lo+=a[i]
 xo+=b[i]
 fo+=c[i]
end

if [fo, lo, xo] == [0, 0, 0]
    puts "YES"
else
    puts "NO"
end

n = $stdin.readline.to_i
dx,dy,dz = 0,0,0
n.times  do
    x,y,z = $stdin.readline.split.map(&:to_i)
    dx,dy,dz = x+dx, y+dy, z+dz
end

puts (dx==0 && dy==0 && dz==0) ? "YES" : "NO"

arr = []
gets.to_i.times do
  arr.push(gets.chomp.split.map &:to_i)
end
arr = arr.transpose.map { |x| x.inject(:+) }
if arr == [0, 0, 0]
  puts "YES"
else
  puts "NO"
end

n = gets.chomp.to_i
x,y,z = 0,0,0
n.times do |i|
  a,b,c = gets.split.map(&:to_i)
  x+=a ; y+=b ; z+=c
end
if [x,y,x] == [0,0,0]
  puts "YES"
else
  puts "NO"
end

#!/usr/bin/env ruby

while true
    break if STDIN.eof?
    n = gets.to_i

    a = b = c = 0
    n.times {
        x, y, z = gets.split.map(&:to_i)

        a += x; b += y; c += z
    }

    puts [a, b, c] == [0, 0, 0] ? 'YES' : 'NO'
end

no_forces = gets.chomp.to_i
x_sum = 0
y_sum = 0
z_sum = 0
no_forces.times do
    forces = gets.chomp.split(/ /).map(&:to_i)
    x_sum += forces[0]
    y_sum += forces[1]
    z_sum += forces[2]
end
if x_sum == 0 && y_sum == 0 && z_sum == 0
    puts "YES"
else
    puts "NO"
end

x=0
y=0
z=0
gets.to_i.times{
	a,b,c=gets.split.map{|e| e.to_i}
	x=x+a
	y=y+b
	z=z+c
}
puts (x|y|z)==0?"YES":"NO"

#Redirecting STDIN to file
#$stdin=File.open("input.txt", "r")
#$stdout=File.open("output.txt", "w")
#END

t=gets.to_i
data=[0,0,0]

for i in 1..t do
  x, y, z=gets.split.map(&:to_i)
  data[0]+=x
  data[1]+=y
  data[2]+=z
end

if data[0]==0 and data[1]==0 and data[2]==0 then
  puts "YES"
else
  puts "NO"
end

a=[]
x=y=z=0
gets.to_i.times{
	a=gets.split
	x+=a[0].to_i
	y+=a[1].to_i
	z+=a[2].to_i
}

puts(if x==y && y==z && z==0 then
		'YES'
	else
		'NO'
	end)

n = gets.to_i
x,y,z = 0,0,0
(1..n).each do
  a, b, c = gets.split.map(&:to_i)
  x += a; y += b; z += c
end
puts x==0 && y==0 && z==0 ? 'YES' : 'NO'

x,y,z = 0,0,0

gets.to_i.times do
  v = gets.split.map(&:to_i)
  x += v[0]; y+= v[1]; z+= v[2];
end

puts [x,y,z].all? {|i| i == 0} ? "YES":  "NO"

n = gets.to_i
av=bv=cv = 0
n.times{
    a,b,c = gets.split.map(&:to_i)
    av = av + a
    bv = bv + b
    cv = cv + c
}
puts (av**2+bv**2+cv**2 == 0 ? 'YES' : 'NO')

x,y,z=0,0,0;gets.to_i.times{a,b,c=gets.split.map &:to_i;x+=a;y+=b;z+=c;};puts [x,y,z]==[0,0,0]?:YES: "NO"

number = gets.chomp.to_i
vectors = []

i = 0
while i < number
	x = gets.chomp
	vectors << x.split(" ")
	i += 1
end

x = 0
y = 0
z = 0
vectors.each do |vector|
	x += vector[0].to_i
	y += vector[1].to_i
	z += vector[2].to_i
end

if x == 0 && y == 0 && z == 0
	print "YES"
else
	print "NO"
end

#puts "Enter the number of vector\n"
n = gets.to_i
a = [n]
b = [n]
c = [n]
for i in 0...n do
    a[i], b[i], c[i] = gets.split.map(&:to_i)
end
x = y = z = 0
for j in 0...n do
    x += a[j]
    y += b[j]
    z += c[j]
end
if x == 0 && y == 0 && z == 0
    puts "YES\n"
else
    puts "NO\n"
end

x_sum = 0
y_sum = 0
z_sum = 0
n = gets.to_i
n.times do
  x,y,z = gets.split(" ").map(&:to_i)
  x_sum += x
  y_sum += y
  z_sum += z
end
puts x_sum == 0 && y_sum == 0 && z_sum == 0 ? "YES" : "NO"

x, y, z = [0, 0, 0]
gets.chomp.to_i.times {
  xi, yi, zi = gets.split.map(&:to_i)
  x += xi
  y += yi
  z += zi
}
puts (x == 0 and y == 0 and z == 0) ? "YES" : "NO"

require 'matrix'

n = gets.to_i

res = Vector[0, 0, 0]

n.times do
	res += Vector.elements(gets.split.map(&:to_i))
end

puts "YES" if res == Vector[0, 0, 0]
puts "NO" unless res == Vector[0, 0, 0]

n = gets.chomp.to_i
init_vector = [0,0,0]
n.times do
  vec = gets.chomp
  vec = vec.split(' ')

  init_vector.map!.with_index {|val, i| val += vec[i].to_i }
end
puts init_vector.all? {|v| v == 0 } ? "YES" : "NO"

puts ( gets.to_i.times.map{gets.split.map(&:to_i)}.transpose.map{|x| x.reduce(&:+)} == [0,0,0] )? "YES" : "NO"

require 'scanf'

def main()
  vectors_count = gets.to_i
  vectors = []
  vectors_count.times do
    vectors << gets.scanf("%d %d %d")
  end
  check_vectors(vectors) ? puts("YES") : puts("NO")
end

def check_vectors(vectors)
  result_sum = 0
  i = 0
  vectors[0].size.times do
    if result_sum == 0 then
      result = 0
      result = vectors.inject(0) {|result, item| result = result + item[i]}
      result_sum += result
    end
    i += 1
  end
  return result_sum == 0
end
main()

n = gets.to_i;s=0
for i in(1..n)
    a = gets.split.map(&:to_i)
    s += (a[0]+a[1]+a[2])
end
puts s==0 ? "SI" : "NO"

n = gets.to_i;s=0
for i in(1..n)
    a = gets.split.map(&:to_i)
    s += (a[0]+a[1]+a[2])
end
puts s==0 ? "YES" : "NO"

n = gets.to_i
a =[]
b=[]
sum = 0

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

b.each do |i|
    i.each do |j|
        sum = sum +j
    end
end

if sum == 0
  puts "YES"
else
  puts "NO"
end

n = gets.to_i
a =[]
b=[]
sum = 0
res = 0

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

b.each do |i|
    i.each do |j|
        sum = sum +j
    end
     res = res + sum
end

if res == 0
  puts "YES"
else
  puts "NO"
end

# https://codeforces.com/problemset/problem/69/A
n = gets.chomp.to_i
forcex = 0
forcey = 0
forcez = 0
1.upto(n) do |force|
    x, y, z = gets.chomp.split(" ").map(&:to_i)
    forcex += x
    forcey += y
    forcez += z
end

if (forcex + forcey + forcez) == 0
    puts "YES"
else
    puts "NO"
end

sum = [0, 0, 0]

n = gets.to_i

for str in $stdin.each_line.take(n)
  arr = str.split(' ').map &:to_i
  (sum.zip(arr)).map do |x|
    x.reduce { :+ }
  end
end

if sum.all? { |x| x == 0 }
  puts "YES"
else
  puts "NO"
end

t = gets.to_i
sum = [0,0,0]
for i in 1..t
 b = gets.chomp.split().map { |e| e.to_i  }
 for i in 0..2
     sum[i] +=  b[i]
 end
end

puts sum.inject(0, :+) == 0 ? 'YES' : 'NO'

n = gets.chomp.to_i
vec = [0, 0, 0]
n.times.each do |_i|
  force = gets.chomp.split(/ /).map(&:to_i)
  vec[0] += force[0]
  vec[1] += force[1]
  vec[2] += force[2]
end
sum = vec.inject(0) { |sum, x| sum + x }
puts sum.zero? ? 'YES' : 'NO'

n = gets.chomp.to_i
vec = [0, 0, 0]
n.times.each do |_i|
  force = gets.chomp.split(/ /).map(&:to_i)
  vec[0] += force[0]
  vec[1] += force[1]
  vec[2] += force[2]
end
puts vec.uniq.count > 1 ? 'NO' : 'YES'

vectorNum = gets.chomp.to_i

totals = Array.new(3) { |elem| elem = 0 }

vectorNum.times do
	vector = gets.chomp.split(' ').map(&:to_i)
	for i in (0...vector.length)
		totals[i] += vector[i]
	end
end

ans = if totals.all? { |elem| elem = 0 }
	'YES'
else
	'NO'
end

puts ans

def equ(*array)
  if array.length < 4 and array.length > 0
    k = 0
    array.each do |element|
      k = k + element
    end
    if k == 0
      puts "YES"
    else
      puts "NO"
    end
  else
  puts "Enter more than 0 and less than 4 input"
  end
end

equ()

def equ(*array)
  if array.length < 4 and array.length > 0
    k = 0
    array.each do |element|
      k = k + element
    end
    if k == 0
      puts "YES"
    else
      puts "NO"
    end
  else
  puts "NO"
  end
end

a = 3

q = "4 -1 7".split(" ")
w = "-5 2 -4".split(" ")
e = "2 -1 -3".split(" ")
res = 0

for i in 0..2
  r = q[i].to_i + w[i].to_i + e[i].to_i
  res = res + r
end

if res == 0
  puts "YES"
else
  puts "NO"
end

a = gets
q = gets.split(" ")
w = gets.split(" ")
e = gets.split(" ")

res = 0

for i in 0..2
  r = q[i].to_i + w[i].to_i + e[i].to_i
  res = res + r
end

if res == 0
  puts "YES"
else
  puts "NO"
end

forces = gets.to_i

def solve(n_forces)
  all_forces = Array.new(3,0)

  (1..n_forces).each do |i|
    a = gets.split(/\s+/).map(&:to_i)
    c = all_forces.zip(a).map(&:sum)
  end

  all_forces == [0,0,0] ? "YES" : "NO"
end

puts solve(forces)

sum = 0
gets.to_i.times do
  sum += gets.chomp.split.map { |x| x.to_i }.inject(:+)
end
if sum == 0
  puts "YES"
else
  puts "NO"
end

def sum( forces )
    sum = 0
    forces.each do |force|
        sum += force
    end
    sum
end
no_forces = gets.chomp.to_i
sum_forces = 0
no_forces.times do
    forces = gets.chomp.split(/ /).map(&:to_i)
    sum_forces += sum forces
end
if sum_forces == 0
    puts "YES"
else
    puts "NO"
end

number = gets.chomp.to_i
vectors = []

i = 0
while i < number
	x = gets.chomp
	vectors << x.split(" ")
	i += 1
end

equilibrium = 0
vectors.each do |vector|
	equilibrium += vector[0].to_i + vector[1].to_i + vector[2].to_i
end

if equilibrium == 0
	print "YES"
else
	print "NO"
end

require 'scanf'

def main()
  vectors_count = gets.to_i
  vectors = []
  vectors_count.times do
    vectors << gets.scanf("%d %d %d")
  end
  check_vectors(vectors) ? puts("YES") : puts("NO")
end

def check_vectors(vectors)
  result_sum = 0
  i = 0
  vectors[0].size.times do
    if result_sum == 0 then
      result = 0
      result = vectors.inject(0) {|result, item| result = result + item[i]}
      result_sum += result
    end
    p i
    i += 1
  end
  return result_sum == 0
end
main()

require 'scanf'

def main()
  vectors_count = readline.to_i
  vectors = []
  vectors_count.times do
    vectors << readline.scanf("%d %d %d")
  end
  result_sum = 0
  i = 0
  vectors_count.times do
    if result_sum == 0 then
      result = 0
      vectors.inject(0) {|result, item| result = result + item[i]}
      result_sum += result
    end
    i += 1
  end
  result_sum == 0 ? puts("YES") : puts("NO")
end

main

require 'scanf'

def main()
  vectors_count = readline.to_i
  vectors = []
  vectors_count.times do
    vectors << readline.scanf("%d %d %d")
  end
  result = 0
  vectors.inject(0) do |result, item|
    result = result + item[0]
  end
  #p result
  vectors.inject(0) {|result, item| result = result + item[1]} if result == 0
  #p result
  vectors.inject(0) {|result, item| result = result + item[2]} if result == 0
  #p result
  result == 0 ? puts("YES") : puts("NO")
end

main

require 'scanf'

def main()
  vectors_count = gets.to_i
  vectors = []
  vectors_count.times do
    vectors << gets.scanf("%d %d %d")
  end
  check_vectors(vectors_count, vectors) ? puts("YES") : puts("NO")
end

def check_vectors(vectors_count, vectors)
  return false unless vectors_count == vectors.size
  result_sum = 0
  i = 0
  vectors_count.times do
    if result_sum == 0 then
      result = 0
      result = vectors.inject(0) {|result, item| result = result + item[i]}
      result_sum += result
    end
    i += 1
  end
  return result_sum == 0
end
def check_vectors(vectors_count, vectors)
  result_sum = 0
  i = 0
  vectors[0].size.times do
    if result_sum == 0 then
      result = 0
      result = vectors.inject(0) {|result, item| result = result + item[i]}
      result_sum += result
    end
    p i
    i += 1
  end
  return result_sum == 0
end
main()

require 'scanf'

def main()
  vectors_count = readline.to_i
  vectors = []
  vectors_count.times do
    vectors << readline.scanf("%d %d %d")
  end
  result = 0
  vectors.inject(0) do |result, item|
    result = result + item[0]
  end
  vectors.inject(0) {|result, item| result = result + item[1]} if result == 0
  vectors.inject(0) {|result, item| result = result + item[2]} if result == 0
  result == 0 ? puts("YES") : puts("NO")
end

main


A sequence a0, a1, ..., at - 1 is called increasing if ai - 1 < ai for each i: 0 < i < t.You are given a sequence b0, b1, ..., bn - 1 and a positive integer d. In each move you may choose one element of the given sequence and add d to it. What is the least number of moves required to make the given sequence increasing?

The first line of the input contains two integer numbers n and d (2 ≤ n ≤ 2000, 1 ≤ d ≤ 106). The second line contains space separated sequence b0, b1, ..., bn - 1 (1 ≤ bi ≤ 106).

Output the minimal number of moves needed to make the sequence increasing.

n, d = gets.split.map{|i| i.to_i}

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

res = 0

(n-1).times do |i|
    k = b[i] - b[i+1]
    if k >= 0 then
        m = k/d + 1
        res += m
        b[i+1] += m*d
    end
end

puts res

n, d = gets.split.map(&:to_i)
b = gets.split.map(&:to_i)
s = 0
1.upto(b.size - 1).each do |i|
	next if b[i] > b[i - 1]
	t = (b[i - 1] - b[i]) / d + 1
	s += t
	b[i] += t * d
end
p s

d=gets.split[1].to_i
a=gets.split.map(&:to_i)
ans=0
1.upto(a.length-1){|i|
    r=a[i-1]-a[i]+1
    if r>0 then
        ans+=(r+d-1)/d
        a[i]+=(r+d-1)/d*d
    end
}
puts ans

#=================================
# Better be sure than sorry.
#=================================
$stdin=File.open("./input.txt","r") if ENV["LOGNAME"]=="skydos"
require 'prime'
require 'mathn'
require 'matrix'
include Math
#=================================

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

ans=0
for i in 1...n
	if data[i]<=data[i-1]
		k=((data[i-1]-data[i]+1)*1.0/d).ceil
		data[i]+=k*d
		ans+=k
	end
end

puts ans

n,d=gets.chomp!.split(" ").map(&:to_i)
s,c=gets.chomp!.split(" ").map(&:to_i),0
(n-1).times{|i|t=s[i]-s[i+1]
if t>=0 then
  t=t/d+1
  c+=t
  s[i+1]+=t*d end}
puts c

s = gets.split(" ")
n = s[0].to_i
d = s[1].to_i

s = gets.split(" ")
mas = Array.new()
for i in 0..n-1
  mas[i] = s[i].to_i
end

count = 0
for i in 1..n-1
  if (mas[i] <= mas[i-1])
    delta = ((mas[i-1] - mas[i]) / d) + 1
    mas[i] = mas[i] +d * delta
    count += delta
  end
end

puts count

n,d = gets.split.map(&:to_i)
b = gets.split.map(&:to_i)
s = 0
1.upto(b.size - 1).each do |i|
	if b[i] <= b[i-1] then
		t = (b[i-1] - b[i]) / d + 1
		s += t
		b[i] += t * d
	end
end
p s

n, d = gets.split.map &:to_i
b = gets.split.map &:to_i
ans = 0
(1...n).each do |i|
  t = [(b[i - 1] - b[i])/d + 1, 0].max
  b[i] += t*d
  ans += t
end
puts ans

#=================================
# Better be sure than sorry.
#=================================
$stdin=File.open("./input.txt","r") if ENV["LOGNAME"]=="skydos"
require 'prime'
require 'mathn'
#=================================

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

ans=0
i=n-2
loop do
	break if i<0

	if data[i]>=data[i+1]
		(i+1).upto(n-1){|j|
			data[j]+=d
			ans+=1
		}
	else
		i-=1
	end
end

puts ans

s = gets.split(" ")
n = s[0].to_i
d = s[1].to_i

s = gets.split(" ")
mas = Array.new()
for i in 0..n-1
  mas[i] = s[i].to_i
end

count = 0
for i in 1..n-1
  if (mas[i] <= mas[i-1])
    delta = ((mas[i-1] - mas[i]) / d) + 1
    mas[i] = mas[i-1] +d * delta
    count += delta
  end
end

puts count


Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito's strength equals s.If Kirito starts duelling with the i-th (1 ≤ i ≤ n) dragon and Kirito's strength is not greater than the dragon's strength xi, then Kirito loses the duel and dies. But if Kirito's strength is greater than the dragon's strength, then he defeats the dragon and gets a bonus strength increase by yi.Kirito can fight the dragons in any order. Determine whether he can move on to the next level of the game, that is, defeat all dragons without a single loss.

The first line contains two space-separated integers s and n (1 ≤ s ≤ 104, 1 ≤ n ≤ 103). Then n lines follow: the i-th line contains space-separated integers xi and yi (1 ≤ xi ≤ 104, 0 ≤ yi ≤ 104) — the i-th dragon's strength and the bonus for defeating it.

On a single line print "YES" (without the quotes), if Kirito can move on to the next level and print "NO" (without the quotes), if he can't.

NoteIn the first sample Kirito's strength initially equals 2. As the first dragon's strength is less than 2, Kirito can fight it and defeat it. After that he gets the bonus and his strength increases to 2 + 99 = 101. Now he can defeat the second dragon and move on to the next level.In the second sample Kirito's strength is too small to defeat the only dragon and win.

s, n = gets.split(' ').map(&:to_i)
ar = []
ans = "YES"
n.times do
  ar << gets.split(' ').map(&:to_i)
end
ar.sort_by(&:first).each do |x,y|
  ans = "NO" if s <= x
  s += y
end
puts ans

s,n = gets.split.map{|i| i.to_i}

dragon = []
n.times do |i|
    dragon << gets.split.map{|j| j.to_i}
end

dragon = dragon.sort{|a,b| a[0] <=> b[0]}

t = true
n.times do |i|
    if s > dragon[i][0] then
        s += dragon[i][1]
    else
        t = false
    end
end

if t then
    puts "YES"
else
    puts "NO"
end

s, n =
gets.split.map &:to_i

all_dragons_dead = true

dragons = []
n.times do
  dragons << gets.split.map(&:to_i)
end

dragons = dragons.sort do |d1, d2|
  d1[0] <=> d2[0]
end

dragons.each do |dragon|
  dragon_s, bonus = dragon

  if s <= dragon_s
    all_dragons_dead = false
    break
  end

  s += bonus
end

output = all_dragons_dead ? "YES" : "NO"
puts output

class Dragon
  attr_accessor :hp
  attr_accessor :bonus
  def initialize(h, b)
    @hp = h
    @bonus = b
  end
end
line1 = gets.chomp.split(" ")
s = line1[0].to_i
n = line1[1].to_i

enemy = []

for i in 1..n
  line = gets.chomp.split(" ").map {|x| x.to_i}
  enemy << Dragon.new(line[0], line[1])
end

enemy = enemy.sort_by {|obj| obj.hp}

win = true
for e in enemy
  if s > e.hp
    s += e.bonus
  else
    win = false
    break
  end
end

if win
  puts "YES"
else
  puts "NO"
end

s,n=gets.split.map(&:to_i)
puts n.times.map{gets.split.map(&:to_i)}.sort_by{|x,y|x}.all?{|x,y|x+y<s+=y} ?"YES":"NO"

s, n = gets.split(" ").map(&:to_i)
a = []

n.times do |i|
  a[i] = gets.split(" ").map(&:to_i)
end

a.sort!{|x,y| x[0] <=> y[0]}

a.each do |el|
  if s <= el[0]
    puts "NO"
    exit
  end
  s += el[1]
end

puts "YES"

class Dragon
	attr_reader :life, :bonus
	def initialize(life, bonus)
		@life = life
		@bonus = bonus
	end
end

input = gets.split
kirito = input[0].to_i
n = input[1].to_i

d = Array.new
for i in 0...n
	input = gets.split
	d[i] = Dragon.new(input[0].to_i, input[1].to_i)
end
d.sort! {|x, y| x.life <=> y.life}

die = false
for i in 0...n
	if kirito <= d[i].life
		puts "NO"
		die = true
		break
	end
	kirito += d[i].bonus
end

if not die then puts "YES" end

#!/usr/bin/ruby

s, n = STDIN.readline.split.collect {|s| s.to_i }
dragons = []
n.times do
	x, y = STDIN.readline.split.collect {|s| s.to_i }
	dragons.push([x, y])
end
dragons.sort!
dragons.each do |x, y|
	if s <= x
		puts 'NO'
		exit
	end
	s += y
end
puts 'YES'

s,n=gets.chomp.split(' ').map(&:to_i)
a=[]
b=[]
n.times do
	x,y=gets.chomp.split(' ').map(&:to_i)
	a.push(x)
	b.push(y)
end
check=0
n.times do
	i=0
	check=nil
	while i<n do
		if a[i]!=0 && s>a[i]
			check=1
			a[i]=0
			s+=b[i]
			break
		end
		i+=1
	end
end
if check
	puts "YES"
else
	puts "NO"
end

s, _ = gets.split.map(&:to_i)
readlines.map(&:strip).map { |x| x.split.map(&:to_i) }.sort_by! { |x| x[0]}.each do |x|
  if s <= x[0]
    puts "NO"
    exit
  else
    s += x[1]
  end
end
puts "YES"

s, n = gets.chomp.split(" ").map(&:to_i)
a = []

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

a.sort_by!{|x, y| x}

a.each do |x, y|
  if s > x
    s += y
  else
    puts "NO"
    exit
  end
end

puts "YES"

# cook your code here
energy,dragons = gets.split(' ').map(&:to_i)
arr = []
dragons.times do |i|
    arr[i]= gets.split(' ').map(&:to_i)
end

arr.sort!
done = true
dragons.times do |i|
    if arr[i][0] < energy
        energy += arr[i][1]
    else
        done = false
        break
    end

end

puts "YES" if done
puts "NO" unless done

s, n = gets.split.map &:to_i
arr = []
n.times do
  arr.push(gets.split.map &:to_i)
end
d, b = arr.transpose
n.times do
  w = d.index { |x| x < s }
  if w == nil
    puts "NO"
    exit
  else
    s += b[w]
    d.delete_at(w)
    b.delete_at(w)
  end
end
puts "YES"

 a=gets.chomp.split(" ")
pow=a[0].to_i
drag=a[1].to_i
dragary=[]
drag.times do
temp=gets.chomp.split(" ")
temp[0]=temp[0].to_i
temp[1]=temp[1].to_i
dragary<< temp
end
dragary.sort!
i=0
loop do
if dragary[i][0]<pow
pow+=dragary[i][1]
i+=1
else
puts "NO"
break
end
break if i>drag-1
end
if i>drag-1
puts "YES"
end

r=->(){gets.to_s.split.map &:to_i}
s,n=*r.call()
a=[];n.times {a<<r.call()}
a.sort_by! {|a| a[0]}
ok=true
a.each do |x|
  ok=false if x[0]>=s
  s+=x[1]
end
print ok ? 'YES' : 'NO'

def r() gets.to_s.split.map &:to_i end
s,n=*r
a=[];n.times {a<<r}
a.sort.each do |x|
  if x[0]>=s then print 'NO';exit(0);end
  s+=x[1]
end
print 'YES'

s, n = gets.chomp.split(/ /).map(&:to_i)
dragons = []
winner = true
n.times do
    dragons << gets.chomp.split(/ /).map(&:to_i)
end
dragons.sort!
kirito = s
dragons.each do |dragon|
    if kirito > dragon[0]
        kirito += dragon[1]
    else
        winner = false
        break
    end
end
if winner
    puts "YES"
else
    puts "NO"
end

#!/usr/bin/env ruby
first_line = gets
strength = first_line.split(' ')[0].to_i
count_of_dragons = first_line.split(' ')[1].to_i

dragons = []

(1..count_of_dragons).each do |i|
	dragon = {}
	drag_str = gets
	dragon["strength"] = drag_str.split(' ')[0].to_i
	dragon["bonus"] = drag_str.split(' ')[1].to_i
	dragons.push(dragon)
end

dragons = dragons.sort_by{ |d| d["strength"] }

dragons.each do |d|
	if strength > d["strength"] then
		strength+= d["bonus"]
	else
		puts "NO"
		exit
	end
end

puts "YES"
exit

n,m=gets.split.map{|e| e.to_i}
x=[]
m.times{|i|
	a=gets.split.map{|e| e.to_i}
	x<<a
}
x.sort!
ans="YES"
while !x.empty?
	if n<=x[0][0] then
		ans="NO"
	end
	n=n+x[0][1]
	x.shift
end
puts ans

s,n = gets.split.map &:to_i
a = []
n.times do |i|
a[i] = gets.split.map(&:to_i)
end
a.sort_by!{|x,y| x }
b = true
for i in a
	if i[0] < s
		s += i[1]
	else
		b = false
	end
end
if b == false
	puts 'NO'
else
	puts 'YES'
end

a=[]
s,n=gets.split.map{|i|i.to_i}
n.times{|i| a[i]=gets.split.map{|i|i.to_i}}
a.sort!
n.times{|i|
	if s <= a[i][0] then
		puts 'NO'
		exit
	else
		s+=a[i][1]
	end
}
puts 'YES'

s,n = gets.split(" ").map(&:to_i)
win = true
dragons = []
n.times do
  dragons << gets.split(" ").map(&:to_i)
end
dragons.sort! do |a,b|
  if a[0] != b[0]
    a[0] <=> b[0]
  else
    b[1] <=> a[1]
  end
end
dragons.each { |dragon|
  if s > dragon[0]
    s += dragon [1]
  else
    win = false
    break
  end
}
puts win ? "YES" : "NO"

s, n = gets.split.map(&:to_i)
d = []
n.times {
  d << gets.split.map(&:to_i)
}
d = d.sort_by{ |x| x[0]}
flag = true
d.each do |x|
  if s <= x[0]
    flag = false
  else
    s += x[1]
  end
end

puts flag ? "YES" : "NO"

power, enemy_count = gets.chop.split.map(&:to_i)

dragons = []
enemy_count.times { dragons << gets.chop.split.map(&:to_i) }

loop do
  weak_dragons = dragons.select { |dragon| power > dragon[0] }
  break if dragons.count.zero? || weak_dragons.count.zero?
  power += weak_dragons.reduce(0) { |bonus, dragon| bonus += dragon[1] }
  dragons -= weak_dragons
end

dragons.count.zero? ? puts('YES') : puts('NO')

#!/usr/bin/env ruby

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

x = n.times.map { gets.split.map(&:to_i) }

yes = 1
n.times do
  id = -1
  x.each_with_index do |arr, i|
    if arr[0] < s
      id = i
      break
    end
  end
  if id == -1
    yes = 0
    break
  end
  s += x[id][1]
  x.delete_at(id)
end

puts(yes == 1 ? 'YES' : 'NO')

#!/usr/bin/env ruby

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

x = n.times.map { gets.split.map(&:to_i) }.sort

yes = true
x.each do |a,b|
  if s <= a
    yes = false
    break
  end
  s += b
end

puts(yes ? 'YES' : 'NO')

s, n = gets.split.map(&:to_i)
a = []
n.times do
  b = gets.split.map(&:to_i)
  a << b
end
a.sort!
ans = 1
n.times do |i|
  if s <= a[i][0]
    ans = 0
    break
  end
  s += a[i][1]
end
puts ans == 0 ? "NO" : "YES"

s, n = gets.split.map(&:to_i)
a = n.times.map{gets.split.map(&:to_i)}.sort
ans = true
n.times do |i|
  if s <= a[i][0]
    ans = false
    break
  end
  s += a[i][1]
end
puts ans ? "YES" : "NO"

class Dragon
  attr_accessor :x, :y

  def initialize(x, y)
    @x = x
    @y = y
  end

  def <=>(other)
    unless self.x == other.x
      self.x - other.x
    else
      other.y - self.y
    end
  end
end

s, n = gets.split.map &:to_i
ar = Array.new
n.times do
  ar << Dragon.new(*(gets.split.map &:to_i))
end
ar.sort!
ar.each do |dragon|
  if dragon.x < s
    s += dragon.y
  else
    puts "NO"
    exit
  end
end
puts "YES"

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

a = 1.upto(n).map do
  gets.split(' ').map(&:to_i)
end.sort { |x, y| x.first <=> y.first }

success = true
a.inject(s) do |strength, dragon|
  if strength <= dragon.first
    success = false
    break
  end

  strength += dragon.last
end

puts success ? 'YES' : 'NO'

first_line = gets.chomp.split(' ')
s = first_line[0].to_i
n = first_line[1].to_i
dragons = []
(0...n).each do |i|
	line = gets.chomp.split(' ')
	dragons[i] = {
		strength: line[0].to_i,
		bonus: line[1].to_i
	}
end

dragons.sort! { |a, b| a[:strength] <=> b[:strength] }
defeated = false
dragons.each do |elem|
	if s <= elem[:strength]
		defeated = true
		break
	end
	s += elem[:bonus]
end

if defeated
	puts "NO"
else
	puts "YES"
end

class Pair
  attr_accessor :x, :y

  def initialize(x = 0, y = 0)
    @x = x
    @y = y
  end

end

s, n = gets.chomp.split(' ')

s = s.to_i
n = n.to_i

dragons = [];

n.times {
  x, y = gets.chomp.split(' ')
  x = x.to_i
  y = y.to_i
  dragons << Pair.new(x, y)
}

dragons.sort! { |a, b| a.x <=> b.x }

isDead = false
dragons.each { |dragon|

  if s <= dragon.x
    isDead = true
    break
  end

  s += dragon.y
}

if isDead
  puts "NO"
else
  puts "YES"
end

class Kirito
  def initialize(strength)
    @strength = strength
  end

  def attack(dragon)
    if @strength > dragon.strength
      @strength += dragon.bonus
      return true
    else
      return false
    end
  end
end

class Dragon
  attr_reader :strength, :bonus
  def initialize(strength, bonus)
    @strength = strength
    @bonus = bonus
  end
end

s, n = gets.split.map(&:to_i)
kirito = Kirito.new(s)
dragons = []
n.times do
  dragons << Dragon.new(*gets.split.map(&:to_i))
end
dragons.sort!{|a, b| a.strength <=> b.strength}
dragons.each do |d|
  unless kirito.attack(d)
    puts "NO"
    exit
  end
end
puts "YES"

s, n =
gets.split.map &:to_i

all_dragons_dead = true

dragons = []
n.times do
  dragons << gets.split.map(&:to_i)
end

dragons = dragons.sort do |d1, d2|
  d1[0] <=> d2[0]
end

dragons.each do |dragon|
  dragon_s, bonus = dragon

  if s < dragon_s
    all_dragons_dead = false
    break
  end

  s += bonus
end

output = all_dragons_dead ? "YES" : "NO"
puts output

s, n =
gets.split.map &:to_i

all_dragons_dead = true

dragons = []
n.times do
  dragons << gets.split.map(&:to_i)
end

dragons = dragons.sort do |d1, d2|
  d1[0] <=> d2[0]
end

dragons.each do |dragon|
  dragon_s, bonus = dragon

  if s < dragon_s
    all_dragons_dead = false
    break
  end

  s += bonus
  s -= dragon_s
end

output = all_dragons_dead ? "YES" : "NO"
puts output

class Dragon
  attr_accessor :hp
  attr_accessor :bonus
  def initialize(h, b)
    @hp = h
    @bonus = b
  end
end
line1 = gets.chomp.split(" ")
s = line1[0].to_i
n = line1[1].to_i

line_hp = []
line_bonus = []
if n == 1
  line = gets.chomp.split(" ").map {|x| x.to_i}
  line_hp[0] = line[0]
  line_bonus[0] = line[1]
else
  line_hp = gets.chomp.split(" ").map {|x| x.to_i}
  line_bonus = gets.chomp.split(" ").map {|x| x.to_i}
end
enemy = []

for i in 1..n
  enemy << Dragon.new(line_hp[i-1], line_bonus[i-1])
end

enemy.sort_by {|obj| obj.hp}

win = true
for e in enemy
  if s > e.hp
    s += e.bonus
  else
    win = false
    break
  end
end

if win
  puts "YES"
else
  puts "NO"
end

s, n = gets.split(" ").map(&:to_i)
a = []

n.times do |i|
  a[i] = gets.split(" ").map(&:to_i)
end

a.sort!{|x,y| x[0] <=> y[0]}

a.each do |el|
  if s < el[0]
    puts "NO"
    exit
  end
  s += el[1]
end

puts "YES"

s, _ = gets.split.map(&:to_i)
readlines.map(&:strip).map { |x| x.split.map(&:to_i) }.sort_by! { |x| x[0]}.each do |x|
  if s < x[0]
    puts "NO"
    exit
  else
    s += x[1]
  end
end
puts "YES"

a=gets.chomp.split(" ")
pow=a[0].to_i
drag=a[1].to_i
dragary=[]
drag.times do
temp=gets.chomp.split(" ")
temp[0]=temp[0].to_i
temp[1]=temp[1].to_i
dragary<< temp
end
dragary.sort!
i=0
loop do
if dragary[i][0]<=pow
pow+=dragary[i][1]
i+=1
else
puts "NO"
break
end
break if i>drag-1
end
if i>drag-1
puts "YES"
end

s, n = gets.chomp.split(/ /).map(&:to_i)
kirito = s
winner = true
n.times do
    x, y = gets.chomp.split(/ /).map(&:to_i)
    if kirito > x
        kirito += y
    else
        winner = false
        break
    end
end
if winner
    puts "YES"
else
    puts "NO"
end

#!/usr/bin/env ruby
first_line = gets
strength = first_line.split(' ')[0].to_i
count_of_dragons = first_line.split(' ')[1].to_i

dragons = []

(1..count_of_dragons).each do |i|
	dragon = {}
	drag_str = gets
	dragon["strength"] = drag_str.split(' ')[0].to_i
	dragon["bonus"] = drag_str.split(' ')[1].to_i
	dragons.push(dragon)
end

dragons.sort_by!{ |d| d["strength"] }

dragons.each do |d|
	if strength > d["strength"] then
		strength+= d["bonus"]
	else
		puts "NO"
		exit
	end
	puts "YES"
	exit
end

#!/usr/bin/env ruby
first_line = gets
strength = first_line.split(' ')[0].to_i
count_of_dragons = first_line.split(' ')[1].to_i

dragons = []

(1..count_of_dragons).each do |i|
	dragon = {}
	drag_str = gets
	dragon["strength"] = drag_str.split(' ')[0].to_i
	dragon["bonus"] = drag_str.split(' ')[1].to_i
	dragons.push(dragon)
end

dragons = dragons.sort_by{ |d| d["strength"] }

dragons.each do |d|
	if strength > d["strength"] then
		strength+= d["bonus"]
	else
		puts "NO"
		exit
	end
	puts "YES"
	exit
end

s,n = gets.split.map &:to_i
a = []
n.times do |i|
a[i] = gets
a.sort!
end
for i in a
	x,y = i.split.map &:to_i
	if x < s
		s += y
	else
		s = -1
	end
end
if s == -1
	puts 'NO'
else
	puts 'YES'
end

s,n = gets.split(" ").map(&:to_i)
win = true
dragons = []
n.times do
  dragons << gets.split(" ").map(&:to_i)
end
dragons.sort! do |a,b|
  if a[0] != b[0]
    a[0] <=> b[0]
  else
    b[1] <=> a[1]
  end
end
dragons.each { |dragon|
  if s >= dragon[0]
    s += dragon [1]
  else
    win = false
    break
  end
}
puts win ? "YES" : "NO"

s, n = gets.split.map(&:to_i)
d = []
n.times {
  d << gets.split.map(&:to_i)
}
d = d.sort_by{ |x| x[0]}
puts d.to_s
flag = true
d.each do |x|
  if s <= x[0]
    flag = false
  else
    s += x[1]
  end
end

puts flag ? "YES" : "NO"

#!/usr/bin/env ruby

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

x = n.times.map { gets.split.map(&:to_i) }

yes = 1
n.times do
  id = -1
  x.each_with_index do |arr, i|
    if arr[0] <= s
      id = i
      break
    end
  end
  if id == -1
    yes = 0
    break
  end
  s += x[id][1]
  x.delete_at(id)
end

puts(yes == 1 ? 'YES' : 'NO')

s, n = gets.split.map(&:to_i)
a = []
n.times do
  b = gets.split.map(&:to_i)
  a << b
end
a.sort!
ans = 1
n.times do |i|
  if s < a[i][0]
    ans = 0
    break
  end
  s += a[i][1]
end
puts ans == 0 ? "NO" : "YES"

first_line = gets.chomp.split(' ')
s = first_line[0].to_i
n = first_line[1].to_i
dragons = []
(0...n).each do |i|
	line = gets.chomp.split(' ')
	dragons[i] = {
		strength: line[0].to_i,
		bonus: line[1].to_i
	}
end

dragons.sort { |a, b| a[:strength] <=> b[:strength] }
defeated = false
dragons.each do |elem|
	if s <= elem[:strength]
		defeated = true
		break
	end
	s += elem[:bonus]
end

if defeated
	puts "NO"
else
	puts "YES"
end


You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick.

For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES".

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i).tally
	if a.any? { |k, v| v.odd? }
		puts 'NO'
	else
		b = a.reduce([]) { |acc, (k, v)| acc.concat([k] * (v / 2)) }.sort
		c = (0...n).map { |i| b[i] * b[~i] }
		puts c == c.rotate(1) ? "YES" : "NO"
	end
end

gets.strip.to_i.times do
  n = gets.strip.to_i
  sticks = gets.strip.split(' ').map(&:to_i)
  h = Hash.new(0)
  sticks.each do |s|
    h[s] += 1
  end

  if h.any? { |k, v| (v % 2) != 0 }
    puts "NO"
  else
    vals = []
    h.each do |k,v|
      h[k] = v / 2
      (v / 2).times { vals << k }
    end
    vals.sort!
    i , j = 0, vals.size - 1
    last = nil
    res = true
    while i < j
      if vals[i] * vals[j] != last && i != 0
        puts "NO"
        res = false
        break
      end
      last = vals[i] * vals[j]
      i += 1
      j -= 1
    end
    puts "YES" if res
  end
end

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  a.sort!
  s = a[0] * a.last
  ok = true
  (0...n).each do |i|
    ok = false if a[2 * i] != a[2 * i + 1] or a[4 * n - 2 * i - 1] != a[4 * n - 2 * i - 2] or a[2 * i] * a[4 * n - 2 * i - 1] != s
  end
  unless ok
    puts "NO"
  else
    puts "YES"
  end
end

q = gets.to_i
ans = []
q.times do
  n = gets.to_i
  pp = gets.split.map(&:to_i).sort{|a,b|b<=>a}

  vv = []
  can = true

  0.step(n*4-2,2) do |i|
    # ペアがないとダメ
    unless pp[i]==pp[i+1]
      can = false
      break
    end

    vv << pp[i]
  end
  #puts vv.to_s #d

  if can
    e1 = vv.shift
    e2 = vv.pop
    s = e1*e2
    while vv.size > 1 do
      e1 = vv.shift
      e2 = vv.pop
      if e1*e2 != s
        can = false
        break
      end
    end
  end

  ans << (can ? 'YES' : 'NO')
end
puts ans

t = gets.to_i
t.times do |index|
    n = (gets.to_i)*4
    a = gets.split(" ").map(&:to_i)
    b = []
    a.sort!
    i = 0
    ans = true
    while i < n
        if a[i] != a[i+1]
            ans = false
        end
        b.push a[i]
        i += 2
    end
    i = 0
    j = n/2 - 1
    area = b[i]*b[j]
    while i <= j
        if (b[i])*(b[j]) != area
            ans = false
        end
        i += 1
        j -= 1
    end
    puts ans ? "YES" : "NO"
end

q = gets.to_i
ans = []
q.times do
  n = gets.to_i
  pp = gets.split.map(&:to_i).sort{|a,b|b<=>a}

  vv = []
  can = true

  0.step(n*4-2,2) do |i|
    # ペアがないとダメ
    unless pp[i]==pp[i+1]
      can = false
      break
    end

    vv << pp[i]
  end
  #puts vv.to_s #d

  if can
    s = vv.inject(:*) / n
    while vv.size > 1 do
      e1 = vv.shift
      idx = pp.index(s/e1)
      if idx.nil?
        can = false
        break
      end
      vv.delete_at(idx)
    end
  end

  ans << (can ? 'YES' : 'NO')
end
puts ans


For a collection of integers $$$S$$$, define $$$\operatorname{mex}(S)$$$ as the smallest non-negative integer that does not appear in $$$S$$$.NIT, the cleaver, decides to destroy the universe. He is not so powerful as Thanos, so he can only destroy the universe by snapping his fingers several times.The universe can be represented as a 1-indexed array $$$a$$$ of length $$$n$$$. When NIT snaps his fingers, he does the following operation on the array:  He selects positive integers $$$l$$$ and $$$r$$$ such that $$$1\le l\le r\le n$$$. Let $$$w=\operatorname{mex}(\{a_l,a_{l+1},\dots,a_r\})$$$. Then, for all $$$l\le i\le r$$$, set $$$a_i$$$ to $$$w$$$. We say the universe is destroyed if and only if for all $$$1\le i\le n$$$, $$$a_i=0$$$ holds.Find the minimum number of times NIT needs to snap his fingers to destroy the universe. That is, find the minimum number of operations NIT needs to perform to make all elements in the array equal to $$$0$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1\le n\le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_n$$$ ($$$0\le a_i\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

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

NoteIn the first test case, we do $$$0$$$ operations and all elements in the array are already equal to $$$0$$$.In the second test case, one optimal way is doing the operation with $$$l=2$$$, $$$r=5$$$.In the third test case, one optimal way is doing the operation twice, respectively with $$$l=4$$$, $$$r=4$$$ and $$$l=2$$$, $$$r=6$$$.In the fourth test case, one optimal way is doing the operation with $$$l=1$$$, $$$r=1$$$.

# gets.to_i
# gets.split.map(&:to_i)

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

  ans = 0
  flag = false
  n.times do |i|
    if !flag && a[i] != 0
      ans += 1
      flag = true
    elsif a[i] == 0
      flag = false
    end
  end

  puts [ans,2].min
end

gets.to_i.times do
  gets
  as = gets.split.map(&:to_i)
  bs = as.drop_while { |a| a == 0 }.reverse.drop_while { |a| a == 0 }.reverse
  if bs.empty?
    p 0
  elsif bs.include?(0)
    p 2
  else
    p 1
  end
end

gets.to_i.times do
    n = gets.to_i
    a = gets.split.map(&:to_i)
    f = true
    ans = 0
    a.each do |x|
        (ans += 1) if (x != 0 && f)
        f = x == 0 ? true : false
    end
    puts (ans > 2)?2 : ans
end

# gets.to_i
# gets.split.map(&:to_i)

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

  ans = 0
  flag = false
  n.times do |i|
    if !flag && a[i] != 0
      ans += 1
      flag = true
    elsif a[i] == 0
      flag = false
    end
  end

  puts ans
end

# gets.to_i
# gets.split.map(&:to_i)

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  list = []

  k = []
  n.times do |i|
    if a[i] != 0
      k << a[i]
    else
      list << k if !k.empty?
      k = []
    end
  end
  list << k if !k.empty?

  puts list.size
end

gets.to_i.times do
  gets
  xs = gets.split.map(&:to_i)
  p xs.slice_when { |a, b| (a == 0) != (b == 0) }.count { |xs| xs.max > 0 }
end

gets.to_i.times do
  gets
  xs = gets.split.map(&:to_i)
  p xs.drop_while { |x| x == 0 }.reverse.drop_while { |x| x == 0 }.reverse.slice_when { |x| x == 0 }.count { |xs| xs.max > 0 }
end

gets.to_i.times do
    n = gets.to_i
    a = gets.split.map(&:to_i)
    f = true
    ans = 0
    a.each do |x|
        (ans += 1) if (x != 0 && f)
        f = x == 0 ? true : false
    end
    puts ans
end


You have a given picture with size $$$w \times h$$$. Determine if the given picture has a single "+" shape or not. A "+" shape is described below:  A "+" shape has one center nonempty cell.  There should be some (at least one) consecutive non-empty cells in each direction (left, right, up, down) from the center. In other words, there should be a ray in each direction.  All other cells are empty. Find out if the given picture has single "+" shape.

The first line contains two integers $$$h$$$ and $$$w$$$ ($$$1 \le h$$$, $$$w \le 500$$$) — the height and width of the picture. The $$$i$$$-th of the next $$$h$$$ lines contains string $$$s_{i}$$$ of length $$$w$$$ consisting "." and "*" where "." denotes the empty space and "*" denotes the non-empty space.

If the given picture satisfies all conditions, print "YES". Otherwise, print "NO". You can output each letter in any case (upper or lower).

NoteIn the first example, the given picture contains one "+".In the second example, two vertical branches are located in a different column.In the third example, there is a dot outside of the shape.In the fourth example, the width of the two vertical branches is $$$2$$$.In the fifth example, there are two shapes.In the sixth example, there is an empty space inside of the shape.

H,W = gets.split.map(&:to_i)
pic = []
cell = 0
H.times do
  s = gets.chomp
  cell += s.count("*")
  pic << s
end

flg = false
ver = false
(H-2).times do |i|
  1.upto(W-2) do |j|
    if pic[i][j] == "*"
      pic[i][j] = "."
      k = i+1
      while k < H && pic[k][j] == "*"
        pic[k][j] = "."
        if !ver && k < H-1 && pic[k][j-1] == "*" && pic[k][j+1] == "*" && pic[k+1][j] == "*"
          l,r = j-1,j+1
          while l >= 0 && pic[k][l] == "*"
            pic[k][l] = "."
            l -= 1
          end
          while r < W && pic[k][r] == "*"
            pic[k][r] = "."
            r += 1
          end
          ver = true
        end
        k += 1
      end
      flg = true
      break
    end
  end
  break if flg
end
emp = true
H.times do |i|
  W.times do |j|
    emp = false if pic[i][j] == "*"
  end
end
#p pic
puts emp && ver ? "YES" : "NO"

h, w = gets.split.map(&:to_i)
f = h.times.map{gets.chomp}
memo_left = (0..h).map{[0] * w}.to_a
memo_up = (0..h).map{[0] * w}.to_a
memo_right = (0..h).map{[0] * w}.to_a
memo_down = (0..h).map{[0] * w}.to_a
cnt = f.map{|s| s.count('*')}.inject(:+)

h.times{|i|
  w.times{|j|
    next if f[i][j] != '*'
    memo_left[i][j] = (i > 0 ? memo_left[i - 1][j] : 0) + 1
    memo_up[i][j] = (j > 0 ? memo_up[i][j - 1] : 0) + 1
  }}
(h-1).downto(0).each{|i|
  (w-1).downto(0).each{|j|
    next if f[i][j] != '*'
    memo_right[i][j] = (i < h - 1 ?  memo_right[i + 1][j] : 0) + 1
    memo_down[i][j] = (j < w - 1 ? memo_down[i][j + 1] : 0) + 1
  }}

h.times{|i|
  w.times{|j|
    next if f[i][j] != '*'
    a = memo_left[i][j]
    b = memo_right[i][j]
    c = memo_up[i][j]
    d = memo_down[i][j]
    if a > 1 and b > 1 and c > 1 and d > 1 and a + b + c + d - 3 == cnt
      puts :YES
      exit
    end
  }
}
puts :NO

h, w = gets.split.map(&:to_i)
f = h.times.map{gets.chomp}
cnt = f.map{|s| s.count('*')}.inject(:+)
h.times{|i|
  w.times{|j|
    a = f[i].chars.drop_while{|x|x==?.}.take_while{|x|x==?*}.size
    b = (0...h).drop_while{|i|f[i][j]==?.}.take_while{|i|f[i][j]==?*}.size
    if a + b - 1 == cnt
      puts :YES
      exit
    end
  }
}
puts :NO

h, w = gets.split.map(&:to_i)
f = h.times.map{gets.chomp}
cnt = f.map{|s| s.count('*')}.inject(:+)
h.times{|i|
  w.times{|j|
    a = i.downto(0).take_while{|ii| f[ii][j] == ?*}.size
    b = i.upto(h-1).take_while{|ii| f[ii][j] == ?*}.size
    c = j.downto(0).take_while{|jj| f[i][jj] == ?*}.size
    d = j.upto(w-1).take_while{|jj| f[i][jj] == ?*}.size
    if a + b + c + d - 3 == cnt
      puts :YES
      exit
    end
  }
}
puts :NO