The last contest held on Johnny's favorite competitive programming platform has been received rather positively. However, Johnny's rating has dropped again! He thinks that the presented tasks are lovely, but don't show the truth about competitors' skills.The boy is now looking at the ratings of consecutive participants written in a binary system. He thinks that the more such ratings differ, the more unfair is that such people are next to each other. He defines the difference between two numbers as the number of bit positions, where one number has zero, and another has one (we suppose that numbers are padded with leading zeros to the same length). For example, the difference of $$$5 = 101_2$$$ and $$$14 = 1110_2$$$ equals to $$$3$$$, since $$$0101$$$ and $$$1110$$$ differ in $$$3$$$ positions. Johnny defines the unfairness of the contest as the sum of such differences counted for neighboring participants.Johnny has just sent you the rating sequence and wants you to find the unfairness of the competition. You have noticed that you've got a sequence of consecutive integers from $$$0$$$ to $$$n$$$. That's strange, but the boy stubbornly says that everything is right. So help him and find the desired unfairness for received numbers.

The input consists of multiple test cases. The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. The following $$$t$$$ lines contain a description of test cases. The first and only line in each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^{18})$$$.

Output $$$t$$$ lines. For each test case, you should output a single line with one integer — the unfairness of the contest if the rating sequence equals to $$$0$$$, $$$1$$$, ..., $$$n - 1$$$, $$$n$$$.

NoteFor $$$n = 5$$$ we calculate unfairness of the following sequence (numbers from $$$0$$$ to $$$5$$$ written in binary with extra leading zeroes, so they all have the same length):   $$$000$$$  $$$001$$$  $$$010$$$  $$$011$$$  $$$100$$$  $$$101$$$ The differences are equal to $$$1$$$, $$$2$$$, $$$1$$$, $$$3$$$, $$$1$$$ respectively, so unfairness is equal to $$$1 + 2 + 1 + 3 + 1 = 8$$$.

def solve
  n = gets.strip.to_i
  an = 0
  (0..64).each { |i|
    if !(n & (1 << i)).zero?
      an += ((1 << (i + 1)) - 1)
    end
  }
  puts an
end

gets.strip.to_i.times do
  solve
end


Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming.It's known that they have worked together on the same file for $$$n + m$$$ minutes. Every minute exactly one of them made one change to the file. Before they started, there were already $$$k$$$ lines written in the file.Every minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines.Monocarp worked in total for $$$n$$$ minutes and performed the sequence of actions $$$[a_1, a_2, \dots, a_n]$$$. If $$$a_i = 0$$$, then he adds a new line to the end of the file. If $$$a_i > 0$$$, then he changes the line with the number $$$a_i$$$. Monocarp performed actions strictly in this order: $$$a_1$$$, then $$$a_2$$$, ..., $$$a_n$$$.Polycarp worked in total for $$$m$$$ minutes and performed the sequence of actions $$$[b_1, b_2, \dots, b_m]$$$. If $$$b_j = 0$$$, then he adds a new line to the end of the file. If $$$b_j > 0$$$, then he changes the line with the number $$$b_j$$$. Polycarp performed actions strictly in this order: $$$b_1$$$, then $$$b_2$$$, ..., $$$b_m$$$.Restore their common sequence of actions of length $$$n + m$$$ such that all actions would be correct — there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence $$$[a_1, a_2, \dots, a_n]$$$ and Polycarp's — subsequence $$$[b_1, b_2, \dots, b_m]$$$. They can replace each other at the computer any number of times.Let's look at an example. Suppose $$$k = 3$$$. Monocarp first changed the line with the number $$$2$$$ and then added a new line (thus, $$$n = 2, \: a = [2, 0]$$$). Polycarp first added a new line and then changed the line with the number $$$5$$$ (thus, $$$m = 2, \: b = [0, 5]$$$).Since the initial length of the file was $$$3$$$, in order for Polycarp to change line number $$$5$$$ two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be $$$[0, 2, 0, 5]$$$ and $$$[2, 0, 0, 5]$$$. Changes $$$[0, 0, 5, 2]$$$ (wrong order of actions) and $$$[0, 5, 2, 0]$$$ (line $$$5$$$ cannot be edited yet) are not correct.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$). Then $$$t$$$ test cases follow. Before each test case, there is an empty line. Each test case contains three lines. The first line contains three integers $$$k$$$, $$$n$$$, $$$m$$$ ($$$0 \le k \le 100$$$, $$$1 \le n, m \le 100$$$) — the initial number of lines in file and lengths of Monocarp's and Polycarp's sequences of changes respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 300$$$). The third line contains $$$m$$$ integers $$$b_1, b_2, \dots, b_m$$$ ($$$0 \le b_j \le 300$$$).

For each test case print any correct common sequence of Monocarp's and Polycarp's actions of length $$$n + m$$$ or -1 if such sequence doesn't exist.

gets.to_i.times {
  gets
  k, n, m = gets.split.map!(&:to_i)
  as = gets.split.map!(&:to_i)
  bs = gets.split.map!(&:to_i)
  xs = []
  i = 0; j = 0
  while i < n || j < m
    if i < n && (as[i] <= k)
      xs << as[i]
      k += 1 if as[i] == 0
      i += 1
    elsif j < m && (bs[j] <= k)
      xs << bs[j]
      k += 1 if bs[j] == 0
      j += 1
    else
      break
    end
  end

  if i == n && j == m
    puts xs.join(' ')
  else
    p -1
  end
}

def solve(first_sec, second_sec, k)
  first_ptr = 0
  second_ptr = 0
  solution = []
  while first_ptr < first_sec.size && second_ptr < second_sec.size do
    if first_sec[first_ptr] < second_sec[second_ptr]
      return -1 if first_sec[first_ptr] > k
      solution << first_sec[first_ptr]
      first_ptr += 1
    else
      return -1 if second_sec[second_ptr] > k
      solution << second_sec[second_ptr]
      second_ptr += 1
    end
    k += 1 if solution[-1] == 0
  end

  while first_ptr < first_sec.size do
    return -1 if first_sec[first_ptr] > k
    solution << first_sec[first_ptr]
    first_ptr += 1
    k += 1 if solution[-1] == 0
  end

  while second_ptr < second_sec.size do
    return -1 if second_sec[second_ptr] > k
    solution << second_sec[second_ptr]
    second_ptr += 1
    k += 1 if solution[-1] == 0
  end

  solution.join(' ')
end

t = gets.chomp.to_i
t.times do
  gets
  k, _ = gets.chomp.split(' ').map(&:to_i)
  first_sec = gets.chomp.split(' ').map(&:to_i)
  second_sec = gets.chomp.split(' ').map(&:to_i)

  puts "#{solve(first_sec, second_sec, k)}\n"
end


Mike and Ann are sitting in the classroom. The lesson is boring, so they decided to play an interesting game. Fortunately, all they need to play this game is a string $$$s$$$ and a number $$$k$$$ ($$$0 \le k < |s|$$$).At the beginning of the game, players are given a substring of $$$s$$$ with left border $$$l$$$ and right border $$$r$$$, both equal to $$$k$$$ (i.e. initially $$$l=r=k$$$). Then players start to make moves one by one, according to the following rules: A player chooses $$$l^{\prime}$$$ and $$$r^{\prime}$$$ so that $$$l^{\prime} \le l$$$, $$$r^{\prime} \ge r$$$ and $$$s[l^{\prime}, r^{\prime}]$$$ is lexicographically less than $$$s[l, r]$$$. Then the player changes $$$l$$$ and $$$r$$$ in this way: $$$l := l^{\prime}$$$, $$$r := r^{\prime}$$$. Ann moves first. The player, that can't make a move loses.Recall that a substring $$$s[l, r]$$$ ($$$l \le r$$$) of a string $$$s$$$ is a continuous segment of letters from s that starts at position $$$l$$$ and ends at position $$$r$$$. For example, "ehn" is a substring ($$$s[3, 5]$$$) of "aaaehnsvz" and "ahz" is not.Mike and Ann were playing so enthusiastically that they did not notice the teacher approached them. Surprisingly, the teacher didn't scold them, instead of that he said, that he can figure out the winner of the game before it starts, even if he knows only $$$s$$$ and $$$k$$$.Unfortunately, Mike and Ann are not so keen in the game theory, so they ask you to write a program, that takes $$$s$$$ and determines the winner for all possible $$$k$$$.

The first line of the input contains a single string $$$s$$$ ($$$1 \leq |s| \leq 5 \cdot 10^5$$$) consisting of lowercase English letters.

Print $$$|s|$$$ lines. In the line $$$i$$$ write the name of the winner (print Mike or Ann) in the game with string $$$s$$$ and $$$k = i$$$, if both play optimally

require 'stringio'
io = StringIO.new

str = gets.chomp

min_c = 'zz'

str.split('').each do |c|
	if c > min_c
		io.puts "Ann"
	else
		io.puts "Mike"
		min_c = c
	end
end

print io.string

require 'stringio'
io = StringIO.new

str = gets.chomp

min_c = 'z'.next

str.split('').each do |c|
	if c > min_c
		io.puts "Ann"
	else
		io.puts "Mike"
		min_c = c
	end
end

print io.string

str = gets.chomp
ks = str.length

ks.times do |k|
	l = r = k

	start = "Ann"

	while true
		if start == "Ann"
			start = "Mike"
		else
			start = "Ann"
		end

		if (l <= 0 || r >= str.length)
			p start
			break
		end

		old_str = str[l..r]

		if l - 1 > 0
			l_str = str[l-1..r]
		end

		if r + 1 < str.length
			r_str = str[l..r+1]
		end

		if (l_str.nil? && r_str.nil?) || ((l_str && l_str > old_str) && (r_str && r_str > old_str))
			p start
			break
		end

		if l_str && r_str
			if l_str < r_str
				l = l-1
			else
				r = r+1
			end
		else
			l = l-1 if l_str && r_str.nil?
			r = r+1 if r_str && l_str.nil?
		end

	end
end


Maxim wants to buy some games at the local game shop. There are $$$n$$$ games in the shop, the $$$i$$$-th game costs $$$c_i$$$.Maxim has a wallet which can be represented as an array of integers. His wallet contains $$$m$$$ bills, the $$$j$$$-th bill has value $$$a_j$$$.Games in the shop are ordered from left to right, Maxim tries to buy every game in that order.When Maxim stands at the position $$$i$$$ in the shop, he takes the first bill from his wallet (if his wallet is empty then he proceeds to the next position immediately) and tries to buy the $$$i$$$-th game using this bill. After Maxim tried to buy the $$$n$$$-th game, he leaves the shop.Maxim buys the $$$i$$$-th game if and only if the value of the first bill (which he takes) from his wallet is greater or equal to the cost of the $$$i$$$-th game. If he successfully buys the $$$i$$$-th game, the first bill from his wallet disappears and the next bill becomes first. Otherwise Maxim leaves the first bill in his wallet (this bill still remains the first one) and proceeds to the next game.For example, for array $$$c = [2, 4, 5, 2, 4]$$$ and array $$$a = [5, 3, 4, 6]$$$ the following process takes place: Maxim buys the first game using the first bill (its value is $$$5$$$), the bill disappears, after that the second bill (with value $$$3$$$) becomes the first one in Maxim's wallet, then Maxim doesn't buy the second game because $$$c_2 > a_2$$$, the same with the third game, then he buys the fourth game using the bill of value $$$a_2$$$ (the third bill becomes the first one in Maxim's wallet) and buys the fifth game using the bill of value $$$a_3$$$.Your task is to get the number of games Maxim will buy.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$) — the number of games and the number of bills in Maxim's wallet. The second line of the input contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le 1000$$$), where $$$c_i$$$ is the cost of the $$$i$$$-th game. The third line of the input contains $$$m$$$ integers $$$a_1, a_2, \dots, a_m$$$ ($$$1 \le a_j \le 1000$$$), where $$$a_j$$$ is the value of the $$$j$$$-th bill from the Maxim's wallet.

Print a single integer — the number of games Maxim will buy.

NoteThe first example is described in the problem statement.In the second example Maxim cannot buy any game because the value of the first bill in his wallet is smaller than the cost of any game in the shop.In the third example the values of the bills in Maxim's wallet are large enough to buy any game he encounter until he runs out of bills in his wallet.

_,a,b=$<.map{|e|e.split.map &:to_i}
r=0
a.each{|e|b[r].to_i>=e&&r+=1}
p r

N, M = gets.split.map(&:to_i)
cs = gets.split.map(&:to_i)
as = gets.split.map(&:to_i)
ans = 0
cs.each do |c|
    if c <= as[0]
        ans += 1
        as.shift
        break if as.length == 0
    end
end
puts ans

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

ans = 0
j = 0

0.upto(n-1).each do |i|
  if cost[i] <= bills[j]
    ans += 1
    j += 1
  end
  break if j >= m
end

puts ans

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

ans = 0
a = as.shift
(0..n-1).each do |i|
  if a >= cs[i]
    ans += 1
    a = as.shift
  end
  break unless a
end

puts ans

n, m = gets.split.map &:to_i
c = gets.split.map &:to_i
a = gets.split.map &:to_i
ngames = 0
(0...n).each do |i|
  if a[0] && a[0] >= c[i]
    ngames += 1
    a.shift
  end
end
puts ngames

