A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count. The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to n clockwise and the child number 1 is holding the ball. First the first child throws the ball to the next one clockwise, i.e. to the child number 2. Then the child number 2 throws the ball to the next but one child, i.e. to the child number 4, then the fourth child throws the ball to the child that stands two children away from him, i.e. to the child number 7, then the ball is thrown to the child who stands 3 children away from the child number 7, then the ball is thrown to the child who stands 4 children away from the last one, and so on. It should be mentioned that when a ball is thrown it may pass the beginning of the circle. For example, if n = 5, then after the third throw the child number 2 has the ball again. Overall, n - 1 throws are made, and the game ends.The problem is that not all the children get the ball during the game. If a child doesn't get the ball, he gets very upset and cries until Natalia Pavlovna gives him a candy. That's why Natalia Pavlovna asks you to help her to identify the numbers of the children who will get the ball after each throw.

The first line contains integer n (2 ≤ n ≤ 100) which indicates the number of kids in the circle.

In the single line print n - 1 numbers which are the numbers of children who will get the ball after each throw. Separate the numbers by spaces.


Having bought his own apartment, Boris decided to paper the walls in every room. Boris's flat has n rooms, each of which has the form of a rectangular parallelepiped. For every room we known its length, width and height of the walls in meters (different rooms can have different dimensions, including height).Boris chose m types of wallpaper to paper the walls of the rooms with (but it is not necessary to use all the types). Each type of wallpaper is sold in rolls of a fixed length and width (the length, naturally, shows how long the unfolded roll will be). In addition, for each type we know the price of one roll of this type.The wallpaper of each type contains strips running along the length of the roll. When gluing the strips must be located strictly vertically (so the roll cannot be rotated, even if the length is less than the width). Besides, a roll can be cut in an arbitrary manner, but the joints of glued pieces should also be vertical. In addition, each room should be papered by only one type of wallpaper. And pieces of the same roll cannot be used to paper different rooms. That is, for each room the rolls are purchased separately. Also, some rolls can be used not completely.After buying an apartment Boris is short of cash, so he wants to spend the minimum money on wallpaper. Help him.

The first line contains a positive integer n (1≤n≤500) — the number of rooms in Boris's apartment.
Each of the next n lines contains three space-separated positive integers — the length, width and height of the walls in a given room in meters, respectively.
The next line contains a positive integer m (1≤m≤500) — the number of available wallpaper types.
Each of the following m lines contains three space-separated positive integers — the length and width in meters of a given wallpaper and the price of one roll, respectively.
All numbers in the input data do not exceed 500. It is guaranteed that each room can be papered using these types of wallpaper.

Print a single number — the minimum total cost of the rolls.

Note to the sample:
The total length of the walls (the perimeter) of the room is 20 m.
One roll of the first type can be cut into pieces to get three vertical 1 meter wide strips, ergo you need 7 rolls of this type, the price equals 700.
A roll of the second type can be cut into pieces to get five 2 meter wide strips, we need 2 rolls, the price is 640.
One roll of the third type can immediately paper 19 meters out of 20, but we cannot use other types and we have to buy a second roll, the price is 1000.

def min_cost_of_wallpaper(n, rooms, m, wallpapers)
  costs = Array.new(n, Float::INFINITY)
  n.times do |i|
    l, w, h = rooms[i]
    perimeter = 2 * (l + w)
    m.times do |j|
      roll_len, roll_wid, price = wallpapers[j]
      strips_per_roll = roll_len / h
      if strips_per_roll >= 1
        rolls_needed = (perimeter.to_f / (strips_per_roll * roll_wid)).ceil
        cost = rolls_needed * price
        costs[i] = [costs[i], cost].min
      end
    end
  end
  costs.sum.to_s
end

n = gets.to_i
rooms = Array.new(n) { gets.split.map(&:to_i) }
m = gets.to_i
wallpapers = Array.new(m) { gets.split.map(&:to_i) }
puts min_cost_of_wallpaper(n, rooms, m, wallpapers)


Jabber ID on the national Berland service «Babber» has a form <username>@<hostname>[/resource], where   <username> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <username> is between 1 and 16, inclusive.  <hostname> — is a sequence of word separated by periods (characters «.»), where each word should contain only characters allowed for <username>, the length of each word is between 1 and 16, inclusive. The length of <hostname> is between 1 and 32, inclusive.  <resource> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <resource> is between 1 and 16, inclusive. The content of square brackets is optional — it can be present or can be absent.There are the samples of correct Jabber IDs: [email protected], [email protected]/contest.Your task is to write program which checks if given string is a correct Jabber ID.

The input contains of a single line. The line has the length between 1 and 100 characters, inclusive. Each characters has ASCII-code between 33 and 127, inclusive.

def is_jabber_id(str)
  # Check if the string matches the pattern for Jabber ID
  pattern = /^([a-zA-Z0-9_]{1,16})@(([a-zA-Z0-9_]{1,16})\.)*([a-zA-Z0-9_]{1,16})(\/([a-zA-Z0-9_]{1,16}))?$/
  if str.match?(pattern)
    return 'YES'
  else
    return 'NO'
  end
end

# Read the input
input = gets.chomp
# Call the function and print the result
puts is_jabber_id(input)

