This problem differs from the next one only in the presence of the constraint on the equal length of all numbers $$$a_1, a_2, \dots, a_n$$$. Actually, this problem is a subtask of the problem D2 from the same contest and the solution of D2 solves this subtask too.A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.Let's denote a function that alternates digits of two numbers $$$f(a_1 a_2 \dots a_{p - 1} a_p, b_1 b_2 \dots b_{q - 1} b_q)$$$, where $$$a_1 \dots a_p$$$ and $$$b_1 \dots b_q$$$ are digits of two integers written in the decimal notation without leading zeros.In other words, the function $$$f(x, y)$$$ alternately shuffles the digits of the numbers $$$x$$$ and $$$y$$$ by writing them from the lowest digits to the older ones, starting with the number $$$y$$$. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.For example: $$$$$$f(1111, 2222) = 12121212$$$$$$ $$$$$$f(7777, 888) = 7787878$$$$$$ $$$$$$f(33, 44444) = 4443434$$$$$$ $$$$$$f(555, 6) = 5556$$$$$$ $$$$$$f(111, 2222) = 2121212$$$$$$Formally,  if $$$p \ge q$$$ then $$$f(a_1 \dots a_p, b_1 \dots b_q) = a_1 a_2 \dots a_{p - q + 1} b_1 a_{p - q + 2} b_2 \dots a_{p - 1} b_{q - 1} a_p b_q$$$;  if $$$p < q$$$ then $$$f(a_1 \dots a_p, b_1 \dots b_q) = b_1 b_2 \dots b_{q - p} a_1 b_{q - p + 1} a_2 \dots a_{p - 1} b_{q - 1} a_p b_q$$$. Mishanya gives you an array consisting of $$$n$$$ integers $$$a_i$$$. All numbers in this array are of equal length (that is, they consist of the same number of digits). Your task is to help students to calculate $$$\sum_{i = 1}^{n}\sum_{j = 1}^{n} f(a_i, a_j)$$$ modulo $$$998\,244\,353$$$.

The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the number of elements in the array. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the elements of the array. All numbers $$$a_1, a_2, \dots, a_n$$$ are of equal length (that is, they consist of the same number of digits).

Print the answer modulo $$$998\,244\,353$$$.

MOD = 998244353
n = gets.to_i
a = gets.split.map(&:to_i)
cnt = [0]*10
a.each do |v|
  cnt[Math.log10(v).to_i] += 1
end
ans = 0
a.each do |v|
  d = Math.log10(v).to_i
  l,r,m = v,0,1
  10.times do |i|
    r += m*(l%10)
    l /= 10
    m *= 100
    if i < d
      ans += l * m * cnt[i] * 2 % MOD
      ans += (r + r*10) * cnt[i] % MOD
    else
      ans += (r + r*10) * cnt[i] % MOD
    end
    ans %= MOD
  end
end
p ans

n = gets.to_i
a = gets.split(/\s+/).map(&:to_i)
mod = 998244353

ten = (0..21).map{|e| 10**e}
ans = 0
a.each do |x|
  t = 0
  while x > 0
    p = x % 10;
    ans = (ans + (p*n*ten[t]) % mod) % mod
    ans = (ans + (p*n*ten[t+1]) % mod) % mod
    x /= 10
    t += 2
  end
end

puts ans


There are n points on a straight line, and the i-th point among them is located at xi. All these coordinates are distinct.Determine the number m — the smallest number of points you should add on the line to make the distances between all neighboring points equal.

The first line contains a single integer n (3 ≤ n ≤ 100 000) — the number of points. The second line contains a sequence of integers x1, x2, ..., xn ( - 109 ≤ xi ≤ 109) — the coordinates of the points. All these coordinates are distinct. The points can be given in an arbitrary order.

Print a single integer m — the smallest number of points you should add on the line to make the distances between all neighboring points equal.

NoteIn the first example you can add one point with coordinate 0.In the second example the distances between all neighboring points are already equal, so you shouldn't add anything.

n = gets.to_i
arr = gets.chomp.split.map {|x| x.to_i}.sort

len = arr[-1] - arr[0]
gcd = arr[1] - arr[0]
arr.each_with_index do |x, i|
    gcd = gcd.gcd(x - arr[i - 1]) if i > 0
end

puts len / gcd + 1 - n

n = readline().to_i
a = readline().split().map(&:to_i).sort

g = 0
left = right = a[0]
for i in 1..n-1
	g = g.gcd(a[i]-a[i-1])
	left = [a[i], left].min
	right = [a[i], right].max
end

puts (right-left)/g + 1 - n

n = gets.to_i

xs = gets.split(" ").map(&:to_i).sort

g = 0
(1...n).each do |i|
    g = g.gcd(xs[i] - xs[i-1])
end

res = 0
(1...n).each do |i|
    res += (xs[i] - xs[i-1]) / g - 1
end

puts res

def gcd(a,b)
    if (b == 0)
        a
    else
        gcd(b,a%b)
    end
end

n = readline.to_i

a = readline.split.map(&:to_i).sort

g = a[1] - a[0]
for i in 1 .. n-2
    g = gcd(g, a[i+1]-a[i])
end

ans = 0
for i in 0 .. n-2
    ans += (a[i+1] - a[i]) / g - 1
end

p ans

def gcd a, b
  return a if b.zero?
  gcd b, a % b
end

n = gets.to_i
a = gets.split.map(&:to_i)
t=0
a.sort!

$num = n
$i = 1
while $i < $num  do
   a[$i] = a[$i] - a[0]
   $i +=1
end
a[0]=0
ans = gcd(a[1],a[2])

$num = n
$i = 3
while $i < $num  do
   ans = gcd(ans, a[$i])
   $i +=1
end
ans = (a[n-1] / ans) - n + 1

puts ans

n = gets.to_i
arr = gets.split
i = 0
while i < arr.length
    arr[i] = arr[i].to_i
    i = i + 1
end
arr = arr.sort
if arr.length == 1
    puts 0
else
    g = arr[1] - arr[0]
    i = 2
    while i < arr.length
        a = g
        b = arr[i] - arr[i - 1]
        while b != 0
            tmp = b
            b = a % b
            a = tmp
        end
        i = i + 1
        g = a
        #puts g
    end
    i = 1
    ans = 0
    while i != arr.length
        ans = ans + (arr[i] - arr[i - 1]) / g - 1
        i = i + 1
    end
    puts ans
end


There are n servers in a laboratory, each of them can perform tasks. Each server has a unique id — integer from 1 to n.It is known that during the day q tasks will come, the i-th of them is characterized with three integers: ti — the moment in seconds in which the task will come, ki — the number of servers needed to perform it, and di — the time needed to perform this task in seconds. All ti are distinct.To perform the i-th task you need ki servers which are unoccupied in the second ti. After the servers begin to perform the task, each of them will be busy over the next di seconds. Thus, they will be busy in seconds ti, ti + 1, ..., ti + di - 1. For performing the task, ki servers with the smallest ids will be chosen from all the unoccupied servers. If in the second ti there are not enough unoccupied servers, the task is ignored.Write the program that determines which tasks will be performed and which will be ignored.

The first line contains two positive integers n and q (1 ≤ n ≤ 100, 1 ≤ q ≤ 105) — the number of servers and the number of tasks.  Next q lines contains three integers each, the i-th line contains integers ti, ki and di (1 ≤ ti ≤ 106, 1 ≤ ki ≤ n, 1 ≤ di ≤ 1000) — the moment in seconds in which the i-th task will come, the number of servers needed to perform it, and the time needed to perform this task in seconds. The tasks are given in a chronological order and they will come in distinct seconds.

Print q lines. If the i-th task will be performed by the servers, print in the i-th line the sum of servers' ids on which this task will be performed. Otherwise, print -1.

NoteIn the first example in the second 1 the first task will come, it will be performed on the servers with ids 1, 2 and 3 (the sum of the ids equals 6) during two seconds. In the second 2 the second task will come, it will be ignored, because only the server 4 will be unoccupied at that second. In the second 3 the third task will come. By this time, servers with the ids 1, 2 and 3 will be unoccupied again, so the third task will be done on all the servers with the ids 1, 2, 3 and 4 (the sum of the ids is 10).In the second example in the second 3 the first task will come, it will be performed on the servers with ids 1 and 2 (the sum of the ids is 3) during three seconds. In the second 5 the second task will come, it will be performed on the server 3, because the first two servers will be busy performing the first task.

n, q = gets.split.map(&:to_i)
server = Array.new(n, 0)
tkds = q.times.map { gets.split.map(&:to_i) }
tkds.sort_by! { |x| x[0] }
tkds.each_with_index do |tkd, i|
  t, k, d = tkd
  # if i > 0
  #   dt = t - tkds[i - 1][0]
  #   server.map! { |x| x == 0 ? 0 : x - [x, dt].min }
  # end
  if server.count { |x| x < t } < k
    puts -1
  else
    use = []
    count = 0
    ans = 0
    server.each_with_index do |x, i|
      if x < t
        server[i] = t + d - 1
        ans += i + 1
        count += 1
      end
      break if count == k
    end
    puts ans
    # use = server.each_with_index
    #   .map { |x, i| [x, i] }
    #   .select { |a| a[0] == 0 }
    #   .take(k)
    # use.each { |a| server[a[1]] = d }
    # puts use.inject(0) { |a, b| a + b[1] + 1 }
  end
end


In this problem you will have to deal with a real algorithm that is used in the VK social network.As in any other company that creates high-loaded websites, the VK developers have to deal with request statistics regularly. An important indicator reflecting the load of the site is the mean number of requests for a certain period of time of T seconds (for example, T = 60 seconds = 1 min and T = 86400 seconds = 1 day). For example, if this value drops dramatically, that shows that the site has access problem. If this value grows, that may be a reason to analyze the cause for the growth and add more servers to the website if it is really needed.However, even such a natural problem as counting the mean number of queries for some period of time can be a challenge when you process the amount of data of a huge social network. That's why the developers have to use original techniques to solve problems approximately, but more effectively at the same time.Let's consider the following formal model. We have a service that works for n seconds. We know the number of queries to this resource at at each moment of time t (1 ≤ t ≤ n). Let's formulate the following algorithm of calculating the mean with exponential decay. Let c be some real number, strictly larger than one.// setting this constant value correctly can adjust   // the time range for which statistics will be calculateddouble c = some constant value; // as the result of the algorithm's performance this variable will contain // the mean number of queries for the last // T seconds by the current moment of timedouble mean = 0.0; for t = 1..n: // at each second, we do the following:    // at is the number of queries that came at the last second;    mean = (mean + at / T) / c;Thus, the mean variable is recalculated each second using the number of queries that came at that second. We can make some mathematical calculations and prove that choosing the value of constant c correctly will make the value of mean not very different from the real mean value ax at t - T + 1 ≤ x ≤ t. The advantage of such approach is that it only uses the number of requests at the current moment of time and doesn't require storing the history of requests for a large time range. Also, it considers the recent values with the weight larger than the weight of the old ones, which helps to react to dramatic change in values quicker.However before using the new theoretical approach in industrial programming, there is an obligatory step to make, that is, to test its credibility practically on given test data sets. Your task is to compare the data obtained as a result of the work of an approximate algorithm to the real data. You are given n values at, integer T and real number c. Also, you are given m moments pj (1 ≤ j ≤ m), where we are interested in the mean value of the number of queries for the last T seconds. Implement two algorithms. The first one should calculate the required value by definition, i.e. by the formula . The second algorithm should calculate the mean value as is described above. Print both values and calculate the relative error of the second algorithm by the formula , where approx is the approximate value, obtained by the second algorithm, and real is the exact value obtained by the first algorithm.

The first line contains integer n (1 ≤ n ≤ 2·105), integer T (1 ≤ T ≤ n) and real number c (1 < c ≤ 100) — the time range when the resource should work, the length of the time range during which we need the mean number of requests and the coefficient c of the work of approximate algorithm. Number c is given with exactly six digits after the decimal point. The next line contains n integers at (1 ≤ at ≤ 106) — the number of queries to the service at each moment of time. The next line contains integer m (1 ≤ m ≤ n) — the number of moments of time when we are interested in the mean number of queries for the last T seconds. The next line contains m integers pj (T ≤ pj ≤ n), representing another moment of time for which we need statistics. Moments pj are strictly increasing.

Print m lines. The j-th line must contain three numbers real, approx and error, where:    is the real mean number of queries for the last T seconds;  approx is calculated by the given algorithm and equals mean at the moment of time t = pj (that is, after implementing the pj-th iteration of the cycle);   is the relative error of the approximate algorithm.  The numbers you printed will be compared to the correct numbers with the relative or absolute error 10 - 4. It is recommended to print the numbers with at least five digits after the decimal point.

total_time, time_slice, constant = gets.strip.split(" ")

total_time = total_time.to_i
time_slice = time_slice.to_i
constant = constant.to_f

arr_requests = gets.strip.split(" ").map(&:to_i)