tmp=gets.split
n=tmp[0].to_i
m=tmp[1].to_i
c=gets.split
a=gets.split
i=0
j=0
ans=0
while i<n and j<m
	#puts "#{i} #{n}/ #{j} #{m}"
	a[j]=a[j].to_i
	c[i]=c[i].to_i
	#puts a[j]>c[i]
	if a[j]>=c[i]
		ans=ans+1
		j=j+1
	end
	i=i+1
end
puts ans

n,m=gets.split.map(&:to_i)
c=gets.split.map(&:to_i)
a=gets.split.map(&:to_i)
ans=0
c.each{|v|
  break if a.empty?
  if v<=a.first
    ans+=1
    a.shift
  end
}

puts ans


Alice and Bob play a game. There is a paper strip which is divided into n + 1 cells numbered from left to right starting from 0. There is a chip placed in the n-th cell (the last one).Players take turns, Alice is first. Each player during his or her turn has to move the chip 1, 2 or k cells to the left (so, if the chip is currently in the cell i, the player can move it into cell i - 1, i - 2 or i - k). The chip should not leave the borders of the paper strip: it is impossible, for example, to move it k cells to the left if the current cell has number i < k. The player who can't make a move loses the game.Who wins if both participants play optimally?Alice and Bob would like to play several games, so you should determine the winner in each game.

The first line contains the single integer T (1 ≤ T ≤ 100) — the number of games. Next T lines contain one game per line. All games are independent. Each of the next T lines contains two integers n and k (0 ≤ n ≤ 109, 3 ≤ k ≤ 109) — the length of the strip and the constant denoting the third move, respectively.

For each game, print Alice if Alice wins this game and Bob otherwise.

T = gets.to_i
T.times {
    n,k = gets.split.map &:to_i
    puts case k % 3
    when 0
     n % (k+1) % 3 == 0 && n % (k+1) != k
    else    n % 3 == 0
    end ? "Bob" : "Alice"
}


Lolek and Bolek are about to travel abroad by plane. The local airport has a special "Choose Your Plane" offer. The offer's conditions are as follows:  it is up to a passenger to choose a plane to fly on;  if the chosen plane has x (x > 0) empty seats at the given moment, then the ticket for such a plane costs x zlotys (units of Polish currency). The only ticket office of the airport already has a queue of n passengers in front of it. Lolek and Bolek have not stood in the queue yet, but they are already wondering what is the maximum and the minimum number of zlotys the airport administration can earn if all n passengers buy tickets according to the conditions of this offer?The passengers buy tickets in turn, the first person in the queue goes first, then goes the second one, and so on up to n-th person.

The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of passengers in the queue and the number of planes in the airport, correspondingly. The next line contains m integers a1, a2, ..., am (1 ≤ ai ≤ 1000) — ai stands for the number of empty seats in the i-th plane before the ticket office starts selling tickets. The numbers in the lines are separated by a space. It is guaranteed that there are at least n empty seats in total.

Print two integers — the maximum and the minimum number of zlotys that the airport administration can earn, correspondingly.

NoteIn the first test sample the number of passengers is equal to the number of empty seats, so regardless of the way the planes are chosen, the administration will earn the same sum.In the second sample the sum is maximized if the 1-st person in the queue buys a ticket to the 1-st plane, the 2-nd person — to the 2-nd plane, the 3-rd person — to the 3-rd plane, the 4-th person — to the 1-st plane. The sum is minimized if the 1-st person in the queue buys a ticket to the 1-st plane, the 2-nd person — to the 1-st plane, the 3-rd person — to the 2-nd plane, the 4-th person — to the 2-nd plane.

n,k = gets.chomp.split(/ /).map!{|x| x.to_i}
ra = gets.chomp.split(/ /).map!{|x| x.to_i}
n1 = n
n2 = n
s1 = 0
s2 = 0
ra2 = ra.sort
ra1 = ra.sort.reverse
idx = 0
while n1 > 0
    rew = false
    rew = true if idx >= k - 1 || ra1[idx] > ra1[idx+1]
    s1 += ra1[idx]
    ra1[idx] -= 1
    n1 -= 1
    if rew
        idx = 0
    else
        idx += 1
    end
end

idx = 0
while n2 > 0
    s2 += ra2[idx]
    n2 -= 1
    ra2[idx] -= 1
    if ra2[idx] <= 0
        idx += 1
    end
end
puts s1.to_s + " " + s2.to_s

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

min_a, k, j, score_min = a.sort, n, 0, 0
while k > 0
  score_min += (min_a[j] <= k ? min_a[j]*(min_a[j]+1)/2 : min_a[j]*(min_a[j]+1)/2-(min_a[j]-k)*(min_a[j]-k+1)/2)
  k -= min_a[j]
  j+=1
end

max_a, k, score_max = a.sort.reverse, n, 0, 0
el = max_a[0]
c = max_a.count el
while k > 0
  score_max += (c <= k ? el*c : el*k)
  el -= 1
  k -= c
  if max_a[c] == el
    while c < m and max_a[c] == el
      c+=1
    end
  end
end

puts "#{score_max} #{score_min}"

n,m = gets.chomp.split.collect{|i| i.to_i}
seats = gets.chomp.split.collect{|i| i.to_i}.sort

minz = 0
mint = 0
nplanes = seats.size
0.upto(nplanes-1) do |i|
    s = seats[i]
    while mint!=n and s!=0
        minz += s
        s -= 1
        mint += 1
    end
    break if mint == n
end
maxz = 0
maxt = 0
seats = seats.reverse
i = 0
while maxt != n
    maxz += seats[0]
    seats[0] -= 1
    maxt += 1
    seats[0] = nil if seats[0] == 0
    seats = seats.compact.sort.reverse
end

puts "#{maxz} #{minz}"

n, m = gets.chomp.split.map{|e|e.to_i}
a = Array.new(m){}
a = gets.chomp.split.map{|e|e.to_i}
b = Marshal.load(Marshal.dump(a))
max = min = 0

n.times do |i|
  a.sort!{|c, d| d <=> c }.reject!{|c| c == 0}
  max += a[0]
  a[0] -= 1
end

n.times do |i|
  b.sort!.reject!{|c| c == 0}
  min += b[0]
  b[0] -= 1
end

puts "#{max} #{min}"

#!/usr/bin/ruby
n,m = gets.chomp.split(' ').map{|x| x.to_i}
a = gets.chomp.split(' ').map{|x| x.to_i}
atm = a.clone
minc = 0
maxc = 0
for i in 0..n-1
  max = -1
  k = 0
  for j in 0..m-1
    if atm[j] > max && atm[j] > 0
      max = atm[j]
      k = j
    end
  end
  atm[k]-=1
  maxc += max
end
for i in 0..n-1
  min = 2147483647
  k = 0
  for j in 0..m-1
    if a[j] < min && a[j] > 0
      min = a[j]
      k = j
    end
  end
  a[k]-=1;
  minc += min
end
puts "#{maxc} #{minc}"

n, m = gets.split.map(&:to_i)
ar_down = gets.split.map(&:to_i).sort { |e| -e }
ar_up = ar_down.sort

min = max = 0
n_up = n
n_down = n

ar_up.each do |e|
  if n_up > e
    n_up -= e
    min += e*(1 + e)/2
  else
    min += (n_up)*(e-n_up+e+1)/2
    break
  end
end

n_down.times do
  m = ar_down.max
  max += m
  ar_down[ar_down.find_index(m)] -=1
end

puts "#{max} #{min}"

def calc(p, a)
  cost = 0
  while p > 0
    index = yield(a)
    cost += a[index]
    a[index] -= 1
    p -= 1
  end
  cost
end

n, _ = gets.chomp.split.map { |x| x.to_i }
a = gets.chomp.split.map { |x| x.to_i }
puts [calc(n, a.clone) { |x| max, index = -1, 0; x.each_with_index { |e, i| if e > max; max = e; index = i end }; index },
      calc(n, a) { |x| min, index = 1001, 0; x.each_with_index { |e, i| if e > 0 && e < min; min = e; index = i end }; index }] * ' '

n,m=gets.split.map &:to_i;
a=gets.split.map &:to_i;

b = a; x=y=0;

n.times{
	a=a.sort;x+=a[0];a[0]-=1;
}

n.times{
	b=b.sort;y+=b[-1];b[-1]-=1;b.pop if b[-1]==0
}

puts [y, x]*' '

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

min_a, k, j, score_min = a.sort, n, 0, 0
while k > 0
  score_min += (min_a[j] <= k ? min_a[j]*(min_a[j]+1)/2 : k*(k+1)/2)
  k -= min_a[j]
  j+=1
end

max_a, k, score_max = a.sort.reverse, n, 0, 0
el = max_a[0]
c = max_a.count el
while k > 0
  score_max += (c <= k ? el*c : el*k)
  el -= 1
  k -= c
  if max_a[c] == el
    while c < m and a[c] == el
      c+=1
    end
  end
end

puts "#{score_max} #{score_min}"

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

min_a, k, j, score_min = a.sort, n, 0, 0
while k > 0
  score_min += (min_a[j] <= k ? min_a[j]*(min_a[j]+1)/2 : min_a[j]*(min_a[j]+1)/2-(min_a[j]-k)*(min_a[j]-k+1)/2)
  k -= min_a[j]
  j+=1
end

max_a, k, score_max = a.sort.reverse, n, 0, 0
el = max_a[0]
c = max_a.count el
while k > 0
  score_max += (c <= k ? el*c : el*k)
  el -= 1
  k -= c
  if max_a[c] == el
    while c < m and a[c] == el
      c+=1
    end
  end
end

puts "#{score_max} #{score_min}"

n,m = gets.chomp.split.collect{|i| i.to_i}
seats = gets.chomp.split.collect{|i| i.to_i}.sort

minz = 0
mint = 0
nplanes = seats.size
0.upto(nplanes-1) do |i|
    s = seats[i]
    while mint!=n and s!=0
        minz += s
        s -= 1
        mint += 1
    end
    break if mint == n
end
maxz = 0
maxt = 0
seats = seats.reverse
i = 0
while maxt != n
    if seats[i] > 0 then
        maxz += seats[i]
        seats[i] -= 1
        maxt += 1
    end
    i += 1
    i %= nplanes
end

puts "#{maxz} #{minz}"

n,m = gets.chomp.split.collect{|i| i.to_i}
seats = gets.chomp.split.collect{|i| i.to_i}.sort

minz = 0
mint = 0
nplanes = seats.size
0.upto(nplanes-1) do |i|
    s = seats[i]
    while mint!=n and s!=0
        minz += s
        s -= 1
        mint += 1
    end
    break if mint == n
end
maxz = 0
maxt = 0
seats = seats.reverse
i = 0
while maxt != n
    while seats[i] >= seats[(i+1)%nplanes]  and maxt!=n
        maxz += seats[i]
        seats[i] -= 1
        maxt += 1
    end
    break if maxt == n
    i += 1
    i %= nplanes
end

puts "#{maxz} #{minz}"


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

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

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

def get_right_count(array, value)
  n, sum = array.size, array[-1]
  result = Array.new(n, 0)
  result[-1] = 1 if sum == value
  (array.size - 2).downto(0) do |index|
    sum += array[index]
    result[index] += result[index + 1]
    result[index] += 1 if sum == value
  end
  result
end

n = gets.to_i
values = gets.split.map { |v| v.to_i }
sum, result = values.inject { |s, v| s + v }, 0

if sum % 3 == 0
  sum /= 3
  left_sum, count = 0, get_right_count(values, sum) + [0, 0]
  values.each_index do |index|
    left_sum += values[index]
    result += count[index + 2] if left_sum == sum
  end
end

puts result

def solve(a)
    sum = a.inject { |s, x| s + x }
    return 0 unless sum % 3 == 0
    one_third = sum / 3
    a.pop
    local = 0
    thirds_count = 0
    ans = 0
    a.each do |x|
        local += x
        ans += thirds_count if local == one_third * 2
        thirds_count += 1 if local == one_third
    end
    return ans
end

gets
a = gets.split(' ').map { |x| x.to_i }
#a = [1, 2, 3, 3]
puts solve(a)

def get_right_count(array, value)
  n, sum = array.size, 0
  result = Array.new(n, 0)
  result[-1] = 1 if array[-1] == value
  (array.size - 2).downto(0) do |index|
    sum += array[index]
    result[index] += result[index + 1]
    result[index] += 1 if sum == value
  end
  result
end

n = gets.to_i
values = gets.split.map { |v| v.to_i }
sum, result = values.inject { |s, v| s + v }, 0

if sum % 3 == 0
  sum /= 3
  left_sum, count = 0, get_right_count(values, sum) + [0, 0]
  values.each_index do |index|
    left_sum += values[index]
    result += count[index + 2] if left_sum == sum
  end
end

puts result


Roma works in a company that sells TVs. Now he has to prepare a report for the last year.Roma has got a list of the company's incomes. The list is a sequence that consists of n integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly k changes of signs of several numbers in the sequence. He can also change the sign of a number one, two or more times.The operation of changing a number's sign is the operation of multiplying this number by -1.Help Roma perform the changes so as to make the total income of the company (the sum of numbers in the resulting sequence) maximum. Note that Roma should perform exactly k changes.

The first line contains two integers n and k (1 ≤ n, k ≤ 105), showing, how many numbers are in the sequence and how many swaps are to be made. The second line contains a non-decreasing sequence, consisting of n integers ai (|ai| ≤ 104). The numbers in the lines are separated by single spaces. Please note that the given sequence is sorted in non-decreasing order.

In the single line print the answer to the problem — the maximum total income that we can obtain after exactly k changes.