[{'input': ['mike@codeforces.com\r\n'], 'output': ['YES\r\n']}, {'input': ['john.smith@codeforces.ru/contest.icpc/12\r\n'], 'output': ['NO\r\n']}, {'input': ['test@test.ri/abacaba\r\n'], 'output': ['YES\r\n']}, {'input': ['@ops\r\n'], 'output': ['NO\r\n']}, {'input': ['this-is-the-test\r\n'], 'output': ['NO\r\n']}, {'input': ['mike@codeforces.commike@codeforces.com\r\n'], 'output': ['NO\r\n']}, {'input': ['oooop/oooop\r\n'], 'output': ['NO\r\n']}, {'input': ['w@S8/XU.5._R7fHq.@../e.WP!54Ey1L\x7f.9jv\r\n'], 'output': ['NO\r\n']}, {'input': ['lNC9D1L5U@.L!_!CcAOEEx.0z.aiW/S430sbQT\r\n'], 'output': ['NO\r\n']}, {'input': ['@/YTd.K1@lD\r\n'], 'output': ['NO\r\n']}, {'input': ['Fyi!d1l@.OesGopTnRn.81xdSb8q\x7f./MzuI\r\n'], 'output': ['NO\r\n']}, {'input': ['_TlPy65\x7fw/@.Vl@.8k\r\n'], 'output': ['NO\r\n']}, {'input': ['xpS@._s8.e0l\x7fJci/.LdiT\r\n'], 'output': ['NO\r\n']}, {'input': ['lGwo\x7f8.D2@.3\r\n'], 'output': ['NO\r\n']}, {'input': ['Ccz9T5rKZQuEerGo@6l.\r\n'], 'output': ['NO\r\n']}, {'input': ['Y@5nh@8.9P.Bx5AaY.1g.Tc_MK7.g_..0.\r\n'], 'output': ['NO\r\n']}, {'input': ['Q2/6y!SP9s\x7fG@7zIGr.Du_nR8.\r\n'], 'output': ['NO\r\n']}, {'input': ['eWfLL@gW!BEJUxF\x7fh@dghf.d4.FiYp/2.Pr7a/5O6zXdAkikjCEDrb\r\n'], 'output': ['NO\r\n']}, {'input': ['8oI/\x7fa@Q\r\n'], 'output': ['NO\r\n']}, {'input': ['J@Y9Gz550l@\x7fPqVZdQ!u\r\n'], 'output': ['NO\r\n']}, {'input': ['VTE6aTTta@DHe4xeG@6.c2R.J.O7sndWEEW.9j@.l..3Bs\r\n'], 'output': ['NO\r\n']}, {'input': ['aeo2XkK@UX.nQJN!Tg..wGN5YOi68U.oP2Yl3/\r\n'], 'output': ['NO\r\n']}, {'input': ['m13zREg8LbPr@T2.Z9@g.9u.v.A..XNH/1/tloIceXydZf3\r\n'], 'output': ['NO\r\n']}, {'input': ['4@@..f3ZT./oUGZ@\r\n'], 'output': ['NO\r\n']}, {'input': ['G.rVAxwDx@a.PVSe!KtpX4tzs/0yQGzZCPJPJoda\r\n'], 'output': ['NO\r\n']}, {'input': ['SV9T5RR425Sl0b@kzj.XT.PFWc..ho/VE7gjf\r\n'], 'output': ['NO\r\n']}, {'input': ['bgko@1../xwSj_\x7fJ\r\n'], 'output': ['NO\r\n']}, {'input': ['n5ymLC.bE@ukio.im2../.\r\n'], 'output': ['NO\r\n']}, {'input': ['zr.KB_6ZMSwI2GA5@R/4iP1ZKHpszW!YN/\r\n'], 'output': ['NO\r\n']}, {'input': ['@alK@pR\r\n'], 'output': ['NO\r\n']}, {'input': ['al_Y2I4IKp@A_N.\x7fruCw0VL/hRzJtx.S7sp/r!c.n9ffh\r\n'], 'output': ['NO\r\n']}, {'input': ['C1rE26_rTAVzLm@6@X5OGX.ibJ9./kkBEVlcU\r\n'], 'output': ['NO\r\n']}, {'input': ['feGSXP@eyUfr\x7f8.x4Re.JL.6B.r/fX_\r\n'], 'output': ['NO\r\n']}, {'input': ['Ht15T@50eo.E@.\r\n'], 'output': ['NO\r\n']}, {'input': ['k9MITs_Ar.JL2RRs4@VRq.wCuJ.6..amF.fE4.5I.6fJ7gz7\r\n'], 'output': ['NO\r\n']}, {'input': ['Mi\x7fWPE8@fc./IViqq4T4PSUuMdhH\r\n'], 'output': ['NO\r\n']}, {'input': ['pxSCmv!NbMvz2@pTQ.t!.Ntz/QEh_sl\r\n'], 'output': ['NO\r\n']}, {'input': ['s@mH@RO\x7f_/iWD\r\n'], 'output': ['NO\r\n']}, {'input': ['UP51i49wX@pvx@2LWm8w/G4M3J./9L6Szy\r\n'], 'output': ['NO\r\n']}, {'input': ['xC_5Vx8NgF..\x7fln@X1.drRTX..1vx.Xb3of@/PQYPeq@_y8!h_iF\r\n'], 'output': ['NO\r\n']}, {'input': ['qG3@LKp\r\n'], 'output': ['YES\r\n']}, {'input': ['flTq1knyb@2!Mtfss\r\n'], 'output': ['NO\r\n']}, {'input': ['/pqi7WXQPJFM4q1@hxUyUy\x7f/_pWo0n\r\n'], 'output': ['NO\r\n']}, {'input': ['zXme@.Dq.TWBs.fB.M\r\n'], 'output': ['NO\r\n']}, {'input': ['o3EaAnc3K6@h\r\n'], 'output': ['YES\r\n']}, {'input': ['G/AZdVMTzRLV4Ucm@eQ!..pq!..tRTi5.Ejkqa/HGpFYk\r\n'], 'output': ['NO\r\n']}, {'input': ['.c_V@L.1v!AFAEk7glM\x7fq.ag8Sy8@0.Qm/OLKoJpZlac\r\n'], 'output': ['NO\r\n']}, {'input': ['WKxNIM79u\x7f@I.RM\r\n'], 'output': ['NO\r\n']}, {'input': ['POTjlYcxAZsbyZPDh@sPm.z6aVaO.H1wEUhD9YvROQFUk/M_jTHS_6!\r\n'], 'output': ['NO\r\n']}, {'input': ['pbRIiuA@KZ2hVed2fMikA.@ebd.tE2Y\r\n'], 'output': ['NO\r\n']}, {'input': ['OlS_OwxYhH@im.0A7o/juNlxB\r\n'], 'output': ['YES\r\n']}, {'input': ['xkjHHDRBEFwgNP@G9TGStEs2Lu.BJge3EBXw3c9EfE\r\n'], 'output': ['YES\r\n']}, {'input': ['bK@8X7tQO.pXBHJpDewD\r\n'], 'output': ['YES\r\n']}, {'input': ['kKUXy6@0WefbXz39ywP.Q3r7uF\r\n'], 'output': ['YES\r\n']}, {'input': ['SllbRLdZ6@.T.E3x.BE2nIv.5db_.38./zgVGNjpldr\r\n'], 'output': ['NO\r\n']}, {'input': ['4lBJkY8c097oa@ZYmVbtiyyYN.gbj\r\n'], 'output': ['YES\r\n']}, {'input': ['F@JX4.SI1/0EY3XmYatfY\r\n'], 'output': ['YES\r\n']}, {'input': ['oLo01@B77Pu.9R.vtAZG0.HQSunv0J.\r\n'], 'output': ['NO\r\n']}, {'input': ['xLEctap0T@22U9W_fA/7iQeJGFu1lSgMZ\r\n'], 'output': ['YES\r\n']}, {'input': ['WYh@yUWfOQiF.gOK9k8aEa\r\n'], 'output': ['YES\r\n']}, {'input': ['BPxNVANhtEh@Oh_go.\r\n'], 'output': ['NO\r\n']}, {'input': ['mGIY@cHRNC8GlJ/2pcl3LYxpi3PaKGs\r\n'], 'output': ['YES\r\n']}, {'input': ['x6yfn7BGwqWd@.N/UXC\r\n'], 'output': ['NO\r\n']}, {'input': ['cUIr@cP.eGQC2xJXvI1X7\r\n'], 'output': ['YES\r\n']}, {'input': ['MLZ6e1vgZ4hOI@ktWk.Ro.o6C4/i8cnKHT\r\n'], 'output': ['YES\r\n']}, {'input': ['XCJIa@jFaP.Eu28YaoT9Z.Epk.Z/4TBzLWf724zE1r\r\n'], 'output': ['YES\r\n']}, {'input': ['Cz1U1xjg6iW0U@.97HoVA.YG.Qd.eI.DCXxtibi6HG.GV/0sN\r\n'], 'output': ['NO\r\n']}, {'input': ['nrKbWV@P0irxQoRxDsNvG/69WxCwCsfB\r\n'], 'output': ['YES\r\n']}, {'input': ['yI1nRv3FbuhgaI@.Y9vKe.8oc.BLi.6JfYT/tT5d36\r\n'], 'output': ['NO\r\n']}, {'input': ['IGsma3L6YTJRrXS@1g.yR3mC.c.xoCns7Wo1.9C.Oe.5ebkR/_97Ltj3\r\n'], 'output': ['YES\r\n']}, {'input': ['Uu538LDu9Bye@Gu0W0P5a.b9zA9nSaNhzB_TQ2.z/qfi5CZrH\r\n'], 'output': ['YES\r\n']}, {'input': ['bdHl525me@XzR_iO23v.YFXbnHUybbgw.i/WVEhm\r\n'], 'output': ['YES\r\n']}, {'input': ['NQsZ0K@eE8VMB.w2nYtKImB.4nUF\r\n'], 'output': ['YES\r\n']}, {'input': ['186@E.MmBaKLj.WYpt4wPZkzv93\r\n'], 'output': ['YES\r\n']}, {'input': ['hmhYxkGtWYRJFtBU@Drg3L7WKujE.lU61Ljqxv./FJ4X\r\n'], 'output': ['NO\r\n']}, {'input': ['t1RIUz9l3FA15@tOL9.rv.NjhouD.\r\n'], 'output': ['NO\r\n']}, {'input': ['_I4ytjyccT@q.WIc.Cqn\r\n'], 'output': ['YES\r\n']}, {'input': ['LwHHRYq@whOoq.e9b6i0xnoWBl7z.SGJiJe/iUij1x7\r\n'], 'output': ['YES\r\n']}, {'input': ['Yesx@9_KiJq2cBI6.\r\n'], 'output': ['NO\r\n']}, {'input': ['Zu5VFUtSbIw@ner5e\r\n'], 'output': ['YES\r\n']}, {'input': ['test@test.\r\n'], 'output': ['NO\r\n']}, {'input': ['test@.test\r\n'], 'output': ['NO\r\n']}, {'input': ['est.@test\r\n'], 'output': ['NO\r\n']}, {'input': ['test@test.ru/\r\n'], 'output': ['NO\r\n']}, {'input': ['asd@asd@\r\n'], 'output': ['NO\r\n']}, {'input': ['@\r\n'], 'output': ['NO\r\n']}, {'input': ['/\r\n'], 'output': ['NO\r\n']}, {'input': ['.\r\n'], 'output': ['NO\r\n']}, {'input': ['mike@\r\n'], 'output': ['NO\r\n']}, {'input': ['@mike\r\n'], 'output': ['NO\r\n']}, {'input': ['@mail.ru\r\n'], 'output': ['NO\r\n']}, {'input': ['test.me\r\n'], 'output': ['NO\r\n']}, {'input': ['$@ru\r\n'], 'output': ['NO\r\n']}, {'input': ['testme@o.o.o.o.o/ooooo\r\n'], 'output': ['YES\r\n']}, {'input': ['oooop/oooop\r\n'], 'output': ['NO\r\n']}, {'input': ['mail.ru/a\r\n'], 'output': ['NO\r\n']}, {'input': ['mike@mail.ru/aaa\r\n'], 'output': ['YES\r\n']}, {'input': ['mike@mike.mike\r\n'], 'output': ['YES\r\n']}]