results = Hash.new

mean = 0.0
j = 0
while j < time_slice-1 do
    mean = (mean + (arr_requests[j].to_f / time_slice.to_f)) / constant
    j+=1
end

arr_summ = arr_requests.slice(0,time_slice-1).inject(:+).to_f

puts
i = time_slice-1
while i < arr_requests.length do
    k = i+1

    arr_summ+=arr_requests[i]
    arr_summ -= arr_requests[i-time_slice] if i > time_slice-1

    real = arr_summ / time_slice

    mean = (mean + (arr_requests[i].to_f / time_slice.to_f)) / constant
    err = (mean - real).abs / real

    results[k] = {real: real, mean: mean, error: err}
    i+=1
end

rq = gets
requests = gets.strip.split(" ")
requests.each do |r|
    r = r.to_i
    puts sprintf("%.6f %.6f %.6f\n", results[r][:real], results[r][:mean], results[r][:error])
end

(n, t, c) = gets.scan(/[\d\.]+/).map(&:to_f)
n = n.to_i
t = t.to_i
a = gets.scan(/\d+/).map(&:to_i)
m = gets.scan(/\d+/).map(&:to_i)
a = [a] if a.is_a? Fixnum
m = [m] if a.is_a? Fixnum
p_arr = gets.scan(/\d+/).map(&:to_i)

mean = [0.0]*(n+1)
real = [0.0]*(n+1)

(n).times do |i|
  mean[i+1] = (mean[i] + a[i].to_f/t) / c
  real[i+1] = real[i] + a[i]
end
p_arr.each do |p|
  r = (real[p] - real[p-t])/t
  puts "%.6f %.6f %.6f" % [r.round(6), mean[p].round(6), ((mean[p]-r).abs/r).round(6)]
end

total_time, time_slice, constant = gets.strip.split(" ")

total_time = total_time.to_i
time_slice = time_slice.to_i
constant = constant.to_f

arr_requests = gets.strip.split(" ").map(&:to_i)

results = Hash.new

mean = 0.0
j = 0
while j < time_slice-1 do
    mean = (mean + (arr_requests[j].to_f / time_slice.to_f)) / constant
    j+=1
end

arr_summ = arr_requests.slice(0,time_slice-1).inject(:+).to_f

puts
i = time_slice-1
while i < arr_requests.length do
    k = i+1

    arr_summ+=arr_requests[i]
    arr_summ -= arr_requests[i-4] if i > 3

    real = arr_summ / time_slice

    mean = (mean + (arr_requests[i].to_f / time_slice.to_f)) / constant
    err = (mean - real).abs / real

    results[k] = {real: real, mean: mean, error: err}
    i+=1
end

rq = gets
requests = gets.strip.split(" ")
requests.each do |r|
    r = r.to_i
    puts sprintf("%.6f %.6f %.6f\n", results[r][:real], results[r][:mean], results[r][:error])
end


Petya has n positive integers a1, a2, ..., an. His friend Vasya decided to joke and replaced all digits in Petya's numbers with a letters. He used the lowercase letters of the Latin alphabet from 'a' to 'j' and replaced all digits 0 with one letter, all digits 1 with another letter and so on. For any two different digits Vasya used distinct letters from 'a' to 'j'.Your task is to restore Petya's numbers. The restored numbers should be positive integers without leading zeros. Since there can be multiple ways to do it, determine the minimum possible sum of all Petya's numbers after the restoration. It is guaranteed that before Vasya's joke all Petya's numbers did not have leading zeros.

The first line contains a single integer n (1 ≤ n ≤ 1 000) — the number of Petya's numbers. Each of the following lines contains non-empty string si consisting of lowercase Latin letters from 'a' to 'j' — the Petya's numbers after Vasya's joke. The length of each string does not exceed six characters.

Determine the minimum sum of all Petya's numbers after the restoration. The restored numbers should be positive integers without leading zeros. It is guaranteed that the correct restore (without leading zeros) exists for all given tests.

NoteIn the first example, you need to replace the letter 'a' with the digit 1, the letter 'b' with the digit 0, the letter 'd' with the digit 2, the letter 'e' with the digit 3, and the letter 'j' with the digit 4. So after the restoration numbers will look like [10, 23, 14]. The sum of them is equal to 47, which is the minimum possible sum of the numbers after the correct restoration.In the second example the numbers after the restoration can look like: [120468, 3579, 2468, 10024, 3]. In the second example the numbers after the restoration can look like: [11, 22, 11].

N = $stdin.gets.chomp.to_i

d = Hash[("a".."j").map{ |a| [a,0] }]
leadings = {}
N.times do
  digits = $stdin.gets.chomp.split("")
  digits.reverse.each_with_index { |e,i|
    if i == digits.size - 1
      leadings[e] = 1
    end
    d[e] += 10 ** i
  }
end

#p leadings
r = d.map{ |k,v| [k,v] }.sort_by{ |r| r[1] }.reverse
#p r
r.each_with_index do |e,i|
  #p [e,i]
  if !leadings.has_key?(e[0])
    f = r.delete_at(i)
    r.unshift(f)
    break
  end
end
#p r
puts r.map{ |r| r[1] }.zip((0..9).to_a).map{ |n,k| n*k }.inject(:+)


Polycarpus participates in a competition for hacking into a new secure messenger. He's almost won.Having carefully studied the interaction protocol, Polycarpus came to the conclusion that the secret key can be obtained if he properly cuts the public key of the application into two parts. The public key is a long integer which may consist of even a million digits!Polycarpus needs to find such a way to cut the public key into two nonempty parts, that the first (left) part is divisible by a as a separate number, and the second (right) part is divisible by b as a separate number. Both parts should be positive integers that have no leading zeros. Polycarpus knows values a and b.Help Polycarpus and find any suitable method to cut the public key.

The first line of the input contains the public key of the messenger — an integer without leading zeroes, its length is in range from 1 to 106 digits. The second line contains a pair of space-separated positive integers a, b (1 ≤ a, b ≤ 108).

In the first line print "YES" (without the quotes), if the method satisfying conditions above exists. In this case, next print two lines — the left and right parts after the cut. These two parts, being concatenated, must be exactly identical to the public key. The left part must be divisible by a, and the right part must be divisible by b. The two parts must be positive integers having no leading zeros. If there are several answers, print any of them. If there is no answer, print in a single line "NO" (without the quotes).

input = gets.chomp
a, b = gets.chomp.split(" ")
a = a.to_i
b = b.to_i

num = Array.new(input.length)
for i in 0...num.length
    num[i] = input[i].to_i
end

left = Array.new(num.length)
acc = 0
for i in 0...num.length
    acc = acc * 10 + num[i]
    acc %= a
    left[i] = acc
end

acc  = 0
rem = 1
ans = false
for i in (num.length-1).downto(1)
    acc = acc + num[i] * rem
    rem *= 10
    rem %= b
    acc %= b
    if num[i] != 0 && left[i-1] == 0 && acc == 0
        puts "YES"
        puts input[0...i]
        puts input[i...input.length]
        ans = true
        break
    end
end

if !ans
    puts "NO"
end

input0 = gets.chomp
key = input0.split("").map { |e| e.ord - 48 }
input = gets.chomp.split
a = Integer(input[0])
b = Integer(input[1])

l = key.length
left = Array.new(l-1)
remainder = key[0].to_i % a
left[0] = remainder

for i in 1...l-1
    remainder_b = left[i-1] * 10
    left[i] = (key[i] + remainder_b) % a
end

right = key[l-1].to_i % b

split = 0
answer = false

if right == 0 && left[l-2] == 0 && key[l-1] != 0
    split = l-2
    answer = true
else
    c = 10 % b
    d = 1
    for i in 1...l-1
        d = (c * d) % b

        remainder_b = key[l-1-i] * d
        right = (right + remainder_b) % b
        if right == 0 && left[l-i-2] == 0
            if key[l-i-1] != 0
                split = l-i-2
                answer = true
                break
            end
        end
    end
end

if !answer
    puts "NO"
else
    x = input0[0..split]
    y = input0[split+1..l-1]
    puts "YES"
    print x
    puts
    print y
end

input = gets.chomp
a, b = gets.chomp.split(" ")
a = a.to_i
b = b.to_i

num = Array.new(input.length)
for i in 0...num.length
    num[i] = input[i].to_i
end

left = Array.new(num.length)
acc = 0
for i in 0...num.length
    acc = acc * 10 + num[i]
    acc %= a
    left[i] = acc
end

acc  = 0
rem = 1
ans = false
for i in (num.length-1).downto(1)
    acc = acc + num[i] * rem
    rem *= 10
    rem %= b
    acc %= b
    if num[i] != 0 && left[i-1] == 0 && acc == 0
        puts "YES"
        puts input[0, i - 1]
        puts input[i, -1]
        ans = true
        break
    end
end

if !ans
    puts "NO"
end

key = gets.chomp.split("")
input = gets.chomp.split
a = Integer(input[0])
b = Integer(input[1])

l = key.length
left = Array.new(l-1)
remainder = key[0].to_i % a
left[0] = remainder

for i in 1...l-1
    key_i = key[i].to_i
    remainder_a = key_i % a
    remainder_b = (left[i-1] * (10 % a)) % a
    left[i] = (remainder_a + remainder_b) % a
end

right = Array.new(l-1)
remainder = key[l-1].to_i % b
right[l-2] = remainder
ten_remainder = Array.new(l-1)
c = 10 % b
d = c
ten_remainder[0] = c
for i in 1...l-1
    d = (c * d) % b
    ten_remainder[i] = d
end

for i in 1...l-1
    key_i = key[l-1-i].to_i
    number = key_i * (10**i) + right[l-i-1][0]
    remainder_a = right[l-i-1]
    remainder_b = ((key_i % b) * ten_remainder[i-1]) % b
    right[l-i-2] = (remainder_a + remainder_b) % b
end
split = 0
answer = false
for i in 0...l-1
    if left[i] == right[i] && left[i] == 0
        split = i
        answer = true
        break
    end
end

if !answer
    puts "NO"
else
    puts "YES"
    print key[0..i].join
    puts
    print key[i+1..l-1].join
end

input0 = gets.chomp
key = input0.split("").map { |e| e.ord - 48 }
input = gets.chomp.split
a = Integer(input[0])
b = Integer(input[1])

l = key.length
left = Array.new(l-1)
remainder = key[0].to_i % a
left[0] = remainder

for i in 1...l-1
    remainder_b = left[i-1] * 10
    left[i] = (key[i] + remainder_b) % a
end

right = Array.new(l-1)
remainder = key[l-1].to_i % b
right[l-2] = remainder
ten_remainder = Array.new(l-1)
c = 10 % b
d = c
ten_remainder[0] = c
for i in 1...l-1
    d = (c * d) % b
    ten_remainder[i] = d
end

for i in 1...l-1
    remainder_a = right[l-i-1]
    remainder_b = key[l-1-i] * ten_remainder[i-1]
    right[l-i-2] = (remainder_a + remainder_b) % b
end
split = 0
answer = false
x = ""
y = ""
for i in 0...l-1
    if left[i] == right[i] && left[i] == 0
        split = i
        if key[i+1] != "0"
            answer = true
            break
        end
    end
end
x = input0[0..split]
y = input0[split+1..l-1]
if !answer
    puts "NO"
else
    puts "YES"
    print x
    puts
    print y
end

key = gets.chomp.split("")
input = gets.chomp.split
a = Integer(input[0])
b = Integer(input[1])

l = key.length
left = Array.new(l-1)
remainder = key[0].to_i % a
left[0] = remainder

for i in 1...l-1
    key_i = key[i].to_i
    remainder_a = key_i % a
    remainder_b = (left[i-1] * (10 % a)) % a
    left[i] = remainder_a + remainder_b
end

right = Array.new(l-1)
remainder = key[l-1].to_i % b
right[l-2] = remainder
ten_remainder = Array.new(l-1)
c = 10 % b
d = c
ten_remainder[0] = c
for i in 1...l-1
    d = (c * d) % b
    ten_remainder[i] = d
end

for i in 1...l-1
    key_i = key[l-1-i].to_i
    number = key_i * (10**i) + right[l-i-1][0]
    remainder_a = right[l-i-1]
    remainder_b = ((key_i % b) * ten_remainder[i-1]) % b
    right[l-i-2] = (remainder_a + remainder_b) % b
end
split = 0
answer = false
for i in 0...l-1
    if left[i] == right[i] && left[i] == 0
        split = i
        answer = true
        break
    end
end

if !answer
    puts "NO"
else
    puts "YES"
    print key[0..i].join
    puts
    print key[i+1..l-1].join
end


Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor «Textpad» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck!

The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000.

Format the given text, aligning it center. Frame the whole text with characters «*» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better.

welcome to the
Codeforces
Beta
Round 5

and
good luck

strings = Array.new
maxlen = 0
while line = gets
  line.strip!
  if line.size>maxlen
    maxlen=line.size
  end
  strings << line