NoteIn the first sample we can get sequence [1, 1, 1], thus the total income equals 3.In the second test, the optimal strategy is to get sequence [-1, 1, 1], thus the total income equals 1.

n, k = gets.split(' ').map{|i| i.to_i}
a = gets.split(' ').map{|i| i.to_i}
i = 0
while k > 0
	if i < a.length and a[i] < 0
		a[i] *= -1
		k -= 1
		i += 1
	else
		break
	end
end

sum = a.reduce{|a, b| a+b}
sum -= (k%2) * a.min * 2
puts sum

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

n, k = gets.chomp.split(" ").map{|n| n.to_i}
sequence = gets.chomp.split(" ").map{|n| n.to_i}
sequence.sort!

i = 0
k.times do
  break if i >= n or sequence[i] >= 0

  sequence[i] *= -1
  i += 1
end

if (k - i) > 0
  sequence.sort!
  if (k - i) % 2 == 1
    sequence[0] *= -1
  end
end

puts sequence.inject{|sum, i| sum+= i}

n,k=gets.split(' ').map(&:to_i)
a=gets.split(' ').map(&:to_i)
neg=a.count {|i| i<0}
[k,neg].min.times {|i| a[i]=-a[i]}
min=a.min_by {|i| i.abs}
sum=a.inject(:+)
k-=neg
if k>0 && k%2==1
  sum-=2*min
end
puts sum

def run
  lines = ARGF.readlines

  n, k = lines.shift.chomp.split(" ").map {|x| x.to_i }
  vals = lines.shift.chomp.split(" ").map {|x| x.to_i }

  vals.length.times do |i|
    if vals[i] < 0
      vals[i] *= -1
      k -= 1
    else
      if k % 2 == 1
        if vals[i - 1] < vals[i]
          vals[i - 1] *= -1
        else
          vals[i] *= -1
        end
      end
      k = 0
    end

    break if k == 0
  end

  vals[vals.length - 1] *= -1 if k % 2 == 1

  puts vals.reduce(0) { |sum, n| sum + n }
end

run if $0 == __FILE__

n,k = gets.chomp.split(" ").collect! {|x| x.to_i}
line = gets.chomp.split(" ").collect! {|x| x.to_i}

s = 0
min = 10001
line.sort!
line.each {|x|
 if x<0
	if k>0
		k -= 1
		s += x.abs
	else
		s += x
	end
	min = x.abs
 else
	if  min > x
		min = x
	end
	s += x
 end
}

if k%2 == 1
	s -= (2*min)
end

puts s

n, k = gets.split.collect{|i| i.to_i}
a = gets.split.collect{|i| i.to_i}.sort
ans = 0
cnt = 0
a.each{|i| cnt+=1 if i<=0}
if cnt>=k
    n.times do |i|
        if i < k
            ans += -a[i]
        else
            ans += a[i]
        end
    end
else
    k -= cnt
    a = a.collect{|i| i.abs}
    if k.odd?
        ans = a.inject{|sum, i| sum+=i}-2*a.min
    else
        ans = a.inject{|sum, i| sum+=i}
    end
end
puts ans

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

neg=a.count {|i| i<0}
[k,neg].min.times {|i| a[i]=-a[i]}

min=a.min_by {|i| i.abs}
sum=a.inject(:+)

k-=neg
sum-=2*min if k>0 && k%2==1

p sum

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

neg=a.count {|i| i<0}
[k,neg].min.times {|i| a[i]=-a[i]}

sum=a.inject(:+)

k-=neg
sum-=2*a.min if k>0 && k%2==1

p sum

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

neg=a.count {|i| i<0}
[k,neg].min.times {|i| a[i]=-a[i]}

min=a.min_by {|i| i.abs}
sum=a.inject(:+)

k-=neg
if k>0 && k%2==1
  sum-=2*min
end

p sum

n,k = gets.split.map &:to_i
a = gets.split.map &:to_i
counter = 0
a.each {|el| counter+=1 if el < 0}
null_position = a.index(0)
pre_null = nil

if counter >= k
  k.times do |index|
    a[index] = -a[index]
  end
elsif null_position
  a.each_with_index do |el,index|
    if el<0
      a[index] *= -1
    else
      break
    end
  end
else
 a.each_with_index do |el,index|
    if el<0
      a[index] = -el
    else
      pre_null = index-1
      break
    end
  end
  if (k-counter) % 2 != 0
    a[a.index(a.min)] *= -1
  end

end
puts a.inject{|sum, el| sum+el}

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

n, k = read_next_line
a = read_next_line
i, p = 0, [n, k].min
while i < p && a[i] < 0
  a[i] = -a[i]
  i += 1
end
if (k - i).odd?
  i -= 1 if i == n || (i > 0 && a[i - 1] < a[i])
  a[i] = -a[i]
end
puts a.inject(:+)

BEGIN{
	def get_line_int()
		return gets.split.map(&:to_i)
	end
	def main()
		n, k = get_line_int
		a = get_line_int
		sum = 0
		a.each_with_index do |x,i|
			break if k == 0
			if x < 0 then
				a[i] *= -1
				k -= 1
			else
				break
			end
		end
		a.each do |x|
			sum += x
		end
		if k != 0 then
			sum -= a.min * 2 if k % 2 == 1
		end
		puts sum
	end
	Test_case = 1
	Test_case.times do
		main()
	end
}

a = gets.split(" ").collect{|x| x.to_i}
n = a[0]
k = a[1]

a = gets.split(" ").collect{|x| x.to_i}
result = 0

a.each_index { |i|
	if a[i] < 0 and k > 0
		a[i] *= -1
		k -= 1
	end
}

result = a.inject{|result, x| result += x}

if k % 2 == 1
	m = a.min { |a, b| a.abs <=> b.abs }
	result -= 2*m
end

puts result

n, k = gets.chomp.split.map(&:to_i)
puts gets.chomp.split.map(&:to_i).map { |x| (k > 0 && x < 0) ? (k -= 1; -x) : x }.sort.tap { |x| k = k % 2 }.map { |x|
	k > 0 ? (k = 0; -x ) : x }.reduce(:+)

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

n, k = gets.chomp.split(" ").map{|n| n.to_i}
sequence = gets.chomp.split(" ").map{|n| n.to_i}
sequence.sort!

idx = 0

k.times do
  if idx < n
    sequence[idx] *= -1
    idx += 1
  else
    sequence.sort!
    idx = 0
  end
end

puts sequence.inject{|sum, i| sum+= i}

def run
  lines = ARGF.readlines

  n, k = lines.shift.chomp.split(" ").map {|x| x.to_i }
  vals = lines.shift.chomp.split(" ").map {|x| x.to_i }

  vals.length.times do |i|
    if vals[i] < 0
      vals[i] *= -1
      k -= 1
    else
      if vals[i - 1] < vals[i]
        vals[i - 1] *= -1
      else
        vals[i] *= -1
      end
      k = 0
    end

    break if k == 0
  end

  puts vals.reduce(0) { |sum, n| sum + n }
end

run if $0 == __FILE__

def run
  lines = ARGF.readlines

  n, k = lines.shift.chomp.split(" ").map {|x| x.to_i }
  vals = lines.shift.chomp.split(" ").map {|x| x.to_i }

  vals.length.times do |i|
    if vals[i] < 0
      vals[i] *= -1
      k -= 1
    else
      if vals[i - 1].abs < vals[i].abs
        vals[i - 1] *= -1
      else
        vals[i] *= -1
      end
      k = 0
    end

    break if k == 0
  end

  puts vals.reduce(0) { |sum, n| sum + n }
end

run if $0 == __FILE__

def run
  lines = ARGF.readlines

  n, k = lines.shift.chomp.split(" ").map {|x| x.to_i }
  vals = lines.shift.chomp.split(" ").map {|x| x.to_i }

  vals.length.times do |i|
    if vals[i] < 0
      vals[i] *= -1
      k -= 1
    else
      if k % 2 == 1
        if vals[i - 1] < vals[i]
          vals[i - 1] *= -1
        else
          vals[i] *= -1
        end
      end
      k = 0
    end

    break if k == 0
  end

  puts vals.reduce(0) { |sum, n| sum + n }
end

run if $0 == __FILE__

n,k = gets.chomp.split(" ").collect! {|x| x.to_i}
line = gets.chomp.split(" ").collect! {|x| x.to_i}

s = 0
min = 0
line.each {|x|
 if x<0
	if k>0
		k -= 1
		s += x.abs
	else
		s += x
	end
	min = x.abs
 else
	if  min > x
		min = x
	end
	s += x
 end
}

if k%2 == 1
	s -= (2*min)
end

puts s

n,k = gets.chomp.split(" ").collect! {|x| x.to_i}
line = gets.chomp.split(" ").collect! {|x| x.to_i}

s = 0
min = 0
line.sort!
line.each {|x|
 if x<0
	if k>0
		k -= 1
		s += x.abs
	else
		s += x
	end
	min = x.abs
 else
	if  min > x
		min = x
	end
	s += x
 end
}

if k%2 == 1
	s -= (2*min)
end

puts s

n,k = gets.chomp.split(" ").collect! {|x| x.to_i}
line = gets.chomp.split(" ").collect! {|x| x.to_i}

s = 0
min = 0
line.each {|x|
 if x<0
	if k>0
		k -= 1
		s += x.abs
	else
		s += x
	end
	min = x.abs
 else
	if  min > x
		min = x
	end
	s += x
 end
}

if k%2 == 1
	s -= min
end

puts s

n, k = gets.split.collect{|i| i.to_i}
a = gets.split.collect{|i| i.to_i}.sort
ans = 0
n.times do |i|
    if i < k
        ans += -a[i]
    else
        ans += a[i]
    end
end
puts ans

n,k=gets.split.map(&:to_i)
a=gets.split.map(&:to_i)
k%=2*n

[k,n].min.times {|i| a[i]=-a[i]}
k-=n
(-1..-k).each {|i| a[i]=-a[i]} if k>0

puts a.inject(:+)

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

k.times do |i|
  if i<n
    case
    when a[i] < 0 then a[i]=-a[i]
    when a[i]==0
      break
    else
      a[0]=-a[0]
    end
  else
    a[0]=-a[0]
  end
end

puts a.inject(:+)

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

k.times do |i|
  if i>=n
    a[0]=-a[0]
  elsif a[i]<0
    a[i]=-a[i]
  elsif a[i]==0
    break
  else
    a[0]=-a[0]
  end
end

puts a.inject(:+)

n,k=gets.split.map(&:to_i)
a=gets.split.map(&:to_i)
k.times {|i| a[i%n]=-a[i%n]}
puts a.inject(:+)

a = gets.split(" ").collect{|x| x.to_i}
n = a[0]
k = a[1]

a = gets.split(" ").collect{|x| x.to_i}
result = 0
minus = 0

a.sort!

a.each{|x|
	if x < 0
		minus += 1
	end
}

if minus >= k
	a.reverse_each { |e|
		if e < 0 and k > 0
			e *= -1
			k -= 1
		end
		result += e
	}
else
	a.inject{|result, x| result += x}
	k -= n
	if k % 2 == 1
		result -= a[0]
	end
end

puts result


Vasiliy has an exam period which will continue for n days. He has to pass exams on m subjects. Subjects are numbered from 1 to m.About every day we know exam for which one of m subjects can be passed on that day. Perhaps, some day you can't pass any exam. It is not allowed to pass more than one exam on any day. On each day Vasiliy can either pass the exam of that day (it takes the whole day) or prepare all day for some exam or have a rest. About each subject Vasiliy know a number ai — the number of days he should prepare to pass the exam number i. Vasiliy can switch subjects while preparing for exams, it is not necessary to prepare continuously during ai days for the exam number i. He can mix the order of preparation for exams in any way.Your task is to determine the minimum number of days in which Vasiliy can pass all exams, or determine that it is impossible. Each exam should be passed exactly one time.

The first line contains two integers n and m (1 ≤ n, m ≤ 105) — the number of days in the exam period and the number of subjects.  The second line contains n integers d1, d2, ..., dn (0 ≤ di ≤ m), where di is the number of subject, the exam of which can be passed on the day number i. If di equals 0, it is not allowed to pass any exams on the day number i.  The third line contains m positive integers a1, a2, ..., am (1 ≤ ai ≤ 105), where ai is the number of days that are needed to prepare before passing the exam on the subject i.

Print one integer — the minimum number of days in which Vasiliy can pass all exams. If it is impossible, print -1.

NoteIn the first example Vasiliy can behave as follows. On the first and the second day he can prepare for the exam number 1 and pass it on the fifth day, prepare for the exam number 2 on the third day and pass it on the fourth day.In the second example Vasiliy should prepare for the exam number 3 during the first four days and pass it on the fifth day. Then on the sixth day he should prepare for the exam number 2 and then pass it on the seventh day. After that he needs to prepare for the exam number 1 on the eighth day and pass it on the ninth day. In the third example Vasiliy can't pass the only exam because he hasn't anough time to prepare for it.

def func x
    return true if x>=@n
    h={}
    i=x
    s=0
    while i>=0
        k=@d[i]
        if k>=0 and !h[k]
            h[k]=1
            s+=@a[k]
        elsif s>0
            s-=1
        end
        i-=1
    end
    h.size==@m and s<=0
end

@n, @m=gets.split.map &:to_i
@d=gets.split.map{|e| e.to_i-1}
@a=gets.split.map &:to_i

x=1<<32
res=2*x-1
while x>0
    res-=x if func res-x
    x>>=1