Ksusha is a vigorous mathematician. She is keen on absolutely incredible mathematical riddles. Today Ksusha came across a convex polygon of non-zero area. She is now wondering: if she chooses a pair of distinct points uniformly among all integer points (points with integer coordinates) inside or on the border of the polygon and then draws a square with two opposite vertices lying in the chosen points, what will the expectation of this square's area be?A pair of distinct points is chosen uniformly among all pairs of distinct points, located inside or on the border of the polygon. Pairs of points p,q (p≠q) and q,p are considered the same.Help Ksusha! Count the required expectation.

The first line contains integer n (3≤n≤10^5) — the number of vertices of Ksusha's convex polygon. Next n lines contain the coordinates of the polygon vertices in clockwise or counterclockwise order. The i-th line contains integers xi,yi (|xi|,|yi|≤10^6) — the coordinates of the vertex that goes i-th in that order.

Print a single real number — the required expected area.
The answer will be considered correct if its absolute and relative error doesn't exceed 10^-6.

def polygon_area(vertices)
  n = vertices.length
  sum = 0
  for i in 0...n
    j = (i+1)%n
    sum += vertices[i][0]*vertices[j][1] - vertices[j][0]*vertices[i][1]
  end
  return sum.abs/2.0
end

def sum_squares(n)
  return n*(n+1)*(2*n+1)/6
