The game of Berland poker is played with a deck of $$$n$$$ cards, $$$m$$$ of which are jokers. $$$k$$$ players play this game ($$$n$$$ is divisible by $$$k$$$).At the beginning of the game, each player takes $$$\frac{n}{k}$$$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to $$$x - y$$$, where $$$x$$$ is the number of jokers in the winner's hand, and $$$y$$$ is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get $$$0$$$ points.Here are some examples:  $$$n = 8$$$, $$$m = 3$$$, $$$k = 2$$$. If one player gets $$$3$$$ jokers and $$$1$$$ plain card, and another player gets $$$0$$$ jokers and $$$4$$$ plain cards, then the first player is the winner and gets $$$3 - 0 = 3$$$ points;  $$$n = 4$$$, $$$m = 2$$$, $$$k = 4$$$. Two players get plain cards, and the other two players get jokers, so both of them are winners and get $$$0$$$ points;  $$$n = 9$$$, $$$m = 6$$$, $$$k = 3$$$. If the first player gets $$$3$$$ jokers, the second player gets $$$1$$$ joker and $$$2$$$ plain cards, and the third player gets $$$2$$$ jokers and $$$1$$$ plain card, then the first player is the winner, and he gets $$$3 - 2 = 1$$$ point;  $$$n = 42$$$, $$$m = 0$$$, $$$k = 7$$$. Since there are no jokers, everyone gets $$$0$$$ jokers, everyone is a winner, and everyone gets $$$0$$$ points. Given $$$n$$$, $$$m$$$ and $$$k$$$, calculate the maximum number of points a player can get for winning the game.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Then the test cases follow. Each test case contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 50$$$, $$$0 \le m \le n$$$, $$$2 \le k \le n$$$, $$$k$$$ is a divisors of $$$n$$$).

For each test case, print one integer — the maximum number of points a player can get for winning the game.

NoteTest cases of the example are described in the statement.

t = gets.to_i

1.upto t do
  n, m, k = gets.split.map(&:to_i)
  a = [m, n/k].min
  b = m - a
  puts (a - ((b + k - 2)/(k-1)))
end

cases = gets.to_i
res = []
cases.times do |i|
  n, m, k = gets.split.map(&:to_i)
  c = n/k
  if c >= m
    res << m
  else
    res << c - (m-c)/(k-1) - ( ((m-c)%(k-1) > 0) ? 1 : 0)
  end
end

res.each { |r| p r }

gets.to_i.times do
    n, m, k = gets.split.map &:to_i
    x = [n/k, m].min
    y = (m - x + k - 2)/(k - 1)
    puts x - y
end

gets.to_i.times do
  n, m, k = gets.split(' ').map(&:to_i)

  max_j = [m, n/k].min

  max_j -= (m - max_j).div(k-1) + ((m - max_j).modulo(k-1).zero? ? 0 : 1)

  puts max_j
end

t = gets.to_i

1.upto t do
  n, m, k = gets.split.map(&:to_i)
  if m == 0
    puts 0
  else
    if (n/k == 1)
      if m == 1
        puts 1
      else
        puts 0
      end
    else
      if (m > n/k)
        z = n/k
        y = m-z
        if y % (k-1) == 0
           puts (z - y/(k+1))
        else
           puts (z - (y/(k-1)+1))
        end
      else
        puts m
      end
    end
  end
end


