Inna and Dima decided to surprise Sereja. They brought a really huge candy matrix, it's big even for Sereja! Let's number the rows of the giant matrix from 1 to n from top to bottom and the columns — from 1 to m, from left to right. We'll represent the cell on the intersection of the i-th row and j-th column as (i, j). Just as is expected, some cells of the giant candy matrix contain candies. Overall the matrix has p candies: the k-th candy is at cell (xk, yk).The time moved closer to dinner and Inna was already going to eat p of her favourite sweets from the matrix, when suddenly Sereja (for the reason he didn't share with anyone) rotated the matrix x times clockwise by 90 degrees. Then he performed the horizontal rotate of the matrix y times. And then he rotated the matrix z times counterclockwise by 90 degrees. The figure below shows how the rotates of the matrix looks like.  Inna got really upset, but Duma suddenly understood two things: the candies didn't get damaged and he remembered which cells contained Inna's favourite sweets before Sereja's strange actions. Help guys to find the new coordinates in the candy matrix after the transformation Sereja made!

The first line of the input contains fix integers n, m, x, y, z, p (1 ≤ n, m ≤ 109; 0 ≤ x, y, z ≤ 109; 1 ≤ p ≤ 105). Each of the following p lines contains two integers xk, yk (1 ≤ xk ≤ n; 1 ≤ yk ≤ m) — the initial coordinates of the k-th candy. Two candies can lie on the same cell.

For each of the p candies, print on a single line its space-separated new coordinates.

NoteJust for clarity. Horizontal rotating is like a mirroring of the matrix. For matrix:QWER      REWQ ASDF  ->  FDSAZXCV      VCXZ

def ans(i,j,n,m,c,r,a)
    c.times{ i,j,n,m = j,n+1-i,m,n }
    if r!=0
        j = m+1-j
    end
    a.times { i,j,n,m = m+1-j,i,m,n }
    puts "#{i} #{j}"
end
n,m,x,y,z,p = gets.split.map(&:to_i)
p.times do | t |
    i,j = gets.split.map(&:to_i)
    ans(i,j,n,m,x%4,y%2,z%4)
end

def ans(i,j,n,m,c,r,a)

    while c>0
        t = i
        i = j
        j = n+1-t

        t = m
        m = n
        n = t

        c = c-1
    end

    if r!=0
        j = m+1-j
    end

    while a>0
        t = j
        j = i
        i = m+1-t

        t = m
        m = n
        n = t

        a = a-1
    end
    print i.to_s+' '+j.to_s+"\n"
end

n,m,x,y,z,p = gets.split.map(&:to_i)

p.times do | t |
    i,j = gets.split.map(&:to_i)
    ans(i,j,n,m,x%4,y%2,z%4)
end

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

n, m, k1, k2, k3, t = read_ints
k1 %= 4
k3 %= 4
k2 %= 2
t.times do
  x, y = read_ints
  h, w = n, m
  k1.times do
    x, y = y, h - x + 1
    h, w = w, h
  end
  k2.times { y = w - y + 1 }
  k3.times do
    x, y = w - y + 1, x
    h, w = w, h
  end
  puts "#{x} #{y}"
end

n,m,x,y,z,p=gets.split.map(&:to_i)
a=[]
b=[]
p.times{
	tx,ty=gets.split.map(&:to_i)
	a<<tx
	b<<ty
}
x%=4
x.times{
	p.times{ |i|
		a[i],b[i]=b[i],n-a[i]+1
	}
	n,m=m,n
}
y%=2
if y>0
	p.times{ |i|
		b[i]=m-b[i]+1
	}
end
z%=4
z.times{
	p.times{ |i|
		a[i],b[i]=m-b[i]+1,a[i]
	}
	n,m=m,n
}
p.times{ |i|
		puts "#{a[i]} #{b[i]}"
	}

def ans(i,j,n,m,c,r,a)

    while c>0
        t = j
        j = n+1-i
        i = t

        t = m
        m = n
        n = t

        c = c-1
    end

    if r
        j = m+1-j
    end

    while a>0
        t = i
        i = m+1-j
        j = t

        t = m
        m = n
        n = t

        a = a-1
    end
    puts i.to_s+' '+j.to_s
end

n,m,x,y,z,p = gets.split.map(&:to_i)

p.times do | t |
    i,j = gets.split.map(&:to_i)
    ans(i,j,n,m,x%4,y%2,z%4)
end

def ans(i,j,n,m,c,r,a)
    c.times{ i,j = j,n+1-i }
    if r!=0
        j = m+1-j
    end
    a.times{ i,j = m+1-j,i }
    puts "#{i} #{j}"
end
n,m,x,y,z,p = gets.split.map(&:to_i)
p.times do | t |
    i,j = gets.split.map(&:to_i)
    ans(i,j,n,m,x%4,y%2,z%4)
end

def ans(i,j,n,m,c,r,a)

    while c>0
        t = i
        i = m+1-j
        j = t

        t = m
        m = n
        n = t

        c = c-1
    end

    if r!=0
        j = m+1-j
    end

    while a>0
        t = j
        j = n+1-i
        i = t

        t = m
        m = n
        n = t

        a = a-1
    end
    print i.to_s+' '+j.to_s+"\n"
end

n,m,x,y,z,p = gets.split.map(&:to_i)

p.times do | t |
    i,j = gets.split.map(&:to_i)
    ans(i,j,n,m,x%4,y%2,z%4)
end

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

n, m, k1, k2, k3, t = read_ints
k1 %= 4
k3 %= 4
k2 %= 2
t.times do
  x, y = read_ints
  h, w = n, m
  k1.times do
    x, y = y, n - x + 1
    h, w = w, h
  end
  k2.times { y = m - y + 1 }
  k3.times do
    x, y = m - y + 1, x
    h, w = w, h
  end
  puts "#{x} #{y}"
end

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

n, m, k1, k2, k3, t = read_ints
k1 %= 4
k3 %= 4
k2 %= 2
t.times do
  x, y = read_ints
  h, w = n, m
  k3.times do
    x, y = y, n - x + 1
    h, w = w, h
  end
  k2.times { y = m - y + 1 }
  k1.times do
    x, y = m - y + 1, x
    h, w = w, h
  end
  puts "#{x} #{y}"
end


Formula One championship consists of series of races called Grand Prix. After every race drivers receive points according to their final position. Only the top 10 drivers receive points in the following order 25, 18, 15, 12, 10, 8, 6, 4, 2, 1. At the conclusion of the championship the driver with most points is the champion. If there is a tie, champion is the one with most wins (i.e. first places). If a tie still exists, it is chosen the one with most second places, and so on, until there are no more place to use for compare. Last year another scoring system was proposed but rejected. In it the champion is the one with most wins. If there is tie, champion is the one with most points. If a tie still exists it is proceeded the same way as in the original scoring system, that is comparing number of second, third, forth, and so on, places.You are given the result of all races during the season and you are to determine the champion according to both scoring systems. It is guaranteed, that both systems will produce unique champion.

The first line contain integer t (1 ≤ t ≤ 20), where t is the number of races. After that all races are described one by one. Every race description start with an integer n (1 ≤ n ≤ 50) on a line of itself, where n is the number of clasified drivers in the given race. After that n lines follow with the classification for the race, each containing the name of a driver. The names of drivers are given in order from the first to the last place. The name of the driver consists of lowercase and uppercase English letters and has length at most 50 characters. Comparing of names should be case-sensetive.

Your output should contain exactly two line. On the first line is the name of the champion according to the original rule, and on the second line the name of the champion according to the alternative rule.

3
3
Hamilton
Vettel
Webber
2
Webber
Vettel
2
Hamilton
Vettel

2
7
Prost
Surtees
Nakajima
Schumacher
Button
DeLaRosa
Buemi
8
Alonso
Prost
NinoFarina
JimClark
DeLaRosa
Nakajima
Patrese
Surtees

NoteIt is not guaranteed that the same drivers participate in all races. For the championship consider every driver that has participated in at least one race. The total number of drivers during the whole season is not more then 50.

class Racer
  N, POINTS = 50, [ 25, 18, 15, 12, 10, 8, 6, 4, 2, 1 ]

  attr_reader :score, :places, :name

  def initialize(name)
    @name = name
    @score = 0
    @places = Array.new(N, 0)
  end

  def add_place(place)
    @score += POINTS[place] if not POINTS[place].nil?
    @places[place] += 1
  end
end

def compare_a(alpha, beta)
  a = alpha.score <=> beta.score
  b = alpha.places <=> beta.places
  return 2 * a + b
end

def compare_b(alpha, beta)
  a = alpha.places.first <=> beta.places.first
  b = alpha.score <=> beta.score
  c = alpha.places[1 .. -1] <=> beta.places[1 .. -1]
  return 4 * a + 2 * b + c
end

def read_race(racers)
  gets.to_i.times do |place|
    name = gets.strip
    racers[name] ||= Racer.new(name)
    racers[name].add_place(place)
  end
end

def read_races(racers)
  gets.to_i.times { read_race(racers) }
end

racers = {}
read_races(racers)

puts racers.values.sort { |x, y| compare_a(x, y) }[-1].name
puts racers.values.sort { |x, y| compare_b(x, y) }[-1].name

t = gets.to_i
pts = [25, 18, 15, 12, 10, 8, 6, 4, 2, 1]
$h = {}
$places = {}
(0...t).each do |i|
    n = gets.to_i
    (0...n).each do |j|
        name = gets.strip
        if $h.key? name
            $h[name] += pts[j] if j < 10
        else
            $h[name] = pts[j] if j < 10
        end
        if $places.key? name
            $places[name][j] += 1
        else
            $places[name] = [0]*100
            $places[name][j] += 1
        end
    end
end
#puts $h.inspect
#puts $places.inspect
def better1 x,y
    return $h[x] <=> $h[y] if $h[x] != $h[y]
    idx = 0
    while $places[x][idx] == $places[y][idx]
        idx += 1
    end
    return $places[x][idx] <=> $places[y][idx]
end

def better2 x,y
    return $places[x][0] <=> $places[y][0] if $places[x][0] != $places[y][0]
    return $h[x] <=> $h[y] if $h[x] != $h[y]
    idx = 1
    while $places[x][idx] == $places[y][idx]
        idx += 1
    end
    return $places[x][idx] <=> $places[y][idx]
end
x = $h.keys
y = $h.keys
xi  = 0
#puts "Is it #{better1 x[2], x[0]}"
(1...x.size).each do |ti|
    xi = ti if better1(x[ti], x[xi]) > 0
end
yi  = 0
(1...y.size).each do |ti|
    yi = ti if better2(y[ti], y[yi]) > 0
end
puts x[xi]
puts y[yi]

#!/usr/bin/ruby

T = gets.to_i

Drivers = Hash.new
Points = [nil, 25, 18, 15, 12, 10, 8, 6, 4, 2 ,1]

T.times do
  n = gets.to_i
  place = 1
  n.times do
    name = gets.chomp
    Drivers[name] = Array.new(51, 0) if (!Drivers[name])
    Drivers[name][0] += Points[place] if place <= 10
    Drivers[name][place] += 1
    place += 1
  end
end

#p Drivers

original_rank = Drivers.to_a.sort {|l, r|
  i = 0
  while (l[1][i] == r[1][i] && i < 52)
    i += 1
  end
  if (i == 52)
    1
  else
    r[1][i] <=> l[1][i]
  end
}

#puts "==="
puts original_rank[0][0]

new_rank = Drivers.to_a
new_rank.each {|e|
  (e[1][1], e[1][0]) = [e[1][0], e[1][1]]
}
#p new_rank
new_rank.sort! {|l, r|
  i = 0
  while (l[1][i] == r[1][i] && i < 52)
    i += 1
  end
  if (i == 52)
    1
  else
    r[1][i] <=> l[1][i]
  end
}

puts new_rank[0][0]


There are n walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the n-th walrus stands at the beginning of the queue. The i-th walrus has the age equal to ai.The i-th walrus becomes displeased if there's a younger walrus standing in front of him, that is, if exists such j (i < j), that ai > aj. The displeasure of the i-th walrus is equal to the number of walruses between him and the furthest walrus ahead of him, which is younger than the i-th one. That is, the further that young walrus stands from him, the stronger the displeasure is.The airport manager asked you to count for each of n walruses in the queue his displeasure.

The first line contains an integer n (2 ≤ n ≤ 105) — the number of walruses in the queue. The second line contains integers ai (1 ≤ ai ≤ 109). Note that some walruses can have the same age but for the displeasure to emerge the walrus that is closer to the head of the queue needs to be strictly younger than the other one.

Print n numbers: if the i-th walrus is pleased with everything, print "-1" (without the quotes). Otherwise, print the i-th walrus's displeasure: the number of other walruses that stand between him and the furthest from him younger walrus.

n = gets.to_i
seq = gets.split.map &:to_i
seq.reverse!
ans = []
list = []
pos = []

def bin_search(list, x)
	b = 0
	e = list.size - 1
	p = -1
	while b <= e
		m = (b+e)/2
		if list[m] >= x
			b = m + 1
		else
			e = m - 1
			p = m
		end
	end
	p
end

seq.each_with_index do |x, i|
	p = bin_search list, x
	ans[i] = -1
	if p != -1
		ans[i] = i - pos[p] - 1
	end
	if list.size > 0 && x < list.last
		list << x
		pos << i
	elsif list.size == 0
		list << x
		pos << i
	end
end

ans.reverse!
ans.each do |a|
	p a
end

