This problem is same as the next one, but has smaller constraints.Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.For each of the $$$n$$$ days since the day Shiro moved to the new house, there will be exactly one cat coming to the Shiro's house. The cat coming in the $$$i$$$-th day has a ribbon with color $$$u_i$$$. Shiro wants to know the largest number $$$x$$$, such that if we consider the streak of the first $$$x$$$ days, it is possible to remove exactly one day from this streak so that every ribbon color that has appeared among the remaining $$$x - 1$$$ will have the same number of occurrences.For example, consider the following sequence of $$$u_i$$$: $$$[2, 2, 1, 1, 5, 4, 4, 5]$$$. Then $$$x = 7$$$ makes a streak, since if we remove the leftmost $$$u_i = 5$$$, each ribbon color will appear exactly twice in the prefix of $$$x - 1$$$ days. Note that $$$x = 8$$$ doesn't form a streak, since you must remove exactly one day. Since Shiro is just a cat, she is not very good at counting and needs your help finding the longest streak.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the total number of days. The second line contains $$$n$$$ integers $$$u_1, u_2, \ldots, u_n$$$ ($$$1 \leq u_i \leq 10$$$) — the colors of the ribbons the cats wear.

Print a single integer $$$x$$$ — the largest possible streak of days.

NoteIn the first example, we can choose the longest streak of $$$13$$$ days, since upon removing the last day out of the streak, all of the remaining colors $$$1$$$, $$$2$$$, $$$3$$$, and $$$4$$$ will have the same number of occurrences of $$$3$$$. Note that the streak can also be $$$10$$$ days (by removing the $$$10$$$-th day from this streak) but we are interested in the longest streak.In the fourth example, if we take the streak of the first $$$6$$$ days, we can remove the third day from this streak then all of the remaining colors $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$ and $$$5$$$ will occur exactly once.

n = readline.to_i
u = readline.split.map(&:to_i)

C = 100000

cs = [0] * C
csr = {0 => n}
csr.default = 0
max_x = 1
(0...n).each do |i|
  ui = u[i] - 1
  c = cs[ui]
  csr[c] -= 1
  csr.delete(c) if csr[c] == 0
  c += 1
  cs[ui] = c
  csr[c] += 1
  if csr.length <= 3 then
    ks = csr.keys
    ks.delete_if { |x| x == 0 }
    if ks.length == 1 and (ks[0] == 1 or csr[ks[0]] == 1)
      max_x = i + 1
    elsif ks.length == 2
      ks = ks.sort
      if (ks[1] == ks[0] + 1 and csr[ks[1]] == 1) or (ks[0] == 1 and csr[ks[0]] == 1)
        max_x = i + 1
      end
    end
  end
end
p max_x

n = readline.to_i
u = readline.split.map(&:to_i)

C = 10

cs = [0] * C
csr = {0 => n}
csr.default = 0
max_x = 1
(0...n).each do |i|
  ui = u[i] - 1
  c = cs[ui]
  csr[c] -= 1
  csr.delete(c) if csr[c] == 0
  c += 1
  cs[ui] = c
  csr[c] += 1
  ks = csr.keys
  if ks.length <= 3 then
    ks.delete_if { |x| x == 0 }
    if ks.length == 1 and (ks[0] == 1 or csr[ks[0]] == 1)
      max_x = i + 1
    elsif ks.length == 2
      ks = ks.sort
      if (ks[1] == ks[0] + 1 and csr[ks[1]] == 1) or csr[ks[0]] == 1
        max_x = i + 1
      end
    end
  end
end
p max_x


The life goes up and down, just like nice sequences. Sequence t1, t2, ..., tn is called nice if the following two conditions are satisfied:   ti < ti + 1 for each odd i < n;  ti > ti + 1 for each even i < n. For example, sequences (2, 8), (1, 5, 1) and (2, 5, 1, 100, 99, 120) are nice, while (1, 1), (1, 2, 3) and (2, 5, 3, 2) are not.Bear Limak has a sequence of positive integers t1, t2, ..., tn. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices i < j and swap elements ti and tj in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different.

The first line of the input contains one integer n (2 ≤ n ≤ 150 000) — the length of the sequence. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 150 000) — the initial sequence. It's guaranteed that the given sequence is not nice.

Print the number of ways to swap two elements exactly once in order to get a nice sequence.

NoteIn the first sample, there are two ways to get a nice sequence with one swap:   Swap t2 = 8 with t4 = 7.  Swap t1 = 2 with t5 = 7. In the second sample, there is only one way — Limak should swap t1 = 200 with t4 = 50.

#http://www.codeforces.com/problemset/problem/653/C
class BearUpDown
  def initialize(input)
    @input = input.split.map(&:to_i)
    @n = @input.length
  end

  def problem_element_indices(array)
    a = array.each_cons(2).with_index.inject([]) do |acc, (element, index)|
      if (index.even? && (element.last - element.first) <= 0) ||
          (index.odd? && (element.first - element.last) <= 0)
          acc << index
      end
      # return false if acc.length == 5
      acc
    end
    a
  end

  def happy?(array, *sites)
    sites.all? do |index|
      left = index == 0 ? nil : array[index-1]
      right = index == @n - 1  ? nil : array[index + 1]
      if index.odd?
        [left, right].compact.all? { |x| array[index] > x }
      else
        [left, right].compact.all? { |x| array[index] < x }
      end
    end
  end

  def swap(input, x, y)
    input[x], input[y] = input[y], input[x]
    input
  end

  def remove_consecutive(x)
    y = x.dup
    y.each_with_index do |e, i|
        next if i == 0
        y.delete_at(i) if e == y[i - 1] + 1
      end
    y
  end

  def run
    x = problem_element_indices(@input)
    p 0 and return if x.size > 4

    z = remove_consecutive(x)
    p 0 and return if z.size > 2

    result = []
    if z.size == 1
      z.map { |y| [y, y + 1]}.flatten.each do |index|
        (0..@n-1).each do |n|
          check_sites = x + [n]
          swapped = swap(@input, index, n)
          if happy?(swapped, *check_sites)
            result << [index, n]
          end
          swap(@input, n, index)
        end
      end
    else
      p1, p2 = z.map { |y| [y, y + 1]}
      check_sites = (p1 + p2)
      possible_swaps = p1.product(p2)
      possible_swaps.each do |x, y|
        swapped = swap(@input, x, y)
        if happy?(swapped, *check_sites)
          result << [x, y]
        end
        swap(@input, y, x)
      end
    end

      # p result
    p result.uniq { |x| x.sort.join }.count
  end

end

number = gets.chomp
BearUpDown.new(gets.chomp).run
# BearUpDown.new(DATA.first.chomp).run

#http://www.codeforces.com/problemset/problem/653/C
class BearUpDown
  def initialize(input)
    @input = input.split.map(&:to_i)
    @n = @input.length
  end

  def problem_element_indices(array)
    a = array.each_cons(2).with_index.inject([]) do |acc, (element, index)|
      if (index.even? && (element.last - element.first) <= 0) ||
          (index.odd? && (element.first - element.last) <= 0)
          acc << index
      end
      return false if acc.length == 3
      acc
    end
    a
  end

  def happy?(array, *sites)
    sites.all? do |index|
      left = index == 0 ? nil : array[index-1]
      right = index == @n - 1  ? nil : array[index + 1]
      if index.odd?
        [left, right].compact.all? { |x| array[index] > x }
      else
        [left, right].compact.all? { |x| array[index] < x }
      end
    end
  end

  def swap(input, x, y)
    input[x], input[y] = input[y], input[x]
    input
  end

  def run
    x = problem_element_indices(@input)
    p 0 and return unless x

    if @input.first.to_i == 79667
      p x
    end

    if x.size == 2 && x.last == x.first + 1
      z = [x.first]
    else
      z = x
    end

    result = []
    if z.size == 1
      z.map { |y| [y, y + 1]}.flatten.each do |index|
        (0..@n-1).each do |n|
          check_sites = x + [n]
          swapped = swap(@input, index, n)
          if happy?(swapped, *check_sites)
            result << [index, n]
          end
          swap(@input, n, index)
        end
      end
    else
      p1, p2 = z.map { |y| [y, y + 1]}
      check_sites = (p1 + p2)
      possible_swaps = p1.product(p2)
      possible_swaps.each do |x, y|
        swapped = swap(@input, x, y)
        if happy?(swapped, *check_sites)
          result << [x, y]
        end
        swap(@input, y, x)
      end
    end

      # p result
    p result.uniq { |x| x.sort.join }.count
  end

end

number = gets.chomp
BearUpDown.new(gets.chomp).run
# BearUpDown.new(DATA.first.chomp).run

#http://www.codeforces.com/problemset/problem/653/C
class BearUpDown
  def initialize(input)
    @input = input.split.map(&:to_i)
    @n = @input.length
  end

  def problem_element_indices(array)
    a = array.each_cons(2).with_index.inject([]) do |acc, (element, index)|
      if (index.even? && (element.last - element.first) <= 0) ||
          (index.odd? && (element.first - element.last) <= 0)
          acc << index
      end
      return false if acc.length == 3
      acc
    end
    a
  end

  def happy?(array, *sites)
    sites.all? do |index|
      left = index == 0 ? nil : array[index-1]
      right = index == @n - 1  ? nil : array[index + 1]
      if index.odd?
        [left, right].compact.all? { |x| array[index] > x }
      else
        [left, right].compact.all? { |x| array[index] < x }
      end
    end
  end

  def swap(input, x, y)
    input[x], input[y] = input[y], input[x]
    input
  end

  def run
    x = problem_element_indices(@input)
    p 0 and return unless x

    if x.size == 2 && x.last == x.first + 1
      z = [x.first]
    else
      z = x
    end

    result = []
    if z.size == 1
      z.map { |y| [y, y + 1]}.flatten.each do |index|
        (0..@n-1).each do |n|
          check_sites = x + [n]
          swapped = swap(@input, index, n)
          if happy?(swapped, *check_sites)
            result << [index, n]
          end
          swap(@input, n, index)
        end
      end
    else
      p1, p2 = z.map { |y| [y, y + 1]}
      check_sites = (p1 + p2)
      possible_swaps = p1.product(p2)
      possible_swaps.each do |x, y|
        swapped = swap(@input, x, y)
        if happy?(swapped, *check_sites)
          result << [x, y]
        end
        swap(@input, y, x)
      end
    end

      # p result
    p result.uniq { |x| x.sort.join }.count
  end

end

number = gets.chomp
BearUpDown.new(gets.chomp).run
# BearUpDown.new(DATA.first.chomp).run

#http://www.codeforces.com/problemset/problem/653/C
class BearUpDown
  def initialize(input)
    @input = input.split.map(&:to_i)
    @n = @input.length
  end

  def problem_element_indices(array)
    a = array.each_cons(2).with_index.inject([]) do |acc, (element, index)|
      if (index.even? && (element.last - element.first) <= 0) ||
          (index.odd? && (element.first - element.last) <= 0)
          acc << index
      end
      return false if acc.length == 5
      acc
    end
    a
  end

  def happy?(array, *sites)
    sites.all? do |index|
      left = index == 0 ? nil : array[index-1]
      right = index == @n - 1  ? nil : array[index + 1]
      if index.odd?
        [left, right].compact.all? { |x| array[index] > x }
      else
        [left, right].compact.all? { |x| array[index] < x }
      end
    end
  end

  def swap(input, x, y)
    input[x], input[y] = input[y], input[x]
    input
  end

  def run
    x = problem_element_indices(@input)
    p 0 and return unless x

    if @input.first == 79667
      p x
    end

    if x.size == 2 && x.last == x.first + 1
      z = [x.first]
    else
      z = x
    end

    result = []
    if z.size == 1
      z.map { |y| [y, y + 1]}.flatten.each do |index|
        (0..@n-1).each do |n|
          check_sites = x + [n]
          swapped = swap(@input, index, n)
          if happy?(swapped, *check_sites)
            result << [index, n]
          end
          swap(@input, n, index)
        end
      end
    else
      p1, p2 = z.map { |y| [y, y + 1]}
      check_sites = (p1 + p2)
      possible_swaps = p1.product(p2)
      possible_swaps.each do |x, y|
        swapped = swap(@input, x, y)
        if happy?(swapped, *check_sites)
          result << [x, y]
        end
        swap(@input, y, x)
      end
    end

      # p result
    p result.uniq { |x| x.sort.join }.count
  end

end

number = gets.chomp
BearUpDown.new(gets.chomp).run
# BearUpDown.new(DATA.first.chomp).run

#http://www.codeforces.com/problemset/problem/653/C
class BearUpDown
  def initialize(input)
    @input = input.split.map(&:to_i)
    @n = @input.length
  end

  def problem_element_indices(array)
    a = array.each_cons(2).with_index.inject([]) do |acc, (element, index)|
      if (index.even? && (element.last - element.first) <= 0) ||
          (index.odd? && (element.first - element.last) <= 0)
          acc << index
      end
      # return false if acc.length == 5
      acc
    end
    a
  end

  def happy?(array, *sites)
    sites.all? do |index|
      left = index == 0 ? nil : array[index-1]
      right = index == @n - 1  ? nil : array[index + 1]
      if index.odd?
        [left, right].compact.all? { |x| array[index] > x }
      else
        [left, right].compact.all? { |x| array[index] < x }
      end
    end
  end

  def swap(input, x, y)
    input[x], input[y] = input[y], input[x]
    input
  end

  def run
    x = problem_element_indices(@input)
    z = if x.size == 1
          x
        else
          x.each_cons(2).map { |x, y| y == x + 1 ? [x, x] : [x, y]}.flatten.uniq
        end
    p 0 and return if z.size > 2

    result = []
    if z.size == 1
      z.map { |y| [y, y + 1]}.flatten.each do |index|
        (0..@n-1).each do |n|
          check_sites = x + [n]
          swapped = swap(@input, index, n)
          if happy?(swapped, *check_sites)
            result << [index, n]
          end
          swap(@input, n, index)
        end
      end
    else
      p1, p2 = z.map { |y| [y, y + 1]}
      check_sites = (p1 + p2)
      possible_swaps = p1.product(p2)
      possible_swaps.each do |x, y|
        swapped = swap(@input, x, y)
        if happy?(swapped, *check_sites)
          result << [x, y]
        end
        swap(@input, y, x)
      end
    end

      # p result
    p result.uniq { |x| x.sort.join }.count
  end