Tanya has $$$n$$$ candies numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th candy has the weight $$$a_i$$$.She plans to eat exactly $$$n-1$$$ candies and give the remaining candy to her dad. Tanya eats candies in order of increasing their numbers, exactly one candy per day.Your task is to find the number of such candies $$$i$$$ (let's call these candies good) that if dad gets the $$$i$$$-th candy then the sum of weights of candies Tanya eats in even days will be equal to the sum of weights of candies Tanya eats in odd days. Note that at first, she will give the candy, after it she will eat the remaining candies one by one.For example, $$$n=4$$$ and weights are $$$[1, 4, 3, 3]$$$. Consider all possible cases to give a candy to dad:  Tanya gives the $$$1$$$-st candy to dad ($$$a_1=1$$$), the remaining candies are $$$[4, 3, 3]$$$. She will eat $$$a_2=4$$$ in the first day, $$$a_3=3$$$ in the second day, $$$a_4=3$$$ in the third day. So in odd days she will eat $$$4+3=7$$$ and in even days she will eat $$$3$$$. Since $$$7 \ne 3$$$ this case shouldn't be counted to the answer (this candy isn't good).  Tanya gives the $$$2$$$-nd candy to dad ($$$a_2=4$$$), the remaining candies are $$$[1, 3, 3]$$$. She will eat $$$a_1=1$$$ in the first day, $$$a_3=3$$$ in the second day, $$$a_4=3$$$ in the third day. So in odd days she will eat $$$1+3=4$$$ and in even days she will eat $$$3$$$. Since $$$4 \ne 3$$$ this case shouldn't be counted to the answer (this candy isn't good).  Tanya gives the $$$3$$$-rd candy to dad ($$$a_3=3$$$), the remaining candies are $$$[1, 4, 3]$$$. She will eat $$$a_1=1$$$ in the first day, $$$a_2=4$$$ in the second day, $$$a_4=3$$$ in the third day. So in odd days she will eat $$$1+3=4$$$ and in even days she will eat $$$4$$$. Since $$$4 = 4$$$ this case should be counted to the answer (this candy is good).  Tanya gives the $$$4$$$-th candy to dad ($$$a_4=3$$$), the remaining candies are $$$[1, 4, 3]$$$. She will eat $$$a_1=1$$$ in the first day, $$$a_2=4$$$ in the second day, $$$a_3=3$$$ in the third day. So in odd days she will eat $$$1+3=4$$$ and in even days she will eat $$$4$$$. Since $$$4 = 4$$$ this case should be counted to the answer (this candy is good). In total there $$$2$$$ cases which should counted (these candies are good), so the answer is $$$2$$$.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of candies. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the weight of the $$$i$$$-th candy.

Print one integer — the number of such candies $$$i$$$ (good candies) that if dad gets the $$$i$$$-th candy then the sum of weights of candies Tanya eats in even days will be equal to the sum of weights of candies Tanya eats in odd days.

NoteIn the first example indices of good candies are $$$[1, 2]$$$.In the second example indices of good candies are $$$[2, 3]$$$.In the third example indices of good candies are $$$[4, 5, 9]$$$.

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

a, b, c, d, s = 0, 0, 0, 0, 0

q.each.with_index do |e, i|
  c += e if i.even?
  d += e if i.odd?
end

q.each.with_index do |e, i|
  c -= e if i.even?
  d -= e if i.odd?

  s += 1 if a + c == b + d

  b += e if i.even?
  a += e if i.odd?
end

puts s

def good(sweets)
  count = 0
  evens = 0
  odds  = 0

  sweets.each_with_index do |x, i|
    if i.even? then evens += x else odds += x end
  end

  sweets.each_with_index do |x, i|
    if i.even? then evens -= x else odds -= x end

    count += 1 if evens == odds

    if i.even? then odds += x else evens += x end
  end
  count
end

gets
sweets = gets.chomp.split.map(&:to_i)
puts(good(sweets))


Burenka is about to watch the most interesting sporting event of the year — a fighting tournament organized by her friend Tonya.$$$n$$$ athletes participate in the tournament, numbered from $$$1$$$ to $$$n$$$. Burenka determined the strength of the $$$i$$$-th athlete as an integer $$$a_i$$$, where $$$1 \leq a_i \leq n$$$. All the strength values are different, that is, the array $$$a$$$ is a permutation of length $$$n$$$. We know that in a fight, if $$$a_i > a_j$$$, then the $$$i$$$-th participant always wins the $$$j$$$-th.The tournament goes like this: initially, all $$$n$$$ athletes line up in ascending order of their ids, and then there are infinitely many fighting rounds. In each round there is exactly one fight: the first two people in line come out and fight. The winner goes back to the front of the line, and the loser goes to the back.Burenka decided to ask Tonya $$$q$$$ questions. In each question, Burenka asks how many victories the $$$i$$$-th participant gets in the first $$$k$$$ rounds of the competition for some given numbers $$$i$$$ and $$$k$$$. Tonya is not very good at analytics, so he asks you to help him answer all the questions.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq q \leq 10^5$$$) — the number of tournament participants and the number of questions. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$) — the array $$$a$$$, which is a permutation. The next $$$q$$$ lines of a test case contain questions. Each line contains two integers $$$i$$$ and $$$k$$$ ($$$1 \leq i \leq n$$$, $$$1 \leq k \leq 10^9$$$) — the number of the participant and the number of rounds. It is guaranteed that the sum of $$$n$$$ and the sum of $$$q$$$ over all test cases do not exceed $$$10^5$$$.

For each Burenka's question, print a single line containing one integer — the answer to the question.

NoteIn the first test case, the first numbered athlete has the strength of $$$3$$$, in the first round he will defeat the athlete with the number $$$2$$$ and the strength of $$$1$$$, and in the second round, the athlete with the number $$$3$$$ and the strength of $$$2$$$.In the second test case, we list the strengths of the athletes fighting in the first $$$5$$$ fights: $$$1$$$ and $$$3$$$, $$$3$$$ and $$$4$$$, $$$4$$$ and $$$2$$$, $$$4$$$ and $$$1$$$, $$$4$$$ and $$$3$$$. The participant with the number $$$4$$$ in the first $$$5$$$ rounds won $$$0$$$ times (his strength is $$$2$$$). The participant with the number $$$3$$$ has a strength of $$$4$$$ and won $$$1$$$ time in the first two fights by fighting $$$1$$$ time.

main = -> {
    t = gets.to_i
    t.times do
        n, q = gets.split.map(&:to_i)
        a = gets.split.map { _1.to_i - 1 }
        car = a[0]
        cdr = a[1..]
        victories = Array.new(n) { [] }
        rounds_before_fix = 0
        while car != n - 1
            if car > cdr[0]
                cdr << cdr.shift
            else
                cdr << car
                car = cdr.shift
            end
            victories[car] << rounds_before_fix
            rounds_before_fix += 1
        end
        q.times do
            i, k = gets.split.map(&:to_i)
            i = a[i - 1]
            vs = victories[i]
            ans = vs.bsearch_index { _1 > k - 1 } || vs.size
            if i == n - 1
                ans += [k - rounds_before_fix, 0].max
            end
            puts ans
        end
    end
}

main.call


Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk. Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times. Polycarp analysed all his affairs over the next n days and made a sequence of n integers a1, a2, ..., an, where ai is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times. Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers b1, b2, ..., bn (bi ≥ ai), where bi means the total number of walks with the dog on the i-th day.

The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of days and the minimum number of walks with Cormen for any two consecutive days.  The second line contains integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of walks with Cormen on the i-th day which Polycarp has already planned.

In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days.  In the second line print n integers b1, b2, ..., bn, where bi — the total number of walks on the i-th day according to the found solutions (ai ≤ bi for all i from 1 to n). If there are multiple solutions, print any of them.

n,k,*a=$<.read.split.map(&:to_i)
b=a[s=0]
(1...n).each{|i|
if b+a[i]<k
s+=k-b-a[i]
a[i]=k-b
end
b=a[i]
}
p s
puts a*' '

n, k = gets.chomp.split.map(&:to_i)
a = gets.chomp.split.map(&:to_i)
inc = 0
(0...n).each_cons(2).each do |i, j|
  if a[i] + a[j] < k
    inc += k - a[i] - a[j]
    a[j] = k - a[i]
  end
end
puts inc
puts a.join(" ")

n,k=gets.split.map{|e| e.to_i}
x=gets.split.map{|e| e.to_i}
arr=[]
sum=0
while x.size>1
	d=x[0]+x[1]
	if k>d then
		x[1]+=(k-d)
		sum+=(k-d)
	end
	arr<<x[0]

	x.shift
end
arr<<x[0]

puts sum
puts arr*" "

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

res=0
b=[a[0]]
for i in 1..n-1
    t=k-a[i]-b[i-1]
    b[i]=a[i]
    if t>0
        res+=t
        b[i]+=t
    end
end
puts res
puts b*' '

class Advisor
  def self.get_advice(src)
    @@norm_work_cnt=src[0][1]
    src[1].unshift @@norm_work_cnt
    walks=src[1].map {|x| x=*x}.each_cons(2).to_a.each {|x| x[1][0]= get_walks_needed(x[0][0],x[1][0])}.
        map {|x| x=x[1]}.flatten
    src[1].shift
    result = [] << walks.zip(src[1]).map {|x,y| x-y}.reduce(:+) << walks
    print_result result
    result
  end
  def self.get_walks_needed(walks_prev,walks_current)
    tmp = @@norm_work_cnt-walks_prev-walks_current
    (tmp>=0)?(tmp+walks_current) : walks_current
  end
  def self.print_result(res)
    puts res[0],res[1].join(' ')
  end
end

if __FILE__ == $0
  src = $stdin.each_line.map {|x| x.split.map {|x| x=(x.to_i)}}
  Advisor.get_advice(src)
end

n,k = gets.split(' ').map {|e| e.to_i}
arr = gets.split(' ').map {|e| e.to_i}
i = 1
tmp = 0
while i < n
	if arr[i]+arr[i-1]<k
		tmp1 = arr[i]
		arr[i]+=k-arr[i-1]-arr[i]
		tmp+=k-tmp1-arr[i-1]
	end
	i+=1
end
puts tmp
puts arr.join(' ')

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

ad = 0
a.each_with_index do |t, i|
  next if i == 0
  dif = k > (a[i - 1] + a[i]) ? k - (a[i - 1] + a[i]) : 0
  ad += dif
  a[i] += dif
end
puts ad
puts a.join " "

def solution(arr, k)
  counter = 0
  for i in 0...arr.size-1 do
    add = k - arr[i+1] - arr[i]
    if  add > 0
      arr[i+1] += add
      counter += add
    end
  end
  puts counter
  puts arr
end

_, k = gets.split.map{ |i| i.to_i }
arr = gets.split.map(&:to_i)

solution(arr, k)

n, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
ans = 0
(n - 1).times do |i|
  c = k - a[i] - a[i + 1]
  if c > 0
    ans += c
    a[i + 1] += c
  end
end
puts ans, a.join(' ')

n, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
ans = 0
(n - 1).times do |i|
  if a[i] + a[i + 1] < k
    c = k - a[i] - a[i + 1]
    ans += c
    a[i + 1] += c
  end
end
puts ans, a.join(' ')

n,k=gets.split(" ").map(&:to_i)
a=gets.split(" ").map(&:to_i)
b=[a[0]]
delta=0
for i in 1...n
	b<<[a[i],k-b[i-1]].max
	if k-b[i-1]>a[i]
		delta+=k-b[i-1]-a[i]
	end
end
puts delta
puts b.join(" ")

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

tot = 0
for i in 0 ... n - 1
  if a[i] + a[i + 1] < k
    add = k - a[i] - a[i + 1]
    a[i + 1] += add
    tot += add
  end
end
puts tot
puts a.join(' ')

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

(0...n).each_cons(2).each do |i, j|
  if a[i] + a[j] < k
    a[j] = k - a[i]
  end
end
puts a.join(" ")

n,k=gets.split.map{|e| e.to_i}
x=gets.split.map{|e| e.to_i}
arr=[]
sum=0
while x.size>1
	d=x[0]+x[1]
	if k>d then
		x[1]+=(k-d)
		sum+=(k-d)
	end
	arr<<x[0]

	x.shift
end
if n>1 then
	arr<<x[0]
else
	if x[0]>=k then
		arr<<x[0]
	else
		sum=k-x[0]
		arr<<k
	end
end
puts sum
puts arr*" "


Anya has bought a new smartphone that uses Berdroid operating system. The smartphone menu has exactly n applications, each application has its own icon. The icons are located on different screens, one screen contains k icons. The icons from the first to the k-th one are located on the first screen, from the (k + 1)-th to the 2k-th ones are on the second screen and so on (the last screen may be partially empty).Initially the smartphone menu is showing the screen number 1. To launch the application with the icon located on the screen t, Anya needs to make the following gestures: first she scrolls to the required screen number t, by making t - 1 gestures (if the icon is on the screen t), and then make another gesture — press the icon of the required application exactly once to launch it.After the application is launched, the menu returns to the first screen. That is, to launch the next application you need to scroll through the menu again starting from the screen number 1.All applications are numbered from 1 to n. We know a certain order in which the icons of the applications are located in the menu at the beginning, but it changes as long as you use the operating system. Berdroid is intelligent system, so it changes the order of the icons by moving the more frequently used icons to the beginning of the list. Formally, right after an application is launched, Berdroid swaps the application icon and the icon of a preceding application (that is, the icon of an application on the position that is smaller by one in the order of menu). The preceding icon may possibly be located on the adjacent screen. The only exception is when the icon of the launched application already occupies the first place, in this case the icon arrangement doesn't change.Anya has planned the order in which she will launch applications. How many gestures should Anya make to launch the applications in the planned order? Note that one application may be launched multiple times.

The first line of the input contains three numbers n, m, k (1 ≤ n, m, k ≤ 105) — the number of applications that Anya has on her smartphone, the number of applications that will be launched and the number of icons that are located on the same screen. The next line contains n integers, permutation a1, a2, ..., an — the initial order of icons from left to right in the menu (from the first to the last one), ai —  is the id of the application, whose icon goes i-th in the menu. Each integer from 1 to n occurs exactly once among ai. The third line contains m integers b1, b2, ..., bm(1 ≤ bi ≤ n) — the ids of the launched applications in the planned order. One application may be launched multiple times.

Print a single number — the number of gestures that Anya needs to make to launch all the applications in the desired order.

NoteIn the first test the initial configuration looks like (123)(456)(78), that is, the first screen contains icons of applications 1, 2, 3, the second screen contains icons 4, 5, 6, the third screen contains icons 7, 8. After application 7 is launched, we get the new arrangement of the icons — (123)(457)(68). To launch it Anya makes 3 gestures. After application 8 is launched, we get configuration (123)(457)(86). To launch it Anya makes 3 gestures. After application 1 is launched, the arrangement of icons in the menu doesn't change. To launch it Anya makes 1 gesture.In total, Anya makes 7 gestures.

n, m, k = gets.split.collect{|i| i.to_i}
a = gets.split.collect{|i| i.to_i}
mark = Hash.new
(0...a.size).each{|i| mark[a[i]] = i}
ans = 0
gets.split.each do |b|
    tmp = mark[b.to_i]
    if tmp != 0
        ans += tmp/k+1
        mark[a[tmp]] -= 1
        mark[a[tmp-1]] += 1
        a[tmp-1], a[tmp] = a[tmp], a[tmp-1]
    else
        ans += 1
    end
end
puts ans

n, m, k = gets.split(" ").map(&:to_i)
a = gets.split(" ").map(&:to_i)
b = gets.split(" ").map(&:to_i)
ans = 0
ind = Array.new(n + 1)
for i in 0...n
  ind[a[i]] = i
end
b.each do |x|
  j = ind[x]
  ans += (j / k) + 1
  if j != 0
    a[j - 1], a[j] = a[j], a[j - 1]
    ind[a[j]] = j
    ind[a[j - 1]] = j - 1
  end
end
puts ans

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

h = {}

a.each_with_index { |value, index| h[ value ] = index }

ans = 0
b.each do |v|
  pos = h[ v ]
  page = (pos + k) / k
  ans += page

  if pos != 0
    a[pos], a[pos - 1] = a[pos - 1], a[pos]
    h[ a[pos] ] = pos
    h[ a[pos - 1] ] = pos - 1
  end
end
puts ans

if __FILE__ == $0
  END { main }
end

def main
  app_count, up_app_count, apps_per_screen = gets.strip.split(" ").map(&:to_i)
  apps = gets.strip.split(" ").map(&:to_i)
  up_apps = gets.strip.split(" ").map(&:to_i)

  app_orders = get_app_orders(apps)

  gesture_count = 0

  up_apps.each do |app|
    app_order = get_app_order(app, app_orders)
    gesture_count += get_gesture_count(app_order, apps_per_screen)
    up_app(app, apps, app_orders)
  end

  puts gesture_count
end

def get_app_orders(apps)
  orders = []
  apps.each_with_index do |app, index|
    orders[app-1] = index
  end
  orders
end

def get_gesture_count(app_order, apps_per_screen)
  app_order / apps_per_screen + 1
end

def up_app(app, apps, app_orders)
  app_order = get_app_order(app, app_orders)
  return if app_order == 0

  prev_app = apps[app_order - 1]
  app_orders[prev_app - 1] += 1
  app_orders[app - 1] -= 1

  apps[get_app_order(app, app_orders)] = app
  apps[get_app_order(prev_app, app_orders)] = prev_app
end

def get_app_order(app, app_orders)
  app_orders[app - 1]
end

n, m, k = gets.split(" ").map(&:to_i)
a = gets.split(" ").map(&:to_i)
b = gets.split(" ").map(&:to_i)
ans = 0
ind = Array.new(n + 1)
for i in 0...n
  ind[a[i]] = i
end
b.each do |x|
  j = ind[x]
  ans += (j / k) + 1
  a[j - 1], a[j] = a[j], a[j - 1] if j != 0
  ind[a[j]] = j
  ind[a[j - 1]] = j - 1
end
puts ans

n, m, k = gets.split(" ").map(&:to_i)
a = gets.split(" ").map(&:to_i)
b = gets.split(" ").map(&:to_i)
ans = 0
ind = Array.new(n + 1)
for i in 0...n
  ind[a[i]] = i
end
m.times do |i|
  ans += (ind[b[i]] / k) + 1
  tmp = a[ind[b[i]] - 1]
  a[ind[b[i]] - 1] = a[ind[b[i]]]
  a[ind[b[i]]] = tmp
  ind[b[i]] -= 1
  ind[tmp] += 1
end
puts ans


In the autumn of this year, two Russian teams came into the group stage of the most prestigious football club competition in the world — the UEFA Champions League. Now, these teams have already started to play in the group stage and are fighting for advancing to the playoffs. In this problem we are interested in the draw stage, the process of sorting teams into groups.The process of the draw goes as follows (the rules that are described in this problem, are somehow simplified compared to the real life). Suppose n teams will take part in the group stage (n is divisible by four). The teams should be divided into groups of four. Let's denote the number of groups as m (). Each team has a rating — an integer characterizing the team's previous achievements. The teams are sorted by the rating's decreasing (no two teams have the same rating).After that four "baskets" are formed, each of which will contain m teams: the first m teams with the highest rating go to the first basket, the following m teams go to the second one, and so on.Then the following procedure repeats m - 1 times. A team is randomly taken from each basket, first from the first basket, then from the second, then from the third, and at last, from the fourth. The taken teams form another group. After that, they are removed from their baskets.The four teams remaining in the baskets after (m - 1) such procedures are performed, form the last group.In the real draw the random selection of teams from the basket is performed by people — as a rule, the well-known players of the past. As we have none, we will use a random number generator, which is constructed as follows. Its parameters are four positive integers x, a, b, c. Every time there is a call to the random number generator, it produces the following actions:  calculates ;  replaces parameter x by value y (assigns );  returns x as another random number. Operation  means taking the remainder after division: , .A random number generator will be used in the draw as follows: each time we need to randomly choose a team from the basket, it will generate a random number k. The teams that yet remain in the basket are considered numbered with consecutive integers from 0 to s - 1, in the order of decreasing rating, where s is the current size of the basket. Then a team number  is taken from the basket.Given a list of teams and the parameters of the random number generator, determine the result of the draw.

The first input line contains integer n (4 ≤ n ≤ 64, n is divisible by four) — the number of teams that take part in the sorting. The second line contains four space-separated integers x, a, b, c (1 ≤ x, a, b, c ≤ 1000) — the parameters of the random number generator. Each of the following n lines describes one team. The description consists of the name of the team and its rating, separated by a single space. The name of a team consists of uppercase and lowercase English letters and has length from 1 to 20 characters. A team's rating is an integer from 0 to 1000. All teams' names are distinct. All team's ratings are also distinct.

Print the way the teams must be sorted into groups. Print the groups in the order, in which they are formed in the sorting. Number the groups by consecutive uppercase English letters, starting from letter 'A'. Inside each group print the teams' names one per line, in the order of decreasing of the teams' rating. See samples for a better understanding of the output format.

8
1 3 1 7
Barcelona 158
Milan 90
Spartak 46
Anderlecht 48
Celtic 32
Benfica 87
Zenit 79
Malaga 16

Group A:
Barcelona
Benfica
Spartak
Celtic
Group B:
Milan
Zenit
Anderlecht
Malaga

NoteIn the given sample the random number generator will be executed four times:   ,  ,  ,  .

if ENV['USER'] != 'watashi'
  $stdin = open('input.txt')
  $> = open('output.txt', 'w')
end

class RNG
  def initialize(x, a, b, c)
    @x = x
    @f = ->(x){(x * a + b) % c}
  end

  def next
    @x = @f[@x]
  end
end

n = gets.to_i
r = RNG.new(*gets.split.map(&:to_i))
a = Array.new(n){
  x, y = gets.split
  [y.to_i, x]
}
n /= 4
a = a.sort.reverse.each_slice(n).to_a
g = 'Group A:'
n.downto(1){|m|
  puts g
  g.succ!
  a.each{|b|
    t = b[r.next % m]
    puts t[1]
    b.delete(t)
  }
}

input = File.open("input.txt", "r")
output = File.open("output.txt", "w")

n = input.gets.to_i
x, a, b, c = input.gets.split.map(&:to_i)

team = Array.new(n)
for i in 0...n
  team[i] = input.gets.split
end

team.sort! {|x, y| y[1].to_i <=> x[1].to_i}

sep = n/4
for i in 0...n/4 do
  output.puts "Group #{('A'.ord+i).chr}:"
  x = (x*a + b)%c
  t1 = x%sep
  output.puts team[t1][0]

  x = (x*a + b)%c
  t2 = sep + x%sep
  output.puts team[t2][0]

  x = (x*a + b)%c
  t3 = sep*2 + x%sep
  output.puts team[t3][0]

  x = (x*a + b)%c
  t4 = sep*3 + x%sep
  output.puts team[t4][0]

  team.delete_at(t1)
  team.delete_at(t2-1)
  team.delete_at(t3-2)
  team.delete_at(t4-3)

  sep -= 1
end

input.close
output.close


Let's call a string good if its length is at least $$$2$$$ and all of its characters are $$$\texttt{A}$$$ except for the last character which is $$$\texttt{B}$$$. The good strings are $$$\texttt{AB},\texttt{AAB},\texttt{AAAB},\ldots$$$. Note that $$$\texttt{B}$$$ is not a good string.You are given an initially empty string $$$s_1$$$.You can perform the following operation any number of times:   Choose any position of $$$s_1$$$ and insert some good string in that position. Given a string $$$s_2$$$, can we turn $$$s_1$$$ into $$$s_2$$$ after some number of operations?

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single string $$$s_2$$$ ($$$1 \leq |s_2| \leq 2 \cdot 10^5$$$). It is guaranteed that $$$s_2$$$ consists of only the characters $$$\texttt{A}$$$ and $$$\texttt{B}$$$. It is guaranteed that the sum of $$$|s_2|$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print "YES" (without quotes) if we can turn $$$s_1$$$ into $$$s_2$$$ after some number of operations, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).