end

puts (res<@n ? res+1 : -1)

def func x
    return true if x>=@n
    i, s, h=x, 0, {}
    while i>=0
        k=@d[i]
        k<0 or h[k] ? s=s>0 ? s-1 : 0 : (h[k]=1; s+=@a[k])
        i-=1
    end
    h.size==@m and s==0
end

@n, @m=gets.split.map &:to_i
@d=gets.split.map{|e| e.to_i-1}
@a=gets.split.map &:to_i

x=1<<32
res=2*x-1
while x>0
    res-=x if func res-x
    x>>=1
end

puts (res<@n ? res+1 : -1)

def func x
    return true if x>=@n
    h={}
    i=x
    p=x
    while i>=0
        k=@d[i]
        if k>=0 and !h[k]
            h[k]=1
            return false if @a[k]>p
            p-=@a[k]
        else
            p-=1
        end
        i-=1
    end
    h.size==@m
end

@n, @m=gets.split.map &:to_i
@d=gets.split.map{|e| e.to_i-1}
@a=gets.split.map &:to_i

x=1<<32
res=2*x-1
while x>0
    res-=x if func res-x
    x>>=1
end

puts (res<@n ? res+1 : -1)

def func x
    return true if x>=@n
    h={}
    i=x
    s=0
    while i>=0
        k=@d[i]
        if k>=0 and !h[k]
            h[k]=1
            s+=@a[k]
        else
            s-=1
        end
        i-=1
    end
    s<=0
end

@n, @m=gets.split.map &:to_i
@d=gets.split.map{|e| e.to_i-1}
@a=gets.split.map &:to_i

x=1<<32
res=2*x-1
while x>0
    res-=x if func res-x
    x>>=1
end

puts (res<@n ? res+1 : -1)

def func x
    return true if x>=@n
    h={}
    i=x
    s=0
    while i>=0
        k=@d[i]
        if k>=0 and !h[k]
            h[k]=1
            s+=@a[k]
        else
            s-=1
        end
        i-=1
    end
    h.size==@m and s<=0
end

@n, @m=gets.split.map &:to_i
@d=gets.split.map{|e| e.to_i-1}
@a=gets.split.map &:to_i

x=1<<32
res=2*x-1
while x>0
    res-=x if func res-x
    x>>=1
end

puts (res<@n ? res+1 : -1)


Innopolis University scientists continue to investigate the periodic table. There are n·m known elements and they form a periodic table: a rectangle with n rows and m columns. Each element can be described by its coordinates (r, c) (1 ≤ r ≤ n, 1 ≤ c ≤ m) in the table.Recently scientists discovered that for every four different elements in this table that form a rectangle with sides parallel to the sides of the table, if they have samples of three of the four elements, they can produce a sample of the fourth element using nuclear fusion. So if we have elements in positions (r1, c1), (r1, c2), (r2, c1), where r1 ≠ r2 and c1 ≠ c2, then we can produce element (r2, c2).  Samples used in fusion are not wasted and can be used again in future fusions. Newly crafted elements also can be used in future fusions.Innopolis University scientists already have samples of q elements. They want to obtain samples of all n·m elements. To achieve that, they will purchase some samples from other laboratories and then produce all remaining elements using an arbitrary number of nuclear fusions in some order. Help them to find the minimal number of elements they need to purchase.

The first line contains three integers n, m, q (1 ≤ n, m ≤ 200 000; 0 ≤ q ≤ min(n·m, 200 000)), the chemical table dimensions and the number of elements scientists already have. The following q lines contain two integers ri, ci (1 ≤ ri ≤ n, 1 ≤ ci ≤ m), each describes an element that scientists already have. All elements in the input are different.

Print the minimal number of elements to be purchased.

NoteFor each example you have a picture which illustrates it.The first picture for each example describes the initial set of element samples available. Black crosses represent elements available in the lab initially.The second picture describes how remaining samples can be obtained. Red dashed circles denote elements that should be purchased from other labs (the optimal solution should minimize the number of red circles). Blue dashed circles are elements that can be produced with nuclear fusion. They are numbered in order in which they can be produced.Test 1We can use nuclear fusion and get the element from three other samples, so we don't need to purchase anything.  Test 2We cannot use any nuclear fusion at all as there is only one row, so we have to purchase all missing elements.  Test 3There are several possible solutions. One of them is illustrated below.Note that after purchasing one element marked as red it's still not possible to immidiately produce the middle element in the bottom row (marked as 4). So we produce the element in the left-top corner first (marked as 1), and then use it in future fusions.

class UnionFind
    attr_reader :set_size
    def initialize(n)
        @par = Array.new(n)
        n.times{ |i| @par[i] = i }
        @rank = Array.new(n, 0)
        @set_size = Array.new(n, 1)
    end

    def find(x)
        if @par[x] == x
            x
        else
            @par[x] = find(@par[x])
        end
    end

    def unite(x,y)
        x = find(x)
        y = find(y)
        return if x == y

        if @rank[x] < @rank[y]
            @par[x] = y
            @set_size[y] += @set_size[x]
        else
            @par[y] = x
            @set_size[x] += @set_size[y]
            @rank[x] += 1 if @rank[x] == @rank[y]
        end
    end

    def same?(x, y)
        find(x) == find(y)
    end
end

N, M, Q = gets.split.map(&:to_i)
uf = UnionFind.new(N+M)
Q.times do
    r, c = gets.split.map(&:to_i)
    uf.unite(r-1, c-1+N)
end
ans = -1
(N+M).times do |i|
    ans += 1 if uf.find(i) == i
end
puts ans


Little Artem likes electronics. He can spend lots of time making different schemas and looking for novelties in the nearest electronics store. The new control element was delivered to the store recently and Artem immediately bought it.That element can store information about the matrix of integers size n × m. There are n + m inputs in that element, i.e. each row and each column can get the signal. When signal comes to the input corresponding to some row, this row cyclically shifts to the left, that is the first element of the row becomes last element, second element becomes first and so on. When signal comes to the input corresponding to some column, that column shifts cyclically to the top, that is first element of the column becomes last element, second element becomes first and so on. Rows are numbered with integers from 1 to n from top to bottom, while columns are numbered with integers from 1 to m from left to right.Artem wants to carefully study this element before using it. For that purpose he is going to set up an experiment consisting of q turns. On each turn he either sends the signal to some input or checks what number is stored at some position of the matrix.Artem has completed his experiment and has written down the results, but he has lost the chip! Help Artem find any initial matrix that will match the experiment results. It is guaranteed that experiment data is consistent, which means at least one valid matrix exists.

The first line of the input contains three integers n, m and q (1 ≤ n, m ≤ 100, 1 ≤ q ≤ 10 000) — dimensions of the matrix and the number of turns in the experiment, respectively. Next q lines contain turns descriptions, one per line. Each description starts with an integer ti (1 ≤ ti ≤ 3) that defines the type of the operation. For the operation of first and second type integer ri (1 ≤ ri ≤ n) or ci (1 ≤ ci ≤ m) follows, while for the operations of the third type three integers ri, ci and xi (1 ≤ ri ≤ n, 1 ≤ ci ≤ m,  - 109 ≤ xi ≤ 109) are given. Operation of the first type (ti = 1) means that signal comes to the input corresponding to row ri, that is it will shift cyclically. Operation of the second type (ti = 2) means that column ci will shift cyclically. Finally, operation of the third type means that at this moment of time cell located in the row ri and column ci stores value xi.

Print the description of any valid initial matrix as n lines containing m integers each. All output integers should not exceed 109 by their absolute value. If there are multiple valid solutions, output any of them.

class Mat
	attr_reader :rows, :columns

	def initialize(rows, columns)
		@data = []
		@rows = rows
		@columns = columns
		for i in 1..rows
			row = []
			for j in 1..columns
				row << nil
			end
			@data << row
		end
	end

	def get(r, c)
		@data[r][c]
	end
	def set(r, c, value)
		@data[r][c] = value
	end

	def rotate_row(row, amt)
		amt += columns if amt < 0
		rev_horiz(row, 0, amt - 1)
		rev_horiz(row, amt, columns - 1)
		rev_horiz(row, 0, columns - 1)
	end

	def rotate_column(column, amt)
		amt += rows if amt < 0
		rev_vert(column, 0, amt - 1)
		rev_vert(column, amt, rows - 1)
		rev_vert(column, 0, rows - 1)
	end

	def print
		@data.each do |row|
			puts row.join(' ')
		end
	end

	private

	def rev_horiz(row, start, finish)
		while (start < finish)
			tmp = @data[row][start]
			@data[row][start] = @data[row][finish]
			@data[row][finish] = tmp
			start += 1
			finish -= 1
		end
	end

	def rev_vert(col, start, finish)
		while (start < finish)
			tmp = @data[start][col]
			@data[start][col] = @data[finish][col]
			@data[finish][col] = tmp
			start += 1
			finish -= 1
		end
	end
end

line = gets.chomp.split(' ')
n = line[0].to_i
m = line[1].to_i
q = line[2].to_i

RowOp = Struct.new(:row)
ColOp = Struct.new(:column)
SetOp = Struct.new(:row, :column, :value)

ops = []

for i in 1..q
	line = gets.chomp.split(' ')
	type = line[0].to_i
	case type
		when 1
			ops << RowOp.new(line[1].to_i - 1)
		when 2
			ops << ColOp.new(line[1].to_i - 1)
		else
			ops << SetOp.new(line[1].to_i - 1, line[2].to_i - 1, line[3].to_i)
	end
end

matrix = Mat.new(n, m)

ops.reverse!

for i in 0..ops.length-1
	case ops[i]
		when SetOp
			matrix.set(ops[i].row, ops[i].column, ops[i].value)
		when RowOp
			matrix.rotate_row(ops[i].row, -1)
		when ColOp
			matrix.rotate_column(ops[i].column, -1)
	end
end

for i in 0..matrix.rows-1
	for j in 0..matrix.columns-1
		matrix.set(i, j, 0) if matrix.get(i, j).nil?
	end
end

matrix.print

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

n, m, q = gis

a = arr2d n, m

v = []
n.times do |i|
    tv = []
    m.times do |j|
        tv << [i, j]
    end
    v << tv
end

q.times do
    t, *rcx = gis
    case t
    when 1
        r, * = rcx
        v[r - 1].rotate!
    when 2
        c, * = rcx
        ta = v[0][c - 1]
        (n - 1).times do |i|
            v[i][c - 1] = v[i + 1][c - 1]
        end
        v[n - 1][c - 1] = ta
    when 3
        r, c, x = rcx
        i, j = v[r - 1][c - 1]
        a[i][j] = x
    end
end

a.map{|z| puts z.map(&:to_s) * " " }

n, m, q = gets.chomp.split(" ").map(&:to_i)
a = Array.new(n).map{Array.new(m, 0)}
qs = []
while line = gets
  qs << line.split(" ").map(&:to_i)
end
qs.reverse.each do |ope|
  t = ope.shift
  if t == 1 then
    r = ope.shift - 1
    cyc = a[r].dup
    temp = cyc.pop
    cyc.unshift(temp)
    a[r] = cyc
  elsif t == 2 then
    c = ope.shift - 1
    cyc = a.map{|b| b[c]}
    temp = cyc.pop
    cyc.unshift(temp)
    n.times do |i|
      a[i][c] = cyc[i]
    end
  else
    r, c, x = ope
    r -= 1
    c -= 1
    a[r][c] = x
  end
end
a.each do |r|
  puts r.join(" ")
end

class Numeric
  def sign
    self<=>0
  end
end

class Array
  def loop_slide!(x=1)
    return false if self.length <= 1
    x = (x.abs % self.length) * (-x.sign)
    x += self.length if x < 0
    new_a = self.drop(x)+self.take(x)
    self.length.times{|i| self[i] = new_a[i]}
  end

  def loop_slide_simple!(x=1)  # x == 1 always
    new_a = self.drop(1)+self.take(1)
    self.length.times{|i| self[i] = new_a[i]}
  end

  def second
    self[1]
  end

  def third
    self[2]
  end
end

class XElement
  def initialize(n,m)
    @rows, @cols = n, m
    @mtx = Array.new
    n.times{@mtx.push Array.new(m, 0)}
  end

  def print_mtx
    @rows.times { |row|
      @cols.times { |col|
        print @mtx[row][col]
        print ' '
      }
      print "\n"
    }
    #print "\n"
  end

  def shift_row!(row_num)
    @mtx[row_num-1].loop_slide!
  end

  def shift_col!(col_num)
    column = Array.new
    @rows.times{|i| column.push(@mtx[i][col_num-1])}
    column.loop_slide!(1)
    @rows.times{|i| @mtx[i][col_num-1] = column[i]}
  end

  def set_num!(row, col, value)
    row, col = row-1, col-1
    @mtx[row][col] = value
  end

=begin
  def command!(args)
    COMMAND[args.first.to_s].call(args.drop(1))
  end
=end
end

COMMAND = {
    "1" => lambda{|x| $elem.shift_row!(x.first)},
    "2" => lambda{|x| $elem.shift_col!(x.first)},
    "3" => lambda{|x| $elem.set_num!(x.first, x.second, x.third)}
}

n,m,q, = gets.split.map{|x| x.to_i}
$elem = XElement.new(n,m)
stack = Array.new
q.times {|x| stack.push gets}
#$elem.print_mtx
q.times {|_|
  com = stack.pop.split.map{|x| x.to_i}
  COMMAND[com.first.to_s].call(com.drop(1))
}
$elem.print_mtx