end

def solve(n, vertices)
  vertices.sort_by! {|x, y| [x, y]}
  x_values = vertices.map {|x, y| x}.uniq
  y_values = Array.new(x_values.length, 0)
  x_values.each_with_index do |x, i|
    y_values[i] = vertices.select {|vx, vy| vx == x}.map {|vx, vy| vy}.sort
  end
  total_sum = 0
  total_count = 0
  x_values.each_with_index do |x, i|
    count = y_values[i].length
    sum = y_values[i].sum
    total_sum += sum_squares(x)*(2*count-sum) + sum_squares(n-x-1)*(2*count-sum)
    total_count += count*count
  end
  return total_sum/total_count.to_f
end

lines = gets.chomp.split('\n').map {|line| line.split.map(&:to_i)}
n = lines.shift[0]
vertices = lines
puts '%.10f' % solve(n, vertices)


There are n cities in Berland. Each city has its index — an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city i, different from the capital, there is kept number pi — index of the last city on the way from the capital to i.Once the king of Berland Berl XXXIV decided to move the capital from city r1 to city r2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above.

The first line contains three space-separated integers n, r1, r2 (2≤n≤5·10^4,1≤r1≠r2≤n) — amount of cities in Berland, index of the old capital and index of the new one, correspondingly.
The following line contains n-1 space-separated integers — the old representation of the road map. For each city, apart from r1, there is given integer pi — index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes.

Output n-1 numbers — new representation of the road map in the same format.

n, r1, r2 = gets.split.map(&:to_i)
graph = Array.new(n+1) {[]}
old_map = gets.split.map(&:to_i)

old_map.insert(r1-1, 0)

(1..n).each do |i|
  graph[i] << old_map[i-1]
  graph[old_map[i-1]] << i if old_map[i-1] != 0
end

visited = Array.new(n+1, false)
new_map = Array.new(n+1, 0)

queue = [r2]
visited[r2] = true

while !queue.empty?
  current_city = queue.shift
  graph[current_city].each do |neighbour|
    unless visited[neighbour]
      new_map[neighbour] = current_city
      visited[neighbour] = true
      queue << neighbour
    end
  end
end

(1..n).each { |i| print "#{new_map[i]} " if i != r2 }


Today there is going to be an unusual performance at the circus — hamsters and tigers will perform together! All of them stand in circle along the arena edge and now the trainer faces a difficult task: he wants to swap the animals' positions so that all the hamsters stood together and all the tigers also stood together. The trainer swaps the animals in pairs not to create a mess. He orders two animals to step out of the circle and swap places. As hamsters feel highly uncomfortable when tigers are nearby as well as tigers get nervous when there's so much potential prey around (consisting not only of hamsters but also of yummier spectators), the trainer wants to spend as little time as possible moving the animals, i.e. he wants to achieve it with the minimal number of swaps. Your task is to help him.

The first line contains number n (2≤n≤1000) which indicates the total number of animals in the arena. The second line contains the description of the animals' positions. The line consists of n symbols "H" and "T". The "H"s correspond to hamsters and the "T"s correspond to tigers. It is guaranteed that at least one hamster and one tiger are present on the arena. The animals are given in the order in which they are located circle-wise, in addition, the last animal stands near the first one.

Print the single number which is the minimal number of swaps that let the trainer to achieve his goal.

In the first example we shouldn't move anybody because the animals of each species already stand apart from the other species. In the second example you may swap, for example, the tiger in position 2 with the hamster in position 5 and then — the tiger in position 9 with the hamster in position 7.

def min_swaps
  n = gets.to_i
  s = gets.chomp.split('')
  tigers = s.count('T')
  hamsters = s.count('H')
  min_swaps = tigers
  s = s * 2
  (0...n).each do |i|
    tigers_in_range = s[i...(i+hamsters)].count('T')
    min_swaps = [min_swaps, tigers_in_range].min
  end
  puts min_swaps
end

min_swaps