NoteIn the first test case, we transform $$$s_1$$$ as such: $$$\varnothing \to \color{red}{\texttt{AAB}} \to \texttt{A}\color{red}{\texttt{AB}}\texttt{AB}$$$.In the third test case, we transform $$$s_1$$$ as such: $$$\varnothing \to \color{red}{\texttt{AAAAAAAAB}}$$$.In the second and fourth test case, it can be shown that it is impossible to turn $$$s_1$$$ into $$$s_2$$$.

gets.to_i.times do
  a = gets.chomp.split('')
  flag = (a[a.size-1] == 'B')
  bcount = 0
  acount = 0
  0.upto(a.size-1) do |i|
    if (a[i]=='B') then
      bcount += 1
    else
      acount += 1
    end
    flag = false if bcount>acount
  end
  puts ((bcount > 0) && flag) ? "YES" : "NO"
end

gets.to_i.times do
  s = gets.chomp
  as = 0
  s.chars.each do |ch|
    case ch
    when "A" then as += 1
    when "B" then as -= 1
    end
    break if as < 0
  end
  ok = as >= 0 && s[-1] == "B"
  puts ok ? "YES" : "NO"
end

gets.to_i.times do
  a = gets.chomp.split('')
  flag = true
  bcount = 0
  acount = 0
  0.upto(a.size-1) do |i|
    if (a[i]=='B') then
      bcount += 1
      if (bcount>acount) then
        flag = false
      end
    else
      acount += 1
    end
  end
  puts ((bcount > 0 ) && flag) ? "YES":"NO"
end

gets.to_i.times do
  a = gets.chomp.split('')
  flag = true
  bcount = 0
  acount = 0
  0.upto(a.size-1) do |i|
    if (a[i]=='B') then
      bcount += 1
      if (bcount>acount)
        flag = false
      end
    else
      acount += 1
    end
  end
  puts ((bcount > 0 ) & flag) ? "YES":"NO"
end


Vova has won $$$n$$$ trophies in different competitions. Each trophy is either golden or silver. The trophies are arranged in a row.The beauty of the arrangement is the length of the longest subsegment consisting of golden trophies. Vova wants to swap two trophies (not necessarily adjacent ones) to make the arrangement as beautiful as possible — that means, to maximize the length of the longest such subsegment.Help Vova! Tell him the maximum possible beauty of the arrangement if he is allowed to do at most one swap.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of trophies. The second line contains $$$n$$$ characters, each of them is either G or S. If the $$$i$$$-th character is G, then the $$$i$$$-th trophy is a golden one, otherwise it's a silver trophy.

Print the maximum possible length of a subsegment of golden trophies, if Vova is allowed to do at most one swap.

NoteIn the first example Vova has to swap trophies with indices $$$4$$$ and $$$10$$$. Thus he will obtain the sequence "GGGGGGGSGS", the length of the longest subsegment of golden trophies is $$$7$$$. In the second example Vova can make no swaps at all. The length of the longest subsegment of golden trophies in the sequence is $$$4$$$. In the third example Vova cannot do anything to make the length of the longest subsegment of golden trophies in the sequence greater than $$$0$$$.

def length(streak)
  streak[1] - streak[0] + 1
end

def solution
  read_int
  medals = read_string

  streaks = []
  crt_streak = nil

  medals.chars.each.with_index do |c, i|
    if c == ?G
      if crt_streak
        crt_streak[1] = i
      else
        crt_streak = [i, i]
        streaks << crt_streak
      end
    else
      crt_streak = nil
    end
  end

  if streaks.size == 0
    puts 0
  elsif streaks.size == 1
    puts length(streaks.first)
  else

    max = 0

    (0...streaks.size).each do |i|
      crt = streaks[i]
      next_streak = streaks[i + 1]

      crt_max = length(crt) + 1

      if next_streak && next_streak[0] == crt[1] + 2
        combined = length(crt) + length(next_streak) + 1
        if streaks.size == 2
          # have to reuse a Gold medal from one of the current streaks
          combined -= 1
        end

        crt_max = combined
      end

      max = [max, crt_max].max

    end

    puts max

  end

end

def read_int
  gets.to_i
end

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

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']

gets
a=(?S+gets.chomp+?S).scan(/(?:G+|S+)/).map(&:size)
res=0
1.step(a.size, 2) do |i|
    break if !a[i]
    t=a[i]+(a.size>4 ? 1 : 0)
    res=a[i] if res<a[i]
    if a[i+2]
        t=[a[i], a[i+2]].max+1
        res=t if res<t
        t=a[i]+(a[i+1]==1 ? a[i+2] : 1)
        res=t if res<t
        res=t+1 if a[i+1]==1 && a.size>6 && res<t+1
    end
end
puts res

n = gets.to_i

gs = gets.chomp

origingold = false
inagold = false
if gs[0]=="G"
  inagold=true
  origingold = true
end

newarr = []

count = 1