def findX(a)
  x0 = 0
  x1 = a.size()-1

  return a[x0] if yield(a[x0])
  while x1-x0 > 1
    x2 = (x0+x1)/2
    if yield(a[x2])
      x1 = x2
    else
      x0 = x2
    end
  end
  a[x1]
end

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

b = []
mdx = 0
lst = []
0.upto(a.size-1) do |i|
  if lst.empty? || a[mdx] >= a[i]
    lst << [a[i], (mdx = i)]
    b[i] = -1
  else
    y = findX(lst){|aa,ii| aa<a[i] }[1]
    b[i] = i-y-1
  end
end

puts b.reverse*" "


You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:  Write parity(a) to the end of a. For example, .  Remove the first character of a. For example, . You cannot perform this operation if a is empty. You can use as many operations as you want. The problem is, is it possible to turn a into b?The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.

The first line contains the string a and the second line contains the string b (1 ≤ |a|, |b| ≤ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.

Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.

NoteIn the first sample, the steps are as follows: 01011 → 1011 → 011 → 0110

A = gets.chomp.count('1')
B = gets.chomp.count('1')
A += 1 if A&1 == 1
# puts "#{A} #{B}"
if A >= B
	puts "YES"
else
	puts "NO"
end

s = gets.chomp
e = gets.chomp
si = s.count('1')
ei = e.count('1')
si += 1 if si % 2 != 0
puts "YES" if si >= ei
puts "NO" if si < ei

s = gets.chomp
e = gets.chomp
si = ei = 0
for i in 0...s.size
    si += 1 if s[i] == '1'
end
for i in 0...e.size
    ei += 1 if e[i] == '1'
end
if si % 2 == 0
    puts "NO" if si < ei
    puts "YES" if si >= ei
else
    if ei > si && si + 1 != ei
        puts "NO"
    else
        puts "YES"
    end
end

s = gets.chomp
e = gets.chomp
si = s.count('1')
ei = e.count('1')
if si % 2 == 0
    puts "NO" if si < ei
    puts "YES" if si >= ei
else
    if ei > si && si + 1 != ei
        puts "NO"
    else
        puts "YES"
    end
end

a = gets.chomp
b = gets.chomp

onesA = a.count('1')
onesB = b.count('1')

onesA += onesA & 1

 if onesA >= onesB
   puts "YES"
 else
   puts "NO"
 end

def ones(s)
  s.split(//).count("1")
end

def parity?(i)
  i % 2 == 1
end

def run(args)
  a = args[0]
  b = args[1]

  a1 = ones(a)
  b1 = ones(b)

  ap = parity?(a1)
  bp = parity?(b1)

  if a1 >= b1
    return "YES"
  else
    if b1 - a1 == 1 and ap
      return "YES"
    else
      return "NO"
    end
  end
  return "sabugo"
end

buffer = []

STDIN.read.split("\n").each do |line|
  buffer << line
  if buffer.size == 2
    puts run(buffer)
    buffer = []
  end
end

s=gets.split(//)
l=s.size
i=0
n=0
while (i<l) do
  if (s[i]=='1') then
    n+=1
  end
  i+=1
end
if (n%2==1) then
  n+=1
end
s=gets.split(//)
l=s.size
i=0
m=0
while (i<l) do
  if (s[i]=='1') then
    m+=1
  end
  i+=1
end
if (n>=m) then puts "YES"
else puts "NO"
end

a = gets.scan('1').size
b = gets.scan('1').size
a += 1 if a.odd?
puts a >= b ? :YES : :NO

def run
  a1 = $stdin.gets.split(//).map(&:to_i).reduce(:+)
  b1 = $stdin.gets.split(//).map(&:to_i).reduce(:+)

  a1 += 1 if a1 % 2 == 1
  $stdout.puts a1 >= b1 ? "YES" : "NO"
end

run if $0 == __FILE__

z=gets
puts z.count('1')+z.count('1')%2>=gets.count('1') ? 'YES' : 'NO'

as = gets
bs = gets
a = as.count('1')
b = bs.count('1')

if a >= b-1 && b%2 == 0 || b%2 == 1 && a >= b || as == bs
  puts "YES"
else
  puts "NO"
end

count = gets.scan('1').size
count += 1 if count % 2 == 1
puts count >= gets.scan('1').size ? "YES" : "NO"

A = gets.chomp
B = gets.chomp
for c in 1..A.length
	# puts A[-c..A.length]
	if B.start_with?A[-c..A.length] and A[0..-c-1].count('1') >= B[c..B.length].count('1')
		puts "YES"
		exit
	end
end
puts "NO"

s = gets.chomp
e = gets.chomp
si = s.count('1')
ei = e.count('1')
si += 1 if si & 1
puts "YES" if si >= ei
puts "NO" if si < ei

s = gets.chomp
e = gets.chomp
si = ei = 0
for i in 0...s.size
    si += 1 if s[i] == '1'
end
for i in 0...e.size
    ei += 1 if e[i] == '1'
end
if si % 2 == 0
    puts "NO" if si < ei
else
    if ei > si && si + 1 != ei
        puts "NO"
    else
        puts "YES"
    end
end

s = gets.chomp
e = gets.chomp
si = ei = 0
for i in 0...s.size
    si += 1 if s[i] == '1'
end
for i in 0...e.size
    ei += 1 if e[i] == '1'
end
if si % 2 == 0
    puts "NO" if si < ei
    puts "YES" if si == ei
else
    if ei > si && si + 1 != ei
        puts "NO"
    else
        puts "YES"
    end
end

def ones(s)
  s.split(//).count("1")
end

def parity?(i)
  i % 2 == 1
end

def run(args)
  a = args[0]
  b = args[1]

  a1 = ones(a)
  b1 = ones(b)

  ap = parity?(a1)
  bp = parity?(b1)

  if a1 == b1
    return "YES"
  else
    if b1 - a1 == 1 and ap
      return "YES"
    else
      return "NO"
    end
  end
  return "sabugo"
end

buffer = []

STDIN.read.split("\n").each do |line|
  buffer << line
  if buffer.size == 2
    puts run(buffer)
    buffer = []
  end
end

def run
  a1 = $stdin.gets.split(//).map(&:to_i).reduce(:+)
  b1 = $stdin.gets.split(//).map(&:to_i).reduce(:+)
  $stdout.puts a1 >= b1 ? "YES" : "NO"
end

run if $0 == __FILE__

as = gets
bs = gets
a = as.count('1')
b = bs.count('1')

if a >= b-1 && b%2 == 0 || b%2 == 1 && a > b || as == bs
  puts "YES"
else
  puts "NO"
end


Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if   the sequence consists of at least two elements  f0 and f1 are arbitrary  fn + 2 = fn + 1 + fn for all n ≥ 0. You are given some sequence of integers a1, a2, ..., an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.

The first line of the input contains a single integer n (2 ≤ n ≤ 1000) — the length of the sequence ai. The second line contains n integers a1, a2, ..., an (|ai| ≤ 109).

Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.

NoteIn the first sample, if we rearrange elements of the sequence as  - 1, 2, 1, the whole sequence ai would be Fibonacci-ish.In the second sample, the optimal way to rearrange elements is , , , , 28.

# Discard input count
gets

# Get numbers as a unique array of ints.
nums_list = gets.split.map { |a| a.to_i }
nums_list_uniq = nums_list.uniq

# Get numbers as another array of ints, but with duplicates tacked on to the end.
nums_list_append = nums_list_uniq + nums_list.group_by{ |e| e }.select { |k, v| v.size > 1 }.map(&:first)

# Now we can compare the unique list against the duplicates list to get every set of fibonacci bases without repetition.

# Also, count how many of each number there are.
num_count = {}
num_count.default = 0
nums_list.each { |num| num_count[num] += 1 }

longest_sequence = 2
nums_list_uniq.each_with_index do |a,a_index|
  nums_list_append.each_with_index do |b,b_index|
    # Skip if the two numbers have the same index
    next if (a_index == b_index)
    i = a
    j = b
    k = a+b
    sequence_length = 2
    # Set up a hash to keep track of the numbers I've already used.
    already_used = {}
    already_used.default = 0
    already_used[a] += 1
    already_used[b] += 1

    # If the count of K's used thus far is less than the total count of K's in the sequence
    while (already_used[k] < num_count[k]) do
      # Add the K
      already_used[k] += 1
      i = j
      j = k
      k = i+j
      sequence_length += 1
    end
    longest_sequence = sequence_length if (sequence_length > longest_sequence)
  end
end

puts longest_sequence.to_s

# Discard input count
gets

# Get numbers as a unique array of ints.
nums_list = gets.split.map { |a| a.to_i }
nums_list_uniq = nums_list.uniq

# Get numbers as another array of ints, but with duplicates tacked on to the end.
nums_list_append = nums_list_uniq + nums_list.group_by{ |e| e }.select { |k, v| v.size > 1 }.map(&:first)

# Hash for quick lookup
nums_index = {}
nums_list_uniq.each {|num| nums_index[num] = true}

longest_sequence = 2

nums_list_uniq.each_with_index do |a,a_index|
  nums_list_append.each_with_index do |b,b_index|
    # Skip if the two numbers have the same index
    next if (a_index == b_index)
    i = a
    j = b
    k = a+b
    sequence_length = 2
    already_used = {}

    while (!nums_index[k].nil? && already_used[k].nil?) do
      already_used[k] = true
      i = j
      j = k
      k = i+j
      sequence_length += 1
    end
    longest_sequence = sequence_length if (sequence_length > longest_sequence)
  end
end

puts longest_sequence.to_s

# Discard input count
gets
# Get numbers as an array of ints.
nums_list = gets.split.map { |a| a.to_i }

# Also hashify them, pointing to their index.
nums_index = {}
nums_list.each_with_index {|num,index| nums_index[num] = index}

longest_sequence = 2

nums_list.each do |a|
  nums_list.each do |b|
    # Skip if the two numbers have the same index
    next if (nums_index[a] == nums_index[b])
    i = a
    j = b
    k = a+b
    sequence_length = 2
    # See how long the longest sequence is
    while (!nums_index[k].nil?) do
      i = j
      j = k
      k = i+j
      sequence_length += 1
    end
    longest_sequence = sequence_length if (sequence_length > longest_sequence)
  end
end

puts longest_sequence.to_s

# Discard input count
gets
# Get numbers as an array of ints.
nums_list = gets.split.map { |a| a.to_i }

# Also hashify them, pointing to their index.
nums_index = {}
nums_list.each_with_index {|num,index| nums_index[num] = index}

longest_sequence = 2

nums_list.each_with_index do |a,a_index|
  nums_list.each_with_index do |b,a_index|
    # Skip if the two numbers have the same index
    next if (nums_index[a] == nums_index[b])
    i = a
    j = b
    k = a+b
    sequence_length = 2
    # See how long the longest sequence is
    while (!nums_index[k].nil?) do
      i = j
      j = k
      k = i+j
      sequence_length += 1
    end
    longest_sequence = sequence_length if (sequence_length > longest_sequence)
  end
end

puts longest_sequence.to_s

# Discard input count
gets
# Get numbers as an array of ints.
nums_list = gets.split.map { |a| a.to_i }

# Also hashify them, pointing to their index.
nums_index = {}
nums_list.each_with_index {|num,index| nums_index[num] = index}

longest_sequence = 2

nums_list.each do |a,a_index|
  nums_list.each do |b,a_index|
    # Skip if the two numbers have the same index
    next if (nums_index[a] == nums_index[b])
    i = a
    j = b
    k = a+b
    sequence_length = 2
    # See how long the longest sequence is
    while (!nums_index[k].nil?) do
      i = j
      j = k
      k = i+j
      sequence_length += 1
    end
    longest_sequence = sequence_length if (sequence_length > longest_sequence)
  end
end

puts longest_sequence.to_s

# Discard input count
gets
# Get numbers as an array of ints.
nums_list = gets.split.map { |a| a.to_i }

# Also hashify them.
nums_index = {}
nums_list.each {|num| nums_index[num] = true}
longest_sequence = 2

# List of A's we have already tested.
a_tested = {}

nums_list.each do |a|

  # Skip this set of b's if we have seen this a before.
  next if (!a_tested[a].nil?)
  a_tested[a] = true

  nums_list.each do |b|
    # Skip if the two numbers have the same index.
    # next if (a_index == b_index)
    i = a
    j = b
    k = a+b
    sequence_length = 2
    # See how long the longest sequence is
    while (!nums_index[k].nil?) do
      i = j
      j = k
      k = i+j
      sequence_length += 1
    end
    longest_sequence = sequence_length if (sequence_length > longest_sequence)
  end
end

puts longest_sequence.to_s

# Discard input count
gets
# Get numbers as a unique array of ints.
nums_list = gets.split.map { |a| a.to_i }
nums_list_uniq = nums_list.uniq
# Get numbers as another array of ints, but with duplicates tacked on to the end.
nums_list_append = nums_list_uniq + nums_list.group_by{ |e| e }.select { |k, v| v.size > 1 }.map(&:first)

puts nums_list_uniq.to_s
puts nums_list_append.to_s

nums_index = {}
nums_list_uniq.each {|num| nums_index[num] = true}

longest_sequence = 2

nums_list_uniq.each_with_index do |a,a_index|
  nums_list_append.each_with_index do |b,b_index|
    # Skip if the two numbers have the same index
    next if (a_index == b_index)
    i = a
    j = b
    k = a+b
    sequence_length = 2
    already_used = {}

    while (!nums_index[k].nil? && already_used[k].nil?) do
      already_used[k] = true
      i = j
      j = k
      k = i+j
      sequence_length += 1
    end
    longest_sequence = sequence_length if (sequence_length > longest_sequence)
  end
end

puts longest_sequence.to_s


A median of an array of integers of length $$$n$$$ is the number standing on the $$$\lceil {\frac{n}{2}} \rceil$$$ (rounding up) position in the non-decreasing ordering of its elements. Positions are numbered starting with $$$1$$$. For example, a median of the array $$$[2, 6, 4, 1, 3, 5]$$$ is equal to $$$3$$$. There exist some other definitions of the median, but in this problem, we will use the described one.Given two integers $$$n$$$ and $$$k$$$ and non-decreasing array of $$$nk$$$ integers. Divide all numbers into $$$k$$$ arrays of size $$$n$$$, such that each number belongs to exactly one array.You want the sum of medians of all $$$k$$$ arrays to be the maximum possible. Find this maximum possible sum.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of test cases. The first line of the description of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \leq n, k \leq 1000$$$). The second line of the description of each test case contains $$$nk$$$ integers $$$a_1, a_2, \ldots, a_{nk}$$$ ($$$0 \leq a_i \leq 10^9$$$) — given array. It is guaranteed that the array is non-decreasing: $$$a_1 \leq a_2 \leq \ldots \leq a_{nk}$$$. It is guaranteed that the sum of $$$nk$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print a single integer — the maximum possible sum of medians of all $$$k$$$ arrays.

t = gets.chomp.to_i
t.times do
  n, k = gets.chomp.split(' ').map(&:to_i)
  arr = gets.chomp.split(' ').map(&:to_i)
  # puts arr.to_s
  t = n / 2
  ind = arr.size - 1 - t
  # puts "ind = " + ind.to_s
  res = 0
  while k > 0 do
    res += arr[ind]
    # puts "el = " + arr[ind].to_s
    k -= 1
    ind -= t + 1
  end
  puts res
end

# 1 -> 0
# 2 -> 1
# 3 -> 1
# 4 -> 2
# 5 -> 2

t=gets.to_i
t.times{
    n,k=gets.split.map &:to_i
    tab=gets.split.map &:to_i
    time = (n.to_f/2).ceil-1
    tab = tab.drop(k*time)
    p tab.each_slice(n - time).map{|x|x[0]}.sum
}


Today, Wet Shark is given n integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark. Note, that if Wet Shark uses no integers from the n integers, the sum is an even integer 0.

The first line of the input contains one integer, n (1 ≤ n ≤ 100 000). The next line contains n space separated integers given to Wet Shark. Each of these integers is in range from 1 to 109, inclusive.

Print the maximum possible even sum that can be obtained if we use some of the given integers.

NoteIn the first sample, we can simply take all three integers for a total sum of 6.In the second sample Wet Shark should take any four out of five integers 999 999 999.

gets
x,y=gets.split.map(&:to_i).sort.reverse.partition{|e|e%2==0}
p x.reduce(0,:+)+y[0,y.size/2*2].reduce(0,:+)

def function
b=gets.chomp
a=gets.chomp
a=a.split(' ').map(&:to_i).sort
sum=0
a.each do |i|
sum+=i
end
if sum%2!=0
a.each do |i|
if i%2!=0
sum-=i
puts sum
break
end
end
else
puts sum
end
end
function

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

min_odd = numbers.find(&:odd?)
sum = numbers.inject(0, :+)
puts sum.even? ? sum : sum - min_odd

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

evens = arr.select(&:even?)
odds = arr.select(&:odd?).sort

odds_sum = odds.size.even? ? odds.inject(0, :+) : odds.drop(1).inject(0, :+)

puts evens.inject(0, :+) + odds_sum

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

par = []
nep = []
sum = a.reduce(:+)
a.each { |x| x.even? ? par.push(x) : nep.push(x) }

puts sum.even? ? sum : sum - nep[0]

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

par, nep = [], []
a.each do |x|
  x.even? ? par.push(x) : nep.push(x)
end
sum = a.reduce(:+)

puts sum.even? ? sum : sum - nep[0]

def sum_all(arr)
	sum =0
	arr.each do |i|
		sum+=i
	end
	return sum
end

n = gets.chomp
arr = gets.split.map(&:to_i)
odd_count =0
even_count =0
arr.each do|i|
	if i.even?
		even_count +=1
	else
		odd_count +=1
	end
end
sum=0

if odd_count.even?
	puts sum_all(arr)
else
	odd_count -=1
arr.sort!.reverse!

sum =0
arr.each do |i|
	if i.odd? and odd_count>0
		sum+=i
		odd_count -=1
	elsif i.even?
		sum+=i
	end
end
puts sum
end

gets
e1=0
o1=-1
x=gets.split.map{|e| e.to_i}
x.each{|e|
	d=e%2
	if d==0 then
		e1+=e
		if o1!=-1 then
			o1+=e
		end
	else
		o2=e1+e
		if o1!=-1 then
			e1=[e1,o1+e].max
		end
		o1=[o1,o2].max
	end
}
puts e1

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

a.sort!{|x, y| y <=> x }
ans = 0
odd = []
a.each do |v|
  if v % 2 == 0
    ans += v
  else
    if odd.size == 0
      odd.push(v)
    else
      ans += v + odd.shift
    end
  end
end
puts ans

# coding: utf-8

n = gets.to_i
a = []
sum = 0
odds = 0
gets.split.each { |i|
    i = i.to_i

    if i.even?
        sum += i
    else
        odds += 1 if i.odd?
        a << i
    end
}
a.sort!
if odds.odd?
    a.shift
end
a << 0

puts a.reduce(:+) + sum

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

s = xs.inject(&:+)
if s % 2 == 0
  puts s
else
  puts s - xs.select { |x| x % 2 == 1 }.min
end

def solve(a)
  s = a.inject(0, :+)
  return s if s.even?
  x = a.lazy.select(&:odd?).min
  return s - x if x
  0
end

gets
puts solve(gets.split.map(&:to_i))

n = gets.to_i
a = gets.split(' ').map &:to_i
s = a.reduce(&:+)
if s%2 == 0
  puts s
else
  mn = Float::INFINITY
  for i in a
    mn = [mn, i].min if i%2 == 1
  end
  puts s - mn
end

n = gets.to_i
a = gets.split.map(&:to_i)
sum = a.inject(:+)
puts sum.even? ? sum : sum - a.select(&:odd?).min

n = gets.to_i
a = gets.split.map(&:to_i).sort
sum = a.inject(:+)
puts sum.even? ? sum : sum - a.find{|x| x.odd?}

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

aoddmin = a.select{|x| x.odd?}.min

asum = a.inject(:+)
if asum.even? then
  puts asum
else
  puts asum - aoddmin
end

gets
a = gets.split.map{|x| x.to_i}
odds = a.select{|x| x%2 == 1}
puts(a.inject(0){|s, x| s + x} - (odds.size%2 != 0 ? odds.min : 0))

gets
x,y=gets.split.map(&:to_i).sort.reverse.partition{|e|e==0}
p x.reduce(0,:+)+y[0,y.size/2*2].reduce(0,:+)

def function
a=gets.chomp
a=a.split(' ').map(&:to_i).sort
sum=0
a.each do |i|
sum+=i
end
a.each do |i|
if i%2!=0
sum-=i
break
end
end
puts sum
end
function

n = gets.chomp
arr = gets.split.map(&:to_i)
odd_count =0
even_count =0
arr.each do |i|
	if i.odd?
		odd_count+=1
	else
		even_count +=1
	end
end

if odd_count.odd?
	odd_count = odd_count -1
end
sum = 0
arr.each do |i|
	if i.odd? and not odd_count.zero?
		sum +=i
		odd_count= odd_count -1
	elsif i.even?
		sum +=i
	end
end
puts sum

gets
e1=0
o1=-1
x=gets.split.map{|e| e.to_i}
x.each{|e|
	d=e%2
	if d==0 then
		e1+=e
		if o1!=-1 then
			o1+=e
		end
	else
		o2=e1+e
		if o1!=-1 then
			e1=o1+e
		end
		o1=o2
	end
}
puts e1

# coding: utf-8

n = gets.to_i
a = []
sum = 0
odds = 0
gets.split.each { |i|
    i = i.to_i

    if i.even?
        sum += i
    else
        odds += 1 if i.odd?
        a << i
    end
}

if odds.odd?
    a.shift
    a << 0
end

puts a.reduce(:+) + sum

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

aoddmax = a.select{|x| x.odd?}.max

asum = a.inject(:+)
if asum.even? then
  puts asum
else
  puts asum - aoddmax
end


Given the integer $$$n$$$ — the number of available blocks. You must use all blocks to build a pedestal. The pedestal consists of $$$3$$$ platforms for $$$2$$$-nd, $$$1$$$-st and $$$3$$$-rd places respectively. The platform for the $$$1$$$-st place must be strictly higher than for the $$$2$$$-nd place, and the platform for the $$$2$$$-nd place must be strictly higher than for the $$$3$$$-rd place. Also, the height of each platform must be greater than zero (that is, each platform must contain at least one block).    Example pedestal of $$$n=11$$$ blocks: second place height equals $$$4$$$ blocks, first place height equals $$$5$$$ blocks, third place height equals $$$2$$$ blocks.Among all possible pedestals of $$$n$$$ blocks, deduce one such that the platform height for the $$$1$$$-st place minimum as possible. If there are several of them, output any of them.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case contains a single integer $$$n$$$ ($$$6 \le n \le 10^5$$$) — the total number of blocks for the pedestal. All $$$n$$$ blocks must be used. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^6$$$.

For each test case, output $$$3$$$ numbers $$$h_2, h_1, h_3$$$ — the platform heights for $$$2$$$-nd, $$$1$$$-st and $$$3$$$-rd places on a pedestal consisting of $$$n$$$ blocks ($$$h_1+h_2+h_3=n$$$, $$$0 < h_3 < h_2 < h_1$$$).  Among all possible pedestals, output the one for which the value of $$$h_1$$$ minimal. If there are several of them, output any of them.

NoteIn the first test case we can not get the height of the platform for the first place less than $$$5$$$, because if the height of the platform for the first place is not more than $$$4$$$, then we can use at most $$$4 + 3 + 2 = 9$$$ blocks. And we should use $$$11 = 4 + 5 + 2$$$ blocks. Therefore, the answer 4 5 2 fits. In the second set, the only suitable answer is: 2 3 1.

#require "prime"
#input of int(split by space)
def get_i()
    return gets.chomp.split(" ").map(&:to_i)
end
#input of float(split by space)
def get_f()
    return gets.chomp.split(" ").map(&:to_f)
end
#input of string(split by space)
def get()
    return gets.chomp.split(" ")
end
#input of string(split per one character)
def get_nsp()
    return gets.chomp.split("")
end
#yes or no decision
def yn_judge(bool,y="Yes",n="No")
    return bool ? y : n
end
#output grid(two dimensional array)
def puts_grid(grid,join_char="")
    grid.each do|line|
        puts line.join(join_char)
    end
end

Dirxy4=[[1,0],[-1,0],[0,1],[0,-1]]
Dirxy8=[[1,0],[1,-1],[1,1],[0,-1],[0,1],[-1,0],[-1,-1],[-1,1]]

INF=Float::INFINITY

#MOD=998_244_353
MOD=10**9+7

T=gets.to_i
T.times do
    n=gets.to_i
    v=n/3
    r=n%3
    case r
    when 0 then
        puts [v,v+1,v-1].join(" ")
    when 1 then
        puts [v,v+2,v-1].join(" ")
    when 2 then
        puts [v+1,v+2,v-1].join(" ")
    end
end

def solution(n)
    fi, se, th = 3, 2, 1
    m = (n - 6) / 3
    r = (n - 6) % 3
    fi += m
    se += m
    th += m
    while r > 0
        if r > 0
            fi += 1
            r -= 1
        end
        if r > 0
            se += 1
            r -= 1
        end
        if r > 0
            th += 1
            r -= 1
        end
    end
    puts se.to_s + " " + fi.to_s + " " + th.to_s
end

n = $stdin.gets.to_i
(0...n).each do |i|
  n = $stdin.gets.to_i
  solution(n)
end

t = gets.to_i

t.times do
  n = gets.to_i
  h1 = h2 = h3 = n / 3
  m = n % 3
  if m == 1
    h1 += 1
  elsif m == 2
    h1 += 1
    h2 += 1
  end

  until h3 < h2 && h2 < h1 && h1+h2+h3 == n
    h1 += 1
    h3 -= 1
  end
  puts [h2, h1, h3].join(" ")
end

#require "prime"
#input of int(split by space)
def get_i()
    return gets.chomp.split(" ").map(&:to_i)
end
#input of float(split by space)
def get_f()
    return gets.chomp.split(" ").map(&:to_f)
end
#input of string(split by space)
def get()
    return gets.chomp.split(" ")
end
#input of string(split per one character)
def get_nsp()
    return gets.chomp.split("")
end
#yes or no decision
def yn_judge(bool,y="Yes",n="No")
    return bool ? y : n
end
#output grid(two dimensional array)
def puts_grid(grid,join_char="")
    grid.each do|line|
        puts line.join(join_char)
    end
end

Dirxy4=[[1,0],[-1,0],[0,1],[0,-1]]
Dirxy8=[[1,0],[1,-1],[1,1],[0,-1],[0,1],[-1,0],[-1,-1],[-1,1]]

INF=Float::INFINITY

#MOD=998_244_353
MOD=10**9+7

T=gets.to_i
T.times do
    n=gets.to_i
    puts [2,n-3,1].join(" ")
end


You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >.The following definition of a regular bracket sequence is well-known, so you can be familiar with it.Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS.For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not.Determine the least number of replaces to make the string s RBS.

The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106.

If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s.

s = gets.strip.split ''

brk = Array.new
right = {'>' => '<', '}' => '{', ']' => '[', ')' => '('}

res = 0

s.each do |e|
	if right.include? e
		if brk.size == 0
			res = -1
			break
		end

		if brk[-1]  == right[e]
			brk.pop
		else
			res += 1
			brk.pop
		end
	else
		brk.push e
	end
end

if res == -1 or brk.any?{|e| e != 0}
	puts 'Impossible'
else
	puts res
end

str = gets.chomp

stack = []
res = 0
hash = {
  ')' => '(',
  '>' => '<',
  ']' => '[',
  '}' => '{'
}

str.each_char do |c|
  case c
  when '(', '{', '<', '[' then stack.push c
  when ')'
    res = 'Impossible' and break if (stack.length==0)
    res += 1 if stack[-1]!='('
    stack.pop
  when '}'
    res = 'Impossible' and break if (stack.length==0)
    res += 1 if stack[-1]!='{'
    stack.pop
  when '>'
    res = 'Impossible' and break if (stack.length==0)
    res += 1 if stack[-1]!='<'
    stack.pop
  when ']'
    res = 'Impossible' and break if (stack.length==0)
    res += 1 if stack[-1]!='['
    stack.pop
  end
end

if stack.length==0
  puts res
else
  puts 'Impossible'
end

s = gets.chomp

RBS = Array.new		# regular bracket sequance
change = 0

for i in 0...s.length
	case s[i]
		when '(', '[', '{', '<' then
			RBS.push s[i]

		when ')', ']', '}', '>' then
			if RBS.empty?
				puts "Impossible"
				exit true
			end

			ch = RBS.pop
			if not ((ch == '(' and s[i] == ')') or (ch == '[' and s[i] == ']') or (ch == '{' and s[i] == '}') or (ch == '<' and s[i] == '>'))
				change = change + 1
			end
	end

end

if not RBS.empty?
	puts "Impossible"
else
	puts change
end

ans=0
s=[]
def type_of b
	case b
	when ?<,?{,?[,?(
		:opening
	when ?>,?},?],?)
		:closing
	end
end

def is_paired?(o,c)
	case o
	when ?<
		c==?>
	when ?{
		c==?}
	when ?[
		c==?]
	when ?(
		c==?)
	end
end

while c=STDIN.getc
	if type_of(c)==:opening
		s.push c
	elsif type_of(c)==:closing
		o=s.pop
		unless o
			puts "Impossible"
			exit
		end
		ans+=1 unless is_paired?(o,c)
	end
end

puts s.empty? ? ans : "Impossible"

s = gets.strip.split ''

brk =Array.new(4, 0)
right = {'>' => 0, '}' => 1, ']' => 2, ')' => 3}
left = {'<' => 0, '{' => 1, '[' => 2, '(' => 3}
res = 0

s.each do |e|
	if right.include? e
		if brk.none?{|i| i > 0}
			res = -1
			break
		end

		if brk[right[e]] != 0
			brk[right[e]] -= 1
		else
			res += 1
			brk[brk.find_index{|e| e != 0}] -= 1
		end
	else left.include? e
			brk[left[e]] += 1
	end
end

if res == -1 or brk.any?{|e| e != 0}
	puts 'Impossible'
else
	puts res
end

ans=0
s=[]
def type_of b
	case b
	when ?<,?{,?[,?(
		:opening
	when :>,?},?],?)
		:closing
	end
end

def is_paired?(o,c)
	case o
	when ?<
		c==?>
	when ?{
		c==?}
	when ?[
		c==?]
	when ?(
		c==?)
	end
end

while c=STDIN.getc
	if type_of(c)==:opening
		s.push c
	elsif type_of(c)==:closing
		o=s.pop
		unless o
			puts "Impossible"
			exit
		end
		ans+=1 unless is_paired?(o,c)
	end
end

puts s.empty? ? ans : "Impossible"

ans=0
s=[]
def type_of b
	case b
	when ?<,?{,?[,?(
		:opening
	when ?>,?},?],?)
		:closing
	end
end

def is_paired?(o,c)
	case o
	when ?<
		c==?>
	when ?{
		c==?}
	when ?[
		c==?]
	when ?(
		c==?)
	end
end

while c=STDIN.getc
	p type_of(c)
	if type_of(c)==:opening
		s.push c
	elsif type_of(c)==:closing
		o=s.pop
		unless o
			puts "Impossible"
			exit
		end
		ans+=1 unless is_paired?(o,c)
	end
end

puts s.empty? ? ans : "Impossible"


A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x < y) from the set, such that y = x·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset.

The first line of the input contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109). The next line contains a list of n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 109). All the numbers in the lines are separated by single spaces.

On the only line of the output print the size of the largest k-multiple free subset of {a1, a2, ..., an}.

NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}.

a,k={},gets.split.map(&:to_i)[1]
gets.split.map(&:to_i).sort.each{|i|a[i]=1 if i%k>0||!a[i/k]}
p a.size

k=gets.split.map(&:to_i)[1]
a,ans={},0
gets.split.map(&:to_i).sort.each{|i|a[i]=1}
a.each do |key,v|
  next if v==0
  ans+=1
  a[key*k]-=1 if a[k*key]
end
p ans

n,k=gets.chomp.split.collect{|a| a.to_i}
arr=gets.chomp.split.collect{|a| a.to_i}.sort
set={}
arr.each{|a| if a%k!=0 || set[a/k]== nil then set[a]=true end }
puts set.size

#!/usr/bin/ruby1.9

n, k = STDIN.readline.split.collect {|s| s.to_i }
a = STDIN.readline.split.collect {|s| s.to_i }

a.sort!
index = {}
a.length.times {|i| index[a[i]] = i }

count = 0
a.length.times do |i|
	next if a[i] < 0
	count += 1
	j = index[k*a[i]]
	a[i] *= -1
	if j != nil
		a[j] *= -1
	end
end

puts count

require 'set'
nk = gets.split(' ').collect!{|i| i.to_i}
n = nk[0]
k = nk[1]

a = gets.split(' ').collect!{|i| i.to_i}.sort!

# ak = []
# size = 0
# a.each do |i|
# 	if !ak.include?(i)
# 		ak << i*k
# 		size += 1
# 	end
# end

# puts size
s = Set.new
a.each do |i|
	s << i*k if !s.include?(i)
end

p s.size

# require 'set'
nk = gets.split(' ').collect!{|i| i.to_i}
n = nk[0]
k = nk[1]

a = gets.split(' ').collect!{|i| i.to_i}.sort!

# s = Set.new
s = {}
b = 0
a.each do |i|
	if !s.include?(i)
		s[i*k] = b
		b += 1
	end
end

p b

def binary_search(ary, x)

  n = ary.size
  left  = 0
  right = n - 1

  while left <= right
    mid = (left + right) / 2

    case ary[mid] <=> x
    when 0
      return mid
    when 1
      right = mid - 1
    when -1
      left  = mid + 1
    end
  end

  return -1
end

n, k = gets.split.map &:to_i
ary  = gets.split.map(&:to_i).sort
aryc = Array.new(n, 0)
ans  = 0

for i in 0 .. n - 1 do

  if aryc[i] == 1 then next end
  aryc[i] = 1

  tmp = ary[i]
  cnt = 1

  while tmp <= ary[n - 1]
    if k == 1 then break end
    tmp *= k
    check = binary_search(ary, tmp)
    if check > -1
      aryc[check] = 1
      cnt += 1
    else
      break
    end
  end

  ans += (cnt + 1) / 2
end

puts ans

nk = gets.split(' ').collect!{|i| i.to_i}
n = nk[0]
k = nk[1]

a = gets.split(' ').collect!{|i| i.to_i}.sort!

# ak = []
# size = 0
# a.each do |i|
# 	if !ak.include?(i)
# 		ak << i*k
# 		size += 1
# 	end
# end

# puts size
s = []
a.each do |i|
	s << i if !s.include?(i/k)
end

p s.size

def binary_search(ary, x)

  n = ary.size
  left  = 0
  right = n - 1

  while left <= right
    mid = (left + right) / 2

    case ary[mid] <=> x
    when 0
      return mid
    when 1
      right = mid - 1
    when -1
      left  = mid + 1
    end
  end

  return -1
end

n, k = gets.split.map &:to_i
ary  = gets.split.map(&:to_i).sort
aryc = Array.new(n, 0)
ans  = 0

for i in 0 .. n - 1 do

  if k == 1 then break end

  if aryc[i] == 1 then next end
  aryc[i] = 1

  tmp = ary[i]
  cnt = 1

  while tmp <= ary[n - 1]
    tmp *= k
    check = binary_search(ary, tmp)
    if check > -1
      aryc[check] = 1
      cnt += 1
    else
      break
    end
  end

  ans += (cnt + 1) / 2
end

puts ans

def binary_search(ary, x)
n = ary.size
left = 0
right = n - 1
while left < right
mid = (left + right) / 2
case ary[mid] <=> x
when 0
return mid
when 1
right = mid
when -1
left  = mid + 1
end
end
return -1
end

n, k = gets.split.map &:to_i
ary = gets.split.map(&:to_i).sort
aryc = Array.new(n, 0)
ans = 0

for i in 0 .. n - 1 do
if aryc[i] == 1 then next end
aryc[i]= 1
tmp = ary[i]
cnt = 1
while tmp <= ary[n - 1]
tmp *= k
check = binary_search(ary, tmp)
if check > -1
break
else
aryc[check] = 1
cnt += 1
end
end
ans += cnt/2
end

puts ans


You have a string $$$s$$$ consisting of digits from $$$0$$$ to $$$9$$$ inclusive. You can perform the following operation any (possibly zero) number of times:   You can choose a position $$$i$$$ and delete a digit $$$d$$$ on the $$$i$$$-th position. Then insert the digit $$$\min{(d + 1, 9)}$$$ on any position (at the beginning, at the end or in between any two adjacent digits). What is the lexicographically smallest string you can get by performing these operations?A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ of the same length if and only if the following holds:   in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a smaller digit than the corresponding digit in $$$b$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then the test cases follow. Each test case consists of a single line that contains one string $$$s$$$ ($$$1 \le |s| \le 2 \cdot 10^5$$$) — the string consisting of digits. Please note that $$$s$$$ is just a string consisting of digits, so leading zeros are allowed. It is guaranteed that the sum of lengths of $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

Print a single string — the minimum string that is possible to obtain.

NoteIn the first test case:   Delete $$$8$$$ and insert $$$9$$$ at the end of the notation. The resulting notation is $$$04299$$$.  Delete $$$4$$$ and insert $$$5$$$ in the $$$3$$$-rd position of the notation. The resulting notation is $$$02599$$$. Nothing needs to be done in the second and third test cases.

gets.to_i.times do
  m = 9
  puts (gets.chomp!.chars.map!(&:to_i).reverse_each.map do |c|
    if m >= c
      m = c
      c
    elsif c == 9
      c
    else
      c + 1
    end
  end.sort!.join)
end

gets.to_i.times do
  a = []
  b = []
  m = 9
  puts (gets.chomp!.chars.map!(&:to_i).reverse_each.map do |c|
    if m >= c
      m = c
      c
    elsif c == 9
      c
    else
      c + 1
    end
  end.sort!.join)
end

gets.to_i.times do
  a = []
  b = []
  m = 9
  gets.chomp!.chars.map!(&:to_i).reverse_each do |c|
    if m >= c
      m = c
      a << c
    else
      b << c
    end
  end
  a += b.map! { |e| e == 9 ? 9 : e + 1 }
  puts a.sort!.join
end

gets.to_i.times do
  a = []
  b = []
  m = 9
  gets.chomp!.chars.map!(&:to_i).reverse_each do |c|
    m = c if m > c
    if m == c
      a << c
    else
      b << c
    end
  end
  a += b.map! { |e| e == 9 ? 9 : e + 1 }
  puts a.sort!.join
end

gets.to_i.times do
  s = gets.chomp!.chars.map!(&:to_i).reverse!
  a = []
  b = []
  m = 9
  s.each do |c|
    m = c if m > c
    if m == c
      a << c
    else
      b << c
    end
  end
  a += b.map! { |e| e == 9 ? 9 : e + 1 }
  puts a.sort!.join
end

gets.to_i.times do
  a = []
  b = []
  m = 9
  gets.chomp!.chars.map!(&:to_i).reverse_each do |c|
    if m >= c
      c = m
      a << c
    else
      b << c
    end
  end
  a += b.map! { |e| e == 9 ? 9 : e + 1 }
  puts a.sort!.join
end

gets.to_i.times do
  s = gets.chomp!.chars.map!(&:to_i)
  a = []
  (0..9).each do |i|
    break if s.empty?
    c = s.count(i)
    if c != 0
      j = s.rindex(i)
      s = s[(j + 1)..-1] + s[0...j].map! do |e|
        if e == i || e == 9
          e
        else
          e + 1
        end
      end.tap { |s| s.delete(i) }.sort!
      a += [i] * c
    end
  end
  puts a.join
end


The student council has a shared document file. Every day, some members of the student council write the sequence TMT (short for Towa Maji Tenshi) in it.However, one day, the members somehow entered the sequence into the document at the same time, creating a jumbled mess. Therefore, it is Suguru Doujima's task to figure out whether the document has malfunctioned. Specifically, he is given a string of length $$$n$$$ whose characters are all either T or M, and he wants to figure out if it is possible to partition it into some number of disjoint subsequences, all of which are equal to TMT. That is, each character of the string should belong to exactly one of the subsequences.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero) characters.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 5000$$$)  — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$3 \le n < 10^5$$$), the number of characters in the string entered in the document. It is guaranteed that $$$n$$$ is divisible by $$$3$$$. The second line of each test case contains a string of length $$$n$$$ consisting of only the characters T and M. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print a single line containing YES if the described partition exists, and a single line containing NO otherwise.

5
3
TMT
3
MTT
6
TMTMTT
6
TMTTTT
6
TTMMTT

NoteIn the first test case, the string itself is already a sequence equal to TMT.In the third test case, we may partition the string into the subsequences TMTMTT. Both the bolded and the non-bolded subsequences are equal to TMT.

t = gets.to_s.to_i

def check(a)
  cnt_t = 0
  cnt_m = 0
  a.each do |c|
    cnt_t += 1 if c == "T"
    cnt_m += 1 if c == "M"
  end
  return false if cnt_m * 2 != cnt_t

  cnt = 0
  a.each do |c|
    cnt += 1 if c == "T"
    cnt -= 1 if c == "M"
    return false if cnt < 0
  end

  cnt = 0
  a.reverse.each do |c|
    cnt += 1 if c == "T"
    cnt -= 1 if c == "M"
    return false if cnt < 0
  end

  return true
end

1.upto(t) do |casenum|
  n = gets.to_s.split.map {|x| x.to_i }
  ar = gets.to_s.strip.split("")

  if check(ar)
    printf("YES\n")
  else
    printf("NO\n")
  end
end


Berland starts to seize the initiative on the war with Flatland. To drive the enemy from their native land, the berlanders need to know exactly how many more flatland soldiers are left in the enemy's reserve. Fortunately, the scouts captured an enemy in the morning, who had a secret encrypted message with the information the berlanders needed so much.The captured enemy had an array of positive integers. Berland intelligence have long been aware of the flatland code: to convey the message, which contained a number m, the enemies use an array of integers a. The number of its subarrays, in which there are at least k equal numbers, equals m. The number k has long been known in the Berland army so General Touristov has once again asked Corporal Vasya to perform a simple task: to decipher the flatlanders' message.Help Vasya, given an array of integers a and number k, find the number of subarrays of the array of numbers a, which has at least k equal numbers.Subarray a[i... j] (1 ≤ i ≤ j ≤ n) of array a = (a1, a2, ..., an) is an array, made from its consecutive elements, starting from the i-th one and ending with the j-th one: a[i... j] = (ai, ai + 1, ..., aj).

The first line contains two space-separated integers n, k (1 ≤ k ≤ n ≤ 4·105), showing how many numbers an array has and how many equal numbers the subarrays are required to have, correspondingly.  The second line contains n space-separated integers ai (1 ≤ ai ≤ 109) — elements of the array.

Print the single number — the number of such subarrays of array a, that they have at least k equal integers. Please do not use the %lld specifier to read or write 64-bit integers in С++. In is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample are three subarrays, containing at least two equal numbers: (1,2,1), (2,1,2) and (1,2,1,2).In the second sample are two subarrays, containing three equal numbers: (1,2,1,1,3) and (1,2,1,1).In the third sample any subarray contains at least one 1 number. Overall they are 6: (1), (1), (1), (1,1), (1,1) and (1,1,1).

n,m=gets.split.map &:to_i;a=gets.split.map &:to_i;h=Hash.new 0;j,z=-1,0;n.times{|i|h[a[j+=1]]+=1 until h[a[j]]>=m||j==n;z+=n-j;h[a[i]]-=1;};p z

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

hs = Hash.new(0)

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

i = 0
j = 0
ok = false
while i < a.size
    if i - 1 >= 0
        ok = false if hs[a[i-1]] == m
        hs[a[i-1]] -= 1
    end

    until ok or j == a.size
        ok = true if (hs[a[j]] += 1) == m
        j += 1
    end
    ans += a.size - j + 1 if ok
#p [i,j,ans]
#    p hs
    i += 1
end

puts ans

n,m=gets.split.map &:to_i;a=gets.split.map &:to_i;h=Hash.new 0;j,z=-1,0;n.times{|i|h[i]-=1;h[a[j+=1]]+=1 until h[a[j]]>=m||j==n;z+=n-j};p z


You've got string s, consisting of small English letters. Some of the English letters are good, the rest are bad.A substring s[l...r] (1 ≤ l ≤ r ≤ |s|) of string s  =  s1s2...s|s| (where |s| is the length of string s) is string  slsl + 1...sr.The substring s[l...r] is good, if among the letters  sl, sl + 1, ..., sr there are at most k bad ones (look at the sample's explanation to understand it more clear).Your task is to find the number of distinct good substrings of the given string s. Two substrings s[x...y] and s[p...q] are considered distinct if their content is different, i.e. s[x...y] ≠ s[p...q].

The first line of the input is the non-empty string s, consisting of small English letters, the string's length is at most 1500 characters. The second line of the input is the string of characters "0" and "1", the length is exactly 26 characters. If the i-th character of this string equals "1", then the i-th English letter is good, otherwise it's bad. That is, the first character of this string corresponds to letter "a", the second one corresponds to letter "b" and so on. The third line of the input consists a single integer k (0 ≤ k ≤ |s|) — the maximum acceptable number of bad characters in a good substring.

Print a single integer — the number of distinct good substrings of string s.

NoteIn the first example there are following good substrings: "a", "ab", "b", "ba", "bab".In the second example there are following good substrings: "a", "aa", "ac", "b", "ba", "c", "ca", "cb".

s = gets.chomp.chars.map &:ord
t = gets.chomp
bads = [0]*97 + t.chars.map{ |i| i == ?0 }
k = gets.to_i

ans = 0
pre = []

for x in (0...s.length).map{ |i| s[i..-1] }.sort
    h = pre.zip(x).take_while{ |i, j| i == j }.length
    p = 0
    x.each_with_index do |c, i|
		p += 1 if bads[c]
        next if i < h
		break if p > k
		ans += 1
    end
	pre = x
end

puts ans

s = gets.chomp.chars.map{ |i| i.ord - 97 }
bads = gets.chomp.chars.map{ |i| i == ?0 }
k = gets.to_i

ans = 0
pre = []

for x in (0...s.length).map{ |i| s[i..-1] }.sort
    h = pre.zip(x).take_while{ |i, j| i == j }.length
    p = 0
    x.each_with_index do |c, i|
		break if k < p += 1 if bads[c]
        ans += 1 unless i < h
    end
	pre = x
end

puts ans

require "Set"

string = gets.chomp.chars.map &:ord
bads = [0]*97 + gets.chomp.chars.map{ |i| 1 - i.to_i }
limit = gets.to_i

zo = string.map{ |i| bads[i] }

left = 0
right = -1
n = 0

h = Set.new

loop do
    for i in left+1..right
        h.add string[i..right]
    end
    break if string.length == right += 1
    if limit < n += bads[string[right]]
        n = limit
        left += zo[left..right].index(1) + 1
    end
    h.add string[left..right]
end

puts h.size


The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dn - 1 is the distance between the n - 1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t.

The first line contains integer n (3 ≤ n ≤ 100) — the number of stations on the circle line. The second line contains n integers d1, d2, ..., dn (1 ≤ di ≤ 100) — the distances between pairs of neighboring stations. The third line contains two integers s and t (1 ≤ s, t ≤ n) — the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces.

Print a single number — the length of the shortest path between stations number s and t.

NoteIn the first sample the length of path 1 → 2 → 3 equals 5, the length of path 1 → 4 → 3 equals 13.In the second sample the length of path 4 → 1 is 100, the length of path 4 → 3 → 2 → 1 is 15.In the third sample the length of path 3 → 1 is 1, the length of path 3 → 2 → 1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0.

def run
  n = ARGF.readline.to_i
  d = ARGF.readline.split.map(&:to_i)
  t, s = ARGF.readline.split.map(&:to_i)

  positive = 0
  cur = t - 1
  while cur != (s - 1)
    positive += d[cur]
    cur = (cur + 1) % n
  end

  negative = 0
  cur = t - 1
  while cur != (s - 1)
    cur = (cur + n - 1) % n
    negative += d[cur]
  end

  puts [positive, negative].min
end

run if $0 == __FILE__

def run
  n = ARGF.readline.to_i
  d = ARGF.readline.split.map(&:to_i)
  t, s = ARGF.readline.split.map(&:to_i)

  sum = 0
  cur = t - 1
  while cur != (s - 1)
    sum += d[cur]
    cur = (cur + 1) % n
  end

  puts [sum, d.reduce(:+) - sum].min
end

run if $0 == __FILE__

a=gets.chomp.to_i
b=gets.chomp.split(" ")
0.upto(a-1) {|i| b[i]=b[i].to_i}
d=gets.chomp.split(" ")
0.upto(1) {|i| d[i]=d[i].to_i}
d.sort!
ans1=0
ans2=0

(d[0]-1).upto(d[1]-2) {|i| ans1+=b[i]}
if d[0]!=1
0.upto(d[0]-2) {|i| ans2+=b[i]}
end
(a-1).downto(d[1]-1 ){|i| ans2+=b[i]}
if ans1<ans2
puts "#{ans1}"
else
puts "#{ans2}"
end

n=gets.to_i
xs=gets.split.map{|e| e.to_i}
a,b=gets.split.map{|e| e.to_i}
c=[a,b].min
d=[a,b].max

sum=0
xs.each{|e| sum+=e}

sum2=0
((c-1)..(d-2)).each{|i|
	sum2+=xs[i]
}
puts [sum2,sum-sum2].min

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

n = gets.to_i
stops = gets.split.map(&:to_i)
a, b = gets.split.map(&:to_i)
from, to = [a, b].min - 1, [a, b].max - 1

total_weight = stops.inject(0, :+)
from_a_to_b = stops[from...to].inject(0, :+)

print [total_weight - from_a_to_b, from_a_to_b].min

n=gets.to_i
a=gets.split.map(&:to_i)
s,t=gets.split.map(&:to_i)
s-=1
t-=1
i,k=s,0
while i!=t do
    k+=a[i]
    i=(i+1)%n
end
res=k
i,k=s,0
while i!=t do
    k+=a[(i-1+n)%n]
    i=(i-1+n)%n
end
puts [res, k].min

n = Integer(gets)
input = gets.chomp
nums = input.split
d = Array.new
for i in 0...n
    d[i] = Integer(nums[i])
end
input2 = gets.chomp
num = input2.split
s = Integer(num[0])
t = Integer(num[1])
sum = 0
for i in 0...n
    sum = sum + d[i]
end
sov = 0
if s <= t
    for i in s-1...t-1
        sov = sov + d[i]
    end
else
    for i in t-1...s-1
        sov = sov + d[i]
    end
end
sov2 = sum - sov
if sov >= sov2
    puts sov2
else
    puts sov
end

n = gets.to_i
d = gets.split(' ').collect!{|i| i.to_i}

s, t = gets.split(' ').collect!{|i| i.to_i - 1}.sort

sum = 0
sum1 = 0
d.each_index do |i|
	sum += d[i]
	sum1 += d[i] if i >= s && i < t
end
sum2 = sum - sum1

p [sum1, sum2].min

gets
ds = gets.split.map(&:to_i)
s, t = gets.split.map(&:to_i)

s, t = [s, t].sort

first = ds[(s-1)..(t-2)].reduce(:+) || 0
second = ds.reduce(:+) - first
p [first, second].min

n = gets.chomp.to_i
arr = gets.split(" ").collect! {|x| x.to_i}
s1,t1 = gets.split(" ").collect! {|x| x.to_i}
sum = 0
arr.each {|v|
	sum += v
}

f = 0
s = [s1,t1].min
t = [s1,t1].max
arr[(s-1)...(t-1)].each {|w|
	f += w
}

puts [f,sum-f].min

n = gets.to_i;
a = gets.split.map(&:to_i);
sum = a.inject(:+);
acc = 0;
d = [0].concat(a.map {|x| acc += x})
s, t = gets.split.map(&:to_i);
s, t = t, s if t < s
p ([d[t-1]-d[s-1], sum - d[t-1] + d[s-1]].min)

n = Integer(gets.chomp)
d = gets.chomp.split.map { |x| x.to_i }
s, t = gets.chomp.split.map { |x| x.to_i }.sort
puts(s == t ? 0 : [d[s - 1...t - 1], d[t - 1...n] + d[0...s - 1]].map { |a| a.inject(:+) }.min)

gets
ds = gets.split.map(&:to_i)
ps = gets.split.map(&:to_i).map(&:pred)
p [ds.slice!(ps.min, ps.reduce(&:-).abs), ds].map { |i|
  (i || []).reduce(&:+).to_i
}.min

n = gets.to_i
ds = gets.split.map(&:to_i)
s, t = gets.split.map(&:to_i).sort
if s == t
  puts 0
  exit
end
sum = ds.inject{|m,i|m+i}
dis = ds[s-1,t-s].inject{|m,i|m+i}
puts [dis, sum - dis].min

n = gets.to_i
ar = [0] + gets.split(' ').map(&:to_i)
s, t = gets.split(' ').map(&:to_i).minmax
v1 = ar.inject(:+)
v2 = ar[s...t].inject(0,:+)
puts [v1-v2, v2].min

n = gets.to_i
d = gets.split.map{|i| i.to_i}
s,t = gets.split.map{|i| i = i.to_i - 1}
res1 = 0
res2 = 0

if s > t then
    k = t
    while k < s do
        res1 += d[k]
        k += 1
    end
    while k < n do
        res2 += d[k]
        k += 1
    end
    k = 0
    while k < t do
        res2 += d[k]
        k += 1
    end
else
    k = s
    res1 = 0
    while k < t do
        res1 += d[k]
        k += 1
    end
    while k < n do
        res2 += d[k]
        k += 1
    end
    k = 0
    while k < s do
        res2 += d[k]
        k += 1
    end
end

puts [res1, res2].min

class Array
  def sum
    self.inject{|sum, x| sum + x}
  end
end
num = gets.chomp.to_i
dis = gets.chomp.split(" ").map {|x| x.to_i}
tmp = gets.chomp.split(" ")
a = tmp[0].to_i
b = tmp[1].to_i
if a > b
  a,b = b,a
end
r1 = 0
for i in a-1..b-2
  r1 += dis[i]
end

if r1 < dis.sum-r1
  puts r1
else
  puts dis.sum-r1
end

n = gets.to_i
d = gets.split(' ').map(&:to_i)
s, t = gets.split(' ').map(&:to_i)
if t < s
  s , t = t, s
end
l1 , l2 = 0, 0

for i in 0..d.size - 1 do
  if (i < s - 1) || (i > t - 2)
    l1 += d[i]
  else
    l2 += d[i]
  end
end

puts (if l1 < l2 then l1 else l2 end)

n = gets.chomp.to_i
d = gets.chomp.split(" ").map{|x| x.to_i}
s,j = gets.chomp.split(" ").map{|x| x.to_i}.sort

sum1 = 0
(s-1..j-2).each do |i|
  sum1 += d[i]
end

sum2 = 0
(0..s-2).each do |i|
  sum2 += d[i]
end

(j-1..n-1).each do |i|
  sum2 += d[i]
end

puts [sum1,sum2 ].min

num_stations = gets.to_i
stations = gets.split.collect {|i| i.to_i}
req_stations = gets.split.collect {|i| i.to_i}
total_distance = stations.inject(:+)
distance = 0
first = req_stations.min
last = req_stations.max
for i in first-1...last-1
	distance = distance + stations[i]
end
puts [distance,total_distance-distance].min

n = gets.to_i
dis = Array.new(n+1, 0)
d = gets.split.map(&:to_i)
for i in 1..n
  dis[i] = dis[i-1]+d[i-1]
end
a = gets.split.map(&:to_i)
A = (a.min) -1
B = (a.max) -1
puts [dis[B] - dis[A], (dis[n]-dis[B]) + dis[A]].min

#!/usr/bin/ruby

n = STDIN.readline.to_i

distances = STDIN.readline.split.collect {|s| s.to_i}
total = distances.inject {|sum, x| sum += x }

limits = STDIN.readline.split.collect {|s| s.to_i}
limits.sort!

sum = 0
((limits[0]-1)..(limits[1]-2)).each do |i|
	sum += distances[i]
end
puts [sum, total-sum].min

l = gets.chomp.to_i
arr = gets.chomp.split(' ').map(&:to_i)
s, t = gets.chomp.split(' ').map(&:to_i).sort

s -= 1
t -= 1

l1 = l2 = 0

s.upto(t-1).each do |ind|
  l1 += arr[ind]
end

(s-1).downto(0).each do |ind|
  l2 += arr[ind]
end

t.upto(l-1).each do |ind|
  l2 += arr[ind]
end

#puts l1, l2, s ,t
puts l1 > l2 ? l2 : l1

n = Integer(gets)
input = gets.chomp
nums = input.split
d = Array.new
for i in 0...n
	d[i] = Integer(nums[i])
end
input2 = gets.chomp
num = input2.split
s = Integer(num[0])
t = Integer(num[1])
sum = 0
for i in 0...n
	sum = sum + d[i]
end
sov = 0
for i in s-1...t-1
	sov = sov + d[i]
end
sov2 = sum - sov
if sov >= sov2
	puts sov2
else
	puts sov
end

n = gets.to_i
d = gets.split(' ').collect!{|i| i.to_i}

s, t = gets.split(' ').collect!{|i| i.to_i}.sort

rast1 = 0
(s..(t-1)).each do |x|
	rast1 += d[x-1]
end

rast2 = 0
if s > 1
	(0..(s-1)).each do |x|
		rast2 += d[x-1]
	end
end

(t..n).each do |x|
	rast2 += d[x-1]
end

if rast1 < rast2
	p rast1
else
	p rast2
end

n = gets.to_i
d = gets.split(' ').collect!{|i| i.to_i}

s, t = gets.split(' ').collect!{|i| i.to_i}.sort

if t > s
	rast1 = 0

	(s..(t-1)).each do |x|
		rast1 += d[x-1]
	end

	rast2 = 0
	if s > 1
		(0..(s-1)).each do |x|
			rast2 += d[x-1]
		end
	end

	(t..n).each do |x|
		rast2 += d[x-1]
	end

	if rast1 < rast2
		p rast1
	else
		p rast2
	end
else
	p 0
end

gets
ds = gets.split.map(&:to_i)
s, t = gets.split.map(&:to_i)

first = ds[(s-1)..(t-2)].reduce(:+) || 0
second = ds.reduce(:+) - first
p [first, second].min

gets
ds = gets.split.map(&:to_i)
ps = gets.split.map(&:to_i).map(&:pred)
puts [ds.rotate!(-ds[0]).slice!(0, ps.reduce(&:-).abs), ds].map { |i|
  (i || []).reduce(&:+)
}.min

l = gets.chomp.to_i
arr = gets.chomp.split(' ').map(&:to_i)
s, t = gets.chomp.split(' ').map(&:to_i).sort

s -= 1
t -= 1

l1 = l2 = 0

s.upto(t-1).each do |ind|
  l1 += arr[ind]
end

s.downto(0).each do |ind|
  l2 += arr[ind]
end

t.upto(l-1).each do |ind|
  l2 += arr[ind]
end

puts l1 > l2 ? l2 : l1


A TV show called "Guess a number!" is gathering popularity. The whole Berland, the old and the young, are watching the show.The rules are simple. The host thinks of an integer y and the participants guess it by asking questions to the host. There are four types of acceptable questions:  Is it true that y is strictly larger than number x?  Is it true that y is strictly smaller than number x?  Is it true that y is larger than or equal to number x?  Is it true that y is smaller than or equal to number x? On each question the host answers truthfully, "yes" or "no".Given the sequence of questions and answers, find any integer value of y that meets the criteria of all answers. If there isn't such value, print "Impossible".

The first line of the input contains a single integer n (1 ≤ n ≤ 10000) — the number of questions (and answers). Next n lines each contain one question and one answer to it. The format of each line is like that: "sign x answer", where the sign is:   ">" (for the first type queries),  "<" (for the second type queries),  ">=" (for the third type queries),  "<=" (for the fourth type queries).  All values of x are integer and meet the inequation  - 109 ≤ x ≤ 109. The answer is an English letter "Y" (for "yes") or "N" (for "no"). Consequtive elements in lines are separated by a single space.

Print any of such integers y, that the answers to all the queries are correct. The printed number y must meet the inequation  - 2·109 ≤ y ≤ 2·109. If there are many answers, print any of them. If such value doesn't exist, print word "Impossible" (without the quotes).

#!/usr/bin/ruby
A=['>','<','<=','>=']
min=-10**9-1
max=10**9+1
gets.to_i.times{
line=gets.chomp.split
line[0]=A.index(line[0])
line[0]^=2 if line[2]=='N'
line[1]=line[1].to_i
if line[0]==0
	min=[line[1]+1,min].max
elsif line[0]==1
	max=[line[1]-1,max].min
elsif line[0]==2
	max=[line[1],max].min
else
	min=[line[1],min].max
end
}
puts min<=max ? min : 'Impossible'

min = 10 ** 9 * (-2)
max = 10 ** 9 * 2

increase_min = proc { |num| min = (min >= num) ? min : num }
decrease_max = proc { |num| max = (max <= num) ? max : num }

n = gets.chomp.to_i
n.times do
    sign, num, answer = gets.chomp.split
    num = num.to_i

    case sign
    when ">"
        increase_min[num + 1] if answer == "Y"
        decrease_max[num] if answer == "N"
    when ">="
        increase_min[num] if answer == "Y"
        decrease_max[num - 1] if answer == "N"
    when "<"
        decrease_max[num - 1] if answer == "Y"
        increase_min[num] if answer == "N"
    when "<="
        decrease_max[num] if answer == "Y"
        increase_min[num + 1] if answer == "N"
    end
end

if min > max
    print "Impossible"
else
    print min
end

class ProblemA
  INF = 2e9.to_i

  def initialize
    @dats = STDIN.read.split("\n")
    @min, @max = -INF, INF
    @qnum = @dats[0].to_i
  end

  def solve
    possible = true
    (1..@qnum).each do |row|
      question = @dats[row]
      operator, num, ans = question.split(" ").map {|s| s = s.gsub(" ", "")}
      num = num.to_i

      ret = case operator
            when ">="
              ans == "Y" ? update(operator, num) : update("<", num)
            when "<="
              ans == "Y" ? update(operator, num) : update(">", num)
            when ">"
              ans == "Y" ? update(operator, num) : update("<=", num)
            when "<"
              ans == "Y" ? update(operator, num) : update(">=", num)
            end
      (possible = false and break) unless ret
    end
    if possible
      print @min
    else
      print "Impossible"
    end
  end

  def update(operator, num)
    case operator
    when ">="
      @min = num if @min < num
    when "<="
      @max = num if @max > num
    when ">"
      @min = num+1 if @min < num+1
    when "<"
      @max = num-1 if @max > num-1
    end
    @min > @max ? false : true
  end
end

solver = ProblemA.new
solver.solve

n = gets.chomp.to_i
max = (10 ** 9) * 2
min = -max
n.times do
    sign, x, ans = gets.chomp.split(/ /)
    x = x.to_i
    if ans == "N"
        case sign
        when '>'
            sign = '<='
        when '>='
            sign = '<'
        when '<'
            sign = '>='
        when '<='
            sign = '>'
        end
    end
    case sign
    when '>='
        min = [min, x].max
    when '>'
        min = [min, x + 1].max
    when '<'
        max = [max, x - 1].min
    when '<='
        max = [max, x].min
    end
end
if min <= max
    puts min
else
    puts "Impossible"
end

n = gets.chomp.to_i

a = 2*-10e8
b = 2* 10e8
n.times do |e|
	s = gets.chomp
	re = /^([>=<]{1,2})\s([-]?\d*)\s([YN])$/
	md = re.match(s)

	token = md[1]
	if md[3] =~ /^N/
		token = '>=' if md[1] == '<'
		token = '<=' if md[1] == '>'
		token = '<'  if md[1] == '>='
		token = '>'  if md[1] == '<='
	end

	if token[0] == '<'
		if b >= md[2].to_i
			b = md[2].to_i - 1

			b += 1 if token.length > 1
		end
	end

	if token[0] == ('>')
		if a <= md[2].to_i
			a = md[2].to_i + 1

			a -= 1 if token.length > 1
		end
	end
end

if a > b
	puts "Impossible"
else
	puts Random.rand(a..b).to_i
end

def reverse_signs(s)
	case s
	when ">="
		return "<"
	when ">"
		return "<="
	when "<"
		return ">="
	when "<="
		return ">"
	end

end

def calc(s,no,start,finish)
	case s
	when ">="
		start = no if no > start
	when ">"
		start = no + 1 if no + 1 > start
	when "<"
		finish = no - 1 if no - 1 < finish
	when "<="
		finish = no	if no < finish
	end
	return start,finish
end

n = gets.to_i
start = -(10 ** 9) * 2
finish = (10 ** 9) * 2

n.times do
	s,no,ans = gets.split(" ")
	no = no.to_i
	# puts "#{s},#{no},#{ans}"
	if ans == "Y"
		# puts "here"
		start,finish =  calc(s,no,start,finish)
		# puts "#{start},#{finish}"
	else
		start,finish =  calc(reverse_signs(s),no,start,finish)
	end
end
# puts start
# puts finish
if start <= finish
	puts "#{start}"
else
	puts "Impossible"
end

a = 2 * -10 ** 9
b = 2 * 10 ** 9
n = gets.to_i
t = { ">=" => "<", "<=" => ">", ">" => "<=", "<" => ">=" }
n.times do
	s, c, an = gets.split
	s = t[s] if an.chomp == "N"
	c = c.to_i
	case s
		when ">="
			a = c if c > a
		when ">"
			a = c + 1 if c + 1 > a
		when "<="
			b = c if c < b
		when "<"
			b = c - 1 if c - 1 < b
	end
end

puts a if (a..b).size.nonzero?
puts "Impossible" if (a..b).size.zero?

#f = File.open('test1.txt', 'r')
f = STDIN

n = f.gets.chomp.to_i
left, right = -2_000_000_000, 2_000_000_000
op = {
  ">" => "<=",
  "<" => ">=",
  ">=" => "<",
  "<=" => ">"
}
n.times do
  sign, x, answer = f.gets.chomp.split
  sign = op[sign] if answer == 'N'
  case sign
    when '<' #
      right = [right, x.to_i - 1].min
    when '>' #
      left = [left, x.to_i + 1].max
    when '<=' #
      right = [right, x.to_i].min
    when '>=' #
      left = [left, x.to_i].max
  end
end

puts (left <= right ? left : 'Impossible')

mn = -0x3f3f3f3f
mx = -mn
gets.to_i.times do
	op, x, ans = gets.split
	x = x.to_i
	(op = "<") && (x = x + 1) if op == "<="
	(op = ">=") && (x = x + 1) if op == ">"
	if op == ">=" && ans == "Y" || op == "<" && ans == "N"
		mn = [mn, x].max
	else
		mx = [mx, x-1].min
	end
end
puts mn <= mx ? mn : "Impossible"

#!/usr/bin/ruby
A=['>','<','<=','>=']
min=-10**9
max=10**9
gets.to_i.times{
line=gets.chomp.split
line[0]=A.index(line[0])
line[0]^=2 if line[2]=='N'
line[1]=line[1].to_i
if line[0]==0
	min=line[1]+1
elsif line[0]==1
	max=line[1]-1
elsif line[0]==2
	max=line[1]
else
	min=line[1]
end
}
puts min<=max ? min : 'Impossible'

#!/usr/bin/ruby
A=['>','<','<=','>=']
min=-10**9
max=10**9
gets.to_i.times{
line=gets.chomp.split
line[0]=A.index(line[0])
line[0]^=2 if line[2]=='N'
line[1]=line[1].to_i
if line[0]==0
	min=[line[1]+1,min].max
elsif line[0]==1
	max=[line[1]-1,max].min
elsif line[0]==2
	max=[line[1],max].min
else
	min=[line[1],min].max
end
}
puts min<=max ? min : 'Impossible'

min = 10 ** 9 * (-1)
max = 10 ** 9

n = gets.chomp.to_i
n.times do
    sign, num, answer = gets.chomp.split
    next if answer == "N"

    num = num.to_i
    case sign
    when ">"
        min = (min > num) ? min : num + 1
    when "<"
        max = (max < num) ? max : num - 1
    when ">="
        min = (min >= num) ? min : num
    when "<="
        max = (max <= num) ? max : num
    end
end

if min > max
    print "Impossible"
else
    print min
end

min = 10 ** 9 * (-1)
max = 10 ** 9

increase_min = proc { |num| min = (min >= num) ? min : num }
decrease_max = proc { |num| max = (max <= num) ? max : num }

n = gets.chomp.to_i
n.times do
    sign, num, answer = gets.chomp.split
    num = num.to_i

    case sign
    when ">"
        increase_min[num + 1] if answer == "Y"
        decrease_max[num] if answer == "N"
    when ">="
        increase_min[num] if answer == "Y"
        decrease_max[num - 1] if answer == "N"
    when "<"
        decrease_max[num - 1] if answer == "Y"
        increase_min[num] if answer == "N"
    when "<="
        decrease_max[num] if answer == "Y"
        increase_min[num + 1] if answer == "N"
    end
end

if min > max
    print "Impossible"
else
    print min
end

class ProblemA
  INF = 2e10
  def initialize
    @dats = STDIN.read.split("\n")
    @min, @max = -INF, INF
    @qnum = @dats[0].to_i
  end

  def solve
    possible = true
    (1..@qnum).each do |row|
      question = @dats[row]
      operator, num, ans = question.split(" ").map {|s| s = s.gsub(" ", "")}
      num = num.to_i

      ret = case operator
            when ">="
              ans == "Y" ? update(operator, num) : update("<", num)
            when "<="
              ans == "Y" ? update(operator, num) : update(">", num)
            when ">"
              ans == "Y" ? update(operator, num) : update("<=", num)
            when "<"
              ans == "Y" ? update(operator, num) : update(">=", num)
            end
      (possible = false and break) unless ret
    end
    if possible
      print @min
    else
      print "Impossible"
    end
  end

  def update(operator, num)
    print "#{operator} #{num}\n"
    case operator
    when ">="
      @min = num if @min < num
    when "<="
      @max = num if @max > num
    when ">"
      @min = num+1 if @min < num+1
    when "<"
      @max = num-1 if @max > num-1
    end
    @min > @max ? false : true
  end
end

solver = ProblemA.new
solver.solve

class ProblemA
  INF = 2e10.to_i

  def initialize
    @dats = STDIN.read.split("\n")
    @min, @max = -INF, INF
    @qnum = @dats[0].to_i
  end

  def solve
    possible = true
    (1..@qnum).each do |row|
      question = @dats[row]
      operator, num, ans = question.split(" ").map {|s| s = s.gsub(" ", "")}
      num = num.to_i

      ret = case operator
            when ">="
              ans == "Y" ? update(operator, num) : update("<", num)
            when "<="
              ans == "Y" ? update(operator, num) : update(">", num)
            when ">"
              ans == "Y" ? update(operator, num) : update("<=", num)
            when "<"
              ans == "Y" ? update(operator, num) : update(">=", num)
            end
      (possible = false and break) unless ret
    end
    if possible
      print @min
    else
      print "Impossible"
    end
  end

  def update(operator, num)
    case operator
    when ">="
      @min = num if @min < num
    when "<="
      @max = num if @max > num
    when ">"
      @min = num+1 if @min < num+1
    when "<"
      @max = num-1 if @max > num-1
    end
    @min > @max ? false : true
  end
end

solver = ProblemA.new
solver.solve

class ProblemA
  INF = 2e10
  def initialize
    @dats = STDIN.read.split("\n")
    @min, @max = -INF, INF
    @qnum = @dats[0].to_i
  end

  def solve
    possible = true
    (1..@qnum).each do |row|
      question = @dats[row]
      operator, num, ans = question.split(" ").map {|s| s = s.gsub(" ", "")}
      num = num.to_i

      ret = case operator
            when ">="
              ans == "Y" ? update(operator, num) : update("<", num)
            when "<="
              ans == "Y" ? update(operator, num) : update(">", num)
            when ">"
              ans == "Y" ? update(operator, num) : update("<=", num)
            when "<"
              ans == "Y" ? update(operator, num) : update(">=", num)
            end
      (possible = false and break) unless ret
    end
    if possible
      print @min
    else
      print "Impossible"
    end
  end

  def update(operator, num)
    case operator
    when ">="
      @min = num if @min < num
    when "<="
      @max = num if @max > num
    when ">"
      @min = num+1 if @min < num+1
    when "<"
      @max = num-1 if @max > num-1
    end
    @min > @max ? false : true
  end
end

solver = ProblemA.new
solver.solve

n = gets.chomp.to_i
max = (10 ** 9) * 2
min = -max
n.times do
    sign, x, ans = gets.chomp.split(/ /)
    x = x.to_i
    if ans == "N"
        case sign
        when '>'
            sign = '<='
        when '>='
            sign = '<'
        when '<'
            sign = '>='
        when '<='
            sign = '>'
        end
    end
    case sign
    when '>='
        min = [min, x].max
    when '>'
        min = [min, x + 1].max
    when '<'
        max = [max, x - 1].min
    when '<='
        max = [max, x].min
    end
end
puts "#{min} #{max}"
if min <= max
    puts min
else
    puts "Impossible"
end

n = gets.chomp.to_i
min = -1000000000
max = -min
n.times do
    sign, x, ans = gets.chomp.split(/ /)
    x = x.to_i
    if ans == "N"
        case sign
        when '>'
            sign = '<='
        when '>='
            sign = '<'
        when '<'
            sign = '>='
        when '<='
            sign = '>'
        end
    end
    case sign
    when '>='
        min = [min, x].max
    when '>'
        min = [min, x + 1].max
    when '<'
        max = [max, x - 1].min
    when '<='
        max = [max, x].min
    end
end
if min <= max
    puts min
else
    puts "Impossible"
end

n = gets.chomp.to_i
min = -1000000000
max = -min
n.times do
    sign, x, ans = gets.chomp.split(/ /)
    x = x.to_i
    if ans == "N"
        case sign
        when '>'
            sign = '<='
        when '>='
            sign = '<'
        when '<'
            sign = '>='
        when '<='
            sign = '>'
        end
    end
    case sign
    when '>', '>='
        min = [min, x].max
    when '<', '<='
        max = [max, x].min
    end
end
if min <= max
    puts min
else
    puts "Impossible"
end

n = gets.chomp.to_i

a = -10e8
b = 10e8
n.times do |e|
	s = gets.chomp
	re = /^([>=<]{1,2})\s([-]?\d*)\s([YN])$/
	md = re.match(s)

	token = md[1]
	if md[3] =~ /^N/
		token = '>=' if md[1] == '<'
		token = '<=' if md[1] == '>'
		token = '<'  if md[1] == '>='
		token = '>'  if md[1] == '<='
	end

	if token[0] == '<'
		if b > md[2].to_i
			b = md[2].to_i - 1
		end

		if token.length > 1
			b += 1
		end
	end

	if token[0].eql?('>')
		if a < md[2].to_i
			a = md[2].to_i + 1
		end

		if token.length > 1
			a -= 1
		end
	end
end

if a > b
	puts "Impossible"
else
	puts Random.rand(a..b).to_i
end

n = gets.chomp.to_i

a = 2*-10e8
b = 10e8
n.times do |e|
	s = gets.chomp
	re = /^([>=<]{1,2})\s([-]?\d*)\s([YN])$/
	md = re.match(s)

	token = md[1]
	if md[3] =~ /^N/
		token = '>=' if md[1] == '<'
		token = '<=' if md[1] == '>'
		token = '<'  if md[1] == '>='
		token = '>'  if md[1] == '<='
	end

	if token[0] == '<'
		if b > md[2].to_i
			b = md[2].to_i - 1

			b += 1 if token.length > 1
		end
	end

	if token[0].eql?('>')
		if a < md[2].to_i
			a = md[2].to_i + 1

			a -= 1 if token.length > 1
		end
	end
end

if a > b
	puts "Impossible"
else
	puts Random.rand(a..b).to_i
end

n = gets.chomp.to_i

a = -10e9
b = 10e9
n.times do |e|
	s = gets.chomp
	re = /^([>=<]{1,2})\s([-]?\d*)\s([YN])$/
	md = re.match(s)
	if md[3] =~ /^Y/
		if md[1][0] == '<'
			if b > md[2].to_i
				b = md[2].to_i - 1
			end

			if md[1].length > 1
				b += 1
			end
		end

		if md[1][0].eql?('>')
			if a < md[2].to_i
				a = md[2].to_i + 1
			end

			if md[1].length > 1
				a -= 1
			end
		end
	end
end

# puts a
# puts b
if a > b
	puts "Impossible"
else
	puts Random.rand(a..b).to_i
end

n = gets.chomp.to_i

a = 2*-10e8
b = 2* 10e8
n.times do |e|
	s = gets.chomp
	re = /^([>=<]{1,2})\s([-]?\d*)\s([YN])$/
	md = re.match(s)

	token = md[1]
	if md[3] =~ /^N/
		token = '>=' if md[1] == '<'
		token = '<=' if md[1] == '>'
		token = '<'  if md[1] == '>='
		token = '>'  if md[1] == '<='
	end

	if token[0] == '<'
		if b > md[2].to_i
			b = md[2].to_i - 1

			b += 1 if token.length > 1
		end
	end

	if token[0].eql?('>')
		if a < md[2].to_i
			a = md[2].to_i + 1

			a -= 1 if token.length > 1
		end
	end
end

if a > b
	puts "Impossible"
else
	puts Random.rand(a..b).to_i
end

n = gets.chomp.to_i

a = -10e8
b = 10e8
n.times do |e|
	s = gets.chomp
	re = /^([>=<]{1,2})\s([-]?\d*)\s([YN])$/
	md = re.match(s)

	token = md[1]
	if md[3] =~ /^N/
		token = '>=' if md[1] == '<'
		token = '<=' if md[1] == '>'
		token = '<'  if md[1] == '>='
		token = '>'  if md[1] == '<='
	end

	if token[0] == '<'
		if b > md[2].to_i
			b = md[2].to_i - 1

			b += 1 if token.length > 1
		end
	end

	if token[0].eql?('>')
		if a < md[2].to_i
			a = md[2].to_i + 1

			a -= 1 if token.length > 1
		end
	end
end

if a > b
	puts "Impossible"
else
	puts Random.rand(a..b).to_i
end

n = gets.chomp.to_i

a = 2*-10e8
b = 2* 10e8
n.times do |e|
	s = gets.chomp
	re = /^([>=<]{1,2})\s([-]?\d*)\s([YN])$/
	md = re.match(s)

	token = md[1]
	if md[3] =~ /^N/
		token = '>=' if md[1] == '<'
		token = '<=' if md[1] == '>'
		token = '<'  if md[1] == '>='
		token = '>'  if md[1] == '<='
	end

	if token[0] == '<'
		if b > md[2].to_i
			b = md[2].to_i - 1

			b += 1 if token.length > 1
		end
	end

	if token[0].eql?('>')
		if a < md[2].to_i
			a = md[2].to_i + 1

			a -= 1 if token.length > 1
		end
	end
end

if a >= b
	puts "Impossible"
else
	puts Random.rand(a..b).to_i
end

n = gets.chomp.to_i

a = -10e9
b = 10e9
n.times do |e|
	s = gets.chomp
	re = /^([>=<]{1,2})\s([-]?\d*)\s([YN])$/
	md = re.match(s)
	if md[3] =~ /^Y/
		if md[1][0] == '<'
			if b > md[2].to_i
				b = md[2].to_i - 1
			end

			if md[1].length > 1
				b += 1
			end
		end

		if md[1][0].eql?('>')
			if a < md[2].to_i
				a = md[2].to_i + 1
			end

			if md[1].length > 1
				a -= 1
			end
		end
	end
end

if a > b
	puts "Impossible"
else
	puts Random.rand(a..b).to_i
end

n = gets.chomp.to_i

a = -10e8
b = 10e8
n.times do |e|
	s = gets.chomp
	re = /^([>=<]{1,2})\s([-]?\d*)\s([YN])$/
	md = re.match(s)
	if md[3] =~ /^Y/
		if md[1][0] == '<'
			if b > md[2].to_i
				b = md[2].to_i - 1
			end

			if md[1].length > 1
				b += 1
			end
		end

		if md[1][0].eql?('>')
			if a < md[2].to_i
				a = md[2].to_i + 1
			end

			if md[1].length > 1
				a -= 1
			end
		end
	end
end

if a > b
	puts "Impossible"
else
	puts Random.rand(a..b).to_i
end

def reverse_signs(s)
	case s
	when ">="
		return "<"
	when ">"
		return "<="
	when "<"
		return ">="
	when "<="
		return ">"
	end

end

def calc(s,no,start,finish)
	case s
	when ">="
		start = no if no > start
	when ">"
		start = no + 1 if no + 1 > start
	when "<"
		finish = no - 1 if no - 1 < finish
	when "<="
		finish = no	if no < finish
	end
	return start,finish
end

n = gets.to_i
start = -10 ** 9
finish = 10 ** 9
n.times do
	s,no,ans = gets.split(" ")
	no = no.to_i
	# puts "#{s},#{no},#{ans}"
	if ans == "Y"
		puts "here"
		start,finish =  calc(s,no,start,finish)
		# puts "#{start},#{finish}"
	else
		start,finish =  calc(reverse_signs(s),no,start,finish)
	end
end
if start <= finish
	puts "#{start}"
else
	puts "Impossible"
end

def reverse_signs(s)
	case s
	when ">="
		return "<"
	when ">"
		return "<="
	when "<"
		return ">="
	when "<="
		return ">"
	end

end

def calc(s,no,start,finish)
	case s
	when ">="
		start = no if no > start
	when ">"
		start = no + 1 if no + 1 > start
	when "<"
		finish = no - 1 if no - 1 < finish
	when "<="
		finish = no	if no < finish
	end
	return start,finish
end

n = gets.to_i
start = -10 ** 9
finish = 10 ** 9
n.times do
	s,no,ans = gets.split(" ")
	no = no.to_i
	# puts "#{s},#{no},#{ans}"
	if ans == "Y"
		# puts "here"
		start,finish =  calc(s,no,start,finish)
		# puts "#{start},#{finish}"
	else
		start,finish =  calc(reverse_signs(s),no,start,finish)
	end
end
if start <= finish
	puts "#{start}"
else
	puts "Impossible"
end

a = -10 ** 9
b = 10 ** 9
n = gets.to_i
t = { ">=" => "<", "<=" => ">", ">" => "<=", "<" => ">=" }
n.times do
	s, c, an = gets.split
	s = t[s] if an.chomp == "N"
	c = c.to_i
	case s
		when ">="
			a = c
		when ">"
			a = c + 1
		when "<="
			b = c
		when "<"
			b = c - 1
	end
end

puts a if (a..b).size.nonzero?
puts "Impossible" if (a..b).size.zero?

a = -10 ** 9
b = 10 ** 9
n = gets.to_i
t = { ">=" => "<", "<=" => ">", ">" => "<=", "<" => ">=" }
n.times do
	s, c, an = gets.split
	s = t[s] if an.chomp == "N"
	c = c.to_i
	case s
		when ">="
			a = c if c > a
		when ">"
			a = c + 1 if c + 1 > a
		when "<="
			b = c if c < b
		when "<"
			b = c - 1 if c - 1 < b
	end
end

puts a if (a..b).size.nonzero? and b >= -10 ** 9 and a <= 10 ** 9
puts "Impossible" unless (a..b).size.nonzero? and b >= -10 ** 9 and a <= 10 ** 9

a = -10 ** 9
b = 10 ** 9
n = gets.to_i
t = { ">=" => "<", "<=" => ">", ">" => "<=", "<" => ">=" }
n.times do
	s, c, an = gets.split
	s = t[s] if an.chomp == "N"
	c = c.to_i
	case s
		when ">="
			a = c if c > a
		when ">"
			a = c + 1 if c + 1 > a
		when "<="
			b = c if c < b
		when "<"
			b = c - 1 if c - 1 < b
	end
end

puts a if (a..b).size.nonzero?
puts "Impossible" if (a..b).size.zero?

a = -10 ** 9 - 1
b = 10 ** 9 + 1
n = gets.to_i
t = { ">=" => "<", "<=" => ">", ">" => "<=", "<" => ">=" }
n.times do
	s, c, an = gets.split
	s = t[s] if an.chomp == "N"
	c = c.to_i
	case s
		when ">="
			a = c if c > a
		when ">"
			a = c + 1 if c + 1 > a
		when "<="
			b = c if c < b
		when "<"
			b = c - 1 if c - 1 < b
	end
end

puts a if (a..b).size.nonzero? and a != -10 ** 9 - 1 and b != 10 ** 9 + 1
puts "Impossible" unless (a..b).size.nonzero? and a != -10 ** 9 - 1 and b != 10 ** 9 + 1

#f = File.open('test1.txt', 'r')
f = STDIN

n = f.gets.chomp.to_i
left, right = -2_000_000_000, 2_000_000_000
op = {
  ">" => "<",
  "<" => ">",
  ">=" => "<=",
  "<=" => ">="
}
n.times do
  sign, x, answer = f.gets.chomp.split
  sign = op[sign] if answer == 'N'
  case sign
    when '<' #
      right = [right, x.to_i - 1].min
    when '>' #
      left = [left, x.to_i + 1].max
    when '<=' #
      right = [right, x.to_i].min
    when '>=' #
      left = [left, x.to_i].max
  end
end

puts (left <= right ? left : 'Impossible')


Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to time Anton would forget writing some letter and write it again. He asks you to count the total number of distinct letters in his set.

The first and the single line contains the set of letters. The length of the line doesn't exceed 1000. It is guaranteed that the line starts from an opening curved bracket and ends with a closing curved bracket. Between them, small English letters are listed, separated by a comma. Each comma is followed by a space.

Print a single number — the number of distinct letters in Anton's set.

#puts "Enter the string\n"
s = gets.chomp.to_s
l = s.length
#puts l
a = [l]
j = 0
for i in 0...l-1 do
    if s[i].ord >= 97 && s[i].ord <= 122
        a[j] = s[i]
        j += 1
        #puts a[j-1]
    end
end

#puts j (size of array a)
if j == 0
    puts 0
elsif j == 1
    puts 1
else
    a =  a.sort
    c = 0
    for k in 0..j do
        if a[k] != a[k+1]
            c += 1
        end
    end
    puts c
end

set = gets.chomp
puts set.tr('{},','').split(' ').uniq.length

require 'set'
puts gets.chomp.gsub(/[{} ]/,"").split(",").to_set.count

#!/usr/bin/env ruby

require 'set'

s = Set.new STDIN.gets.strip[1...-1].split(',').map(&:strip)

puts s.size

a = gets.chomp.chars
a[-1] = a[0] = ""
p a.join("").split(", ").uniq.size

a=gets.chomp.split("")
a.delete("{")
a.delete("}")
a.delete(" ")
a.delete(",")
a.uniq!
puts "#{a.length}"

ar = gets.chomp.split(/[^[:lower:]]/).select{|x| x.length>0}
hs = Hash.new 0
ar.each{|x| hs[x]+=1}
puts hs.length

letters = gets
letters = letters.slice(1, letters.length - 3).split(', ')

puts letters.uniq.length

#!/usr/bin/ruby
p gets.chomp[1...-1].split(', ').uniq.size

require 'set'

set = Set.new
s = gets.chomp
s.gsub!(/{|}| /, "")

s.split(",").each { |c| set << c }
puts set.length

s = gets.chomp
l = s.length
c={}
for i in 0...l
if s[i]=="{" || s[i]=="}"||s[i]==","||s[i]==" " then next
elsif c["#{s[i]}"]==nil then
    c["#{s[i]}"]=1
end
end
puts c.length

array = gets.delete('{}').chomp.split(", ")
puts array.uniq.count

s = gets.chomp
s =  s.delete!  "{, } "
s =  s.chars.uniq
puts s.size

numbers = gets.strip[1..-2].split(', ')

set = Hash.new(0)
numbers.each do |num|
  set[num] += 1
end

puts set.size

input = gets.chomp
letter = input.gsub(/[^a-zA-Z ]/," ").split(" ")
counter = {}
for i in 0...letter.length
	counter[letter[i]] = 1
end
sum = 0
counter.each do |key, value|
	sum += value
end
puts sum

s = $stdin.readline

b = s.scan(/[a-z]/)

puts b.uniq.count

def run
  h = Hash.new(0)
  $stdin.gets.gsub(/[{}]/, "").split(",").map(&:strip).each do |c|
    h[c] += 1 if c != ""
  end
  puts h.size
end

run if $0 == __FILE__

s = gets.chomp()
c = 0
('a'..'z').each do |char|
    if s.include? char
        c += 1
    end
end
puts(c)

puts gets.chomp.gsub(/{|}/, '').split(', ').uniq.count

s = gets.chomp
puts s.gsub("{", "").gsub("}", "").split(",").map(&:strip).uniq.count

line = gets.chomp
letters = line[1..(line.length - 2)].split(/, /)
letters.uniq!
puts letters.length

require 'set'
s=gets.chomp
s=s.slice(1,s.size-2).split(", ")
puts Set.new(s).count

s=gets.chomp
s.gsub!('{','').gsub!('}','')
arr = s.split(',').map(&:strip)
co = {}
arr.each do |a|
  if co[a].nil?
    co[a] = 1
  else
  co[a] +=1
  end
end

puts co.keys.length

a=gets.chomp
if a.length==2
	puts "0"
elsif a.length==3
	puts "1"
else
	puts a[1..(a.length-2)].split(",").map{|s| s.lstrip.rstrip}.uniq.length
end

hash = Hash.new(0)
gets.chomp.slice(1...-1).split(/,\s*/).each {|e| hash[e] +=1}
puts hash.length

require 'set'
s=gets
s=s.slice(1,s.size-2).split(", ")
puts Set.new(s).count


Ivan is collecting coins. There are only $$$N$$$ different collectible coins, Ivan has $$$K$$$ of them. He will be celebrating his birthday soon, so all his $$$M$$$ freinds decided to gift him coins. They all agreed to three terms:  Everyone must gift as many coins as others. All coins given to Ivan must be different. Not less than $$$L$$$ coins from gifts altogether, must be new in Ivan's collection.But his friends don't know which coins have Ivan already got in his collection. They don't want to spend money so they want to buy minimum quantity of coins, that satisfy all terms, irrespective of the Ivan's collection. Help them to find this minimum number of coins or define it's not possible to meet all the terms.

The only line of input contains 4 integers $$$N$$$, $$$M$$$, $$$K$$$, $$$L$$$ ($$$1 \le K \le N \le 10^{18}$$$; $$$1 \le M, \,\, L \le 10^{18}$$$) — quantity of different coins, number of Ivan's friends, size of Ivan's collection and quantity of coins, that must be new in Ivan's collection.

Print one number — minimal number of coins one friend can gift to satisfy all the conditions. If it is impossible to satisfy all three conditions print "-1" (without quotes).

NoteIn the first test, one coin from each friend is enough, as he will be presented with 15 different coins and 13 of them will definitely be new.In the second test, Ivan has 11 friends, but there are only 10 different coins. So all friends can't present him different coins.

n,m,k,l=gets.split.map &:to_i
x=(k+l+m-1)/m
p m*x>n ? -1 : x

N,M,K,L=gets.split.map &:to_i
if M>N
    puts -1
    exit
end
d=N/M
x=N-K
if d*M-K<L
    puts -1
    exit
end
puts (L+K+M-1)/M

#N different collectible coins,
#Ivan has K of them
#M freinds
#L coins from gifts altogether, must be new in Ivan's collection

N, M, K, L = gets.split(" ").map(&:to_i)

#example 1
# N, M, K, L = "20 15 2 3".split(" ").map(&:to_i)
#assert 1

#example 2
# N, M, K, L = "10 11 2 4".split(" ").map(&:to_i)
#assert -1

def condition_all_coins_different( friends, coins_per_friend, total_collectable_coins )
	return false if friends * coins_per_friend > total_collectable_coins
	true
end

def condition_minimum_amount_of_new_coins( minimum_new_coins, total_coins_gifted, total_collectable_coins, already_present_coins )
	#possible_new_coins = total_collectable_coins - already_present_coins
	total_coins_gifted >= minimum_new_coins + already_present_coins
end

coins_per_friend = ( K + L ) / M
until condition_minimum_amount_of_new_coins( L, M * coins_per_friend, N, K )
 #condition_all_coins_different( M, coins_per_friend, N ) and
	coins_per_friend += 1
end

# puts coins_per_friend

if condition_all_coins_different( M, coins_per_friend, N)
	puts coins_per_friend
else
	puts -1
end

n,m,k,l=gets.split.map &:to_i
x=(k+l)/m
p m*x>n ? x : -1

n,m,k,l=gets.split.map &:to_i
x=(k+l)/m
p m*x>n ? -1 : x

n,m,k,l=gets.split.map &:to_i
x=(k+l+m-1)/m
p m*x>n ? x : -1