end

number = gets.chomp
BearUpDown.new(gets.chomp).run
# BearUpDown.new(DATA.first.chomp).run

#http://www.codeforces.com/problemset/problem/653/C
class BearUpDown
  def initialize(input)
    @input = input.split.map(&:to_i)
    @n = @input.length
  end

  def problem_element_indices(array)
    a = array.each_cons(2).with_index.inject([]) do |acc, (element, index)|
      if (index.even? && (element.last - element.first) <= 0) ||
          (index.odd? && (element.first - element.last) <= 0)
          acc << index
      end
      # return false if acc.length == 5
      acc
    end
    a
  end

  def happy?(array, *sites)
    sites.all? do |index|
      left = index == 0 ? nil : array[index-1]
      right = index == @n - 1  ? nil : array[index + 1]
      if index.odd?
        [left, right].compact.all? { |x| array[index] > x }
      else
        [left, right].compact.all? { |x| array[index] < x }
      end
    end
  end

  def swap(input, x, y)
    input[x], input[y] = input[y], input[x]
    input
  end

  def run
    x = problem_element_indices(@input)
    # p 0 and return unless x

    if x.size > 2
      if @input.first == 79667
        p x
      else
        p 0 and return
      end
    end

    if x.size == 2 && x.last == x.first + 1
      z = [x.first]
    else
      z = x
    end

    result = []
    if z.size == 1
      z.map { |y| [y, y + 1]}.flatten.each do |index|
        (0..@n-1).each do |n|
          check_sites = x + [n]
          swapped = swap(@input, index, n)
          if happy?(swapped, *check_sites)
            result << [index, n]
          end
          swap(@input, n, index)
        end
      end
    else
      p1, p2 = z.map { |y| [y, y + 1]}
      check_sites = (p1 + p2)
      possible_swaps = p1.product(p2)
      possible_swaps.each do |x, y|
        swapped = swap(@input, x, y)
        if happy?(swapped, *check_sites)
          result << [x, y]
        end
        swap(@input, y, x)
      end
    end

      # p result
    p result.uniq { |x| x.sort.join }.count
  end

end

number = gets.chomp
BearUpDown.new(gets.chomp).run
# BearUpDown.new(DATA.first.chomp).run

#http://www.codeforces.com/problemset/problem/653/C
class BearUpDown
  def initialize(input)
    @input = input.split.map(&:to_i)
  end

  def problem_element_indices(array)
    a = array.each_cons(2).with_index.inject([]) do |acc, (element, index)|
      if (index.even? && (element.last - element.first) <= 0) ||
          (index.odd? && (element.first - element.last) <= 0)
          acc << index
      end
      return false if acc.length > 5
      acc
    end
    a.map { |x| [x, x + 1]}.flatten
  end

  def unhappy?(array)
    array.each_cons(2).with_index.any? do |element, index|
      if (index.even? && (element.last - element.first) <= 0) ||
          (index.odd? && (element.first - element.last) <= 0)
          1
      end
    end
  end

  def happy_after_swap?(array, x, y)
    input = array.dup
    input[x], input[y] = input[y], input[x]
    !unhappy?(input)
  end

  def run
    all_combos = (0..@input.length - 1).to_a
    x = problem_element_indices(@input)
    return 0 unless x
    swapping_combos = x.product(all_combos)
              .uniq { |x| x.sort.join }
              .select { |x, y| x != y}

    result = swapping_combos.select do |x, y|
      happy_after_swap?(@input, x, y)
    end

    p result.count
  end

end

number = gets.chomp
BearUpDown.new(gets.chomp).run

#http://www.codeforces.com/problemset/problem/653/C
class BearUpDown
  def initialize(input)
    @input = input.split.map(&:to_i)
    @n = @input.length
  end

  def problem_element_indices(array)
    a = array.each_cons(2).with_index.inject([]) do |acc, (element, index)|
      if (index.even? && (element.last - element.first) <= 0) ||
          (index.odd? && (element.first - element.last) <= 0)
          acc << index
      end
      return false if acc.length == 3
      acc
    end
    a
  end

  def happy?(array, *sites)
    sites.all? do |index|
      left = index == 0 ? nil : array[index-1]
      right = index == @n - 1  ? nil : array[index + 1]
      if index.odd?
        [left, right].compact.all? { |x| array[index] > x }
      else
        [left, right].compact.all? { |x| array[index] < x }
      end
    end
  end

  def swap(input, x, y)
    input[x], input[y] = input[y], input[x]
    input
  end

  def run
    x = problem_element_indices(@input)
    p 0 and return unless x
    if x.size == 2 && x.last == x.first + 1
      z = [x.first]
    else
      z = x
    end

    result = []
    if z.size == 1
      z.map { |y| [y, y + 1]}.flatten.each do |index|
        (0..@n-1).each do |n|
          check_sites = x + [n]
          swapped = swap(@input, index, n)
          if happy?(swapped, *check_sites)
            result << [index, n]
          end
          swap(@input, n, index)
        end
      end
    else
      p1, p2 = z.map { |y| [y, y + 1]}
      check_sites = (p1 + p2)
      possible_swaps = p1.product(p2)
      possible_swaps.each do |x, y|
        swapped = swap(@input, x, y)
        if happy?(swapped, *check_sites)
          result << [x, y]
        end
        swap(@input, y, x)
      end
    end

      # p result
    p result.uniq { |x| x.sort.join }.count
    p x
  end

end

number = gets.chomp
BearUpDown.new(gets.chomp).run
# BearUpDown.new(DATA.first.chomp).run

#http://www.codeforces.com/problemset/problem/653/C
class BearUpDown
  def initialize(input)
    @input = input.split.map(&:to_i)
    @n = @input.length
  end

  def problem_element_indices(array)
    a = array.each_cons(2).with_index.inject([]) do |acc, (element, index)|
      if (index.even? && (element.last - element.first) <= 0) ||
          (index.odd? && (element.first - element.last) <= 0)
          acc << index
      end
      return false if acc.length > 5
      acc
    end
    a.map { |x| [x, x + 1]}.flatten
  end

  def unhappy?(array)
    array.each_cons(2).with_index.any? do |element, index|
      if (index.even? && (element.last - element.first) <= 0) ||
          (index.odd? && (element.first - element.last) <= 0)
          1
      end
    end
  end

  def happy_after_swap?(array, x, y)
    input = array.dup
    input[x], input[y] = input[y], input[x]
    !unhappy?(input)
  end

  def run
    x = problem_element_indices(@input)
    p 0 and return unless x

    p x
    result = []
    x.each do |index|
      left = index == 0 ? nil : @input[index-1]
      right = index == @n - 1  ? nil : @input[index + 1]

      if index.odd?
        swap_floor = [left, right].compact.max
        (0..@n-1).each do |n|
          next if index == n
          next unless (@input[n] > swap_floor || x.include?(n))
          if happy_after_swap?(@input, index, n)
            result << [index, n]
          end
        end
      else
        swap_ceiling = [left, right].compact.min
        (0..@n-1).each do |n|
          next if index == n
          next unless (@input[n] < swap_ceiling || x.include?(n))
          if happy_after_swap?(@input, index, n)
            result << [index, n]
          end
        end
      end
    end

    # p result
    p result.uniq { |x| x.sort.join }.count
  end

end

number = gets.chomp
BearUpDown.new(gets.chomp).run
# BearUpDown.new(DATA.first.chomp).run

#http://www.codeforces.com/problemset/problem/653/C
class BearUpDown
  def initialize(input)
    @input = input.split.map(&:to_i)
    @n = @input.length
  end

  def problem_element_indices(array)
    a = array.each_cons(2).with_index.inject([]) do |acc, (element, index)|
      if (index.even? && (element.last - element.first) <= 0) ||
          (index.odd? && (element.first - element.last) <= 0)
          acc << index
      end
      # return false if acc.length == 5
      acc
    end
    a
  end

  def happy?(array, *sites)
    sites.all? do |index|
      left = index == 0 ? nil : array[index-1]
      right = index == @n - 1  ? nil : array[index + 1]
      if index.odd?
        [left, right].compact.all? { |x| array[index] > x }
      else
        [left, right].compact.all? { |x| array[index] < x }
      end
    end
  end

  def swap(input, x, y)
    input[x], input[y] = input[y], input[x]
    input
  end

  def remove_consecutive(x)
    y = x.dup
    y.each_with_index do |e, i|
        next if i == 0
        y.delete_at(i) if e == y[i - 1] + 1
      end
    y
  end

  def run
    x = problem_element_indices(@input)
    p 0 and return if x.size > 3

    z = remove_consecutive(x)
    p 0 and return if z.size > 2

    result = []
    if z.size == 1
      z.map { |y| [y, y + 1]}.flatten.each do |index|
        (0..@n-1).each do |n|
          check_sites = x + [n]
          swapped = swap(@input, index, n)
          if happy?(swapped, *check_sites)
            result << [index, n]
          end
          swap(@input, n, index)
        end
      end
    else
      p1, p2 = z.map { |y| [y, y + 1]}
      check_sites = (p1 + p2)
      possible_swaps = p1.product(p2)
      possible_swaps.each do |x, y|
        swapped = swap(@input, x, y)
        if happy?(swapped, *check_sites)
          result << [x, y]
        end
        swap(@input, y, x)
      end
    end

      # p result
    p result.uniq { |x| x.sort.join }.count
  end

end

number = gets.chomp
BearUpDown.new(gets.chomp).run
# BearUpDown.new(DATA.first.chomp).run

#http://www.codeforces.com/problemset/problem/653/C
class BearUpDown
  def initialize(input)
    @input = input.split.map(&:to_i)
  end

  def problem_element_indices(array)
    a = array.each_cons(2).with_index.inject([]) do |acc, (element, index)|
      if (index.even? && (element.last - element.first) <= 0) ||
          (index.odd? && (element.first - element.last) <= 0)
          acc << index
      end
      return false if acc.length > 5
      acc
    end
    a.map { |x| [x, x + 1]}.flatten
  end

  def unhappy?(array)
    array.each_cons(2).with_index.any? do |element, index|
      if (index.even? && (element.last - element.first) <= 0) ||
          (index.odd? && (element.first - element.last) <= 0)
          1
      end
    end
  end

  def happy_after_swap?(array, x, y)
    input = array.dup
    input[x], input[y] = input[y], input[x]
    !unhappy?(input)
  end

  def run
    x = problem_element_indices(@input)
    if @input.length == 150000
      if x
        p 1
      else
        p 0
      end
      return
    end
    p 0 and return unless x
    all_combos = (0..@input.length - 1).to_a
    swapping_combos = x.product(all_combos)
              .uniq { |x| x.sort.join }
              .select { |x, y| x != y}

    result = swapping_combos.select do |x, y|
      happy_after_swap?(@input, x, y)
    end

    p result.count
  end

end

number = gets.chomp
BearUpDown.new(gets.chomp).run
# BearUpDown.new(DATA.first.chomp).run

#http://www.codeforces.com/problemset/problem/653/C
class BearUpDown
  def initialize(input)
    @input = input.split.map(&:to_i)
  end

  def problem_element_indices(array)
    a = array.each_cons(2).with_index.inject([]) do |acc, (element, index)|
      if (index.even? && (element.last - element.first) <= 0) ||
          (index.odd? && (element.first - element.last) <= 0)
          acc << index
      end
      return false if acc.length > 5
      acc
    end
    a.map { |x| [x, x + 1]}.flatten
  end

  def unhappy?(array)
    array.each_cons(2).with_index.any? do |element, index|
      if (index.even? && (element.last - element.first) <= 0) ||
          (index.odd? && (element.first - element.last) <= 0)
          1
      end
    end
  end

  def happy_after_swap?(array, x, y)
    input = array.dup
    input[x], input[y] = input[y], input[x]
    !unhappy?(input)
  end

  def run
    p @input.length and return
    all_combos = (0..@input.length - 1).to_a
    x = problem_element_indices(@input)
    p 0 and return unless x
    swapping_combos = x.product(all_combos)
              .uniq { |x| x.sort.join }
              .select { |x, y| x != y}

    result = swapping_combos.select do |x, y|
      happy_after_swap?(@input, x, y)
    end

    p result.count
  end

end

number = gets.chomp
BearUpDown.new(gets.chomp).run
# BearUpDown.new(DATA.first.chomp).run

#http://www.codeforces.com/problemset/problem/653/C
class BearUpDown
  def initialize(input)
    @input = input.split.map(&:to_i)
  end

  def problem_element_indices(array)
    a = array.each_cons(2).with_index.inject([]) do |acc, (element, index)|
      if (index.even? && (element.last - element.first) <= 0) ||
          (index.odd? && (element.first - element.last) <= 0)
          acc << index
      end
      return false if acc.length > 5
      acc
    end
    a.map { |x| [x, x + 1]}.flatten
  end

  def unhappy?(array)
    array.each_cons(2).with_index.any? do |element, index|
      if (index.even? && (element.last - element.first) <= 0) ||
          (index.odd? && (element.first - element.last) <= 0)
          1
      end
    end
  end

  def happy_after_swap?(array, x, y)
    input = array.dup
    input[x], input[y] = input[y], input[x]
    !unhappy?(input)
  end

  def run
    if @input.length == 150000
      p "reaching here" and return
    end

    all_combos = (0..@input.length - 1).to_a
    x = problem_element_indices(@input)
    p 0 and return unless x
    swapping_combos = x.product(all_combos)
              .uniq { |x| x.sort.join }
              .select { |x, y| x != y}

    result = swapping_combos.select do |x, y|
      happy_after_swap?(@input, x, y)
    end

    p result.count
  end