gs.each_char.with_index do |ch,i|
  next if i==0
  if inagold
    if ch=="S"
      newarr.push count
      count = 1
      inagold = false
    else
      count+=1
    end
  else
    if ch=="G"
      newarr.push count
      count = 1
      inagold = true
    else
      count += 1
    end
  end
end

newarr.push count

def checkifgold(i,origin)
  if origin
    return i%2==0
  else
    return i%2==1
  end
end

maxgold = 0
maxtwogold = 0
prevgold = 0
wasaone = false

#p newarr

newarr.each_with_index do |x,i|

#  puts wasaone
#  puts x
#  puts i
#  puts checkifgold(i,origingold)

  if checkifgold(i,origingold)
    maxgold = x if x>maxgold
    if wasaone
      asd = prevgold+x+1
      maxtwogold = asd if asd>maxtwogold
    end
    prevgold = x
  else
    if x==1
      wasaone = true
    else
      wasaone = false
    end
  end

end

if newarr.length==1
  if origingold
    puts maxgold
  else
    puts 0
  end
  exit
end

if newarr.length==2
  puts maxgold
  exit
end

if newarr.length==3
  if not origingold
    puts maxgold
    exit
  end
end

if newarr.length<5 or (newarr.length==5 and not origingold)
  puts [maxgold+1,maxtwogold-1].max
  exit
end
#puts maxgold
#puts maxtwogold
puts [maxgold+1,maxtwogold].max

def length(streak)
  streak[1] - streak[0] + 1
end

def solution
  read_int
  medals = read_string

  streaks = []
  crt_streak = nil

  medals.chars.each.with_index do |c, i|
    if c == ?G
      if crt_streak
        crt_streak[1] = i
      else
        crt_streak = [i, i]
        streaks << crt_streak
      end
    else
      crt_streak = nil
    end
  end

  if streaks.size == 0
    puts 0
  elsif streaks.size == 1
    puts length(streaks.first)
  else

    max = 0

    (0...streaks.size).each do |i|
      crt = streaks[i]
      next_streak = streaks[i + 1]

      crt_max = length(crt)

      if next_streak && next_streak[0] == crt[1] + 2
        combined = length(crt) + length(next_streak) + 1
        if streaks.size == 2
          # have to reuse a Gold medal from one of the current streaks
          combined -= 1
        end

        crt_max = combined
      end

      max = [max, crt_max].max

    end

    puts max

  end

end

def read_int
  gets.to_i
end

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

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']

gets
a=(?S+gets.chomp+?S).scan(/(?:G+|S+)/).map(&:size)
res=0
1.step(a.size, 2) do |i|
    break if !a[i]
    t=a[i]+(a.size>4 ? 1 : 0)
    res=a[i] if res<a[i]
    if a[i+2]
        t=a[i]+(a[i+1]==1 ? a[i+2] : 1)
        res=t if res<t
        res=t+1 if a[i+1]==1 && a.size>6 && res<t+1
    end
end
puts res

gets
a=(?S+gets.chomp+?S).scan(/(?:G+|S+)/).map(&:size)
res=0
1.step(a.size, 2) do |i|
    break if !a[i]
    t=a[i]+(a.size>4 ? 1 : 0)
    res=a[i] if res<a[i]
    if a[i+2]
        t=a[i]+(a.size>6 && a[i+1]==1 ? a[i+2]+1 : 1)
        res=t if res<t
    end
end
puts res

gets
a=(?S+gets.chomp+?S).scan(/(?:G+|S+)/).map(&:size)
res=0
1.step(a.size, 2) do |i|
    break if !a[i]
    res=a[i] if res<a[i]
    if a[i+2]
        t=a[i]+a[i+2]+(a.size>5 ? 1 : 0)
        res=t if res<t
    end
end
puts res

gets
a=(?S+gets.chomp+?S).scan(/(?:G+|S+)/).map(&:size)
res=0
1.step(a.size, 2) do |i|
    break if !a[i]
    res=a[i] if res<a[i]
    if a[i+2]
        t=a[i]+a[i+2]+(a.size>5 && a[i+1]==1 ? 1 : 0)
        res=t if res<t
    end
end
puts res

gets
a=(?S+gets.chomp+?S).scan(/(?:G+|S+)/).map(&:size)
res=0
1.step(a.size, 2) do |i|
    break if !a[i]
    t=a[i]+(a.size>4 ? 1 : 0)
    res=a[i] if res<a[i]
    if a[i+2]
        t=a[i]+a[i+2]+(a.size>6 && a[i+1]==1 ? 1 : 0)
        res=t if res<t
    end
end
puts res


You're playing a game called Osu! Here's a simplified version of it. There are n clicks in a game. For each click there are two outcomes: correct or bad. Let us denote correct as "O", bad as "X", then the whole play can be encoded as a sequence of n characters "O" and "X".Using the play sequence you can calculate the score for the play as follows: for every maximal consecutive "O"s block, add the square of its length (the number of characters "O") to the score. For example, if your play can be encoded as "OOXOOOXXOO", then there's three maximal consecutive "O"s block "OO", "OOO", "OO", so your score will be 22 + 32 + 22 = 17. If there are no correct clicks in a play then the score for the play equals to 0.You know that the probability to click the i-th (1 ≤ i ≤ n) click correctly is pi. In other words, the i-th character in the play sequence has pi probability to be "O", 1 - pi to be "X". You task is to calculate the expected score for your play.

The first line contains an integer n (1 ≤ n ≤ 105) — the number of clicks. The second line contains n space-separated real numbers p1, p2, ..., pn (0 ≤ pi ≤ 1). There will be at most six digits after the decimal point in the given pi.

Print a single real number — the expected score for your play. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.

NoteFor the first example. There are 8 possible outcomes. Each has a probability of 0.125.  "OOO"  →  32 = 9;  "OOX"  →  22 = 4;  "OXO"  →  12 + 12 = 2;  "OXX"  →  12 = 1;  "XOO"  →  22 = 4;  "XOX"  →  12 = 1;  "XXO"  →  12 = 1;  "XXX"  →  0. So the expected score is

n = gets.to_i
e = 0
a = 0
f = gets.split.map(&:to_f)
f.each { |d|
    a += d*(2*e+1)
    e = (e+1)*d
}
p a

n = gets.to_i
p = gets.split.map(&:to_f)
a = 0.0
e = 0.0
p.each {|x|
  a += x*(2*e+1)
  e = x*(e+1)
}
print a

n = gets.to_i
e = 0
a = 0
f = (gets.split)
f.each { |d|
    a += d.to_f*(2*e+1)
    e = (e+1)*d.to_f
}
p a

n=Integer(gets());
q = gets().split(" ").map(&:to_f);
e_sz = e = 0; q.each { |p| e=(1-p)*e+p*e+2*p*e_sz + p; e_sz=p*(e_sz+1);}
printf "%.10f\n", e

n = gets.to_i
ans = 0
exp = 0

p = gets.split.map &:to_f
p.each do |p|
  ans += p*(2*exp + 1)
  exp = p*(exp+1)
end
puts ans


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

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

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

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

require 'prime'

n = gets.to_i
knights = gets.split.map(&:to_i)
divs = (1..n).to_a.select{|v| n%v == 0}.select{|v| v <= n/3}

divs.each do |i|
	#if arr[i] == 1
		#check
		if n % i == 0
			(0..(i-1)).each do |start|
				ok = true
				pos = start
				(n/i).times do
					if knights[pos] == 0
						ok = false
						break
					end
					pos = (pos+i) % n
				end
				if ok
					puts "YES"
					exit
				end
			end
		end

=begin
		(2..i+1).each do |k|
			if (i+1) % k == 0
				arr[(i+1)/k-1] = 0
			end
		end
=end
#	end
end
puts "NO"

n = gets.chomp
n = n.to_i

knights = gets.chomp
knights = knights.split(' ')

ok = false;

for i in 1..n
	if i * 3 > n; break; end;
	if n % i != 0; next; end;

	for j in 0..i-1
		ok = true;
		k = j;
		while k < n
			if knights[k] == "0"
				ok = false;
				break;
			end
			k += i;
		end
		if ok == true
			break;
		end
	end
	if ok
		break;
	end
end

if ok
	puts "YES";
else
	puts "NO";
end

#!/usr/bin/env/ruby

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

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

#exec(debug = true)
exec

require 'prime'

n = gets.to_i
knights = gets.split.map(&:to_i)
divs = n.prime_division.map{|a| a[0]-1}.select{|v| v+1<=n/3} + [0]

divs.each do |i|
	#if arr[i] == 1
		#check
		if n % (i+1) == 0
			(0..i).each do |start|
				ok = true
				pos = start
				(n/(i+1)).times do
					if knights[pos] == 0
						ok = false
						break
					end
					pos = (pos+i+1) % n
				end
				if ok
					puts "YES"
					exit
				end
			end
		end

=begin
		(2..i+1).each do |k|
			if (i+1) % k == 0
				arr[(i+1)/k-1] = 0
			end
		end
=end
#	end
end
puts "NO"

#!/usr/bin/env/ruby

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

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

exec(debug = true)
#exec

#!/usr/bin/env/ruby

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

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

exec

#!/usr/bin/env/ruby

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

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

#exec(debug = true)
exec

#!/usr/bin/env/ruby

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

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

exec(debug = true)
#exec


Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table $$$M$$$ with $$$n$$$ rows and $$$n$$$ columns such that $$$M_{ij}=a_i \cdot a_j$$$ where $$$a_1, \dots, a_n$$$ is some sequence of positive integers.Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array $$$a_1, \dots, a_n$$$. Help Sasha restore the array!

The first line contains a single integer $$$n$$$ ($$$3 \leqslant n \leqslant 10^3$$$), the size of the table.  The next $$$n$$$ lines contain $$$n$$$ integers each. The $$$j$$$-th number of the $$$i$$$-th line contains the number $$$M_{ij}$$$ ($$$1 \leq M_{ij} \leq 10^9$$$). The table has zeroes on the main diagonal, that is, $$$M_{ii}=0$$$.

In a single line print $$$n$$$ integers, the original array $$$a_1, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$). It is guaranteed that an answer exists. If there are multiple answers, print any.

n = gets.to_i
arr = Array.new(n)

n.times do |i|
	arr[i] = gets.split(' ').collect(&:to_i)
end

a2 = Math.sqrt( ((arr[2][1] * arr[0][1])/arr[0][2]).round ).round

ans = []

n.times do |i|
	if i == 1
		ans << a2
	else
		ans << (arr[i][1]/a2).to_i
	end
end

print ans.join(' ')

n = gets.to_i
arr = Array.new(n)

n.times do |i|
	arr[i] = gets.split(' ').collect(&:to_i)
end

a2 = Math.sqrt((arr[2][1] * arr[0][1])/arr[2][1]).to_i

ans = []

n.times do |i|
	if i == 1
		ans << a2
	else
		ans << (arr[i][1]/a2).to_i
	end
end

print ans.join(' ')

n = gets.to_i
arr = Array.new(n)

