s = gets.chomp
st = []
seq = []
rev = {}
rev[')'] = '('
rev[']'] = '['
i = 0
s.each_char do |c|
    if (c == '(' || c == '[')
        st.push([i, c])
    elsif (st.size() > 0 && (c == ')' || c == ']') && rev[c] == st.last[1])
        seq.push(st.last)
        seq.push([i, c])
        st.pop
    else
        while (st.size() > 0)
            st.pop
        end
    end
    i += 1
end
seq.sort!
res = "", mx = -1, prv = -1, c = 0, t = ""
for i in seq
    # puts "#{i[0]} #{i[1]}"
    if (i[0] - prv == 1 || prv == -1)
        c += 1 if (i[1] == '[')
        t += i[1]
    else
        if (mx < c)
            mx = c
            res = t.dup
            t = ""
            c = 0
            c += 1 if (i[1] == '[')
            t += i[1]
        end
    end
    prv = i[0]
end

if (mx < c)
    mx = c
    res = t.dup
end
puts mx, res

A bracket sequence is a string, containing only characters "(", ")", "[" and "]".A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([])" are correct (the resulting expressions are: "(1)+[1]", "([1+1]+1)"), and "](" and "[" are not. The empty string is a correct bracket sequence by definition.A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (where |s| is the length of string s) is the string slsl + 1... sr. The empty string is a substring of any string by definition.You are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets «[» as possible.

The first and the only line contains the bracket sequence as a string, consisting only of characters "(", ")", "[" and "]". It is guaranteed that the string is non-empty and its length doesn't exceed 105 characters.

In the first line print a single integer — the number of brackets «[» in the required bracket sequence. In the second line print the optimal sequence. If there are more than one optimal solutions print any of them.

A,B,C,D=[?[,?],?(,?)].map(&:ord)
def match(c,d)
	return 1 if (c==A)&&(d==B)
	return 0 if (c==C)&&(d==D)
	false
end
t=gets.chomp
s=t.bytes.each_with_index.map.to_a
size=s.size
table=Array.new(size+1)
stack=[]
s.each{|chr|
	ord,idx=chr
	if (ord==A)||(ord==C)||stack.empty?
		stack.push chr
	else
		if m=match(stack.last.first,ord)
			_ord,_idx=stack.pop
			table[idx]=0
			table[_idx]=m
		else
			stack.push chr
		end
	end
}
max=0
sum=0
_l=l=r=0
table.each_with_index{|n,idx|
	if n
		sum+=n
	else
		if sum>max
			max=sum
			l=_l
			r=idx-1
		end
		sum=0
		_l=idx+1
	end
}
puts max
puts max==0 ? "" : t[l..r]


num = gets.chomp

num_of_four = 0
num_of_seven = 0
ans_num = ""
len = num.length

def get_bigger len
  ans_num = "4"
  append_times = len / 2
  append_times.times { ans_num << "4" }
  append_times.times { ans_num << "7" }
  ans_num << "7"
end

def get_rest(ans_num, len, num_of_four, num_of_seven)
  rest_four = len / 2 - num_of_four
  rest_seven = len / 2 - num_of_seven
  rest_four.times { ans_num << "4" }
  rest_seven.times { ans_num << "7" }
  return ans_num
end

if num[0] > "7" || len % 2 == 1
  ans_num = ans_num << (get_bigger len)

else
  index = len
  for i in 0...len
    if num[i] == "4" #many 4
      num_of_four = num_of_four + 1
      if num_of_four > len / 2
        num_of_four = num_of_four - 1
        index = i
        break
      end

    elsif num[i] == "7" #many 7
      num_of_seven = num_of_seven + 1
      if num_of_seven > len / 2
        num_of_seven = num_of_seven - 1
        index = i
        break
      end

    else
      index = i
      break
    end
  end

  if index == len
    ans_num = num
  elsif num[index] <= "4"
    ans_num = ans_num << num[0...index]
    ans_num = get_rest ans_num, len, num_of_four, num_of_seven

  elsif num[index] < "7"
    if len / 2 - num_of_seven != 0
      ans_num = ans_num << num[0...index]
      ans_num << "7"
      num_of_seven = num_of_seven + 1
      ans_num = get_rest ans_num, len, num_of_four, num_of_seven
    else
      index = index - 1
      while index >= 0
        if num[index] == "4"
          num_of_four = num_of_four - 1
          break if len / 2 - num_of_seven != 0
        end
        num_of_seven = num_of_seven - 1
        index = index - 1
      end
      if index == -1
        ans_num = get_bigger len
      else
        ans_num = ans_num << num[0...index]
        ans_num << "7"
        num_of_seven = num_of_seven + 1
        ans_num = get_rest ans_num, len, num_of_four, num_of_seven
      end
    end
  else
    index = index - 1
    while index >= 0
      if num[index] == "4"
        num_of_four = num_of_four - 1
        break if len / 2 - num_of_seven != 0
      end
      num_of_seven = num_of_seven - 1
      index = index - 1
    end
    if index == -1
      ans_num = get_bigger len
    else
      ans_num = ans_num << num[0...index]
      ans_num << "7"
      num_of_seven = num_of_seven + 1
      ans_num = get_rest ans_num, len, num_of_four, num_of_seven
    end
  end
end

puts ans_num

Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Lucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. For example, numbers 47, 7744, 474477 are super lucky and 4, 744, 467 are not.One day Petya came across a positive integer n. Help him to find the least super lucky number which is not less than n.

The only line contains a positive integer n (1 ≤ n ≤ 10100000). This number doesn't have leading zeroes.

Output the least super lucky number that is more than or equal to n.

num = gets.chomp

num_of_four = 0
num_of_seven = 0
ans_num = ""
len = num.length

def get_bigger len
  ans_num = "4"
  append_times = len / 2
  append_times.times { ans_num << "4" }
  append_times.times { ans_num << "7" }
  ans_num << "7"
end

def get_rest(ans_num, len, num_of_four, num_of_seven)
  rest_four = len / 2 - num_of_four
  rest_seven = len / 2 - num_of_seven
  rest_four.times { ans_num << "4" }
  rest_seven.times { ans_num << "7" }
  return ans_num
end

def operation_with_seven(index, num, num_of_four, num_of_seven, len)
  ans_num = ""
  index = index - 1
  while index >= 0
    if num[index] == "4"
      num_of_four = num_of_four - 1
      break if len / 2 - num_of_seven > 0
    else
      num_of_seven = num_of_seven - 1
    end
    index = index - 1
  end
  if index == -1
    ans_num = get_bigger len
  else
    ans_num = ans_num << num[0...index]
    ans_num << "7"
    num_of_seven = num_of_seven + 1
    ans_num = get_rest ans_num, len, num_of_four, num_of_seven
  end
  return ans_num
end

if num[0] > "7" || len % 2 == 1
  ans_num = ans_num << (get_bigger len)

else
  index = len
  for i in 0...len
    if num[i] == "4" #many 4
      num_of_four = num_of_four + 1
      if num_of_four > len / 2
        num_of_four = num_of_four - 1
        index = i
        break
      end

    elsif num[i] == "7" #many 7
      num_of_seven = num_of_seven + 1
      if num_of_seven > len / 2
        num_of_seven = num_of_seven - 1
        index = i
        break
      end

    else
      index = i
      break
    end
  end

  if index == len
    ans_num = num
  elsif num[index] <= "4"
    ans_num = ans_num << num[0...index]
    ans_num = get_rest ans_num, len, num_of_four, num_of_seven

  elsif num[index] < "7"
    if len / 2 - num_of_seven > 0
      ans_num = ans_num << num[0...index]
      ans_num << "7"
      num_of_seven = num_of_seven + 1
      ans_num = get_rest ans_num, len, num_of_four, num_of_seven
    else
      ans_num = operation_with_seven index, num, num_of_four, num_of_seven, len
    end
  else
    ans_num = operation_with_seven index, num, num_of_four, num_of_seven, len
  end
end

puts ans_num


$numAs=Array.new(1, 0)
$numBs=Array.new(1, 0)
$numAs1=Array.new(1, 0)
$numBs1=Array.new(1, 0)

def f(a, b, c, d)
    nA=[b-a+1, $numAs[b]].min
    nB=$numBs[b]-$numBs[a-1]
    nA1=[d-c+1, $numAs1[d]].min
    nB1=$numBs1[d]-$numBs1[c-1]
#    print nA, nB, nA1, nB1, "\n"
    if (nB==nB1)
        if (nA>=nA1 && (nA%3)==(nA1%3))
            print 1
        else
            print 0
        end
    elsif (nB<nB1)
        if (nB==0)
            nA-=1
        end
        if (nA>=nA1)
            print 1
        else
            print 0
        end
    else
        print 0
    end
end

s=gets
s1=gets
n=gets.to_i
(0..s.length-1).each{|x| $numBs.push($numBs[x]+(s[x]=="B" || s[x]=="C" ? 1 : 0 ))}
(0..s1.length-1).each{|x| $numBs1.push($numBs1[x]+(s1[x]=="B" || s1[x]=="C" ? 1 : 0 ))}
(0..s.length-1).each{|x| $numAs.push(s[x]=='A' ? $numAs[x]+1 : 0)}
(0..s1.length-1).each{|x| $numAs1.push(s1[x]=='A' ? $numAs1[x]+1 : 0)}
t=Array.new
for i in 0...n
  t=gets.split(' ').collect{|x| x.to_i}
  f(t[0], t[1], t[2], t[3])
end

Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times:   A  BC  B  AC  C  AB  AAA  empty string Note that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source.

The first line contains a string S (1 ≤ |S| ≤ 105). The second line contains a string T (1 ≤ |T| ≤ 105), each of these strings consists only of uppercase English letters 'A', 'B' and 'C'. The third line contains the number of queries Q (1 ≤ Q ≤ 105). The following Q lines describe queries. The i-th of these lines contains four space separated integers ai, bi, ci, di. These represent the i-th query: is it possible to create T[ci..di] from S[ai..bi] by applying the above transitions finite amount of times? Here, U[x..y] is a substring of U that begins at index x (indexed from 1) and ends at index y. In particular, U[1..|U|] is the whole string U. It is guaranteed that 1 ≤ a ≤ b ≤ |S| and 1 ≤ c ≤ d ≤ |T|.

Print a string of Q characters, where the i-th character is '1' if the answer to the i-th query is positive, and '0' otherwise.

NoteIn the first query we can achieve the result, for instance, by using transitions .The third query asks for changing AAB to A — but in this case we are not able to get rid of the character 'B'.

$numAs=Array.new(1, 0)
$numBs=Array.new(1, 0)
$numAs1=Array.new(1, 0)
$numBs1=Array.new(1, 0)

def f(a, b, c, d)
    nA=[b-a+1, $numAs[b]].min
    nB=$numBs[b]-$numBs[a-1]
    nA1=[d-c+1, $numAs1[d]].min
    nB1=$numBs1[d]-$numBs1[c-1]
#    print nA, nB, nA1, nB1, "\n"
    if (nB==nB1)
        if (nA>=nA1 && (nA%3)==(nA1%3))
            print 1
        else
            print 0
        end
    elsif (nB<nB1 && (nB%2)==(nB1%2))
        if (nB==0)
            nA-=1
        end
        if (nA>=nA1)
            print 1
        else
            print 0
        end
    else
        print 0
    end
end

s=gets
s1=gets
n=gets.to_i
(0..s.length-1).each{|x| $numBs.push($numBs[x]+(s[x]=="B" || s[x]=="C" ? 1 : 0 ))}
(0..s1.length-1).each{|x| $numBs1.push($numBs1[x]+(s1[x]=="B" || s1[x]=="C" ? 1 : 0 ))}
(0..s.length-1).each{|x| $numAs.push(s[x]=='A' ? $numAs[x]+1 : 0)}
(0..s1.length-1).each{|x| $numAs1.push(s1[x]=='A' ? $numAs1[x]+1 : 0)}
t=Array.new
for i in 0...n
  t=gets.split(' ').collect{|x| x.to_i}
  f(t[0], t[1], t[2], t[3])
end


n, k = gets.split.collect{|x| x.to_i}

old_scheme = "aaaa"
(1..n).each{
  scheme = nil
  lines = Array.new(4) { gets.chomp }

  lines.each_index{|i|
    pos = []
    lines[i].scan(/[aeiou]/){pos << $~.begin(0)}
    if pos[-k].nil?
      puts "NO"
      exit
    end
    lines[i] = lines[i][pos[-k]..-1]
  }

  scheme = "aabb" if lines[0] == lines[1] and lines[2] == lines[3]
  scheme = "abab" if lines[0] == lines[2] and lines[1] == lines[3]
  scheme = "abba" if lines[0] == lines[3] and lines[1] == lines[2]
  scheme = "aaaa" if lines[0] == lines[1] and lines[1] == lines[2] and lines[2] == lines[3]
  if scheme.nil? or (old_scheme != scheme and old_scheme != "aaaa")
    puts "NO"
    exit
  end

  old_scheme = scheme
}

puts old_scheme

Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes.Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels.Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit ≠ ermit).Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines):   Clerihew (aabb);  Alternating (abab);  Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa).If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme.Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task.