class Mat
	attr_reader :rows, :columns

	def initialize(rows, columns)
		@data = []
		@rows = rows
		@columns = columns
		for i in 1..rows
			row = []
			for j in 1..columns
				row << nil
			end
			@data << row
		end
	end

	def get(r, c)
		@data[r][c]
	end
	def set(r, c, value)
		@data[r][c] = value
	end

	def rotate_row(row, amt)
		amt += rows if amt < 0
		rev_horiz(row, 0, amt - 1)
		rev_horiz(row, amt, rows - 1)
		rev_horiz(row, 0, rows - 1)
	end

	def rotate_column(column, amt)
		amt += columns if amt < 0
		rev_vert(column, 0, amt - 1)
		rev_vert(column, amt, columns - 1)
		rev_vert(column, 0, columns - 1)
	end

	def print
		@data.each do |row|
			puts row.join(' ')
		end
	end

	private

	def rev_horiz(row, start, finish)
		while (start < finish)
			tmp = @data[row][start]
			@data[row][start] = @data[row][finish]
			@data[row][finish] = tmp
			start += 1
			finish -= 1
		end
	end

	def rev_vert(col, start, finish)
		while (start < finish)
			tmp = @data[start][col]
			@data[start][col] = @data[finish][col]
			@data[finish][col] = tmp
			start += 1
			finish -= 1
		end
	end
end

line = gets.chomp.split(' ')
n = line[0].to_i
m = line[1].to_i
q = line[2].to_i

RowOp = Struct.new(:row)
ColOp = Struct.new(:column)
SetOp = Struct.new(:row, :column, :value)

ops = []

for i in 1..q
	line = gets.chomp.split(' ')
	type = line[0].to_i
	case type
		when 1
			ops << RowOp.new(line[1].to_i - 1)
		when 2
			ops << ColOp.new(line[1].to_i - 1)
		else
			ops << SetOp.new(line[1].to_i - 1, line[2].to_i - 1, line[3].to_i)
	end
end

matrix = Mat.new(n, m)

first_set = nil
for i in 0..ops.length-1
	next if !first_set && !ops[i].is_a?(SetOp)
	first_set ||= i

	case ops[i]
		when SetOp
			matrix.set(ops[i].row, ops[i].column, ops[i].value)
		when RowOp
			matrix.rotate_row(ops[i].row, 1)
		when ColOp
			matrix.rotate_column(ops[i].column, 1)
	end
end

rev_ops = ops[0..first_set-1].reverse
rev_ops.each do |op|
	case op
		when RowOp
			matrix.rotate_row(ops[i].row, -1)
		when ColOp
			matrix.rotate_column(ops[i].column, -1)
	end
end

for i in 0..matrix.rows-1
	for j in 0..matrix.columns-1
		matrix.set(i, j, 0) if matrix.get(i, j).nil?
	end
end

matrix.print

class Numeric
  def sign
    self<=>0
  end
end

class Array
  def loop_slide!(x=1)
    x = (x.abs % self.length) * (-x.sign)
    x += self.length if x < 0
    new_a = self.drop(x)+self.take(x)
    self.length.times{|i| self[i] = new_a[i]}
  end

  def second
    self[1]
  end

  def third
    self[2]
  end
end

class XElement
  def initialize(n,m)
    @rows, @cols = n, m
    @mtx = Array.new
    n.times{@mtx.push Array.new(m, 0)}
  end

  def print_mtx
    @rows.times { |row|
      @cols.times { |col|
        print @mtx[row][col]
        print ' '
      }
      print "\n"
    }
    #print "\n"
  end

  def shift_row!(row_num)
    @mtx[row_num-1].loop_slide!
  end

  def shift_col!(col_num)
    column = Array.new
    @cols.times{|i| column.push(@mtx[i][col_num-1])}
    column.loop_slide!(-1)
    @cols.times{|i| @mtx[i][col_num-1] = column[i]}
  end

  def set_num!(row, col, value)
    row, col = row-1, col-1
    @mtx[row][col] = value
  end

=begin
  def command!(args)
    COMMAND[args.first.to_s].call(args.drop(1))
  end
=end
end

COMMAND = {
    "1" => lambda{|x| $elem.shift_row!(x.first)},
    "2" => lambda{|x| $elem.shift_col!(x.first)},
    "3" => lambda{|x| $elem.set_num!(x.first, x.second, x.third)}
}

n,m,q, = gets.split.map{|x| x.to_i}
$elem = XElement.new(n,m)
stack = Array.new
q.times {|x| stack.push gets}
#$elem.print_mtx
q.times {|_|
  com = stack.pop.split.map{|x| x.to_i}
  COMMAND[com.first.to_s].call(com.drop(1))

}
$elem.print_mtx


Wilbur is playing with a set of n points on the coordinate plane. All points have non-negative integer coordinates. Moreover, if some point (x, y) belongs to the set, then all points (x', y'), such that 0 ≤ x' ≤ x and 0 ≤ y' ≤ y also belong to this set.Now Wilbur wants to number the points in the set he has, that is assign them distinct integer numbers from 1 to n. In order to make the numbering aesthetically pleasing, Wilbur imposes the condition that if some point (x, y) gets number i, then all (x',y') from the set, such that x' ≥ x and y' ≥ y must be assigned a number not less than i. For example, for a set of four points (0, 0), (0, 1), (1, 0) and (1, 1), there are two aesthetically pleasing numberings. One is 1, 2, 3, 4 and another one is 1, 3, 2, 4.Wilbur's friend comes along and challenges Wilbur. For any point he defines it's special value as s(x, y) = y - x. Now he gives Wilbur some w1, w2,..., wn, and asks him to find an aesthetically pleasing numbering of the points in the set, such that the point that gets number i has it's special value equal to wi, that is s(xi, yi) = yi - xi = wi.Now Wilbur asks you to help him with this challenge.

The first line of the input consists of a single integer n (1 ≤ n ≤ 100 000) — the number of points in the set Wilbur is playing with. Next follow n lines with points descriptions. Each line contains two integers x and y (0 ≤ x, y ≤ 100 000), that give one point in Wilbur's set. It's guaranteed that all points are distinct. Also, it is guaranteed that if some point (x, y) is present in the input, then all points (x', y'), such that 0 ≤ x' ≤ x and 0 ≤ y' ≤ y, are also present in the input. The last line of the input contains n integers. The i-th of them is wi ( - 100 000 ≤ wi ≤ 100 000) — the required special value of the point that gets number i in any aesthetically pleasing numbering.

If there exists an aesthetically pleasant numbering of points in the set, such that s(xi, yi) = yi - xi = wi, then print "YES" on the first line of the output. Otherwise, print "NO". If a solution exists, proceed output with n lines. On the i-th of these lines print the point of the set that gets number i. If there are multiple solutions, print any of them.

NoteIn the first sample, point (2, 0) gets number 3, point (0, 0) gets number one, point (1, 0) gets number 2, point (1, 1) gets number 5 and point (0, 1) gets number 4. One can easily check that this numbering is aesthetically pleasing and yi - xi = wi.In the second sample, the special values of the points in the set are 0,  - 1, and  - 2 while the sequence that the friend gives to Wilbur is 0, 1, 2. Therefore, the answer does not exist.

n = gets.chomp.to_i

diff = []
map_x = {}
map_y = {}

n.times do
   x,y = gets.chomp.split.map(&:to_i)
   d = y - x

   diff << d

   if(!map_x[d])

     map_x[d] = []
     map_y[d] = []
   end

   map_x[d] << x
   map_y[d] << y

end

ws = gets.chomp.split.map(&:to_i)

px = []
py = []

map_x.keys.each do |k|
  map_x[k].sort!.reverse!
end

map_y.keys.each do |k|
  map_y[k].sort!.reverse!
end

enable = true

if(diff.sort != ws.sort)

  enable = false
else
  ws.each do |d|
    if(!map_x[d] || map_x[d].empty?)
      enable = false;
      break;
    end
    px << map_x[d].pop
    py << map_y[d].pop

  end
end

if enable
  x = -1
  y = -1

  0.upto(px.size - 1) do |index|
    if(px[index] <= x && py[index] <= y)
      enable = false
      break;
    end
    x = px[index]
    y = py[index]
  end
end

if(enable)
  puts "YES"
  0.upto(px.size - 1) do |index|
    printf("%d %d\n", px[index], py[index]);
  end

else
  puts "NO"
end

require 'set'

def solve(a, s)
  front = Hash.new do |h, diff|
    h[diff] = diff.abs - 2
  end
  a = a.to_set

  pts = s.map do |diff|
    existing = front[diff]

    left = front[diff + 1]
    return -1 if left < existing
    right = front[diff - 1]
    return -1 if right < existing

    nw = existing + 2
    # y + x = nw
    # y - x = diff
    y = (nw + diff) / 2
    x = (nw - diff) / 2
    pt = [x,y]
    return -1 unless a.include?(pt)

    front[diff] = nw
    pt
  end
end

n = gets.to_i
a = Array.new(n) { gets.split.map(&:to_i) }
diffs = gets.split.map(&:to_i)

res = solve(a, diffs)
if res == -1
  puts 'NO'
else
  puts 'YES'
  puts res.map{|cs| cs.join(' ')}
end

points = Array.new { Array.new(3) }
a = Array.new { Array.new(2) }
n = STDIN.gets.to_i

def check_values(a, points, n)
  points.sort! do |x, y|
    if x[2] != y[2]
      x[2] <=> y[2]
    else
      x[0] <=> y[0]
    end
  end
  a.sort! do |x, y|
    if x[0] != y[0]
      x[0] <=> y[0]
    else
      x[1] <=> y[1]
    end
  end

  a.each_with_index do |val, i|
    if (val[0] != points[i][2])
      return false
    end
  end

  return true
end

def print_res(a, points, n)
  if !check_values(a, points, n)
    puts "NO"
    return
  else
    res = Array.new
    points.each_with_index do |point, i|
      res[a[i][1]] = point
    end

    #min_x = 0
    #min_y = 0
    #max_x = 0
    #max_y = 0
    #print "#{res} \n"
    max_l = 0
    max_r = 0
    #res.each_with_index do |r, i|
      #if (r[0] < min_x && r[1] < max_y) || (r[0] < max_x && r[1] < min_y)
      #  print "#{r[0]} #{r[1]} #{min_x} #{max_x} #{max_y} "
      #  puts "NO"
      #  return
      #else
      #  if r[0] > max_x
      #    max_x = r[0]
      #    min_y = r[1]
      #  end
      #  if r[1] > max_y
      #    max_y = r[1]
      #    min_x = r[0]
      #  end
     #   print "#{max_y} #{r[1]}     "
  #    for j in 0..i-1 do
  #      if r[0] < res[j][0] && r[1] < res[j][1]
  #        puts "NO"
  #        return
  #      end
  #    end
   #   cur_l = r[1] - r[0]
   #   cur_r = r[0] - r[1]
   #   if (max_l > cur_l && max_r > cur_r)
   #     puts "NO"
   #     return
   #   end
   #   max_l = cur_l if max_l >

    #end
    for i in 1..n - 1 do
      if res[i][0] <= res[i-1][0] && res[i][1] <= res[i-1][1]
        puts "NO"
        return
      end
    end

    puts "YES"
    res.each do |r|
      puts "#{r[0]} #{r[1]}"
    end
  end
end

for i in 0..n-1 do
  points.push(STDIN.gets.split(" ").to_a.map{|q| q.to_i})
  points[i][2] = points[i][1] - points[i][0]
end

STDIN.gets.split(" ").to_a.each_with_index do |num, i|
  a.push((num + " #{i}").split(" ").to_a.map{|q| q.to_i})
end

print_res(a, points, n)

n = gets.chomp.to_i

diff = []
map_x = {}
map_y = {}

n.times do
   x,y = gets.chomp.split.map(&:to_i)
   d = y - x

   diff << d

   if(!map_x[d])

     map_x[d] = []
     map_y[d] = []
   end

   map_x[d] << x
   map_y[d] << y

end

ws = gets.chomp.split.map(&:to_i)

px = []
py = []

map_x.keys.each do |k|
  map_x[k].sort!.reverse!
end

map_y.keys.each do |k|
  map_y[k].sort!.reverse!
end

enable = true

if(diff.sort != ws.sort)

  enable = false
else
  ws.each do |d|
    if(!map_x[d] || map_x[d].empty?)
      enable = false;
      break;
    end
    px << map_x[d].pop
    py << map_y[d].pop

  end
end

if enable
  x = -1
  y = -1

  0.upto(px.size - 1) do |index|
    if(px[index] < x && py[index] < y)
      puts "h3e";
      enable = false
      break;
    end
    x = px[index]
    y = py[index]
  end
end

if(enable)
  puts "YES"
  0.upto(px.size - 1) do |index|
    printf("%d %d\n", px[index], py[index]);
  end

else
  puts "NO"
end

n = gets.chomp.to_i

diff = []
map_x = {}
map_y = {}

n.times do
   x,y = gets.chomp.split.map(&:to_i)
   d = y - x

   diff << d

   if(!map_x[d])

     map_x[d] = []
     map_y[d] = []
   end

   map_x[d] << x
   map_y[d] << y

end

ws = gets.chomp.split.map(&:to_i)

px = []
py = []

map_x.keys.each do |k|
  map_x[k].sort!.reverse!
end

map_y.keys.each do |k|
  map_y[k].sort!.reverse!
end

