The territory of Berland is represented by a rectangular field n × m in size. The king of Berland lives in the capital, located on the upper left square (1, 1). The lower right square has coordinates (n, m). One day the king decided to travel through the whole country and return back to the capital, having visited every square (except the capital) exactly one time. The king must visit the capital exactly two times, at the very beginning and at the very end of his journey. The king can only move to the side-neighboring squares. However, the royal advise said that the King possibly will not be able to do it. But there is a way out — one can build the system of one way teleporters between some squares so that the king could fulfill his plan. No more than one teleporter can be installed on one square, every teleporter can be used any number of times, however every time it is used, it transports to the same given for any single teleporter square. When the king reaches a square with an installed teleporter he chooses himself whether he is or is not going to use the teleport. What minimum number of teleporters should be installed for the king to complete the journey? You should also compose the journey path route for the king.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 100, 2 ≤  n · m) — the field size. The upper left square has coordinates (1, 1), and the lower right square has coordinates of (n, m).

On the first line output integer k — the minimum number of teleporters. Then output k lines each containing 4 integers x1 y1 x2 y2 (1 ≤ x1, x2 ≤ n, 1 ≤ y1, y2 ≤ m) — the coordinates of the square where the teleporter is installed (x1, y1), and the coordinates of the square where the teleporter leads (x2, y2). Then print nm + 1 lines containing 2 numbers each — the coordinates of the squares in the order in which they are visited by the king. The travel path must start and end at (1, 1). The king can move to side-neighboring squares and to the squares where a teleporter leads. Besides, he also should visit the capital exactly two times and he should visit other squares exactly one time.

m,n=gets.split.map(&:to_i)
f,n,m=0,m,n if m%2>z=0
s=[[i=1,j=1]]
v="s.unshift [n,m,z=1,n<2?1:j]if j%2>0||n<2&&m>2;n<2&&j=1"
loop{s<<[i+=1,j]while i<n
break eval v if m==j
s<<[i,j+=1]
s<<[i-=1,j]while i>2
break eval v if m==j
s<<[i,j+=1]}
s<<[1,j+1]until 0>j-=1
f||s.map!{|i|i.each_slice(2).to_a.flat_map &:reverse}
puts z,s.map{|i|i*" "}

n,m=gets.split.map(&:to_i)
f,n,m=0,m,n if n%2==0
s=[[i=1,j=1]]
z = 0
loop do
    while i < n
        s << [i+=1,j]
    end
    if m == j
        if n == 1
            s.unshift [1,m,1,1]
            s << [1,1]
        else
            s.unshift [n,m,1,j=m]
            if i > 1
                s << [1,j]
                while j > 1
                    s << [1,j-=1]
                end
            end
        end
        z = 1
        break
    end
    s << [i,j+=1]
    while i > 2
        s << [i-=1,j]
    end
    if m == j
        if n == 1
            if m > 2
                z = 1
                s.unshift [1,m,1,1]
            end
            s << [1,1]
        else
            #s.unshift [n,m,1,j=m]
            if i > 1
                s << [1,j]
                while j > 1
                    s << [1,j-=1]
                end
            end
        end
        break
    end
    s << [i,j+=1]
end
p z
if f
    s.map!{|i|i.each_slice(2).to_a.flat_map &:reverse}
end
s.each{|i|puts i*" "}

def generate_teleport_path(n, m)
  path = []
  columns = [ (1 .. m).to_a.reverse, (1 .. m).to_a ]
  (1 .. n).each do |row|
    index = row % 2
    columns[index].each { |col| path.push([row, col]) }
  end
  path.push([1, 1])
  return path
end

def generate_path(n, m)
  if n % 2 == 1
    result = generate_path(m, n)
    return result.map { |v| v.reverse }
  end
  path = []
  (1 .. m).each { |col| path.push([1, col]) }
  columns = [ (2 .. m).to_a.reverse, (2 .. m).to_a ]
  (2 .. n).each do |row|
    index = row % 2
    columns[index].each { |col| path.push([row, col]) }
  end
  n.downto(1) { |row| path.push([row, 1]) }
  return path
end

n, m = gets.split.map { |v| v.to_i }

teleports = []

if n == 1 and m == 1
  path = [[1, 1], [1, 1]]
elsif (n == 1 and m == 2) or (n == 2 and m == 1)
  path = [[1, 1], [n, m], [1, 1]]
elsif n % 2 == 1 and m % 2 == 1 or n == 1 or m == 1
  teleports = [[n, m, 1, 1]]
  path = generate_teleport_path(n, m)
else
  path = generate_path(n, m)
end

puts teleports.size
teleports.each { |port| puts port.join(' ') }
path.each { |pair| puts pair.join(' ') }

n,m=gets.split.map(&:to_i)
f,n,m=0,m,n if n%2==0
s=[[i=1,j=1]]
z = 0
loop do
    while i < n
        s << [i+=1,j]
    end
    if m == j
        z = 1
        s.unshift [n,m,1,j=m]
        break
    end
    s << [i,j+=1]
    while i > 2
        s << [i-=1,j]
    end
    if m == j
        break
    end
    s << [i,j+=1]
end
s << [1,j] if i>1
while j > 1
    s << [1,j-=1]
end
p z
if f
    s.map!{|i|i.each_slice(2).to_a.flat_map &:reverse}
end
s.each{|i|puts i*" "}

n,m=gets.split.map(&:to_i)
f,n,m=0,m,n if n%2==0
s=[[i=1,j=1]]
z = 0
loop do
    while i < n
        s << [i+=1,j]
    end
    if m == j
        if n == 1
            s.unshift [1,m,1,1]
            s << [1,1]
        else
            s.unshift [n,m,1,j=m]
            if i > 1
                s << [1,j]
                while j > 1
                    s << [1,j-=1]
                end
            end
        end
        z = 1
        break
    end
    s << [i,j+=1]
    while i > 2
        s << [i-=1,j]
    end
    if m == j
        if n == 1
            s.unshift [1,m,1,1]
            s << [1,1]
        else
            #s.unshift [n,m,1,j=m]
            if i > 1
                s << [1,j]
                while j > 1
                    s << [1,j-=1]
                end
            end
        end
        z = 1
        break
    end
    s << [i,j+=1]
end
p z
if f
    s.map!{|i|i.each_slice(2).to_a.flat_map &:reverse}
end
s.each{|i|puts i*" "}

n,m=gets.split.map(&:to_i)
f,n,m=0,m,n if n%2==0
s=[[i=1,j=1]]
z = 0
loop do
    while i < n
        s << [i+=1,j]
    end
    if m == j
        z = 1
        s.unshift [n,m,1,j=m]
        break
    end
    s << [i,j+=1]
    while i > 2
        s << [i-=1,j]
    end
    if m == j
        break
    end
    s << [i,j+=1]
end
s << [1,j]
while j > 1
    s << [1,j-=1]
end
p z
if f
    s.map!{|i|i.each_slice(2).to_a.flat_map &:reverse}
end
s.each{|i|puts i*" "}

n,m=gets.split.map(&:to_i)
f,n,m=0,m,n if n%2==0
s=[[i=1,j=1]]
z = 0
loop do
    while i < n
        s << [i+=1,j]
    end
    if m == j
        if n == 1
            z = 1
            s.unshift [1,m,1,1]
            s << [1,1]
        else
            z = 1
            s.unshift [n,m,1,j=m]
            if i > 1
                s << [1,j]
                while j > 1
                    s << [1,j-=1]
                end
            end
        end
        z = 1
        break
    end
    s << [i,j+=1]
    while i > 2
        s << [i-=1,j]
    end
    if m == j
        if n == 1
            z = 1
            s.unshift [1,m,1,1]
            s << [1,1]
        else
            #s.unshift [n,m,1,j=m]
            if i > 1
                s << [1,j]
                while j > 1
                    s << [1,j-=1]
                end
            end
        end
        z = 1
        break
    end
    s << [i,j+=1]
end
p z
if f
    s.map!{|i|i.each_slice(2).to_a.flat_map &:reverse}
end
s.each{|i|puts i*" "}

n,m=gets.split.map(&:to_i)
f,n,m=0,m,n if n%2==0
s=[[i=1,j=1]]
z = 0
loop do
    while i < n
        s << [i+=1,j]
    end
    if m == j
        if n == 1
            s.unshift [1,m,1,1]
            s << [1,1]
        else
            s.unshift [n,m,1,j=m]
            if i > 1
                s << [1,j]
                while j > 1
                    s << [1,j-=1]
                end
            end
        end
        z = 1
        break
    end
    s << [i,j+=1]
    while i > 2
        s << [i-=1,j]
    end
    if m == j
        if n == 1
            s.unshift [1,m,1,1]
            s << [1,1]
        else
            s.unshift [n,m,1,j=m]
            if i > 1
                s << [1,j]
                while j > 1
                    s << [1,j-=1]
                end
            end
        end
        z = 1
        break
    end
    s << [i,j+=1]
end
p z
if f
    s.map!{|i|i.each_slice(2).to_a.flat_map &:reverse}
end
s.each{|i|puts i*" "}

n,m=gets.split.map(&:to_i)
f,n,m=0,m,n if n%2==0
s=[[i=1,j=1]]
z = 0
loop do
    while i < n
        s << [i+=1,j]
    end
    if m == j
        if n == 1
            s.unshift [1,m,1,1]
            s << [1,1]
        else
            s.unshift [n,m,1,j=m]
            if i > 1
                s << [1,j]
                while j > 1
                    s << [1,j-=1]
                end
            end
        end
        z = 1
        break
    end
    s << [i,j+=1]
    while i > 2
        s << [i-=1,j]
    end
    if m == j
        if n == 1
            z = 1
            s.unshift [1,m,1,1]
            s << [1,1]
        else
            #s.unshift [n,m,1,j=m]
            if i > 1
                s << [1,j]
                while j > 1
                    s << [1,j-=1]
                end
            end
        end
        break
    end
    s << [i,j+=1]
end
p z
if f
    s.map!{|i|i.each_slice(2).to_a.flat_map &:reverse}
end
s.each{|i|puts i*" "}

n,m=gets.split.map(&:to_i)
f,n,m=0,m,n if n%2==0
s=[[i=1,j=1]]
z = 0
loop do
    while i < n
        s << [i+=1,j]
    end
    if m == j
        z = 1
        s.unshift [m,n,j=m,1]
        break
    end
    s << [i,j+=1]
    while i > 2
        s << [i-=1,j]
    end
    if m == j
        break
    end
    s << [i,j+=1]
end
s << [1,j]
while j > 1
    s << [1,j-=1]
end
p z
if f
    s.map!{|i|i.each_slice(2).to_a.flat_map &:reverse}
end
s.each{|i|puts i*" "}

def generate_teleport_path(n, m)
  path = []
  columns = [ (1 .. m).to_a.reverse, (1 .. m).to_a ]
  (1 .. n).each do |row|
    index = row % 2
    columns[index].each { |col| path.push([row, col]) }
  end
  path.push([1, 1])
  return path
end

def generate_path(n, m)
  if n % 2 == 1
    result = generate_path(m, n)
    return result.map { |v| v.reverse }
  end
  path = []
  (1 .. m).each { |col| path.push([1, col]) }
  columns = [ (2 .. m).to_a.reverse, (2 .. m).to_a ]
  (2 .. n).each do |row|
    index = row % 2
    columns[index].each { |col| path.push([row, col]) }
  end
  n.downto(1) { |row| path.push([row, 1]) }
  return path
end

n, m = gets.split.map { |v| v.to_i }

teleports = []

if n == 1 and m == 1
  path = [[1, 1], [1, 1]]
elsif n % 2 == 1 and m % 2 == 1 or n == 1 or m == 1
  teleports = [[n, m, 1, 1]]
  path = generate_teleport_path(n, m)
else
  path = generate_path(n, m)
end

puts teleports.size
teleports.each { |port| puts port.join(' ') }
path.each { |pair| puts pair.join(' ') }


One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on.These events are given as a sequence of strings "name1 reposted name2", where name1 is the name of the person who reposted the joke, and name2 is the name of the person from whose news feed the joke was reposted. It is guaranteed that for each string "name1 reposted name2" user "name1" didn't have the joke in his feed yet, and "name2" already had it in his feed by the moment of repost. Polycarp was registered as "Polycarp" and initially the joke was only in his feed.Polycarp measures the popularity of the joke as the length of the largest repost chain. Print the popularity of Polycarp's joke.

The first line of the input contains integer n (1 ≤ n ≤ 200) — the number of reposts. Next follow the reposts in the order they were made. Each of them is written on a single line and looks as "name1 reposted name2". All the names in the input consist of lowercase or uppercase English letters and/or digits and have lengths from 2 to 24 characters, inclusive. We know that the user names are case-insensitive, that is, two names that only differ in the letter case correspond to the same social network user.

Print a single integer — the maximum length of a repost chain.

5
tourist reposted Polycarp
Petr reposted Tourist
WJMZBMR reposted Petr
sdya reposted wjmzbmr
vepifanov reposted sdya

6
Mike reposted Polycarp
Max reposted Polycarp
EveryOne reposted Polycarp
111 reposted Polycarp
VkCup reposted Polycarp
Codeforces reposted Polycarp

@data = $stdin.read.split
n = @data.shift.to_i
result = 0
h = {}
(@data.size / 3).times do
	a, rep, b = @data.shift, @data.shift, @data.shift
	raise 'wrong data' unless rep == 'reposted'
	h[b.downcase] ||= 1
	h[a.downcase] = h[b.downcase] + 1
	result = [result, h[a.downcase]].max