n.times do |i|
	arr[i] = gets.split(' ').collect(&:to_i)
end

a2 = Math.sqrt((arr[2][1] * arr[0][1])/arr[2][1]).ceil

ans = []

n.times do |i|
	if i == 1
		ans << a2
	else
		ans << (arr[i][1]/a2).to_i
	end
end

print ans.join(' ')

n = gets.to_i
arr = Array.new(n)

n.times do |i|
	arr[i] = gets.split(' ').collect(&:to_i)
end

p ((arr[2][1] * arr[0][1])/arr[2][1]).round

a2 = Math.sqrt( ((arr[2][1] * arr[0][1])/arr[0][2]).round ).round

ans = []

n.times do |i|
	if i == 1
		ans << a2
	else
		ans << (arr[i][1]/a2).to_i
	end
end

print ans.join(' ')

n = gets.to_i
arr = Array.new(n)

n.times do |i|
	arr[i] = gets.split(' ').collect(&:to_i)
end

ce = Math.sqrt((arr[2][1] * arr[0][1])/arr[2][1]).ceil
fl = Math.sqrt((arr[2][1] * arr[0][1])/arr[2][1]).floor

if (ce.to_f * ce.to_f) > (arr[2][1].to_f * arr[0][1].to_f)/arr[2][1].to_f
	a2 = ce
else
	a2 = fl
end

ans = []

n.times do |i|
	if i == 1
		ans << a2
	else
		ans << (arr[i][1]/a2).to_i
	end
end

print ans.join(' ')

n = gets.to_i
arr = Array.new(n)

n.times do |i|
	arr[i] = gets.split(' ').collect(&:to_i)
	p arr[i]
end

a2 = Math.sqrt((arr[2][1] * arr[0][1])/arr[2][1]).to_i

n.times do |i|
	if i == 1
		print "#{a2} "
	else
		print "#{arr[i][1]/a2} "
	end
end


You came to the exhibition and one exhibit has drawn your attention. It consists of $$$n$$$ stacks of blocks, where the $$$i$$$-th stack consists of $$$a_i$$$ blocks resting on the surface.The height of the exhibit is equal to $$$m$$$. Consequently, the number of blocks in each stack is less than or equal to $$$m$$$.There is a camera on the ceiling that sees the top view of the blocks and a camera on the right wall that sees the side view of the blocks. Find the maximum number of blocks you can remove such that the views for both the cameras would not change.Note, that while originally all blocks are stacked on the floor, it is not required for them to stay connected to the floor after some blocks are removed. There is no gravity in the whole exhibition, so no block would fall down, even if the block underneath is removed. It is not allowed to move blocks by hand either.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100\,000$$$, $$$1 \le m \le 10^9$$$) — the number of stacks and the height of the exhibit. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le m$$$) — the number of blocks in each stack from left to right.

Print exactly one integer — the maximum number of blocks that can be removed.

NoteThe following pictures illustrate the first example and its possible solution.Blue cells indicate removed blocks. There are $$$10$$$ blue cells, so the answer is $$$10$$$.

n,_ = gets.split
arr = gets.split.map(&:to_i)
arr.sort_by!{|a| -a}

total = arr.inject(&:+)
needed = 0

(0...arr.size).each do |i|
    if i == arr.size-1
        needed += [1,arr[i]].max
    elsif arr[i] > arr[i+1]
        needed += arr[i] - arr[i+1]
    else
        needed +=1
        arr[i+1] = arr[i]-1
    end
end

puts total-needed

n, m = gets.split.map{|x| x.to_i}
a = gets.split.map{|x| x.to_i}.sort.reverse
m = a.max
d = 0
(0...n-1).each do |i|
    if a[i] == a[i + 1]
        d += a[i] if a[i] > 1
        a[i + 1] = [a[i] - 1, 1].max
    elsif a[i] > a[i + 1]
        d += a[i + 1]
    else
        d += a[i] if a[i] > 1
        d += a[i + 1] - a[i]
        a[i + 1] = [a[i] - 1, 1].max
    end
end
puts d


A line on the plane is described by an equation Ax + By + C = 0. You are to find any point on this line, whose coordinates are integer numbers from  - 5·1018 to 5·1018 inclusive, or to find out that such points do not exist.

The first line contains three integers A, B and C ( - 2·109 ≤ A, B, C ≤ 2·109) — corresponding coefficients of the line equation. It is guaranteed that A2 + B2 > 0.

If the required point exists, output its coordinates, otherwise output -1.

def extgcd(a, b)
	if b == 0
		[a, 1, 0]
	else
		g, x, y = extgcd(b, a % b)
		[g, y, x - a / b * y]
	end
end

a, b, c = gets.split.map(&:to_i)
g, x, y = extgcd(a, b)

if c % g == 0
	c /= -g
	puts "#{x*c} #{y*c}"
else
	p -1
end

def E_GCD(a,b)
  if b==0
    return 1,0,a
  else
    x,y,d = E_GCD(b, a%b)
    return y,x-y*(a/b),d
  end
end

  a,b,c = gets.split.map(&:to_i)
  x,y,d = E_GCD(a,b)

  if c%d==0
    puts "#{-x*c/d} #{-y*c/d}"
  else
    puts -1
  end


Limak is a little polar bear. He loves connecting with other bears via social networks. He has n friends and his relation with the i-th of them is described by a unique integer ti. The bigger this value is, the better the friendship is. No two friends have the same value ti.Spring is starting and the Winter sleep is over for bears. Limak has just woken up and logged in. All his friends still sleep and thus none of them is online. Some (maybe all) of them will appear online in the next hours, one at a time.The system displays friends who are online. On the screen there is space to display at most k friends. If there are more than k friends online then the system displays only k best of them — those with biggest ti.Your task is to handle queries of two types:  "1 id" — Friend id becomes online. It's guaranteed that he wasn't online before.  "2 id" — Check whether friend id is displayed by the system. Print "YES" or "NO" in a separate line. Are you able to help Limak and answer all queries of the second type?

The first line contains three integers n, k and q (1 ≤ n, q ≤ 150 000, 1 ≤ k ≤ min(6, n)) — the number of friends, the maximum number of displayed online friends and the number of queries, respectively. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 109) where ti describes how good is Limak's relation with the i-th friend. The i-th of the following q lines contains two integers typei and idi (1 ≤ typei ≤ 2, 1 ≤ idi ≤ n) — the i-th query. If typei = 1 then a friend idi becomes online. If typei = 2 then you should check whether a friend idi is displayed. It's guaranteed that no two queries of the first type will have the same idi becuase one friend can't become online twice. Also, it's guaranteed that at least one query will be of the second type (typei = 2) so the output won't be empty.

For each query of the second type print one line with the answer — "YES" (without quotes) if the given friend is displayed and "NO" (without quotes) otherwise.

NoteIn the first sample, Limak has 4 friends who all sleep initially. At first, the system displays nobody because nobody is online. There are the following 8 queries:  "1 3" — Friend 3 becomes online.  "2 4" — We should check if friend 4 is displayed. He isn't even online and thus we print "NO".  "2 3" — We should check if friend 3 is displayed. Right now he is the only friend online and the system displays him. We should print "YES".  "1 1" — Friend 1 becomes online. The system now displays both friend 1 and friend 3.  "1 2" — Friend 2 becomes online. There are 3 friends online now but we were given k = 2 so only two friends can be displayed. Limak has worse relation with friend 1 than with other two online friends (t1 < t2, t3) so friend 1 won't be displayed  "2 1" — Print "NO".  "2 2" — Print "YES".  "2 3" — Print "YES".

class PQueue

  #
  #VERSION = "2.1.0"  #:erb: VERSION = "<%= version %>"

  #
  # Returns a new priority queue.
  #
  # If elements are given, build the priority queue with these initial
  # values. The elements object must respond to #to_a.
  #
  # If a block is given, it will be used to determine the priority between
  # the elements. The block must must take two arguments and return `1`, `0`,
  # or `-1` or `true`, `nil` or `false. It should return `0` or `nil` if the
  # two arguments are considered equal, return `1` or `true` if the first
  # argument is considered greater than the later, and `-1` or `false` if
  # the later is considred to be greater than the first.
  #
  # By default, the priority queue retrieves maximum elements first
  # using the #<=> method.
  #
  def initialize(elements=nil, &block) # :yields: a, b
    @que = []
    @cmp = block || lambda{ |a,b| a <=> b }
    replace(elements) if elements
  end

 protected

  #
  # The underlying heap.
  #
  attr_reader :que #:nodoc:

 public

  #
  # Priority comparison procedure.
  #
  attr_reader :cmp

  #
  # Returns the size of the queue.
  #
  def size
    @que.size
  end

  #
  # Alias of size.
  #
  alias length size

  #
  # Add an element in the priority queue.
  #
  def push(v)
    @que << v
    reheap(@que.size-1)
    self
  end

  #
  # Traditional alias for #push.
  #
  alias enq push

  #
  # Alias of #push.
  #
  alias :<< :push

  #
  # Get the element with the highest priority and remove it from
  # the queue.
  #
  # The highest priority is determined by the block given at instantiation
  # time.
  #
  # The deletion time is O(log n), with n is the size of the queue.
  #
  # Return nil if the queue is empty.
  #
  def pop
    return nil if empty?
    @que.pop
  end

  #
  # Traditional alias for #pop.
  #
  alias deq pop

  # Get the element with the lowest priority and remove it from
  # the queue.
  #
  # The lowest priority is determined by the block given at instantiation
  # time.
  #
  # The deletion time is O(log n), with n is the size of the queue.
  #
  # Return nil if the queue is empty.
  #
  def shift
    return nil if empty?
    @que.shift
  end

  #
  # Returns the element with the highest priority, but
  # does not remove it from the queue.
  #
  def top
    return nil if empty?
    return @que.last
  end

  #
  # Traditional alias for #top.
  #
  alias peek top

  #
  # Returns the element with the lowest priority, but
  # does not remove it from the queue.
  #
  def bottom
    return nil if empty?
    return @que.first
  end

  #
  # Add more than one element at the same time. See #push.
  #
  # The elements object must respond to #to_a, or be a PQueue itself.
  #
  def concat(elements)
    if empty?
      if elements.kind_of?(PQueue)
        initialize_copy(elements)
      else
        replace(elements)
      end
    else
      if elements.kind_of?(PQueue)
        @que.concat(elements.que)
        sort!
      else
        @que.concat(elements.to_a)
        sort!
      end
    end
    return self
  end

  #
  # Alias for #concat.
  #
  alias :merge! :concat

  #
  # Return top n-element as a sorted array.
  #
  def take(n=@size)
    a = []
    n.times{a.push(pop)}
    a
  end

  #
  # Returns true if there is no more elements left in the queue.
  #
  def empty?
    @que.empty?
  end

  #
  # Remove all elements from the priority queue.
  #
  def clear
    @que.clear
    self
  end

  #
  # Replace the content of the heap by the new elements.
  #
  # The elements object must respond to #to_a, or to be
  # a PQueue itself.
  #
  def replace(elements)
    if elements.kind_of?(PQueue)
      initialize_copy(elements)
    else
      @que.replace(elements.to_a)
      sort!
    end
    self
  end

  #
  # Return a sorted array, with highest priority first.
  #
  def to_a
    @que.dup
  end

  #
  # Return true if the given object is present in the queue.
  #
  def include?(element)
    @que.include?(element)
  end

  #
  # Push element onto queue while popping off and returning the next element.
  # This is qquivalent to successively calling #pop and #push(v).
  #
  def swap(v)
    r = pop
    push(v)
    r
  end

  #
  # Iterate over the ordered elements, destructively.
  #
  def each_pop #:yields: popped
    until empty?
      yield pop
    end
    nil
  end

  #
  # Pretty inspection string.
  #
  def inspect
    "<#{self.class}: size=#{size}, top=#{top || "nil"}>"
  end

  #
  # Return true if the queues contain equal elements.
  #
  def ==(other)
    size == other.size && to_a == other.to_a
  end

 private

  #
  #
  #
  def initialize_copy(other)
    @cmp  = other.cmp
    @que  = other.que.dup
    sort!
  end

  #
  # The element at index k will be repositioned to its proper place.
  #
  # This, of course, assumes the queue is already sorted.
  #
  def reheap(k)
    return self if size <= 1

    que = @que.dup

    v = que.delete_at(k)
    i = binary_index(que, v)

    que.insert(i, v)

    @que = que

    return self
  end

  #
  # Sort the queue in accorance to the given comparison procedure.
  #
  def sort!
    @que.sort! do |a,b|
      case @cmp.call(a,b)
      when  0, nil   then  0
      when  1, true  then  1
      when -1, false then -1
      else
        warn "bad comparison procedure in #{self.inspect}"
        0
      end
    end
    self
  end

  #
  # Alias of #sort!
  #
  alias heapify sort!

  #
  def binary_index(que, target)
    upper = que.size - 1
    lower = 0

    while(upper >= lower) do
      idx  = lower + (upper - lower) / 2
      comp = @cmp.call(target, que[idx])

      case comp
      when 0, nil
        return idx
      when 1, true
        lower = idx + 1
      when -1, false
        upper = idx - 1
      else
      end
    end
    lower
  end