end
left=true
(maxlen+1).times {print "*"}
puts "*"
strings.each do |s|
  diff = maxlen-s.size
  margin=diff/2
  print "*"
  margin.times {print " "}
  if diff%2==0
    print s
  else
    print " " if !left
    print s
    print " " if left
    left=!left
  end
  margin.times {print " "}
  puts "*"
end
(maxlen+1).times {print "*"}
puts "*"

def display(s,n,flag)
  t=(n-s.length)
  h=t/2
  t=t-h
  t,h=h,t if flag
  print " "*t
  print s
  print " "*h
end
memo=[]
max=0
while line=gets
  line.chomp!
  max=line.length if max <line.length
  memo.push(line)
end
print "*"*(max+2)
puts ""
tmp=0
memo.length.times do |i|
  tmp+=1 if (max-memo[i].length)%2==1
  print "*"
  display(memo[i],max,tmp % 2 == 1)
  puts "*"
end
print "*"*(max+2)
puts ""

lines = []
while line = gets do
  lines << line.chomp
end
haba = 0
lines.each do |x|
  haba = x.size if x.size>haba
end
res = '*'*(haba+2)
res += "\r\n"
flag=true
lines.each do |x|
  thisL = '*'
  s = (haba-x.size)
  if(s%2==0||flag)
    thisL += ' '*(s/2)
    flag=false unless s%2==0
  else
    thisL += ' '*(s/2+1)
    flag=true
  end
  thisL += x.chomp
  thisL += ' '*(haba+1-thisL.size)
  res += (thisL+"*\r\n")
end
res += '*'*(haba+2)
print res+"\r\n"

lines = []
max_width = 0
while (line = gets)
	line.strip!
	max_width = line.length if line.length > max_width
	lines << line
end

top_bottom = "*" * (max_width + 2)
left = true
puts top_bottom
lines.each do |line|
	space = max_width - line.length
	left_space = left ? space / 2 : (space / 2.0).ceil
	right_space = left ? (space / 2.0).ceil : space / 2
	left = !left if space % 2 == 1
	puts "*" + " " * left_space + line + " " * right_space + "*"
end
puts top_bottom

input, max = [], 0
while g = gets; input.push g.strip; end
input.map! { |i| l = i.length; max = l if l > max; [i, l] }

puts '*' * (max + 2)

left = false

input.each do |i|
	print '*'
	m = (max - i[1])
	s =  m / 2
	if (m % 2).even?
		print ' ' * s, i[0], ' ' * s
	else
		l, r = s, s
		left ? l += 1 : r += 1
		print ' ' * l, i[0], ' ' * r
		left = !left
	end
	puts '*'
end

puts '*' * (max + 2)

def justify(str_arr)
  len_arr = str_arr.collect {|s| s.size}
  len = len_arr.max

  justify_left = true
  res = ['*' * (len+2)]
  str_arr.each do |s|
    spaces = len - s.size
    sp_left = spaces/2
    sp_right = spaces - spaces/2
    if spaces % 2 != 0 and s != ''
      if !justify_left
        sp_left += 1
        sp_right -= 1
      end
      justify_left = !justify_left
    end
    ss = ' '*sp_left + s + ' '*sp_right
    res << '*' + ss + '*'
  end
  res << '*' * (len+2)
  res
end

if __FILE__ == $0
  arr = []
  while line = gets
    arr << line.chomp
  end
  res = justify(arr)
  res.each {|s| puts s}
end

def display(s,n)
  t=(n-s.length)
  h=t/2
  (t-h).times do
    print " "
  end
  print s
  h.times do
    print " "
  end
end
memo=Array.new
max=0
while line=gets
  line.chomp!
  max=max<line.length ? line.length : max
  memo.push(line)
end
(max+2).times do |i|
  print "*"
end
puts ""
memo.length.times do |i|
  print "*"
  display(memo[i],max)
  puts "*"
end
(max+2).times do |i|
  print "*"
end
puts ""

def display(s,n)
  t=(n-s.length)
  h=t/2
  (t-h).times do
    print " "
  end
  print s
  h.times do
    print " "
  end
end
memo=Array.new
max=0
while line=gets
  line.chomp!
  max=max<line.length ? line.length : max
  memo << line
end
(max+2).times do |i|
  print "*"
end
puts ""
memo.length.times do |i|
  print "*"
  display(memo[i],max)
  puts "*"
end
(max+2).times do |i|
  print "*"
end
puts ""

lines = []
while line = gets do
  lines << line.chomp
end
haba = 0
lines.each do |x|
  haba = x.size if x.size>haba
end
res = '*'*(haba+2)
lines.each do |x|
  res +="\n"
  res += '*'
  s = (haba-x.size)/2
  res += ' '*s
  res += x.chomp
  if (haba-x.size)%2 == 0
    res += ' '*s
  else
    res += ' '*(s+1)
  end
  res +='*'
end
res += "\n"
res += '*'*(haba+2)
puts res

lines = []
while line = gets do
  lines << line.chomp
end
haba = 0
lines.each do |x|
  haba = x.size if x.size>haba
end
res = '*'*(haba+2)
lines.each do |x|
  res +="\n"
  res += '*'
  s = (haba-x.size)/2
  if (haba-x.size)%2 == 0
    res += ' '*s
  else
    res += ' '*(s+1)
  end
  res += x.chomp
  res += ' '*s
  res +='*'
end
res += "\n"
res += '*'*(haba+2)
print res

lines = []
while line = gets do
  lines << line
end
haba = 0
lines.each do |x|
  haba = x.size if x.size>haba
end
res = '*'*(haba+1)
lines.each do |x|
  res +="\n"
  res += '*'
  s = (haba-x.size)/2
  res += ' '*s
  res += x.chomp
  if (haba-x.size)%2 == 0
    res += ' '*s
  else
    res += ' '*(s+1)
  end
  res +='*'
end
res += "\n"
res += '*'*(haba+1)
print res

lines = []
while line = gets do
  lines << line.chomp
end
haba = 0
lines.each do |x|
  haba = x.size if x.size>haba
end
res = '*'*(haba+2)
res += "\r\n"
lines.each do |x|
  res += '*'
  s = (haba-x.size)/2
  res += ' '*s
  res += x.chomp
  res += ' '*(haba-x.size-s)
  res += "*\r\n"
end
res += '*'*(haba+2)
print res+"\r\n"

lines = []
while line = gets do
  lines << line.chomp
end
haba = 0
lines.each do |x|
  haba = x.size if x.size>haba
end
res = '*'*(haba+2)
lines.each do |x|
  res +="\n"
  res += '*'
  s = (haba-x.size)/2
  res += ' '*s
  res += x.chomp
  if (haba-x.size)%2 == 0
    res += ' '*s
  else
    res += ' '*(s+1)
  end
  res +='*'
end
res += "\n"
res += '*'*(haba+2)
print res

lines = []
while line = gets do
  lines << line.chomp
end
haba = 0
lines.each do |x|
  haba = x.size if x.size>haba
end
res = '*'*(haba+2)
lines.each do |x|
  res +="\n"
  res += '*'
  s = (haba-x.size)/2
  if (haba-x.size)%2 == 0
    res += ' '*s
  else
    res += ' '*(s+1)
  end
  res += x.chomp
  res += ' '*s
  res +='*'
end
res += "\n"
res += '*'*(haba+2)
puts res

lines = []
while line = gets do
  lines << line
end
haba = 0
lines.each do |x|
  haba = x.size if x.size>haba
end
res = '*'*(haba+1)
lines.each do |x|
  res +="\n"
  res += '*'
  s = (haba-x.size)/2
  res += ' '*s
  res += x.chomp
  if (haba-x.size)%2 == 0
    res += ' '*s
  else
    res += ' '*(s+1)
  end
  res +='*'
end
res += "\n"
res += '*'*(haba+1)
puts res

lines = []
while line = gets do
  lines << line.chomp
end
haba = 0
lines.each do |x|
  haba = x.size if x.size>haba
end
res = '*'*(haba+2)
lines.each do |x|
  res +="\r\n"
  res += '*'
  s = (haba-x.size)/2
  if (haba-x.size)%2 == 0
    res += ' '*s
  else
    res += ' '*(s+1)
  end
  res += x.chomp
  res += ' '*s
  res +='*'
end
res += "\r\n"
res += '*'*(haba+2)
print res+"\r\n"

input, max = STDIN.read.split("\n"), 0
input.map! { |i| l = i.length; max = l if l > max; [i, l] }

puts '*' * (max + 2)

left = false

input.each do |i|
	print '*'
	m = (max - i[1])
	s =  m / 2
	if (m % 2).even?
		print ' ' * s, i[0], ' ' * s
	else
		l, r = s, s
		left ? l += 1 : r += 1
		print ' ' * l, i[0], ' ' * r
		left = !left
	end
	puts '*'
end

puts '*' * (max + 2)


Caisa is going to have a party and he needs to buy the ingredients for a big chocolate cake. For that he is going to the biggest supermarket in town.Unfortunately, he has just s dollars for sugar. But that's not a reason to be sad, because there are n types of sugar in the supermarket, maybe he able to buy one. But that's not all. The supermarket has very unusual exchange politics: instead of cents the sellers give sweets to a buyer as a change. Of course, the number of given sweets always doesn't exceed 99, because each seller maximizes the number of dollars in the change (100 cents can be replaced with a dollar).Caisa wants to buy only one type of sugar, also he wants to maximize the number of sweets in the change. What is the maximum number of sweets he can get? Note, that Caisa doesn't want to minimize the cost of the sugar, he only wants to get maximum number of sweets as change.

The first line contains two space-separated integers n, s (1 ≤ n, s ≤ 100). The i-th of the next n lines contains two integers xi, yi (1 ≤ xi ≤ 100; 0 ≤ yi < 100), where xi represents the number of dollars and yi the number of cents needed in order to buy the i-th type of sugar.

Print a single integer representing the maximum number of sweets he can buy, or -1 if he can't buy any type of sugar.

NoteIn the first test sample Caisa can buy the fourth type of sugar, in such a case he will take 50 sweets as a change.

n, s = gets.chomp.split(" ").map { |e| e.to_i }
arr = []

n.times {
  arr << gets.chomp.split(" ").map { |e| e.to_i }
}

arr.select! { |x, y| (x.to_f + y.to_f / 100.0) <= s.to_f  }
arr.map! { |x, y|
 if y == 0
  [x, y]
 else
  [x, 100 - y]
 end
}

if arr.empty?
  puts "-1"
else
  arr.sort_by! { |x, y| -y }
  puts arr.first.last
end

#!/usr/bin/ruby2.0

n, s = STDIN.readline.split.collect {|s| s.to_i }
s *= 100
best = -1
n.times do
	d, c = STDIN.readline.split.collect {|s| s.to_i }
	change = s - (d*100 + c)
	best = [best, change%100].max if change >= 0
end
puts best

(n, s) = gets.chomp.split.map(&:to_i);
max = -1
n.times do |x|
  (x, y) = gets.chomp.split.map(&:to_i);
  if (s - x) * 100 >= y
    max = [max, (100 - y) % 100].max
  end
end
puts max;

n, s = gets.split.map(&:to_i)
max = -1
n.times do
  x, y = gets.split.map(&:to_i)
  if (s - x) * 100 >= y
    max = [max, (100 - y) % 100].max
  end
end
puts max

x = gets.split.map(&:to_i)

a = []
for i in 0...x[0]
    b = gets.split.map(&:to_i)
    a << 100 - b[1] if x[1] > b[0] and b[1] > 0
    a << 0 if x[1] >= b[0] and b[1] == 0
end

puts a.size > 0 ? a.max : -1

class Pair
  attr_accessor :first, :second

  def initialize(f, s)
    @first = f
    @second = s
  end

  def <=(y)
    return @first < y.first || (@first == y.first && @second <= y.second)
  end

  def -(y)
    if y.second == 0
      0
    else
      100 - y.second
    end
  end
end

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

a = Pair.new(s, 0)

arr = []

n.times{ arr.push(Pair.new(*gets.split.map{|c| c.to_i})) }

mx = -1

arr.each do |p|
  mx = [mx, a - p].max if p <= a
end

puts mx

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

s *= 100
res = -1
n.times do
  x, y = gets.chomp.split(' ').map(&:to_i)
  cost = 100*x + y
  #(1..(s/cost).to_i).each do |kg|
    total = cost # * kg
    if s >= total
      ost = (100-(total % 100)) % 100
      res = [res, ost].max
    end
  #end
end

puts res

#!/usr/bin/env ruby
# coding: utf-8

# $stdin = File.new('rf','r')

n, s = readline.chomp.split(' ').map(&:to_i)
x, y = [], []
n.times { |i| x[i], y[i] = *readline.chomp.split(' ').map(&:to_i) }

candies = -1
x.zip(y).each do |dollars, cents|
  next if dollars + cents.fdiv(100) > s
  candies = [candies, -cents % 100].max
end
puts candies

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