end
puts result

class List
  attr_accessor :element, :next_elem

  def initialize(element, next_elem)
    @element = element
    @next_elem = next_elem
  end
end

class Graph
  attr_accessor :vertices

  def initialize(vertices)
    @vertices = vertices
  end

  def add_edge(name1, name2)
    if vertices[name1].nil? then
      vertices[name1] = List.new(name2, nil)
    else
      vertices[name1] = List.new(name2, vertices[name1])
    end
  end

  def print_edges
    vertices.each do |name, vertex|
      # next if vertex == ""
      while !vertex.nil? do
        puts "edge #{name} - #{vertex.element}"
        vertex = vertex.next_elem
      end
    end
  end

  # def print_verteces
  #   puts vertices.keys.join(" ")
  # end
end

def dfs(graph, name)
  current_vertex = graph.vertices[name]
  if current_vertex.nil?
    return 1
  else
    max = 1
    while !current_vertex.nil?
      max = [max, dfs(graph, current_vertex.element)].max
      current_vertex = current_vertex.next_elem
    end
  end
  return max + 1
end

reposts = Graph.new({})
n = gets.strip.to_i
n.times do |i|
  str = gets.strip.split(" ")
  reposts.add_edge(str.last.downcase, str.first.downcase)
end
# reposts.print_edges
puts dfs(reposts, "polycarp")

rlevels = Hash.new

rlevels["polycarp"] = 1

repcount = gets.strip.to_i

repcount.times do |i|
    string = gets.strip.downcase.split(" ")
    name1 = string[0]
    name2 = string[2]
    rl = rlevels[name2]
    rlevels[name1] = rl+1
end

p rlevels.values.max

h = Hash.new

n = gets.to_i

h['polycarp'] = 1
ans = 1

n.times do |i|
    a, b, c = gets.split.map {|s| s.downcase }
    h[a] = h[c] + 1

    ans = [ans, h[a]].max
end

puts ans

amount =  gets.chomp.to_i
$names = []

amount.times {
	repost = gets.chomp.split(' ')
	$names.push([repost[0].downcase, repost[2].downcase])
}

$max = 0

def dfs(name, length)
	$names.each { |x|
		if x[1] == name
			dfs(x[0], length+1)
		end
	}

	if length > $max
		$max = length
	end
end

dfs("polycarp", 0)

puts $max + 1

gets
w = {}
while(ln = gets)
  dst, _, src = ln.downcase.split(' ')
  w[dst] = (w[src] || 1) + 1
end
puts w.values.max

gets
w = {}
while(ln = gets)
  dst, src = ln.downcase.split(' ') - ['reposted']
  w[dst] = (w[src] || 1) + 1
end
puts w.values.max

h=Hash.new(0)

gets.to_i.times do |x|
  a=gets.chomp.split
  n1=a[0].downcase
  n2=a[2].downcase
  h[n2]=1 if x==0
  h[n1]=h[n2]+1
end

p h.values.max

n = gets.sub("\n","").to_i
h = {"polycarp"=>1}
n.downto(1) do
	a,b = gets.sub("\n","").split(" reposted ").map{|i| i.downcase}
	h[a] = h[b] + 1
end
max = 0
h.values.each{|i| max = i if(i>max)}
puts max

@inf = 1000000000
e = gets.strip.to_i

depth = {}
depth['polycarp'] = 1

e.times do |i|
  x, _, y = gets.strip.split.map(&:to_s).map(&:downcase)
  depth[x] = (depth[y] || 0) + 1
end

puts depth.values.max

i = gets.to_i
seq = 0
reposts = Array.new()
owners = Array.new().push("polycarp")
reposters = Array.new()
1.upto(i) { reposts.push(gets.split(' ').map { |e| e.downcase  } ) }
while owners.count > 0
	owners.each do |owner|
		reposts.each do |repost|
			reposters<< repost.first if repost.last == owner
		end
	end
	owners = reposters.clone()
	reposters.clear()
	seq+=1
end
puts seq


A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1 ≤ i ≤ n) (n is the permutation size) the following equations hold ppi = i and pi ≠ i. Nickolas asks you to print any perfect permutation of size n for the given n.

A single line contains a single integer n (1 ≤ n ≤ 100) — the permutation size.

If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p1, p2, ..., pn — permutation p, that is perfect. Separate printed numbers by whitespaces.

n = gets.to_i
if n % 2 == 1
  puts -1
else
  puts (1..n).each_slice(2).map{|x,y| [y,x]}.inject(:+).map(&:to_s).join(' ')
end

sin = STDIN
sout = STDOUT
# sin = File.open("test.in", "r")
# sout = File.open("test.out", "w")

n = sin.readline.to_i
sout.puts(n.even? ? (1..n).to_a.reverse.to_s.gsub(",", "")[1...-1] : -1)

jom = gets.to_i

if jom%2 == 1
       print "-1"
else
  print "2 1 "
  jom.downto(3) { |n| print n.to_s + " " }
end

#!/usr/bin/ruby
n=gets.to_i
puts n%2==1 ? -1 : [*1..n].each_slice(2).map{|a,b|[b,a]}*' '

n = gets.to_i
puts n.odd? ? -1 : [*1..n].each_slice(2).map(&:reverse)

n=gets.to_i
if n%2!=0
puts -1
else
	a=(1..n).to_a
	i=0
	while i<n do
		a[i],a[i+1]=a[i+1],a[i]; i+=2; end
	print a.join(" ")
	end

n = gets.to_i

if n % 2 == 1
  puts "-1"
  exit
end

for i in 1..n/2
  print "#{i*2} #{i*2 - 1} "
end

def main(n)
  ans = []
  if n % 2 == 0
    1.step(n, 2) do |i|
      ans << i + 1
      ans << i
    end
  else
    ans << -1
  end

  return ans
end

n = gets.chomp.to_i
ans = main(n)
puts ans.join(" ")

n = gets.to_i
if n%2 == 1
  print "-1"
else
  for i in 1..n
    if i%2 == 1
	  print (i+1).to_s + " "
	else
	  print (i-1).to_s + " "
	end
  end
end

def permute(n)
  return -1 if n % 2 == 1
  a = (1..n).to_a

  i = 0
  p = []
  while i < n-1
    p[i] = a[i+1]
    p[i+1] = a[i]
    i +=2
  end
  p.join(' ')
end

n = gets.to_i
puts permute(n)

n=gets.to_i
a=[0]
if n&1==1
	puts "-1"
	exit
end
for i in 1..n
	a.push(i)
end
for k in 1..(n/2)+2
	if 2*(k)<=n
		a[2*k],a[(2*k)-1]=a[(2*k)-1],a[2*k]
	end
end
for i in 1..n
	print a[i].to_s+' '
end
puts

n = gets.to_i
if n.odd?
  puts (-1)
  exit
else
  a = (1..n).to_a
  (0...n).select { |x| x.even? }.map { |x| a[x], a[x+1] = a[x+1], a[x]}
  puts a*' '
end

a=gets.chomp.to_i
if a%2==1
puts "-1"
else
a.downto(1) do |i|
printf"#{i} "
end
end

n = gets.to_i
if n % 2 == 1 then
    puts -1
else
    (n / 2).times do |i|
        print (2 * (i + 1)).to_s + " " + (2 * (i + 1) - 1).to_s
        if i == n - 1 then print "\n" else print " " end
    end
end

n = gets.to_i

if n.odd?
  puts -1
else
  ans = []
  (1..n).each do |i|
    if i.odd?
      ans << i + 1
    else
      ans << i - 1
    end
  end
  puts ans.join(" ")
end

n = gets.chomp.to_i
if n.even?
    array = (1..n).to_a
    index = 0
    while index < n
        array[index], array[index + 1] = array[index + 1], array[index]
        index += 2
    end
    puts array.join(" ")
else
    puts "-1"
end

n=gets.to_i
if n%2==1 then
	puts -1
else
	arr=[]
	2.step(n,2){|i|
		arr<<(i)
		arr<<(i-1)
	}
	puts arr*" "
end

n = gets.to_i
if n % 2 == 1
  puts "-1"
  exit
end
a = -1
n.times do |i|
  if i % 2 == 0
    a += 3
  else
    a -= 1
  end
  print a
  if n != i-1
    print " "
  else
    print "\n"
  end
end

require 'set'
require 'rational'
require 'mathn'
include Math
$stdin = File.open("./input.txt", "r") if ENV["USER"] == "new"
# ====================================

n = gets.to_i

if n%2!=0 then
  print -1
  exit
end

n.downto(1) do |index|
  print index," "
end

a=1
n=gets.to_i
half=n/2

if n==2
	puts '2 1'
elsif n%2==0
	half.times{|i|
	print a+1,' ',a
	if i!=(half-1) then
		print ' '
	else
		print "\n"
	end
	a+=2}
else
	puts '-1'
end

n = gets.to_i
if n%2==1
	p -1
	exit
end
(n/2).times do |x|
	print "#{2*x+2} #{2*x+1} "
end

n = gets.to_i
if n.odd?
	puts -1
else
	p = (1..n).each_slice(2).map{|a| [a[1],a[0]]}.flatten
	puts p.join(" ")
end

l = (1..gets.to_i).to_a
i = 1
while i < l.size
	l[i - 1], l[i] = l[i], l[i - 1]
	i += 2
end

if l.each_with_index.all? { |x, i| l[x - 1] == i + 1 and x != i + 1 }
	puts l.join(" ")
else
	puts -1
end

n = gets.to_i
if n%2==0
    puts (1..n).to_a.select{|x| x%2!=0}.map{|x| [x+1,x]}.flatten.join(' ')
else
    p -1
end

n = gets.to_i
if n%2 == 0
  (n/2).times {|x| print x*2 + 2, ' ', x*2 + 1, ' '}
else
  puts -1
end

#!/usr/bin/env ruby
$stdin.readlines.each do |line|
    n = line.strip.to_i
    if n % 2 == 0
        nums = (1..n).to_a
        i = 0
        while i < n-1
            t = nums[i]
            nums[i] = nums[i+1]
            nums[i+1] = t
            i += 2
        end
        puts nums.join(' ')
    else
        puts '-1'
    end
end

n = gets.to_i
if n % 2 == 0
  (1..n/2).each { |i|
    print 2*i, ' ', 2*i-1, ' '
  }
else
  puts -1
end

n = gets.to_i
if (n%2==1)
  puts -1
  exit
end
(n/2).times do |i|
  print "#{2*(i+1)} #{2*(i+1)-1} "
end

n = Integer(gets.chomp)
if n.even?
  a = []
  for i in (1..n).step(2)
    a << i + 1 << i
  end
  puts(a * ' ')
else
  puts -1
end

n = gets.to_i

if n.odd?
	puts -1
else
	p = Array.new(n) { |i, v| v = i + 1 }
	(n / 2).times do |i|
		p[i * 2], p[i * 2 + 1] = p[i * 2 + 1], p[i * 2]
	end
	puts p.join ' '
end

jom = gets.to_i

if jom == 1 or jom == 3
  puts "-1"
else
  print "2 1 "
  jom.downto(3) { |n| print n.to_s + " " }
end

def main(n)
  return [-1] if n == 1

  ans = []
  if n % 2 == 0
    1.step(n, 2) do |i|
      ans << i + 1
      ans << i
    end
  else
    1.step(n, 3) do |i|
      ans << i + 1
      ans << i + 2
      ans << i
    end
  end

  return ans
end

n = gets.chomp.to_i
ans = main(n)
puts ans.join(" ")

def permute(n)
  return -1 if n == 1
  a = (1..n).to_a
  # Swapping elements with their consecutives
  (1..n-1).each {|i| t = a[i-1]; a[i-1] = a[i]; a[i] = t}
  a.join(' ')
end

n = gets.to_i
puts permute(n)

def permute(n)
  return -1 if n == 1
  a = (1..n).to_a

  i = 0
  p = []
  while i < n-1
    p[i] = a[i+1]
    p[i+1] = a[i]
    i +=2
  end
  p.join(' ')
end

n = gets.to_i
puts permute(n)

n = gets.chomp.to_i
if n > 1
    array = (1..n).to_a
    index = 0
    while index < n
        array[index], array[index + 1] = array[index + 1], array[index]
        index += 2
    end
    puts array.join(" ")
else
    puts "-1"
end

n=gets.to_i
if n==1 then
	puts -1
else
	puts (1..(n-1)).to_a.unshift(n)*" "
end

n=gets.to_i
half=n/2

if n==1 then
	puts '-1'
elsif n==2
	puts '2 1'
else
	half.downto(1){|i|
	print i,' '
	}

	(n).downto(half+1){|i|
	print i
	print (if i!=(half+1) then
		' '
	else
		"\n"
	end)
	}
end

n=gets.to_i
half=n/2

if n==2
	puts '2 1'
elsif n%2==0
	half.downto(1){|i|
	print i,' '
	}

	(n).downto(half+1){|i|
	print i
	print (if i!=(half+1) then
		' '
	else
		"\n"
	end)
	}
else
	puts '-1'
end


Every Codeforces user has rating, described with one integer, possibly negative or zero. Users are divided into two divisions. The first division is for users with rating 1900 or higher. Those with rating 1899 or lower belong to the second division. In every contest, according to one's performance, his or her rating changes by some value, possibly negative or zero.Limak competed in n contests in the year 2016. He remembers that in the i-th contest he competed in the division di (i.e. he belonged to this division just before the start of this contest) and his rating changed by ci just after the contest. Note that negative ci denotes the loss of rating.What is the maximum possible rating Limak can have right now, after all n contests? If his rating may be arbitrarily big, print "Infinity". If there is no scenario matching the given information, print "Impossible".

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000). The i-th of next n lines contains two integers ci and di ( - 100 ≤ ci ≤ 100, 1 ≤ di ≤ 2), describing Limak's rating change after the i-th contest and his division during the i-th contest contest.