end # class PQueue

n, k, q = gets.split.map(&:to_i)	# Friends, Friend view size, Queries
t = gets.split.map(&:to_i)			# Friendship Powers!! [#n]
window = PQueue.new

q.times do
	act, friendid = gets.split.map(&:to_i)
	fpower = t[friendid-1]
	if act==1
		# Add friend
		window << fpower
		window.shift if window.length>k
	else
		puts (if window.include? fpower
			"YES"
		else
			"NO"
		end)
	end
end


Chilly Willy loves playing with numbers. He only knows prime numbers that are digits yet. These numbers are 2, 3, 5 and 7. But Willy grew rather bored of such numbers, so he came up with a few games that were connected with them.Chilly Willy wants to find the minimum number of length n, such that it is simultaneously divisible by all numbers Willy already knows (2, 3, 5 and 7). Help him with that.A number's length is the number of digits in its decimal representation without leading zeros.

A single input line contains a single integer n (1 ≤ n ≤ 105).

Print a single integer — the answer to the problem without leading zeroes, or "-1" (without the quotes), if the number that meet the problem condition does not exist.

def t(n)
    if n % 2 == 0 then
        return true
    else
        return false
    end
end

def th(n)
    if n % 3 == 0 then
        return true
    else
        return false
    end
end

def f(n)
    if n % 5 == 0 then
        return true
    else
        return false
    end
end

def s(n)
    if n % 7 == 0 then
        return true
    else
        return false
    end
end

n = gets.to_i

num = 10**(n-1)
h = 1

while !t(num) do
    num += h
end

h = 2

while !th(num) do
    num += h
end

h *= 3

while !f(num) do
    num += h
end

h *= 5

while !s(num) && num < 10**n do
    num += h
end

if !s(num) then
    num = -1
end

puts num

a=10**(gets.to_i-1)
if a<100 then
    puts -1
else
    while a%7!=0 do
        a+=1
    end
    while a%2!=0 || a%3!=0 || a%5!=0 do
        a+=7
    end
    puts a
end

a=10**(gets.to_i-1)
if a<100 then
    puts -1
else
    while a%7!=0 do
        a+=1
    end
    while a%2!=0 || a%3!=0 || a%5!=0 || a%7!=0 do
        a+=7
    end
    puts a
end

n = gets.to_i
if n < 3 then
  print -1
  exit
else
  x = 10**(n-1) +20
  while x%7 != 0 do x += 30 end
  print x
end

n = gets.to_i
if n < 3 then
  print -1
  exit
end
Num = 2*3*5*7
k = 10**(n-1)
while k%Num != 0 do
  k += 10
end
print k

n=gets.chomp.to_i
def s n
  if n<3
    puts -1
    return
  end
  s = 210
  z = 10**(n-1)
  d = z/s
  puts s*(d+1)
end
s n

#!/usr/bin/env ruby
require 'bigdecimal'
n = STDIN.gets.chomp.to_i
x = 10 ** (n - 1) / 210

a = x * 210
b = (x + 1) * 210
if a.to_s.length == n && a > 0
  puts a
elsif b.to_s.length == n && b > 0
  puts b
else
  puts -1
end

n=gets.chomp.to_i

res=0
a=[2,3,5,7]

((10**(n-1))..(10**n-1)).each do |i|
flag=1
a.each do |j|
if i%j!=0
flag=0
break
end
end

if flag==1
res=i
break
end

end

res=-1 if res==0

puts res

n = gets.to_i
m = 2*3*5*7
if (n < 3)
	puts -1
elsif n == 3
	puts m
else
	k = 10**(n-1)
	r = k % m
	puts k + m - r
end

n = gets.to_i

num = 10**(n-1)
while (num % 3) != 0 || (num % 7) != 0 do
    num += 10
end

puts num

a=10**(gets.to_i-1)
if a<100 then
    puts -1
else
    while a%7!=0 do
        a+=1
    end
    while a%2!=0 || a%3!=0 || a%5!=0 do
        a+=1
    end
    puts a
end

a=10**(gets.to_i-1)
if a<1000 then
	puts -1
else
	while a%7!=0 do
		a+=1
	end
	while a%2!=0 || a%3!=0 || a%5!=0 do
		a+=7
	end
	puts a
end

#!/usr/bin/env ruby
require 'bigdecimal'
n = STDIN.gets.chomp.to_i

log = n - 1 - Math::log(2 * 3 * 5 * 7, 10)
x = (BigDecimal.new('10.0') ** log).to_i
a = x * 210
b =  (x + 1) * 210

if a.to_s.length == n && a > 0
  puts a
elsif b.to_s.length == n && b > 0
  puts b
else
  puts "-1"
end

#!/usr/bin/env ruby
require 'bigdecimal'
n = STDIN.gets.chomp.to_i

log = n - 1 - Math::log(2 * 3 * 5 * 7, 10)
if log < 0
  puts -1
  exit
end
x = (BigDecimal.new('10.0') ** log).to_i
a = x * 210
b =  (x + 1) * 210
c =  (x + 2) * 210

if a.to_s.length == n
  puts a
elsif b.to_s.length == n
  puts b
elsif c.to_s.length == n
else
  puts "-1"
end

#!/usr/bin/env ruby
require 'bigdecimal'
n = STDIN.gets.chomp.to_i
x = 10 ** (n - 1) / 210

if x < 1
  puts -1
  exit
end
a = x * 210
b = (x + 1) * 210
if a.to_s.length == n
  puts a
elsif b.to_s.length == n
  puts b
else
  puts -1
end


Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0, 1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [k - d, k + d] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [k - d, k]. If she escapes to the right, her new interval will be [k, k + d].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls.

The input consists of only one line. The only line contains the string s (1 ≤ |s| ≤ 106). Each character in s will be either "l" or "r".

Output n lines — on the i-th line you should print the i-th stone's number from the left.

NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1.

index = 0
s = gets.chomp
ans = Array.new
for i in 0...s.length
    if s[i] == 'r'
        puts i+1
    else
        ans.push(i+1)
    end
end
ans.reverse.each{|i| puts i}

left = 0.0
right = 1.0
s = gets.chomp
ans = Hash.new
for i in 0...s.length
    tmp = (left+right)/2
    ans[tmp] = i+1
    if s[i] == 'l'
        right = tmp
    else
        left = tmp
    end
end
ans.sort.each{|i| puts i[1]}


You've got a list of program warning logs. Each record of a log stream is a string in this format:  "2012-MM-DD HH:MM:SS:MESSAGE" (without the quotes). String "MESSAGE" consists of spaces, uppercase and lowercase English letters and characters "!", ".", ",", "?". String "2012-MM-DD" determines a correct date in the year of 2012. String "HH:MM:SS" determines a correct time in the 24 hour format.The described record of a log stream means that at a certain time the record has got some program warning (string "MESSAGE" contains the warning's description).Your task is to print the first moment of time, when the number of warnings for the last n seconds was not less than m.

The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 10000). The second and the remaining lines of the input represent the log stream. The second line of the input contains the first record of the log stream, the third line contains the second record and so on. Each record of the log stream has the above described format. All records are given in the chronological order, that is, the warning records are given in the order, in which the warnings appeared in the program.  It is guaranteed that the log has at least one record. It is guaranteed that the total length of all lines of the log stream doesn't exceed 5·106 (in particular, this means that the length of some line does not exceed 5·106 characters). It is guaranteed that all given dates and times are correct, and the string 'MESSAGE" in all records is non-empty.

If there is no sought moment of time, print -1. Otherwise print a string in the format "2012-MM-DD HH:MM:SS" (without the quotes) — the first moment of time when the number of warnings for the last n seconds got no less than m.

require 'date'

n, m = gets.split.map &:to_i
logs = $<.map { |s| DateTime.parse(s[0, 19]) }
(m - 1).upto(logs.size - 1) do |i|
  if (logs[i] - logs[i - (m - 1)]) * 60 * 60 * 24 < n
    puts logs[i].to_s.gsub(/T/, ' ').gsub(/\+.*/, '')
    exit
  end
end

puts -1

require 'date'

n, m = gets.chomp.split.map &:to_i

l = n + 10
counts = Array.new(l) do |i|
  [0, 0]
end

first = 0
last = prev = 0
total = 0
ans = -1
while line=gets
  time_str = line[0..18]
  time = DateTime.parse(time_str).to_time
  total += 1
  if first != last && time == counts[prev][0]
    counts[prev][1] += 1
  else
    while first != last && counts[first][0] <= time - n
      total -= counts[first][1]
      first += 1
      first = 0 if first == l
    end
    counts[last][0] = time
    counts[last][1] = 1
    prev = last
    last += 1
    last = 0 if last == l
  end
  if total >= m
    ans = time_str
    break
  end