The first line contains two integers n and k (1 ≤ n ≤ 2500, 1 ≤ k ≤ 5) — the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on.

Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes.

NoteIn the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".

2 1
day
may
sun
fun
test
hill
fest
thrill

n, m = gets.split.map(&:to_i)
b = [true] * 4
n.times do
    a = Array.new(4){gets[/([aeiou][^aeiou]*){#{m}}$/]}
    1.upto(3) do |i|
        if b[i]
            b[i] &= a[0] && a[0] == a[i]
            j = i != 1 ? 1 : 2
            k = i != 3 ? 3 : 2
            b[i] &= a[j] && a[j] == a[k]
        end
    end
end

if b.all?
    puts :aaaa
elsif b[1]
    puts :aabb
elsif b[2]
    puts :abab
elsif b[3]
    puts :abba
else
    puts :NO
end

[{'input': '1 1\r\nday\r\nmay\r\nsun\r\nfun\r\n', 'output': ['aabb\r\n']}, {'input': '1 1\r\nday\r\nmay\r\ngray\r\nway\r\n', 'output': ['aaaa\r\n']}, {'input': '2 1\r\na\r\na\r\na\r\na\r\na\r\na\r\ne\r\ne\r\n', 'output': ['aabb\r\n']}, {'input': '2 1\r\nday\r\nmay\r\nsun\r\nfun\r\ntest\r\nhill\r\nfest\r\nthrill\r\n', 'output': ['NO\r\n']}, {'input': '2 5\r\na\r\na\r\na\r\na\r\na\r\na\r\ne\r\ne\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\nrezwbgy\r\nxakgmv\r\njogezwbgy\r\napezwbgy\r\n', 'output': ['NO\r\n']}, {'input': '2 1\r\nnuqfxwrb\r\napqfkw\r\nuqfxwrb\r\nnhcuqfxwrb\r\nogkznwncmt\r\nevf\r\nogkznwncmt\r\nogkznwncmt\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\naawjvkxx\r\nawjvkxx\r\nxawjvkxx\r\nawjvkxx\r\n', 'output': ['aaaa\r\n']}, {'input': '2 2\r\nrhcujgxabk\r\nnjgdqpurul\r\nueoedt\r\ncpcfhbyvo\r\nzmfwnieog\r\npkpylassbf\r\nhrfeod\r\ncdwuil\r\n', 'output': ['NO\r\n']}, {'input': '2 1\r\nol\r\nol\r\nol\r\nzol\r\nek\r\nek\r\nek\r\nqek\r\n', 'output': ['aaaa\r\n']}, {'input': '3 2\r\nexdaoao\r\nrdwunurp\r\ndunurp\r\ntyqzuxao\r\ndupocgsps\r\nzsiravcm\r\nnqiravcm\r\nlnupocgsps\r\niwashk\r\neepkqcykbv\r\nyviwashk\r\neepkqcykbv\r\n', 'output': ['NO\r\n']}, {'input': '2 1\r\ndaihacbnhgfts\r\nsqihpntjvczkw\r\nmihpntjvczkw\r\nvyacbnhgfts\r\ntsvovdpqajmgvcj\r\ncexqkwrvctomb\r\njxbomb\r\ngnpajmgvcj\r\n', 'output': ['abba\r\n']}, {'input': '3 2\r\netba\r\ntfecetba\r\nzkitbgcuuy\r\nuuy\r\nbuxeoi\r\nmekxoi\r\nblviwoehy\r\niwoehy\r\njyfpaqntiz\r\nqvaqntiz\r\nhciak\r\niak\r\n', 'output': ['aabb\r\n']}, {'input': '4 3\r\niixxiojrrdytjcbkvymw\r\nbjqixxiojrrdytjcbkvymw\r\nogjixxiojrrdytjcbkvymw\r\nevixxpfxpgicpg\r\njkotitixiughfhphliuurx\r\ngyubkqtonejprfjzvqxbdpn\r\ndpudxfoqnhekjytbwiuurx\r\noubkqtonejprfjzvqxbdpn\r\npgzaendrxjhsfzjmijv\r\npomuaendrxjhsfzjmijv\r\nafyuyxueaendrxjhsfzjmijv\r\naendrxjhsfzjmijv\r\nyubweicj\r\ntbnsuxqigmxdfnmbipubweicj\r\nfuftydlmoo\r\nmdkuftydlmoo\r\n', 'output': ['NO\r\n']}, {'input': '5 2\r\nqurcmcbxyoddgyyccsmb\r\nlsdzsqoa\r\neurcmcbxyoddgyyccsmb\r\noa\r\nutyxmdhcvaclynmstwsx\r\nmkyycelbmkmdrilmbvr\r\nutyxmdhcvaclynmstwsx\r\nrduyelbmkmdrilmbvr\r\nhmguhvqswwciowwgu\r\nnoe\r\nzmyncuwrowwgu\r\nqrhymghavvbmigzsjoe\r\nbvofhknbzusykztlxwms\r\nbpbfmvjaimkdeddy\r\neofhknbzusykztlxwms\r\nmhivpkxkpazimkdeddy\r\negvywnhmfngllaknmn\r\nmblkvhenlggoftwjgk\r\nzegvywnhmfngllaknmn\r\ngrdenlggoftwjgk\r\n', 'output': ['abab\r\n']}, {'input': '7 3\r\nferwljzwakxedlgwl\r\noerwljzwakxedlgwl\r\nhyqombizhuhxedprb\r\netptjrizhuhxedprb\r\nurtuckar\r\ndkartmwramklcmi\r\nrurtuckar\r\nnurartmwramklcmi\r\niraziomsv\r\nsaziomsv\r\nbprapiqpayzurgij\r\nusyemayzurgij\r\nztstmeecvmkvuu\r\nquexlecvmkvuu\r\nrlhwecvmkvuu\r\nzecvmkvuu\r\niikymgbncljtub\r\nqiikymgbncljtub\r\nbcavhexqamyszgfya\r\nojexqamyszgfya\r\nieyxqinjinjv\r\nxtiudieyxqinjinjv\r\nthtceyxqinjinjv\r\nmuneyxqinjinjv\r\nwreae\r\nqylcjhjzfhteae\r\nozcjthgyuchqo\r\nfcjozcjthgyuchqo\r\n', 'output': ['NO\r\n']}, {'input': '16 1\r\ni\r\ni\r\ni\r\ni\r\ni\r\nu\r\ni\r\ni\r\no\r\na\r\na\r\no\r\na\r\ni\r\na\r\na\r\ni\r\ni\r\no\r\no\r\ni\r\ni\r\ni\r\ni\r\nu\r\nu\r\nu\r\nu\r\no\r\ne\r\ne\r\ne\r\no\r\ni\r\no\r\ni\r\na\r\na\r\na\r\na\r\nu\r\no\r\no\r\nu\r\ni\r\no\r\no\r\ni\r\na\r\na\r\ne\r\ne\r\na\r\na\r\na\r\na\r\na\r\no\r\na\r\na\r\nu\r\na\r\nu\r\nu\r\n', 'output': ['NO\r\n']}, {'input': '16 1\r\neb\r\neb\r\nfe\r\nce\r\ner\r\ner\r\new\r\new\r\nu\r\ncu\r\nu\r\nu\r\nud\r\nik\r\nud\r\nik\r\nve\r\niw\r\niw\r\nne\r\nel\r\nob\r\nel\r\nob\r\no\r\neo\r\no\r\nyo\r\nav\r\nav\r\nei\r\nmi\r\nu\r\noh\r\noh\r\nzu\r\niw\r\niw\r\na\r\nma\r\ni\r\nu\r\nku\r\ngi\r\nac\r\no\r\no\r\nac\r\ni\r\ner\r\nai\r\ner\r\nyu\r\nuf\r\nuf\r\nhu\r\nef\r\nef\r\nef\r\nef\r\nmu\r\nu\r\nqe\r\nie\r\n', 'output': ['NO\r\n']}, {'input': '25 1\r\nw\r\ni\r\nv\r\nx\r\nh\r\ns\r\nz\r\ny\r\no\r\nn\r\nh\r\ni\r\nf\r\nf\r\ny\r\nr\r\nb\r\nu\r\no\r\np\r\nz\r\nh\r\nt\r\no\r\nw\r\nx\r\nh\r\no\r\nj\r\ny\r\nw\r\nj\r\ny\r\nh\r\nh\r\nr\r\ns\r\nb\r\ny\r\nr\r\nw\r\no\r\nl\r\nl\r\nh\r\nh\r\nw\r\nu\r\na\r\nv\r\no\r\nx\r\nd\r\nw\r\nc\r\nf\r\ni\r\ne\r\nj\r\nq\r\nk\r\na\r\ne\r\nl\r\nw\r\nm\r\nf\r\na\r\nc\r\na\r\nb\r\nf\r\nj\r\nb\r\nx\r\ni\r\nx\r\ne\r\nu\r\nh\r\nm\r\no\r\ni\r\nq\r\nm\r\nk\r\nn\r\nd\r\nl\r\np\r\nc\r\nw\r\nu\r\nz\r\nc\r\nk\r\ng\r\ny\r\nj\r\ny\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\ne\r\ne\r\ne\r\ne\r\n', 'output': ['aaaa\r\n']}, {'input': '1 1\r\na\r\ne\r\ne\r\ne\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\ne\r\na\r\ne\r\ne\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\na\r\na\r\ne\r\ne\r\n', 'output': ['aabb\r\n']}, {'input': '1 1\r\ne\r\ne\r\na\r\ne\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\na\r\ne\r\na\r\ne\r\n', 'output': ['abab\r\n']}, {'input': '1 1\r\ne\r\na\r\na\r\ne\r\n', 'output': ['abba\r\n']}, {'input': '1 1\r\na\r\na\r\na\r\ne\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\ne\r\ne\r\ne\r\na\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\na\r\ne\r\ne\r\na\r\n', 'output': ['abba\r\n']}, {'input': '1 1\r\ne\r\na\r\ne\r\na\r\n', 'output': ['abab\r\n']}, {'input': '1 1\r\na\r\na\r\ne\r\na\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\ne\r\ne\r\na\r\na\r\n', 'output': ['aabb\r\n']}, {'input': '1 1\r\na\r\ne\r\na\r\na\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\ne\r\na\r\na\r\na\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\na\r\na\r\na\r\na\r\n', 'output': ['aaaa\r\n']}, {'input': '1 2\r\neraub\r\nbee\r\naab\r\nttbee\r\n', 'output': ['NO\r\n']}, {'input': '10 1\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\na\r\ny\r\n', 'output': ['NO\r\n']}, {'input': '1 2\r\neeereaatktb\r\nbee\r\niaattb\r\nottbee\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\nab\r\nac\r\nad\r\naf\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\nar\r\nat\r\nay\r\naw\r\n', 'output': ['NO\r\n']}, {'input': '2 1\r\na\r\ne\r\na\r\ne\r\na\r\na\r\na\r\na\r\n', 'output': ['abab\r\n']}, {'input': '1 1\r\na\r\ne\r\na\r\ni\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\na\r\ne\r\na\r\ne\r\n', 'output': ['abab\r\n']}, {'input': '1 1\r\nabbbbbbbbbbbbbbbbcbbbbbbbbbbbbbbbb\r\nabbbbbbbbbbbbbbbbfbbbbbbbbbbbbbbbb\r\nabbbbbbbbbbbbbbbbxbbbbbbbbbbbbbbbb\r\nabbbbbbbbbbbbbbbbdbbbbbbbbbbbbbbbb\r\n', 'output': ['NO\r\n']}, {'input': '2 1\r\na\r\ne\r\ne\r\na\r\na\r\na\r\na\r\na\r\n', 'output': ['abba\r\n']}, {'input': '1 1\r\nbug\r\nsuy\r\nluh\r\ngut\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\nam\r\nat\r\nan\r\nag\r\n', 'output': ['NO\r\n']}, {'input': '2 1\r\na\r\na\r\ne\r\ne\r\na\r\na\r\na\r\na\r\n', 'output': ['aabb\r\n']}, {'input': '1 4\r\naieoabcd\r\naeioabcd\r\naoeiabcd\r\naoieabcd\r\n', 'output': ['NO\r\n']}, {'input': '1 2\r\naec\r\naed\r\naek\r\naem\r\n', 'output': ['NO\r\n']}, {'input': '1 1\r\nar\r\nab\r\nak\r\naz\r\n', 'output': ['NO\r\n']}, {'input': '2 1\r\na\r\na\r\na\r\na\r\na\r\nb\r\nb\r\nb\r\n', 'output': ['NO\r\n']}]


n, m = gets.split.map(&:to_i)
identifiers = {}
memory_blocks = {}
identifier = 1

n.times do
	command = gets.split(' ')
	case command[0]
		when "alloc"
			start_index = 0
			block_size = command[1].to_i
			fit = false
			while memory_blocks[start_index]
				start_index += memory_blocks[start_index]
			end
			while start_index + block_size <= m
				break if block_size == m && !memory_blocks.empty?
				check = memory_blocks.select { |k, v| (k < start_index + block_size) && (k >= start_index) }
				if check.empty?
					memory_blocks[start_index] = block_size
					identifiers[identifier] = start_index
					puts identifier
					identifier += 1
					fit = true
					puts "memory_blocks is #{memory_blocks}"
					puts "identifiers is #{identifiers}"
					break
				else
					next_index = check.min
					start_index = next_index[0] + memory_blocks[next_index[0]]
				end
			end
			puts "NULL" unless fit
		when "erase"
			d_iden = command[1].to_i
			iden_index = identifiers[d_iden]
			if iden_index.nil?
				puts "ILLEGAL_ERASE_ARGUMENT"
			else
				identifiers.delete(d_iden)
				memory_blocks.delete(iden_index)
				puts "memory_blocks is #{memory_blocks}"
				puts "identifiers is #{identifiers}"
			end
		else # defragment
			start_index = 0
			copy = {}
			memory_blocks.size.times do
				lowest = memory_blocks.min
				copy[start_index] = lowest[1]
				identifiers[identifiers.key(lowest[0])] = start_index
				start_index += lowest[1]
				memory_blocks.delete(lowest[0])
			end
			memory_blocks = copy
			puts "memory_blocks is #{memory_blocks}"
			puts "identifiers is #{identifiers}"
		end
end

There is little time left before the release of the first national operating system BerlOS. Some of its components are not finished yet — the memory manager is among them. According to the developers' plan, in the first release the memory manager will be very simple and rectilinear. It will support three operations:   alloc n — to allocate n bytes of the memory and return the allocated block's identifier x;  erase x — to erase the block with the identifier x;  defragment — to defragment the free memory, bringing all the blocks as close to the beginning of the memory as possible and preserving their respective order; The memory model in this case is very simple. It is a sequence of m bytes, numbered for convenience from the first to the m-th.The first operation alloc n takes as the only parameter the size of the memory block that is to be allocated. While processing this operation, a free block of n successive bytes is being allocated in the memory. If the amount of such blocks is more than one, the block closest to the beginning of the memory (i.e. to the first byte) is prefered. All these bytes are marked as not free, and the memory manager returns a 32-bit integer numerical token that is the identifier of this block. If it is impossible to allocate a free block of this size, the function returns NULL.The second operation erase x takes as its parameter the identifier of some block. This operation frees the system memory, marking the bytes of this block as free for further use. In the case when this identifier does not point to the previously allocated block, which has not been erased yet, the function returns ILLEGAL_ERASE_ARGUMENT.The last operation defragment does not have any arguments and simply brings the occupied memory sections closer to the beginning of the memory without changing their respective order.In the current implementation you are to use successive integers, starting with 1, as identifiers. Each successful alloc operation procession should return following number. Unsuccessful alloc operations do not affect numeration.You are to write the implementation of the memory manager. You should output the returned value for each alloc command. You should also output ILLEGAL_ERASE_ARGUMENT for all the failed erase commands.

The first line of the input data contains two positive integers t and m (1 ≤ t ≤ 100;1 ≤ m ≤ 100), where t — the amount of operations given to the memory manager for processing, and m — the available memory size in bytes. Then there follow t lines where the operations themselves are given. The first operation is alloc n (1 ≤ n ≤ 100), where n is an integer. The second one is erase x, where x is an arbitrary 32-bit integer numerical token. The third operation is defragment.

Output the sequence of lines. Each line should contain either the result of alloc operation procession , or ILLEGAL_ERASE_ARGUMENT as a result of failed erase operation procession. Output lines should go in the same order in which the operations are processed. Successful procession of alloc operation should return integers, starting with 1, as the identifiers of the allocated blocks.

6 10
alloc 5
alloc 3
erase 1
alloc 6
defragment
alloc 6

input = gets.chomp.split.map do |x|
    Integer(x)
end

n = input[0]
m = input[1]

memory = Array.new(m) { |i| 0 }
next_id = 1

def find_and_fill_block(memory, len, next_id)
    head = 0
    for i in 0...memory.length
        if head <= i - len
            break
        end

        if memory[i] != 0
            head = i + 1
        end
    end
    if head + len <= memory.length
        for i in 0...len
            memory[head + i] = next_id
        end
        return true
    end

    return false
end

def erase_block(memory, id)
    flag = false
    for i in 0...memory.length
        if memory[i] == id
            memory[i] = 0
            flag = true
        end
    end

    return flag
end

def defragment(memory)
    j = 0
    for i in 0...memory.length
        if memory[i] != 0
            memory[j] = memory[i]
            j += 1
        end
    end
    for i in j...memory.length
        memory[i] = 0
    end
end

for i in 0...n
    input = gets.chomp.split
    command = input[0]
    if command[0] == 'a'
        len = Integer(input[1])
        ret = find_and_fill_block(memory, len, next_id)
        if ret
            puts next_id
            next_id += 1
        else
            puts "NULL"
        end
    elsif command[0] == 'e'
        cur_id = Integer(input[1])
        ret = cur_id != 0 && erase_block(memory, cur_id)
        if !ret
            puts "ILLEGAL_ERASE_ARGUMENT"
        end
    else
        defragment(memory)
    end
end

[{'input': '6 10\r\nalloc 5\r\nalloc 3\r\nerase 1\r\nalloc 6\r\ndefragment\r\nalloc 6\r\n', 'output': ['1\r\n2\r\nNULL\r\n3\r\n']}, {'input': '6 1\r\ndefragment\r\nalloc 10\r\nalloc 1\r\nerase -1\r\nerase 1\r\nerase 1\r\n', 'output': ['NULL\r\n1\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '14 100\r\nalloc 99\r\nalloc 1\r\nalloc 1\r\nerase 2\r\nalloc 1\r\nerase 4\r\nerase 1\r\nalloc 100\r\nalloc 1\r\nalloc 99\r\ndefragment\r\nerase 4\r\nalloc 100\r\nalloc 99\r\n', 'output': ['1\r\n2\r\nNULL\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n4\r\nNULL\r\nNULL\r\nNULL\r\n']}, {'input': '26 25\r\ndefragment\r\nerase 1\r\nerase -1560200883\r\nalloc 44\r\ndefragment\r\nalloc 75\r\nalloc 22\r\ndefragment\r\nerase 4\r\ndefragment\r\nalloc 57\r\nalloc 53\r\nerase 4\r\nerase -1639632026\r\nerase -2121605039\r\nerase 3\r\nalloc 51\r\nalloc 65\r\ndefragment\r\nerase 2\r\nerase 4\r\nalloc 52\r\nerase 3\r\ndefragment\r\nerase -1842529282\r\nerase 3\r\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\n1\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '22 9\r\nerase 1\r\nalloc 6\r\nalloc 65\r\nerase 1\r\nalloc 87\r\nerase -1638927047\r\nalloc 5\r\nerase 2\r\nalloc 70\r\ndefragment\r\nalloc 20\r\nalloc 48\r\nerase -69401977\r\nalloc 20\r\ndefragment\r\nerase 7\r\ndefragment\r\nerase 9\r\nerase 7\r\nerase 4\r\ndefragment\r\nalloc 66\r\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\r\n1\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\nNULL\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n']}, {'input': '12 40\r\nerase 1\r\nalloc 21\r\nalloc 5\r\nalloc 7\r\ndefragment\r\ndefragment\r\nerase 2\r\nalloc 83\r\nerase 4\r\ndefragment\r\nalloc 59\r\ndefragment\r\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\r\n1\r\n2\r\n3\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n']}, {'input': '38 18\r\nalloc 72\r\nerase 2\r\nalloc 50\r\ndefragment\r\nerase 3\r\ndefragment\r\nalloc 43\r\nalloc 41\r\ndefragment\r\ndefragment\r\nalloc 26\r\nalloc 46\r\nalloc 16\r\nalloc 15\r\ndefragment\r\ndefragment\r\nalloc 95\r\nerase 7\r\nerase 7\r\nerase 5\r\nerase 2\r\nerase 9\r\nerase 7\r\nalloc 43\r\ndefragment\r\nerase 7\r\ndefragment\r\nalloc 48\r\nalloc 77\r\nerase 10\r\nerase 11\r\nalloc 16\r\nalloc 84\r\nerase 1\r\ndefragment\r\nalloc 86\r\ndefragment\r\nerase 13\r\n', 'output': ['NULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nNULL\r\nNULL\r\n1\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '37 74\r\nalloc 11\r\ndefragment\r\nerase 1\r\ndefragment\r\nerase 2\r\ndefragment\r\nalloc 90\r\nerase 3\r\nerase 2\r\nerase 3\r\nerase 1\r\nerase 1\r\nalloc 38\r\nalloc 19\r\nerase 1\r\nerase 3\r\ndefragment\r\nalloc 93\r\nerase 5\r\nerase 4\r\nalloc 66\r\nalloc 71\r\nerase 5\r\ndefragment\r\ndefragment\r\ndefragment\r\ndefragment\r\nerase 7\r\nalloc 47\r\nerase -95616683\r\nerase 2\r\nalloc 28\r\nalloc 32\r\nerase 11\r\nalloc 50\r\ndefragment\r\ndefragment\r\n', 'output': ['1\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n4\r\n5\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n']}, {'input': '16 49\r\nerase -751005193\r\ndefragment\r\nalloc 37\r\nalloc 82\r\nerase 3\r\nerase 1\r\nalloc 80\r\nalloc 51\r\ndefragment\r\nalloc 74\r\nerase 1\r\nalloc 91\r\ndefragment\r\ndefragment\r\nalloc 98\r\ndefragment\r\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\r\n1\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\n']}, {'input': '42 98\r\ndefragment\r\ndefragment\r\ndefragment\r\ndefragment\r\ndefragment\r\nalloc 5\r\nalloc 66\r\ndefragment\r\nerase 3\r\nalloc 53\r\ndefragment\r\nerase 4\r\nerase 2\r\nalloc 70\r\nerase 3\r\ndefragment\r\ndefragment\r\nerase 2\r\nerase 3\r\nerase -1327931832\r\nalloc 93\r\nalloc 64\r\nerase 7\r\nerase 6\r\nerase 3\r\nalloc 61\r\nalloc 12\r\nalloc 65\r\nerase 2\r\nalloc 46\r\nerase 11\r\nerase 9\r\nerase 9\r\nerase 6\r\nalloc 2\r\nalloc 78\r\ndefragment\r\nerase 13\r\nerase 6\r\nerase 10\r\nalloc 53\r\nalloc 46\r\n', 'output': ['1\r\n2\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n4\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\n']}, {'input': '19 46\r\nalloc 21\r\nerase 2\r\nerase 1\r\ndefragment\r\nalloc 4\r\ndefragment\r\ndefragment\r\nalloc 40\r\nerase 1\r\ndefragment\r\ndefragment\r\nalloc 68\r\nerase -388966015\r\nalloc 85\r\nalloc 53\r\nerase 4\r\ndefragment\r\nalloc 49\r\nalloc 88\r\n', 'output': ['1\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\n']}, {'input': '44 46\r\nalloc 28\r\nalloc 36\r\ndefragment\r\nerase -937404236\r\nalloc 71\r\ndefragment\r\nalloc 81\r\nalloc 51\r\nerase 3\r\ndefragment\r\nalloc 48\r\nerase 1\r\ndefragment\r\nalloc 36\r\ndefragment\r\ndefragment\r\nerase 1\r\ndefragment\r\ndefragment\r\nerase -1173350787\r\nalloc 94\r\nerase 5\r\ndefragment\r\nerase 9\r\nalloc 98\r\nerase 7\r\ndefragment\r\nerase 5\r\nerase 1\r\ndefragment\r\nerase 2\r\ndefragment\r\nerase 4\r\ndefragment\r\nerase 9\r\nalloc 8\r\ndefragment\r\nerase 9\r\ndefragment\r\ndefragment\r\ndefragment\r\nerase 1\r\nalloc 70\r\nerase 9\r\n', 'output': ['1\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nNULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n2\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '26 25\r\nalloc 25\r\nerase 1\r\nalloc 24\r\nerase 2\r\nalloc 23\r\nerase 3\r\nalloc 24\r\nerase 4\r\nalloc 24\r\nerase 5\r\nalloc 21\r\nerase 6\r\nalloc 24\r\nerase 7\r\nalloc 25\r\nerase 8\r\nalloc 25\r\nerase 9\r\nalloc 24\r\nerase 10\r\nalloc 25\r\nerase 11\r\nalloc 25\r\nerase 12\r\nalloc 25\r\nerase 13\r\n', 'output': ['1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n11\r\n12\r\n13\r\n']}, {'input': '22 9\r\nalloc 9\r\nerase 1\r\nalloc 9\r\nerase 2\r\nalloc 9\r\nerase 3\r\nalloc 9\r\nerase 4\r\nalloc 9\r\nerase 5\r\nalloc 9\r\nerase 6\r\nalloc 9\r\nerase 7\r\nalloc 9\r\nerase 8\r\nalloc 9\r\nerase 9\r\nalloc 9\r\nerase 10\r\nalloc 9\r\nerase 11\r\n', 'output': ['1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n10\r\n11\r\n']}, {'input': '7 6\r\nalloc 1\r\nalloc 2\r\nalloc 3\r\nerase 1\r\ndefragment\r\nerase 3\r\nalloc 4\r\n', 'output': ['1\r\n2\r\n3\r\n4\r\n']}, {'input': '3 1\r\nerase -1\r\nerase 0\r\nerase -2147483648\r\n', 'output': ['ILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '7 100\r\nalloc 100\r\nerase 2147483647\r\nerase 1\r\nalloc 50\r\nalloc 50\r\nerase 3\r\nerase -2147483648\r\n', 'output': ['1\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\n']}, {'input': '12 10\r\nalloc 6\r\nalloc 2\r\nerase 1\r\nalloc 4\r\nalloc 2\r\nerase 3\r\nalloc 2\r\nalloc 3\r\nalloc 1\r\nalloc 1\r\nalloc 1\r\nalloc 1\r\n', 'output': ['1\r\n2\r\n3\r\n4\r\n5\r\nNULL\r\n6\r\n7\r\n8\r\n9\r\n']}, {'input': '8 50\r\nalloc 51\r\ndefragment\r\nalloc 100\r\ndefragment\r\nerase 1\r\nalloc 50\r\ndefragment\r\nalloc 50\r\n', 'output': ['NULL\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n1\r\nNULL\r\n']}, {'input': '10 10\r\nalloc 10\r\nerase -1\r\nerase 1\r\nalloc 5\r\nerase -1\r\nalloc 5\r\nerase 0\r\nalloc 5\r\nerase 0\r\nalloc 5\r\n', 'output': ['1\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\nILLEGAL_ERASE_ARGUMENT\r\n3\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\nNULL\r\n']}, {'input': '16 10\r\nalloc 10\r\ndefragment\r\ndefragment\r\ndefragment\r\nalloc 10\r\nerase 1\r\nerase 2\r\nalloc 6\r\ndefragment\r\ndefragment\r\nalloc 4\r\ndefragment\r\ndefragment\r\nerase 3\r\ndefragment\r\nalloc 6\r\n', 'output': ['1\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\n3\r\nNULL\r\n']}, {'input': '16 10\r\nalloc 10\r\ndefragment\r\ndefragment\r\ndefragment\r\nalloc 10\r\nerase 1\r\nerase 2\r\nalloc 6\r\ndefragment\r\ndefragment\r\nalloc 4\r\ndefragment\r\ndefragment\r\nerase 2\r\ndefragment\r\nalloc 6\r\n', 'output': ['1\r\nNULL\r\nILLEGAL_ERASE_ARGUMENT\r\n2\r\n3\r\n4\r\n']}]


n = gets.to_i
arr = gets.split(" ").map(&:to_i).sort.reverse
ans = nil
if arr.include?(0)
	sum = arr.inject(0,:+)
	if sum % 3 == 0
		ans = arr.join("")
	elsif sum % 3 == 1

		one = [1,4,7]
		two = [2,5,8]
		l = nil
		one.each do |o|
			l = arr.rindex(o)
			if l
				arr.delete_at(l)
				break
			end
		end

		unless l
			deleted = 0
			two.each do |t|
				l = arr.rindex(t)
				if l
					if deleted == 0
						l1 = arr.index(t)
						if l == l1
							arr.delete_at(l)
							deleted = 1
							next
						else
							arr.delete_at(l)
							arr.delete_at(l1)
							break
						end
					end

					if deleted == 1
						arr.delete_at(l)
					end

				end
			end
		end

		# j = arr.length - 1
		# while j >= 0
		# 	a = arr[j]

		# 	if a % 3 == 1 && one.length < 1
		# 		one << j
		# 		break
		# 	end

		# 	if a % 3 == 2  && two.length < 2
		# 		two << j
		# 	end
		# 	j -= 1
		# end
		# if one.empty?
		# 	arr.delete_at(two[0])
		# 	arr.delete_at(two[1])
		# else
		# 	arr.delete_at(one[0])
		# end

		# puts "here"
		# l = arr.rindex{|a| a % 3 == 1}
		# if l
		# 	arr.delete_at(l)
		# else
		# 	l = arr.rindex{|a| a % 3 == 2}
		# 	arr.delete_at(l)
		# 	l = arr.rindex{|a| a % 3 == 2}
		# 	arr.delete_at(l)
		# end
	else

		one = [1,4,7]
		two = [2,5,8]
		l = nil
		two.each do |o|
			l = arr.rindex(o)
			if l
				arr.delete_at(l)
				break
			end
		end

		unless l
			deleted = 0
			one.each do |t|
				l = arr.rindex(t)
				if l
					if deleted == 0
						l1 = arr.index(t)
						if l == l1
							arr.delete_at(l)
							deleted = 1
							next
						else
							arr.delete_at(l)
							arr.delete_at(l1)
							break
						end
					end

					if deleted == 1
						arr.delete_at(l)
					end

				end
			end
		end

		# one = [1,4,7]
		# two = [2,5,8]
		# j = arr.length - 1
		# while j >= 0
		# 	a = arr[j]

		# 	if a % 3 == 2 && two.length < 1
		# 		two << j
		# 		break
		# 	end

		# 	if a % 3 == 1  && one.length < 2
		# 		one << j
		# 	end
		# 	j -= 1
		# end
		# if two.empty?
		# 	arr.delete_at(one[0])
		# 	arr.delete_at(one[1])
		# else
		# 	arr.delete_at(two[0])
		# end

		# l = arr.rindex{|a| a % 3 == 2}
		# if l
		# 	arr.delete_at(l)
		# else
		# 	l = arr.rindex{|a| a % 3 == 1}
		# 	arr.delete_at(l)
		# 	l = arr.rindex{|a| a % 3 == 1}
		# 	arr.delete_at(l)
		# end
	end
	ans = arr.join("")
	if ans.to_i == 0
		puts "0"
	else
		puts ans
	end
else
	puts "-1"
end

Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.Each digit is allowed to occur in the number the same number of times it occurs in the set.

A single line contains a single integer n (1 ≤ n ≤ 100000) — the number of digits in the set. The second line contains n digits, the digits are separated by a single space.

On a single line print the answer to the problem. If such number does not exist, then you should print -1.

NoteIn the first sample there is only one number you can make — 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number.

n = gets.to_i
arr = gets.split(" ").map(&:to_i).sort.reverse
ans = nil
if arr.include?(0)
	sum = arr.inject(0,:+)
	if sum % 3 == 0
		ans = arr.join("")
	elsif sum % 3 == 1

		one = [1,4,7]
		two = [2,5,8]
		l = nil
		one.each do |o|
			l = arr.rindex(o)
			if l
				arr.delete_at(l)
				break
			end
		end

		unless l
			deleted = 0
			two.each do |t|
				l = arr.rindex(t)
				if l
					if deleted == 0
						l1 = arr.index(t)
						if l == l1
							arr.delete_at(l)
							deleted = 1
							next
						else
							arr.delete_at(l)
							arr.delete_at(l1)
							break
						end
					end

					if deleted == 1
						arr.delete_at(l)
					end

				end
			end
		end

		# j = arr.length - 1
		# while j >= 0
		# 	a = arr[j]

		# 	if a % 3 == 1 && one.length < 1
		# 		one << j
		# 		break
		# 	end

		# 	if a % 3 == 2  && two.length < 2
		# 		two << j
		# 	end
		# 	j -= 1
		# end
		# if one.empty?
		# 	arr.delete_at(two[0])
		# 	arr.delete_at(two[1])
		# else
		# 	arr.delete_at(one[0])
		# end

		# puts "here"
		# l = arr.rindex{|a| a % 3 == 1}
		# if l
		# 	arr.delete_at(l)
		# else
		# 	l = arr.rindex{|a| a % 3 == 2}
		# 	arr.delete_at(l)
		# 	l = arr.rindex{|a| a % 3 == 2}
		# 	arr.delete_at(l)
		# end
	else

		one = [1,4,7]
		two = [2,5,8]
		l = nil
		two.each do |o|
			l = arr.rindex(o)
			if l
				arr.delete_at(l)
				break
			end
		end

		unless l
			deleted = 0
			one.each do |t|
				l = arr.rindex(t)
				if l
					if deleted == 0
						l1 = arr.index(t)
						if l == l1
							arr.delete_at(l)
							deleted = 1
							next
						else
							arr.delete_at(l)
							arr.delete_at(l1)
							break
						end
					end

					if deleted == 1
						arr.delete_at(l)
					end

				end
			end
		end

		# one = [1,4,7]
		# two = [2,5,8]
		# j = arr.length - 1
		# while j >= 0
		# 	a = arr[j]

		# 	if a % 3 == 2 && two.length < 1
		# 		two << j
		# 		break
		# 	end

		# 	if a % 3 == 1  && one.length < 2
		# 		one << j
		# 	end
		# 	j -= 1
		# end
		# if two.empty?
		# 	arr.delete_at(one[0])
		# 	arr.delete_at(one[1])
		# else
		# 	arr.delete_at(two[0])
		# end

		# l = arr.rindex{|a| a % 3 == 2}
		# if l
		# 	arr.delete_at(l)
		# else
		# 	l = arr.rindex{|a| a % 3 == 1}
		# 	arr.delete_at(l)
		# 	l = arr.rindex{|a| a % 3 == 1}
		# 	arr.delete_at(l)
		# end
	end
	ans = arr.join("")
	unless /[^0]/ =~ ans
		puts "0"
	else
		puts ans
	end
else
	puts "-1"
end


number_of_books,limit_height = gets.split.collect! {|x| x.to_i}

books_height = []
books_height = gets.split.collect! {|x| x.to_i}

max_books = 1
result = []
max_h = min_h = books_height[0]
max_i = min_i = 0
max_sub_h = 0
min_sub_h = 1000000
max_sub_i = min_sub_i = 0
count = 0
i = 0
while i < number_of_books
#(number_of_books).times do |i|
#    count = i + 1
#    max_h = min_h = books_height[i]
#    max_i = min_i = count - 1
    if max_sub_i > i
        max_h = max_sub_h
        max_i = max_sub_i
    else
        max_h = books_height[i]
        max_i = i
        count = i + 1
    end
    if min_sub_i > i
        min_h = min_sub_i
        min_i = min_sub_i
    else
        min_h = books_height[i]
        min_i = i
        count = i + 1
    end
    max_sub_h = 0
    min_sub_h = 1000000
    max_sub_i = min_sub_i = 0
    while count < number_of_books
        if max_h <= books_height[count]
            max_h = books_height[count]
            max_i = count
        elsif min_h >= books_height[count]
            min_h = books_height[count]
            min_i = count
        elsif max_i < min_i && max_sub_h < max_h
            max_sub_h = books_height[count]
            max_sub_i = count
        elsif min_i < max_i && min_sub_h > min_h
            min_sub_h = books_height[count]
            min_sub_i = count
        end
        if (max_h - min_h).abs > limit_height
            break
        end
        count += 1
    end
    if count - i >= max_books
        if count - i > max_books
            result.clear
        end
        max_books = count - i
        result.push [i + 1,count]
    end
    if count == number_of_books || number_of_books - i <= max_books
        break
    elsif max_i >= min_i
        i = min_i + 1
    elsif min_i > max_i
        i = max_i + 1
    else
        i += 1
    end
end
puts max_books.to_s + ' ' + result.length.to_s
result.length.times do |i|
    puts result[i][0].to_s + ' ' + result[i][1].to_s
end

There are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were published during a particular time period. It is obvious that if the books differ much in size, the visitors will not like it. That was why the organizers came to the opinion, that the difference between the highest and the lowest books in the exposition should be not more than k millimeters.The library has n volumes of books by Berlbury, arranged in chronological order of their appearance. The height of each book in millimeters is know, it is hi. As Berlbury is highly respected in the city, the organizers want to include into the exposition as many books as possible, and to find out what periods of his creative work they will manage to cover. You are asked to help the organizers cope with this hard task.

The first line of the input data contains two integer numbers separated by a space n (1 ≤ n ≤ 105) and k (0 ≤ k ≤ 106) — the amount of books by Berlbury in the library, and the maximum allowed height difference between the lowest and the highest books. The second line contains n integer numbers separated by a space. Each number hi (1 ≤ hi ≤ 106) is the height of the i-th book in millimeters.

In the first line of the output data print two numbers a and b (separate them by a space), where a is the maximum amount of books the organizers can include into the exposition, and b — the amount of the time periods, during which Berlbury published a books, and the height difference between the lowest and the highest among these books is not more than k milllimeters. In each of the following b lines print two integer numbers separated by a space — indexes of the first and the last volumes from each of the required time periods of Berlbury's creative work.

number_of_books,limit_height = gets.split.collect! {|x| x.to_i}

books_height = []
books_height = gets.split.collect! {|x| x.to_i}

max_books = 1
result = []
max_h = min_h = books_height[0]
max_i = min_i = 0
max_sub_h = 0
min_sub_h = 1000000
max_sub_i = min_sub_i = 0
count = 0
i = 0
while i < number_of_books
    if max_sub_i > i
        max_h = max_sub_h
        max_i = max_sub_i
    else
        max_h = books_height[i]
        max_i = i
    end
    if min_sub_i > i
        min_h = min_sub_i
        min_i = min_sub_i
    else
        min_h = books_height[i]
        min_i = i
    end
    if count <= i
        count = i + 1
    end
    max_sub_h = 0
    min_sub_h = 1000000
    max_sub_i = min_sub_i = 0
    while count < number_of_books
        if max_h <= books_height[count]
            max_h = books_height[count]
            max_i = count
        elsif min_h >= books_height[count]
            min_h = books_height[count]
            min_i = count
        elsif max_i < min_i && max_sub_h < max_h
            max_sub_h = books_height[count]
            max_sub_i = count
        elsif min_i < max_i && min_sub_h > min_h
            min_sub_h = books_height[count]
            min_sub_i = count
        end
        if (max_h - min_h).abs > limit_height
            break
        end
        count += 1
    end
    if count - i >= max_books
        if count - i > max_books
            result.clear
        end
        max_books = count - i
        result.push [i + 1,count]
    end
    if count == number_of_books || number_of_books - i <= max_books
        break
    elsif max_i >= min_i
        i = min_i + 1
    elsif min_i > max_i
        i = max_i + 1
    else
        i += 1
    end
    count -= 1
end
puts max_books.to_s + ' ' + result.length.to_s
result.length.times do |i|
    puts result[i][0].to_s + ' ' + result[i][1].to_s
end


Game "Minesweeper 1D" is played on a line of squares, the line's height is 1 square, the line's width is n squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 — the total number of bombs in adjacent squares.For example, the correct field to play looks like that: 001*2***101*. The cells that are marked with "*" contain bombs. Note that on the correct field the numbers represent the number of bombs in adjacent cells. For example, field 2* is not correct, because cell with value 2 must have two adjacent cells with bombs.Valera wants to make a correct field to play "Minesweeper 1D". He has already painted a squared field with width of n cells, put several bombs on the field and wrote numbers into some cells. Now he wonders how many ways to fill the remaining cells with bombs and numbers are there if we should get a correct field in the end.

The first line contains sequence of characters without spaces s1s2... sn (1 ≤ n ≤ 106), containing only characters "*", "?" and digits "0", "1" or "2". If character si equals "*", then the i-th cell of the field contains a bomb. If character si equals "?", then Valera hasn't yet decided what to put in the i-th cell. Character si, that is equal to a digit, represents the digit written in the i-th square.

Print a single integer — the number of ways Valera can fill the empty cells and get a correct field. As the answer can be rather large, print it modulo 1000000007 (109 + 7).

NoteIn the first test sample you can get the following correct fields: 001**1, 001***, 001*2*, 001*10.

s = gets.chomp!
mods = 1000000007
dp = [[0,0,0],[0,0,0]]

len =s.size
cur =0;nxt=1;

case s[0]
when '0'
	dp[cur][0]=1
when '1'
	dp[cur][1]=1
when '2'
	p 0
	exit
when '*'
	dp[cur][2]=1
when '?'
	dp[cur][0]=dp[cur][1]=dp[cur][2]=1
end

for i in 1...len
	case s[i]
	when '0'
		dp[nxt][0]=dp[cur][0]
	when '1'
		dp[nxt][1]= dp[cur][0]
		dp[nxt][0]= dp[cur][2]
	when '2'
		dp[nxt][1]=dp[cur][2]
	when '*'
		dp[nxt][2]= (dp[cur][1]+dp[cur][2])%mods
	when '?'
		dp[nxt][1]= (dp[cur][2]+dp[cur][0])%mods
		dp[nxt][0]= (dp[cur][0]+dp[cur][2])%mods
		dp[nxt][2]= (dp[cur][1]+dp[cur][2])%mods
	end
	cur = nxt
	nxt = cur==0?1:0
	dp[nxt] = [0,0,0]
end

puts "#{(dp[cur][0]+dp[cur][2])%mods}"


#!/usr/bin/env/ruby

def exec(debug = false)
  length = gets.chomp.to_i
  elements = gets.chomp.split(/\s/).map{|s| s.to_i}
  return puts "NO" unless length == elements.size

  max = length / 3
  p "max: #{max}" if debug
  max.times do |i|
    ii = i + 1
    p "ii: #{ii}" if debug
    next if length % ii != 0
    elements.each_with_index do |e, index|
      break if index == max
      success = true
      next if e == 0
      next if index >= ii
      p "index:#{index}" if debug
      (index + ii).step(length - 1, ii) do |j|
        p "j: #{j}" if debug
        unless elements[j] == 1
          p "break" if debug
          success = false
          break
        end
      end
      return puts("YES") if success
    end
  end
  puts "NO"
end

exec(debug = true)
#exec

There are n knights sitting at the Round Table at an equal distance from each other. Each of them is either in a good or in a bad mood.Merlin, the wizard predicted to King Arthur that the next month will turn out to be particularly fortunate if the regular polygon can be found. On all vertices of the polygon knights in a good mood should be located. Otherwise, the next month will bring misfortunes.A convex polygon is regular if all its sides have same length and all his angles are equal. In this problem we consider only regular polygons with at least 3 vertices, i. e. only nondegenerated.On a picture below some examples of such polygons are present. Green points mean knights in a good mood. Red points mean ones in a bad mood.  King Arthur knows the knights' moods. Help him find out if the next month will be fortunate or not.

The first line contains number n, which is the number of knights at the round table (3 ≤ n ≤ 105). The second line contains space-separated moods of all the n knights in the order of passing them around the table. "1" means that the knight is in a good mood an "0" means that he is in a bad mood.

Print "YES" without the quotes if the following month will turn out to be lucky. Otherwise, print "NO".

n=gets.to_i
a=gets.split.map(&:to_i)
3.upto(n){|i|
        if n%i==0 then
                k=n/i
                k.times{|j|
                        ok=1
                        now=j
                        i.times{
                                if a[now]==0 then
                                        ok=0
                                        break
                                end
                                now+=k
                        }
                        if ok==1 then
                                puts "YES"
                                exit
                        end
                }
        end
}
puts "NO"


#!/usr/bin/env ruby
class Integer
  def min(x)
    self < x ? self : x
  end
end
n = gets.to_i
a = gets.split.map { |x| x.to_i }
b = (0...n).to_a.sort_by { |x| a[x] }
ls = []; nx = []
l = 0; r = n - 1
n.times do |i|
  ls[i] = i - 1
  nx[i] = i + 1
end
ans = 0
b.each_with_index do |i, ix|
  break if ix > n - 2
  if i == l
    ans += a[i]
    l = nx[l]
  elsif i == r
    ans += a[i]
    r = ls[r]
  else
    ans += a[ls[i]].min(a[nx[i]])
    nx[ls[i]] = nx[i]
    ls[nx[i]] = ls[i]
  end
end
puts ans

Artem has an array of n positive integers. Artem decided to play with it. The game consists of n moves. Each move goes like this. Artem chooses some element of the array and removes it. For that, he gets min(a, b) points, where a and b are numbers that were adjacent with the removed number. If the number doesn't have an adjacent number to the left or right, Artem doesn't get any points. After the element is removed, the two parts of the array glue together resulting in the new array that Artem continues playing with. Borya wondered what maximum total number of points Artem can get as he plays this game.

The first line contains a single integer n (1 ≤ n ≤ 5·105) — the number of elements in the array. The next line contains n integers ai (1 ≤ ai ≤ 106) — the values of the array elements.

In a single line print a single integer — the maximum number of points Artem can get.

gets
s,ans=[],0
gets.split.map(&:to_i).each do |i|
  while s[-2]&&(k=[s[-2],i].min)>=s[-1]
    ans+=k
    s.pop
  end
  s.push i
end
s.sort!
(0..s.size-3).each{|i| ans+=s[i]}
p ans


class Spell
	def initialize(idx, power, dmg)
		@idx = idx
		@power = power
		@dmg = dmg
		@used = false
	end
	attr_accessor :idx, :power, :dmg, :used
end

n,mx,reg = gets.chomp.split(/ /).map!{|x|x.to_i}
ra = Array.new(n)
ret = true
sa = Array.new
for i in 0..n-1
	a = gets.chomp.split(/ /).map!{|x|x.to_i}
	ra[i] = Spell.new( i+1, a[0], a[1] )
end

ra.sort!{|a,b| b.dmg <=> a.dmg }

mxw = mx
dmgpermin = 0
mtime = 0

while mxw > 0
	prevmxw = mxw
	notfound = true
	for i in 0..n-1
		next if ra[i].used
		next if ra[i].power*mx < mxw*100
		dmgpermin += ra[i].dmg
		ra[i].used = true
		sa.push( mtime.to_s + " " + ra[i].idx.to_s )
		notfound = false
		break
	end
	mxw -= dmgpermin
	mxw += reg
	mxw = mx if mxw > mx

	break if mxw < 0

	mtime += 1

	if notfound && prevmxw <= mxw
		ret = false
		break
	end
end

ret = false if mxw > 0

if ret
	puts "YES"
	puts mtime.to_s + " " + sa.length.to_s
	sa.each{|x| puts x }
else
	puts "NO"
end

Vasya’s elder brother Petya loves playing computer games. In one of his favourite computer games Petya reached the final level where a fight with the boss take place.While playing the game Petya found spell scrolls and now he is about to use them. Let’s describe the way fighting goes on this level:1) The boss has two parameters: max — the initial amount of health and reg — regeneration rate per second.2) Every scroll also has two parameters: powi — spell power measured in percents — the maximal amount of health counted off the initial one, which allows to use the scroll (i.e. if the boss has more than powi percent of health the scroll cannot be used); and dmgi the damage per second inflicted upon the boss if the scroll is used. As soon as a scroll is used it disappears and another spell is cast upon the boss that inflicts dmgi of damage per second upon him until the end of the game.During the battle the actions per second are performed in the following order: first the boss gets the damage from all the spells cast upon him, then he regenerates reg of health (at the same time he can’t have more than max of health), then the player may use another scroll (no more than one per second).The boss is considered to be defeated if at the end of a second he has nonpositive ( ≤ 0) amount of health.Help Petya to determine whether he can win with the set of scrolls available to him and if he can, determine the minimal number of seconds he needs to do it.

The first line contains three integers N, max and reg (1 ≤ N, max, reg ≤ 1000) –– the amount of scrolls and the parameters of the boss. The next N lines contain two integers powi and dmgi each — the parameters of the i-th scroll (0 ≤ powi ≤ 100, 1 ≤ dmgi ≤ 2000).

In case Petya can’t complete this level, output in the single line NO. Otherwise, output on the first line YES. On the second line output the minimal time after which the boss can be defeated and the number of used scrolls. In the next lines for each used scroll output space-separated number of seconds passed from the start of the battle to the moment the scroll was used and the number of the scroll. Scrolls are numbered starting from 1 in the input order. The first scroll is considered to be available to be used after 0 seconds. Output scrolls in the order they were used. It is not allowed to use scrolls after the boss is defeated.

class Spell
	def initialize(idx, power, dmg)
		@idx = idx
		@power = power
		@dmg = dmg
		@used = false
	end
	attr_accessor :idx, :power, :dmg, :used
end

n,mx,reg = gets.chomp.split(/ /).map!{|x|x.to_i}
ra = Array.new(n)
ret = true
sa = Array.new
for i in 0..n-1
	a = gets.chomp.split(/ /).map!{|x|x.to_i}
	ra[i] = Spell.new( i+1, a[0], a[1] )
end

ra.sort!{|a,b| b.dmg <=> a.dmg }

mxw = mx
dmgpermin = 0
mtime = 0

while mxw > 0
	prevmxw = mxw
	notfound = true
	for i in 0..n-1
		next if ra[i].used
		next if ra[i].power*mx < mxw*100
		dmgpermin += ra[i].dmg
		ra[i].used = true
		sa.push( mtime.to_s + " " + ra[i].idx.to_s )
		notfound = false
		break
	end
	mxw -= dmgpermin
	mxw += reg
	mxw = mx if mxw > mx
	mtime += 1

	if notfound && prevmxw <= mxw
		ret = false
		break
	end
end

ret = false if mxw > 0

if ret
	puts "YES"
	puts mtime.to_s + " " + sa.length.to_s
	sa.each{|x| puts x }
else
	puts "NO"
end


#! ruby
# Try Codeforces
# author: Leonardone @ NEETSDKASU

def gi(); gets.to_i; end
def gis(); gets.chomp.split.map(&:to_i); end

n, m = gis

h = []
1.upto(n) do |i|
    h[i] = [-1] * n.succ
    h[i][i] = 0
end

m.times do
    u, v = gis
    h[u][v] = h[v][u] = 1
end

t1 = []
t2 = []
1.upto(n) do |i|
    t1[i] = []
    t2[i] = []
    1.upto(n) do |j|
        case h[i][j]
        when 1
            t1[i] << j
        when -1
            t2[i] << j
        end
    end
end

if t1[1].empty? || t2[1].empty? || t1[n].empty? || t2[n].empty?
    puts '-1'
    exit
end

l1 = [1]
v1 = [true] + ([false] * n)
flg = true
ct = 0
while flg && !l1.empty? do
    ct += 1
    l2 = []
    l1.each do |k|
        if t1[k][-1] == n
            flg = false
            break
        end
        t1[k].each do |x|
            next if v1[x]
            l2 << x
        end
    end
    l1 = l2
end

if flg
    puts '-1'
    exit
end

l1 = [1]
v1 = [true] + ([false] * n)
flg = true
cb = 0
while flg && !l1.empty? do
    cb += 1
    l2 = []
    l1.each do |k|
        if t2[k][-1] == n
            flg = false
            break
        end
        t2[k].each do |x|
            next if v1[x]
            l2 << x
        end
    end
    l1 = l2
end

if flg
    puts '-1'
    exit
end

puts [ct,cb].max

In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety — in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.

The first line of the input contains two integers n and m (2 ≤ n ≤ 400, 0 ≤ m ≤ n(n - 1) / 2) — the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1 ≤ u, v ≤ n, u ≠ v). You may assume that there is at most one railway connecting any two towns.

Output one integer — the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output  - 1.

NoteIn the first sample, the train can take the route  and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4.

#! ruby
# Try Codeforces
# author: Leonardone @ NEETSDKASU

def gi(); gets.to_i; end
def gis(); gets.chomp.split.map(&:to_i); end

n, m = gis

h = []
1.upto(n) do |i|
    h[i] = [-1] * n.succ
    h[i][i] = 0
end

m.times do
    u, v = gis
    h[u][v] = h[v][u] = 1
end

t1 = []
t2 = []
1.upto(n) do |i|
    t1[i] = []
    t2[i] = []
    1.upto(n) do |j|
        case h[i][j]
        when 1
            t1[i] << j
        when -1
            t2[i] << j
        end
    end
end

if t1[1].empty? || t2[1].empty? || t1[n].empty? || t2[n].empty?
    puts '-1'
    exit
end

l1 = [1]
v1 = [true] + ([false] * n)
flg = true
ct = 0
while flg && !l1.empty? do
    ct += 1
    l2 = []
    l1.each do |k|
        if t1[k][-1] == n
            flg = false
            break
        end
        t1[k].each do |x|
            next if v1[x]
            v1[x] = true
            l2 << x
        end
    end
    l1 = l2
end

if flg
    puts '-1'
    exit
end

l1 = [1]
v1 = [true] + ([false] * n)
flg = true
cb = 0
while flg && !l1.empty? do
    cb += 1
    l2 = []
    l1.each do |k|
        if t2[k][-1] == n
            flg = false
            break
        end
        t2[k].each do |x|
            next if v1[x]
            v1[x] = true
            l2 << x
        end
    end
    l1 = l2
end

if flg
    puts '-1'
    exit
end

puts [ct,cb].max


// Author: sighduck
// URL: https://codeforces.com/contest/1230/problem/B

package main

import (
	"bufio"
	"fmt"
	"os"
)

func _Solve(current int, n int, k int, S string) string {
	if n == 1 && k > 0 {
		return "0"
	}
	if k == 0 || current == n {
		return S
	}
	if current == 0 && string(S[current]) != "1" {
		k -= 1
		S = "1" + S[1:]
	} else if current != 0 && S[current] > 0 {
		k -= 1
		S = S[:current] + "0" + S[current+1:]
	}
	return _Solve(current+1, n, k, S)
}

func Solve(n int, k int, S string) string {
	return _Solve(0, n, k, S)
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var n, k int
	var s string
	fmt.Fscanf(reader, "%d %d\n%s\n", &n, &k, &s)

	fmt.Fprintf(writer, "%s\n", Solve(n, k, s))
}

Ania has a large integer $$$S$$$. Its decimal representation has length $$$n$$$ and doesn't contain any leading zeroes. Ania is allowed to change at most $$$k$$$ digits of $$$S$$$. She wants to do it in such a way that $$$S$$$ still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 200\,000$$$, $$$0 \leq k \leq n$$$) — the number of digits in the decimal representation of $$$S$$$ and the maximum allowed number of changed digits. The second line contains the integer $$$S$$$. It's guaranteed that $$$S$$$ has exactly $$$n$$$ digits and doesn't contain any leading zeroes.

Output the minimal possible value of $$$S$$$ which Ania can end with. Note that the resulting integer should also have $$$n$$$ digits.

NoteA number has leading zeroes if it consists of at least two digits and its first digit is $$$0$$$. For example, numbers $$$00$$$, $$$00069$$$ and $$$0101$$$ have leading zeroes, while $$$0$$$, $$$3000$$$ and $$$1010$$$ don't have leading zeroes.

package main

import (
   "fmt"
   "os"
   "bufio"
   "strconv"
)

const MaxBuf = 200100
var buf []byte
var sc = bufio.NewScanner(os.Stdin)

func init() {
   sc.Split(bufio.ScanWords)
   sc.Buffer(buf,MaxBuf)
}

func readString() string {
   sc.Scan()
   return sc.Text()
}

func readInt64() int64 {
   sc.Scan()
   r,_ := strconv.ParseInt(sc.Text(),10,64)
   return r
}

func readInt() int {
   sc.Scan()
   r,_ := strconv.Atoi(sc.Text())
   return r
}

func main() {
	n := readInt()
	k := readInt()
	s := readString()

	r := make([]rune,n)
	for i,v := range s {
		var x rune
		if k > 0 {
			if i == 0 {
				if len(s) == 1 {
					x = '0'
				} else {
					x = '1'
				}
				if v != x {
					k--
				}
			} else {
				x = '0'
				if v != x {
					k--
				}
			}
		} else {
			x = v
		}
		r[i] = x
	}

	fmt.Println(string(r))

}


package main

import (
	"bufio"
	"fmt"
	"os"
)

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)

func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }

func min(a, b int) int {
	if a <= b {
		return a
	}
	return b
}

func printSlice(a []int) {
	printf("  ")
	for i := 0; i < len(a); i++ {
		printf("%d ", a[i])
	}
	printf("\n")
}

func main() {
	defer writer.Flush()
	var n int
	scanf("%d\n", &n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		scanf("%d", &a[i])
	}
	// printSlice(a)
	dp := make([]int, n+1)
	s := ""
	for i := 1; i <= n; i++ {
		var x, y, z int
		x = 1e5
		y = 1e5
		z = 1e5
		var prev byte
		if i >= 2 {
			prev = s[i-2]
		} else {
			prev = 'x'
		}
		if (a[i-1] == 2 || a[i-1] == 3) && (prev != 's') {
			y = dp[i-1]
		}
		if (a[i-1] == 1 || a[i-1] == 3) && (prev != 'c') {
			z = dp[i-1]
		}
		x = dp[i-1] + 1
		minans := min(x, min(y, z))
		dp[i] = minans
		if minans == x {
			s += "r"
		} else if minans == y {
			s += "s"
		} else {
			s += "c"
		}

	}
	printf("%d\n", dp[n])
}

Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:  on this day the gym is closed and the contest is not carried out;  on this day the gym is closed and the contest is carried out;  on this day the gym is open and the contest is not carried out;  on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has — he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.

The first line contains a positive integer n (1 ≤ n ≤ 100) — the number of days of Vasya's vacations. The second line contains the sequence of integers a1, a2, ..., an (0 ≤ ai ≤ 3) separated by space, where:    ai equals 0, if on the i-th day of vacations the gym is closed and the contest is not carried out;  ai equals 1, if on the i-th day of vacations the gym is closed, but the contest is carried out;  ai equals 2, if on the i-th day of vacations the gym is open and the contest is not carried out;  ai equals 3, if on the i-th day of vacations the gym is open and the contest is carried out.

Print the minimum possible number of days on which Vasya will have a rest. Remember that Vasya refuses:   to do sport on any two consecutive days,  to write the contest on any two consecutive days.

NoteIn the first test Vasya can write the contest on the day number 1 and do sport on the day number 3. Thus, he will have a rest for only 2 days.In the second test Vasya should write contests on days number 1, 3, 5 and 7, in other days do sport. Thus, he will not have a rest for a single day.In the third test Vasya can do sport either on a day number 1 or number 2. He can not do sport in two days, because it will be contrary to the his limitation. Thus, he will have a rest for only one day.

package main

import (
	"bufio"
	"fmt"
	"os"
)

var bufin *bufio.Reader
var bufout *bufio.Writer

const maxn = 100

var n int
var a [maxn + 1]int
var f [maxn + 1][3]int

func min(x int, y int) int {
	if x < y {
		return x
	}
	return y
}

func main() {
	bufin = bufio.NewReader(os.Stdin)
	bufout = bufio.NewWriter(os.Stdout)
	defer bufout.Flush()

	fmt.Fscan(bufin, &n)
	for i := 1; i <= n; i++ {
		fmt.Fscan(bufin, &a[i])
	}

	for j := 0; j < 3; j++ {
		f[0][j] = 0
	}

	for i := 1; i <= n; i++ {
		f[i][0] = n
		for j := 0; j < 3; j++ {
			f[i][0] = min(f[i][0], f[i-1][j]+1)
		}

		f[i][1] = n
		if (a[i] & 1) == 1 {
			f[i][1] = min(f[i][1], f[i-1][0])
			f[i][1] = min(f[i][1], f[i-1][2])
		}

		f[i][2] = n
		if ((a[i] >> 1) & 1) == 1 {
			f[i][2] = min(f[i][2], f[i-1][0])
			f[i][2] = min(f[i][2], f[i-1][1])
		}
	}

	r := min(min(f[n][0], f[n][1]), f[n][2])
	fmt.Fprint(bufout, r)
}


package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
)