[{'input': ['3\r\nHTH\r\n'], 'output': ['0\r\n']}, {'input': ['9\r\nHTHTHTHHT\r\n'], 'output': ['2\r\n']}, {'input': ['2\r\nTH\r\n'], 'output': ['0\r\n']}, {'input': ['4\r\nHTTH\r\n'], 'output': ['0\r\n']}, {'input': ['4\r\nHTHT\r\n'], 'output': ['1\r\n']}, {'input': ['7\r\nTTTHTTT\r\n'], 'output': ['0\r\n']}, {'input': ['8\r\nHHTHHTHH\r\n'], 'output': ['1\r\n']}, {'input': ['13\r\nHTTTHHHTTTTHH\r\n'], 'output': ['3\r\n']}, {'input': ['20\r\nTTHTHTHHTHTTHHTTTHHH\r\n'], 'output': ['4\r\n']}, {'input': ['35\r\nTTTTTTHTTHTTTTTHTTTTTTTTTTTHTHTTTTT\r\n'], 'output': ['3\r\n']}, {'input': ['120\r\nTTTTTTTHTHTHTTTTTHTHTTTTHTTTTTTTTTTTTTTTTTTTTHTTHTTTTHTTHTTTTTTTTTTTTTTTHTTTTTTHTHTTHTTTTTTHTTTTTTTTTHTTHTTTTHTTTHTTTTTH\r\n'], 'output': ['14\r\n']}, {'input': ['19\r\nHHHHHHHHHHHHHTTTHHH\r\n'], 'output': ['0\r\n']}, {'input': ['87\r\nHTHHTTHHHHTHHHHHTTTHHTHHHHTTTTHHHTTHHTHTHTHHTTHTHHTHTHTTHHHTTTTTHTTHHHHHHTHHTHHTHTTHTHH\r\n'], 'output': ['17\r\n']}, {'input': ['178\r\nTHHHTHTTTHTTHTTHHHHHTTTHTTHHTHTTTHTHTTTTTHHHTHTHHHTHHHTTTTTTTTHHHHTTHHTHHHHTHTTTHHHHHHTHHTHTTHTHTTTTTTTTTHHTTHHTHTTHHTHHHHHTTHHTTHHTTHHHTTHHTTTTHTHHHTHTTHTHTTTHHHHTHHTHHHTHTTTTTT\r\n'], 'output': ['40\r\n']}]


You are given a n×m field consisting only of periods ('.') and asterisks ('*'). Your task is to count all right triangles with two sides parallel to the square sides, whose vertices are in the centers of '*'-cells. A right triangle is a triangle in which one angle is a right angle (that is, a 90 degree angle).

The first line contains two positive integer numbers n and m (1≤n,m≤1000). The following n lines consist of m characters each, describing the field. Only '.' and '*' are allowed.

Output a single number — total number of square triangles in the field. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).

n, m = gets.split.map(&:to_i)
field = Array.new(n){Array.new(m, 0)}
rows = Array.new(n, 0)
cols = Array.new(m, 0)

n.times do |i|
  line = gets.chomp.chars
  m.times do |j|
    if line[j] == '*'
      field[i][j] = 1
      rows[i] += 1
      cols[j] += 1
    end
  end
end

count = 0
n.times do |i|
  m.times do |j|
    if field[i][j] == 1
      count += (rows[i] - 1) * (cols[j] - 1)
    end
  end
end

puts count


One popular blog site edits the uploaded photos like this. It cuts a rectangular area out of them so that the ratio of height to width (i.e. the height/width quotient) can vary from 0.8 to 1.25 inclusively. Besides, at least one side of the cut area should have a size, equal to some power of number 2 (2^x for some integer x). If those rules don't indicate the size of the cut are clearly, then the way with which the cut part possesses the largest area is chosen. Of course, both sides of the cut area should be integer. If there are several answers to this problem, you should choose the answer with the maximal height.

The first line contains a pair of integers h and w (1≤h,w≤10^9) which are the height and width of the uploaded photo in pixels.

Print two integers which are the height and width of the cut area.

def find_cut_area(h, w)
    max_height = 0
    max_width = 0
    max_area = 0

    (0..30).each do |i|
        size = 2 ** i
        break if size > h

        width = [w, (size / 0.8).floor].min
        next if width < size * 0.8 || width > size * 1.25

        area = size * width
        if area > max_area
            max_area = area
            max_height = size
            max_width = width
        end
    end

    (0..30).each do |i|
        size = 2 ** i
        break if size > w

        height = [h, (size / 0.8).floor].min
        next if height < size * 0.8 || height > size * 1.25

        area = size * height
        if area > max_area || (area == max_area && height > max_height)
            max_area = area
            max_height = height
            max_width = size
        end
    end

    return max_height, max_width
end

h, w = gets.split.map(&:to_i)
height, width = find_cut_area(h, w)
puts "#{height} #{width}"


Polycarp is very careful. He even types numeric sequences carefully, unlike his classmates. If he sees a sequence without a space after the comma, with two spaces in a row, or when something else does not look neat, he rushes to correct it. For example, number sequence written like "1,2 ,3,...,   10" will be corrected to "1, 2, 3, ..., 10".In this task you are given a string s, which is composed by a concatination of terms, each of which may be:   a positive integer of an arbitrary length (leading zeroes are not allowed),  a "comma" symbol (","),  a "space" symbol (" "),  "three dots" ("...", that is, exactly three points written one after another, also known as suspension points). Polycarp wants to add and remove spaces in the string s to ensure the following:   each comma is followed by exactly one space (if the comma is the last character in the string, this rule does not apply to it),  each "three dots" term is preceded by exactly one space (if the dots are at the beginning of the string, this rule does not apply to the term),  if two consecutive numbers were separated by spaces only (one or more), then exactly one of them should be left,  there should not be other spaces. Automate Polycarp's work and write a program that will process the given string s.

The input data contains a single string s. Its length is from 1 to 255 characters. The string s does not begin and end with a space. Its content matches the description given above.

Print the string s after it is processed. Your program's output should be exactly the same as the expected answer. It is permissible to end output line with a line-break character, and without it.


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


Let's introduce a number system which is based on a roman digits. There are digits I, V, X, L which correspond to the numbers $$$1$$$, $$$5$$$, $$$10$$$ and $$$50$$$ respectively. The use of other roman digits is not allowed.Numbers in this system are written as a sequence of one or more digits. We define the value of the sequence simply as the sum of digits in it.For example, the number XXXV evaluates to $$$35$$$ and the number IXI — to $$$12$$$.Pay attention to the difference to the traditional roman system — in our system any sequence of digits is valid, moreover the order of digits doesn't matter, for example IX means $$$11$$$, not $$$9$$$.One can notice that this system is ambiguous, and some numbers can be written in many different ways. Your goal is to determine how many distinct integers can be represented by exactly $$$n$$$ roman digits I, V, X, L.

The only line of the input file contains a single integer $$$n$$$ ($$$1 \le n \le 10^9$$$) — the number of roman digits to use.

Output a single integer — the number of distinct integers which can be represented using $$$n$$$ roman digits exactly.