s *= 100

a = Array.new(n) do
  x, y = gets.chomp.split(' ').map(&:to_i)
  x*100 + y
end

def solve(a, s)
  a = a.select{|p| p <= s}
  return -1 if a.empty?
  a.map{|x| (s - x)%100 }.max
end

puts solve(a, s)

n,s = gets.split.map(&:to_i)
max = -1
n.times { |_|
	d,c = gets.split.map(&:to_i)
	if s * 100 >= d * 100 + c
		max = [max, (100 - c) % 100].max
	end
}
puts max

n, s = gets.split.map(&:to_i)
ans = -1
n.times do
  x, y = gets.split.map(&:to_i)
  next if s < x || (s == x && y > 0)
  c = (100 - y) % 100
  ans = [ans, c].max
end
puts ans

n, s = gets.split.map(&:to_i)
sweets = 0
can_buy = false
n.times do
  x, y = gets.split.map(&:to_i)
  x += 1 if y > 0
  sweets = 100 - y if s >= x && 100 - y > sweets && y != 0
  can_buy = true if s >= x
end
puts can_buy ? sweets : -1

def read_next_line
  gets.chomp.split.map(&:to_i)
end

n, s = read_next_line
puts (0...n).map { |_| read_next_line }.select { |a| a[0] < s || a[0] == s && a[1] == 0 }.map { |a| (100 - a[1]) % 100 }.max || -1

line = gets
i, s = line.split.map(&:to_i)
min_nu = 10 ** 9
zero_found = false
i.times do
	line = gets.split
	linetmp = "#{line[0]}.#{line[1]}".to_f
	next if linetmp > s
	num = line[1].to_i
	min_nu = num if num < min_nu && num != 0
	zero_found = true if num == 0
end
if min_nu == 10 ** 9 and zero_found
	puts "0"
elsif min_nu == 10 ** 9
	puts "-1"
else
	puts 100 - min_nu
end

n, s = gets.chomp.split(" ").map { |e| e.to_i }
arr = []

n.times {
  arr << gets.chomp.split(" ").map { |e| e.to_i }
}

arr.select! { |x, y| (x.to_f + y.to_f / 100.0) <= s.to_f  }
arr.select! { |x, y| y != 0 }

if arr.empty?
  puts "-1"
else
  arr.sort_by! { |x, y| y }
  puts 100 - arr.first.last
end

(n, s) = gets.chomp.split.map(&:to_i);
max = -1
(1..n).each do |x|
  (x, y) = gets.chomp.split.map(&:to_i);
  if (x > s || (x == s && y != 0) || y == 0) then
    next;
  end
  max = [max, 100 - y].max;
end
puts max;

x = gets.split.map(&:to_i)

a = []
for i in 0...x[0]
    b = gets.split.map(&:to_i)
    a << 100 - b[1] if x[1] > b[0]
end

puts a.size > 0 ? a.max : -1

x = gets.split.map(&:to_i)

a = []
for i in 0...x[0]
    b = gets.split.map(&:to_i)
    a << 100 - b[1] if x[1] > b[0] and b[1] > 0
end

puts a.size > 0 ? a.max : -1

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

res = -1
n.times do
  x, y = gets.chomp.split(' ').map(&:to_i)
  cost = x + 0.01 * y
  (1..(s/cost).to_i).each do |kg|
    total = cost * kg
    if s >= total && y > 0
      res = [res, 100-y].max
    end
  end
end

puts res

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

res = -1
n.times do
  x, y = gets.chomp.split(' ').map(&:to_i)
  cost = x + 0.01 * y
  (1..(s/cost).to_i).each do |kg|
    total = cost * kg
    total_y = (y * kg) % 100
    if s >= total && total_y > 0
      res = [res, 100-total_y].max
    end
  end
end

puts res

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

s *= 100
res = -1
n.times do
  x, y = gets.chomp.split(' ').map(&:to_i)
  cost = 100*x + y
  (1..(s/cost).to_i).each do |kg|
    total = cost * kg
    if s >= total
      ost = total % 100 > 0 ? 100-(total % 100) : 0
      res = [res, ost].max
    end
  end
end

puts res

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

s *= 100
res = -1
n.times do
  x, y = gets.chomp.split(' ').map(&:to_i)
  cost = 100*x + y
  (1..(s/cost).to_i).each do |kg|
    total = cost * kg
    if s >= total && total % 100 > 0
      res = [res, 100-(total % 100)].max
    end
  end
end

puts res

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

res = -1
n.times do
  x, y = gets.chomp.split(' ').map(&:to_i)
  cost = x + 0.01 * y
  if s >= cost && y > 0
    res = [res, 100-y].max
  end
end

puts res

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

s *= 100
res = -1
n.times do
  x, y = gets.chomp.split(' ').map(&:to_i)
  cost = 100*x + y
  (1..(s/cost).to_i).each do |kg|
    total = cost * kg
    if s >= total
      #ost = total % 100 > 0 ? 100-(total % 100) : 0
      ost = (100-(total % 100)) % 100
      res = [res, ost].max
    end
  end
end

puts res

n, s = gets.split.map(&:to_i)
sweets = 0
can_buy = false
n.times do
  x, y = gets.split.map(&:to_i)
  sweets = 100 - y if s >= x && 100 - y > sweets && y != 0
  can_buy = true if s >= x
end
puts can_buy ? sweets : -1

n, s = gets.split.map(&:to_i)
sweets = -1
n.times do
  x, y = gets.split.map(&:to_i)
  next if s < x || (s == x && y > 0)
  sweets = 100 - y if 100 - y > sweets && y != 0
end
puts sweets

n, s = gets.split.map(&:to_i)
sweets = 0
n.times do
  x, y = gets.split.map(&:to_i)
  sweets = 100 - y if x < s && 100 - y > sweets && y != 0
end
puts sweets == 0 ? -1 : sweets

n, s = gets.split.map(&:to_i)
sweets = 0
can_buy = false
n.times do
  x, y = gets.split.map(&:to_i)
  sweets = 100 - y if s > x && 100 - y > sweets && y != 0
  can_buy = true if s > x
end
puts can_buy ? sweets : -1

line = gets
i, s = line.split.map(&:to_i)
min_nu = 10 ** 9
zero_found = false
i.times do
	line = gets.split
	linetmp = "#{line[0]}.#{line[1]}".to_f
	next if linetmp > s
	num = line[1].to_i
	min_nu = num if num < min_nu && num != 0
	zero_found = true if num == 0
end
if min_nu == 10 ** 9 and zero_found
	puts "0"
elsif min_nu == 10 ** 9
	puts "-1"
else
	puts min_nu
end

line = gets
i, s = line.split.map(&:to_i)
min_nu = -1
i.times do
	line = gets.split
	line = "#{line[0]}.#{line[1]}".to_f
	next if line > s
	num = s - line
	num = ("0." + num.to_s.split(".")[1]).to_f
	# puts num
	min_nu = num if num > min_nu && num >= 0
end
if min_nu != -1
	min_nu = min_nu.to_s.gsub!(/0\./, "")
	min_nu += "0" if min_nu.size  == 1 && min_nu != "0"
end
puts min_nu

line = gets
i, s = line.split.map(&:to_i)
min_nu = -1
i.times do
	line = gets.split
	line = "#{line[0]}.#{line[1]}".to_f
	next if line > s
	num = s - line
	num = ("0." + num.to_s.split(".")[1]).to_f
	# puts num
	min_nu = num if num > min_nu && num > 0
end
if min_nu != -1
	min_nu = min_nu.to_s.gsub!(/0\./, "")
	min_nu += "0" if min_nu.size  == 1
end
puts min_nu


First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word — some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction —  it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: , where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.

The only line contains a string s (5 ≤ |s| ≤ 104) consisting of lowercase English letters.

On the first line print integer k — a number of distinct possible suffixes. On the next k lines print suffixes.  Print suffixes in lexicographical (alphabetical) order.

NoteThe first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.

require 'set'

word = gets.chomp[5..-1].reverse

suffixes = Set.new
poss2 = Array.new(word.length, false)
poss3 = Array.new(word.length, false)

poss2[0], poss3[0] = true, true

(word.length).times { |x|
  if (poss3[x-3]) or (poss2[x-2] and (word[x-2..x-1] != word[x..x+1]))
    if word[x+1] != nil
      #suffixes.add (word[x+1]||''+word[x]||'')
      poss2[x] = true
    end
  end

  if (poss2[x-2]) or (poss3[x-3] and (word[x-3..x-1] != word[x..x+2]))
    if word[x+2] != nil
      #suffixes.add(word[x+2]||''+word[x+1]||''+word[x]||'')
      poss3[x] = true
    end
  end
}

(word.length-1).times { |x| suffixes.add word[x..x+1].reverse if poss2[x] }
(word.length-2).times { |x| suffixes.add word[x..x+2].reverse if poss3[x] }

suffixes = suffixes.to_a.sort

#puts word
#poss2.each {|e| print e; print ' '}; puts
#poss3.each {|e| print e; print ' '}; puts

puts suffixes.length
puts suffixes if suffixes.length>0

require 'set'

word = gets.chomp[5..-1].reverse

suffixes = Set.new
poss2 = Array.new(word.length, false)
poss3 = Array.new(word.length, false)

poss2[0], poss3[0] = true, true

(word.length).times { |x|
  if (poss3[x-3]) or (poss2[x-2] and (word[x-2]||''+word[x-1]||'' != word[x]||''+word[x+1]||''))
    if word[x+1] != nil
      #suffixes.add (word[x+1]||''+word[x]||'')
      poss2[x] = true
    end
  end

  if (poss2[x-2]) or (poss3[x-3] and (word[x-3]||''+word[x-2]||''+word[x-1]||'' != word[x]||''+word[x+1]||''+word[x+2]||''))
    if word[x+2] != nil
      #suffixes.add(word[x+2]||''+word[x+1]||''+word[x]||'')
      poss3[x] = true
    end
  end
}

(word.length-1).times { |x| suffixes.add word[x..x+1].reverse if poss2[x] }
(word.length-2).times { |x| suffixes.add word[x..x+2].reverse if poss3[x] }

suffixes = suffixes.to_a.sort

#puts word
#poss2.each {|e| print e; print ' '}; puts
#poss3.each {|e| print e; print ' '}; puts

puts suffixes.length
puts suffixes


Polycarp wrote on the board a string $$$s$$$ containing only lowercase Latin letters ('a'-'z'). This string is known for you and given in the input.After that, he erased some letters from the string $$$s$$$, and he rewrote the remaining letters in any order. As a result, he got some new string $$$t$$$. You have to find it with some additional information.Suppose that the string $$$t$$$ has length $$$m$$$ and the characters are numbered from left to right from $$$1$$$ to $$$m$$$. You are given a sequence of $$$m$$$ integers: $$$b_1, b_2, \ldots, b_m$$$, where $$$b_i$$$ is the sum of the distances $$$|i-j|$$$ from the index $$$i$$$ to all such indices $$$j$$$ that $$$t_j > t_i$$$ (consider that 'a'<'b'<...<'z'). In other words, to calculate $$$b_i$$$, Polycarp finds all such indices $$$j$$$ that the index $$$j$$$ contains a letter that is later in the alphabet than $$$t_i$$$ and sums all the values $$$|i-j|$$$.For example, if $$$t$$$ = "abzb", then:  since $$$t_1$$$='a', all other indices contain letters which are later in the alphabet, that is: $$$b_1=|1-2|+|1-3|+|1-4|=1+2+3=6$$$;  since $$$t_2$$$='b', only the index $$$j=3$$$ contains the letter, which is later in the alphabet, that is: $$$b_2=|2-3|=1$$$;  since $$$t_3$$$='z', then there are no indexes $$$j$$$ such that $$$t_j>t_i$$$, thus $$$b_3=0$$$;  since $$$t_4$$$='b', only the index $$$j=3$$$ contains the letter, which is later in the alphabet, that is: $$$b_4=|4-3|=1$$$. Thus, if $$$t$$$ = "abzb", then $$$b=[6,1,0,1]$$$.Given the string $$$s$$$ and the array $$$b$$$, find any possible string $$$t$$$ for which the following two requirements are fulfilled simultaneously:  $$$t$$$ is obtained from $$$s$$$ by erasing some letters (possibly zero) and then writing the rest in any order;  the array, constructed from the string $$$t$$$ according to the rules above, equals to the array $$$b$$$ specified in the input data.

The first line contains an integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. Each test case consists of three lines:   the first line contains string $$$s$$$, which has a length from $$$1$$$ to $$$50$$$ and consists of lowercase English letters;  the second line contains positive integer $$$m$$$ ($$$1 \le m \le |s|$$$), where $$$|s|$$$ is the length of the string $$$s$$$, and $$$m$$$ is the length of the array $$$b$$$;  the third line contains the integers $$$b_1, b_2, \dots, b_m$$$ ($$$0 \le b_i \le 1225$$$).  It is guaranteed that in each test case an answer exists.