func main() {
	reader := bufio.NewReader(os.Stdin)

	n, vb, vs := readThreeNums(reader)
	X := readNNums(reader, n)
	room := readNNums(reader, 2)

	fmt.Println(solve(n, vb, vs, X, room))
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func solve(n int, vb int, vs int, X []int, exam []int) int {
	time := make([]float64, n)
	v1 := float64(vs)
	v2 := float64(vb)
	var best = math.MaxFloat64
	var pos int
	for i := 0; i < n; i++ {
		t1 := float64(X[0]) / v1
		t2 := distance(exam[0], exam[1], X[i], 0) / v2
		time[i] = t1 + t2
		if i > 0 && time[i] < best {
			best = time[i]
			pos = i
		}
	}
	return pos + 1
}

func distance(a, b, c, d int) float64 {
	dx := float64(c - a)
	dy := float64(d - b)
	return math.Sqrt(dx*dx + dy*dy)
}

And again a misfortune fell on Poor Student. He is being late for an exam.Having rushed to a bus stop that is in point (0, 0), he got on a minibus and they drove along a straight line, parallel to axis OX, in the direction of increasing x.Poor Student knows the following:   during one run the minibus makes n stops, the i-th stop is in point (xi, 0)  coordinates of all the stops are different  the minibus drives at a constant speed, equal to vb  it can be assumed the passengers get on and off the minibus at a bus stop momentarily  Student can get off the minibus only at a bus stop  Student will have to get off the minibus at a terminal stop, if he does not get off earlier  the University, where the exam will be held, is in point (xu, yu)  Student can run from a bus stop to the University at a constant speed vs as long as needed  a distance between two points can be calculated according to the following formula:   Student is already on the minibus, so, he cannot get off at the first bus stop Poor Student wants to get to the University as soon as possible. Help him to choose the bus stop, where he should get off. If such bus stops are multiple, choose the bus stop closest to the University.

The first line contains three integer numbers: 2 ≤ n ≤ 100, 1 ≤ vb, vs ≤ 1000. The second line contains n non-negative integers in ascending order: coordinates xi of the bus stop with index i. It is guaranteed that x1 equals to zero, and xn ≤ 105. The third line contains the coordinates of the University, integers xu and yu, not exceeding 105 in absolute value.

In the only line output the answer to the problem — index of the optimum bus stop.

NoteAs you know, students are a special sort of people, and minibuses usually do not hurry. That's why you should not be surprised, if Student's speed is higher than the speed of the minibus.

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"math"
	"os"
)