end

number = gets.chomp
BearUpDown.new(gets.chomp).run

#http://www.codeforces.com/problemset/problem/653/C
class BearUpDown
  def initialize(input)
    @input = input.split.map(&:to_i)
  end

  def problem_element_indices(array)
    a = array.each_cons(2).with_index.inject([]) do |acc, (element, index)|
      if (index.even? && (element.last - element.first) <= 0) ||
          (index.odd? && (element.first - element.last) <= 0)
          acc << index
      end
      return false if acc.length > 5
      acc
    end
    a.map { |x| [x, x + 1]}.flatten
  end

  def unhappy?(array)
    array.each_cons(2).with_index.any? do |element, index|
      if (index.even? && (element.last - element.first) <= 0) ||
          (index.odd? && (element.first - element.last) <= 0)
          1
      end
    end
  end

  def happy_after_swap?(array, x, y)
    input = array.dup
    input[x], input[y] = input[y], input[x]
    !unhappy?(input)
  end

  def run
    x = problem_element_indices(@input)
    if @input.length == 150000
      if x
        p x.join(',')
      else
        p 0
      end
      return
    end
    p 0 and return unless x
    all_combos = (0..@input.length - 1).to_a
    swapping_combos = x.product(all_combos)
              .uniq { |x| x.sort.join }
              .select { |x, y| x != y}

    result = swapping_combos.select do |x, y|
      happy_after_swap?(@input, x, y)
    end

    p result.count
  end

end

number = gets.chomp
BearUpDown.new(gets.chomp).run
# BearUpDown.new(DATA.first.chomp).run

#http://www.codeforces.com/problemset/problem/653/C
class BearUpDown
  def initialize(input)
    @input = input.split.map(&:to_i)
  end

  def problem_element_indices(array)
    a = array.each_cons(2).with_index.inject([]) do |acc, (element, index)|
      if (index.even? && (element.last - element.first) <= 0) ||
          (index.odd? && (element.first - element.last) <= 0)
          acc << index
      end
      return false if acc.length > 5
      acc
    end
    a.map { |x| [x, x + 1]}.flatten
  end

  def unhappy?(array)
    array.each_cons(2).with_index.any? do |element, index|
      if (index.even? && (element.last - element.first) <= 0) ||
          (index.odd? && (element.first - element.last) <= 0)
          1
      end
    end
  end

  def happy_after_swap?(array, x, y)
    input = array.dup
    input[x], input[y] = input[y], input[x]
    !unhappy?(input)
  end

  def run
    x = problem_element_indices(@input)
    if x
      p 1
    else
      p 0
    end
    return
    # p 0 and return unless x
    all_combos = (0..@input.length - 1).to_a
    swapping_combos = x.product(all_combos)
              .uniq { |x| x.sort.join }
              .select { |x, y| x != y}

    result = swapping_combos.select do |x, y|
      happy_after_swap?(@input, x, y)
    end

    p result.count
  end

end

number = gets.chomp
BearUpDown.new(gets.chomp).run
# BearUpDown.new(DATA.first.chomp).run

#http://www.codeforces.com/problemset/problem/653/C
class BearUpDown
  def initialize(input)
    @input = input.split.map(&:to_i)
    @n = @input.length
  end

  def problem_element_indices(array)
    a = array.each_cons(2).with_index.inject([]) do |acc, (element, index)|
      if (index.even? && (element.last - element.first) <= 0) ||
          (index.odd? && (element.first - element.last) <= 0)
          acc << index
      end
      # return false if acc.length == 5
      acc
    end
    a
  end

  def happy?(array, *sites)
    sites.all? do |index|
      left = index == 0 ? nil : array[index-1]
      right = index == @n - 1  ? nil : array[index + 1]
      if index.odd?
        [left, right].compact.all? { |x| array[index] > x }
      else
        [left, right].compact.all? { |x| array[index] < x }
      end
    end
  end

  def swap(input, x, y)
    input[x], input[y] = input[y], input[x]
    input
  end

  def remove_consecutive(x)
    y = x.dup
    y.each_with_index do |e, i|
        next if i == 0
        y.delete_at(i) if e == y[i - 1] + 1
      end
    y
  end

  def run
    x = problem_element_indices(@input)
    p 0 and return if x.size > 3
    z = remove_consecutive(x)
    # if @input.first == 150000
    #   p x
    # end

    result = []
    if z.size == 1
      z.map { |y| [y, y + 1]}.flatten.each do |index|
        (0..@n-1).each do |n|
          check_sites = x + [n]
          swapped = swap(@input, index, n)
          if happy?(swapped, *check_sites)
            result << [index, n]
          end
          swap(@input, n, index)
        end
      end
    else
      p1, p2 = z.map { |y| [y, y + 1]}
      check_sites = (p1 + p2)
      possible_swaps = p1.product(p2)
      possible_swaps.each do |x, y|
        swapped = swap(@input, x, y)
        if happy?(swapped, *check_sites)
          result << [x, y]
        end
        swap(@input, y, x)
      end
    end

      # p result
    p result.uniq { |x| x.sort.join }.count
  end

end

number = gets.chomp
BearUpDown.new(gets.chomp).run
# BearUpDown.new(DATA.first.chomp).run

#http://www.codeforces.com/problemset/problem/653/C
class BearUpDown
  def initialize(input)
    @input = input.split.map(&:to_i)
    @n = @input.length
  end

  def problem_element_indices(array)
    a = array.each_cons(2).with_index.inject([]) do |acc, (element, index)|
      if (index.even? && (element.last - element.first) <= 0) ||
          (index.odd? && (element.first - element.last) <= 0)
          acc << index
      end
      return false if acc.length == 3
      acc
    end
    a
  end

  def happy?(array, *sites)
    sites.all? do |index|
      left = index == 0 ? nil : array[index-1]
      right = index == @n - 1  ? nil : array[index + 1]
      if index.odd?
        [left, right].compact.all? { |x| array[index] > x }
      else
        [left, right].compact.all? { |x| array[index] < x }
      end
    end
  end

  def swap(input, x, y)
    input[x], input[y] = input[y], input[x]
    input
  end

  def run
    x = problem_element_indices(@input)
    p 0 and return unless x
    p x
    if x.size == 2 && x.last == x.first + 1
      z = [x.first]
    else
      z = x
    end

    result = []
    if z.size == 1
      z.map { |y| [y, y + 1]}.flatten.each do |index|
        (0..@n-1).each do |n|
          check_sites = x + [n]
          swapped = swap(@input, index, n)
          if happy?(swapped, *check_sites)
            result << [index, n]
          end
          swap(@input, n, index)
        end
      end
    else
      p1, p2 = z.map { |y| [y, y + 1]}
      check_sites = (p1 + p2)
      possible_swaps = p1.product(p2)
      possible_swaps.each do |x, y|
        swapped = swap(@input, x, y)
        if happy?(swapped, *check_sites)
          result << [x, y]
        end
        swap(@input, y, x)
      end
    end

      # p result
    p result.uniq { |x| x.sort.join }.count
  end

end

number = gets.chomp
BearUpDown.new(gets.chomp).run
# BearUpDown.new(DATA.first.chomp).run


Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n    input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF        //here INF is a number big enoughtot=0for i from 1 to n    for j from (i+1) to n        ++tot        if (p[j].x-p[i].x>=d) then break    //notice that "break" is only to be                                            //out of the loop "for j"        d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?

A single line which contains two space-separated integers n and k (2 ≤ n ≤ 2000, 1 ≤ k ≤ 109).

If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≤ 109) representing the coordinates of the i-th point. The conditions below must be held:   All the points must be distinct.  |xi|, |yi| ≤ 109.  After running the given code, the value of tot should be larger than k.

n, k = gets.split.map(&:to_i)
puts 2 * k >= n * (n - 1) ? "no solution" : [*1..n].map{|i|"0 "+i.to_s}

n, k = gets.split.map(&:to_i)
if (n - 1) * n > k * 2
  n.times do |i|
    puts [0, i].join(' ')
  end
else
  puts "no solution"
end

#!/usr/bin/ruby1.9

point_num, limit = STDIN.readline.split.collect {|s| s.to_i }

if point_num*(point_num-1)/2 <= limit
	puts 'no solution'
	exit
end

(point_num-1).times do |i|
	puts '%d %d' % [i, i*10000]
end
puts '%d %d' % [point_num, 0]

n,k = gets().split().map{ |x| x.to_i}
if (1.0*n*(n-1)/2 <= k)
    puts "no solution";
else
    (1..n).each do |i|
       puts "0 %d" % [i];
    end
end

input = STDIN.read

input =~ /^(\d+) (\d+)/
n, k  = $1.to_i, $2.to_i
l = (n * (n - 1)) / 2

if (k >= l)
  puts 'no solution'
else
  (0...n).each { |y| puts "0 #{y}" }
end

n, k = gets.chomp.split.map { |num| num.to_i }
if k >= ((n - 1) * n / 2)
  puts "no solution"
else
  (1..n).each do |i|
    puts "0 #{i}"
  end
end

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

if k>=(n*(n-1)/2)
  puts "no solution"
else
  (1..n).each { |k|
    puts "0 #{k}"
  }
end

n,k = gets.strip.split(' ').map {|x| x.to_i}

if( k>= (n*(n-1))/2 )
  puts 'no solution'
else
  n.times do |i|
    puts "0 #{i*2}"
  end
end

#!/usr/bin/ruby

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

tot = n * (n - 1) / 2

if tot <= k
  puts "no solution"
else
  0.upto(n - 1) {|y| puts "0 #{y}" }
end

n, k = gets.split.map(&:to_i)
if (n - 1) * n > k
  n.times do |i|
    puts [0, i].join(' ')
  end
else
  puts "no solution"
end

n,k = gets().split().map{ |x| x.to_i}
if (1.0*n*(n-1)/2 < k)
    puts "no solution";
else
    (1..n).each do |i|
       puts "0 %d" % [i];
    end
end

input = STDIN.read

input =~ /^(\d+) (\d+)/
n, k  = $1.to_i, $2.to_i
l = (n * (n - 1)) / 2

if (k > l)
  puts 'no solution'
else
  (0...n).each { |y| puts "0 #{y}" }
end

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

if k>(n*(n-1)/2)
  puts "no solution"
else
  (1..n).each { |k|
    puts "0 #{k}"
  }
end

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

if k>(n*(n+1)/2)
  puts "no solution"
else
  (1..n).each { |k|
    puts "0 #{k}"
  }
end


You are given two huge binary integer numbers $$$a$$$ and $$$b$$$ of lengths $$$n$$$ and $$$m$$$ respectively. You will repeat the following process: if $$$b > 0$$$, then add to the answer the value $$$a~ \&~ b$$$ and divide $$$b$$$ by $$$2$$$ rounding down (i.e. remove the last digit of $$$b$$$), and repeat the process again, otherwise stop the process.The value $$$a~ \&~ b$$$ means bitwise AND of $$$a$$$ and $$$b$$$. Your task is to calculate the answer modulo $$$998244353$$$.Note that you should add the value $$$a~ \&~ b$$$ to the answer in decimal notation, not in binary. So your task is to calculate the answer in decimal notation. For example, if $$$a = 1010_2~ (10_{10})$$$ and $$$b = 1000_2~ (8_{10})$$$, then the value $$$a~ \&~ b$$$ will be equal to $$$8$$$, not to $$$1000$$$.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the length of $$$a$$$ and the length of $$$b$$$ correspondingly. The second line of the input contains one huge integer $$$a$$$. It is guaranteed that this number consists of exactly $$$n$$$ zeroes and ones and the first digit is always $$$1$$$. The third line of the input contains one huge integer $$$b$$$. It is guaranteed that this number consists of exactly $$$m$$$ zeroes and ones and the first digit is always $$$1$$$.

Print the answer to this problem in decimal notation modulo $$$998244353$$$.

MOD = 998244353

def solution
  read_ints

  astr = read_string.reverse
  bstr = read_string

  cumm = 0
  b = bstr.chars.map { |i| cumm += i.to_i; b = cumm }

  b = b.reverse

  total = 0

  pow = nil

  astr.chars.each.with_index do |c, i|
    pow = (pow ? pow * 2 : 1) % MOD
    next if c != ?1
    break unless b[i]
    total += pow * b[i]
    total = total % MOD
  end

  puts total

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


You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.

The first line contains two integers n, m (1 ≤ n, m ≤ 2·105) — the sizes of arrays a and b. The second line contains n integers — the elements of array a ( - 109 ≤ ai ≤ 109). The third line contains m integers — the elements of array b ( - 109 ≤ bj ≤ 109).

Print m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value bj.

gets
a=gets.split.map(&:to_i).sort
puts gets.split.map(&:to_i).map{|e|
	(0...a.size).bsearch{|i|a[i]>e}||a.size
}*' '

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

as.sort!
cnt = 0
hs = Hash.new(0)
as.each do |a|
  cnt += 1
  hs[a] = cnt
end
as.reverse!
cs = []
bs.each do |b|
 cs << hs[as.bsearch {|a| a <= b }]
end

puts cs.*' '

n, m = gets.chomp.split(" ").map(&:to_i)
a = gets.chomp.split(" ").map(&:to_i).sort
b = gets.chomp.split(" ").map(&:to_i)
res = Array.new()
b.each do |e|
  tmp = (0...n).bsearch {|i| a[i] > e}
  if tmp.nil? then
    res << n
  else
    res << tmp
  end
end
puts res.join(" ")


Saitama accidentally destroyed a hotel again. To repay the hotel company, Genos has volunteered to operate an elevator in one of its other hotels. The elevator is special — it starts on the top floor, can only move down, and has infinite capacity. Floors are numbered from 0 to s and elevator initially starts on floor s at time 0.The elevator takes exactly 1 second to move down exactly 1 floor and negligible time to pick up passengers. Genos is given a list detailing when and on which floor passengers arrive. Please determine how long in seconds it will take Genos to bring all passengers to floor 0.