Output $$$q$$$ lines: the $$$k$$$-th of them should contain the answer (string $$$t$$$) to the $$$k$$$-th test case. It is guaranteed that an answer to each test case exists. If there are several answers, output any.

NoteIn the first test case, such strings $$$t$$$ are suitable: "aac', "aab".In the second test case, such trings $$$t$$$ are suitable: "a", "b", "c".In the third test case, only the string $$$t$$$ equals to "aba" is suitable, but the character 'b' can be from the second or third position.

gets.to_i.times do
	s = gets.chomp
	m = gets.to_i
	a = gets.split.map(&:to_i)
	cnt = s.chars.tally.to_a.sort.reverse
	ans = '?' * m

	while a.count(-1) < m
		zero = (0...m).select { a[_1] == 0 }
		cnt.shift while cnt[0][1] < zero.size
		zero.each do |i|
			ans[i] = cnt[0][0]
			(0...m).each { |j| a[j] -= (i - j).abs if a[j] > 0 }
			a[i] = -1
		end
		cnt.shift
	end

	puts ans
end


Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite — cookies. Ichihime decides to attend the contest. Now she is solving the following problem. You are given four positive integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$, such that $$$a \leq b \leq c \leq d$$$. Your task is to find three integers $$$x$$$, $$$y$$$, $$$z$$$, satisfying the following conditions: $$$a \leq x \leq b$$$. $$$b \leq y \leq c$$$. $$$c \leq z \leq d$$$. There exists a triangle with a positive non-zero area and the lengths of its three sides are $$$x$$$, $$$y$$$, and $$$z$$$.Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her?

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$)  — the number of test cases. The next $$$t$$$ lines describe test cases. Each test case is given as four space-separated integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$1 \leq a \leq b \leq c \leq d \leq 10^9$$$).

For each test case, print three integers $$$x$$$, $$$y$$$, $$$z$$$  — the integers you found satisfying the conditions given in the statement. It is guaranteed that the answer always exists. If there are multiple answers, print any.

NoteOne of the possible solutions to the first test case:One of the possible solutions to the second test case:

def valid?(a,b,c)
  # puts "#{a} #{b} #{c} -> #{((a+b)>c) && ((a+c)>b) && ((b+c)>a)}"
  ((a+b)>c) && ((a+c)>b) && ((b+c)>a)
end

t = gets.chomp.to_i
t.times do
  a, b, c, d =  gets.chomp.split.map(&:to_i)

  if(a>b)
    x=a
  else
    x=b
  end

  if(b>c)
    y=b
  else
    y=c
  end

  if(c<d)
    z=c
  else
    z=d
  end
  puts "#{x} #{y} #{z}"
end

t = gets.chomp.to_i

until t==0
    t-=1
    x = gets.split.map(&:to_i)
    puts("#{x[1]} #{x[2]} #{x[2]}")
end

file = File.exist?('in.in') ? File.new('in.in','r') : STDIN

t = file.gets.to_i

while t != 0
  a,b,c,d = file.gets.split.map(&:to_i)
  puts "#{b} #{c} #{c}"
  t -= 1
end

t = gets.chomp.to_i
t.times do |testcase|
  (a,b,c,d) = gets.split.map(&:to_i)
  print "#{b} #{c} "
  print [b+c-1 , d].min ; print "\n"
end

t = gets.to_i
t.times do
    a, b, c, d = gets.strip.split.map(&:to_i)
    puts "#{b} #{c} #{c}"
end

gets.to_i.times {
  a, b, c, d = gets.split.map { |v| v.to_i }
  puts "%d %d %d" % [a, c, c]
}

1.upto(gets.chomp.to_i) do
  a,b,c,d = gets.chomp.split.map(&:to_i)
  puts [b,c,c].join(' ')
end

t = gets.to_i
t.times do
  a, b, c, d = gets.split.map(&:to_i)
  x = a
  y = c
  z = c
  puts "#{x} #{y} #{z}"
end

1.upto(gets.to_i) do
  a, b, c, d = gets.split(' ').map(&:to_i)

  puts "#{b} #{c} #{[d, b + c - 1].min}"
end

(1).upto(gets.to_i) do
  a=gets.split(' ')
  puts a[1]+" "+a[2]+" "+a[2]
end

t=gets.to_i
(1).upto(t) do
  a = gets.split(' ')
  puts "#{a[1]} #{a[2]} #{a[2]}"
end

t = gets.chomp.to_i
t.times do
  a, b, c, d =  gets.chomp.split.map(&:to_i)

  puts "#{b} #{b} #{b}"
end

t = gets.chomp.to_i
t.times do
  a, b, c, d =  gets.chomp.split.map(&:to_i)

  puts "#{a} #{a} #{a}"
end

t = gets.chomp.to_i
t.times do
  a, b, c, d =  gets.chomp.split.map(&:to_i)
  puts "#{a} #{b} #{d}"
end

file = File.exist?('in.in') ? File.new('in.in','r') : STDIN

t = file.gets.to_i

while t != 0
  a,b,c,d = file.gets.split.map(&:to_i)

  puts "#{a} #{b} #{c}"
  t -= 1
end

file = File.exist?('in.in') ? File.new('in.in','r') : STDIN

t = file.gets.to_i

while t != 0
  a,b,c,d = file.gets.split.map(&:to_i)

  puts "#{b} #{c} #{d}"
  t -= 1
end

t = gets.chomp.to_i
t.times do |testcase|
  (a,b,c,d) = gets.split.map(&:to_i)
  puts "#{a} #{b} #{c}"
end

t = gets.chomp.to_i
t.times do |testcase|
  (a,b,c,d) = gets.split.map(&:to_i)
  puts "#{b} #{c} #{d}"
end

t = gets.chomp.to_i
t.times do |testcase|
  (a,b,c,d) = gets.split.map(&:to_i)
  print "#{b} #{c} "
  print b+c-1 ; print "\n"
end


A boy Bob likes to draw. Not long ago he bought a rectangular graph (checked) sheet with n rows and m columns. Bob shaded some of the squares on the sheet. Having seen his masterpiece, he decided to share it with his elder brother, who lives in Flatland. Now Bob has to send his picture by post, but because of the world economic crisis and high oil prices, he wants to send his creation, but to spend as little money as possible. For each sent square of paper (no matter whether it is shaded or not) Bob has to pay 3.14 burles. Please, help Bob cut out of his masterpiece a rectangle of the minimum cost, that will contain all the shaded squares. The rectangle's sides should be parallel to the sheet's sides.

The first line of the input data contains numbers n and m (1 ≤ n, m ≤ 50), n — amount of lines, and m — amount of columns on Bob's sheet. The following n lines contain m characters each. Character «.» stands for a non-shaded square on the sheet, and «*» — for a shaded square. It is guaranteed that Bob has shaded at least one square.

Output the required rectangle of the minimum cost. Study the output data in the sample tests to understand the output format better.

st = gets.split
n = st[0].to_i
m = st[1].to_i

str = []
maxn = -1
minn = 51
maxm = -1
minm = 51
n.times do |i|
    str << gets.chomp
    if k = str[i].index("*")
                q = str[i].rindex("*")
        if q > maxm then
            maxm = q
        end
        if k < minm then
            minm = k
        end
        if i < minn then
            minn = i
        end
        if i > maxn then
            maxn = i
        end
    end
end

result = []
n.times do |i|
    if i >= minn && i <= maxn then
        a = str[i][minm..maxm]
        result << a
    end
end

result.size.times do |i|
    puts result[i]
end

ns,ms = gets.chomp.split(/ /)
n = ns.to_i
m = ms.to_i
ar = Array.new(n)
for i in 0..n-1
	ar[i] = gets.chomp
end

x1 = m-1
x2 = 0
y1 = -1
y2 = -1
for i in 0..n-1
	wx1 = ar[i].index("*")
	x1 = [x1, wx1].min if wx1 != nil
	wx2 = ar[i].rindex("*")
	x2 = [x2, wx2].max if wx2 != nil
	if wx1 != nil && y1 == -1
		y1 = i
	end
	y2 = i if wx1 != nil
end
for i in y1..y2
	puts ar[i].slice(x1..x2)
end

input=gets.split.map(&:to_i)
map=[]
for i in 0..input[0]-1
        map.push(gets.split[0])
end
sx=0
str=""
for i in 0..input[1]-1
        str+="."
end
for i in 0..input[0]-1
        if map[i]==str then
                sx=i+1
        else
                break
        end
end
ex=input[0]-1
(input[0]-1).downto(0){|i|
        if map[i]==str then
                ex=i-1
        else
                break
        end
}

sy=0
ey=input[1]-1
for i in 0..input[1]-1
        ok=1
        for j in 0..input[0]-1
                if map[j][i]=="*" then
                        ok=false
                        break
                end
        end
        if ok then
                sy=i+1
        else
                break
        end
end

(input[1]-1).downto(0){|i|
        ok=1
        for j in 0..input[0]-1
                if map[j][i]=="*" then
                        ok=false
                        break
                end
        end
        if ok then
                ey=i-1
        else
                break
        end
}

sx.upto(ex){|i|
        puts map[i][sy..ey]
}

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

g,f,l,b=[],[0,m-1],[0,0],false

n.times{|i|

  g<<gets.chomp!

  if c=/[*]/=~g[i] then

    if(!b) then

      f[0]=i

      b=true

    end

    if c<f[1] then f[1]=c end

  end

  if c=/[*][.]*$/=~g[i] then

    l[0]=i

    if c>l[1] then l[1]=c end

  end

}

g[f[0]..l[0]].each{|s|puts s[f[1]..l[1]]}

height,width = gets.split.map(&:to_i)
data = Array.new
range = Array.new(4,0)
range[0] = height
range[1] = width
height.times do |h|
  data[h] = gets.chomp
  width.times do |w|
    if(data[h][w,1] == "*") then
      if h < range[0] then range[0] = h end
      if h > range[2] then range[2] = h end
      if w < range[1] then range[1] = w end
      if w > range[3] then range[3] = w end
    end
  end
end
#p range
for h in range[0]..range[2] do
  puts data[h][range[1]..range[3]]
end

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

t, d = -1, -1
l, r = m + 1, -1
a.size.times do |i|
    pos = a[i] =~ /\*/
    pos = m if pos == nil

    l = [l, pos].min

    if pos < m
        t = i if t == -1
        d = i
    end

    rpos = a[i] =~ /\.+\z/
    rpos = m if rpos == nil
    r = [r, rpos].max
end

a = a[t..d].map { |s| s[l...r] }
puts a * "\n"

s = gets.split(" ").map { |e| e.to_i }
str = Array.new(0)
for i in 0..s[0]-1 do
     str.push(gets)
end
xcord = Array.new(0)
ycord = Array.new(0)
for i in 0..s[0]-1 do
    k = str[i].count("*")
    if k > 0 then
        xcord.push(i)
    end
    for j in 0..s[1]-1 do
        if str[i][j] == '*' then
            ycord.push(j)
        end
    end
end

for i in xcord.min..xcord.max do
    for j in ycord.min..ycord.max do
        print str[i][j]
    end
    puts
end

require 'set'

n, m = gets.chomp!.split.map(&:to_i)
grid = []
indexes = []
n.times do |index|
	row = gets.chomp!
	grid << row
	indexes << index if (re = /[*]/) =~ row
end

width = Set.new
row_start, row_end = indexes.min, indexes.max
m.times do |col|
	(row_start..row_end).each do |row|
		(width << col and break) if grid[row][col] == "*"
	end
end

start_index, end_index = width.min, width.max
(row_start..row_end).each do |row|
	puts grid[row][start_index..end_index]
end

n,m = gets.split.map(&:to_i)
mat = []
n.times{mat = mat << gets }
x,a,y,b= m,n,0,0
for i in 0...n
  a = i if mat[i].count('.') != m && i < a ;b = i if mat[i].count('.') != m && i > b
end
for i in 0...m do
  cnt = 0
  for j in 0...n do
    cnt += 1 if mat[j][i,1] == '.'
  end
  x = i if cnt != n && x > i ;y = i if cnt != n && y < i
end
for i in a..b do
  puts mat[i][x..y]
end

n,m = gets.split.map{|str| str.to_i}
flats = []
n.times{
    flats = flats << gets
}

x1,y1,x2,y2= m,n,0,0
#puts flats[0]
for i in 0...n
    y1 = i if flats[i].count('.') != m && i < y1
    y2 = i if flats[i].count(".") != m && i > y2
end

for i in 0...m do
    cnt = 0
    for j in 0...n do
        cnt += 1 if flats[j][i,1] == '.'
    end
    x1 = i if cnt != n && x1 > i
    x2 = i if cnt != n && x2 < i
end
#puts "#{y1},#{y2},#{x1},#{x2}"
for i in y1..y2 do
    puts flats[i][x1..x2]
end