end

puts ans

input = gets.chomp.split
n = Integer(input[0])
m = Integer(input[1])
log_stream = Array.new
while line = gets do
    log_stream.push(line)
end

x = n / 3600
y = (n % 3600) / 60
z = n - 3600 * x - 60 * y

def time_back(log, x, y, z)
    year = log[0..3].to_i
    month = log[5..6].to_i
    date = log[8..9].to_i
    hour = log[11..12].to_i
    minute = log[14..15].to_i
    second = log[17..18].to_i
    if second - z >= 0
        second = second - z
    else
        second = second - z + 60
        y += 1
    end
    if minute - y >= 0
        minute = minute - y
    else
        minute = minute - y + 60
        x += 1
    end
    if hour - x >= 0
        hour = hour - x
    else
        hour = hour - x + 24
        date -= 1
        if date == 0
            month -= 1
            if [1,3,5,7,8,10].include? month
                date = 31
            elsif [4,6,9,11].include? month
                date = 30
            elsif month == 0
                date = 31
                month = 12
                year -= 1
            elsif month == 2
                if year % 4 == 0
                    date = 29
                else
                    date = 28
                end
            end
        end
    end
    if month < 10
        month = "0" + month.to_s
    end
    if date < 10
        date = "0" + date.to_s
    end
    if hour < 10
        hour = "0" + hour.to_s
    end
    if minute < 10
        minute = "0" + minute.to_s
    end
    if second < 10
        second = "0" + second.to_s
    end
    return "#{year}-#{month}-#{date} #{hour}:#{minute}:#{second}"
end

moment = -1
for i in m-1...log_stream.length
    if time_back(log_stream[i], x, y, z) < log_stream[i-m+1][0..18]
        moment = log_stream[i]
        break
    end
end
if moment != -1
    puts moment[0..18]
else
    puts moment
end

require 'date'

n, m = gets.split.map &:to_i
logs = $<.map { |s| DateTime.parse(s.strip).new_offset(0) }
puts logs.map { |l| l.to_time }
puts logs.map { |l| l.to_time.to_s }
puts logs.map { |l| l.to_time.to_s.gsub(/ \+.*/, '_') }
(m - 1).upto(logs.size - 1) do |i|
  if (logs[i] - logs[i - (m - 1)]) * 60 * 60 * 24 < n
    puts logs[i].to_time.to_s.gsub(/ \+.*/, '')
    exit
  end
end

puts -1

require 'date'

n, m = gets.split.map &:to_i
logs = $<.map { |s| DateTime.parse(s.strip) }
puts logs
(m - 1).upto(logs.size - 1) do |i|
  if (logs[i] - logs[i - (m - 1)]) * 60 * 60 * 24 < n
    puts logs[i].to_time.to_s.gsub(/ \+.*/, '')
    exit
  end
end

puts -1

require 'date'

n, m = gets.split.map &:to_i
logs = $<.map { |s| DateTime.parse(s.strip) }
puts logs.map { |l| l.to_time }
puts logs.map { |l| l.to_time.to_s }
puts logs.map { |l| l.to_time.to_s.gsub(/ \+.*/, '_') }
(m - 1).upto(logs.size - 1) do |i|
  if (logs[i] - logs[i - (m - 1)]) * 60 * 60 * 24 < n
    puts logs[i].to_time.to_s.gsub(/ \+.*/, '')
    exit
  end
end

puts -1

require 'date'

n, m = gets.split.map &:to_i
logs = $<.map { |s| DateTime.parse(s.strip) }
(m - 1).upto(logs.size - 1) do |i|
  if (logs[i] - logs[i - (m - 1)]) * 60 * 60 * 24 < n
    puts logs[i].new_offset(0).to_time.to_s.gsub(/ \+.*/, '')
    exit
  end
end

puts -1

require 'date'

n, m = gets.split.map &:to_i
logs = $<.map { |s| DateTime.parse(s.strip) }
(m - 1).upto(logs.size - 1) do |i|
  if (logs[i] - logs[i - (m - 1)]) * 60 * 60 * 24 < n
    puts logs[i].to_s.gsub(/T/, '').gsub(/ \+.*/, '')
    exit
  end
end

puts -1

require 'date'

n, m = gets.split.map &:to_i
logs = $<.map { |s| DateTime.parse(s.strip).new_offset("+0000") }
(m - 1).upto(logs.size - 1) do |i|
  if (logs[i] - logs[i - (m - 1)]) * 60 * 60 * 24 < n
    puts logs[i].to_time.to_s.gsub(/ \+.*/, '')
    exit
  end
end

puts -1

require 'date'

n, m = gets.split.map &:to_i
logs = $<.map { |s| DateTime.parse(s.strip).new_offset("+0000") }
puts logs.map { |l| l.to_time }
puts logs.map { |l| l.to_time.to_s }
puts logs.map { |l| l.to_time.to_s.gsub(/ \+.*/, '_') }
(m - 1).upto(logs.size - 1) do |i|
  if (logs[i] - logs[i - (m - 1)]) * 60 * 60 * 24 < n
    puts logs[i].to_time.to_s.gsub(/ \+.*/, '')
    exit
  end
end

puts -1

require 'date'

n, m = gets.split.map &:to_i
logs = $<.map { |s| DateTime.parse(s[0, 19].strip) }
(m - 1).upto(logs.size - 1) do |i|
  if (logs[i] - logs[i - (m - 1)]) * 60 * 60 * 24 < n
    puts logs[i].to_s.gsub(/T/, ' ').gsub(/ \+.*/, '')
    exit
  end
end

puts -1

require 'date'

n, m = gets.split.map &:to_i
logs = $<.map { |s| DateTime.parse(s.strip) }
(m - 1).upto(logs.size - 1) do |i|
  if (logs[i] - logs[i - (m - 1)]) * 60 * 60 * 24 < n
    puts logs[i].to_s.gsub(/ \+.*/, '')
    exit
  end
end

puts -1

require 'date'

n, m = gets.split.map &:to_i
logs = $<.map { |s| DateTime.parse(s.strip) }
(m - 1).upto(logs.size - 1) do |i|
  puts logs[i]
  if (logs[i] - logs[i - (m - 1)]) * 60 * 60 * 24 < n
    puts logs[i].to_time.to_s.gsub(/ \+.*/, '')
    exit
  end
end

puts -1

require 'date'

n, m = gets.split.map &:to_i
logs = $<.map { |s| DateTime.parse(s.strip) }
(m - 1).upto(logs.size - 1) do |i|
  if (logs[i] - logs[i - (m - 1)]) * 60 * 60 * 24 < n
    puts logs[i].to_s.gsub(/T/, ' ').gsub(/ \+.*/, '')
    exit
  end
end

puts -1

require 'date'

n, m = gets.split.map &:to_i
logs = $<.map { |s| DateTime.parse(s.strip) }
(m - 1).upto(logs.size - 1) do |i|
  if (logs[i] - logs[i - (m - 1)]) * 60 * 60 * 24 < n
    puts logs[i].to_s.gsub(/T/, ' ').gsub(/\+.*/, '')
    exit
  end
end

puts -1

require 'date'

n, m = gets.split.map &:to_i
logs = $<.map { |s| DateTime.parse(s.strip) }
(m - 1).upto(logs.size - 1) do |i|
  if (logs[i] - logs[i - (m - 1)]) * 60 * 60 * 24 < n
    puts logs[i].new_offset(0).to_s.gsub(/ \+.*/, '')
    exit
  end
end

puts -1

require 'date'

n, m = gets.split.map &:to_i
logs = $<.map { |s| DateTime.parse(s.strip) }
(m - 1).upto(logs.size - 1) do |i|
  if (logs[i] - logs[i - (m - 1)]) * 60 * 60 * 24 < n
    puts logs[i].to_time.to_s.gsub(/ \+.*/, '')
    exit
  end
end

puts -1

input = gets.chomp.split
n = Integer(input[0])
m = Integer(input[1])
log_stream = Array.new
while line = gets do
    log_stream.push(line)
end

x = n / 3600
y = (n % 3600) / 60
z = n - 3600 * x - 60 * y

def time_back(log, x, y, z)
    year = log[0..3].to_i
    month = log[5..6].to_i
    date = log[8..9].to_i
    hour = log[11..12].to_i
    minute = log[14..15].to_i
    second = log[17..18].to_i
    if second - z >= 0
        second = second - z
    else
        second = second - z + 60
        y += 1
    end
    if minute - y >= 0
        minute = minute - y
    else
        minute = minute - y + 60
        x += 1
    end
    if hour - x >= 0
        hour = hour - x
    else
        hour = hour - x + 24
        date -= 1
        if date == 0
            month -= 1
            if [1,3,5,7,8,10].include? month
                date = 31
            elsif [4,6,9,11].include? month
                date = 30
            elsif month == 0
                date = 31
                month = 12
                year -= 1
            elsif month == 2
                if year % 4 == 0
                    date = 29
                else
                    date = 28
                end
            end
        end
    end
    if month < 10
        month = "0" + month.to_s
    end
    if date < 10
        date = "0" + date.to_s
    end
    if hour < 10
        hour = "0" + hour.to_s
    end
    if minute < 10
        minute = "0" + minute.to_s
    end
    if second < 10
        second = "0" + second.to_s
    end
    return "#{year}-#{month}-#{date} #{hour}:#{minute}:#{second}"
end

moment = -1
puts log_stream.length
for i in m-1...log_stream.length
    puts
    puts time_back(log_stream[i], x, y, z)
    puts log_stream[i-m+1][0..18]
    if time_back(log_stream[i], x, y, z) < log_stream[i-m+1][0..18]
        moment = log_stream[i]
        break
    end
end
if moment != -1
    puts moment[0..18]
else
    puts moment
end


For a given array $$$a$$$ consisting of $$$n$$$ integers and a given integer $$$m$$$ find if it is possible to reorder elements of the array $$$a$$$ in such a way that $$$\sum_{i=1}^{n}{\sum_{j=i}^{n}{\frac{a_j}{j}}}$$$ equals $$$m$$$? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for example, $$$\frac{5}{2}=2.5$$$.

The first line contains a single integer $$$t$$$ — the number of test cases ($$$1 \le t \le 100$$$). The test cases follow, each in two lines. The first line of a test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$0 \le m \le 10^6$$$). The second line contains integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^6$$$) — the elements of the array.

For each test case print "YES", if it is possible to reorder the elements of the array in such a way that the given formula gives the given value, and "NO" otherwise.

NoteIn the first test case one of the reorders could be $$$[1, 2, 5]$$$. The sum is equal to $$$(\frac{1}{1} + \frac{2}{2} + \frac{5}{3}) + (\frac{2}{2} + \frac{5}{3}) + (\frac{5}{3}) = 8$$$. The brackets denote the inner sum $$$\sum_{j=i}^{n}{\frac{a_j}{j}}$$$, while the summation of brackets corresponds to the sum over $$$i$$$.