The first line of input contains two integers n and s (1 ≤ n ≤ 100, 1 ≤ s ≤ 1000) — the number of passengers and the number of the top floor respectively. The next n lines each contain two space-separated integers fi and ti (1 ≤ fi ≤ s, 1 ≤ ti ≤ 1000) — the floor and the time of arrival in seconds for the passenger number i.

Print a single integer — the minimum amount of time in seconds needed to bring all the passengers to floor 0.

NoteIn the first sample, it takes at least 11 seconds to bring all passengers to floor 0. Here is how this could be done:1. Move to floor 5: takes 2 seconds.2. Pick up passenger 3.3. Move to floor 3: takes 2 seconds.4. Wait for passenger 2 to arrive: takes 4 seconds.5. Pick up passenger 2.6. Go to floor 2: takes 1 second.7. Pick up passenger 1.8. Go to floor 0: takes 2 seconds.This gives a total of 2 + 2 + 4 + 1 + 2 = 11 seconds.

#!/usr/bin/ruby
n,f=gets.split.map(&:to_i)
r=f
n.times{
	a,b=gets.split.map(&:to_i)
	r=[r,[f-a,b].max+a].max
}
p r

n, s = gets.chomp.split.map(&:to_i)
floors = []
n.times { floors << gets.chomp.split.map(&:to_i) }

c = 0
idx = s
floors.reverse.each do |a, b|
  c += (idx - a)
  c += (b > c) ? (b - c) : 0
  idx = a
end
puts c + idx

#! 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, s = gis

mx = s

n.times do
    f, t = gis
    mx = [f + t, mx].max
end

puts mx

n, s = gets.split.map(&:to_i)
n.times do
	t, f = gets.split.map(&:to_i)
	s = [s, t+f].max
end
puts s

def Int_maker(a)
	0.upto(a.length-1) {|i| a[i]=a[i].to_i }
	return a
end
info=Int_maker(gets.chomp.split(" "))
passenger=[]
0.upto(info[0]-1){|i| passenger[i]=Int_maker(gets.chomp.split(" "))}
passenger.sort!
passenger.reverse!
k=info[1]
time=0
0.upto(info[0]-1) do |i|
	if i==0
		time=k-(passenger[0][0])
		if time<(passenger[i][1])
			time=(passenger[i][1])
		end
	else
		time=time+(passenger[i-1][0])-(passenger[i][0])
		if time<(passenger[i][1])
			time=(passenger[i][1])
		end
	end
end
time=time+passenger[passenger.length-1][0]
puts time

a = gets.split.map(&:to_i)
n = a[0]
s = a[1]

max = s
(1..n).each do
	a = gets.split.map(&:to_i)
	sum = a[0] + a[1]
	max = sum if sum > max
end

puts max

arr1 = gets.chomp.split(/ /).map(&:to_i)
num = arr1[0]
floor_max = arr1[1]
pass = Array.new
time = Array.new
index=0
num.times do
	str = gets.chomp.split(/ /).map(&:to_i)
	pass[index] = str[0]
	time[index] = str[1]
	index+=1
end

_final=0

index=floor_max
loop do
	break if index < 0
	index1=0
	loop do
		break if index1>=num
		if pass[index1] == index && time[index1]>_final
			_final = time[index1]
		end
		index1+=1
	end
	#puts "Final is #{_final} and index is #{index}"

	index=index-1
	break if index < 0
	_final+=1
end

puts _final

n, s = gets.chomp.split.map(&:to_i)
ans = s
n.times do
  f, t = gets.chomp.split.map(&:to_i)
  ans = [ans, f + t].max
end
puts ans

sum, top_floor = gets.split.map(&:to_i)
wait = Hash.new{|hsh,key| hsh[key] = [] }
wait[0].push 0

for i in 0..sum-1
    f_t = gets.split
    floor = f_t[0].to_i
    time = f_t[1].to_i
	wait[floor].push time
end

wait = wait.sort.reverse
all_time = 0

for i in 0..wait.length-1

    shift = wait.shift
    c_floor = shift[0]
    c_floor_time = shift[1]

	if top_floor > c_floor
		all_time += top_floor - c_floor
		top_floor = c_floor
	end

	if top_floor.to_i == c_floor.to_i
		c_floor_time = c_floor_time.sort.reverse
		c_floor_time[0] = c_floor_time[0] - all_time

		if c_floor_time[0] < 0
			c_floor_time[0] = 0
		end

		all_time +=c_floor_time[0]
	end
end
p all_time

n, s = gets.split.map(&:to_i)
a = n.times.map{gets.split.map(&:to_i)}.reverse + [[0, 0]]
current_floor = s
time_spent = 0
a.each do |f, t|
  time_spent += [current_floor - f, t - time_spent].max
  current_floor = f
end
puts time_spent

a = gets.split(' ').collect {|x| x.to_i}
n = a[0]
s = a[1]
result = s
(1..n).each do
  a = gets.split(' ').collect {|x| x.to_i}
  result = a[0] + a[1] if a[0]+a[1] > result
end

puts result

n, s = gets.chomp.split(" ").map(&:to_i)
psgs = Array.new()
n.times do
  psgs << gets.chomp.split(" ").map(&:to_i)
end
psgs = psgs.sort_by{|x| x[0]}.reverse
res = 0
current = s
psgs.each do |f, t|
  res += current - f
  current = f
  if res < t then
    res = t
  end
end
if current != 0 then
  res += current
end
puts res

n, s = gets.split.map(&:to_i)
map = Hash.new
(1..n).each do
  floor, time = gets.split.map(&:to_i)
  if map[floor] == nil
    map[floor] = time
  else
    map[floor] = [map[floor], time].max
  end
end

curr = s
time = 0
s.downto(1).each do |floor|
  if map[floor] == nil
    next
  end
  time = [time+curr-floor, map[floor]].max
  curr = floor
end

time += curr

puts time

class Solver
	def main
		n, s = gets.split.map { |x| x.to_i }
		ans = []
		n.times do
			f, t = gets.split.map { |x| x.to_i }
			ans << [t, s - f].max + f
		end
		puts ans.max
	end
end
Solver.new.main

def Int_maker(a)
	0.upto(a.length-1) {|i| a[i]=a[i].to_i }
	return a
end
info=Int_maker(gets.chomp.split(" "))
passenger=[]
0.upto(info[0]-1){|i| passenger[i]=Int_maker(gets.chomp.split(" "))}
passenger.sort!
passenger.reverse!
k=info[1]-1
time=0
0.upto(info[0]-1) do |i|
	if i==0
		time=k-(passenger[0][0])
		if time<(passenger[i][1])
			time=(passenger[i][1])
		end
	else
		time=time+(passenger[i-1][0])-(passenger[i][0])
		if time<(passenger[i][1])
			time=(passenger[i][1])
		end
	end
end
time=time+passenger[passenger.length-1][0]
puts time

def Int_maker(a)
	0.upto(a.length-1) {|i| a[i]=a[i].to_i }
	return a
end
info=Int_maker(gets.chomp.split(" "))
passenger=[]
0.upto(info[0]-1){|i| passenger[i]=Int_maker(gets.chomp.split(" "))}
passenger.sort!
passenger.reverse!
k=info[1]-1
time=0
0.upto(info[0]-1) do |i|
	if i==0
		time=k-(passenger[0][0])
	else
		time=time+(passenger[i-1][0])-(passenger[i][0])
		if time<(passenger[i][1])
			time=(passenger[i][1])
		end
	end
end
time=time+passenger[passenger.length-1][0]
puts time

n, s = gets.chomp.split.map(&:to_i)
ans = s + 1
n.times do
  f, t = gets.chomp.split.map(&:to_i)
  ans = [ans, f + t].max
end
puts ans

s_f = gets.split
sum = s_f[0].to_i
top_floor = s_f[1].to_i

wait = Hash.new
for i in 0..sum-1
	f_t = gets.split
	floor = f_t[0].to_i
	time = f_t[1].to_i
	wait[floor] = time
end

wait = wait.sort.reverse
step_flag = 0

all_time = 0
for i in 0..sum-1
	#Записываем значение wait в top и wait_time
	shift = wait.shift
	c_floor = shift[0]
	c_wait_time = shift[1]
	if step_flag==0
		step = top_floor - c_floor
	end
	step_flag = 1

	#Время ожидания у текущего пассажира
	wait_time = c_wait_time - all_time
	if wait_time < 0
		wait_time = 0
	end

	all_time += wait_time
end
all_time+=step+1
puts all_time

n, s = gets.split.map(&:to_i)
map = Hash.new
(1..n).each do
  floor, time = gets.split.map(&:to_i)
  map[floor] = time
end

curr = s
time = 0
s.downto(0).each do |floor|
  if map[floor] == nil
    next
  end
  time = [time+curr-floor, map[floor]].max
  curr = floor
end

time += curr

puts time