If Limak's current rating can be arbitrarily big, print "Infinity" (without quotes). If the situation is impossible, print "Impossible" (without quotes). Otherwise print one integer, denoting the maximum possible value of Limak's current rating, i.e. rating after the n contests.

NoteIn the first sample, the following scenario matches all information Limak remembers and has maximum possible final rating:  Limak has rating 1901 and belongs to the division 1 in the first contest. His rating decreases by 7.  With rating 1894 Limak is in the division 2. His rating increases by 5.  Limak has rating 1899 and is still in the division 2. In the last contest of the year he gets  + 8 and ends the year with rating 1907. In the second sample, it's impossible that Limak is in the division 1, his rating increases by 57 and after that Limak is in the division 2 in the second contest.

#!/usr/bin/ruby
ma=Float::INFINITY
mi=-ma
s=0
gets.to_i.times{
	c,d=gets.split.map &:to_i
	if d==1
		mi=[mi,1900-s].max
	else
		ma=[ma,1899-s].min
	end
	s+=c
}
puts ma==Float::INFINITY ? :Infinity : ma>=mi ? ma+s : :Impossible

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

d1acc = 0
current = nil
ans = nil
a.each_with_index do |x, i|
  change, div = x
  if div == 1
    d1acc += change
  elsif div == 2
    ans = 'Impossible' if i > 0 && a[i - 1][1] == 1 && d1acc >= 0
    d1acc = 0
    current = 1899 unless current
  end
  if current
    current += change
    if current < 1900 && i < n - 1 && a[i + 1][1] == 1
      current = 1900
    elsif current >= 1900 && i < n - 1 && a[i + 1][1] == 2
      current = 1899
    end
  end
end
if current
  try = current
  a.reverse.each do |change, div|
    try -= change
    ans = 'Impossible' if try < 1900 && div != 2 || try >= 1900 && div != 1
  end
else
  ans = 'Infinity'
end
puts ans || current

def solve(a)
  current = nil
  a.each do |change, div|
    current ||= 1899 if div == 2
    if current
      current = 1900 if div == 1 && current < 1900
      current = 1899 if div == 2 && current >= 1900
      current += change
    end
  end

  if current
    a.reverse_each.inject(current) do |try, (change, div)|
      try -= change
      return 'Impossible' if div == 1 && try < 1900 || div == 2 && try >= 1900
      try
    end
  else
    return 'Infinity'
  end

  return current
end

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

puts solve(a)


A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily $$$7$$$ days!In detail, she can choose any integer $$$k$$$ which satisfies $$$1 \leq k \leq r$$$, and set $$$k$$$ days as the number of days in a week.Alice is going to paint some $$$n$$$ consecutive days on this calendar. On this calendar, dates are written from the left cell to the right cell in a week. If a date reaches the last day of a week, the next day's cell is the leftmost cell in the next (under) row.She wants to make all of the painted cells to be connected by side. It means, that for any two painted cells there should exist at least one sequence of painted cells, started in one of these cells, and ended in another, such that any two consecutive cells in this sequence are connected by side.Alice is considering the shape of the painted cells. Two shapes are the same if there exists a way to make them exactly overlapped using only parallel moves, parallel to the calendar's sides.For example, in the picture, a week has $$$4$$$ days and Alice paints $$$5$$$ consecutive days. [1] and [2] are different shapes, but [1] and [3] are equal shapes.    Alice wants to know how many possible shapes exists if she set how many days a week has and choose consecutive $$$n$$$ days and paints them in calendar started in one of the days of the week. As was said before, she considers only shapes, there all cells are connected by side.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case, the only line contains two integers $$$n$$$, $$$r$$$ ($$$1 \le n \le 10^9, 1 \le r \le 10^9$$$).

For each test case, print a single integer  — the answer to the problem. Please note, that the answer for some test cases won't fit into $$$32$$$-bit integer type, so you should use at least $$$64$$$-bit integer type in your programming language.

NoteIn the first test case, Alice can set $$$1,2,3$$$ or $$$4$$$ days as the number of days in a week.There are $$$6$$$ possible paintings shown in the picture, but there are only $$$4$$$ different shapes. So, the answer is $$$4$$$. Notice that the last example in the picture is an invalid painting because all cells are not connected by sides.    In the last test case, be careful with the overflow issue, described in the output format.

t = gets.to_i
t.times do
	n, r = gets.split.map &:to_i
	x = 0
	k = [r, n-1].min
	x += [0, (k+1)*k/2].max
	x += 1 if r >= n
	p x
end

require 'set'; require 'prime'; require 'pp'
INF=Float::INFINITY; MOD=10**9+7
t = gets.chomp.to_i
t.times do
  n,r = gets.chomp.split.map(&:to_i)
  if n > r
    num = r
    puts num * (num+1) / 2
  else
    num = n - 1
    puts num * (num+1) / 2 + 1
  end
end
#######

n = gets.chomp.to_i
n.times do
    n, r = gets.chomp.split(" ").map(&:to_i)
    if n > r
        ans =  r * (1 + r)
        puts ans / 2
    elsif n <= r
        ans = (n-1) * n
        puts ans / 2 + 1
    end
end

# this code is just to observe speed
t = gets.chomp.to_i
a = Array.new(t)
for i in 0..t-1 do
  n,r = gets.chomp.split.map(&:to_i)
  if n > r
    num = r
    a[i] = num * (num+1) / 2
  else
    num = n - 1
    a[i] = num * (num+1) / 2 + 1
  end
end

puts a.join("\n")


Malek has recently found a treasure map. While he was looking for a treasure he found a locked door. There was a string s written on the door consisting of characters '(', ')' and '#'. Below there was a manual on how to open the door. After spending a long time Malek managed to decode the manual and found out that the goal is to replace each '#' with one or more ')' characters so that the final string becomes beautiful. Below there was also written that a string is called beautiful if for each i (1 ≤ i ≤ |s|) there are no more ')' characters than '(' characters among the first i characters of s and also the total number of '(' characters is equal to the total number of ')' characters. Help Malek open the door by telling him for each '#' character how many ')' characters he must replace it with.

The first line of the input contains a string s (1 ≤ |s| ≤ 105). Each character of this string is one of the characters '(', ')' or '#'. It is guaranteed that s contains at least one '#' character.

If there is no way of replacing '#' characters which leads to a beautiful string print  - 1. Otherwise for each character '#' print a separate line containing a positive integer, the number of ')' characters this character must be replaced with. If there are several possible answers, you may output any of them.

Note|s| denotes the length of the string s.

s = STDIN.readline.strip

def fail
  puts -1
  exit
end

result = []
sum = 0
s.each_char do |ch|
  if ch == '('
    sum += 1
  elsif ch == ')'
    sum -= 1
    fail if sum < 0
  else
    result.push(1)
    sum -= 1
    fail if sum < 0
  end
end
result[-1] += sum

pos = s.index('(', s.rindex('#'))
if pos != nil
  tail_sum = 0
  s[pos..-1].each_char do |ch|
    if ch == '('
      tail_sum += 1
    else
      tail_sum -= 1
    end
  end
  fail if tail_sum > 0
end

puts result.join("\n")

def solve(s)
    to = s.count {|c| c == '('}
    tc = s.count {|c| c == ')'}
    tp = s.count {|c| c == '#'}
    co = 0
    cc = 0
    cp = 0
    res = []
    i = 0
    r = tc
    s.each do |c|
        if c == '#'
            cp += 1
            if cp < tp
                res << 1
                cc += 1
            else
                if cc >= to
                    return nil
                end
                diff = to - cc - r
                return nil if diff == 0
                res << diff
                cc += diff
            end
        elsif c == '('
            co += 1
        elsif c == ')'
            cc += 1
            r -= 1
        end
        if cc > co
            #puts "#{i}: #{co}  #{cc}"
            return nil
        end
        i += 1
    end
    return res
end
s = STDIN.gets.chomp.split(//)
res = solve(s)
if not res
    puts "-1"
else
    res.each do |r|
        puts r
    end
end


This is the easy version of the problem. The difference between the versions is that the easy version does not require you to output the numbers of the rods to be removed. You can make hacks only if all versions of the problem are solved.Stitch likes experimenting with different machines with his friend Sparky. Today they built another machine.The main element of this machine are $$$n$$$ rods arranged along one straight line and numbered from $$$1$$$ to $$$n$$$ inclusive. Each of these rods must carry an electric charge quantitatively equal to either $$$1$$$ or $$$-1$$$ (otherwise the machine will not work). Another condition for this machine to work is that the sign-variable sum of the charge on all rods must be zero.More formally, the rods can be represented as an array of $$$n$$$ numbers characterizing the charge: either $$$1$$$ or $$$-1$$$. Then the condition must hold: $$$a_1 - a_2 + a_3 - a_4 + \ldots = 0$$$, or $$$\sum\limits_{i=1}^n (-1)^{i-1} \cdot a_i = 0$$$.Sparky charged all $$$n$$$ rods with an electric current, but unfortunately it happened that the rods were not charged correctly (the sign-variable sum of the charge is not zero). The friends decided to leave only some of the rods in the machine. Sparky has $$$q$$$ questions. In the $$$i$$$th question Sparky asks: if the machine consisted only of rods with numbers $$$l_i$$$ to $$$r_i$$$ inclusive, what minimal number of rods could be removed from the machine so that the sign-variable sum of charges on the remaining ones would be zero? Perhaps the friends got something wrong, and the sign-variable sum is already zero. In that case, you don't have to remove the rods at all.If the number of rods is zero, we will assume that the sign-variable sum of charges is zero, that is, we can always remove all rods.Help your friends and answer all of Sparky's questions!

Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$), denoting the number of test cases. Description of the test cases follows. The first line of each test case contains two positive integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 3 \cdot 10^5$$$) — the number of rods and the number of questions. The second line of each test case contains a non-empty string $$$s$$$ of length $$$n$$$, where the charge of the $$$i$$$-th rod is $$$1$$$ if $$$s_i$$$ is the "+" symbol, or $$$-1$$$ if $$$s_i$$$ is the "-" symbol. Each next line from the next $$$q$$$ lines contains two positive integers $$$l_i$$$ ans $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — numbers, describing Sparky's questions. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of $$$q$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case, print a single integer — the minimal number of rods that can be removed.

NoteIn the first test case for the first query you can remove the rods numbered $$$5$$$ and $$$8$$$, then the following set of rods will remain: +--+--++-++-. It is easy to see that here the sign-variable sum is zero.In the second test case:  For the first query, we can remove the rods numbered $$$1$$$ and $$$11$$$, then the following set of rods will remain: --++---++---. It is easy to see that here the sign-variable sum is zero.  For the second query we can remove the rod numbered $$$9$$$, then the following set of rods will remain: ---++-. It is easy to see that here the variable sum is zero.  For the third query we can not remove the rods at all.

t = gets.to_i
t.times do

n, q = gets.split.map!(&:to_i)
s = gets.chomp.chars.map! { |c| c == "+" ? 1 : -1 }
1.step(n-1, 2) { |i| s[i] = -s[i] }

x = 0
cs = s.map { |si| x += si }.unshift(0)

q.times do
  l, r = gets.split.map!(&:to_i)
  l -= 1
  diff = cs[r] - cs[l]

  if diff == 0
    puts 0
    next
  end

  if (r - l).even?
    puts 2
  else
    puts 1
  end
end

end


Not so long ago, Vlad came up with an interesting function: $$$f_a(x)=\left\lfloor\frac{x}{a}\right\rfloor + x \bmod a$$$, where $$$\left\lfloor\frac{x}{a}\right\rfloor$$$ is $$$\frac{x}{a}$$$, rounded down, $$$x \bmod a$$$ — the remainder of the integer division of $$$x$$$ by $$$a$$$.For example, with $$$a=3$$$ and $$$x=11$$$, the value $$$f_3(11) = \left\lfloor\frac{11}{3}\right\rfloor + 11 \bmod 3 = 3 + 2 = 5$$$.The number $$$a$$$ is fixed and known to Vlad. Help Vlad find the maximum value of $$$f_a(x)$$$ if $$$x$$$ can take any integer value from $$$l$$$ to $$$r$$$ inclusive ($$$l \le x \le r$$$).

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of input test cases. This is followed by $$$t$$$ lines, each of which contains three integers $$$l_i$$$, $$$r_i$$$ and $$$a_i$$$ ($$$1 \le l_i \le r_i \le 10^9, 1 \le a_i \le 10^9$$$) — the left and right boundaries of the segment and the fixed value of $$$a$$$.

For each test case, output one number on a separate line — the maximum value of the function on a given segment for a given $$$a$$$.

NoteIn the first sample:  $$$f_3(1) = \left\lfloor\frac{1}{3}\right\rfloor + 1 \bmod 3 = 0 + 1 = 1$$$,  $$$f_3(2) = \left\lfloor\frac{2}{3}\right\rfloor + 2 \bmod 3 = 0 + 2 = 2$$$,  $$$f_3(3) = \left\lfloor\frac{3}{3}\right\rfloor + 3 \bmod 3 = 1 + 0 = 1$$$,  $$$f_3(4) = \left\lfloor\frac{4}{3}\right\rfloor + 4 \bmod 3 = 1 + 1 = 2$$$ As an answer, obviously, $$$f_3(2)$$$ and $$$f_3(4)$$$ are suitable.