n, m = gets.split.collect{|i| i.to_i}
s = Array.new(n)
n.times{|i| s[i] = gets.chomp }
up, low, left, right = 0, n-1, m-1, m-1
(0...n).each do |i|
    if s[i].include?("*")
        up = i
        break
    end
end
(n-1).downto(0).each do |i|
    if s[i].include?("*")
        low = i
        break
    end
end
(0...n).each do |i|
    if s[i].index("*") and s[i].index("*")<left
        left = s[i].index("*")
    end
end
(0...n).each do |i|
    if s[i].index("*") and s[i].reverse.index("*")<right
        right = s[i].reverse.index("*")
    end
end
right = m-right
(up..low).each do |i|
    puts s[i][left...right]
end

n, m = gets.split.collect{|i| i.to_i}
s = Array.new(n)
n.times{|i| s[i] = gets.chomp}
up, low, left, right = 0, n-1, m-1, m-1
(0...n).each do |i|
    if s[i].include?("*")
        up = i
        break
    end
end
(n-1).downto(0).each do |i|
    if s[i].include?("*")
        low = i
        break
    end
end
(0...n).each{|i| left = s[i].index("*") if s[i].index("*") and s[i].index("*")<left}
(0...n).each{|i| right = s[i].reverse.index("*") if s[i].index("*") and s[i].reverse.index("*")<right}
right = m-right
(up..low).each{|i| puts s[i][left...right]}

def find_ast_range sheet
	s=0
	loop{
		break if sheet[s]=~/\*/
		s+=1
	}
	t=sheet.size-1
	loop{
		break if sheet[t]=~/\*/
		t-=1
	}
	s..t
end

n,m=gets.split.map{|str|str.to_i}
sheet=[]
temp=[]
n.times{
	str=gets.chomp!
	sheet<<str
	temp<<str.split(//)
}
sheet_t=temp.transpose.map{|strs|strs*""}

n_range=find_ast_range sheet
m_range=find_ast_range sheet_t
sheet[n_range].each{|str|puts str[m_range]}

def find_ast_range sheet
	s=0
	loop{
		break if sheet[s]=~/\*/
		s+=1
	}
	t=sheet.size-1
	loop{
		break if sheet[t]=~/\*/
		t-=1
	}
	s..t
end

n,m=gets.split.map(&:to_i)
sheet=[]
temp=[]
n.times{
	str=gets.chomp!
	sheet<<str
	temp<<str.split(//)
}
sheet_t=temp.transpose.map{|strs|strs*""}

n_range=find_ast_range sheet
m_range=find_ast_range sheet_t
sheet[n_range].each{|str|puts str[m_range]}

input = STDIN.read.split("\n"); input.shift

x, y = [], []
input.each.with_index {|v, i| y.push i if v =~ /[*]/ }

input[0].length.times do |i|
	input.each do |v|
		if v[i] == '*'
			x.push i
			break
		end
	end
end

x, y = (x.first..x.last), (y.first..y.last)

y.each {|i| puts input[i][x]}

n, m = gets.split.collect{|i| i.to_i}
s = Array.new(n)
n.times{|i| s[i] = gets.chomp }
up, low, left, right = 0, n-1, 0, m-1
(0...n).each do |i|
    if s[i].include?("*")
        up = i
        break
    end
end
(n-1).downto(0).each do |i|
    if s[i].include?("*")
        low = i
        break
    end
end
(0...n).each do |i|
    if s[i].index("*") and s[i].index("*")<left
        left = s[i].index("*")
    end
end
(0...n).each do |i|
    if s[i].index("*") and s[i].reverse.index("*")<right
        right = s[i].reverse.index("*")
    end
end
right = m-right
(up..low).each do |i|
    puts s[i][left...right]
end

n, m = gets.split.collect{|i| i.to_i}
s = Array.new(n)
n.times{|i| s[i] = gets.chomp }
up, low, left, right = 0, n-1, 0, m-1
(0...n).each do |i|
    if s[i].include?("*")
        up = i
        break
    end
end
(n-1).downto(0).each do |i|
    if s[i].include?("*")
        low = i
        break
    end
end
(0...n).each do |i|
    if s[i].index("*") and s[i].index("*")>left
        left = s[i].index("*")
    end
end
(0...n).each do |i|
    if s[i].index("*") and s[i].reverse.index("*")<right
        right = s[i].reverse.index("*")
    end
end
right = m-right
(up..low).each do |i|
    puts s[i][left...right]
end

input = STDIN.read.split("\n"); input.shift
input -= ["." * input[0].length]

input.map! {|i| i.split('')}
input = input.transpose

input.map! {|i| i.join('')}
input -= ["." * input[0].length]

input.map! {|i| i.split('')}
input = input.transpose

input.each {|i| puts i.join}


Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has $$$a$$$ coins, Barbara has $$$b$$$ coins and Cerene has $$$c$$$ coins. Recently Polycarp has returned from the trip around the world and brought $$$n$$$ coins.He wants to distribute all these $$$n$$$ coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives $$$A$$$ coins to Alice, $$$B$$$ coins to Barbara and $$$C$$$ coins to Cerene ($$$A+B+C=n$$$), then $$$a + A = b + B = c + C$$$.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all $$$n$$$ coins between sisters in a way described above.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. Each test case is given on a new line and consists of four space-separated integers $$$a, b, c$$$ and $$$n$$$ ($$$1 \le a, b, c, n \le 10^8$$$) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.

For each test case, print "YES" if Polycarp can distribute all $$$n$$$ coins between his sisters and "NO" otherwise.

def solve
	a, b, c, n = gets.split.map(&:to_i)
	sum = a+b+c+n
	return "NO" if sum % 3 != 0
	avg = sum / 3

	return "NO" if [a, b, c].max > avg
	return "YES"
end

gets.to_i.times do
	puts solve
end

T = gets.to_i

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

  max = [a, b, c].max

  [a, b, c].each do |v|
    n -= max - v
  end

  if n >= 0 && n % 3 == 0
    puts 'YES'
  else
    puts 'NO'
  end
end

gets.to_i.times {
  a, b, c, n = gets.split.map { |v| v.to_i }
  total = a + b + c + n

  if (a >= b) and (a >= c)
    m = a
  elsif (b >= a) and (b >= c)
    m = b
  else
    m = c
  end

  d = 3 * m - a - b - c
  if (total % 3 == 0) and (n >= d)
    puts "YES"
  else
    puts "NO"
  end
}

# coding: utf-8

# if __FILE__ == $0
# end

sets = gets.to_i
sets.times {
    a, b, c, n = gets.split.map(&:to_i)
    pick_max = [a, b, c].max
    fillups = (pick_max - a) + (pick_max - b) + (pick_max - c)
    remains = n - fillups

    if remains >= 0
        puts "YES" if remains % 3 == 0
        puts "NO" if remains % 3 != 0
    else
        puts "NO"
    end
}

def getline
    return gets.split.map(&:to_i)
end
t=gets.to_i
t.times do |i|
    a, b, c, n = getline()
    s = [a,b,c].sort!
    a, b, c = s[2], s[1], s[0]
    d = a-b+a-c
    if d <= n and (n-d) % 3 == 0 then
        print "YES\n"
    else
        print "NO\n"
    end
end

t = gets.to_i

1.upto(t) do
  a, b, c, n = gets.split(' ').map(&:to_i)

  eql = [a, b, c].inject(0) { |sum, x| sum + [a, b, c].max - x }

  puts (n - eql).modulo(3).zero? && (n >= eql) ? 'YES' : 'NO'
end

T = gets.to_i

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

  max = [a, b, c].max

  [a, b, c].each do |v|
    n -= max - v
  end

  if n % 3 == 0
    puts 'YES'
  else
    puts 'NO'
  end
end

gets.to_i.times {
  a, b, c, n = gets.split.map { |v| v.to_i }
  total = a + b + c + n
  if a > b and a > c
    m = a
  elsif b > a and b > c
    m = b
  else
    m = c
  end
  d = 3 * m - a - b - c
  if total % 3 == 0 and n >= d
    puts "YES"
  else
    puts "NO"
  end
}

# coding: utf-8

# if __FILE__ == $0
# end

sets = gets.to_i
sets.times {
    a, b, c, n = gets.split.map(&:to_i)
    pick_max = [a, b, c].max
    fillups = (pick_max - a) + (pick_max - b) + (pick_max - c)
    remains = n - fillups

    puts "YES" if remains % 3 == 0
    puts "NO" if remains % 3 != 0
}

t = gets.to_i

1.upto(t) do
  a, b, c, n = gets.split(' ').map(&:to_i)

  puts (n - [a, b, c].inject(0) { |sum, x| sum + [a, b, c].max - x }).modulo(3).zero? ? 'YES' : 'NO'
end


You have integer $$$n$$$. Calculate how many ways are there to fully cover belt-like area of $$$4n-2$$$ triangles with diamond shapes. Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it. $$$2$$$ coverings are different if some $$$2$$$ triangles are covered by the same diamond shape in one of them and by different diamond shapes in the other one.Please look at pictures below for better understanding.  On the left you can see the diamond shape you will use, and on the right you can see the area you want to fill. These are the figures of the area you want to fill for $$$n = 1, 2, 3, 4$$$. You have to answer $$$t$$$ independent test cases.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^{4}$$$) — the number of test cases. Each of the next $$$t$$$ lines contains a single integer $$$n$$$ ($$$1 \le n \le 10^{9}$$$).

For each test case, print the number of ways to fully cover belt-like area of $$$4n-2$$$ triangles using diamond shape. It can be shown that under given constraints this number of ways doesn't exceed $$$10^{18}$$$.

NoteIn the first test case, there are the following $$$2$$$ ways to fill the area:  In the second test case, there is a unique way to fill the area:

t=gets.to_i
for i in 1..t do
	n=gets.to_i
	puts n
end

# coding: utf-8

# 색의 개수가 아니라 1의 크기를 가진 다이아몬드로,
# 현재 n 길이의 도형(문제의 이미지를 참고)를 메꿀 수 있느냐를 묻는 문제
# 그 경우의 수! (partitioning, not coloring)

t = gets.to_i
t.times {
    n = gets.to_i
    puts n
}

1.upto(gets.chomp.to_i) do |tt|
  n = gets.chomp.to_i
  puts n
end

n = gets.to_i

n.times do
  t = gets.to_i
  puts t
end

t = gets.to_i
t.times do
  n = gets.to_i
  puts n
end

n = gets.chomp.to_i

for i in (0...n)
  puts gets.chomp
end

t = gets.to_i
t.times do
  n = gets.to_i
  puts (n >= 2) ? 2 : 1
end

1.upto(gets.to_i) do
  puts gets.to_i > 1 ? 2 : 1
end


You are given an array $$$a$$$ of length $$$n$$$, and an integer $$$x$$$. You can perform the following operation as many times as you would like (possibly zero): replace two adjacent elements of the array by their sum. For example, if the initial array was $$$[3, 6, 9]$$$, in a single operation one can replace the last two elements by their sum, yielding an array $$$[3, 15]$$$, or replace the first two elements to get an array $$$[9, 9]$$$. Note that the size of the array decreases after each operation.The beauty of an array $$$b=[b_1, \ldots, b_k]$$$ is defined as $$$\sum_{i=1}^k \left\lceil \frac{b_i}{x} \right\rceil$$$, which means that we divide each element by $$$x$$$, round it up to the nearest integer, and sum up the resulting values. For example, if $$$x = 3$$$, and the array is $$$[4, 11, 6]$$$, the beauty of the array is equal to $$$\left\lceil \frac{4}{3} \right\rceil + \left\lceil \frac{11}{3} \right\rceil + \left\lceil \frac{6}{3} \right\rceil = 2 + 4 + 2 = 8$$$.Please determine the minimum and the maximum beauty you can get by performing some operations on the original array.

The first input line contains a single integer $$$t$$$ — the number of test cases ($$$1 \le t \le 1000$$$). The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 10^5$$$, $$$1 \leq x \leq 10^9$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$), the elements of the array $$$a$$$.  It is guaranteed that the sum of values of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case output two integers — the minimal and the maximal possible beauty.

NoteIn the first test case the beauty of the array does not change if we perform any operations.In the second example we can leave the array unchanged to attain the maximum beauty, and to get the minimum beauty one can replace two elements $$$4$$$ and $$$11$$$ with their sum, yielding an array $$$[6, 15]$$$, which has its beauty equal to $$$7$$$.

def method(v, x)
  v / x + (v % x != 0 ? 1 : 0)
end

t = gets.to_i
t.times do
  n, x = gets.split.map { |x| x.to_i }
  a = gets.split.map { |x| x.to_i }
  puts "#{method(a.sum, x)} #{a.map { |v| method(v, x) }.sum}"
end

def method(v, x)
  v / x + (v % x != 0 ? 1 : 0)
end

t = gets.to_i
t.times do
  n, x = gets.split.map {|x| x.to_i }
  a = gets.split.map {|x| x.to_i }
  puts "#{method(a.sum, x)} #{a.map { |v| method(v, x) }.sum}"
end