This problem is given in two editions, which differ exclusively in the constraints on the number $$$n$$$.You are given an array of integers $$$a[1], a[2], \dots, a[n].$$$ A block is a sequence of contiguous (consecutive) elements $$$a[l], a[l+1], \dots, a[r]$$$ ($$$1 \le l \le r \le n$$$). Thus, a block is defined by a pair of indices $$$(l, r)$$$.Find a set of blocks $$$(l_1, r_1), (l_2, r_2), \dots, (l_k, r_k)$$$ such that:  They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks $$$(l_i, r_i)$$$ and $$$(l_j, r_j$$$) where $$$i \neq j$$$ either $$$r_i < l_j$$$ or $$$r_j < l_i$$$.  For each block the sum of its elements is the same. Formally, $$$$$$a[l_1]+a[l_1+1]+\dots+a[r_1]=a[l_2]+a[l_2+1]+\dots+a[r_2]=$$$$$$ $$$$$$\dots =$$$$$$ $$$$$$a[l_k]+a[l_k+1]+\dots+a[r_k].$$$$$$  The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks $$$(l_1', r_1'), (l_2', r_2'), \dots, (l_{k'}', r_{k'}')$$$ satisfying the above two requirements with $$$k' > k$$$.     The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.

The first line contains integer $$$n$$$ ($$$1 \le n \le 50$$$) — the length of the given array. The second line contains the sequence of elements $$$a[1], a[2], \dots, a[n]$$$ ($$$-10^5 \le a_i \le 10^5$$$).

In the first line print the integer $$$k$$$ ($$$1 \le k \le n$$$). The following $$$k$$$ lines should contain blocks, one per line. In each line print a pair of indices $$$l_i, r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — the bounds of the $$$i$$$-th block. You can print blocks in any order. If there are multiple answers, print any of them.

N = gets.to_i
A = gets.split.map &:to_i
ss = [0]
A.each{ |a| ss << (ss[-1] + a) }
segs = {}
(1..N).each{ |j|
  (1..j).each{ |i|
    seg = [i,j]
    v = ss[j] - ss[i-1]
    segs[v] ||= []
    segs[v] << seg
  }
}

seqs = []
segs.each{ |v,ss|
  rb = 0
  sss = []
  ss.each{ |l,r|
    if rb < l
      sss << [l,r]
      rb = r
    end
  }
  if seqs.size < sss.size
    seqs = sss
  end
}

p seqs.size
seqs.each{ |a,b|
  puts [a,b] * " "
}

N = gets.to_i
A = gets.split.map &:to_i
ss = [0]
A.each{ |a| ss << (ss[-1] + a) }
ans = 0
seqs = []
(0...N).each{ |j|
  (0..j).each{ |i|
    m = 1
    qs = [[i+1,j+1]]
    d = ss[j+1] - ss[i]
    k0 = j+1
    (j+1...N).each{ |k|
      (k0..k).each{ |l|
        e = ss[k+1] - ss[l]
        if d == e
          m += 1
          qs << [l+1,k+1]
          k0 = k+1
          break
        end
      }
    }
    if m > ans
      ans = m
      seqs = qs
    end
  }
}
puts ans
seqs.each{ |a,b| puts [a,b] * " " }

N = gets.to_i
A = gets.split.map &:to_i
ss = [0]
A.each{ |a| ss << (ss[-1] + a) }
ans = 0
seqs = []
(0...N).each{ |j|
  (0..j).each{ |i|
    m = 1
    qs = [[i+1,j+1]]
    d = ss[j+1] - ss[i]
    k0 = j+1
    (j+1...N).each{ |k|
      (k0..k).each{ |l|
        e = ss[k+1] - ss[l]
        if d == e
          m += 1
          qs << [l+1,k+1]
          k0 = k+1
        end
      }
    }
    if m > ans
      ans = m
      seqs = qs
    end
  }
}
puts ans
seqs.each{ |a,b| puts [a,b] * " " }

N = gets.to_i
A = gets.split.map &:to_i
ss = [0]
A.each{ |a| ss << (ss[-1] + a) }
ans = 0
seqs = []
p A, ss
(0...N).each{ |j|
  (0..j).each{ |i|
    m = 1
    qs = [[i+1,j+1]]
    d = ss[j+1] - ss[i]
    k0 = j+1
    (j+1...N).each{ |k|
      (k0..k).each{ |l|
        e = ss[k+1] - ss[l]
        if d == e
          m += 1
          qs << [l+1,k+1]
          k0 = k+1
        end
      }
    }
    if m > ans
      ans = m
      seqs = qs
    end
  }
}
puts ans
seqs.each{ |a,b| puts [a,b] * " " }


Sasha likes investigating different math objects, for example, magic squares. But Sasha understands that magic squares have already been studied by hundreds of people, so he sees no sense of studying them further. Instead, he invented his own type of square — a prime square. A square of size $$$n \times n$$$ is called prime if the following three conditions are held simultaneously:   all numbers on the square are non-negative integers not exceeding $$$10^5$$$;  there are no prime numbers in the square;  sums of integers in each row and each column are prime numbers. Sasha has an integer $$$n$$$. He asks you to find any prime square of size $$$n \times n$$$. Sasha is absolutely sure such squares exist, so just help him!

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Each of the next $$$t$$$ lines contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required size of a square.

For each test case print $$$n$$$ lines, each containing $$$n$$$ integers — the prime square you built. If there are multiple answers, print any.

T = gets.to_i

T.times do
  n = gets.to_i
  ans = Array.new(n) { Array.new(n, 0) }

  n.times do |y|
    2.times do |x|
      ans[y][(y + x) % n] = 1
    end
  end

  puts ans.map { |row| row.join(' ') }
end

t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  arr = Array.new(n){[0] * n}
  n.times do |i|
    arr[i][i] = 1
    if (i + 1 < n)
      arr[i][i + 1] = 1
    end
  end
  arr[1][0] = arr[n - 1][n - 2] = 1
  n.times do |i|
    puts arr[i].join(" ")
  end
end

t = gets.to_i

1.upto t do
  n = gets.to_i
  arr = Array.new(n) { Array.new(n, 0) }

  0.upto n-1 do |i|
    arr[i][i] = 1
    arr[i][n-1-i] = 1
  end

  if n.odd?
    arr[(n-1)/2][((n-1)/2)+1] = 1
    arr[(n+1)/2][(n-1)/2] = 1
  end

  puts arr.map { |x| x.join(' ') }
end


You are given a number $$$n$$$ (divisible by $$$3$$$) and an array $$$a[1 \dots n]$$$. In one move, you can increase any of the array elements by one. Formally, you choose the index $$$i$$$ ($$$1 \le i \le n$$$) and replace $$$a_i$$$ with $$$a_i + 1$$$. You can choose the same index $$$i$$$ multiple times for different moves.Let's denote by $$$c_0$$$, $$$c_1$$$ and $$$c_2$$$ the number of numbers from the array $$$a$$$ that have remainders $$$0$$$, $$$1$$$ and $$$2$$$ when divided by the number $$$3$$$, respectively. Let's say that the array $$$a$$$ has balanced remainders if $$$c_0$$$, $$$c_1$$$ and $$$c_2$$$ are equal.For example, if $$$n = 6$$$ and $$$a = [0, 2, 5, 5, 4, 8]$$$, then the following sequence of moves is possible:   initially $$$c_0 = 1$$$, $$$c_1 = 1$$$ and $$$c_2 = 4$$$, these values are not equal to each other. Let's increase $$$a_3$$$, now the array $$$a = [0, 2, 6, 5, 4, 8]$$$;  $$$c_0 = 2$$$, $$$c_1 = 1$$$ and $$$c_2 = 3$$$, these values are not equal. Let's increase $$$a_6$$$, now the array $$$a = [0, 2, 6, 5, 4, 9]$$$;  $$$c_0 = 3$$$, $$$c_1 = 1$$$ and $$$c_2 = 2$$$, these values are not equal. Let's increase $$$a_1$$$, now the array $$$a = [1, 2, 6, 5, 4, 9]$$$;  $$$c_0 = 2$$$, $$$c_1 = 2$$$ and $$$c_2 = 2$$$, these values are equal to each other, which means that the array $$$a$$$ has balanced remainders. Find the minimum number of moves needed to make the array $$$a$$$ have balanced remainders.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^4$$$) — the length of the array $$$a$$$. It is guaranteed that the number $$$n$$$ is divisible by $$$3$$$. The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 100$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$150\,000$$$.

For each test case, output one integer — the minimum number of moves that must be made for the $$$a$$$ array to make it have balanced remainders.

NoteThe first test case is explained in the statements.In the second test case, you need to make one move for $$$i=2$$$.The third test case you need to make three moves:   the first move: $$$i=9$$$;  the second move: $$$i=9$$$;  the third move: $$$i=2$$$. In the fourth test case, the values $$$c_0$$$, $$$c_1$$$ and $$$c_2$$$ initially equal to each other, so the array $$$a$$$ already has balanced remainders.

def method(h, n)
  res = 0
  (0..2).each { |v| h[v] = 0 unless h.key?(v) }
  while h.max_by { |k, v| v }[1] > n
    k, v = h.each.max_by { |k, v| v }
    h[k] = n
    h[(k + 1) % 3] += v - n
    res += v - n
  end
  res
end

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  puts method(a.group_by { |x| x % 3 }.transform_values(&:size), n / 3)
end

def method(h, n)
  res = 0
  (0..2).each { |v| h[v] = 0 unless h.key?(v) }
  while h.each_value.max > n
    k, v = h.each.max_by { |k, v| v }
    h[k] = n
    h[(k + 1) % 3] += v - n
    res += v - n
  end
  res
end

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  puts method(a.group_by { |x| x % 3 }.transform_values(&:size), n / 3)
end
#

def method(h, n)
  res = 0
  (0..2).each { |v| h[v] = 0 unless h.key?(v) }
  h.each do |k, v|
    if v > n
      res += v - n
      h[k] = n
      h[(k + 1) % 3] += v - n
    end
  end while h.values.max > n
  res
end

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  puts method(a.group_by { |x| x % 3 }.transform_values(&:size), n / 3)
end

def method(h, n)
  res = 0
  (0..2).each { |v| h[v] = 0 unless h.key?(v) }
  while h.values.max > n
    k, v = h.each.max_by { |k, v| v }
    h[k] = n
    h[(k + 1) % 3] += v - n
    res += v - n
  end
  res
end

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  puts method(a.group_by { |x| x % 3 }.transform_values(&:size), n / 3)
end
#

# frozen_string_literal: true

test = gets.to_i
test.times do
  n = gets.chomp.to_i
  numbers = gets.chomp.split.map(&:to_i)
  remainders = []
  (0..2).each do |index|
    remainders << numbers.count{|x| x % 3 == index}
  end

  result = 0
  while idx = (0..2).detect{|x| remainders[x] > n / 3}
    result += remainders[idx] - n / 3
    remainders[(idx+1)% 3] += remainders[idx] - n / 3
    remainders[idx] = n / 3
  end
  puts result
end

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i)
	c = (0...3).map { |k| a.count { _1 % 3 == k } }

	ans = 0
	while true
		i = c.index { _1 > n / 3 }
		break unless i
		ans += 1
		c[i] -= 1
		c[-~i % 3] += 1
	end
	puts ans
end

def solve
  count = [0, 0, 0]
  n = gets.to_i
  arr = gets.split(' ').map(&:to_i)
  arr.each do |i|
    count[i % 3] += 1
  end

  ans = 0

  2.times do
    3.times do |i|
      if count[i] > n / 3
        ans += count[i] - n / 3
        count[(i + 1) % 3] += count[i] - n / 3
        count[i] = n / 3
      end
    end
  end

  puts ans
end

t = gets.to_i
t.times { solve }

gets.to_i.times do
  n=gets.to_i/3
  a=gets.split.map(&:to_i)
  c0,c1,c2=0,0,0
  a.each do |aa|
    if aa%3==0
      c0+=1
    elsif aa%3==1
      c1+=1
    else
      c2+=1
    end
  end
  c=0
  while !(c0==c1&&c1==c2)
    if c0>n
      c1+=c0-n
      c+=c0-n
      c0=n
    elsif c1>n
      c2+=c1-n
      c+=c1-n
      c1=n
    elsif c2>n
      c0+=c2-n
      c+=c2-n
      c2=n
    end
  end
  puts c
end


There are n sharks who grow flowers for Wet Shark. They are all sitting around the table, such that sharks i and i + 1 are neighbours for all i from 1 to n - 1. Sharks n and 1 are neighbours too.Each shark will grow some number of flowers si. For i-th shark value si is random integer equiprobably chosen in range from li to ri. Wet Shark has it's favourite prime number p, and he really likes it! If for any pair of neighbouring sharks i and j the product si·sj is divisible by p, then Wet Shark becomes happy and gives 1000 dollars to each of these sharks.At the end of the day sharks sum all the money Wet Shark granted to them. Find the expectation of this value.

The first line of the input contains two space-separated integers n and p (3 ≤ n ≤ 100 000, 2 ≤ p ≤ 109) — the number of sharks and Wet Shark's favourite prime number. It is guaranteed that p is prime. The i-th of the following n lines contains information about i-th shark — two space-separated integers li and ri (1 ≤ li ≤ ri ≤ 109), the range of flowers shark i can produce. Remember that si is chosen equiprobably among all integers from li to ri, inclusive.

Print a single real number — the expected number of dollars that the sharks receive in total. You answer will be considered correct if its absolute or relative error does not exceed 10 - 6.  Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

NoteA prime number is a positive integer number that is divisible only by 1 and itself. 1 is not considered to be prime.Consider the first sample. First shark grows some number of flowers from 1 to 2, second sharks grows from 420 to 421 flowers and third from 420420 to 420421. There are eight cases for the quantities of flowers (s0, s1, s2) each shark grows: (1, 420, 420420): note that s0·s1 = 420, s1·s2 = 176576400, and s2·s0 = 420420. For each pair, 1000 dollars will be awarded to each shark. Therefore, each shark will be awarded 2000 dollars, for a total of 6000 dollars. (1, 420, 420421): now, the product s2·s0 is not divisible by 2. Therefore, sharks s0 and s2 will receive 1000 dollars, while shark s1 will receive 2000. The total is 4000. (1, 421, 420420): total is 4000  (1, 421, 420421): total is 0.  (2, 420, 420420): total is 6000.  (2, 420, 420421): total is 6000.  (2, 421, 420420): total is 6000. (2, 421, 420421): total is 4000.The expected value is .In the second sample, no combination of quantities will garner the sharks any money.

n, p = gets.chomp.split(" ").map(&:to_i)
sharks = []

n.times do
  l, r = gets.chomp.split(" ").map(&:to_i)

  x, y = l, r
  if x % p != 0
    x += p-x%p
  end
  y -= y%p
  dividends = (y-x)/p+1

  sharks << {l: l, r: r, dividends: dividends, total: r-l+1}
end

sharks << sharks.first

# puts sharks.inspect

sum = sharks.each_cons(2).map do |shark_a, shark_b|
  shark_a_not_p = 1 - shark_a[:dividends]/shark_a[:total].to_f
  shark_b_not_p = 1 - shark_b[:dividends]/shark_b[:total].to_f

  (1 - (shark_a_not_p * shark_b_not_p))*2000
end.inject(0, :+)

puts sum

def solve(a, p)
  q = a.map do |l, r|
    (r / p - (l - 1) / p).to_f / (r - l + 1)
  end
  2000 * ( 2*q[1..-1].reduce(0, :+) - q.each_cons(2).map {|q1, q2| q1*q2}.reduce(0, :+))
end

n, p = gets.split.map(&:to_i)
a = Array.new(n+1) do |i|
  next if i == n
  gets.split.map(&:to_i)
end
a[-1] = a[0]

puts solve(a, p)

n, p = gets.chomp.split(" ").map(&:to_i)
sharks = []

n.times do
  l, r = gets.chomp.split(" ").map(&:to_i)

  x, y = l, r
  if x % p != 0
    x += p-x%p
  end
  y -= y%p
  dividends = (y-x)/p+1

  sharks << {l: l, r: r, dividends: dividends, total: r-l+1}
end

sharks << sharks.first

puts sharks.inspect

sum = sharks.each_cons(2).map do |shark_a, shark_b|
  shark_a_not_p = 1 - shark_a[:dividends]/shark_a[:total].to_f
  shark_b_not_p = 1 - shark_b[:dividends]/shark_b[:total].to_f

  (1 - (shark_a_not_p * shark_b_not_p))*2000
end.inject(0, :+)

puts sum

n, p = gets.chomp.split(" ").map(&:to_i)
sharks = []

n.times do
  l, r = gets.chomp.split(" ").map(&:to_i)
  dividends = (r-l+1)/p
  sharks << {l: l, r: r, dividends: dividends, total: r-l+1}
end

sharks << sharks.first

sum = sharks.each_cons(2).map do |shark_a, shark_b|
  shark_a_not_p = 1 - shark_a[:dividends]/shark_a[:total].to_f
  shark_b_not_p = 1 - shark_b[:dividends]/shark_b[:total].to_f

  (1 - (shark_a_not_p * shark_b_not_p))*2000
end.inject(0, :+)

puts sum


In the school computer room there are n servers which are responsible for processing several computing tasks. You know the number of scheduled tasks for each server: there are mi tasks assigned to the i-th server.In order to balance the load for each server, you want to reassign some tasks to make the difference between the most loaded server and the least loaded server as small as possible. In other words you want to minimize expression ma - mb, where a is the most loaded server and b is the least loaded one.In one second you can reassign a single task. Thus in one second you can choose any pair of servers and move a single task from one server to another.Write a program to find the minimum number of seconds needed to balance the load of servers.

The first line contains positive number n (1 ≤ n ≤ 105) — the number of the servers.  The second line contains the sequence of non-negative integers m1, m2, ..., mn (0 ≤ mi ≤ 2·104), where mi is the number of tasks assigned to the i-th server.

Print the minimum number of seconds required to balance the load.

NoteIn the first example two seconds are needed. In each second, a single task from server #2 should be moved to server #1. After two seconds there should be 3 tasks on server #1 and 4 tasks on server #2.In the second example the load is already balanced.A possible sequence of task movements for the third example is:  move a task from server #4 to server #1 (the sequence m becomes: 2 2 3 3 5);  then move task from server #5 to server #1 (the sequence m becomes: 3 2 3 3 4);  then move task from server #5 to server #2 (the sequence m becomes: 3 3 3 3 3). The above sequence is one of several possible ways to balance the load of servers in three seconds.

n = gets.chomp.to_i
a = gets.split.map(&:to_i)
sum = a.reduce(0, :+)
lower_median = sum / n
upper_median = lower_median + (sum % n == 0 ? 0 : 1)
upper_total = 0
lower_total = 0
a.each do |val|
  lower_total += lower_median - val if val < lower_median
  upper_total += val - upper_median if val > upper_median
end
puts lower_total > upper_total ? lower_total : upper_total

#!/usr/bin/env ruby

gets
m = gets.split.map(&:to_i)
avg = m.inject(:+) / m.size
overage = m.inject(:+) - (avg * m.size)
bal = 0
m.sort!
m.reverse!
m.each do |l|
  if l > avg
    if overage > 0
      bal += l - (avg + 1)
      overage -= 1
    else
      bal += l - avg
    end
  else
    if overage > 0
      bal += (avg + 1) - l
      overage -= 1
    else
      bal += avg - l
    end
  end
end
puts bal / 2

# Accept at
n = gets.to_i
a = gets.split(' ').map { |x|
  x.to_i
}
sum = a.inject { |sum, t| sum += t}
ave = sum / a.length
n1 = sum - ave * a.length
result = 0
tmp = 0
a.each { |t|
  result += t - ave - 1 if t >= ave+1
  tmp += 1 if t >= ave+1
}

result += tmp - n1 if tmp > n1
puts result

n = gets.chomp.to_i
m = gets.chomp.split(" ").map(&:to_i).sort
msum = m.inject(:+)
mmod = msum % n
if mmod == 0
  mm = Array.new(n, msum / n)
else
  mm = Array.new(n - mmod, msum / n) + Array.new(mmod, msum / n + 1)
end
res = 0
m.zip(mm).each do |a, b|
  res += (a - b).abs
end
puts res / 2

n = gets.to_i
m = gets.split(' ').map{ |x| x.to_i }
msum = m.inject{|sum,x| sum+x}
avg = msum / n
ans1 = ans2 = 0
for iter in m
    if iter < avg
        ans1 += avg - iter
    end
    if iter > avg
        ans2 += iter - avg - 1
    end
end
puts [ans1, ans2].max

n = gets.to_i
servers = gets.split.map(&:to_i).sort.reverse
sum = servers.reduce(&:+)
min_load = sum/servers.length
extra = sum%servers.length
optimal = Array.new(n, min_load)
for i in 0...extra
  optimal[i] += 1
end
count = 0
for i in 0...n
  count += (servers[i]-optimal[i]).abs
end
puts count/2

m = Array.new
n = gets.chomp.to_i
t = gets.chomp.split(/ /)
t.each {|u| m << u.to_i}
m.sort!

s = 0
m.each {|t| s = s + t}

hash = Hash.new
if (s % n == 0)
	hash[s / n] = n
else
	hash[s/n] = n - s % n
	hash[s/n+1] = s % n
end

for i in 0..m.size do
	if hash.has_key?(m[i]) && hash[m[i]] != 0
		hash[m[i]] = hash[m[i]] - 1
		if hash[m[i]] == 0
			hash.delete m[i]
		end
		m[i] = 0
	end
end

sec = 0
if hash.size == 1
	hash.each_key {|key|
		if hash[key] != 0
			m.each {|m_i|
				if m_i != 0
					sec = sec + (m_i - key).abs
				end
			}
		end
	}
else
	m.each {|m_i|
		if m_i != 0
			if m_i < s / n
				if hash[s/n] > 0
					sec = sec + (s/n - m_i).abs
					hash[s/n] = hash[s/n] - 1
				elsif hash[s/n + 1] > 0
					sec = sec + (m_i - s/n - 1).abs
					hash[s/n + 1] = hash[s/n + 1] - 1
				end
			elsif m_i > s/n + 1
			  if hash[s/n + 1] > 0
					sec = sec + (m_i - s/n - 1).abs
					hash[s/n + 1] = hash[s/n + 1] - 1
				elsif hash[s/n] > 0
					sec = sec + (s/n - m_i).abs
					hash[s/n] = hash[s/n] - 1
				end
			end
		end
	}
end

print sec / 2

m = Array.new
n = gets.chomp.to_i
t = gets.chomp.split(/ /)
t.each {|u| m << u.to_i}
m.sort!

s = 0
m.each {|t| s = s + t}

hash = Hash.new
if (s % n == 0)
	hash[s / n] = n
else
	hash[s/n] = n - s % n
	hash[s/n+1] = s % n
end

sec = 0
if hash.size == 1
			m.each {|m_i|
				sec = sec + (m_i - s/n).abs
			}
else
	m.each {|m_i|
		if m_i != 0
			if m_i <= s / n
				if hash[s/n] > 0
					sec = sec + (s/n - m_i).abs
					hash[s/n] = hash[s/n] - 1
				elsif hash[s/n + 1] > 0
					sec = sec + (m_i - s/n - 1).abs
					hash[s/n + 1] = hash[s/n + 1] - 1
				end
			elsif m_i >= s/n + 1
			  if hash[s/n + 1] > 0
					sec = sec + (m_i - s/n - 1).abs
					hash[s/n + 1] = hash[s/n + 1] - 1
				elsif hash[s/n] > 0
					sec = sec + (s/n - m_i).abs
					hash[s/n] = hash[s/n] - 1
				end
			end
		end
	}
end

print sec / 2

m = Array.new
n = gets.chomp.to_i
t = gets.chomp.split(/ /)

s = 0
t.each {|u| m << u.to_i; s = s + u.to_i}
m.sort!

hash = Hash.new
if (s % n == 0)
	hash[s / n] = n
else
	hash[s/n] = n - s % n
	hash[s/n+1] = s % n
end

sec = 0
if hash.size == 1
			m.each {|m_i|
				sec = sec + (m_i - s/n).abs
			}
else
	m.each {|m_i|
		if m_i <= s / n
			if hash[s/n] > 0
				sec = sec + (s/n - m_i).abs
				hash[s/n] = hash[s/n] - 1
			else
				sec = sec + (m_i - s/n - 1).abs
				hash[s/n + 1] = hash[s/n + 1] - 1
			end
		else
		  if hash[s/n + 1] > 0
				sec = sec + (m_i - s/n - 1).abs
				hash[s/n + 1] = hash[s/n + 1] - 1
			else
				sec = sec + (s/n - m_i).abs
				hash[s/n] = hash[s/n] - 1
			end
		end
	}
end

print sec / 2

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

count = 0
while a[n - 1] - a[0] > 1 do
  # balance
  diff = a[n - 1] - a[0]
  a[0] += diff / 2
  a[n - 1] -= diff / 2
  a[n - 1] -= 1 if diff % 2 != 0
  count += diff / 2

  # resort
  i = n - 1
  while a[i] < a[i - 1] do
    temp = a[i]
    a[i] = a[i - 1]
    a[i - 1] = temp
    i -= 1
  end
  i = 0
  while a[i] > a[i + 1] do
    temp = a[i]
    a[i] = a[i + 1]
    a[i + 1] = temp
    i += 1
  end
end

puts count

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

count = 0
while a[n - 1] - a[0] > 1 do
  # balance
  a[0] += 1
  a[n - 1] -= 1

  # resort
  i = n - 1
  while a[i] < a[i - 1] do
    temp = a[i]
    a[i] = a[i - 1]
    a[i - 1] = temp
  end
  i = 0
  while a[i] > a[i + 1] do
    temp = a[i]
    a[i] = a[i + 1]
    a[i + 1] = temp
  end
  count += 1
end

puts count

#!/usr/bin/env ruby

gets
m = gets.split.map(&:to_i)
avg = m.inject(:+) / m.size
overage = m.inject(:+) - (avg * m.size)
bal = 0
m.sort!
m.reverse!
m.each do |l|
  p overage, bal
  if l > avg
    if overage > 0
      bal += l - (avg + 1)
      overage -= 1
    else
      bal += l - avg
    end
  else
    if overage > 0
      bal += (avg + 1) - l
      overage -= 1
    else
      bal += avg - l
    end
  end
end
puts bal

#!/usr/bin/env ruby

gets
m = gets.split.map(&:to_i)
avg = m.inject(:+) / m.size
overage = m.inject(:+) - (avg * m.size)
bal = 0
m.sort!
m.reverse!
m.each do |l|
  if l > avg
    if overage > 0
      bal += l - (avg + 1)
      overage -= 1
    else
      bal += l - avg
    end
  else
    if overage > 0
      bal += (avg + 1) - l
      overage -= 1
    else
      bal += l - avg
    end
  end
end
puts bal

#!/usr/bin/env ruby

gets
m = gets.split.map(&:to_i)
m.sort!
c = 0
while m.last - m.first > 1
  diff = m.last - m.first
  move = diff / 2
  m[0] += move
  m[m.size - 1] -= move
  m.sort!
  c += move
end
puts c

#!/usr/bin/env ruby

gets
m = gets.split.map(&:to_i)
avg = m.inject(:+) / m.size
bal = 0
m.each do |l|
  if l < avg
    bal += avg - l
  end
end
puts bal

#!/usr/bin/env ruby

gets
m = gets.split.map(&:to_i)
avg = m.inject(:+) / m.size
m.sort!
c = 0
while m.last - m.first > 1
  move = [avg - m.first, m.last - (avg + 1)].max
  diff = m.last - m.first
  m[0] += move
  m[m.size - 1] -= move
  m.sort!
  c += move
end
puts c

n = gets.to_i
a = gets.split(' ').map { |x|
  x.to_i
}
sum = a.inject { |sum, t| sum += t}
ave = sum / a.length
n1 = sum - ave * a.length
result = 0
a.each { |t|
  result += t - ave if t >= ave
}
puts result - n1

n = gets.to_i
a = gets.split(' ').map { |x|
  x.to_i
}
m = a.inject { |sum, t| sum += t} / 1.0 / a.length
result = 0
a.each { |t|
  result += t - m.ceil if t >= m
}
puts result

n = gets.to_i
a = gets.split(' ').map { |x|
  x.to_i
}
sum = a.inject { |sum, t| sum += t}
ave = sum / a.length
even= true if (ave * a.length == sum)

ceil = ave
ceil = ave+1 unless even

result = 0
a.each { |t|
  result += t - ceil if t >= ceil
}
puts result

n = gets.chomp.to_i
loads = gets.chomp.split(" ").map(&:to_i)
m = loads.inject(:+) / n
loads = loads.select{|i| i - m < 0}
if loads.empty? then
  puts 0
else
  puts loads.map{|i| i - m}.inject(:+).abs()
end

n = gets.to_i
m = gets.split(' ').map{ |x| x.to_i }
msum = m.inject{|sum,x| sum+x}
avg = msum / n
ans1 = 0
for iter in m
    if iter < avg
        ans1 += avg - iter
    end
end
puts ans1

n = gets.to_i
servers = gets.split.map(&:to_i)
sum = servers.reduce(&:+)
min_load = sum/servers.length
count = 0
for server in servers
  if server < min_load
    count += min_load-server
  end
end

puts count

n = gets.to_i
servers = gets.split.map(&:to_i)
sum = servers.reduce(&:+)
min_load = sum/servers.length
extra = sum-(min_load*servers.length)
count = 0
for server in servers
  if server > min_load
    count += server-min_load
  end
end

puts count-extra

n = gets.to_i
servers = gets.split.map(&:to_i).sort.reverse
sum = servers.reduce(&:+)
min_load = sum/servers.length
count = 0
for server in servers
  count += (server-min_load).abs
end

puts count/2

m = Array.new
n = gets.chomp.to_i
t = gets.chomp.split(/ /)
t.each {|u| m << u.to_i}
m.sort!

s = 0
m.each {|t| s = s + t}

hash = Hash.new
if (s % n == 0)
	hash[s / n] = n
else
	hash[s/n] = n - s % n
	hash[s/n+1] = s % n
end

m.each {|x|
	if hash.has_key? x
		hash[x] = hash[x] - 1
		m.delete x
		if hash[x] == 0
			hash.delete x
		end
	end
}

sec = 0
if hash.size == 1
	hash.each_key {|key|
		m.each {|m_i|
			sec = sec + (m_i - key).abs
		}
	}
	print sec / 2
else
	hash.each_key { |key|
		m.each {|m_i|
			if m_i < hash[s/n]
					sec = sec + (s/n - m_i).abs
					hash[s/n] = hash[s/n] - 1
			elsif hash[s/n + 1] > 0
				if m_i > hash[s/n + 1]
					sec = sec + (m_i - s/n + 1).abs
					hash[s/n + 1] = hash[s/n + 1] - 1
				end
			end
		}
	}
	print sec / 2
end

m = Array.new
n = gets.chomp.to_i
t = gets.chomp.split(/ /)
t.each {|u| m << u.to_i}
m.sort!

s = 0
m.each {|t| s = s + t}

hash = Hash.new
if (s % n == 0)
	hash[s / n] = n
else
	hash[s/n] = n - s % n
	hash[s/n+1] = s % n
end

for i in 0..m.size do
	if hash.has_key?(m[i]) && hash[m[i]] != 0
		hash[m[i]] = hash[m[i]] - 1
		if hash[m[i]] == 0
			hash.delete m[i]
		end
		m[i] = 0
	end
end

sec = 0
if hash.size == 1
	hash.each_key {|key|
		if hash[key] != 0
			m.each {|m_i|
				if m_i != 0
					sec = sec + (m_i - key).abs
				end
			}
		end
	}
else
	m.each {|m_i|
		if m_i != 0
			if m_i < s/n
				sec = sec + (s/n - m_i).abs
				hash[s/n] = hash[s/n] - 1
			elsif hash[s/n + 1] > 0
				if m_i > s/n + 1
					sec = sec + (m_i - s/n - 1).abs
					hash[s/n + 1] = hash[s/n + 1] - 1
				end
			end
		end
	}
end

print sec / 2


Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him.

The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence.  The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105).