enable = true

if(diff.sort != ws.sort)

  enable = false
else
  ws.each do |d|
    if(!map_x[d] || map_x[d].empty?)
      enable = false;
      break;
    end
    px << map_x[d].pop
    py << map_y[d].pop

  end
end

if enable
  x = -1
  y = -1

  0.upto(px.size - 1) do |index|
    if(px[index] < x && py[index] < y)
      enable = false
      break;
    end
    x = px[index]
    y = py[index]
  end
end

if(enable)
  puts "YES"
  0.upto(px.size - 1) do |index|
    printf("%d %d\n", px[index], py[index]);
  end

else
  puts "NO"
end

points = Array.new { Array.new(3) }
a = Array.new { Array.new(2) }
n = STDIN.gets.to_i

def check_values(a, points, n)
  points.sort! do |x, y|
    if x[2] != y[2]
      x[2] <=> y[2]
    else
      x[1] <=> y[1]
    end
  end
  a.sort! { |x, y| x[0] <=> y[0] }

  a.each_with_index do |val, i|
    if (val[0] != points[i][2])
      return false
    end
  end

  return true
end

def print_res(a, points, n)
  if !check_values(a, points, n)
    puts "NO"
    return
  else
    a.sort! { |x, y| x[0] <=> y[0] }
    res = Array.new
    points.each_with_index do |point, i|
      res[a[i][1]] = point
    end

    max_x = 0
    max_y = 0
    res.each do |r|
      if r[0] < max_x && r[1] < max_y
        puts "NO"
        return
      else
        max_x = r[0] if r[0] > max_x
        max_y = r[1] if r[1] > max_y
      end
    end

    puts "YES"
    res.each do |r|
      puts "#{r[0]} #{r[1]}"
    end
  end
end

for i in 0..n-1 do
  points.push(STDIN.gets.split(" ").to_a.map{|q| q.to_i})
  points[i][2] = points[i][1] - points[i][0]
end

STDIN.gets.split(" ").to_a.each_with_index do |num, i|
  a.push((num + " #{i}").split(" ").to_a.map{|q| q.to_i})
end

print_res(a, points, n)

points = Array.new { Array.new(3) }
a = Array.new { Array.new(2) }
n = STDIN.gets.to_i

def check_values(a, points, n)
  points.sort! do |x, y|
    if x[2] != y[2]
      x[2] <=> y[2]
    else
      x[1] <=> y[1]
    end
  end
  a.sort! { |x, y| x[0] <=> y[0] }

  a.each_with_index do |val, i|
    if (val[0] != points[i][2])
      return false
    end
  end

  return true
end

def print_res(a, points, n)
  if !check_values(a, points, n)
    puts "NO"
    return
  else
    a.sort! { |x, y| x[0] <=> y[0] }
    res = Array.new
    points.each_with_index do |point, i|
      res[a[i][1]] = point
    end

    max_x = 0
    max_y = 0
    res.each do |r|
      if r[0] < max_x && r[1] < max_y
        puts "NO"
        return
      else
        max_x = r[0] if r[0] > max_x
        max_y = r[1] if r[1] > max_y
      end
    end

    puts "Yes"
    res.each do |r|
      puts "#{r[0]} #{r[1]}"
    end
  end
end

for i in 0..n-1 do
  points.push(STDIN.gets.split(" ").to_a.map{|q| q.to_i})
  points[i][2] = points[i][1] - points[i][0]
end

STDIN.gets.split(" ").to_a.each_with_index do |num, i|
  a.push((num + " #{i}").split(" ").to_a.map{|q| q.to_i})
end

print_res(a, points, n)

points = Array.new { Array.new(3) }
a = Array.new { Array.new(2) }
n = STDIN.gets.to_i

def check_values(a, points, n)
  points.sort! do |x, y|
    if x[2] != y[2]
      x[2] <=> y[2]
    else
      x[0] <=> y[0]
    end
  end
  a.sort! do |x, y|
    if x[0] != y[0]
      x[0] <=> y[0]
    else
      x[1] <=> y[1]
    end
  end

  a.each_with_index do |val, i|
    if (val[0] != points[i][2])
      return false
    end
  end

  return true
end

def print_res(a, points, n)
  if !check_values(a, points, n)
    puts "NO"
    return
  else
    res = Array.new
    points.each_with_index do |point, i|
      res[a[i][1]] = point
    end

    max_x = 0
    max_y = 0
   # print "#{res} \n"
   # res.each do |r|
    #  if r[0] < max_x && r[1] < max_y
    #    print "#{r[0]} #{r[1]} #{max_x} #{max_y} "
    #    puts "NO"
    #    return
    #  else
    #    max_x = r[0] if r[0] > max_x
    #    max_y = r[1] if r[1] > max_y
    #    print "#{max_y} #{r[1]}     "
    #  end
    #end

    puts "YES"
    res.each do |r|
      puts "#{r[0]} #{r[1]}"
    end
  end
end

for i in 0..n-1 do
  points.push(STDIN.gets.split(" ").to_a.map{|q| q.to_i})
  points[i][2] = points[i][1] - points[i][0]
end

STDIN.gets.split(" ").to_a.each_with_index do |num, i|
  a.push((num + " #{i}").split(" ").to_a.map{|q| q.to_i})
end

print_res(a, points, n)

points = Array.new { Array.new(3) }
a = Array.new { Array.new(2) }
n = STDIN.gets.to_i

def check_values(a, points, n)
  points.sort! do |x, y|
    if x[2] != y[2]
      x[2] <=> y[2]
    else
      x[0] <=> y[0]
    end
  end
  a.sort! do |x, y|
    if x[0] != y[0]
      x[0] <=> y[0]
    else
      x[1] <=> y[1]
    end
  end

  a.each_with_index do |val, i|
    if (val[0] != points[i][2])
      return false
    end
  end

  return true
end

def print_res(a, points, n)
  if !check_values(a, points, n)
    puts "NO"
    return
  else
    res = Array.new
    points.each_with_index do |point, i|
      res[a[i][1]] = point
    end

    min_x = 0
    min_y = 0
    max_x = 0
    max_y = 0
    #print "#{res} \n"
    res.each do |r|
      if (r[0] < min_x && r[1] < max_y) && (r[0] < max_x && r[1] < max_y)
        #print "#{r[0]} #{r[1]} #{max_x} #{max_y} "
        puts "NO"
        return
      else
        if r[0] > max_x
          max_x = r[0]
          min_y = r[1]
        end
        if r[1] > max_y
          max_y = r[1]
          min_x = r[0]
        end
     #   print "#{max_y} #{r[1]}     "
      end
    end

    puts "YES"
    res.each do |r|
      puts "#{r[0]} #{r[1]}"
    end
  end
end

for i in 0..n-1 do
  points.push(STDIN.gets.split(" ").to_a.map{|q| q.to_i})
  points[i][2] = points[i][1] - points[i][0]
end

STDIN.gets.split(" ").to_a.each_with_index do |num, i|
  a.push((num + " #{i}").split(" ").to_a.map{|q| q.to_i})
end

print_res(a, points, n)

points = Array.new { Array.new(3) }
a = Array.new { Array.new(2) }
n = STDIN.gets.to_i

def check_values(a, points, n)
  points.sort! do |x, y|
    if x[2] != y[2]
      x[2] <=> y[2]
    else
      x[1] <=> y[1]
    end
  end
  #print points
  #puts
  a.sort! { |x, y| x[0] <=> y[0] }

  a.each_with_index do |val, i|
    if (val[0] != points[i][2])
      return false
    end
  end

  return true
end

def print_res(a, points, n)
  if !check_values(a, points, n)
    puts "NO"
    return
  else
    res = Array.new
    points.each_with_index do |point, i|
      res[a[i][1]] = point
    end

    max_x = 0
    max_y = 0
    res.each do |r|
      if r[0] < max_x && r[1] < max_y
        puts "NO"
        return
      else
        max_x = r[0] if r[0] > max_x
        max_y = r[1] if r[1] > max_y
      end
    end

    puts "YES"
    res.each do |r|
      puts "#{r[0]} #{r[1]}"
    end
  end
end

for i in 0..n-1 do
  points.push(STDIN.gets.split(" ").to_a.map{|q| q.to_i})
  points[i][2] = points[i][1] - points[i][0]
end

STDIN.gets.split(" ").to_a.each_with_index do |num, i|
  a.push((num + " #{i}").split(" ").to_a.map{|q| q.to_i})
end

print_res(a, points, n)


Highway 201 is the most busy street in Rockport. Traffic cars cause a lot of hindrances to races, especially when there are a lot of them. The track which passes through this highway can be divided into $$$n$$$ sub-tracks. You are given an array $$$a$$$ where $$$a_i$$$ represents the number of traffic cars in the $$$i$$$-th sub-track. You define the inconvenience of the track as $$$\sum\limits_{i=1}^{n} \sum\limits_{j=i+1}^{n} \lvert a_i-a_j\rvert$$$, where $$$|x|$$$ is the absolute value of $$$x$$$. You can perform the following operation any (possibly zero) number of times: choose a traffic car and move it from its current sub-track to any other sub-track.Find the minimum inconvenience you can achieve.

The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 10\,000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\leq n\leq 2\cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0\leq a_i\leq 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each test case, print a single line containing a single integer: the minimum inconvenience you can achieve by applying the given operation any (possibly zero) number of times.

NoteFor the first test case, you can move a car from the $$$3$$$-rd sub-track to the $$$1$$$-st sub-track to obtain $$$0$$$ inconvenience.For the second test case, moving any car won't decrease the inconvenience of the track.

t = gets.chomp.to_i

t.times do
  n = gets.chomp.to_i
  arr = gets.chomp.split(' ').map(&:to_i)
  sum = arr.reduce(&:+)
  rem = sum % arr.size
  print "#{rem * (arr.size - rem)}\n"
end


The Little Girl loves problems on games very much. Here's one of them.Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules:  The players move in turns; In one move the player can remove an arbitrary letter from string s.  If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't. Determine which player will win, provided that both sides play optimally well — the one who moves first or the one who moves second.

The input contains a single line, containing string s (1 ≤ |s|  ≤  103). String s consists of lowercase English letters.

In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.