n = STDIN.gets.chomp.to_i
n.times.each do
  l,r,a = STDIN.gets.chomp.split(" ").map(&:to_i)
    puts [r/a+r%a,(r-r%a-1)/a+(r-r%a-1)%a].max if r-r%a-1>=l
    puts r/a+r%a if r-r%a-1<l
end

# Consider an example:
# a = 5
# Then the values from 0 to ... are:
# 0 1 2 3 4   1 2 3 4 5   2 3 4 5 6   3 4 5 6 7
# And so, if we are looking for the maximum, we should only consider:
# (1) Within each group, the farthest value to the right in the group that is
# available in the range l .. r
# (2) The last two groups.
# The reason for (2) is that, if a number is not in the last two groups, then
# it must be small than the last item in the second-to-last group.
# The last group might not be complete, which is why we need to check the second-
# to-last group as well.
# Answer is either :
# - Largest number in set (last item in last group) OR
# - Largest number i such that i % a = a - 1.     The mod of this is higher than the first choice.
#
# It's sufficient to check these two numbers:
# r
# r / a * a - 1, but only if it's in the range l .. r
#

gets.to_i.times do
  l,r,a = gets.split.map { |i| i.to_i }

  f = lambda {|i| i / a + i % a }
  last_of_second_last = r / a * a - 1
  if last_of_second_last.between?(l, r) then
    best = [f.call(r), f.call(last_of_second_last)].max
  else
    best = f.call(r)
  end
  puts(best)
end

def f(x,a)
  return(x/a + x % a)
end

def process(l, r, a)

  return [f(l, a),f(r,a)].max if r-l<=1
  m = (l + r ) / 2

  #puts "#{l} #{m} #{r} f#{f(l,a)} f#{f(m,a)} f#{f(r,a)}"
  #func = [l,m,r]
  #func = [l,m,r].sort!{|x,y| f(x,a) <=> f(y,a)}.drop(1).sort!
  #puts(" xxx #{func} xxx")
  fl=f(l,a)
  fm=f(m,a)
  fr=f(r,a)

  if fm>fl
    return process(m,r,a)
  elsif fm>fr
    return process(l,m,a)
  elsif fl>fr
    return process(l,m,a)
  else
    return process(m,r,a)

  end

  #if f(m,a)>=f(l,a)
#
  #  return process(m,r,a)
  #elsif f(m,a)>=f(r,a)
#
  #  return process(l,m,a)
  #else
  #  return process(m,r,a)
  #end
end

n = STDIN.gets.chomp.to_i
n.times.each do
  l,r,a = STDIN.gets.chomp.split(" ").map(&:to_i)
  #puts "#### #{l} #{r} #{a} ####"
  puts("#{process(l,r,a)}")
end

#n = STDIN.gets.chomp.to_i
#n.times.each do
#  l,r,a = STDIN.gets.chomp.split(" ").map(&:to_i)
#
#  puts ([r-(r%a)-1,l].max ... r+1).to_a.map { |value| (value/a) + value%a }.max
#end

#352038877 421606206 705339697
#
#l=352038877
#r=421606206
#a=705339697
#
#puts([r-a-1,l].max ... r+1)
#puts("count : #{([r-a-1,l].max ... r+1).count}\n")
#puts( "r%a : #{r%a}")
#
#([r-(r%a)-1,l].max ... r+1).to_a.each { |x|
#  puts "#{x}/#{a} + #{x}%#{a}  #{x/a} #{x%a} = #{x/a+x%a}"
#}
#

#r-(r/a)-1
#12-(1)-1
#a=8
#l=0
#(1...12).to_a.each do |i|
#  x=l+i
#
#  puts "#{x}/#{a} + #{x}%#{a}  #{x/a} #{x%a} = #{x/a+x%a}"
#end
#
#a=10
#l=90
#r=110
#x=r
#while x % a != a-1 and x >= l
#  x-=1
#end
#puts x

#l=5
#r=8
#a=4
##x=r
#puts ([r-(r/a),l].max ... r+1).to_a.map { |value| (value/a) + value%a }.max

# l 5
# r 8
# a 4
# x 7
#
# 4 = 7/4 + 7%4
#
# 10/2 + 10%2  5 0 = 0
# 11/2 + 11%2  5 1 = 1
#
#
#
#
#  x/a + x%a = Y

def f(x,a)
  return(x/a + x % a)
end

def process(l, r, a)

  return [f(l, a),f(r,a)].max if r-l<=1
  m = (l + r ) / 2

  if f(m,a)>=f(l,a)

    return process(m,r,a)
  elsif f(m,a)>=f(r,a)

    return process(l,m,a)
  else
    return process(m,r,a)
  end
end

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

  puts(process(l,r,a))
end

n = STDIN.gets.chomp.to_i
n.times.each do
  l,r,a = STDIN.gets.chomp.split(" ").map(&:to_i)
  puts ([a-l-1,l].max ... r+1).map { |value| (value/a) + value%a }.max
end

n = STDIN.gets.chomp.to_i
n.times.each do
  l,r,a = STDIN.gets.chomp.split(" ").map(&:to_i)
  puts (a-l ... r+1).map { |value| (value/a) + value%a }.max
end


Polycarp had an array $$$a$$$ of $$$3$$$ positive integers. He wrote out the sums of all non-empty subsequences of this array, sorted them in non-decreasing order, and got an array $$$b$$$ of $$$7$$$ integers.For example, if $$$a = \{1, 4, 3\}$$$, then Polycarp wrote out $$$1$$$, $$$4$$$, $$$3$$$, $$$1 + 4 = 5$$$, $$$1 + 3 = 4$$$, $$$4 + 3 = 7$$$, $$$1 + 4 + 3 = 8$$$. After sorting, he got an array $$$b = \{1, 3, 4, 4, 5, 7, 8\}.$$$Unfortunately, Polycarp lost the array $$$a$$$. He only has the array $$$b$$$ left. Help him to restore the array $$$a$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Each test case consists of one line which contains $$$7$$$ integers $$$b_1, b_2, \dots, b_7$$$ ($$$1 \le b_i \le 10^9$$$; $$$b_i \le b_{i+1}$$$).  Additional constraint on the input: there exists at least one array $$$a$$$ which yields this array $$$b$$$ as described in the statement.

For each test case, print $$$3$$$ integers — $$$a_1$$$, $$$a_2$$$ and $$$a_3$$$. If there can be several answers, print any of them.

NoteThe subsequence of the array $$$a$$$ is a sequence that can be obtained from $$$a$$$ by removing zero or more of its elements.Two subsequences are considered different if index sets of elements included in them are different. That is, the values of the elements don't matter in the comparison of subsequences. In particular, any array of length $$$3$$$ has exactly $$$7$$$ different non-empty subsequences.

n = gets.to_i
a = []

def find_ans(arr)
  i = 1
  j = i + 1
  while arr[i] + arr[j] != arr.last - arr[0]
    if j == i + 1
      j += 1
    else
      i += 1
    end
  end
  [arr[0], arr[i], arr[j]]
end

(0..n-1).each do |x|
	q = gets.chomp.split().map { |e| e.to_i  }
  p
	a.append(find_ans(q))
end

a.each do |x|
 puts x.join(' ')
end

t = gets.to_i
ans = []
t.times do
  b = gets.split.map(&:to_i)
  a = [b[0],b[1]]
  if b[0]+b[1] == b[2]
    a << b[3]
  else
    a << b[2]
  end
  ans << a
end
ans.each do |arr|
  puts arr.join(" ")
end

testcases = Integer(gets.chomp)
resultados = []

for i in 0..testcases-1
    arreglo = gets.chomp
    b = arreglo.split(" ")
    numeroAConstruir = b[6].to_i
    validar = true
    finalPrincipal = false
    aumentoPrincipal = 0
    finalSecundario = false
    aumentoSecundario = 1
    finalTerceario = false
    aumentoTercerario = 2
    while validar
        if finalTerceario
            finalTerceario = false
            aumentoSecundario+=1
            if aumentoSecundario == 5
                finalSecundario = true
            end
            aumentoTercerario = aumentoSecundario + 1
        end
        if finalSecundario
            finalSecundario = false
            aumentoPrincipal += 1
            aumentoSecundario = aumentoPrincipal + 1
            aumentoTercerario = aumentoSecundario + 1
        end
            b1 = b[aumentoPrincipal].to_i
            b2 = b[aumentoSecundario].to_i
            b3 = b[aumentoTercerario].to_i
        if b1+b2+b3 == numeroAConstruir
            resultados.push(b1.to_s+" "+b2.to_s+" "+b3.to_s)
            break
        end
        aumentoTercerario +=1
        if aumentoTercerario == 6
            finalTerceario = true
        end
    end
end
puts resultados

n = gets.to_i
a = []

def find_ans(arr)
  i = 1
  j = i + 1
  while arr[i] + arr[j] != arr.last - arr[0]
    if j == i + 1
      j += 1
    else
      i += 1
    end
  end
  [arr[0], arr[i], arr[j]]
end

(0..n-1).each do |x|
	q = gets.chomp.split().map { |e| e.to_i  }
  p
	a.append(find_ans(q))
end

a.each do |x|
 p x.map(&:inspect).join(' ')
end

n = gets.to_i
a = []

def find_ans(arr)
  i = 1
  j = i + 1
  while arr[i] + arr[j] != arr.last - arr[0]
    if j == i + 1
      j += 1
    else
      i += 1
    end
  end
  [arr[0], arr[i], arr[j]]
end

(0..n-1).each do |x|
	q = gets.chomp.split().map { |e| e.to_i  }
  p
	a.append(find_ans(q))
end

a.each do |x|
 p x
end


This is the easy version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version all prices are different.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.

The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ different integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres.

In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.

NoteIn the example it's not possible to place ice spheres in any order so that Sage would buy $$$3$$$ of them. If the ice spheres are placed like this $$$(3, 1, 4, 2, 5)$$$, then Sage will buy two spheres: one for $$$1$$$ and one for $$$2$$$, because they are cheap.

N = gets.to_i
A = gets.split.map(&:to_i).sort
res = []

N.times do |i|
  if i.even?
    res << A.pop
  else
    res << A.shift
  end
end

if N.even?
  puts N / 2 - 1
  puts res.join(' ')
else
  puts N / 2
  puts res.join(' ')
end


CQXYM is counting permutations length of $$$2n$$$.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).A permutation $$$p$$$(length of $$$2n$$$) will be counted only if the number of $$$i$$$ satisfying $$$p_i<p_{i+1}$$$ is no less than $$$n$$$. For example:  Permutation $$$[1, 2, 3, 4]$$$ will count, because the number of such $$$i$$$ that $$$p_i<p_{i+1}$$$ equals $$$3$$$ ($$$i = 1$$$, $$$i = 2$$$, $$$i = 3$$$). Permutation $$$[3, 2, 1, 4]$$$ won't count, because the number of such $$$i$$$ that $$$p_i<p_{i+1}$$$ equals $$$1$$$ ($$$i = 3$$$). CQXYM wants you to help him to count the number of such permutations modulo $$$1000000007$$$ ($$$10^9+7$$$).In addition, modulo operation is to get the remainder. For example:  $$$7 \mod 3=1$$$, because $$$7 = 3 \cdot 2 + 1$$$,  $$$15 \mod 4=3$$$, because $$$15 = 4 \cdot 3 + 3$$$.

The input consists of multiple test cases.  The first line contains an integer $$$t (t \geq 1)$$$ — the number of test cases. The description of the test cases follows. Only one line of each test case contains an integer $$$n(1 \leq n \leq 10^5)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$

For each test case, print the answer in a single line.

t = gets.to_i
MOD = 1000000007
t.times do
  n = gets.to_i
  a = 1
  (1..n*2).each {|i| a = (a * i) % MOD}
  puts (a * 500000004) % MOD
end


Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula , where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 ≤ x ≤ m.

The first line contains integer n (1 ≤ n ≤ 105) — the number of array elements. The next line contains n space-separated integers a0, a1, ..., an - 1 (0 ≤ ai ≤ 104) — elements of array a. The third line contains a sequence of digits zero and one without spaces s0s1... sn - 1 — the binary representation of number m. Number m equals .

Print a single integer — the maximum value of function f(x) for all .

NoteIn the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27.

n = gets.chomp.to_i
a = gets.chomp.split(" ").map{|i| i.to_i}
mbits = gets.chomp

length = mbits.length
max = 0
length.times.each do |i|
  max += a[i] if mbits[i] == '1'
end

default = max
sub_sum = 0
i = 0
while i < n do
  if mbits[i] == '1'
    last_sum = default + sub_sum - a[i]
    max = last_sum if last_sum > max
  else
    sub_sum += a[i]
  end
  i += 1

end

puts max

n = gets.to_i
a = gets.chomp.split(" ").map{|i| i.to_i}
b = gets.chomp.split("").map{|i| i.to_i}

S = []
T = []
s = 0
S[0] = a[0]
(1..n-1).each do |i|
  S[i] = S[i-1] + a[i]
end

max = 0
j = n-1
T[n] = 0
while j>= 0 do
    if b[j] == 0
     T[j] = T[j+1]
    else
        T[j] = T[j+1] + a[j]
    end
    j -= 1
end

max = T[0]

(1..n-1).each do |i|
    if b[i] == 1
        s = S[i-1] + T[i+1]
    end
    if s > max
        max = s
    end
end