Print a single integer — the maximum number of points that Alex can earn.

NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points.

def main
  gets
  seq = gets.split.map(&:to_i)
  puts max_score(seq)
end

def max_score(sequence)
  count = Hash.new(0)
  sequence.each { |x| count[x] += 1 }
  nums = count.keys.sort

  # best[k] is the best Alex can do with the first k nums
  best = []
  best[0] = 0

  nums.each_index do |i|
    next_best = best.last
    if i > 0 && nums[i - 1] + 1 == nums[i]
      base = best[-2]
    else
      base = best[-1]
    end
    with_cur = base + nums[i] * count[nums[i]]
    next_best = with_cur if with_cur > next_best
    best << next_best
  end
  best.last
end

main if __FILE__ == $0

n = gets.to_i
a = gets.split.map(&:to_i)
s = Array.new(100002, 0)
for i in 0...a.size
  s[a[i]] += a[i]
end
for i in 2..100001
	s[i] = [ s[i] + s[i - 2] , s[i - 1] ].max
end
puts s[100001]

# def bore(arr)
# 	poi = []

# 	return 0 if arr.empty?
# 	arr.uniq.each do |a|

# 		i = arr.index(a)
# 	 	@freq[a] = arr.count(a)	unless @freq[a]
# 		val = @freq[a]
# 		poi << (val * a) + bore( arr - [a,a+1,a-1])
# 	end
# 	return poi.max
# end

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