s = gets.to_s.chomp
s_ = s.split(//).uniq
ans = 0
s_.each do |chr|
		ans += 1 if s.count(chr).odd?
end
if ans.odd? or ans.zero? then
	puts "First"
	else
		puts "Second"
end

s, ans = gets.to_s.chomp, 0
s_ = s.split(//).uniq
s_.each{|chr| ans += 1 if s.count(chr).odd?}
(ans.odd? or ans.zero?) ? (puts "First") : (puts "Second")

# -*- encoding: utf-8 -*-
chars = gets.chomp.split("")

hash = Hash.new 0
chars.each do |char|
  hash[char] += 1
end

odds = 0
hash.each do |key, value|
  odds += 1 if value % 2 == 1
end

puts (odds == 0 or odds % 2 == 1) ? "First" : "Second"

hash=Array.new(26,0)
gets.chomp.split('').each{ |i| hash[i.ord-97]+=1 }
ct=0
hash.each{ |i| ct+=1 if i&1==1 }
puts (ct==0 || ct&1!=0) ? "First" : "Second"

def is_palindrome?(word)
	odd_count = 0
	word.uniq.map do |x|
		odd_count = odd_count + 1 if word.count(x).odd?
	end
	if odd_count > 1
		false
	else
		true
	end
end

def remove_letter(stringArray)
	stringArray.uniq.map do |x|
		if stringArray.count(x) == 1
			stringArray.delete(x)
			puts stringArray
			return stringArray
		else
			return stringArray
		end
	end
end

def do_stuff(stringArray)
	if is_palindrome(stringArray)
		"win"
	else
		next_turn
	end
end

def test(word)
	odd_count = 0
	word.uniq.map do |x|
		odd_count = odd_count + 1 if word.count(x).odd?
	end
	if odd_count.odd? || odd_count <= 1
		puts "First"
	else
		puts "Second"
	end
end

string = "aabb"
stringArray = gets.chomp.split(//)

test(stringArray)

# coding: utf-8

s = gets.chomp.split(//)
co = Array.new(26) { 0 }
l = s.length
for c in s
    co[c.ord - 'a'.ord] += 1
end
turns = 0
odds = co.count { |c| c.odd? }
if odds > 1
    turns += odds - 1
end

if turns.even?
    puts "First"
else
    puts "Second"
end

# 각 턴에서 임의의 한 글자를 지울 수 있다
# 각 턴이 돌아오기 전 플레이어는 글자를 재배치하여
# 팰린드롬을 구성할 수 있다. 이러면 승리한다.
# 두 플레이어가 최적의 플레이를 수행할 때 누가 이길것인가?

# 팰린드롬을 구성하기 위해 최소로 지워야하는 문자수 = 턴 수
# 이 수에 따라 승패가 갈린다.
# 전체 문자는 reorder 될 수 있으므로 문자의 배열 순서는
# 중요하지 않다. 회문을 구성할 수 있는지 여부만 중요한듯

s = gets.strip

if s == s.reverse
	print :First
else
	ar = s.split('')

	letters = {}
	ar.each do |let|
		if letters[let]
			letters[let] += 1
		else
			letters[let] = 1
		end
	end

	sum = 0
	letters.each_value  do |num|
		sum += 1 if !num.even?
	end

	# p sum
	# p (sum-1).even?

	if sum == 0 || (sum-1).even?
		print :First
	else
		print :Second
	end
end

s = gets.chomp
char_count = Hash.new(0)
s.each_char do |c|
	char_count[c] += 1
end
odd_count = char_count.values.count{|a| a.odd? }
if odd_count == 1 || odd_count == 0
	first = true
elsif s.length % 2 == 0
	first = false
else
	first = true
end
puts first ? "First" : "Second"

s = gets.chomp
hash = {}
s.each_char { |ch|
	if !hash.has_key? ch
		hash[ch] = 1
	else
		hash[ch] +=1
	end
}

n = 0

hash.values.each { |v|
  if v%2==1
	n += 1
  end
}

k = n%2
if n==0
 k=1
end
puts (k==1) ? "First" : "Second"

class String
  def is_possible_palindrome?
    g = self.split('').inject(Hash.new(0)) { |h, e| h[e] += 1; h }
    odd = false
    g.values.each { |v|
      if v.odd?
        if odd
          return false
        else
          odd = true
        end
      end
    }
    true
  end
end

w = gets.chomp
puts(w.is_possible_palindrome? || w.size.odd? ? 'First' : 'Second')

# Codeforces Round #169
# Problem B -- Little Girl and Game
count = [0] * 26
gets.chomp.each_char do |c|
    count[c.ord - 'a'.ord] += 1
end
odds = count.count { |x| x % 2 == 1 }
puts (odds <= 1 or odds % 2 == 1) ? "First" : "Second"

s = gets.strip
a = Array.new(30, 0)
s.size.times do |i|
	a[ s[i].ord - 'a'.ord] += 1
end
ans = 0
26.times do |i|
	a[i] -= (a[i]/2)*2
	ans += a[i]
end
puts (ans>0 && ans%2==0) ? "Second" : "First"

n,k=gets.chomp.split.map(&:to_i)
m=[]
n.times do
	a,b=gets.chomp.split.map(&:to_i)
	if b>k
		m.push(a-b+k)
	else
		m.push(a)
	end
end
puts m.max

def is_palindrome?(word)
	odd_count = 0
	word.uniq.map do |x|
		odd_count = odd_count + 1 if word.count(x).odd?
	end
	if odd_count > 1
		false
	else
		true
	end
end

def remove_letter(stringArray)
	stringArray.uniq.map do |x|
		if stringArray.count(x) == 1
			stringArray.delete(x)
			puts stringArray
			return stringArray
		else
			return stringArray
		end
	end
end

def do_stuff(stringArray)
	if is_palindrome(stringArray)
		"win"
	else
		next_turn
	end
end

def test(word)
	odd_count = 0
	word.uniq.map do |x|
		odd_count = odd_count + 1 if word.count(x).odd?
	end
	if odd_count.odd?
		puts "First"
	else
		puts "Second"
	end
end

string = "abddddbca"
stringArray = gets.chomp.split(//)

test(stringArray)

s = gets.strip

if s == s.reverse
	print :First
else
	ar = s.split('')

	letters = {}
	ar.each do |let|
		if letters[let]
			letters[let] += 1
		else
			letters[let] = 1
		end
	end

	sum = 0
	letters.each_value  do |num|
		sum += 1 if !num.even?
	end

	# p sum

	if sum = 0 || !(sum-1).even?
		print :First
	else
		print :Second
	end
end

s = gets.strip

if s == s.reverse
	print :First
else
	ar = s.split('')

	letters = {}
	ar.each do |let|
		if letters[let]
			letters[let] += 1
		else
			letters[let] = 1
		end
	end

	sum = 0
	letters.each_value  do |num|
		sum += 1 if !num.even?
	end

	if sum = 0 || (sum-1).even?
		print :First
	else
		print :Second
	end
end

s = gets.strip

if s == s.reverse
	print :First
else
	ar = s.split('')

	letters = {}
	ar.each do |let|
		if letters[let]
			letters[let] += 1
		else
			letters[let] = 1
		end
	end

	sum = 0
	letters.each_value  do |num|
		sum += 1 if !num.even?
	end

	if (sum-1).even?
		print :First
	else
		print :Second
	end
end

s = gets.chomp
char_count = Hash.new(0)
s.each_char do |c|
	char_count[c] += 1
end
odd_count = char_count.values.count{|a| a.odd? }
if odd_count == 1
	first = true
elsif s.length % 2 == 0
	first = false
else
	first = true
end
puts first ? "First" : "Second"

class String
  def is_palindrome?
    self[0...size / 2] == self[-size / 2..-1].reverse
  end
end

w = gets.chomp
puts(w.is_palindrome? || w.size.odd? ? 'First' : 'Second')


During their New Year holidays, Alice and Bob play the following game using an array $$$a$$$ of $$$n$$$ integers:   Players take turns, Alice moves first.  Each turn a player chooses any element and removes it from the array.  If Alice chooses even value, then she adds it to her score. If the chosen value is odd, Alice's score does not change.  Similarly, if Bob chooses odd value, then he adds it to his score. If the chosen value is even, then Bob's score does not change. If there are no numbers left in the array, then the game ends. The player with the highest score wins. If the scores of the players are equal, then a draw is declared.For example, if $$$n = 4$$$ and $$$a = [5, 2, 7, 3]$$$, then the game could go as follows (there are other options):   On the first move, Alice chooses $$$2$$$ and get two points. Her score is now $$$2$$$. The array $$$a$$$ is now $$$[5, 7, 3]$$$.  On the second move, Bob chooses $$$5$$$ and get five points. His score is now $$$5$$$. The array $$$a$$$ is now $$$[7, 3]$$$.  On the third move, Alice chooses $$$7$$$ and get no points. Her score is now $$$2$$$. The array $$$a$$$ is now $$$[3]$$$.  On the last move, Bob chooses $$$3$$$ and get three points. His score is now $$$8$$$. The array $$$a$$$ is empty now.  Since Bob has more points at the end of the game, he is the winner. You want to find out who will win if both players play optimally. Note that there may be duplicate numbers in the array.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array $$$a$$$. The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the array $$$a$$$ used to play the game. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output on a separate line:    "Alice" if Alice wins with the optimal play;  "Bob" if Bob wins with the optimal play;  "Tie", if a tie is declared during the optimal play.

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

def solve
    n = gets.chomp.to_i
    ar = arline.sort.reverse
    odd = ar.select{|x| x%2 == 1}.sum
    alice = ar.zip(0..n).select{|x, y| y%2 == 0}.map{|x| x[0]}.sum

    case odd <=> alice
    when 0
        puts "Tie"
    when 1
        puts "Bob"
    when -1
        puts "Alice"
    end
end

tc = gets.chomp.to_i
(1..tc).each do
    solve
end

def solve()
  odds, evens = [], []
  n = gets.to_i
  nums = gets.chomp.split.map!(&:to_i)
  nums.each do |i|
    i.odd? ? odds.append(i) : evens.append(i)
  end
  odds.sort!
  evens.sort!
  alice_point = 0
  bob_point = 0
  alices_turn = true
  until (odds.empty?  && evens.empty?) do
    # puts "Size:#{odds.length}, #{evens.length}"
    if alices_turn
      if evens.empty?
        odds.pop
      elsif (not odds.empty?) and odds.last > evens.last
        odds.pop
      else
        alice_point += evens.pop
      end
    else
      if odds.empty?
        evens.pop
      elsif (not evens.empty?) and evens.last > odds.last
        evens.pop
      else
        bob_point += odds.pop
      end
    end
    alices_turn = !alices_turn
  end
  res = alice_point <=> bob_point
  if res == 1
    puts "Alice"
  elsif res == 0
    puts "Tie"
  else
    puts "Bob"
  end
end

tcase = gets.to_i
tcase.times do solve() end

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i).sort.reverse
	x, y = 0, 0
	a.each_with_index do |val, i|
		x += val if i.even? && val.even?
		y += val if i.odd? && val.odd?
	end
	puts x < y ? 'Bob' : x > y ? 'Alice' : 'Tie'
end

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map &:to_i
  a.sort!.reverse!
  res = [0, 0]
  a.each_with_index do |it, i|
    res[1] += it if it % 2 == 1 && i % 2 == 1
    res[0] += it if it % 2 == 0 && i % 2 == 0
  end
  puts res[0] > res[1] ? "Alice" : (res[0] < res[1] ? "Bob" : "Tie")
end

t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  arr = gets.chomp.split(' ').map(&:to_i)
  arr = arr.sort.reverse
  ch = 0
  a = b = 0
  arr.each do |el|
    if ch == 0 && el % 2 == 0
      a += el
    end
    if ch == 1 && el % 2 == 1
      b += el
    end
    ch = 1 - ch
  end
  case
  when a > b
    puts "Alice"
  when b > a
    puts "Bob"
  else
    puts "Tie"
  end
end

gets.to_i.times do
  n=gets.to_i
  a=gets.split.map(&:to_i).sort.reverse
  f=0
  s=0
  n.times do |i|
    if i.even?
      if a[i].even?
        f+=a[i]
      end
    else
      if a[i].odd?
        s+=a[i]
      end
    end
  end
  if f>s
    puts "Alice"
  elsif f<s
    puts "Bob"
  else
    puts "Tie"
  end
end


There is an infinite 2-dimensional grid. The robot stands in cell $$$(0, 0)$$$ and wants to reach cell $$$(x, y)$$$. Here is a list of possible commands the robot can execute:  move north from cell $$$(i, j)$$$ to $$$(i, j + 1)$$$;  move east from cell $$$(i, j)$$$ to $$$(i + 1, j)$$$;  move south from cell $$$(i, j)$$$ to $$$(i, j - 1)$$$;  move west from cell $$$(i, j)$$$ to $$$(i - 1, j)$$$;  stay in cell $$$(i, j)$$$. The robot wants to reach cell $$$(x, y)$$$ in as few commands as possible. However, he can't execute the same command two or more times in a row.What is the minimum number of commands required to reach $$$(x, y)$$$ from $$$(0, 0)$$$?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of testcases. Each of the next $$$t$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$0 \le x, y \le 10^4$$$) — the destination coordinates of the robot.

For each testcase print a single integer — the minimum number of commands required for the robot to reach $$$(x, y)$$$ from $$$(0, 0)$$$ if no command is allowed to be executed two or more times in a row.

NoteThe explanations for the example test:We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively.In the first test case, the robot can use the following sequence: NENENENENE.In the second test case, the robot can use the following sequence: NENENEN.In the third test case, the robot can use the following sequence: ESENENE0ENESE.In the fourth test case, the robot doesn't need to go anywhere at all.In the fifth test case, the robot can use the following sequence: E0E.

gets.to_i.times{
    x, y = gets.split.map &:to_i
    a, b = [0, 0]
    if x == y
        puts x*2
    else
        move = 0
        (
            move += 2
            x -= 1
            y -= 1
        ) while x > 0 && y > 0
        if x == 0 && y == 0
            puts move
        else
            move += 1
            if x > 0
                x -= 1
            else
                y -= 1
            end
            if x == 0 && y == 0
                puts move
            else
                (
                    x -= 2
                    move += 4
                ) while x > 1
                (
                    y -= 2
                    move += 4
                ) while y > 1
                if x == 1 || y == 1
                   move += 2
                end
                puts move
            end
        end
    end
}

def get_int
  gets.chomp.to_i
end

get_int.times do |i|
  x, y = gets.split.map(&:to_i)
  puts 2 * [x, y].max - 1 + ((x == y) ? 1 : 0)
end

t = gets.chomp.to_i
t.times do
  x, y = gets.chomp.split(' ').map(&:to_i).map{|el| el.abs}
  if (x - y).abs < 2
    puts x + y
  else
    x, y = y, x if x < y
    puts x + y + (x - y) - 1
  end
end

t = gets.chomp.to_i
t.times do
    x, y = gets.chomp.split(" ").map(&:to_i)
    big = [x,y].max
    small = [x,y].min
    sa = big - small
    if x == 0 && y == 0
        puts "0"
    elsif sa <= 1
        puts big + small
    else
        puts small * 2 + (big - small - 1)*2 + 1
    end
end

n = gets.to_i
n.times do
  x, y = gets.chomp!.split.map(&:to_i)
  x, y = y, x unless x >= y
  if x > y
    p y * 2 + ((x - y) * 2 - 1)
  else
    p y * 2
  end
end


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

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

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

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


You are given a string s consisting of lowercase Latin letters. Character c is called k-dominant iff each substring of s with length at least k contains this character c.You have to find minimum k such that there exists at least one k-dominant character.

The first line contains string s consisting of lowercase Latin letters (1 ≤ |s| ≤ 100000).

Print one number — the minimum value of k such that there exists at least one k-dominant character.

module Memoizer
  def memoize(methodname)
    raise ArgumentError, "statefull method [#{methodname}]should not be memoized" if methodname.match(/\!\z/)
    unbound_method = instance_method(methodname)
    raise ArgumentError, "method [#{methodname}] with argument cannot be memoized" if unbound_method.arity > 0
    memoized_object_name = "@_memoized_#{methodname}"
    define_method(methodname) do
      if(instance_variable_get(memoized_object_name).nil?)
        instance_variable_set(memoized_object_name, unbound_method.bind(self).call)
      end
      instance_variable_get(memoized_object_name)
    end
  end
end

class Array
  def enumerate(&block)
    self.zip(0..length).map(&block)
  end
end
class Problem
  def initialize(xs)
    @xs = xs
    @last_index = Array.new(30){ -1 }
    @longests = Array.new(30){ -1 }
  end

  def solve!
    @xs.split("").each.with_index do |x, i|
      p = x.ord - 'a'.ord
      distance = i - @last_index[p]
      @longests[p] = [@longests[p], distance].max
      @last_index[p] = i
    end
    l = @xs.length
    (0..26).each do |x|
      distance = l - @last_index[x]
      @longests[x] = [@longests[x], distance].max
    end
  end

  attr_reader(:longests)
  attr_reader(:last_index)
end

prob = Problem.new(gets.strip)
prob.solve!
print prob.longests.select{|x| x >= 0 }.min

def is_posible?(s, k)
    n = s.size
    return true if n == k
    chars = [0]*255
    s[0...k].split("").each{ |c| chars[c.ord] += 1 }
    i = 1

    while i+k <= n do
        chars[s[i+k-1].ord] += 1 if chars[s[i+k-1].ord] and chars[s[i+k-1].ord] > 0
        chars[s[i-1].ord] -= 1 if chars[s[i-1].ord]
        i += 1
    end

    chars.each do |v|
       return true if v > 0
    end
    false
end

def solution(s)
  beg = 1
  last = s.size - 1
  min_k = s.size

  while (beg <= last) do
     mid = (last + beg)/2

     if is_posible?(s, mid)
         min_k = mid
         last = mid - 1
     else
         beg = mid + 1
     end
  end
  min_k
end

puts solution(gets.strip())

def is_posible?(s, k)
    n = s.size
    return true if n == k
    chars = {}
    s[0...k].split("").uniq.each{ |c| chars[c] = 1 }
    i = 1

    while i+k < n do
        chars[s[i+k-1]] += 1 if chars[s[i+k-1]] and chars[s[i+k-1]] > 0
        chars[s[i-1]] -= 1 if chars[s[i-1]] and chars[s[i-1]] > 0
        i += 1
    end

    chars.each do |k,v|
       return true if v > 0
    end
    false
end

def solution(s)
  beg = 1
  last = s.size - 1
  min_k = s.size

  while (beg <= last) do
     mid = (last + beg)/2

     if is_posible?(s, mid)
         min_k = mid
         last = mid - 1
     else
         beg = mid + 1
     end
  end
  min_k
end

puts solution(gets.strip())

def is_posible?(s, k)
    n = s.size
    return true if n == k
    chars = [0]*255
    s[0...k].split("").each{ |c| chars[c.ord] += 1 }
    i = 1

    while i+k <= n do
        puts "#{chars[97..122]}"
        chars[s[i+k-1].ord] += 1 if chars[s[i+k-1].ord] and chars[s[i+k-1].ord] > 0
        chars[s[i-1].ord] -= 1 if chars[s[i-1].ord]
        i += 1
    end
    puts "#{chars[97..122]}"

    chars.each do |v|
       return true if v > 0
    end
    false
end

def solution(s)
  beg = 1
  last = s.size - 1
  min_k = s.size

  while (beg <= last) do
     mid = (last + beg)/2

     if is_posible?(s, mid)
         min_k = mid
         last = mid - 1
     else
         beg = mid + 1
     end
  end
  min_k
end

puts solution(gets.strip())

def is_posible?(s, k)
    n = s.size
    return true if n == k
    chars = [0]*255
    s[0...k].split("").each{ |c| chars[c.ord] += 1 }
    i = 1

    while i+k < n do
        chars[s[i+k-1].ord] += 1 if chars[s[i+k-1].ord] and chars[s[i+k-1].ord] > 0
        chars[s[i-1].ord] -= 1 if chars[s[i-1].ord]
        i += 1
    end

    chars.each do |v|
       return true if v > 0
    end
    false
end

def solution(s)
  beg = 1
  last = s.size - 1
  min_k = s.size

  while (beg <= last) do
     mid = (last + beg)/2

     if is_posible?(s, mid)
         min_k = mid
         last = mid - 1
     else
         beg = mid + 1
     end
  end
  min_k
end

puts solution(gets.strip())

def is_posible?(s, k)
    n = s.size
    chars = s[0...k].split("").uniq

    i = 0
    while i+k < n do
        chars.each do |c|
            chars.delete(c) if !s[i...(i+k)].include?(c)
        end
        return false if chars.size == 0
        i += 1
    end
    true
end

def solution(s)
  beg = 1
  last = s.size - 1
  min_k = s.size

  while (beg <= last) do
     mid = (last + beg)/2

     if is_posible?(s, mid)
         min_k = mid
         last = mid - 1
     else
        puts mid
         beg = mid + 1
     end
  end
  min_k
end

s = gets.strip()


Lunar New Year is approaching, and Bob is struggling with his homework – a number division problem.There are $$$n$$$ positive integers $$$a_1, a_2, \ldots, a_n$$$ on Bob's homework paper, where $$$n$$$ is always an even number. Bob is asked to divide those numbers into groups, where each group must contain at least $$$2$$$ numbers. Suppose the numbers are divided into $$$m$$$ groups, and the sum of the numbers in the $$$j$$$-th group is $$$s_j$$$. Bob's aim is to minimize the sum of the square of $$$s_j$$$, that is $$$$$$\sum_{j = 1}^{m} s_j^2.$$$$$$Bob is puzzled by this hard problem. Could you please help him solve it?

The first line contains an even integer $$$n$$$ ($$$2 \leq n \leq 3 \cdot 10^5$$$), denoting that there are $$$n$$$ integers on Bob's homework paper. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^4$$$), describing the numbers you need to deal with.

A single line containing one integer, denoting the minimum of the sum of the square of $$$s_j$$$, which is $$$$$$\sum_{i = j}^{m} s_j^2,$$$$$$ where $$$m$$$ is the number of groups.

NoteIn the first sample, one of the optimal solutions is to divide those $$$4$$$ numbers into $$$2$$$ groups $$$\{2, 8\}, \{5, 3\}$$$. Thus the answer is $$$(2 + 8)^2 + (5 + 3)^2 = 164$$$.In the second sample, one of the optimal solutions is to divide those $$$6$$$ numbers into $$$3$$$ groups $$$\{1, 2\}, \{1, 2\}, \{1, 2\}$$$. Thus the answer is $$$(1 + 2)^2 + (1 + 2)^2 + (1 + 2)^2 = 27$$$.

# Input
n = gets.to_i
a = gets.split.map { |i| i.to_i }

# Most effecient way: splitting into pairs from the middle

# Processing
a.sort!
sum = 0
(n / 2).times { |i| sum += (a[i] + a[n - 1 - i])**2 }

# Output
puts sum

DBG = true
n = gets.to_i
a = gets.split.map{|z| z.to_i}
  #a,b = gets.split
  #a = a.to_i
  #b = b.to_i

a.sort!
sum = 0
for i in 0...(n/2)
  sum += (a[i]+a[n-1-i])**2
end
puts "#{sum}"

n = gets.to_i
a = gets.split(" ").sort_by{|e| e.to_i}
r = 0
for i in 0..n/2-1
	r+=(a[i].to_i+a[n-1-i].to_i)**2
end
p r

gets
a=gets.split.map{|e|e.to_i}.sort
r=0
a.size.times{|i|r+=(a[i]+a[-i-1])**2}
p r/2

gets
a=gets.split.map{|e|e.to_i}.sort
r=0
(0..a.size/2-1).each{|i|r+=(a[i]+a[-i-1])**2}
p r

n = gets.to_i
a = gets.split(" ").map{|z| z.to_i}.sort
r = 0
for i in 0..n-1
	r+=(a[i]+a[n-1-i])**2
end
p r/2

n = gets.to_i
a = gets.split(" ")
for i in 0..n-1 do
	a[i] = a[i].to_i
end
a = a.sort
ans = 0
for i in 0..n/2-1 do
	ans+=(a[i]+a[n-1-i])*(a[i]+a[n-1-i])
end
p ans

gets
a = gets.split.map{|e| e.to_i}.sort
r=0
(0..a.size/2-1).each{|i|	r+=(a[i]+a[-i-1])**2}
p r

if File.exists?("input")
  $stdin = File.open("input")
  $stdout = File.open("output","w")
end

n = gets.to_i
arr = gets.chomp.split(" ").map(&:to_i).sort

k = n/2
s = 0

(0..k-1).each do |i|
	s += (arr[i]+arr[n-1-i])**2
end

puts s


It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days!When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last n days. So now he has a sequence a1, a2, ..., an, where ai is the sleep time on the i-th day.The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider k consecutive days as a week. So there will be n - k + 1 weeks to take into consideration. For example, if k = 2, n = 3 and a = [3, 4, 7], then the result is .You should write a program which will calculate average sleep times of Polycarp over all weeks.

The first line contains two integer numbers n and k (1 ≤ k ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).

Output average sleeping time over all weeks.  The answer is considered to be correct if its absolute or relative error does not exceed 10 - 6. In particular, it is enough to output real number with at least 6 digits after the decimal point.

NoteIn the third example there are n - k + 1 = 7 weeks, so the answer is sums of all weeks divided by 7.

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

n,k = scan
aa = scan

res = 0.0
l = 0
sum = 0
aa.each_index{|r|
    if r-l >= k
        res += sum
        sum -= aa[l]
        l+=1
    end
    sum += aa[r]
}
res += sum
res /= n-k+1

p res


The student council is preparing for the relay race at the sports festival.The council consists of $$$n$$$ members. They will run one after the other in the race, the speed of member $$$i$$$ is $$$s_i$$$. The discrepancy $$$d_i$$$ of the $$$i$$$-th stage is the difference between the maximum and the minimum running speed among the first $$$i$$$ members who ran. Formally, if $$$a_i$$$ denotes the speed of the $$$i$$$-th member who participated in the race, then $$$d_i = \max(a_1, a_2, \dots, a_i) - \min(a_1, a_2, \dots, a_i)$$$.You want to minimize the sum of the discrepancies $$$d_1 + d_2 + \dots + d_n$$$. To do this, you are allowed to change the order in which the members run. What is the minimum possible sum that can be achieved?

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2000$$$)  — the number of members of the student council. The second line contains $$$n$$$ integers $$$s_1, s_2, \dots, s_n$$$ ($$$1 \le s_i \le 10^9$$$)  – the running speeds of the members.

Print a single integer  — the minimum possible value of $$$d_1 + d_2 + \dots + d_n$$$ after choosing the order of the members.

NoteIn the first test case, we may choose to make the third member run first, followed by the first member, and finally the second. Thus $$$a_1 = 2$$$, $$$a_2 = 3$$$, and $$$a_3 = 1$$$. We have:  $$$d_1 = \max(2) - \min(2) = 2 - 2 = 0$$$.  $$$d_2 = \max(2, 3) - \min(2, 3) = 3 - 2 = 1$$$.  $$$d_3 = \max(2, 3, 1) - \min(2, 3, 1) = 3 - 1 = 2$$$. The resulting sum is $$$d_1 + d_2 + d_3 = 0 + 1 + 2 = 3$$$. It can be shown that it is impossible to achieve a smaller value.In the second test case, the only possible rearrangement gives $$$d_1 = 0$$$, so the minimum possible result is $$$0$$$.

MAXN = 2000

def calcd(a, i, j, cache)
  return 0 if i == j
  return a[j] - a[i] if i + 1 == j

  return cache[i * MAXN + j] if cache[i * MAXN + j]

  x = a[j] - a[i]
  x1 = cache[(i + 1) * MAXN + j + 0] || calcd(a, i + 1, j, cache)
  x2 = cache[i * MAXN + j - 1] || calcd(a, i, j - 1, cache)
  x += x1 < x2 ? x1 : x2
  cache[i * MAXN + j] = x
  return x
end

n = gets.to_s.split.map {|x| x.to_i }
s = gets.to_s.split.map {|x| x.to_i }.sort

printf("%d\n", calcd(s, 0, s.size - 1, [nil] * (MAXN * MAXN)))

def calcd(a)
  return 0 if a.size <= 1
  x = a[-1] - a[0]
  if a[1] - a[0] > a[-1] - a[-2]
    return x + calcd(a[1 .. -1])
  elsif a[1] - a[0] == a[-1] - a[-2]
    x1 = calcd(a[1 .. -1])
    x2 = calcd(a[0 .. -2])
    return x + [x1, x2].min
  else
    return x + calcd(a[0 .. -2])
  end
end

n = gets.to_s.split.map {|x| x.to_i }
s = gets.to_s.split.map {|x| x.to_i }.sort

p calcd(s)

def calcd(a)
  return 0 if a.size <= 1
  if a[1] - a[0] > a[-1] - a[-2]
    return a[-1] - a[0] + calcd(a[1 .. -1])
  else
    return a[-1] - a[0] + calcd(a[0 .. -2])
  end
end

n = gets.to_s.split.map {|x| x.to_i }
s = gets.to_s.split.map {|x| x.to_i }.sort

p calcd(s)

def calcd(a)
  sum = 0
  min = a[0]
  max = a[0]
  a.each do |x|
    min = x if x < min
    max = x if x > max
    sum += max - min
  end
  sum
end

def calcdx(s, m)
  calcd(s.sort {|a, b| (a - m).abs <=> (b - m).abs })
end

n = gets.to_s.split.map {|x| x.to_i }
s = gets.to_s.split.map {|x| x.to_i }

min = s.min
max = s.max + 1

best = calcdx(s, min)

while max - min > 0
  mid = (min + max) / 2
  tmp = calcdx(s, mid)
  if tmp < best
    best = tmp
    min = mid
  else
    max = mid
  end
end

printf("%d\n", best)