func main() {
	bs, _ := ioutil.ReadAll(os.Stdin)
	reader := bytes.NewBuffer(bs)

	var n int
	var vb, vs, xu, yu float64

	fmt.Fscanf(reader, "%d %f %f\n", &n, &vb, &vs)
	stop := make([]float64, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%f", &stop[i])
		if i != n-1 {
			fmt.Fscanf(reader, " ")
		} else {
			fmt.Fscanf(reader, "\n")
		}
	}
	fmt.Fscanf(reader, "%f %f", &xu, &yu)
	min := 99999999999.0
	var minStop int
	for i := 1; i < n; i++ {
		t := stop[i]/vb + math.Sqrt((xu-stop[i])*(xu-stop[i])+yu*yu)/vs
		if t < min {
			minStop = i
			min = t
		} else if t == min {
			if math.Abs(xu-stop[minStop]) > math.Abs(xu-stop[i]) {
				minStop = i
				min = t
			}
		}
	}
	fmt.Printf("%d", minStop+1)
}


package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
	"strings"
)

/*
1
3
---
0
======
2
2 2
---
1
======
2
-4 -4
---
1
======
6
1 2 3 1 2 3
---
1
======
5
1 -2 3 0 -1
---
0
*/

//goland:noinspection GoUnhandledErrorResult
func main() {
	defer writer.Flush()

	bld := strings.Builder{}

	t := 1
	//scanf("%d\n", &t)

	for ; t > 0; t-- {
		var n int
		scanf("%d\n", &n)

		// overflow is expected
		ps := make([]int, n)

		if strconv.IntSize == 64 {
			printf("64bit")
			return
		}

		for i := 0; i < n; i++ {
			var num int
			scanf("%d", &num)

			if i == 0 {
				ps[i] = num
			} else {
				ps[i] = ps[i-1] + num
			}
		}

		cnt := 0

		for i := 0; i < n-1; i++ {
			leftSum := ps[i]
			rightSum := ps[n-1] - ps[i]
			if leftSum == rightSum {
				cnt++
			}
		}

		fmt.Fprintln(&bld, cnt)
	}

	printf("%s", bld.String())
}