gets.chomp.to_i.times do |_i|
  n, m = gets.split.map(&:to_i)
  a = gets.split.map(&:to_i)
  puts (m == a.inject(0, :+) ? 'YES' : 'NO')
end

T = gets.to_i

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

  if a.sum == m
    puts 'YES'
  else
    puts 'NO'
  end
end

t = gets.chomp.to_i
t.times do
  n, m = gets.chomp.split(' ').map(&:to_i)
  c = gets.chomp.split(' ').map(&:to_i)
  if c.sum == m
    puts "YES"
  else
    puts "NO"
  end
end

t = gets.to_i

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

  if(a.sum == m)
    puts "YES"
  else
    puts "NO"
  end
end

test_cases = gets.chomp

test_cases.to_i.times do
 x = gets.chomp.split(" ").map(&:to_i)[1]
 y = gets.chomp.split(" ").map(&:to_i)
 puts y.sum == x ? "YES" : "NO"

end


Very soon Berland will hold a School Team Programming Olympiad. From each of the m Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by n Berland students. There were at least two schoolboys participating from each of the m regions of Berland. The result of each of the participants of the qualifying competition is an integer score from 0 to 800 inclusive.The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points. There may be a situation where a team of some region can not be formed uniquely, that is, there is more than one school team that meets the properties described above. In this case, the region needs to undertake an additional contest. The two teams in the region are considered to be different if there is at least one schoolboy who is included in one team and is not included in the other team. It is guaranteed that for each region at least two its representatives participated in the qualifying contest.Your task is, given the results of the qualifying competition, to identify the team from each region, or to announce that in this region its formation requires additional contests.

The first line of the input contains two integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 10 000, n ≥ 2m) — the number of participants of the qualifying contest and the number of regions in Berland. Next n lines contain the description of the participants of the qualifying contest in the following format: Surname (a string of length from 1 to 10 characters and consisting of large and small English letters), region number (integer from 1 to m) and the number of points scored by the participant (integer from 0 to 800, inclusive). It is guaranteed that all surnames of all the participants are distinct and at least two people participated from each of the m regions. The surnames that only differ in letter cases, should be considered distinct.

Print m lines. On the i-th line print the team of the i-th region — the surnames of the two team members in an arbitrary order, or a single character "?" (without the quotes) if you need to spend further qualifying contests in the region.

5 2
Ivanov 1 763
Andreev 2 800
Petrov 1 595
Sidorov 1 790
Semenov 2 503

5 2
Ivanov 1 800
Andreev 2 763
Petrov 1 800
Sidorov 1 800
Semenov 2 503

NoteIn the first sample region teams are uniquely determined.In the second sample the team from region 2 is uniquely determined and the team from region 1 can have three teams: "Petrov"-"Sidorov", "Ivanov"-"Sidorov", "Ivanov" -"Petrov", so it is impossible to determine a team uniquely.

#!/usr/bin/ruby
n,m=gets.split.map(&:to_i)
h=Hash.new{|h,k|h[k]=[]}
n.times{
	a,b,c=gets.split
	h[b.to_i-1]<<[-c.to_i,a]
}
m.times{|i|
	h[i].sort!
	if h[i].size<=2 || h[i][1][0]!=h[i][2][0]
		puts h[i][0,2].map(&:last)*' '
	else
		puts '?'
	end
}

n, m = gets.chomp.split.map(&:to_i)
memo = Hash.new {|h, k| h[k] = [] }
Player = Struct.new(:name, :point)

n.times do
  name, region, point = gets.chomp.split.map { |e| e == e.to_i.to_s ? e.to_i : e }
  memo[region] << Player.new(name, point)
end

memo.keys.sort.each do |key|
  players = memo[key].sort_by { |p| -p.point }
  selected = players.take(2)

  if players.length <= 2 || players[1..2].map(&:point).uniq.length == 2
    puts selected.map(&:name).join(' ')
  else
    puts "?"
  end
end

n, m = readline.split(' ').collect(&:to_i)
arr = Array.new(m) {Array.new}
n.times do
  name, region, mark = readline.split(' ')
  region, mark = region.to_i, mark.to_i
  arr[region - 1].push([mark, name])
end
arr.each do |a|
  a.sort!.reverse!
  if a.length <= 2 || a[2][0] < a[1][0]
    print a[0][1], " ", a[1][1]
    puts
  else
    puts "?"
  end
end

a=gets.chomp.split(" ")
input=a[0].to_i
city=a[1].to_i
max2=Array.new(city){Array.new(2,0)}
name=Array.new(city) {Hash.new { |hash, key| hash[key] = [] } }
input.times do
temp=gets.chomp.split(" ")
tc=temp[1].to_i
ts=temp[2].to_i
if ts>max2[tc-1][0]
max2[tc-1][1]=max2[tc-1][0]
max2[tc-1][0]=ts
elsif ts>max2[tc-1][1]
max2[tc-1][1]=ts
end
name[tc-1][ts]<<temp[0]
end
0.upto(city-1) do |i|
if max2[i][0]==max2[i][1]
if name[i][max2[i][0]].length>2
puts "?"
else
puts name[i][max2[i][0]].join(" ")
end
else
if name[i][max2[i][0]].length + name[i][max2[i][1]].length>2
puts "?"
else
printf "#{ name[i][max2[i][0]][0]} "
puts "#{ name[i][max2[i][1]][0]}"
end
end
end

n, m = gets.split.map(&:to_i)
a = Array.new(m).map{Array.new}
n.times do
  na, re, sc = gets.split
  re = re.to_i - 1
  sc = sc.to_i
  a[re].push([sc, na])
end

m.times do |i|
  t = a[i].sort{ |x, y| y[0] <=> x[0] }
  if t.length < 3
    puts "#{t[0][1]} #{t[1][1]}"
  elsif t[1][0] == t[2][0]
    puts "?"
  else
    puts "#{t[0][1]} #{t[1][1]}"
  end
end

def update(g, str, score)
	if !$a[g][0] || score >= $a[g][0]
		$a[g][2] = $a[g][1]
		$a[g][1] = $a[g][0]
		$a[g][0] = score
		$name[g][2] = $name[g][1]
		$name[g][1] = $name[g][0]
		$name[g][0] = str
	elsif !$a[g][1] || score >= $a[g][1]
		$a[g][2] = $a[g][1]
		$a[g][1] = score
		$name[g][2] = $name[g][1]
		$name[g][1] = str
	elsif !$a[g][2] || score >= $a[g][2]
		$a[g][2] = score
		$name[g][2] = str
	end
end

buf=gets.split(' ')
n,m=buf[0].to_i, buf[1].to_i
$a=Array.new(m+1)
$name=Array.new(m+1)
for i in 1..m
	$a[i]=Array.new(3)
	$name[i]=Array.new(3)
end
for i in 1..n
	buf=gets.split(' ')
	update(buf[1].to_i, buf[0], buf[2].to_i)
end
for i in 1..m
	if $a[i][1] == $a[i][2]
		puts '?'
	else
		puts $name[i][0] + ' ' + $name[i][1]
	end
end

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

region = Array.new(m) { |r| r = [] }
ans = Array.new(m) { |r| r = [] }
n.times do
    info = gets.chomp.split(' ')
    region[info[1].to_i - 1] << [info[0], info[2].to_i]
end

region.each do |r|
    r.sort! { |a, b| if a[1] > b[1] then -1 elsif a[1] < b[1] then 1 else 0 end }
end

region.each_with_index do |r, i|
    sameWithMax = r.count { |p| p[1] == r[0][1] }
    sameWithSubSequent = 0

    if (sameWithMax < r.length)
        sameWithSubSequent = r.count { |p| p[1] == r[sameWithMax][1] }
    end

    if (sameWithMax >= 3 || (sameWithMax < 2 && sameWithMax + sameWithSubSequent >= 3))
        ans[i] << '?'
    else
        ans[i] << "#{r[0][0]} #{r[1][0]}"
    end
end

ans.each do |a|
    puts a
end

n, m = gets.chomp.split.map(&:to_i)
memo = Hash.new {|h, k| h[k] = [] }
Player = Struct.new(:name, :point)

n.times do
  name, region, point = gets.chomp.split.map { |e| e == e.to_i.to_s ? e.to_i : e }
  memo[region] << Player.new(name, point)
end

memo.keys.sort.each do |key|
  players = memo[key].sort_by { |p| -p.point }
  selected = players.take(2)

  if players.length <= 2 || players[1..2].map(&:point).uniq == 1
    puts selected.map(&:name).join(' ')
  else
    puts "?"
  end
end

n, m = gets.chomp.split.map(&:to_i)
memo = Hash.new {|h, k| h[k] = [] }
Player = Struct.new(:name, :point)

n.times do
  name, region, point = gets.chomp.split.map { |e| e == e.to_i.to_s ? e.to_i : e }
  memo[region] << Player.new(name, point)
end

memo.keys.sort.each do |key|
  players = memo[key]
  max = players.map(&:point).max
  max_players = players.select { |p| p.point == max }
  selected = players.sort_by { |p| -p.point }.take(2)
  if max_players.length > 2 || selected.map(&:name).uniq.length == 1
    puts "?"
  else
    puts selected.map(&:name).join(' ')
  end
end

n, m = gets.chomp.split.map(&:to_i)
memo = Hash.new {|h, k| h[k] = [] }
Player = Struct.new(:name, :point)

n.times do
  name, region, point = gets.chomp.split.map { |e| e == e.to_i.to_s ? e.to_i : e }
  memo[region] << Player.new(name, point)
end

memo.keys.sort.each do |key|
  players = memo[key]
  max = players.map(&:point).max
  if players.map(&:point).select { |p| p == max }.length > 2
    puts "?"
  else
    puts players.sort_by { |p| -p.point }.take(2).map(&:name).join(' ')
  end
end

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

region = Array.new(m) { |r| r = [] }
ans = Array.new(m) { |r| r = [] }
n.times do
    info = gets.chomp.split(' ')
    region[info[1].to_i - 1] << [info[0], info[2].to_i]
end

region.each do |r|
    r.sort! { |a, b| if a[1] > b[1] then -1 elsif a[1] < b[1] then 1 else 0 end }
end

region.each_with_index do |r, i|
    sameWithMax = r.count { |p| p[1] == r[0][1] }
    sameWithSubSequent = 0

    if (sameWithMax < r.length)
        sameWithSubSequent = r.count { |p| p[1] == r[sameWithMax][1] }
    end

    if (sameWithMax + sameWithSubSequent >= 3)
        ans[i] << '?'
    else
        ans[i] << "#{r[0][0]} #{r[1][0]}"
    end
end

ans.each do |a|
    puts a
end