puts max


Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant.Shop, where Noora is working, has a plan on the following n days. For each day sales manager knows exactly, that in i-th day ki products will be put up for sale and exactly li clients will come to the shop that day. Also, the manager is sure, that everyone, who comes to the shop, buys exactly one product or, if there aren't any left, leaves the shop without buying anything. Moreover, due to the short shelf-life of the products, manager established the following rule: if some part of the products left on the shelves at the end of the day, that products aren't kept on the next day and are sent to the dump.For advertising purposes manager offered to start a sell-out in the shop. He asked Noora to choose any f days from n next for sell-outs. On each of f chosen days the number of products were put up for sale would be doubled. Thus, if on i-th day shop planned to put up for sale ki products and Noora has chosen this day for sell-out, shelves of the shop would keep 2·ki products. Consequently, there is an opportunity to sell two times more products on days of sell-out.Noora's task is to choose f days to maximize total number of sold products. She asks you to help her with such a difficult problem.

The first line contains two integers n and f (1 ≤ n ≤ 105, 0 ≤ f ≤ n) denoting the number of days in shop's plan and the number of days that Noora has to choose for sell-out. Each line of the following n subsequent lines contains two integers ki, li (0 ≤ ki, li ≤ 109) denoting the number of products on the shelves of the shop on the i-th day and the number of clients that will come to the shop on i-th day.

Print a single integer denoting the maximal number of products that shop can sell.

NoteIn the first example we can choose days with numbers 2 and 4 for sell-out. In this case new numbers of products for sale would be equal to [2, 6, 2, 2] respectively. So on the first day shop will sell 1 product, on the second — 5, on the third — 2, on the fourth — 2. In total 1 + 5 + 2 + 2 = 10 product units.In the second example it is possible to sell 5 products, if you choose third day for sell-out.

# Try Codeforces
# author: Leonardone @ NEETSDKASU
############################################################
def gs() gets.strip 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){|m,e| m[e]+=1;m} end
############################################################

n, f = gis

ans = 0
kls = []
n.times do
    kl = gis
    k, l = kl
    mn = kl.min
    kls << [k * 2, l].min - mn
    ans += mn
end

xs = kls.sort.reverse
f.times do |i|
    ans += xs[i]
end

puts ans


Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made. Value of x is calculated as maximum of p·ai + q·aj + r·ak for given p, q, r and array a1, a2, ... an such that 1 ≤ i ≤ j ≤ k ≤ n. Help Snape find the value of x. Do note that the value of x may be negative.

First line of input contains 4 integers n, p, q, r ( - 109 ≤ p, q, r ≤ 109, 1 ≤ n ≤ 105). Next line of input contains n space separated integers a1, a2, ... an ( - 109 ≤ ai ≤ 109).

Output a single integer the maximum value of p·ai + q·aj + r·ak that can be obtained provided 1 ≤ i ≤ j ≤ k ≤ n.

NoteIn the first sample case, we can take i = j = k = 5, thus making the answer as 1·5 + 2·5 + 3·5 = 30.In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.

array = gets.split(" ")
n = array.shift
big_max = -999999999999999999999
shuzu = gets.split(" ")
sum=[]
sum[0] = -9999999999999999999999
for i in 0..n.to_i-1 do
    sum[i] = sum[i-1] if i>0
    temp = array[0].to_i*shuzu[i].to_i
    if temp > sum[i]
        sum[i] = temp;
    end
end

sum2 = []
sum2[0] = -9999999999999999999999
for i in 0..n.to_i-1 do
    sum2[i] = sum2[i-1] if i>0
    temp = sum[i]+array[1].to_i*shuzu[i].to_i
    if temp > sum2[i]
            sum2[i] = temp;
    end
end

#p sum
#p sum2
for i in 0..n.to_i-1
    max = sum2[i]+array[2].to_i*shuzu[i].to_i
    big_max=max if max>big_max
end
print big_max

n, p, q, r = gets.split.map{|x| x.to_i}
arr = gets.split.map{|x| x.to_i}

minus = arr.min
plus  = arr.max

p p * (p < 0 ? minus : plus) + q * (q < 0 ? minus : plus) + r * (r < 0 ? minus : plus)

n, p, q, r = gets.split.map{|x| x.to_i}
arr = gets.split.map{|x| x.to_i}

INF = 10**18

dp = [[-INF, -INF, -INF]]

n.times do |i|
	dp << [0, 0, 0]
	dp[i + 1][0] = [dp[i][0], p * arr[i]].max
	dp[i + 1][1] = [dp[i][1], dp[i + 1][0] + q * arr[i]].max
	dp[i + 1][2] = [dp[i][2], dp[i + 1][1] + r * arr[i]].max
end

ans = -INF
n.times{|i| ans = [ans, dp[i + 1][2]].max}

p ans

array = gets.split(" ")
n = array.shift
big_max = -9999999999999999999
shuzu = gets.split(" ")
sum=[]
sum[0] = -9999999999999999999
for i in 0..n.to_i-1 do
    sum[i] = sum[i-1] if i>0
    temp = array[0].to_i*shuzu[i].to_i
    if temp > sum[i]
        sum[i] = temp;
    end
end

sum2 = []
sum2[0] = -9999999999999999999
for i in 0..n.to_i-1 do
    sum2[i] = sum2[i-1] if i>0
    temp = sum[i]+array[1].to_i*shuzu[i].to_i
    if temp > sum2[i]
            sum2[i] = temp;
    end
end

p sum
p sum2
for i in 0..n.to_i-1
    max = sum2[i]+array[2].to_i*shuzu[i].to_i
    big_max=max if max>big_max
end
print big_max


In an ICPC contest, balloons are distributed as follows:   Whenever a team solves a problem, that team gets a balloon.  The first team to solve a problem gets an additional balloon.  A contest has 26 problems, labelled $$$\textsf{A}$$$, $$$\textsf{B}$$$, $$$\textsf{C}$$$, ..., $$$\textsf{Z}$$$. You are given the order of solved problems in the contest, denoted as a string $$$s$$$, where the $$$i$$$-th character indicates that the problem $$$s_i$$$ has been solved by some team. No team will solve the same problem twice.Determine the total number of balloons that the teams received. Note that some problems may be solved by none of the teams.

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of testcases. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 50$$$) — the length of the string. The second line of each test case contains a string $$$s$$$ of length $$$n$$$ consisting of uppercase English letters, denoting the order of solved problems.

For each test case, output a single integer — the total number of balloons that the teams received.

6

3

ABA

1

A

3

ORZ

5

BAAAA

4

BKPT

10

CODEFORCES

NoteIn the first test case, $$$5$$$ balloons are given out:   Problem $$$\textsf{A}$$$ is solved. That team receives $$$2$$$ balloons: one because they solved the problem, an an additional one because they are the first team to solve problem $$$\textsf{A}$$$.  Problem $$$\textsf{B}$$$ is solved. That team receives $$$2$$$ balloons: one because they solved the problem, an an additional one because they are the first team to solve problem $$$\textsf{B}$$$.  Problem $$$\textsf{A}$$$ is solved. That team receives only $$$1$$$ balloon, because they solved the problem. Note that they don't get an additional balloon because they are not the first team to solve problem $$$\textsf{A}$$$.  The total number of balloons given out is $$$2+2+1=5$$$.In the second test case, there is only one problem solved. The team who solved it receives $$$2$$$ balloons: one because they solved the problem, an an additional one because they are the first team to solve problem $$$\textsf{A}$$$.

#!/usr/bin/env ruby

numtests = gets.chomp.to_i

(1..numtests).each do |numline|
  ballons = 0
  solved = []
  n = gets.chomp.to_i
  l = gets.chomp
  (0..n-1).each do |i|
    c = l[i]
    if solved.include?(c)
      ballons += 1
    else
      ballons += 2
      solved << c
    end
  end
  puts ballons
end

require 'set'

t = gets.to_i

t.times do
  gets
  ln = gets.chomp
  s = Set.new
  b = 0
  ln.each_char do |c|
    b += 1 if not s.include? c
    s << c
    b += 1
  end
  puts b
end

def icpc_baloons(str, n)
  map = {}
  str.chars.each do |s|
    if map.key?(s)
      map[s] += 1
    else
      map[s] = 2
    end
  end
  ans = 0

  map.each do |k, v|
    ans += v
  end
  ans
end
t = gets.chomp.to_i
inputs = []
(0..t-1).each do
  n = gets.chomp.to_i
  str = gets.chomp
  inputs.push([str, n])
end

inputs.each do |input|
  puts icpc_baloons(input[0], input[1])
end


A big football championship will occur soon! $$$n$$$ teams will compete in it, and each pair of teams will play exactly one game against each other.There are two possible outcomes of a game:  the game may result in a tie, then both teams get $$$1$$$ point;  one team might win in a game, then the winning team gets $$$3$$$ points and the losing team gets $$$0$$$ points. The score of a team is the number of points it gained during all games that it played.You are interested in a hypothetical situation when all teams get the same score at the end of the championship. A simple example of that situation is when all games result in ties, but you want to minimize the number of ties as well.Your task is to describe a situation (choose the result of each game) so that all teams get the same score, and the number of ties is the minimum possible.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow. Each test case is described by one line containing one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of teams.

For each test case, print $$$\frac{n(n - 1)}{2}$$$ integers describing the results of the games in the following order: the first integer should correspond to the match between team $$$1$$$ and team $$$2$$$, the second — between team $$$1$$$ and team $$$3$$$, then $$$1$$$ and $$$4$$$, ..., $$$1$$$ and $$$n$$$, $$$2$$$ and $$$3$$$, $$$2$$$ and $$$4$$$, ..., $$$2$$$ and $$$n$$$, and so on, until the game between the team $$$n - 1$$$ and the team $$$n$$$. The integer corresponding to the game between the team $$$x$$$ and the team $$$y$$$ should be $$$1$$$ if $$$x$$$ wins, $$$-1$$$ if $$$y$$$ wins, or $$$0$$$ if the game results in a tie. All teams should get the same score, and the number of ties should be the minimum possible. If there are multiple optimal answers, print any of them. It can be shown that there always exists a way to make all teams have the same score.

NoteIn the first test case of the example, both teams get $$$1$$$ point since the game between them is a tie.In the second test case of the example, team $$$1$$$ defeats team $$$2$$$ (team $$$1$$$ gets $$$3$$$ points), team $$$1$$$ loses to team $$$3$$$ (team $$$3$$$ gets $$$3$$$ points), and team $$$2$$$ wins against team $$$3$$$ (team $$$2$$$ gets $$$3$$$ points).

gets.to_i.times do
  n=gets.to_i
  l=[]
  if n.odd?
    n-=1
    while n>0
      n.times do |i|
        if i.even?
          l << 1
        else
          l << -1
        end
      end
      n-=1
    end
    puts l.join(" ")
  else
    n-=1
    nn=n-1
    while n>0
      n.times do |i|
        if i<nn
          if i.even?
            l << 1
          else
            l << -1
          end
        elsif i==nn
          l << 0
        else
          if i.even?
            l << -1
          else
            l << 1
          end
        end
      end
      n-=1
      nn-=2
    end
    puts l.join(" ")
  end
end


It is the hard version of the problem. The only difference is that in this version $$$1 \le n \le 300$$$.In the cinema seats can be represented as the table with $$$n$$$ rows and $$$m$$$ columns. The rows are numbered with integers from $$$1$$$ to $$$n$$$. The seats in each row are numbered with consecutive integers from left to right: in the $$$k$$$-th row from $$$m (k - 1) + 1$$$ to $$$m k$$$ for all rows $$$1 \le k \le n$$$. $$$1$$$$$$2$$$$$$\cdots$$$$$$m - 1$$$$$$m$$$$$$m + 1$$$$$$m + 2$$$$$$\cdots$$$$$$2 m - 1$$$$$$2 m$$$$$$2m + 1$$$$$$2m + 2$$$$$$\cdots$$$$$$3 m - 1$$$$$$3 m$$$$$$\vdots$$$$$$\vdots$$$$$$\ddots$$$$$$\vdots$$$$$$\vdots$$$$$$m (n - 1) + 1$$$$$$m (n - 1) + 2$$$$$$\cdots$$$$$$n m - 1$$$$$$n m$$$ The table with seats indices There are $$$nm$$$ people who want to go to the cinema to watch a new film. They are numbered with integers from $$$1$$$ to $$$nm$$$. You should give exactly one seat to each person.It is known, that in this cinema as lower seat index you have as better you can see everything happening on the screen. $$$i$$$-th person has the level of sight $$$a_i$$$. Let's define $$$s_i$$$ as the seat index, that will be given to $$$i$$$-th person. You want to give better places for people with lower sight levels, so for any two people $$$i$$$, $$$j$$$ such that $$$a_i < a_j$$$ it should be satisfied that $$$s_i < s_j$$$.After you will give seats to all people they will start coming to their seats. In the order from $$$1$$$ to $$$nm$$$, each person will enter the hall and sit in their seat. To get to their place, the person will go to their seat's row and start moving from the first seat in this row to theirs from left to right. While moving some places will be free, some will be occupied with people already seated. The inconvenience of the person is equal to the number of occupied seats he or she will go through.Let's consider an example: $$$m = 5$$$, the person has the seat $$$4$$$ in the first row, the seats $$$1$$$, $$$3$$$, $$$5$$$ in the first row are already occupied, the seats $$$2$$$ and $$$4$$$ are free. The inconvenience of this person will be $$$2$$$, because he will go through occupied seats $$$1$$$ and $$$3$$$.Find the minimal total inconvenience (the sum of inconveniences of all people), that is possible to have by giving places for all people (all conditions should be satisfied).

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 300$$$) — the number of rows and places in each row respectively. The second line of each test case contains $$$n \cdot m$$$ integers $$$a_1, a_2, \ldots, a_{n \cdot m}$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the sight level of $$$i$$$-th person. It's guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print a single integer — the minimal total inconvenience that can be achieved.