const maxUint = ^uint(0)

//goland:noinspection GoUnusedConst
const minUint = 0
const maxInt = int(maxUint >> 1)

//goland:noinspection GoUnusedConst
const minInt = -maxInt - 1

//goland:noinspection GoUnusedType
type pair struct {
	fst int
	snd int
}

var reader = bufio.NewReader(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

//goland:noinspection GoUnusedFunction
func printf(f string, a ...interface{}) {
	if _, err := fmt.Fprintf(writer, f, a...); err != nil {
		panic(err)
	}
}

func scanf(f string, a ...interface{}) {
	if _, err := fmt.Fscanf(reader, f, a...); err != nil {
		panic(err)
	}
}

//goland:noinspection GoUnusedFunction
func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

//goland:noinspection GoUnusedFunction
func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

//goland:noinspection GoUnusedFunction
func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

//goland:noinspection GoUnusedFunction
func isPrime(n int) bool {
	if n == 2 || n == 3 {
		return true
	}

	if n <= 1 || n%2 == 0 || n%3 == 0 {
		return false
	}

	for i := 5; i*i <= n; i += 6 {
		if n%i == 0 || n%(i+2) == 0 {
			return false
		}
	}

	return true
}

//goland:noinspection GoUnusedFunction
func gcd(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

//goland:noinspection GoUnusedFunction
func lcm(a, b int) int {
	return abs(a) / gcd(a, b) * abs(b)
}

// Examples:
//	digitAt(1234, 0) -> 4
//	digitAt(1234, 1) -> 3
//	digitAt(1234, 2) -> 2
//	digitAt(1234, 3) -> 2
//	digitAt(1234, 4) -> panic!
//goland:noinspection GoUnusedFunction
func digitAt(num, pos int) int {
	lenNum := int(math.Log10(float64(num))) + 1
	if pos >= lenNum {
		err := fmt.Sprintf("Out of bound access for digit. Position passed %d, number lenght %d", pos, lenNum)
		panic(err)
	}

	rem := num % int(math.Pow(10, float64(pos+1)))
	return rem / int(math.Pow(10, float64(pos)))
}

Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into two pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?

The first input line contains integer n (1≤n≤10^5) — amount of squares in the stripe. The second line contains n space-separated numbers — they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.

Output the amount of ways to cut the stripe into two non-empty pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.

package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strings"
)

/*
1
3
---
0
======
2
2 2
---
1
======
2
-4 -4
---
1
======
6
1 2 3 1 2 3
---
1
======
5
1 -2 3 0 -1
---
0
*/

//goland:noinspection GoUnhandledErrorResult
func main() {
	defer writer.Flush()

	bld := strings.Builder{}

	t := 1
	//scanf("%d\n", &t)

	for ; t > 0; t-- {
		var n int
		scanf("%d\n", &n)

		ps := make([]int, n)

		for i := 0; i < n; i++ {
			var num int
			scanf("%d", &num)

			if i == 0 {
				ps[i] = num
			} else {
				ps[i] = ps[i-1] + num
			}
		}

		cnt := 0

		for i := 0; i < n-1; i++ {
			leftSum := ps[i]
			rightSum := ps[n-1] - ps[i]
			if leftSum == rightSum {
				cnt++
			}
		}

		fmt.Fprintln(&bld, cnt)
	}

	printf("%s", bld.String())
}

const maxUint = ^uint(0)

//goland:noinspection GoUnusedConst
const minUint = 0
const maxInt = int(maxUint >> 1)

//goland:noinspection GoUnusedConst
const minInt = -maxInt - 1

//goland:noinspection GoUnusedType
type pair struct {
	fst int
	snd int
}

var reader = bufio.NewReader(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

//goland:noinspection GoUnusedFunction
func printf(f string, a ...interface{}) {
	if _, err := fmt.Fprintf(writer, f, a...); err != nil {
		panic(err)
	}
}

func scanf(f string, a ...interface{}) {
	if _, err := fmt.Fscanf(reader, f, a...); err != nil {
		panic(err)
	}
}

//goland:noinspection GoUnusedFunction
func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

//goland:noinspection GoUnusedFunction
func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

//goland:noinspection GoUnusedFunction
func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

//goland:noinspection GoUnusedFunction
func isPrime(n int) bool {
	if n == 2 || n == 3 {
		return true
	}

	if n <= 1 || n%2 == 0 || n%3 == 0 {
		return false
	}

	for i := 5; i*i <= n; i += 6 {
		if n%i == 0 || n%(i+2) == 0 {
			return false
		}
	}

	return true
}

//goland:noinspection GoUnusedFunction
func gcd(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

//goland:noinspection GoUnusedFunction
func lcm(a, b int) int {
	return abs(a) / gcd(a, b) * abs(b)
}

// Examples:
//	digitAt(1234, 0) -> 4
//	digitAt(1234, 1) -> 3
//	digitAt(1234, 2) -> 2
//	digitAt(1234, 3) -> 2
//	digitAt(1234, 4) -> panic!
//goland:noinspection GoUnusedFunction
func digitAt(num, pos int) int {
	lenNum := int(math.Log10(float64(num))) + 1
	if pos >= lenNum {
		err := fmt.Sprintf("Out of bound access for digit. Position passed %d, number lenght %d", pos, lenNum)
		panic(err)
	}

	rem := num % int(math.Pow(10, float64(pos+1)))
	return rem / int(math.Pow(10, float64(pos)))
}


package main

import (
	"fmt"
)

func can_buy(cur uint64, prizes []int) int {
	for i:=4; i>=0; i-- {
		if cur >= uint64(prizes[i]) {
			return i
		}
	}
	return -1
}

func main() {
	var n int
	var cur uint64 = 0
	fmt.Scan(&n)
	points := make([]int, n)
	prizes := make([]int, 5)
	claimed_prizes := make([]int, 5)
	for i:=0; i<n; i++ {
		fmt.Scan(&points[i])
	}
	for i:=0; i<5; i++ {
		fmt.Scan(&prizes[i])
		claimed_prizes[i] = 0
	}
	for i:=0; i<n; i++ {
		fmt.Println(i)
		cur += uint64(points[i])
		for idx:=can_buy(cur, prizes); idx!=-1; idx=can_buy(cur,prizes) {
			cur -= uint64(prizes[idx])
			claimed_prizes[idx]++
		}
	}
	for i:=0; i<5; i++ {
		fmt.Printf("%d ", claimed_prizes[i])
	}
	fmt.Printf("\n")
	fmt.Println(cur)
}

Vasya, like many others, likes to participate in a variety of sweepstakes and lotteries. Now he collects wrappings from a famous chocolate bar "Jupiter". According to the sweepstake rules, each wrapping has an integer written on it — the number of points that the participant adds to his score as he buys the bar. After a participant earns a certain number of points, he can come to the prize distribution center and exchange the points for prizes. When somebody takes a prize, the prize's cost is simply subtracted from the number of his points.Vasya didn't only bought the bars, he also kept a record of how many points each wrapping cost. Also, he remembers that he always stucks to the greedy strategy — as soon as he could take at least one prize, he went to the prize distribution centre and exchanged the points for prizes. Moreover, if he could choose between multiple prizes, he chose the most expensive one. If after an exchange Vasya had enough points left to get at least one more prize, then he continued to exchange points.The sweepstake has the following prizes (the prizes are sorted by increasing of their cost):   a mug (costs a points),  a towel (costs b points),  a bag (costs c points),  a bicycle (costs d points),  a car (costs e points). Now Vasya wants to recollect what prizes he has received. You know sequence p1, p2, ..., pn, where pi is the number of points Vasya got for the i-th bar. The sequence of points is given in the chronological order. You also know numbers a, b, c, d, e. Your task is to find, how many prizes Vasya received, what prizes they are and how many points he's got left after all operations are completed.

The first line contains a single integer n (1 ≤ n ≤ 50) — the number of chocolate bar wrappings that brought points to Vasya. The second line contains space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ 109). The third line contains 5 integers a, b, c, d, e (1 ≤ a < b < c < d < e ≤ 109) — the prizes' costs.

Print on the first line 5 integers, separated by a space — the number of mugs, towels, bags, bicycles and cars that Vasya has got, respectively. On the second line print a single integer — the number of points Vasya will have left after all operations of exchange are completed. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample Vasya gets 3 points after eating the first chocolate bar. Then he exchanges 2 points and gets a mug. Vasya wins a bag after eating the second chocolate bar. Then he wins a towel after eating the third chocolate bar. After all chocolate bars 3 - 2 + 10 - 10 + 4 - 4 = 1 points remains.

package main
import (
	"fmt"
	//"sort"
	"os"
	"strconv"
	"bufio"

)

func main() {
	var n,i,f,j,e int64
	e=0
	a:=make([]int64,55)
	x:=make([]int64,10)
	y:=make([]int64,10)
	input := bufio.NewScanner(os.Stdin)
	input.Split(bufio.ScanWords)
	fmt.Scan(&n)
	for i=1;i<=n;i++ {
		input.Scan()
		aa,_ := strconv.ParseInt(input.Text(),0,64)
		a[i]=aa
	}
	for i=1;i<=5;i++ {
		input.Scan()
		bb,_ := strconv.ParseInt(input.Text(),0,64)
		x[i]=bb
	}
	for i=1;i<=n;i++ {
		e+=a[i]
		for j=5;j>=1;j-- {
			y[j]+=e/x[j]
			e%=x[j]
		}
	}
	for f=1; f<=5;f++ {
		fmt.Print(y[f]," ")
	}
	fmt.Println()
	fmt.Println(e)
}


package main

import (
	"bufio"
	"fmt"
	"os"
)

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)

func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }

type game struct {
	name  string
	score int
	place [10]int
}

func main() {
	// STDOUT MUST BE FLUSHED MANUALLY!!!
	defer writer.Flush()
	if len(os.Args[1:]) == 1 {
		file, _ := os.Open(os.Args[1])
		reader = bufio.NewReader(file)
	}

	var n, t int
	scanf("%d\n", &t)
	n2n := make(map[string]int)
	start := 0
	var s string
	c := make([]game, 50)
	rank := [10]int{25, 18, 15, 12, 10, 8, 6, 4, 2, 1}
	for i := 0; i < t; i++ {
		scanf("%d\n", &n)
		for j := 0; j < n; j++ {
			scanf("%s\n", &s)
			if j >= 10 {
				continue
			}
			index, ok := n2n[s]
			if !ok {
				n2n[s] = start
				index = start
				start++
			}
			c[index].name = s
			c[index].score += rank[j]
			c[index].place[j]++
		}
	}
	ma := c[0]
	//fmt.Println(c)
	for i := 1; i < 50; i++ {
		if bigger(c[i], ma) {
			ma = c[i]
		}
	}
	printf("%s\n", ma.name)
	ma = c[0]
	for i := 1; i < 50; i++ {
		if bigger2(c[i], ma) {
			ma = c[i]
		}
	}
	printf("%s\n", ma.name)
}