a = gets.to_i
for i in 1..a do
    c = gets.chop.split(/ /).map(&:to_i)
    w = c[0]
    h = c[1].to_f
    b = gets.chop
    c = b.split(/ /).map(&:to_i)
    x = c.inject(0){|n, m| n + m}
    x = x / h
    x = x.ceil
    l = 0
    for i in 0..w-1 do
        q = c[i] / h
        q = q.ceil
        l += q
    end
    print x, " ", l, "\n"
end

#!/usr/bin/env ruby

gets.to_i.times {
    n, x = gets.split.map &:to_i
    nums = gets.split.map &:to_i
    max = nums.map{|num| (num.to_f / x).ceil }.sum
    min = (nums.sum.to_f / x).ceil
    puts "#{min} #{max}"
}

def read
  gets.split.map &:to_i
end
gets.to_i.times do
  _, x = read
  a = read
  print (a.sum + x - 1) / x, " ", a.map { |it| (it + x - 1) / x }.sum, "\n"
end

t = gets.chomp.to_i
t.times do
    n, x = gets.chomp.split(" ").map(&:to_i)
    a = gets.chomp.split(" ").map(&:to_i)
    max = 0
    ans = 0
    a.each do |i|
        max += (i/x.to_f).ceil
        ans += i
    end
    min = (ans/x.to_f).ceil
    print "#{min}" + " " + "#{max}" + "\n"
end

t = gets.chomp.to_i
t.times do
  n, x = gets.chomp.split(' ').map(&:to_i)
  arr = gets.chomp.split(' ').map(&:to_i)
  min = 0
  max = 0
  ind = 0
  sum = 0
  while ind < arr.size
    sum += arr[ind]
    max += (1.0 * arr[ind] / x).ceil
    ind += 1
  end
  min += (1.0 * sum / x).ceil
  puts [min, max].join ' '
end

t = gets.to_i
ans = []
t.times do
  n,x = gets.chomp.split(" ").map(&:to_i)
  a = gets.chomp.split(" ").map(&:to_i)
  min = (a.sum + x - 1) / x
  max = 0
  a.each do |v|
    max += (v + x - 1) / x
  end
  ans << [min,max]
end
ans.each do |v|
  puts v.join(" ")
end


Vladik and Chloe decided to determine who of them is better at math. Vladik claimed that for any positive integer n he can represent fraction  as a sum of three distinct positive fractions in form .Help Vladik with that, i.e for a given n find three distinct positive integers x, y and z such that . Because Chloe can't check Vladik's answer if the numbers are large, he asks you to print numbers not exceeding 109.If there is no such answer, print -1.

The single line contains single integer n (1 ≤ n ≤ 104).

If the answer exists, print 3 distinct numbers x, y and z (1 ≤ x, y, z ≤ 109, x ≠ y, x ≠ z, y ≠ z). Otherwise print -1. If there are multiple answers, print any of them.

n=gets.to_i
if n==1
    puts -1
else
    puts [n, n+1, n*(n+1)]*' '
end

$, = " "
n = gets.to_i
if n == 1
    puts -1
else
    print n, n + 1, n * (n + 1), "\n"
end

n = gets.strip.to_i
puts -1 if n == 1
puts [n, n+1, n*n+n].map(&:to_s).join(' ') if n != 1


Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed $$$n$$$ cans in a row on a table. Cans are numbered from left to right from $$$1$$$ to $$$n$$$. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down.Vasya knows that the durability of the $$$i$$$-th can is $$$a_i$$$. It means that if Vasya has already knocked $$$x$$$ cans down and is now about to start shooting the $$$i$$$-th one, he will need $$$(a_i \cdot x + 1)$$$ shots to knock it down. You can assume that if Vasya starts shooting the $$$i$$$-th can, he will be shooting it until he knocks it down.Your task is to choose such an order of shooting so that the number of shots required to knock each of the $$$n$$$ given cans down exactly once is minimum possible.

The first line of the input contains one integer $$$n$$$ $$$(2 \le n \le 1\,000)$$$ — the number of cans. The second line of the input contains the sequence $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 1\,000)$$$, where $$$a_i$$$ is the durability of the $$$i$$$-th can.

In the first line print the minimum number of shots required to knock each of the $$$n$$$ given cans down exactly once. In the second line print the sequence consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the order of indices of cans that minimizes the number of shots required. If there are several answers, you can print any of them.

NoteIn the first example Vasya can start shooting from the first can. He knocks it down with the first shot because he haven't knocked any other cans down before. After that he has to shoot the third can. To knock it down he shoots $$$20 \cdot 1 + 1 = 21$$$ times. After that only second can remains. To knock it down Vasya shoots $$$10 \cdot 2 + 1 = 21$$$ times. So the total number of shots is $$$1 + 21 + 21 = 43$$$.In the second example the order of shooting does not matter because all cans have the same durability.

n = gets.chomp.to_i
arr = gets.chomp.split(' ').map(&:to_i).zip(1..n).sort.reverse
res = 0
arr.each_with_index do |el, ind|
  res += el[0] * ind + 1
end
puts res
puts arr.map{|el| el[1]}.join(' ')

n = gets.chomp.to_i
a = gets.chomp.split(" ").map(&:to_i)
b = []
n.times do |i|
    b[i] = [a[i], i]
end
b.sort!.reverse!
ans = 0
n.times do |i|
    a[i] = b[i][1] + 1
    ans += b[i][0] * i + 1
end
puts ans
puts a.join(' ')

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

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

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

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

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

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

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

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

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

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

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

n = inp[0]
a = inp
t = []
a.size.times do |i|
  t[i] = [a[i],i]
end
t.sort!.reverse!
ans = 0
anst = []
n.times do |i|
  ans += 1
  ans += t[i][0]*i
  anst.push(t[i][1]+1)
end
p ans
puts anst.join(" ")

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

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

#def bs(ar,eq,n) en=(eq==1 ? :>= : :>); ar.bsearch_index{|x|x.send(en,n)} end
def C(a,b) b==0||a==b ? 1 : (b=a-b if a/2<b;(a-b+1..a).inject(:*)/(1..b).inject(:*)) end

def puts_yesno(can) puts(can ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def debug(k,v) puts "#{k}:#{v}" end
########### ( ˘ω˘ )ｽﾔｧ… ###########
n=gi
a=gsmi
ar=[]
ans=[]
n.times do |i|
  ar<<[a[i],i+1]
end
desc ar

n.times do |i|
  cnt+=ar[i][0]*i+1
  ans<<ar[i][1]
end
puts "#{cnt}\n#{ans.join(" ")}"


We will consider the numbers $$$a$$$ and $$$b$$$ as adjacent if they differ by exactly one, that is, $$$|a-b|=1$$$.We will consider cells of a square matrix $$$n \times n$$$ as adjacent if they have a common side, that is, for cell $$$(r, c)$$$ cells $$$(r, c-1)$$$, $$$(r, c+1)$$$, $$$(r-1, c)$$$ and $$$(r+1, c)$$$ are adjacent to it.For a given number $$$n$$$, construct a square matrix $$$n \times n$$$ such that:   Each integer from $$$1$$$ to $$$n^2$$$ occurs in this matrix exactly once;  If $$$(r_1, c_1)$$$ and $$$(r_2, c_2)$$$ are adjacent cells, then the numbers written in them must not be adjacent.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$). Then $$$t$$$ test cases follow. Each test case is characterized by one integer $$$n$$$ ($$$1 \le n \le 100$$$).

For each test case, output:    -1, if the required matrix does not exist;  the required matrix, otherwise (any such matrix if many of them exist).  The matrix should be outputted as $$$n$$$ lines, where each line contains $$$n$$$ integers.

def gen_matrix(n, seed = nil)
  m = n.times.map { [-1] * n }
  seed ||= n
  srand(seed)
  pool = 1.upto(n * n).map {|i| i}.shuffle

  0.upto(n - 1) do |i|
    0.upto(n - 1) do |j|
      upper = ((i >= 1) ? m[i - 1][j] : -1)
      left  = ((j >= 1) ? m[i][j - 1] : -1)
      x = pool.pop
      retry_count = 5
      while ((x - upper).abs == 1 || (x - left).abs == 1) && retry_count > 0
        retry_count -= 1
        pool.push(x)
        pool.shuffle!
        x = pool.pop
      end
      if retry_count == 0
        return gen_matrix(n, seed + 1)
      end
      m[i][j] = x
    end
  end
  return m
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  if n == 2
    printf("-1\n")
    next
  end
  m = gen_matrix(n, n)
  m.each {|row| printf("%s\n", row.join(" ")) }
end

t = Integer(gets.chomp)
t.times{
    n = Integer(gets.chomp)

    if(n==2)
        puts -1
    else
        ev = 1
        od = n%2 == 0 ? (n*n)/2 + 1 : ((n*n)+1)/2 + 1
        for i in 0...n do
            for j in 0...n do
                if((i+j)%2 == 0)
                    print "#{ev} "
                    ev += 1
                else
                    print "#{od} "
                    od += 1
                end
            end
            print "\n"
        end
    end
}

gets.to_i.times {
  n = gets.to_i

  if n == 2
    p -1
    next
  end

  m = Array.new(n) { [0] * n }

  cur = 1
  n.times { |i|
    n.times { |j|
      next if (i & 1) != (j & 1)
      m[i][j] = cur
      cur += 1
    }
  }
  n.times { |i|
    n.times { |j|
      next if (i & 1) == (j & 1)
      m[i][j] = cur
      cur += 1
    }
  }

  n.times { |i|
    puts m[i].join(' ')
  }
}

def gen_matrix(n, seed = nil)
  m = n.times.map { [-1] * n }
  seed ||= n
  srand(seed)
  pool = 1.upto(n * n).map {|i| i}.shuffle

  0.upto(n - 1) do |i|
    0.upto(n - 1) do |j|
      upper = ((i >= 1) ? m[i - 1][j] : -1)
      left  = ((j >= 1) ? m[i][j - 1] : -1)
      x = pool.pop
      retry_count = 5
      while (x - upper).abs == 1 || (x - left).abs == 1 && retry_count > 0
        retry_count -= 1
        pool.push(x)
        pool.shuffle!
        x = pool.pop
      end
      if retry_count == 0
        return gen_matrix(n, seed + 1)
      end
      m[i][j] = x
    end
  end
  return m
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  if n == 2
    printf("-1\n")
    next
  end
  m = gen_matrix(n, n)
  m.each {|row| printf("%s\n", row.join(" ")) }
end

def gen_matrix(n)
  m = n.times.map { [-1] * n }
  pool = 1.upto(n * n).map {|i| i}.shuffle

  0.upto(n - 1) do |i|
    0.upto(n - 1) do |j|
      upper = i >= 1 ? m[i - 1][j] : -1
      left  = j >= 1 ? m[i][j - i] : -1
      x = pool.pop
      return gen_matrix(n) if (x - upper).abs == 1 || (x - left).abs == 1
      m[i][j] = x
    end
  end
  return m
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  if n == 2
    printf("-1\n")
    next
  end
  m = gen_matrix(n)
  m.each {|row| printf("%s\n", row.join(" ")) }
end

def gen_matrix(n)
  m = n.times.map { [0] * n }
  srand(n)
  pool = 1.upto(n * n).map {|i| i}.shuffle

  0.upto(n - 1) do |i|
    0.upto(n - 1) do |j|
      upper = i >= 1 ? m[i - 1][j] : -1
      left  = j >= 1 ? m[i][j - i] : -1

      x = pool.shift
      while (x - upper).abs == 1 || (x - left).abs == 1
        pool.push(x)
        x = pool.shift
      end
      m[i][j] = x
    end
  end
  return m
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  if n == 2
    printf("-1\n")
    next
  end
  m = gen_matrix(n)
  m.each {|row| printf("%s\n", row.join(" ")) }
end

t = Integer(gets.chomp)
t.times{
    n = Integer(gets.chomp)

    if(n==2)
        puts -1
    else
        ev = 1
        od = n%2 == 0 ? (n*n)/2 : ((n*n)+1)/2 + 1
        for i in 0...n do
            for j in 0...n do
                if((i+j)%2 == 0)
                    print "#{ev} "
                    ev += 1
                else
                    print "#{od} "
                    od += 1
                end
            end
            print "\n"
        end
    end
}


Let there be an array $$$b_1, b_2, \ldots, b_k$$$. Let there be a partition of this array into segments $$$[l_1; r_1], [l_2; r_2], \ldots, [l_c; r_c]$$$, where $$$l_1 = 1$$$, $$$r_c = k$$$, and for any $$$2 \leq i \leq c$$$ holds that $$$r_{i-1} + 1 = l_i$$$. In other words, each element of the array belongs to exactly one segment.Let's define the cost of a partition as $$$$$$c + \sum_{i = 1}^{c} \operatorname{mex}(\{b_{l_i}, b_{l_i + 1}, \ldots, b_{r_i}\}),$$$$$$ where $$$\operatorname{mex}$$$ of a set of numbers $$$S$$$ is the smallest non-negative integer that does not occur in the set $$$S$$$. In other words, the cost of a partition is the number of segments plus the sum of MEX over all segments. Let's define the value of an array $$$b_1, b_2, \ldots, b_k$$$ as the maximum possible cost over all partitions of this array.You are given an array $$$a$$$ of size $$$n$$$. Find the sum of values of all its subsegments.An array $$$x$$$ is a subsegment of an array $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