NoteIn the first sample there are exactly $$$4$$$ integers which can be represented — I, V, X and L.In the second sample it is possible to represent integers $$$2$$$ (II), $$$6$$$ (VI), $$$10$$$ (VV), $$$11$$$ (XI), $$$15$$$ (XV), $$$20$$$ (XX), $$$51$$$ (IL), $$$55$$$ (VL), $$$60$$$ (XL) and $$$100$$$ (LL).


International Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where y stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string y that has never been used before. Among all such valid abbreviations they choose the shortest one and announce it to be the abbreviation of this year's competition.For example, the first three Olympiads (years 1989, 1990 and 1991, respectively) received the abbreviations IAO'9, IAO'0 and IAO'1, while the competition in 2015 received an abbreviation IAO'15, as IAO'5 has been already used in 1995.You are given a list of abbreviations. For each of them determine the year it stands for.

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of abbreviations to process.  Then n lines follow, each containing a single abbreviation. It's guaranteed that each abbreviation contains at most nine digits.

For each abbreviation given in the input, find the year of the corresponding Olympiad.

def find_earliest(s, forbid)
	(0...100000).each{ |i|
		s2 = (i == 0 ? "" : i.to_s) + s
		if s2.to_i >= 1989 && !forbid.include?(s2.to_i)
			return s2.to_i
		end
	}
end

n = gets.chomp.to_i

n.times {
	s = gets.chomp[4..-1]
	forbid = []
	ans = 0
	(1..s.size).each{ |i|
		ans = find_earliest(s[(-i)..-1], forbid)
		forbid.push ans
	}
	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


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


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


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


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


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']}]


A car number in Berland consists of exactly n digits. A number is called beautiful if it has at least k equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of n digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one.Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one.

The first line contains two space-separated integers n and k (2 ≤ n ≤ 104, 2 ≤ k ≤ n) which represent how many digits the number has and how many equal digits a beautiful number should have. The second line consists of n digits. It describes the old number of Vasya's car. It is guaranteed that the number contains no spaces and only contains digits.

On the first line print the minimum sum of money Vasya needs to change the number. On the second line print the car's new number. If there are several solutions, print the lexicographically minimum one.

NoteIn the first sample replacing the second digit with an "8" costs |9 - 8| = 1. Replacing the fifth digit with an "8" costs the same. Replacing the sixth digit costs |6 - 8| = 2. As a result, Vasya will pay 1 + 1 + 2 = 4 for a beautiful number "888188".The lexicographical comparison of strings is performed by the < operator in modern programming languages. The string x is lexicographically smaller than the string y, if there exists such i (1 ≤ i ≤ n), that xi < yi, and for any j (1 ≤ j < i) xj = yj. The strings compared in this problem will always have the length n.

k=gets.split[1].to_i
a=gets.split[0].bytes.to_a
n=a.length
cnt=Array.new(10,0)
n.times{|i|
    a[i]-=48
    cnt[a[i]]+=1
}
mincost=99999999
res=[]
10.times{|d|
    cost=0
    count=cnt[d]
    1.upto(9){|i|
        if count>=k then
            break
        end
        if d+i<=9 then
            if cnt[d+i]+count>=k then
                cost+=i*(k-count)
                count=k
            else
                count+=cnt[d+i]
                cost+=cnt[d+i]*i
            end
        end
        if d-i>=0 then
            if cnt[d-i]+count>=k then
                cost+=i*(k-count)
                count=k
            else
                count+=cnt[d-i]
                cost+=cnt[d-i]*i
            end
        end
    }
    if cost<mincost then
        mincost=cost
        res=[]
    end
    if cost==mincost then
        ans=Array.new(n,0)
        used=Array.new(n,0)
        count=0
        0.upto(9){|i|
            tar=d+i
            n.times{|j|
                if count>=k then
                    break
                end
                if used[j]==0 && a[j]==tar then
                    ans[j]=d
                    count+=1
                    used[j]=true
                end
            }
            tar=d-i
            (n-1).downto(0){|j|
                if count>=k then
                    break
                end
                if used[j]==0 && a[j]==tar then
                    ans[j]=d
                    count+=1
                    used[j]=true
                end
            }
        }
        n.times{|j|
            if used[j]==0 then
                ans[j]=a[j]
            end
        }
        res.push(ans)
    end
}
puts mincost
ans=res.min
ans.each{|i| print i}
puts


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]


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']}]


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


The History of Magic is perhaps the most boring subject in the Hogwarts school of Witchcraft and Wizardry. Harry Potter is usually asleep during history lessons, and his magical quill writes the lectures for him. Professor Binns, the history of magic teacher, lectures in such a boring and monotonous voice, that he has a soporific effect even on the quill. That's why the quill often makes mistakes, especially in dates.So, at the end of the semester Professor Binns decided to collect the students' parchments with notes and check them. Ron Weasley is in a panic: Harry's notes may contain errors, but at least he has some notes, whereas Ron does not have any. Ronald also has been sleeping during the lectures and his quill had been eaten by his rat Scabbers. Hermione Granger refused to give Ron her notes, because, in her opinion, everyone should learn on their own. Therefore, Ron has no choice but to copy Harry's notes.Due to the quill's errors Harry's dates are absolutely confused: the years of goblin rebellions and other important events for the wizarding world do not follow in order, and sometimes even dates from the future occur. Now Ron wants to change some of the digits while he copies the notes so that the dates were in the chronological (i.e. non-decreasing) order and so that the notes did not have any dates strictly later than 2011, or strictly before than 1000. To make the resulting sequence as close as possible to the one dictated by Professor Binns, Ron will change no more than one digit in each date into other digit. Help him do it.

The first input line contains an integer n (1 ≤ n ≤ 1000). It represents the number of dates in Harry's notes. Next n lines contain the actual dates y1, y2, ..., yn, each line contains a date. Each date is a four-digit integer (1000 ≤ yi ≤ 9999).

Print n numbers z1, z2, ..., zn (1000 ≤ zi ≤ 2011). They are Ron's resulting dates. Print each number on a single line. Numbers zi must form the non-decreasing sequence. Each number zi should differ from the corresponding date yi in no more than one digit. It is not allowed to change the first digit of a number into 0. If there are several possible solutions, print any of them. If there's no solution, print "No solution" (without the quotes).