NoteIn the first test case, there is a single way to give seats: the first person sits in the first place and the second person — in the second. The total inconvenience is $$$1$$$.In the second test case the optimal seating looks like this:   In the third test case the optimal seating looks like this:   The number in a cell is the person's index that sits on this place.

module AtCoder
  class FenwickTree
    def initialize(n = 0)
      @n = n
      @data = Array.new(n, 0).unshift(nil)
    end

    def add(idx, x)
      idx += 1
      while idx <= @n
        @data[idx] += x
        idx += idx & -idx
      end
      self
    end

    def sum(l, r)
      __sum__(r) - __sum__(l)
    end

    private

    def __sum__(r)
      s = 0
      while r > 0
        s += @data[r]
        r ^= r & -r
      end
      s
    end
  end
end

t = gets.to_i
t.times do

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

cnt = 0
h = a.tally
h1 = {}
h2 = {}
h.keys.sort.each { |k| h1[k] = cnt; h2[k] = (cnt += h[k]) }

score = 0
ft = Array.new(n) { AtCoder::FenwickTree.new(m) }
a.each do |ai|
  i1, j1 = h1[ai].divmod(m)
  i2, j2 = h2[ai].divmod(m)

  if i1 < i2
    score += ft[i1].sum(0, m)
    h1[ai] += 1
    next
  end

  i = i1
  j = j2 - 1
  x = ft[i]
  score += x.sum(0, j)
  x.add(j, 1)

  h1[ai] += 1
  h2[ai] -= 1
end

puts score

end


Little walrus Fangy loves math very much. That's why when he is bored he plays with a number performing some operations.Fangy takes some positive integer x and wants to get a number one from it. While x is not equal to 1, Fangy repeats the following action: if x is odd, then he adds 1 to it, otherwise he divides x by 2. Fangy knows that for any positive integer number the process ends in finite time.How many actions should Fangy perform to get a number one from number x?

The first line contains a positive integer x in a binary system. It is guaranteed that the first digit of x is different from a zero and the number of its digits does not exceed 106.

NoteLet's consider the third sample. Number 101110 is even, which means that we should divide it by 2. After the dividing Fangy gets an odd number 10111 and adds one to it. Number 11000 can be divided by 2 three times in a row and get number 11. All that's left is to increase the number by one (we get 100), and then divide it by 2 two times in a row. As a result, we get 1.

n=gets.split[0]
n=n.bytes.to_a
k=0
l=n.length
ans=0
(l-1).downto(0){|i|
    if i==0 && k==0 then
        ans+=1
    else
        if n[i]+k==49 then
            ans+=1
            k=1
        elsif n[i]+k==50 then
            k=1
        else
            k=0
        end
        ans+=1
    end
}
ans+=k
puts ans-1

n=gets.split[0]
n=n.bytes.to_a
k=0
l=n.length
ans=0
(l-1).downto(0){|i|
    if i==0 && k==0 then
        ans+=1;k=1
    else
        if n[i]+k==49 then
            ans+=1
            k=1
        elsif n[i]+k==50 then
            k=1
        else
            k=0
        end
        ans+=1
    end
}
ans+=k
puts ans-1

#=================================
require 'prime'
require 'set'
require 'matrix'
require 'tsort'
include Math

if ARGV.include?("ONLINE_JUDGE")
	$stdin = File.open("./input.txt", "r")
	ARGV.delete("ONLINE_JUDGE")
end
#=================================

b=gets.strip

if b.length==1 && b=="1"
	puts 0
	exit
end

ans=count=0

loop do
	if b[-1]=="1"
		count+=1
		i=b.length-1

		while b[i]=="1"
			b[i]="0"
			i-=1
			count+=1
		end

		b[i]="1" if i>=0
		b=b[0..i]
	else
		i=b.length-1

		while b[i]=="0"
			count+=1
			i-=1
		end

		b=b[0..i]
	end

	ans=count if b.length!=0
	break if b.length==0
end

puts ans


And again a misfortune fell on Poor Student. He is being late for an exam.Having rushed to a bus stop that is in point (0, 0), he got on a minibus and they drove along a straight line, parallel to axis OX, in the direction of increasing x.Poor Student knows the following:   during one run the minibus makes n stops, the i-th stop is in point (xi, 0)  coordinates of all the stops are different  the minibus drives at a constant speed, equal to vb  it can be assumed the passengers get on and off the minibus at a bus stop momentarily  Student can get off the minibus only at a bus stop  Student will have to get off the minibus at a terminal stop, if he does not get off earlier  the University, where the exam will be held, is in point (xu, yu)  Student can run from a bus stop to the University at a constant speed vs as long as needed  a distance between two points can be calculated according to the following formula:   Student is already on the minibus, so, he cannot get off at the first bus stop Poor Student wants to get to the University as soon as possible. Help him to choose the bus stop, where he should get off. If such bus stops are multiple, choose the bus stop closest to the University.

The first line contains three integer numbers: 2 ≤ n ≤ 100, 1 ≤ vb, vs ≤ 1000. The second line contains n non-negative integers in ascending order: coordinates xi of the bus stop with index i. It is guaranteed that x1 equals to zero, and xn ≤ 105. The third line contains the coordinates of the University, integers xu and yu, not exceeding 105 in absolute value.

In the only line output the answer to the problem — index of the optimum bus stop.

NoteAs you know, students are a special sort of people, and minibuses usually do not hurry. That's why you should not be surprised, if Student's speed is higher than the speed of the minibus.

n,vb,vs = gets.chomp.split(/ /).map!{|x| x.to_i}
ar = gets.chomp.split(/ /).map!{|x| x.to_i}
xu,yu = gets.chomp.split(/ /).map!{|x| x.to_i}

mint = 0
mind = 0
idx = 0
for i in 1..n-1
	wk = (ar[i]-xu).abs
	wkt = ar[i].to_f/vb+Math.sqrt(wk*wk + yu*yu)/vs
	if idx == 0 || mint > wkt
		mint = wkt
		mind = wk
		idx = i+1
	elsif mint == wkt
		if mind > wk
			mint = wkt
			mind = wk
			idx = i+1
		end
	end
end
puts idx

n, vb, vs = gets.split.map{|i| i.to_f}
x = gets.split.map{|i| i.to_i}
xu, yu = gets.split.map{|i| i.to_i}
ans = [1e100, -1, -1]
1.upto(x.length - 1) do |i|
	d = (xu - x[i]) ** 2 + yu ** 2
	t = x[i] / vb + Math.sqrt(d) / vs
	ans = [t, d, i] if t < ans[0] - 1e-6 || (t < ans[0] + 1e-6 && d < ans[1])
end
p ans[2] + 1

#

n,vb,vs=STDIN.gets.chomp.split
xn=STDIN.gets.chomp.split
xu,yu=STDIN.gets.chomp.split
n=n.to_i
vb=vb.to_i
vs=vs.to_i
xu=xu.to_i
yu=yu.to_i
for i in 0...xn.length do xn[i]=xn[i].to_i end
idx=0
min_t=-1
min_u=-1
for i in 1...xn.length
  d=Math::sqrt((xu-xn[i])*(xu-xn[i])+yu*yu)
  t=1.0*(xn[i]-xn[1])/vb
  t+=1.0*d/vs
  if min_t==-1
    min_t=t
    min_u=d
    idx=i
  elsif t<min_t
    min_t=t
    min_u=d
    idx=i
  elsif t==min_t && d<min_u
    min_u=d
    idx=i
  end
end
puts(idx+1)

n, Vb, Vs = gets.split.collect { |x| x.to_i }
i = gets.split.collect { |x| x.to_i }
Xu, Yu = gets.split.collect { |x| x.to_i }

min_time = -1
min_dist = -1
best_stop = -1

1.upto(i.size - 1) do |x|
	dist = Math.sqrt((Xu - i[x])**2 + Yu**2)
	time = i[x] * 1.0 / Vb + dist * 1.0 / Vs

	if min_time == -1 or time < min_time
		min_time = time
		min_dist = dist
		best_stop = x + 1
	elsif time == min_time and dist < min_dist
		min_dist = dist
		best_stop = x + 1
	end
end

puts best_stop

# -*- coding: utf-8 -*-
def dist (x0, y0, x1, y1)
  dx = (x1 - x0).to_f
  dy = (y1 - y0).to_f
  return Math.sqrt(dx * dx + dy * dy)
end

n,vb,vs = gets.split.map(&:to_i)
bus = gets.split.map(&:to_i)
xu,yu = gets.split.map(&:to_i)

time = Array.new

for i in 2..n do
  x = bus[i-1]
  time[i] = x.to_f / vb.to_f + dist(x, 0, xu, yu) / vs;
end

min_time = time[2..n].min;

for i in 2..n do
  if min_time == time[i] then
    ans = i
  end
end

print ans
puts

include Math
fst=gets.split
n=fst[0].to_i
vb=fst[1].to_f
vs=fst[2].to_f
bus_stops=gets.split.map{ |x| x.to_f}
univ = gets.split.map{ |x| x.to_f}
t = nil
res = nil
bu = nil
(n-1).times do |i|
  bx = bus_stops[i+1]
  l = sqrt((univ[0]-bx)**2 + (univ[1])**2)
  temp_t = (bx/vb)+(l/vs)
  if t==nil || t>temp_t
    t=temp_t
    bu = l
    res = i+2
  elsif t==temp_t
    if bu>l
      t=temp_t
      bu = l
      res = i+2
    end
  end
end
puts res

def dist(x1,y1,x2,y2)
	Math.sqrt(((x2-x1)**2) + ((y2-y1)**2))
end

n,v_b,v_s = gets.split(" ").map(&:to_i)
arr = gets.split(" ").map(&:to_i)
univ_x,univ_y = gets.split(" ").map(&:to_i)

ans = {}

arr[1..-1].each_with_index do |a,i|
	bus_time = a/v_b.to_f
	# puts "h33 #{bus_time}"
	walk_time = (dist(univ_x,univ_y,a,0))/v_s
	# puts "#{[bus_time + walk_time,walk_time]}"
	ans[[bus_time + walk_time,walk_time]] = i

end
# puts "#{ans}"

key = ans.keys.min

puts "#{ans[key]+2}"

#$stdin = File.open('in.txt', 'r')
@n,@vb,@vs = gets.split(/\s+/).map {|x| x.to_i}
@stopes = gets.split(/\s+/).map {|x| x.to_i}
@xu,@yu = gets.split(/\s+/).map {|x| x.to_i}

@stopes.unshift(0)
# a = 2
# b = @n
#
def compute(index)
  @stopes[index]/@vb.to_f + Math.sqrt(@yu*@yu+(@stopes[index]-@xu)*(@stopes[index]-@xu))/@vs
end

if @vs > @vb
  puts 2
else
  kms = @stopes[2].abs
  x = @stopes[2]
  answer = 2
  min = kms/@vb.to_f + Math.sqrt(@yu*@yu+(x-@xu)*(x-@xu))/@vs

  i = 3
#  puts "#{answer} #{min} #{compute(2)}"

  while i <= @n
    kms += (@stopes[i-1].abs-@stopes[i].abs).abs
    x = @stopes[i]
    val = kms/@vb.to_f + Math.sqrt(@yu*@yu+(x-@xu)*(x-@xu))/@vs

    if val < min
      answer = i
      min = val
    elsif (val == min) && ((@stopes[answer]-@xu).abs > (@stopes[i]-@xu).abs)
      answer = i
    end
    i += 1
  end
  puts answer
end
# av = compute(a)
# bv = compute(b)
#
# while b > a
#   # puts "a #{a} #{av}"
#   # puts "b #{b} #{bv}"
#   if bv > av
#     b = ((b+a) / 2)
#     bv = compute(b)
#   else
#     a = ((b+a) / 2) + 1
#     av = compute(a)
#   end
# end
# #puts "#{a} #{b}"
# # if (b-a) == 1
# #   mv = compute(a+1)
# #   if mv < av
# #     a += 1
# #     av = mv
# #   end
# # end
# #puts "#{av} #{bv}"
# if av > bv
#   puts b
# else #if bv > av
#   puts a
# # else
# #   av = (@stopes[a]-@xu).abs
# #   bv = (@stopes[b]-@xu).abs
# #   puts bv > av ? a : b
# end
#

n, vb, vs = gets.split(/\s+/).map{|x| x.to_i}
x = gets.split(/\s+/).map{|x| x.to_i}
xu, yu = gets.split(/\s+/).map{|x| x.to_i}

res = 0
rest = 0.0
resd = 0.0
(1...n).each {|i|
  dx = (x[i] - xu).to_f
  dy = (0 - yu).to_f
  d = Math.sqrt(dx * dx + dy * dy)
  t = x[i].to_f / vb + d / vs
  if res == 0 || t < rest || (t == rest && d < resd) then
    res = i
    rest = t
    resd = d
  end
}
p res + 1

#� ������ ������ ���� ��� ����� �����: 2???n? ??100, 1???vb,?vs? ??1000. �� ������ ������ ���� n  ��������������� ����� ����� � ������� �����������
#: ���������� xi ��������� ����� i. �������������, ��� x1  ����� ����, � xn? ??105.
#� ������� ������ ���� ���������� ������������, ����� ����� xu � yu, �� ������ �� ����������� 105.