func bigger(left, right game) bool {
	if left.score > right.score {
		return true
	}
	if left.score < right.score {
		return false
	}
	for i := 0; i < 10; i++ {
		if left.place[i] > right.place[i] {
			return true
		} else if left.place[i] < right.place[i] {
			return false
		}
	}

	return false
}

func bigger2(left, right game) bool {
	if left.place[0] > right.place[0] {
		return true
	} else if left.place[0] < right.place[0] {
		return false
	}
	if left.score > right.score {
		return true
	}
	if left.score < right.score {
		return false
	}
	for i := 1; i < 10; i++ {
		if left.place[i] > right.place[i] {
			return true
		} else if left.place[i] < right.place[i] {
			return false
		}
	}

	return false
}

Formula One championship consists of series of races called Grand Prix. After every race drivers receive points according to their final position. Only the top 10 drivers receive points in the following order 25, 18, 15, 12, 10, 8, 6, 4, 2, 1. At the conclusion of the championship the driver with most points is the champion. If there is a tie, champion is the one with most wins (i.e. first places). If a tie still exists, it is chosen the one with most second places, and so on, until there are no more place to use for compare. Last year another scoring system was proposed but rejected. In it the champion is the one with most wins. If there is tie, champion is the one with most points. If a tie still exists it is proceeded the same way as in the original scoring system, that is comparing number of second, third, forth, and so on, places.You are given the result of all races during the season and you are to determine the champion according to both scoring systems. It is guaranteed, that both systems will produce unique champion.