The input contains several test cases. The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 30$$$) — the number of test cases. The first line for each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the length of the array. The second line contains a sequence of integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$) — the array elements. It is guaranteed that the sum of the values $$$n$$$ over all test cases does not exceed $$$100$$$.

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

NoteIn the second test case:   The best partition for the subsegment $$$[2, 0, 1]$$$: $$$[2], [0, 1]$$$. The cost of this partition equals to $$$2 + \operatorname{mex}(\{2\}) + \operatorname{mex}(\{0, 1\}) = 2 + 0 + 2 = 4$$$.  The best partition for the subsegment $$$[2, 0]$$$: $$$[2], [0]$$$. The cost of this partition equals to $$$2 + \operatorname{mex}(\{2\}) + \operatorname{mex}(\{0\}) = 2 + 0 + 1 = 3$$$  The best partition for the subsegment $$$[2]$$$: $$$[2]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{2\}) = 1 + 0 = 1$$$.  The best partition for the subsegment $$$[0, 1]$$$: $$$[0, 1]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{0, 1\}) = 1 + 2 = 3$$$.  The best partition for the subsegment $$$[0]$$$: $$$[0]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{0\}) = 1 + 1 = 2$$$.  The best partition for the subsegment $$$[1]$$$: $$$[1]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{1\}) = 1 + 0 = 1$$$. The sum of values over all subsegments equals to $$$4 + 3 + 1 + 3 + 2 + 1 = 14$$$.

class Array
  def n
    return length
  end
end

$__cur_readed = []
$__cur_index = 0

def rs
	while $__cur_index >= $__cur_readed.length
		$__cur_readed = gets.split(" ")
		$__cur_index = 0
	end
	$__cur_index+=1
	return $__cur_readed[$__cur_index-1]
end

def ri
	res = rs.to_i
end

def ra2 n
	return Array.new(n) {|i| ri}
end

def ra
	return ra2 ri
end

t = ri

for _ in (1..t)
	a = ra
	res = 0
	for i in (0..a.n-1)
		for j in (i..a.n-1)
			for k in (i..j)
				res+=1
				if a[k] == 0
					res +=1
				end
			end
		end
	end
	puts res
end

$__cur_readed = []
$__cur_index = 0

def rs
	while $__cur_index >= $__cur_readed.length
		$__cur_readed = gets.split(" ")
		$__cur_index = 0
	end
	$__cur_index+=1
	return $__cur_readed[$__cur_index-1]
end

def ri
	return rs.to_i
end

def ra2 n
	return Array.new(n) {|i| ri}
end

def ra
	return ra2 ri
end

t = ri

for _ in (1..t)
	a = ra
	res = 0
	for i in (0..a.length-1)
		for j in (i..a.length-1)
			for k in (i..j)
				res+=1
				if a[k] == 0
					res +=1
				end
			end
		end
	end
	puts res
end

gets.to_i.times {
  n = gets.to_i
  xs = gets.split.map(&:to_i).map { _1 > 0 ? 0 : 1 }
  ans = 0
  n.times { |r|
    (r + 1).times { |l|
      ans += r - l + 1
      ans += xs[l..r].sum
    }
  }
  p ans
}

$__cur_readed = []
$__cur_index = 0

def rs
	while $__cur_index >= $__cur_readed.length
		$__cur_readed = gets.split(" ")
		$__cur_index = 0
	end
	$__cur_index+=1
	return $__cur_readed[$__cur_index-1]
end

def ri
	return rs.to_i
end

def ra2 n
	return Array.new(n) {|i| ri}
end

def ra
	return ra2 ri
end

t = ri

for _ in (1..t)
	a = ra
	res = 0
	for i in (0..a.length-1)
		for j in (i..a.length-1)
			for k in (i..j)
				res+=1
				if a[res] == 0
					res +=1
				end
			end
		end
	end
	puts res
end


You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.

For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.

NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.

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

gi.times do
  n = gi
  a = gli
  if a == (1..n).to_a
    puts 0
  elsif a[0] == n && a[-1] == 1
    puts 3
  elsif a[0] == 1 || a[-1] == n
    puts 1
  else
    puts 2
  end
end

def f
  n = gets.chomp.to_i
  a = gets.chomp.split(" ").map(&:to_i)

  if a.each_with_index.all?{|c, i| c == i + 1}
    puts 0
  elsif a.first == 1 || a.last == n
    puts 1
  elsif a.first == n && a.last == 1
    puts 3
  else
    puts 2
  end
end

t = gets.chomp.to_i
t.times do
  f()
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  a = gets.to_s.split.map {|x| x.to_i }
  sa = a.sort
  already_sorted = true
  a.each_with_index do |x, i|
    if sa[i] != x
      already_sorted = false
      break
    end
  end

  if a[0] == sa[-1] && a[-1] == sa[0]
    printf("3\n")
  elsif sa[0] == a[0] || sa[-1] == a[-1]
    printf("%d\n", already_sorted ? 0 : 1)
  else
    printf("2\n")
  end
end

t = gets.to_i
t.times{
	n = gets.to_i
	arr = gets.split.map &:to_i
	if arr == arr.sort then
		p 0
	elsif arr[0] == arr.min || arr.last == arr.max then
		p 1
	elsif arr[0] == arr.max && arr.last == arr.min then
		p 3
	else
		p 2
	end
}

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

gi.times do
  n = gi
  a = gli
  if a == (1..n).to_a
    puts 0
  elsif a[0] == 1 || a[-1] == n
    puts 1
  else
    puts 2
  end
end

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

gi.times do
  n = gi
  a = gli
  if a.sort == (1..n).to_a
    puts 0
  elsif a[0] == 1 || a[-1] == n
    puts 1
  else
    puts 2
  end
end

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

gi.times do
  _ = gi
  a = gli
  if a.sort == a
    puts 0
  elsif a.min == a[0] || a.max == a[-1]
    puts 1
  else
    puts 2
  end
end

def f
  n = gets.chomp.to_i
  a = gets.chomp.split(" ").map(&:to_i)

  if a.each_with_index.all?{|c, i| c == i + 1}
    puts 0
  elsif a.first == 1 || a.last == n
    puts 1
  else
    puts 2
  end
end

t = gets.chomp.to_i
t.times do
  f()
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  a = gets.to_s.split.map {|x| x.to_i }
  sa = a.sort
  already_sorted = true
  a.each_with_index do |x, i|
    if sa[i] != x
      already_sorted = false
      break
    end
  end

  if sa[0] == a[0] || sa[-1] == a[-1]
    printf("%d\n", already_sorted ? 0 : 1)
  else
    printf("2\n")
  end
end

t = gets.to_i
t.times{
	n = gets.to_i
	arr = gets.split.map &:to_i
	if arr == arr.sort then
		p 0
	elsif arr[0] == arr.min || arr.last == arr.max then
		p 1
	else
		p 2
	end
}


Nastya came to her informatics lesson, and her teacher who is, by the way, a little bit famous here gave her the following task.Two matrices $$$A$$$ and $$$B$$$ are given, each of them has size $$$n \times m$$$. Nastya can perform the following operation to matrix $$$A$$$ unlimited number of times:   take any square square submatrix of $$$A$$$ and transpose it (i.e. the element of the submatrix which was in the $$$i$$$-th row and $$$j$$$-th column of the submatrix will be in the $$$j$$$-th row and $$$i$$$-th column after transposing, and the transposed submatrix itself will keep its place in the matrix $$$A$$$). Nastya's task is to check whether it is possible to transform the matrix $$$A$$$ to the matrix $$$B$$$.    Example of the operation As it may require a lot of operations, you are asked to answer this question for Nastya.A square submatrix of matrix $$$M$$$ is a matrix which consist of all elements which comes from one of the rows with indeces $$$x, x+1, \dots, x+k-1$$$ of matrix $$$M$$$ and comes from one of the columns with indeces $$$y, y+1, \dots, y+k-1$$$ of matrix $$$M$$$. $$$k$$$ is the size of square submatrix. In other words, square submatrix is the set of elements of source matrix which form a solid square (i.e. without holes).

The first line contains two integers $$$n$$$ and $$$m$$$ separated by space ($$$1 \leq n, m \leq 500$$$) — the numbers of rows and columns in $$$A$$$ and $$$B$$$ respectively. Each of the next $$$n$$$ lines contains $$$m$$$ integers, the $$$j$$$-th number in the $$$i$$$-th of these lines denotes the $$$j$$$-th element of the $$$i$$$-th row of the matrix $$$A$$$ ($$$1 \leq A_{ij} \leq 10^{9}$$$). Each of the next $$$n$$$ lines contains $$$m$$$ integers, the $$$j$$$-th number in the $$$i$$$-th of these lines denotes the $$$j$$$-th element of the $$$i$$$-th row of the matrix $$$B$$$ ($$$1 \leq B_{ij} \leq 10^{9}$$$).

Print "YES" (without quotes) if it is possible to transform $$$A$$$ to $$$B$$$ and "NO" (without quotes) otherwise. You can print each letter in any case (upper or lower).

NoteConsider the third example. The matrix $$$A$$$ initially looks as follows.$$$$$$ \begin{bmatrix} 1 & 2 & 3\\ 4 & 5 & 6\\ 7 & 8 & 9 \end{bmatrix} $$$$$$Then we choose the whole matrix as transposed submatrix and it becomes$$$$$$ \begin{bmatrix} 1 & 4 & 7\\ 2 & 5 & 8\\ 3 & 6 & 9 \end{bmatrix} $$$$$$Then we transpose the submatrix with corners in cells $$$(2, 2)$$$ and $$$(3, 3)$$$. $$$$$$ \begin{bmatrix} 1 & 4 & 7\\ 2 & \textbf{5} & \textbf{8}\\ 3 & \textbf{6} & \textbf{9} \end{bmatrix} $$$$$$So matrix becomes$$$$$$ \begin{bmatrix} 1 & 4 & 7\\ 2 & 5 & 6\\ 3 & 8 & 9 \end{bmatrix} $$$$$$and it is $$$B$$$.

n, m = gets.split(" ").map(&:to_i)
a = []
b = []
(0..n-1).each do |i|
    a += gets.split(" ").map(&:to_i)
end

(0..n-1).each do |i|
    b += gets.split(" ").map(&:to_i)
end
h = []
l = []
(0..n-1).each do |i|
    (0..m-1).each do |j|
	    h[i+j].nil? ? h[i+j]=[a[i*m+j]] : h[i+j] << a[i*m+j]
	    l[i+j].nil? ? l[i+j]=[b[i*m+j]] : l[i+j] << b[i*m+j]
    end
end
res = "YES"
(0..n+m-2).each do |i|
    res = "NO" if h[i].sort != l[i].sort
    break if res == "NO"
end

puts res

n, m = gets.split(" ").map(&:to_i)
a = []
b = []
(0..n-1).each do |i|
    a += gets.split(" ").map(&:to_i)
end

(0..n-1).each do |i|
    b += gets.split(" ").map(&:to_i)
end

h = {}
(0..n-1).each do |i|
    (0..m-1).each do |j|
         if h[i+j]
            h[i+j][a[i*n+j]].nil? ? h[i+j][a[i*n+j]] = 1 : h[i+j][a[i*n+j]] += 1
         else
            h[i+j] = {a[i*n+j] => 1}
         end
    end
end
res = "YES"
(0..n-1).each do |i|
    (0..m-1).each do |j|
        if h[i+j][b[i*n+j]].nil?
            res = "NO"
        else
	    if h[i+j][b[i*n+j]] < 1
	       res = "NO"
            end
        end
    end
    break if res == "NO"
end

puts res

n, m = gets.split(" ").map(&:to_i)
a = []
b = []
(0..n-1).each do |i|
    a += gets.split(" ").map(&:to_i)
end

(0..n-1).each do |i|
    b += gets.split(" ").map(&:to_i)
end
h = {}
(0..n-1).each do |i|
    (0..m-1).each do |j|
         if h[i+j]
            if h[i+j][a[i*m+j]].nil?
		h[i+j][a[i*m+j]] = 1
	    else
		h[i+j][a[i*m+j]] += 1
	    end
         else
            h[i+j] = {a[i*m+j] => 1}
         end
    end
end
res = "YES"
(0..n-1).each do |i|
    (0..m-1).each do |j|
        if h[i+j][b[i*m+j]].nil?
            res = "NO"
        else
	    if h[i+j][b[i*m+j]] < 1
	       res = "NO"
            end
        end
    end
    break if res == "NO"
end

puts res