n, vb, vs = gets.split(' ').map{|z|z.to_i}
crd = gets.split(' ').map{|z|z.to_i}
xu,yu = gets.split(' ').map{|z|z.to_i}

min = 105000000
ru = 105000000
res=0
crd[1..-1].each_with_index{|xi,i|
  mru = (xu-xi)*(xu-xi)+yu*yu
  d = (Math.sqrt(xi*xi)*vs+Math.sqrt(mru)*vb)
  if (d < min)||((d==min)&&(mru < ru)) then
    min = d
    res = i+1
    ru = mru
  end
}

puts res+1

n,vb,vs = gets.chomp.split(/ /).map!{|x| x.to_i}
ar = gets.chomp.split(/ /).map!{|x| x.to_i}
xu,yu = gets.chomp.split(/ /).map!{|x| x.to_i}

mind = 0
idx = 0
for i in 0..n-1
	wk = (ar[i]-xu).abs
	if idx == 0 || mind > wk
		mind = wk
		idx = i+1
	end
end
puts idx

n,vb,vs = gets.chomp.split(/ /).map!{|x| x.to_i}
ar = gets.chomp.split(/ /).map!{|x| x.to_i}
xu,yu = gets.chomp.split(/ /).map!{|x| x.to_i}

mint = 0
idx = 0
for i in 1..n-1
	wk = (ar[i]-xu).abs
	wkt = ar[i]/vb+Math.sqrt(wk*wk + yu*yu)/vs
	if idx == 0 || mint >= wkt
		mint = wkt
		mind = wk
		idx = i+1
	end
end
puts idx

n,vb,vs = gets.chomp.split(/ /).map!{|x| x.to_i}
ar = gets.chomp.split(/ /).map!{|x| x.to_i}
xu,yu = gets.chomp.split(/ /).map!{|x| x.to_i}

mint = 0
idx = 0
for i in 1..n-1
	wk = (ar[i]-xu).abs
	wkt = ar[i]/vb+Math.sqrt(wk*wk + yu*yu)/vs
	if idx == 0 || mint + 1e-6 > wkt
		mint = wkt
		mind = wk
		idx = i+1
	elsif (mint - wkt).abs < 1e-6
		if mind > wk
			mint = wkt
			mind = wk
			idx = i+1
		end
	end
end
puts idx

n,vb,vs = gets.chomp.split(/ /).map!{|x| x.to_i}
ar = gets.chomp.split(/ /).map!{|x| x.to_i}
xu,yu = gets.chomp.split(/ /).map!{|x| x.to_i}

mint = 0
mind = 0
idx = 0
for i in 1..n-1
	wk = (ar[i]-xu).abs
	wkt = ar[i]/vb+Math.sqrt(wk*wk + yu*yu)/vs
	if idx == 0 || mint > wkt
		mint = wkt
		mind = wk
		idx = i+1
	elsif mint == wkt
		if mind > wk
			mint = wkt
			mind = wk
			idx = i+1
		end
	end
end
puts idx

n,vb,vs = gets.chomp.split(/ /).map!{|x| x.to_i}
ar = gets.chomp.split(/ /).map!{|x| x.to_i}
xu,yu = gets.chomp.split(/ /).map!{|x| x.to_i}

mint = 0
idx = 0
for i in 1..n-1
	wk = (ar[i]-xu).abs
	wkt = ar[i]/vb+Math.sqrt(wk*wk + yu*yu)/vs
	if idx == 0 || mint > wkt
		mint = wkt
		mind = wk
		idx = i+1
	elsif mint == wkt
		if mind > wk
			mint = wkt
			mind = wk
			idx = i+1
		end
	end
end
puts idx

n,vb,vs = gets.chomp.split(/ /).map!{|x| x.to_i}
ar = gets.chomp.split(/ /).map!{|x| x.to_i}
xu,yu = gets.chomp.split(/ /).map!{|x| x.to_i}

mint = 0
mind = 0
idx = 0
for i in 1..n-1
	wk = (ar[i]-xu).abs
	wkt = ar[i]/vb+Math.sqrt(wk*wk + yu*yu)/vs
	if idx == 0 || mint > wkt
		mint = wkt
		mind = wk
		idx = i+1
	end
end
puts idx

n,vb,vs = gets.chomp.split(/ /).map!{|x| x.to_i}
ar = gets.chomp.split(/ /).map!{|x| x.to_i}
xu,yu = gets.chomp.split(/ /).map!{|x| x.to_i}

mint = 0
idx = 0
for i in 1..n-1
	wk = (ar[i]-xu).abs
	wkt = ar[i]/vb+Math.sqrt(wk*wk + yu*yu)/vs
	if idx == 0 || mint > wkt
		mint = wkt
		mind = wk
		idx = i+1
	elsif (mint - wkt).abs < 1e-6
		if mind > wk
			mint = wkt
			mind = wk
			idx = i+1
		end
	end
end
puts idx

n, vb, vs = gets.split.map{|i| i.to_f}
x = gets.split.map{|i| i.to_i}
xu, yu = gets.split.map{|i| i.to_i}
ans = [1e100, -1, -1]
1.upto(x.length - 1) do |i|
	d = (xu - x[i]) ** 2 + yu ** 2
	t = x[i] / vb + Math.sqrt(d) / vs
	ans = [d, t, i] if t < ans[0] - 1e-8 || (t < ans[0] + 1e-8 && d < ans[1])
end
p ans[2] + 1

n, vb, vs = gets.split.map{|i| i.to_i}
x = gets.split.map{|i| i.to_i}
xu, yu = gets.split.map{|i| i.to_i}
best = 1e100
ans = -1
x.each_index do |i|
	temp = x[i] / vb + Math.sqrt(yu * yu + (xu - x[i]) * (xu - x[i])) / vs
	ans, best = i, temp if temp < best
end
p ans

n, vb, vs = gets.split.map{|i| i.to_f}
x = gets.split.map{|i| i.to_i}
xu, yu = gets.split.map{|i| i.to_i}
x = 1.upto(x.length - 1).map do |i|
	d = (xu - x[i]) ** 2 + yu ** 2
	t = x[i] / vb + Math.sqrt(d) / vs
	[t, -d, i + 1]
end
p x.min[2]

n, vb, vs = gets.split.map{|i| i.to_i}
x = gets.split.map{|i| i.to_i}
xu, yu = gets.split.map{|i| i.to_i}
best = 1e100
ans = -1
1.upto(x.length - 1) do |i|
	temp = x[i] / vb + Math.sqrt((xu - x[i]) * (xu - x[i]) + yu * yu) / vs
	ans, best = i, temp if temp <= best + 1e-8
end
print ans + 1, "\n"

n, vb, vs = gets.split.map{|i| i.to_i}
x = gets.split.map{|i| i.to_i}
xu, yu = gets.split.map{|i| i.to_i}
best = 1e100
ans = -1
x.each_index do |i|
	temp = x[i] / vb + Math.sqrt(yu * yu + (xu - x[i]) * (xu - x[i])) / vs
	ans, best = i, temp if temp < best
end
print ans + 1, "\n"

n,vb,vs=STDIN.gets.chomp.split
xn=STDIN.gets.chomp.split
xu,yu=STDIN.gets.chomp.split
n=n.to_i
vb=vb.to_i
vs=vs.to_i
xu=xu.to_i
yu=yu.to_i
for i in 0...xn.length do xn[i]=xn[i].to_i end
xn<<xn[xn.length-1]
idx=0
min=-1
ts=0
for i in 1...xn.length-1
  d=Math::sqrt((xu-xn[i])*(xu-xn[i])+yu*yu)
  t=d/vs+ts
  if min==-1
    min=t
    idx=i
  elsif t<min
    min=t
    idx=i
  end
  t+=(xn[i+1]-xn[i])/vb
end
puts(idx+1)

n,vb,vs=STDIN.gets.chomp.split
xn=STDIN.gets.chomp.split
xu,yu=STDIN.gets.chomp.split
n=n.to_i
vb=vb.to_i
vs=vs.to_i
xu=xu.to_i
yu=yu.to_i
for i in 0...xn.length do xn[i]=xn[i].to_i end
idx=0
min=-1
for i in 1...xn.length
  d=Math::sqrt((xu-xn[i])*(xu-xn[i])+yu*yu)
  t=1.0*(xn[i]-xn[1])/vb
  t=d/vs+t
  if min==-1
    min=t
    idx=i
  elsif t<min
    min=t
    idx=i
  end
end
puts(idx+1)

# -*- coding: utf-8 -*-
def dist (x0, y0, x1, y1)
  dx = (x1 - x0).to_f
  dy = (y1 - y0).to_f
  return Math.sqrt(dx * dx + dy * dy)
end

n,vb,vs = gets.split.map(&:to_i)
bus = gets.split.map(&:to_i)
xu,yu = gets.split.map(&:to_i)

time = Array.new

for i in 2..n do
  x = bus[i-1]
  time[i] = x.to_f / vb.to_f + dist(x, 0, xu, yu) / vs;
end

min_time = time[2..n].min;

for i in 2..n do
  if min_time == time[i] then
    print i
    puts
    break
  end
end

include Math
fst=gets.split
n=fst[0].to_i
vb=fst[1].to_f
vs=fst[2].to_f
bus_stops=gets.split.map{ |x| x.to_f}
univ = gets.split.map{ |x| x.to_f}
t = nil
res = nil
(n-1).times do |i|
  bx = bus_stops[i+1]
  l = sqrt((univ[0]-bx)**2 + (univ[1])**2)
  temp_t = (bx/vb)+(l/vs)
  if t==nil || t>temp_t
    t=temp_t
    res = i+2
  end
end
puts res

n,vb,vs=gets.split.map &:to_i
z=[1e9,1e9,0];
a=gets.split.map &:to_i
x,y=gets.split.map &:to_i
n.times{|i|d=((x-a[i])**2+y**2)**0.5;z=[[d/vs+x[i]/vb,d,i],z].min}
print z[2]+1

def dist(x1,y1,x2,y2)
	Math.sqrt(((x2-x1)**2) + ((y2-y1)**2))
end

n,v_b,v_s = gets.split(" ").map(&:to_i)
arr = gets.split(" ").map(&:to_i)
univ_x,univ_y = gets.split(" ").map(&:to_i)

ans = {}

arr[1..-1].each_with_index do |a,i|
	bus_time = a/v_b
	walk_time = (dist(univ_x,univ_y,a,0))/v_s
	ans[[bus_time + walk_time,walk_time]] = i
end
# puts "#{ans}"

key = ans.keys.min

puts "#{ans[key]+2}"

#$stdin = File.open('in.txt', 'r')
@n,@vb,@vs = gets.split(/\s+/).map {|x| x.to_i}
@stopes = gets.split(/\s+/).map {|x| x.to_i}
@xu,@yu = gets.split(/\s+/).map {|x| x.to_i}

@stopes.unshift(0)
a = 2
b = @n

def compute(index)
  @stopes[index]/@vb.to_f + Math.sqrt(@yu*@yu+(@stopes[index]-@xu)*(@stopes[index]-@xu))/@vs
end

av = compute(a)
bv = compute(b)

while b > a
  if av > bv
    a = ((b+a) / 2) + 1
    av = compute(a)
  else
    b = ((b+a) / 2)
    bv = compute(b)
  end
end
# if (b-a) == 1
#   mv = compute(a+1)
#   if mv < av
#     a += 1
#     av = mv
#   end
# end
#puts "#{av} #{bv}"
if av > bv
  puts b
else bv > av
  puts a
# else
#   puts a
  # av = (@stopes[a]-@xu).abs
  # bv = (@stopes[b]-@xu).abs
  # puts av > bv ? b : a
end

@n,@vb,@vs = gets.split(/\s+/).map {|x| x.to_i}
@stopes = gets.split(/\s+/).map {|x| x.to_i}
@xu,@yu = gets.split(/\s+/).map {|x| x.to_i}

@stopes.unshift(0)
a = 1
b = @n

def compute(index)
  @stopes[index]/@vb.to_f + Math.sqrt(@yu*@yu+(@stopes[index]-@xu)*(@stopes[index]-@xu))/@vs
end

av = compute(a)
bv = compute(b)

while (b-a) > 1
  if av > bv
    a = ((b+a) / 2)
  else
    b = ((b+a) / 2)+1
  end

  av = compute(a)
  bv = compute(b)
end
#puts "#{av} #{bv}"
if av > bv
  puts b
elsif bv > av
  puts a
else
  av = (@stopes[a]-@xu).abs
  bv = (@stopes[b]-@xu).abs
  puts av > bv ? b : a
end

#$stdin = File.open('in.txt', 'r')
@n,@vb,@vs = gets.split(/\s+/).map {|x| x.to_i}
@stopes = gets.split(/\s+/).map {|x| x.to_i}
@xu,@yu = gets.split(/\s+/).map {|x| x.to_i}

@stopes.unshift(0)
a = 2
b = @n

def compute(index)
  @stopes[index]/@vb.to_f + Math.sqrt(@yu*@yu+(@stopes[index]-@xu)*(@stopes[index]-@xu))/@vs
end

av = compute(a)
bv = compute(b)

while (b-a) > 1
  if av > bv
    a = ((b+a) / 2)
  else
    b = ((b+a) / 2)
  end

  av = compute(a)
  bv = compute(b)
end
if (b-a) == 1
  mv = compute(a+1)
  if mv < av
    a += 1
    av = mv
  end
end
#puts "#{av} #{bv}"
if av > bv
  puts b
else bv > av
  puts a
# else
#   puts a
  # av = (@stopes[a]-@xu).abs
  # bv = (@stopes[b]-@xu).abs
  # puts av > bv ? b : a