The first line contain integer t (1≤t≤20), where t is the number of races. After that all races are described one by one. Every race description start with an integer n (1≤n≤50) on a line of itself, where n is the number of clasified drivers in the given race. After that n lines follow with the classification for the race, each containing the name of a driver. The names of drivers are given in order from the first to the last place. The name of the driver consists of lowercase and uppercase English letters and has length at most 50 characters. Comparing of names should be case-sensetive.

Your output should contain exactly two line. On the first line is the name of the champion according to the original rule, and on the second line the name of the champion according to the alternative rule.

It is not guaranteed that the same drivers participate in all races. For the championship consider every driver that has participated in at least one race. The total number of drivers during the whole season is not more then 50.

3
3
Hamilton
Vettel
Webber
2
Webber
Vettel
2
Hamilton
Vettel

2
7
Prost
Surtees
Nakajima
Schumacher
Button
DeLaRosa
Buemi
8
Alonso
Prost
NinoFarina
JimClark
DeLaRosa
Nakajima
Patrese
Surtees

package main

import (
  "os"
  "bufio"
  "strconv"
  "fmt"
  "sort"
)

var scanner *bufio.Scanner

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

type Driver struct {
  Name string
  Points int
  Places map[int]int
  MaxPlace int
}

var drivers = map[string]*Driver{}

type OldList []*Driver
type NewList []*Driver
func (list OldList) Len() int {
  return len(list)
}
func (list OldList) Swap(i, j int) {
  list[i], list[j] = list[j], list[i]
}
func (list NewList) Len() int {
  return len(list)
}
func (list NewList) Swap(i, j int) {
  list[i], list[j] = list[j], list[i]
}

func (list OldList) Less(i, j int) bool {
  a, b := list[i], list[j]
  if a.Points != b.Points {
    return a.Points > b.Points
  }
  return comparePlaces(a, b)
}
func (list NewList) Less(i, j int) bool {
  a, b := list[i], list[j]
  if a.Places[1] != b.Places[1] {
    return a.Places[1] > b.Places[1]
  }
  if a.Points != b.Points {
    return a.Points > b.Points
  }
  return comparePlaces(a, b)
}
func comparePlaces(a, b *Driver) bool {
  for p := 1; p <= a.MaxPlace || p <= b.MaxPlace; p++ {
    placesA := a.Places[p]
    placesB := b.Places[p]
    if placesA != placesB {
      return placesA > placesB
    }
  }
  return true
}

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer := bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  points := map[int]int{ 1: 25, 2: 18, 3: 15, 4: 12, 5: 10,
      6: 8, 7: 6, 8: 4, 9: 2, 10: 1 }

  t := getI()
  for ti := 0; ti < t; ti++ {
    n := getI()
    for ni := 0; ni < n; ni++ {
      name := getS()
      place := ni+1
      driver, found := drivers[name]
      if !found {
        driver = &Driver{ name, 0, map[int]int{}, 0 }
        drivers[name] = driver
      }
      driver.Points += points[place]
      driver.Places[place] += 1
      if place > driver.MaxPlace {
        driver.MaxPlace = place
      }
    }
  }
  oldList, newList := []*Driver{}, []*Driver{}
  for _, driver := range drivers {
    oldList = append(oldList, driver)
    newList = append(newList, driver)
  }
  sort.Sort(OldList(oldList))
  sort.Sort(NewList(newList))
  writer.WriteString(fmt.Sprintf("%s\n", oldList[0].Name))
  writer.WriteString(fmt.Sprintf("%s\n", newList[0].Name))
}


package main

import (
	"fmt"
	"bufio"
	"os"
	"strconv"
)

var scanner = bufio.NewScanner(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

//Wrong
func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	n := nextInt()
	_ = n

	s := next()

	i, count := 0, 0

	for i<len(s) && s[i]=='.' {
		i++
	}

	if i==len(s) {
		println(0)
		return
	}

	lastPush := i
	i++

	if s[lastPush]=='R' {
		count += lastPush
	}

	for i<len(s) {
		if s[i] != '.' {
			if s[i] == 'R' {
				count += i - lastPush - 1
			} else {
				if (i-lastPush)%2 == 0 {
					count++
				}
			}
			lastPush = i
		}
		i++
	}

	if s[lastPush]=='L' {
		count += len(s) - lastPush - 1
	}

	println(count)
}

func next() string {
	if !scanner.Scan() {
		panic("Scan error")
	}
	return scanner.Text()
}

func nextInt() int {
	n, err := strconv.Atoi(next())
	if err != nil {
		panic(err)
	}
	return n
}

func nextFloat() float64 {
	n, err := strconv.ParseFloat(next(), 64)
	if err != nil {
		panic(err)
	}
	return n
}

func println(a ...interface{}) {
	fmt.Fprintln(writer, a...)
}

func print(a ...interface{}) {
	fmt.Fprint(writer, a...)
}

Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show".Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes either to the left or to the right. However, somewhere between every two dominoes pushed in the same direction there is at least one domino pushed in the opposite direction.After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. The figure shows one possible example of the process.  Given the initial directions Chris has pushed the dominoes, find the number of the dominoes left standing vertically at the end of the process!

The first line contains a single integer n (1 ≤ n ≤ 3000), the number of the dominoes in the line. The next line contains a character string s of length n. The i-th character of the string si is equal to    "L", if the i-th domino has been pushed to the left;  "R", if the i-th domino has been pushed to the right;  ".", if the i-th domino has not been pushed.  It is guaranteed that if si = sj = "L" and i < j, then there exists such k that i < k < j and sk = "R"; if si = sj = "R" and i < j, then there exists such k that i < k < j and sk = "L".

Output a single integer, the number of the dominoes that remain vertical at the end of the process.

NoteThe first example case is shown on the figure. The four pieces that remain standing vertically are highlighted with orange.In the second example case, all pieces fall down since the first piece topples all the other pieces.In the last example case, a single piece has not been pushed in either direction.

package main

import (
	"fmt"
	"bufio"
	"os"
	"strconv"
)

var scanner = bufio.NewScanner(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

//Wrong
func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	n := nextInt()
	_ = n

	s := next()

	i, count := 0, 0

	for i<len(s) && s[i]=='.' {
		i++
	}

	if i==len(s) {
		println(len(s))
		return
	}

	lastPush := i
	i++

	if s[lastPush]=='R' {
		count += lastPush
	}

	for i<len(s) {
		if s[i] != '.' {
			if s[i] == 'R' {
				count += i - lastPush - 1
			} else {
				if (i-lastPush)%2 == 0 {
					count++
				}
			}
			lastPush = i
		}
		i++
	}

	if s[lastPush]=='L' {
		count += len(s) - lastPush - 1
	}

	println(count)
}

func next() string {
	if !scanner.Scan() {
		panic("Scan error")
	}
	return scanner.Text()
}

func nextInt() int {
	n, err := strconv.Atoi(next())
	if err != nil {
		panic(err)
	}
	return n
}

func nextFloat() float64 {
	n, err := strconv.ParseFloat(next(), 64)
	if err != nil {
		panic(err)
	}
	return n
}

func println(a ...interface{}) {
	fmt.Fprintln(writer, a...)
}

func print(a ...interface{}) {
	fmt.Fprint(writer, a...)
}


// 38A
package main

import (
	"fmt"
)

func main() {
	var n, a, b, y int
	d := [100]int{0}
	fmt.Scan(&n)
	for i := 1; i < n; i++ {
		fmt.Scan(&d[i])
	}
	fmt.Scan(&a, &b)
	for i := a; i < b-1; i++ {
		y += d[i]
	}
	fmt.Println(y)
}

The Berland Armed Forces System consists of n ranks that are numbered using natural numbers from 1 to n, where 1 is the lowest rank and n is the highest rank.One needs exactly di years to rise from rank i to rank i + 1. Reaching a certain rank i having not reached all the previous i - 1 ranks is impossible.Vasya has just reached a new rank of a, but he dreams of holding the rank of b. Find for how many more years Vasya should serve in the army until he can finally realize his dream.

The first input line contains an integer n (2 ≤ n ≤ 100). The second line contains n - 1 integers di (1 ≤ di ≤ 100). The third input line contains two integers a and b (1 ≤ a < b ≤ n). The numbers on the lines are space-separated.

Print the single number which is the number of years that Vasya needs to rise from rank a to rank b.

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func main() {
	var n int
	if _, err := fmt.Scanf("%d\n", &n); err != nil {
		return
	}

	di := make([]int, n+1)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	for i := 0; scanner.Scan(); i++ {
		a, err := strconv.Atoi(scanner.Text())
		if err != nil {
			return
		}
		di[i] = a
	}

	var years int = 0
	for i := di[n-1]; i < di[n]; i++ {
		years += di[i-1]
	}

	fmt.Println(years)
}