@freq = Hash.new(0)

arr.each{|i| @freq[i] += 1}

one_count = @freq[1]

f = []

f[0] = 0
f[1] = one_count

(2..1000001).each do |i|
	f[i] = [f[i-1],f[i-2] + (@freq[i] * i)].max
end
puts f[-1]

def solution(arr)
  dp = Array.new(arr.max+2, 0)
  arr.each { |a| dp[a] += 1 }

  for i in 2...dp.size do
    dp[i] = [dp[i-2] + i*dp[i], dp[i-1]].max
  end
  dp.last
end

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

puts solution(arr)

n = gets.to_i
a = gets.split.map(&:to_i)
c = Array.new(a.max + 1, 0)
for i in 0...a.size
  c[a[i]] += a[i]
end

dp = Array.new(c.size, 0)
dp[1] = c[1]
for i in 2...c.size
  dp[i] = [dp[i - 2] + c[i], dp[i - 1]].max
end
puts dp[c.size - 1]

def parse(s)
  nn = s.split.map(&:to_i)
  nn.group_by { |n| n }.reduce(Hash.new(0)) { |acc, (k, v)| acc[k] = v.reduce(:+); acc }
end

def next_smallest_keys(ks, i)
  s1, s2 = 0
  j = i-1
  while j >= 0
    next_k = ks[j]
    if next_k < ks[i] - 1
      if s1.zero?
        s1 = next_k
      else
        s2 = next_k
        break
      end
    end
    j -= 1
  end
  [s1, s2]
end

def get_max_points(m)
  ks = m.keys.sort
  t = Hash.new(0)
  ans = 0

  ks.each_with_index do |k, i|

    k1, k2 = next_smallest_keys(ks, i)
    v = m[k]
    t[k] = v + [t[k1], t[k2]].max
    ans = [ans, t[k]].max
  end

  ans
end
#input = '6 6 8 9 7 9 6 9 5 7 7 4 5 3 9 1 10 3 4 5 8 9 6 5 6 4 10 9 1 4 1 7 1 4 9 10 8 2 9 9 10 5 8 9 5 6 8 7 2 8 7 6 2 6 10 8 6 2 5 5 3 2 8 8 5 3 6 2 1 4 7 2 7 3 7 4 10 10 7 5 4 7 5 10 7 1 1 10 7 7 7 2 3 4 2 8 4 7 4 4'

STDIN.gets
input = STDIN.gets.chomp

m = parse input
p get_max_points m

def f(x)
  return 0 if x < 0
  $c[x]
end

def n(x)
  return 0 unless $d.key?(x)
  $d[x]
end

gets

a = gets.split(' ').map(&:to_i).sort.reverse
$d = Hash[a.group_by{|n|n}.map{|k, v|[k, v.size]}]
m = a.first
$c = [ 0 ]

1.upto(m) do |i|
  $c.push([f(i-2) + i*n(i), f(i-1)].max)
end

puts $c.last

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

cnt = Array.new(1e5+5,0)
a.map{|x| cnt[x]+=1}

dp = Array.new(1e5+5,0)

i = 1
hi2 = 0
dp[1] = cnt[1]
(dp.length-2).times do
    i += 1
    hi2 = [hi2,dp[i-2]].max
    dp[i] = i * cnt[i] + hi2
end

puts dp.max

# Author : Fuad Ashraful Mehmet
#Date: 18th April

n=gets.to_i
a=gets.split.map(&:to_i)
c=Array.new(a.max+1,0)

for i in 0...a.size
    c[a[i]]+=a[i]

end

dp=Array.new(c.size,0)
dp[1]=c[1]

for i in 2...c.size
    dp[i]=[dp[i-2]+c[i],dp[i-1]].max

end

puts dp[c.size-1]

n = gets.chomp.to_i
a = gets.chomp.split(" ").map(&:to_i)
h = Hash.new(0)
a.each do |v|
  h[v] += 1
end
keys = h.keys.push(0).sort

r  = keys.size.times.map{ 0 }
rw = keys.size.times.map{ 0 }

keys.each_with_index do |k, i|
  rw[i] = [r[i-1], rw[i-1]].max
  if keys[i-1] == k - 1
    r[i] = rw[i-1] + k*h[k]
  else
    r[i] = rw[i-1] > r[i-1] ? rw[i-1] : r[i-1]
    r[i] += k*h[k]
  end
end

puts [r.last, rw.last].max

n = gets.strip.to_i
arr = gets.strip.split(" ").map(&:to_i)
arr.sort!
j = 1
uniq_array = []
uniq_array[0] = arr[0]
frequency = Hash.new(0)
frequency[arr[0]] = 1
while j < arr.length do
  if arr[j] != arr[j - 1] then
    uniq_array.push(arr[j])
    frequency[arr[j]] = 1
  else
    frequency[arr[j]] += 1
  end
  j += 1
end
# p uniq_array
# p frequency
results = []
results[0] = uniq_array[0] * frequency[uniq_array[0]]
if uniq_array.length > 1 then
  if uniq_array[1] - uniq_array[0] > 1 then
    results[1] = results[0] + uniq_array[1] * frequency[uniq_array[1]]
  else
    second_sum = uniq_array[1] * frequency[uniq_array[1]]
    results[1] = second_sum > results[0] ? second_sum : results[0]
  end
end
i = 2
while i < uniq_array.length do
  if uniq_array[i] - uniq_array[i - 1] > 1 then
    results[i] = results[i - 1] + uniq_array[i] * frequency[uniq_array[i]]
  elsif results[i - 1] > uniq_array[i] * frequency[uniq_array[i]] + results[i - 2] then
    results[i] = results[i - 1]
  else
    results[i] =  uniq_array[i] * frequency[uniq_array[i]] + results[i - 2]
  end
  i += 1
end
puts results.last

n = gets.strip.to_i
arr = gets.strip.split(" ").map(&:to_i)
arr.sort!
j = 1
uniq_array = []
uniq_array[0] = arr[0]
frequency = Hash.new(0)
frequency[arr[0]] = 1
while j < arr.length do
  if arr[j] != arr[j - 1] then
    uniq_array.push(arr[j])
    frequency[arr[j]] = 1
  else
    frequency[arr[j]] += 1
  end
  j += 1
end
# p uniq_array
# p frequency

prev = uniq_array[0] * frequency[uniq_array[0]]
if uniq_array.length > 1 then
  if uniq_array[1] - uniq_array[0] > 1 then
    current = prev + uniq_array[1] * frequency[uniq_array[1]]
  else
    second_sum = uniq_array[1] * frequency[uniq_array[1]]
    current = second_sum > prev ? second_sum : prev
  end
else
  current = prev
end
i = 2
while i < uniq_array.length do
  if uniq_array[i] - uniq_array[i - 1] > 1 then
    prev = current
    current += uniq_array[i] * frequency[uniq_array[i]]
  elsif current < uniq_array[i] * frequency[uniq_array[i]] + prev then
    temp = current
    current =  uniq_array[i] * frequency[uniq_array[i]] + prev
    prev = temp
  else
    prev = current
  end
  i += 1
end
puts current

def calc (mas)
  pairs = {}
  mas.each_index { |i| mas[i]= mas[i].to_i}
  cur = mas[0]
  count = 0
  mas.each do |x|
    if x==cur
      count += 1
    else
      pairs[cur] = count
      cur = x
      count = 1
    end
  end
  pairs[cur] = count
  pairs
end
n = gets.to_i
a = gets.split(" ")
a.sort_by! {|x| x.to_i}
b = calc(a)
best1 = 0
prev1 = -1
best2 = 0
b.each_pair {|x,y|
  new_best2 = [best1,best2].max
  if x!=prev1+1
    new_best1 = [best2, best1].max + x*y
  else
    new_best1 = best2 + x*y
  end
  prev1 = x
  best1 = new_best1
  best2 = new_best2
}
puts [best1,best2].max

gets
a=gets.split.map(&:to_i).sort
d=[0]*a.size
d[0]=a[0]
a.each_with_index{|e,i|
	next if i==0
	d[i]=d[i-1]
	s=(i>1) ? d[i-2] : 0
	d[i]=[d[i], s+e].max
}
p d[-1]

# def bore(arr)
# 	poi = []

# 	return 0 if arr.empty?
# 	arr.uniq.each do |a|

# 		i = arr.index(a)
# 	 	@freq[a] = arr.count(a)	unless @freq[a]
# 		val = @freq[a]
# 		poi << (val * a) + bore( arr - [a,a+1,a-1])
# 	end
# 	return poi.max
# end

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

# @freq = {}

# puts bore(arr)
@freq = Hash.new(0)

arr.uniq.each{|i| @freq[i] += 1}

one_count = @freq[1]

f = []

f[0] = 0
f[1] = one_count
max = one_count

(2..10000).each do |i|
	f[i] = [f[i-1],f[i-2] + (@freq[i] * i)].max

end
puts f[-1]

# def bore(arr)
# 	poi = []

# 	return 0 if arr.empty?
# 	arr.uniq.each do |a|

# 		i = arr.index(a)
# 	 	@freq[a] = arr.count(a)	unless @freq[a]
# 		val = @freq[a]
# 		poi << (val * a) + bore( arr - [a,a+1,a-1])
# 	end
# 	return poi.max
# end

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

@freq = Hash.new(0)

arr.each{|i| @freq[i] += 1}

one_count = @freq[1]

f = []

f[0] = 0
f[1] = one_count

(2..10000).each do |i|
	f[i] = [f[i-1],f[i-2] + (@freq[i] * i)].max
end
puts f[-1]

# def bore(arr)
# 	poi = []

# 	return 0 if arr.empty?
# 	arr.uniq.each do |a|

# 		i = arr.index(a)
# 	 	@freq[a] = arr.count(a)	unless @freq[a]
# 		val = @freq[a]
# 		poi << (val * a) + bore( arr - [a,a+1,a-1])
# 	end
# 	return poi.max
# end

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

# @freq = {}

# puts bore(arr)
@freq = Hash.new(0)

arr.uniq.each{|i| @freq[i] += i}

one_count = @freq[1]

f = []

f[0] = 0
f[1] = one_count
max = one_count

(2..10000).each do |i|
	f[i] = [f[i-1],f[i-2] + (@freq[i] * i)].max

end
puts f[-1]

# def bore(arr)
# 	poi = []

# 	return 0 if arr.empty?
# 	arr.uniq.each do |a|

# 		i = arr.index(a)
# 	 	@freq[a] = arr.count(a)	unless @freq[a]
# 		val = @freq[a]
# 		poi << (val * a) + bore( arr - [a,a+1,a-1])
# 	end
# 	return poi.max
# end

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

# @freq = {}

# puts bore(arr)
@freq = Hash.new(0)

arr.each{|i| @freq[i] += 1}

one_count = @freq[1]

f = []

f[0] = 0
f[1] = one_count
max = one_count

(2..10000).each do |i|
	f[i] = [f[i-1],f[i-2] + (@freq[i] * i)].max

end
puts f[-1]

# def bore(arr)
# 	poi = []

# 	return 0 if arr.empty?
# 	arr.uniq.each do |a|

# 		i = arr.index(a)
# 	 	@freq[a] = arr.count(a)	unless @freq[a]
# 		val = @freq[a]
# 		poi << (val * a) + bore( arr - [a,a+1,a-1])
# 	end
# 	return poi.max
# end

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

# @freq = {}
# puts bore(arr)
@freq = {}

# (1..10000).each{|i| @freq[i] = arr.count(i)}
one_count = arr.count(1)
f = Hash.new(0)

f[0] = 0
f[1] = one_count
max = one_count

arr.sort.uniq.each do |i|
	f[i] = [f[i-1],f[i-2] + (arr.count(i) * i)].max
	max = f[i] if f[i] > max
end
# puts f.max
puts max

n = gets.to_i
a = gets.split.map(&:to_i)
b = a.sort.uniq
c = Array.new(b.max + 1, 0)
for i in 0...b.size
  c[b[i]] = b[i] * a.count(b[i])
end

s = Array.new(b.max + 1, 0)
s[0] = 1
for i in 1...c.size - 1
  if c[i] >= c[i - 1] + c[i + 1]
    s[i - 1] = 0
    s[i + 1] = 0
    s[i] = 1
  else
    s[i - 1] = 1 if s[i - 2] == 0
    s[i + 1] = 1
    s[i] = 0
  end
end
ans = 0
for i in 0...c.size
  ans += c[i] * s[i]
end
p ans

n = gets.to_i
a = gets.split.map(&:to_i)
b = a.sort.uniq
c = Array.new(b.max + 1, 0)
for i in 0...b.size
  c[b[i]] = b[i] * a.count(b[i])
end

s = Array.new(b.max + 1, 0)
ans = c[1]
for i in 2...c.size
  if ans + c[i] - c[i - 1] > ans
    s[i] = 1
    ans += c[i] - c[i - 1]
    if s[i - 2] == 0 && s[i - 3] == 0 && c[i - 2] > 0
      ans += c[i - 2]
      s[i - 2] = 1
    end
  end