def min(x, lim)
  (lim.."2011").each do |s|
    d = 0
    for i in 0..3
       d += (s[i] == x[i]) ? 0 : 1
    end
    next if d > 1

    return s
  end

  return false
end

lim = "1000"
o = []
gets.to_i.times do
  s = gets.chomp
  r = min(s, lim)
  unless r
    puts "No solution"
    exit
  end
  o << r
  lim = r
end
puts o


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


Last year the world's largest square was built in Berland. It is known that the square can be represented as an infinite plane with an introduced Cartesian system of coordinates. On that square two sets of concentric circles were painted. Let's call the set of concentric circles with radii 1, 2, ..., K and the center in the point (z, 0) a (K, z)-set. Thus, on the square were painted a (N, x)-set and a (M, y)-set. You have to find out how many parts those sets divided the square into.

The first line contains integers N, x, M, y. (1 ≤ N, M ≤ 100000,  - 100000 ≤ x, y ≤ 100000, x ≠ y).

n,x,m,y = gets.chomp.split(/ /).map!{|x| x.to_i}
if x > y
	x,y = y,x
	n,m = m,n
end

ret = n+1
for i in 1..m
    ly=y-i-x
	ry=y+i-x
    if (ly>=n || ly<=-n)
		ret+=1
	elsif (ly>=0 && ry>=0)
	  ry=[n,ry-1].min
      ret+=2*(ry-ly)
    else
      ry=[n,ry-1].min
      ret +=2*(ry+ly)+1
    end
end

puts ret


Berland scientists noticed long ago that the world around them depends on Berland population. Due to persistent research in this area the scientists managed to find out that the Berland chronology starts from the moment when the first two people came to that land (it is considered to have happened in the first year). After one Berland year after the start of the chronology the population had already equaled 13 people (the second year). However, tracing the population number during the following years was an ultimately difficult task, still it was found out that if di — the number of people in Berland in the year of i, then either di = 12di - 2, or di = 13di - 1 - 12di - 2. Of course no one knows how many people are living in Berland at the moment, but now we can tell if there could possibly be a year in which the country population equaled A. That's what we ask you to determine. Also, if possible, you have to find out in which years it could be (from the beginning of Berland chronology). Let's suppose that it could be in the years of a1, a2, ..., ak. Then you have to define how many residents could be in the country during those years apart from the A variant. Look at the examples for further explanation.

The first line contains integer A (1 ≤ A < 10300). It is guaranteed that the number doesn't contain leading zeros.

On the first output line print YES, if there could be a year in which the total population of the country equaled A, otherwise print NO.  If the answer is YES, then you also have to print number k — the number of years in which the population could equal A. On the next line you have to output precisely k space-separated numbers — a1, a2, ..., ak. Those numbers have to be output in the increasing order. On the next line you should output number p — how many variants of the number of people could be in the years of a1, a2, ..., ak, apart from the A variant. On each of the next p lines you have to print one number — the sought number of residents. Those number also have to go in the increasing order.  If any number (or both of them) k or p exceeds 1000, then you have to print 1000 instead of it and only the first 1000 possible answers in the increasing order. The numbers should have no leading zeros.


Vasya tries to break in a safe. He knows that a code consists of n numbers, and every number is a 0 or a 1. Vasya has made m attempts to enter the code. After each attempt the system told him in how many position stand the right numbers. It is not said in which positions the wrong numbers stand. Vasya has been so unlucky that he hasn’t entered the code where would be more than 5 correct numbers. Now Vasya is completely bewildered: he thinks there’s a mistake in the system and it is self-contradictory. Help Vasya — calculate how many possible code variants are left that do not contradict the previous system responses.

The first input line contains two integers n and m (6 ≤ n ≤ 35, 1 ≤ m ≤ 10) which represent the number of numbers in the code and the number of attempts made by Vasya. Then follow m lines, each containing space-separated si and ci which correspondingly indicate Vasya’s attempt (a line containing n numbers which are 0 or 1) and the system’s response (an integer from 0 to 5 inclusively).

Print the single number which indicates how many possible code variants that do not contradict the m system responses are left.

$b = 4096.times.to_a.map{|i| i.to_s(2).count('1')}

def bits(x)
	$b[x & 4095] + $b[(x >> 12) & 4095] + $b[x >> 24]
end

n, m = gets.split.map(&:to_i)
a = []
m.times do |t|
	s, c = gets.split
	s = s.to_i(2)
	c = c.to_i
	if t.zero? then
		[*0..n-1].combination(c).each do |i|
			a << s
			i.each{|j| a[-1] ^= 1 << j}
		end
	else
		a.reject!{|i| bits(i ^ s) != c}
	end
end
p a.size

__END__
: || 0