end

@n,@vb,@vs = gets.split(/\s+/).map {|x| x.to_i}
@stopes = gets.split(/\s+/).map {|x| x.to_i}
@xu,@yu = gets.split(/\s+/).map {|x| x.to_i}

@stopes.unshift(0)
a = 2
b = @n

def compute(index)
  @stopes[index]/@vb.to_f + Math.sqrt(@yu*@yu+(@stopes[index]-@xu)*(@stopes[index]-@xu))/@vs
end

av = compute(a)
bv = compute(b)

while (b-a) > 1
  if av > bv
    a = ((b+a) / 2)
  else
    b = ((b+a) / 2)
  end

  av = compute(a)
  bv = compute(b)
end
#puts "#{av} #{bv}"
if av > bv
  puts b
elsif bv > av
  puts a
else
  av = (@stopes[a]-@xu).abs
  bv = (@stopes[b]-@xu).abs
  puts av > bv ? b : a
end

#$stdin = File.open('in.txt', 'r')
@n,@vb,@vs = gets.split(/\s+/).map {|x| x.to_i}
@stopes = gets.split(/\s+/).map {|x| x.to_i}
@xu,@yu = gets.split(/\s+/).map {|x| x.to_i}

@stopes.unshift(0)
a = 2
b = @n

def compute(index)
  @stopes[index]/@vb.to_f + Math.sqrt(@yu*@yu+(@stopes[index]-@xu)*(@stopes[index]-@xu))/@vs
end

av = compute(a)
bv = compute(b)

while (b-a) > 1
  if av > bv
    a = ((b+a) / 2)
  else
    b = ((b+a) / 2)
  end

  av = compute(a)
  bv = compute(b)
end
if (b-a) == 1
  mv = compute(a+1)
  if mv < av
    a += 1
    av = mv
  end
end
#puts "#{av} #{bv}"
if av > bv
  puts b
elsif bv > av
  puts a
else
  av = (@stopes[a]-@xu).abs
  bv = (@stopes[b]-@xu).abs
  puts av > bv ? b : a
end

#$stdin = File.open('in.txt', 'r')
@n,@vb,@vs = gets.split(/\s+/).map {|x| x.to_i}
@stopes = gets.split(/\s+/).map {|x| x.to_i}
@xu,@yu = gets.split(/\s+/).map {|x| x.to_i}

@stopes.unshift(0)
a = 2
b = @n

def compute(index)
  @stopes[index]/@vb.to_f + Math.sqrt(@yu*@yu+(@stopes[index]-@xu)*(@stopes[index]-@xu))/@vs
end

av = compute(a)
bv = compute(b)

while b > a
  # puts "a #{a} #{av}"
  # puts "b #{b} #{bv}"
  if bv > av
    b = ((b+a) / 2)
    bv = compute(b)
  else
    a = ((b+a) / 2) + 1
    av = compute(a)
  end
end
#puts "#{a} #{b}"
# if (b-a) == 1
#   mv = compute(a+1)
#   if mv < av
#     a += 1
#     av = mv
#   end
# end
#puts "#{av} #{bv}"
if av > bv
  puts b
else #if bv > av
  puts a
# else
#   av = (@stopes[a]-@xu).abs
#   bv = (@stopes[b]-@xu).abs
#   puts bv > av ? a : b
end

#� ������ ������ ���� ��� ����� �����: 2???n? ??100, 1???vb,?vs? ??1000. �� ������ ������ ���� n  ��������������� ����� ����� � ������� �����������
#: ���������� xi ��������� ����� i. �������������, ��� x1  ����� ����, � xn? ??105.
#� ������� ������ ���� ���������� ������������, ����� ����� xu � yu, �� ������ �� ����������� 105.

n, vb, vs = gets.split(' ').map{|z|z.to_i}
crd = gets.split(' ').map{|z|z.to_i}
xu,yu = gets.split(' ').map{|z|z.to_i}

min = 105000000
res= 0
crd[1..-1].each_with_index{|xi,i|
  d = Math.sqrt(xi*xi)*vs+Math.sqrt((xu-xi)*(xu-xi)+yu*yu)*vb
  if d < min then
    min = d
    res = i+1
  end
}

puts res+1


Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up $$$q$$$ questions about this song. Each question is about a subsegment of the song starting from the $$$l$$$-th letter to the $$$r$$$-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment $$$k$$$ times, where $$$k$$$ is the index of the corresponding letter in the alphabet. For example, if the question is about the substring "abbcb", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c" three times, so that the resulting string is "abbbbcccbb", its length is $$$10$$$. Vasya is interested about the length of the resulting string.Help Petya find the length of each string obtained by Vasya.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1\leq n\leq 100\,000$$$, $$$1\leq q \leq 100\,000$$$) — the length of the song and the number of questions.  The second line contains one string $$$s$$$ — the song, consisting of $$$n$$$ lowercase letters of English letters. Vasya's questions are contained in the next $$$q$$$ lines. Each line contains two integers $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq n$$$) — the bounds of the question.

Print $$$q$$$ lines: for each question print the length of the string obtained by Vasya.

NoteIn the first example Vasya is interested in three questions. In the first question Vasya considers the substring "aba", that transforms to "abba", so the answer is equal to $$$4$$$. In the second question Vasya considers "baca", that transforms to "bbaccca", so the answer is $$$7$$$. In the third question Vasya considers the string "abacaba",that transforms to "abbacccabba" of length $$$11$$$.

inputs = STDIN.read.strip.split("\n")
inputs.shift

class NumArray
  def initialize(nums)
    @x = nums.clone
    @x.unshift(0)
    (1...@x.size).each do |i|
      @x[i] += @x[i-1]
    end
  end

  def sum_range(left, right)
    @x[right+1] - @x[left]
  end
end

nums = []
inputs.shift.bytes.each do |b|
  nums << b - 96
end

nums.unshift(0)
nums = NumArray.new(nums)

inputs.each do |inp|
  from, to = inp.split(' ').map(&:to_i)

  puts nums.sum_range(from, to)
end

n,q=gets.split.map(&:to_i)
s=gets.chomp.chars.map{|x|x.ord-96}
t=[0]
s.each do |ss|
  t << t[-1]+ss
end
q.times do
  l,r=gets.split.map(&:to_i)
  puts t[r]-t[l-1]
end


You have k pieces of laundry, each of which you want to wash, dry and fold. You are at a laundromat that has n1 washing machines, n2 drying machines and n3 folding machines. Each machine can process only one piece of laundry at a time. You can't dry a piece of laundry before it is washed, and you can't fold it before it is dried. Moreover, after a piece of laundry is washed, it needs to be immediately moved into a drying machine, and after it is dried, it needs to be immediately moved into a folding machine.It takes t1 minutes to wash one piece of laundry in a washing machine, t2 minutes to dry it in a drying machine, and t3 minutes to fold it in a folding machine. Find the smallest number of minutes that is enough to wash, dry and fold all the laundry you have.

The only line of the input contains seven integers: k, n1, n2, n3, t1, t2, t3 (1 ≤ k ≤ 104; 1 ≤ n1, n2, n3, t1, t2, t3 ≤ 1000).

Print one integer — smallest number of minutes to do all your laundry.

NoteIn the first example there's one instance of each machine, each taking 5 minutes to complete. You have only one piece of laundry, so it takes 15 minutes to process it.In the second example you start washing first two pieces at moment 0. If you start the third piece of laundry immediately, then by the time it is dried, there will be no folding machine available, so you have to wait, and start washing third piece at moment 2. Similarly, you can't start washing next piece until moment 5, since otherwise there will be no dryer available, when it is washed. Start time for each of the eight pieces of laundry is 0, 0, 2, 5, 10, 10, 12 and 15 minutes respectively. The last piece of laundry will be ready after 15 + 10 + 5 + 2 = 32 minutes.

$n = Array.new(3)
$t = Array.new(3)
k, $n[0], $n[1], $n[2], $t[0], $t[1], $t[2] = gets.split.map &:to_i

$now = Array.new(k) { 0 }

1.upto(2) do |i|
  $t[i] += $t[i - 1]
end

def make (q, p)
  x = q + 1 - $n[p]
  time = 0
  if x >= 0
    time = $now[x]
    time += $t[p]
  elsif p > 0
    time += $t[p - 1]
  end
  time
end

$now[0] = 0

0.upto(k - 2) do |i|
  ans = []
  ans << make(i, 2) - $t[1] << make(i, 1) - $t[0] << make(i, 0)
  st = ans.max
  $now[i + 1] = st
end
puts ($now[k - 1] + $t[2])

n=Array.new(3)
t=Array.new(3)
k,n[0],n[1],n[2],t[0],t[1],t[2]=gets.split.map(&:to_i)

starts=Array.new(k){0}

def when_free (k, n, t, starts, nnum)
	num=n[nnum]
	x=k+1-num

	time=0
	if(x>=0)
		time=starts[x]

		if (nnum==2)
			time+=(t[0]+t[1]+t[2])
		end

		if (nnum==1)
			time+=(t[0]+t[1])
		end

		if(nnum==0)
			time+=t[0]
		end
	else
		if (nnum==2)
			time+=(t[0]+t[1])
		end

		if (nnum==1)
			time+=(t[0])
		end
	end
	time
end

starts[0]=0
for i in 1...k do
	t2free=when_free(i-1,n,t,starts,2)
	t1free=when_free(i-1,n,t,starts,1)
	t0free=when_free(i-1,n,t,starts,0)

	start=t2free-t[1]-t[0]
	if (t1free>start+t[0])
		start=t1free-t[0]
	end

	if (t0free>start)
		start=t0free
	end
	starts[i]=start
end

puts (starts[k-1]+t[0]+t[1]+t[2])


A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not.A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a0, a1, ..., an - 1 if and only if ai = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points.You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation.

The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n integers a0, a1, ..., an - 1 — the given permutation.

Print a single integer — the maximum possible number of fixed points in the permutation after at most one swap operation.

n = gets.to_i
array = gets.chop!.split(' ').map(&:to_i)
fixed_points, remain_points = [], []
array.each_with_index do |e, i|
  fixed_points.push e if e == i
  remain_points.push [e, i] if e != i
end
result = fixed_points.size
remain_points.each do |point|
  if array[point[0]] == point[1]
    result += 2
    break
  end
end
result += 1 if result == fixed_points.size && remain_points.size != 0
puts result

n = gets.to_i
array = gets.chop!.split(' ').map(&:to_i)
fixed_points, remain_points, plus = [], [], 0
array.each_with_index do |e, i|
  if e == i
    fixed_points.push e
  else
    plus = 2 if array[e] == i
    plus = 1 if plus == 0
  end
end
puts fixed_points.size + plus

n = gets.to_i
array = gets.chop!.split(' ').map(&:to_i)
fixed_points = array.select.with_index { |e, i| e == i}
plus = array.select.with_index { |e, i| e != i && array[e] == i }.empty? ? 1 : 2
plus -= 1 if fixed_points.size == array.size
puts fixed_points.size + plus

n = Integer(gets)
input = gets.chomp
nums = input.split
a = Array.new
for i in 0...n
	a[i] = Integer(nums[i])
end
c = 0
for i in 0...n
	if a[i] == i
		c += 1
	end
end
def match(a,i,j)
	if a[i] == j && a[j] == i
		return true
	else
		return false
	end
end
d = 0
for i in 0...n
	j = a[i]
		if a[i] == j && a[j] == i && i != j
			d = 1
			break
		end

end
if c == n
	puts n
else
	if d == 1
		puts c + 2
	else
		puts c + 1
	end
end

def main()
	n=gets.chomp.to_i
	ar=gets.chomp.split(" ").map{|i| i.to_i}
	ans=0
	key=[]
	for i in 0...n
		if i==ar[i]
			ans+=1
		else
			key<<i
		end
	end
	if ans==n
		puts ans
		return
	end
	ans+=1
	for i in key
		val=ar[i]
		if ar[val]==i
			ans+=1
			break
		end
	end
	puts ans
end
main()

input = ARGF.read

numbers = input.lines.to_a[1].split(" ").map(&:to_i)

score = 0

old_posns = {}
swap = :no

numbers.each.with_index do |number, index|
  if number == index
    score += 1
  else
    old_posns[number] = index
    if swap == :no || swap == :single
      if old_posns[index] == number
        swap = :double
      end
    end

    if swap == :no
      if old_posns.include?(index)
        swap = :single
      end
    end
  end
end

case swap
when :single
  score += 1
when :double
  score += 2
end

puts score

n = gets.chomp.to_i
a = gets.chomp.split.map { |x| x.to_i }
count = 0
double_swap = false
for i in 0...n
  if a[i] == i
    count += 1
  elsif !double_swap && (v = a[i]) > i && a[v] == i
    double_swap = true
  end
end
count += double_swap ? 2 : 1 if count < n
puts count

n = gets.to_i
p = gets.split.map { |x| x.to_i }

cnt = 0
flag = false
n.times do |i|
	if p[i] == i
		cnt += 1
	elsif p[p[i]] == i
		flag = true
	end
end

if cnt == n
	puts cnt
elsif flag
	puts cnt + 2
else
	puts cnt + 1
end

n = gets.to_i
p = gets.split.map { |x| x.to_i }

cnt = 0
flag = false
n.times do |i|
	if p[i] == i
		cnt += 1
	elsif p[p[i]] == i
		puts i, p[i], p[p[i]]
		flag = true
	end
end

if cnt == n
	puts cnt
elsif flag
	puts cnt + 2
else
	puts cnt + 1
end