end
p ans

n = gets.to_i
a = gets.split.map(&:to_i)
b = a.sort.uniq
c = Array.new(b.max + 1, 0)
for i in 0...b.size
  c[b[i]] = b[i] * a.count(b[i])
end

s = Array.new(b.max + 1, 0)
s[0] = 0
for i in 1...c.size - 1
  if c[i] >= c[i - 1] + c[i + 1]
    s[i - 1] = 0
    s[i + 1] = 0
    s[i] = 1
  else
    s[i - 1] = 1 if s[i - 2] == 0
    s[i + 1] = 1
    s[i] = 0
  end
end
s[0] = 0
for i in 1...c.size
  s[i] = 1 if s[i - 1] == 0 && s[i + 1] == 0
end
ans = 0
for i in 0...c.size
  ans += c[i] * s[i]
end
p ans

n = gets.to_i
a = gets.split.map(&:to_i)
b = a.sort.uniq
c = Array.new(b.max + 1, 0)
for i in 0...b.size
  c[b[i]] = b[i] * a.count(b[i])
end

s = Array.new(b.max + 1, 0)
s[0] = 1
for i in 1...c.size - 1
  if c[i] >= c[i - 1] + c[i + 1]
    s[i - 1] = 0
    s[i + 1] = 0
    s[i] = 1
  else
    s[i - 1] = 1
    s[i + 1] = 1
    s[i] = 0
  end
end
ans = 0
for i in 0...c.size
  ans += c[i] * s[i]
end
p ans

n = gets.to_i
a = gets.split.map(&:to_i)
b = a.sort.uniq
c = Array.new(b.max + 1, 0)
for i in 0...b.size
  c[b[i]] = b[i] * a.count(b[i])
end

s = Array.new(b.max + 1, 0)
s[0] = 1
for i in 1...c.size - 1
  if c[i] >= c[i - 1] + c[i + 1]
    s[i - 1] = 0
    s[i + 1] = 0
    s[i] = 1
  else
    s[i - 1] = 1 if s[i - 2] == 0
    s[i + 1] = 1
    s[i] = 0
  end
  p s
end
p s
p c
ans = 0
for i in 0...c.size
  ans += c[i] * s[i]
end
p ans

# Hypothesis
# choose the most popular number
# if popularity is equal,
# take the largest number
def step(ak, sequence)
  sequence.delete_at(sequence.index(ak))
  sequence.select do |a|
    a != ak + 1 && a != ak - 1
  end
end

def get_next_pick(sequence)
  freq = sequence.inject(Hash.new(0)) { |h, v| h[v] += 1; h }
  if freq.values.uniq.length == 1
    sequence.max
  else
    sequence.max_by { |v| freq[v] }
  end
end

def simulate(input)
  sequence = input.split.map(&:to_i)
  score = 0
  until sequence.length == 0
    next_pick = get_next_pick(sequence)
    score += next_pick
    sequence = step(next_pick, sequence)
  end
  score
end

#input = '1 2'
#score = simulate(input)
#p "#{input}: #{score}"
#
#input = '1 2 3'
#score = simulate(input)
#p "#{input}: #{score}"
#
#input = '1 2 1 3 2 2 2 2 3'
#score = simulate(input)
#p "#{input}: #{score}"

input = gets.chomp
p input
input = gets.chomp
simulate(input)

# Hypothesis
# choose the most popular number
# if popularity is equal,
# take the largest number
def step(ak, sequence)
  sequence.delete_at(sequence.index(ak))
  sequence.select do |a|
    a != ak + 1 && a != ak - 1
  end
end

def get_next_pick(sequence)
  freq = sequence.inject(Hash.new(0)) { |h, v| h[v] += 1; h }
  if freq.values.uniq.length == 1
    sequence.max
  else
    sequence.max_by { |v| freq[v] }
  end
end

def simulate(input)
  sequence = input.split.map(&:to_i)
  score = 0
  until sequence.length == 0
    next_pick = get_next_pick(sequence)
    score += next_pick
    sequence = step(next_pick, sequence)
  end
  score
end

input = gets.chomp
simulate(input)

# Hypothesis
# choose the most popular number
# if popularity is equal,
# take the largest number
def step(ak, sequence)
  sequence.delete_at(sequence.index(ak))
  sequence.select do |a|
    a != ak + 1 && a != ak - 1
  end
end

def get_next_pick(sequence)
  freq = sequence.inject(Hash.new(0)) { |h, v| h[v] += 1; h }
  if freq.values.uniq.length == 1
    sequence.max
  else
    sequence.max_by { |v| freq[v] }
  end
end

def simulate(a)
  sequence = a
  score = 0
  until sequence.length == 0
    next_pick = get_next_pick(sequence)
    score += next_pick
    sequence = step(next_pick, sequence)
  end
  score
end

while STDIN.gets
  a = $_.split.map(&:to_i)
  if a.length > 1
    puts simulate(a)
  end
end

gets
a = gets.split(' ').map(&:to_i).sort.reverse
b = a.uniq.map { |x| [x, a.count{ |y| y == x } ] }.sort do |x, y|
  y.last != x.last ? y.last <=> x.last : y.first <=> x.first
end
c = Hash[ b ]

puts(
  b.map do |elm|
    res = [elm.last, c[elm.first]].min
    c[elm.first-1] = [0, c[elm.first-1]-res].max if c.key?(elm.first-1)
    c[elm.first+1] = [0, c[elm.first+1]-res].max if c.key?(elm.first+1)
    c[elm.first]   = 0

    res*elm.first
  end.inject(&:+)
)

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

#p a

prv = 1e6
score = 0
n.times do
    x = a.shift
    if x < prv - 1
        score += x
        prv = x
    end
end

puts score

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

cnt = Array.new(1e5+5,0)
a.map{|x| cnt[x]+=1}

dp = Array.new(1e5+5,0)

i = 1
hi2 = 0
(dp.length-2).times do
    i += 1
    hi2 = [hi2,dp[i-2]].max
    dp[i] = i * cnt[i] + hi2
end

puts dp.max

n = gets.chomp.to_i
a = gets.chomp.split(" ").map(&:to_i)
h = Hash.new(0)
a.each do |v|
  h[v] += 1
end
keys = h.keys.push(0).sort

r  = keys.size.times.map{ 0 }
rw = keys.size.times.map{ 0 }

keys.each_with_index do |k, i|
  rw[i] = r[i-1]
  if keys[i-1] == k - 1
    r[i] = rw[i-1] + k*h[k]
  else
    r[i] = rw[i-1] > r[i-1] ? rw[i-1] : r[i-1]
    r[i] += + k*h[k]
  end
end

puts [r[keys.last], rw[keys.last]].max

n = gets.chomp.to_i
a = gets.chomp.split(" ").map(&:to_i)
h = Hash.new(0)
a.each do |v|
  h[v] += 1
end
r = n.times.map{ 0 }

keys = h.keys.push(0).sort
keys.each_with_index do |k, i|
  r[i] = r[i-1]
  prev_key = keys[i-1]
  prev_score = h[prev_key]*prev_key
  score = h[k]*k
  if prev_key == k-1
    if score > prev_score
      r[i] += score - prev_score
      if keys[i-1] == keys[i-2] + 1
        r[i]+= r[i-2]
      end
    end
  else
    r[i] += h[k]*k
  end
end

puts r[keys.last]

n = gets.chomp.to_i
a = gets.chomp.split(" ").map(&:to_i)
h = Hash.new(0)
a.each do |v|
  h[v] += 1
end
keys = h.keys.push(0).sort

r  = keys.size.times.map{ 0 }
rw = keys.size.times.map{ 0 }

keys.each_with_index do |k, i|
  rw[i] = r[i-1]
  if keys[i-1] == k - 1
    r[i] = rw[i-1] + k*h[k]
  else
    r[i] = rw[i-1] > r[i-1] ? rw[i-1] : r[i-1]
    r[i] += + k*h[k]
  end
end

puts [r.last, rw.last].max

n = gets.strip.to_i
arr = gets.strip.split(" ").map(&:to_i)
arr.sort!
frequency = arr.inject({}){|freq, elem| freq.merge(elem => arr.count(elem))}
arr.uniq!
# p arr
# p frequency
results = []
results[0] = arr[0] * frequency[arr[0]]
if arr.length > 1 then
  second_sum = arr[1] * frequency[arr[1]]
  results[1] = second_sum > results[0] ? second_sum : results[0]
end
i = 2
while i < arr.length do
  if arr[i] - arr[i - 1] > 1 then
    results[i] = results[i - 1] + arr[i] * frequency[arr[i]]
  elsif results[i - 1] > arr[i] * frequency[arr[i]] + results[i - 2] then
    results[i] = results[i - 1]
  else
    results[i] =  arr[i] * frequency[arr[i]] + results[i - 2]
  end
  i += 1
end
puts results.last

n = gets.strip.to_i
arr = gets.strip.split(" ").map(&:to_i)
arr.sort!
frequency = arr.inject({}){|freq, elem| freq.merge(elem => arr.count(elem))}
arr.uniq!
# p arr
# p frequency
results = []
results[0] = arr[0] * frequency[arr[0]]
results[1] = arr[1] * frequency[arr[1]] if arr.length > 1
i = 2
while i < arr.length do
  if arr[i] - arr[i - 1] > 1 then
    results[i] = results[i - 1] + arr[i] * frequency[arr[i]]
  elsif results[i - 1] > arr[i] * frequency[arr[i]] + results[i - 2] then
    results[i] = results[i - 1]
  else
    results[i] =  arr[i] * frequency[arr[i]] + results[i - 2]
  end
  i += 1
end
puts results.last

n = gets.strip.to_i
arr = gets.strip.split(" ").map(&:to_i)
arr.sort!
j = 1
uniq_array = []
uniq_array[0] = arr[0]
frequency = Hash.new(0)
frequency[arr[0]] = 1
while j < arr.length do
  if arr[j] != arr[j - 1] then
    uniq_array.push(arr[j])
    frequency[arr[j]] = 1
  else
    frequency[arr[j]] += 1
  end
  j += 1
end
# p uniq_array
# p frequency

prev = uniq_array[0] * frequency[uniq_array[0]]
if uniq_array.length > 1 then
  if uniq_array[1] - uniq_array[0] > 1 then
    current = prev + uniq_array[1] * frequency[uniq_array[1]]
  else
    second_sum = uniq_array[1] * frequency[uniq_array[1]]
    current = second_sum > prev ? second_sum : prev
  end
end
i = 2
while i < uniq_array.length do
  if uniq_array[i] - uniq_array[i - 1] > 1 then
    current = current + uniq_array[i] * frequency[uniq_array[i]]
  elsif current <= uniq_array[i] * frequency[uniq_array[i]] + prev then
    current =  uniq_array[i] * frequency[uniq_array[i]] + prev
  end
  i += 1
end
puts current

n = gets.strip.to_i
arr = gets.strip.split(" ").map(&:to_i)
arr.sort!
j = 1
uniq_array = []
uniq_array[0] = arr[0]
frequency = Hash.new(0)
frequency[arr[0]] = 1
while j < arr.length do
  if arr[j] != arr[j - 1] then
    uniq_array.push(arr[j])
    frequency[arr[j]] = 1
  else
    frequency[arr[j]] += 1
  end
  j += 1
end
# p uniq_array
# p frequency

prev = uniq_array[0] * frequency[uniq_array[0]]
if uniq_array.length > 1 then
  if uniq_array[1] - uniq_array[0] > 1 then
    current = prev + uniq_array[1] * frequency[uniq_array[1]]
  else
    second_sum = uniq_array[1] * frequency[uniq_array[1]]
    current = second_sum > prev ? second_sum : prev
  end
end
i = 2
while i < uniq_array.length do
  if uniq_array[i] - uniq_array[i - 1] > 1 then
    prev = current
    current += uniq_array[i] * frequency[uniq_array[i]]
  elsif current < uniq_array[i] * frequency[uniq_array[i]] + prev then
    temp = current
    current =  uniq_array[i] * frequency[uniq_array[i]] + prev
    prev = temp
  else
    prev = current
  end
  i += 1
end
puts current

n = gets.to_i
arr = gets.split.map { |x| x.to_i }.sort
hash = Hash.new(0)
arr.each { |x| hash[x] += 1 }
hash = Hash[hash.sort_by { |key,value| value }]
sum = 0
while hash.size != 0
  temp = hash[hash.keys.last]
  sum += temp * hash.keys.last
  temp_key = hash.keys.last
  hash.delete(temp_key)
  hash.delete(temp_key - 1)
  hash.delete(temp_key + 1)
end
puts sum


You are given an array $$$a$$$ consisting of $$$n$$$ positive integers. You have to choose a positive integer $$$d$$$ and paint all elements into two colors. All elements which are divisible by $$$d$$$ will be painted red, and all other elements will be painted blue.The coloring is called beautiful if there are no pairs of adjacent elements with the same color in the array. Your task is to find any value of $$$d$$$ which yields a beautiful coloring, or report that it is impossible.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. The first line of each testcase contains one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of elements of the array. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^{18}$$$).

For each testcase print a single integer. If there is no such value of $$$d$$$ that yields a beautiful coloring, print $$$0$$$. Otherwise, print any suitable value of $$$d$$$ ($$$1 \le d \le 10^{18}$$$).

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  x = gets.chomp.split(" ").map(&:to_i)
  a = []
  b = []
  n.times do |i|
    if i%2==0
      a << x[i]
    else
      b << x[i]
    end
  end
  a_gcd = a.inject(:gcd)
  b_gcd = b.inject(:gcd)
  if b.all?{|v|v%a_gcd != 0}
    ans << a_gcd
  elsif a.all?{|v|v%b_gcd != 0}
    ans << b_gcd
  else
    ans << 0
  end
end
puts ans