Every year a race takes place on the motorway between cities A and B. This year Vanya decided to take part in the race and drive his own car that has been around and bears its own noble name — The Huff-puffer.So, Vasya leaves city A on the Huff-puffer, besides, at the very beginning he fills the petrol tank with α liters of petrol (α ≥ 10 is Vanya's favorite number, it is not necessarily integer). Petrol stations are located on the motorway at an interval of 100 kilometers, i.e. the first station is located 100 kilometers away from the city A, the second one is 200 kilometers away from the city A, the third one is 300 kilometers away from the city A and so on. The Huff-puffer spends 10 liters of petrol every 100 kilometers. Vanya checks the petrol tank every time he passes by a petrol station. If the petrol left in the tank is not enough to get to the next station, Vanya fills the tank with α liters of petrol. Otherwise, he doesn't stop at the station and drives on. For example, if α = 43.21, then the car will be fuelled up for the first time at the station number 4, when there'll be 3.21 petrol liters left. After the fuelling up the car will have 46.42 liters. Then Vanya stops at the station number 8 and ends up with 6.42 + 43.21 = 49.63 liters. The next stop is at the station number 12, 9.63 + 43.21 = 52.84. The next stop is at the station number 17 and so on. You won't believe this but the Huff-puffer has been leading in the race! Perhaps it is due to unexpected snow. Perhaps it is due to video cameras that have been installed along the motorway which register speed limit breaking. Perhaps it is due to the fact that Vanya threatened to junk the Huff-puffer unless the car wins. Whatever the reason is, the Huff-puffer is leading, and jealous people together with other contestants wrack their brains trying to think of a way to stop that outrage.One way to do this is to mine the next petrol station where Vanya will stop. Your task is to calculate at which station this will happen and warn Vanya. You don't know the α number, however, you are given the succession of the numbers of the stations where Vanya has stopped. Find the number of the station where the next stop will be.

The first line contains an integer n (1 ≤ n ≤ 1000) which represents the number of petrol stations where Vanya has stopped. The next line has n space-separated integers which represent the numbers of the stations. The numbers are positive and do not exceed 106, they are given in the increasing order. No two numbers in the succession match. It is guaranteed that there exists at least one number α ≥ 10, to which such a succession of stops corresponds.

Print in the first line "unique" (without quotes) if the answer can be determined uniquely. In the second line print the number of the station where the next stop will take place. If the answer is not unique, print in the first line "not unique".

NoteIn the second example the answer is not unique. For example, if α = 10, we'll have such a sequence as 1, 2, 3, and if α = 14, the sequence will be 1, 2, 4.

gets
x = gets.split.map &:to_i
mina = []
maxa = []
x.map.with_index do |o,i|
    mina << Float(o)/(i+1)
    maxa << Float(o+1)/(i+1)-0.00000001
end
a = ([mina.max,1].max*(x.size+1)).floor
b = (maxa.min*(x.size+1)).floor
puts a == b ? "unique\n#{a}" : "not unique"


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"


Let's imagine: there is a chess piece billiard ball. Its movements resemble the ones of a bishop chess piece. The only difference is that when a billiard ball hits the board's border, it can reflect from it and continue moving.More formally, first one of four diagonal directions is chosen and the billiard ball moves in that direction. When it reaches the square located on the board's edge, the billiard ball reflects from it; it changes the direction of its movement by 90 degrees and continues moving. Specifically, having reached a corner square, the billiard ball is reflected twice and starts to move the opposite way. While it moves, the billiard ball can make an infinite number of reflections. At any square of its trajectory the billiard ball can stop and on that the move is considered completed.  It is considered that one billiard ball a beats another billiard ball b if a can reach a point where b is located.You are suggested to find the maximal number of billiard balls, that pairwise do not beat each other and that can be positioned on a chessboard n × m in size.

The first line contains two integers n and m (2 ≤ n, m ≤ 106).

Print a single number, the maximum possible number of billiard balls that do not pairwise beat each other. Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is preferred to use cin (also you may use the %I64d specificator).

n,m=gets.chomp.split.collect{|a| a.to_i}
puts ((n-1).gcd(m-1)+1)


Ahmed and Mostafa used to compete together in many programming contests for several years. Their coach Fegla asked them to solve one challenging problem, of course Ahmed was able to solve it but Mostafa couldn't.This problem is similar to a standard problem but it has a different format and constraints.In the standard problem you are given an array of integers, and you have to find one or more consecutive elements in this array where their sum is the maximum possible sum.But in this problem you are given n small arrays, and you will create one big array from the concatenation of one or more instances of the small arrays (each small array could occur more than once). The big array will be given as an array of indexes (1-based) of the small arrays, and the concatenation should be done in the same order as in this array. Then you should apply the standard problem mentioned above on the resulting big array.For example let's suppose that the small arrays are {1, 6, -2}, {3, 3} and {-5, 1}. And the indexes in the big array are {2, 3, 1, 3}. So the actual values in the big array after formatting it as concatenation of the small arrays will be {3, 3, -5, 1, 1, 6, -2, -5, 1}. In this example the maximum sum is 9.Can you help Mostafa solve this problem?

The first line contains two integers n and m, n is the number of the small arrays (1 ≤ n ≤ 50), and m is the number of indexes in the big array (1 ≤ m ≤ 250000). Then follow n lines, the i-th line starts with one integer l which is the size of the i-th array (1 ≤ l ≤ 5000), followed by l integers each one will be greater than or equal -1000 and less than or equal 1000. The last line contains m integers which are the indexes in the big array, and you should concatenate the small arrays in the same order, and each index will be greater than or equal to 1 and less than or equal to n. The small arrays are numbered from 1 to n in the same order as given in the input. Some of the given small arrays may not be used in big array. Note, that the array is very big. So if you try to build it straightforwardly, you will probably get time or/and memory limit exceeded.

Print one line containing the maximum sum in the big array after formatting it as described above. You must choose at least one element for the sum, i. e. it cannot be empty. Please, do not use %lld specificator to write 64-bit integers in C++. It is preferred to use cout (also you may use %I64d).

small_size, big_indexes = gets.chomp.split.map{|s| s.to_i}
smalls = []
small_size.times do
  array = gets.chomp.split.map{|s| s.to_i}
  array.shift
  sum = r_sum = 0
  left = right = max = -1001
  tmp = 0
  array.size.times do |i|
    sum += array[i]
    r_sum += array[-i - 1]
    left = sum if sum > left
    right = r_sum if r_sum > right
    max = array[i] if array[i] > max
    tmp += array[i]
    if tmp < 0
      tmp = 0
    else
      max = tmp if tmp > max
    end
  end
  small = {
    :sum => sum,
    :left => left,
    :right => right,
    :max => max,
  }
  smalls << small
end
max = -1001
tmp = 0
gets.chomp.split.map{|s| s.to_i}.each do |i|
  i -= 1
  max = smalls[i][:max] if smalls[i][:max] >= max
  max = tmp + smalls[i][:left] if tmp + smalls[i][:left] > max
  tmp += smalls[i][:sum]
  tmp = smalls[i][:right] if smalls[i][:right] > tmp
  tmp = 0 if tmp < 0
end
puts max